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
Provenance
- Commit
672c2d7- Tree
796d12b- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
1a47ea2
100 files changed+4963 added−4795 removed
added:lib/arguments/cwd.js+49 added
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849import {statSync} from 'node:fs';import {resolve} from 'node:path';import {fileURLToPath} from 'node:url';import process from 'node:process';
export const normalizeCwd = (cwd = getDefaultCwd()) => { const cwdString = safeNormalizeFileUrl(cwd, 'The "cwd" option'); return resolve(cwdString);};
const getDefaultCwd = () => { try { return process.cwd(); } catch (error) { error.message = `The current directory does not exist.\n${error.message}`; throw error; }};
export const safeNormalizeFileUrl = (file, name) => { const fileString = normalizeFileUrl(file);
if (typeof fileString !== 'string') { throw new TypeError(`${name} must be a string or a file URL: ${fileString}.`); }
return fileString;};
export const normalizeFileUrl = file => file instanceof URL ? fileURLToPath(file) : file;
export const fixCwdError = (originalMessage, cwd) => { if (cwd === getDefaultCwd()) { return originalMessage; }
let cwdStat; try { cwdStat = statSync(cwd); } catch (error) { return `The "cwd" option is invalid: ${cwd}.\n${error.message}\n${originalMessage}`; }
if (!cwdStat.isDirectory()) { return `The "cwd" option is not a directory: ${cwd}.\n${originalMessage}`; }
return originalMessage;};added:lib/arguments/escape.js+12 added
123456789101112export const joinCommand = (filePath, rawArgs) => { const fileAndArgs = [filePath, ...rawArgs]; const command = fileAndArgs.join(' '); const escapedCommand = fileAndArgs.map(arg => escapeArg(arg)).join(' '); return {command, escapedCommand};};
const escapeArg = arg => typeof arg === 'string' && !NO_ESCAPE_REGEXP.test(arg) ? `"${arg.replaceAll('"', '\\"')}"` : arg;
const NO_ESCAPE_REGEXP = /^[\w.-]+$/;added:lib/arguments/node.js+46 added
12345678910111213141516171819202122232425262728293031323334353637383940414243444546import {execPath, execArgv} from 'node:process';import {basename, resolve} from 'node:path';import {execa} from '../async.js';import {handleOptionalArguments} from './options.js';import {safeNormalizeFileUrl} from './cwd.js';
export function execaNode(file, args, options) { [args, options] = handleOptionalArguments(args, options);
if (options.node === false) { throw new TypeError('The "node" option cannot be false with `execaNode()`.'); }
return execa(file, args, {...options, node: true});}
export const handleNodeOption = (file, args, { node: shouldHandleNode = false, nodePath = execPath, nodeOptions = execArgv.filter(arg => !arg.startsWith('--inspect')), cwd, execPath: formerNodePath, ...options}) => { if (formerNodePath !== undefined) { throw new TypeError('The "execPath" option has been removed. Please use the "nodePath" option instead.'); }
const normalizedNodePath = safeNormalizeFileUrl(nodePath, 'The "nodePath" option'); const resolvedNodePath = resolve(cwd, normalizedNodePath); const newOptions = {...options, nodePath: resolvedNodePath, cwd};
if (!shouldHandleNode) { return [file, args, newOptions]; }
if (basename(file, '.exe') === 'node') { throw new TypeError('When the "node" option is true, the first argument does not need to be "node".'); }
return [ resolvedNodePath, [...nodeOptions, file, ...args], {ipc: true, ...newOptions, shell: false}, ];};added:lib/arguments/options.js+91 added
1+import {basename} from 'node:path';2+import process from 'node:process';3+import crossSpawn from 'cross-spawn';4+import {npmRunPathEnv} from 'npm-run-path';5+import {normalizeForceKillAfterDelay} from '../exit/kill.js';6+import {validateTimeout} from '../exit/timeout.js';7+import {handleNodeOption} from './node.js';8+import {logCommand, verboseDefault} from './verbose.js';9+import {joinCommand} from './escape.js';10+import {normalizeCwd, safeNormalizeFileUrl, normalizeFileUrl} from './cwd.js';11+12+export const handleOptionalArguments = (args = [], options = {}) => Array.isArray(args)13+ ? [args, options]14+ : [[], args];15+16+export const handleArguments = (rawFile, rawArgs, rawOptions) => {17+ const filePath = safeNormalizeFileUrl(rawFile, 'First argument');18+ const {command, escapedCommand} = joinCommand(filePath, rawArgs);19+20+ rawOptions.cwd = normalizeCwd(rawOptions.cwd);21+ const [processedFile, processedArgs, processedOptions] = handleNodeOption(filePath, rawArgs, rawOptions);22+23+ const {command: file, args, options: initialOptions} = crossSpawn._parse(processedFile, processedArgs, processedOptions);24+25+ const options = addDefaultOptions(initialOptions);26+ validateTimeout(options);27+ options.shell = normalizeFileUrl(options.shell);28+ options.env = getEnv(options);29+ options.forceKillAfterDelay = normalizeForceKillAfterDelay(options.forceKillAfterDelay);30+31+ if (process.platform === 'win32' && basename(file, '.exe') === 'cmd') {32+ // #11633+ args.unshift('/q');34+ }35+36+ logCommand(escapedCommand, options);37+38+ return {file, args, command, escapedCommand, options};39+};40+41+const 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+});80+81+const DEFAULT_MAX_BUFFER = 1000 * 1000 * 100;82+83+const getEnv = ({env: envOption, extendEnv, preferLocal, localDir, nodePath}) => {84+ const env = extendEnv ? {...process.env, ...envOption} : envOption;85+86+ if (preferLocal) {87+ return npmRunPathEnv({env, cwd: localDir, execPath: nodePath});88+ }89+90+ return env;91+};added:lib/arguments/verbose.js+22 added
12345678910111213141516171819202122import {writeFileSync} from 'node:fs';import {debuglog} from 'node:util';import process from 'node:process';
export const verboseDefault = debuglog('execa').enabled;
export const logCommand = (escapedCommand, {verbose}) => { if (!verbose) { return; }
// Write synchronously to ensure it is written before spawning the child process. // This guarantees this line is written to `stderr` before the child process prints anything. writeFileSync(process.stderr.fd, `[${getTimestamp()}] ${escapedCommand}\n`);};
const getTimestamp = () => { const date = new Date(); return `${padField(date.getHours(), 2)}:${padField(date.getMinutes(), 2)}:${padField(date.getSeconds(), 2)}.${padField(date.getMilliseconds(), 3)}`;};
const padField = (field, padding) => String(field).padStart(padding, '0');added:lib/exit/cleanup.js+16 added
12345678910111213141516import {addAbortListener} from 'node:events';import {onExit} from 'signal-exit';
// `cleanup` option handlingexport const cleanupOnExit = (spawned, {cleanup, detached}, {signal}) => { if (!cleanup || detached) { return; }
const removeExitHandler = onExit(() => { spawned.kill(); }); addAbortListener(signal, () => { removeExitHandler(); });};added:lib/exit/code.js+14 added
1234567891011121314import {DiscardedError} from '../return/error.js';
export const waitForSuccessfulExit = async exitPromise => { const [exitCode, signal] = await exitPromise;
if (!isProcessErrorExit(exitCode, signal) && isFailedExit(exitCode, signal)) { throw new DiscardedError(); }
return [exitCode, signal];};
const isProcessErrorExit = (exitCode, signal) => exitCode === undefined && signal === undefined;export const isFailedExit = (exitCode, signal) => exitCode !== 0 || signal !== null;added:lib/exit/kill.js+76 added
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576import os from 'node:os';import {setTimeout} from 'node:timers/promises';import {isErrorInstance} from '../return/clone.js';
export const normalizeForceKillAfterDelay = forceKillAfterDelay => { if (forceKillAfterDelay === false) { return forceKillAfterDelay; }
if (forceKillAfterDelay === true) { return DEFAULT_FORCE_KILL_TIMEOUT; }
if (!Number.isFinite(forceKillAfterDelay) || forceKillAfterDelay < 0) { throw new TypeError(`Expected the \`forceKillAfterDelay\` option to be a non-negative integer, got \`${forceKillAfterDelay}\` (${typeof forceKillAfterDelay})`); }
return forceKillAfterDelay;};
const DEFAULT_FORCE_KILL_TIMEOUT = 1000 * 5;
// Monkey-patches `childProcess.kill()` to add `forceKillAfterDelay` behavior and `.kill(error)`export const spawnedKill = ({kill, spawned, options: {forceKillAfterDelay, killSignal}, controller}, signalOrError, errorArgument) => { const {signal, error} = parseKillArguments(signalOrError, errorArgument, killSignal); emitKillError(spawned, error); const killResult = kill(signal); setKillTimeout({kill, signal, forceKillAfterDelay, killSignal, killResult, controller}); return killResult;};
const parseKillArguments = (signalOrError, errorArgument, killSignal) => { const [signal = killSignal, error] = isErrorInstance(signalOrError) ? [undefined, signalOrError] : [signalOrError, errorArgument];
if (typeof signal !== 'string' && typeof signal !== 'number') { throw new TypeError(`The first argument must be an error instance or a signal name string/number: ${signal}`); }
if (error !== undefined && !isErrorInstance(error)) { throw new TypeError(`The second argument is optional. If specified, it must be an error instance: ${error}`); }
return {signal, error};};
const emitKillError = (spawned, error) => { if (error !== undefined) { spawned.emit(errorSignal, error); }};
// Like `error` signal but internal to Execa.// E.g. does not make process crash when no `error` listener is set.export const errorSignal = Symbol('error');
const setKillTimeout = async ({kill, signal, forceKillAfterDelay, killSignal, killResult, controller}) => { if (!shouldForceKill(signal, forceKillAfterDelay, killSignal, killResult)) { return; }
try { await setTimeout(forceKillAfterDelay, undefined, {signal: controller.signal}); kill('SIGKILL'); } catch {}};
const shouldForceKill = (signal, forceKillAfterDelay, killSignal, killResult) => normalizeSignal(signal) === normalizeSignal(killSignal) && forceKillAfterDelay !== false && killResult;
const normalizeSignal = signal => typeof signal === 'string' ? os.constants.signals[signal.toUpperCase()] : signal;added:lib/exit/timeout.js+20 added
1234567891011121314151617181920import {setTimeout} from 'node:timers/promises';import {DiscardedError} from '../return/error.js';
export const validateTimeout = ({timeout}) => { if (timeout !== undefined && (!Number.isFinite(timeout) || timeout < 0)) { throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${timeout}\` (${typeof timeout})`); }};
// `timeout` option handlingexport const throwOnTimeout = (spawned, timeout, context, controller) => timeout === 0 || timeout === undefined ? [] : [killAfterTimeout(spawned, timeout, context, controller)];
const killAfterTimeout = async (spawned, timeout, context, {signal}) => { await setTimeout(timeout, undefined, {signal}); context.timedOut = true; spawned.kill(); throw new DiscardedError();};modified:lib/pipe/streaming.js+1 added-1 removed
1 import {finished} from 'node:stream/promises';2 import mergeStreams from '@sindresorhus/merge-streams';3-import {incrementMaxListeners} from '../stdio/utils.js';3+import {incrementMaxListeners} from '../utils.js';4 5 // 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 linesmodified:lib/pipe/validate.js+2 added-2 removed
1 import {ChildProcess} from 'node:child_process';2-import {STANDARD_STREAMS_ALIASES} from '../stdio/utils.js';3-import {makeEarlyError} from '../error.js';2+import {STANDARD_STREAMS_ALIASES} from '../utils.js';3+import {makeEarlyError} from '../return/error.js';4 import {abortSourceStream, endDestinationStream} from './streaming.js';5 6 export const normalizePipeArguments = (destination, from, {spawned: source, stdioStreamsGroups, options}) => {7 const {destinationStream, destinationError} = getDestinationStream(destination);138 unmodified linesadded:lib/return/clone.js+70 added
1+export const getFinalError = (initialError, message) => {2+ const error = createFinalError(initialError, message);3+ previousErrors.add(error);4+ return error;5+};6+7+const createFinalError = (error, message) => {8+ if (!isErrorInstance(error)) {9+ return new Error(message);10+ }11+12+ return previousErrors.has(error)13+ ? cloneError(error, message)14+ : setErrorMessage(error, message);15+};16+17+export const isErrorInstance = value => Object.prototype.toString.call(value) === '[object Error]';18+19+const 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+};27+28+const 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+};36+37+// Known error properties38+const COPIED_ERROR_PROPERTIES = [39+ 'cause',40+ 'errors',41+ 'code',42+ 'errno',43+ 'syscall',44+ 'path',45+ 'dest',46+ 'address',47+ 'port',48+ 'info',49+];50+51+// 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/5171555+const setErrorMessage = (error, newMessage) => {56+ const {message, stack} = error;57+ error.message = newMessage;58+ error.stack = fixStack(stack, message, newMessage);59+ return error;60+};61+62+const fixStack = (stack, message, newMessage) => stack.includes(newMessage)63+ ? stack64+ : stack.replace(`: ${message}`, `: ${newMessage}`);65+66+// Two `execa()` calls might return the same error.67+// So we must close those before directly mutating them.68+export const isPreviousError = error => previousErrors.has(error);69+70+const previousErrors = new WeakSet();added:lib/return/error.js+191 added
1+import {signalsByName} from 'human-signals';2+import stripFinalNewline from 'strip-final-newline';3+import {isBinary, binaryToString} from '../utils.js';4+import {fixCwdError} from '../arguments/cwd.js';5+import {getFinalError, isPreviousError} from './clone.js';6+7+export 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+});28+29+export 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+});44+45+export 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);73+74+ error.shortMessage = shortMessage;75+ error.originalMessage = originalMessage;76+ error.command = command;77+ error.escapedCommand = escapedCommand;78+ error.cwd = cwd;79+80+ 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;87+88+ error.stdout = stdio[1];89+ error.stderr = stdio[2];90+91+ if (all !== undefined) {92+ error.all = all;93+ }94+95+ error.stdio = stdio;96+97+ if ('bufferedData' in error) {98+ delete error.bufferedData;99+ }100+101+ error.pipedFrom = [];102+103+ return error;104+};105+106+// Indicates that the error is used only to interrupt control flow, but not in the return value107+export class DiscardedError extends Error {}108+109+// `signal` and `exitCode` emitted on `spawned.on('exit')` event can be `null`.110+// We normalize them to `undefined`111+const 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+};117+118+const 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+};143+144+const getErrorPrefix = ({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled}) => {145+ if (timedOut) {146+ return `Command timed out after ${timeout} milliseconds`;147+ }148+149+ if (isCanceled) {150+ return 'Command was canceled';151+ }152+153+ if (errorCode !== undefined) {154+ return `Command failed with ${errorCode}`;155+ }156+157+ if (signal !== undefined) {158+ return `Command was killed with ${signal} (${signalDescription})`;159+ }160+161+ if (exitCode !== undefined) {162+ return `Command failed with exit code ${exitCode}`;163+ }164+165+ return 'Command failed';166+};167+168+const getOriginalMessage = (error, cwd) => {169+ if (error === undefined) {170+ return '';171+ }172+173+ const originalMessage = isPreviousError(error) ? error.originalMessage : String(error?.message ?? error);174+ return fixCwdError(originalMessage, cwd);175+};176+177+const serializeMessagePart = messagePart => Array.isArray(messagePart)178+ ? messagePart.map(messageItem => serializeMessageItem(messageItem)).join('')179+ : serializeMessageItem(messagePart);180+181+const serializeMessageItem = messageItem => {182+ if (typeof messageItem === 'string') {183+ return messageItem;184+ }185+186+ if (isBinary(messageItem)) {187+ return binaryToString(messageItem);188+ }189+190+ return '';191+};added:lib/return/output.js+19 added
1+import {Buffer} from 'node:buffer';2+import stripFinalNewline from 'strip-final-newline';3+import {bufferToUint8Array} from '../utils.js';4+5+export const handleOutput = (options, value) => {6+ if (value === undefined || value === null) {7+ return;8+ }9+10+ if (Array.isArray(value)) {11+ return value;12+ }13+14+ if (Buffer.isBuffer(value)) {15+ value = bufferToUint8Array(value);16+ }17+18+ return options.stripFinalNewline ? stripFinalNewline(value) : value;19+};modified:lib/stdio/async.js+1 added-1 removed
1 import {createReadStream, createWriteStream} from 'node:fs';2 import {Buffer} from 'node:buffer';3 import {Readable, Writable} from 'node:stream';4+import {isStandardStream, incrementMaxListeners} from '../utils.js';5 import {handleInput} from './handle.js';6 import {pipeStreams} from './pipeline.js';7 import {TYPE_TO_MESSAGE} from './type.js';8 import {generatorToDuplexStream, pipeGenerator} from './generator.js';8-import {isStandardStream, incrementMaxListeners} from './utils.js';9 10 // Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, before spawning, in async mode11 export const handleInputAsync = options => handleInput(addPropertiesAsync, options, false);12 82 unmodified linesadded:lib/stdio/encoding-end.js+49 added
1+import {Buffer} from 'node:buffer';2+import {isUint8Array} from '../utils.js';3+4+/*5+When using generators, add an internal generator that converts chunks from `Buffer` to `string` or `Uint8Array`.6+This allows generator functions to operate with those types instead.7+Chunks 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 string11+12+However, those are converted to Buffer:13+- on writes: `Duplex.writable` `decodeStrings: true` default option14+- on reads: `Duplex.readable` `readableEncoding: null` default option15+*/16+export const getEncodingStartGenerator = encoding => {17+ if (encoding === 'buffer') {18+ return {transform: encodingStartBufferGenerator.bind(undefined, new TextEncoder())};19+ }20+21+ const textDecoder = new TextDecoder();22+ return {23+ transform: encodingStartStringGenerator.bind(undefined, textDecoder),24+ final: encodingStartStringFinal.bind(undefined, textDecoder),25+ };26+};27+28+const 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+};37+38+const encodingStartStringGenerator = function * (textDecoder, chunk) {39+ yield Buffer.isBuffer(chunk) || isUint8Array(chunk)40+ ? textDecoder.decode(chunk, {stream: true})41+ : chunk;42+};43+44+const encodingStartStringFinal = function * (textDecoder) {45+ const lastChunk = textDecoder.decode();46+ if (lastChunk !== '') {47+ yield lastChunk;48+ }49+};added:lib/stdio/encoding-start.js+55 added
1+import {StringDecoder} from 'node:string_decoder';2+import {isUint8Array} from '../utils.js';3+import {willPipeStreams} from './forward.js';4+5+// Apply the `encoding` option using an implicit generator.6+// This encodes the final output of `stdout`/`stderr`.7+export const handleStreamsEncoding = (stdioStreams, {encoding}, isSync) => {8+ const newStdioStreams = stdioStreams.map(stdioStream => ({...stdioStream, encoding}));9+ if (!shouldEncodeOutput(newStdioStreams, encoding, isSync)) {10+ return newStdioStreams;11+ }12+13+ 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+};33+34+const shouldEncodeOutput = (stdioStreams, encoding, isSync) => stdioStreams[0].direction === 'output'35+ && !IGNORED_ENCODINGS.has(encoding)36+ && !isSync37+ && willPipeStreams(stdioStreams);38+39+// eslint-disable-next-line unicorn/text-encoding-identifier-case40+const IGNORED_ENCODINGS = new Set(['utf8', 'utf-8', 'buffer']);41+42+const encodingEndStringGenerator = function * (stringDecoder, chunk) {43+ yield stringDecoder.write(chunk);44+};45+46+const encodingEndStringFinal = function * (stringDecoder) {47+ const lastChunk = stringDecoder.end();48+ if (lastChunk !== '') {49+ yield lastChunk;50+ }51+};52+53+const encodingEndObjectGenerator = function * (stringDecoder, chunk) {54+ yield isUint8Array(chunk) ? stringDecoder.end(chunk) : chunk;55+};deleted:lib/stdio/encoding.js-103 removed
1-import {StringDecoder} from 'node:string_decoder';2-import {Buffer} from 'node:buffer';3-import {isUint8Array} from './utils.js';4-import {willPipeStreams} from './pipe.js';5-6-// Apply the `encoding` option using an implicit generator.7-// This encodes the final output of `stdout`/`stderr`.8-export const handleStreamsEncoding = (stdioStreams, {encoding}, isSync) => {9- const newStdioStreams = stdioStreams.map(stdioStream => ({...stdioStream, encoding}));10- if (!shouldEncodeOutput(newStdioStreams, encoding, isSync)) {11- return newStdioStreams;12- }13-14- 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-};34-35-const shouldEncodeOutput = (stdioStreams, encoding, isSync) => stdioStreams[0].direction === 'output'36- && !IGNORED_ENCODINGS.has(encoding)37- && !isSync38- && willPipeStreams(stdioStreams);39-40-// eslint-disable-next-line unicorn/text-encoding-identifier-case41-const IGNORED_ENCODINGS = new Set(['utf8', 'utf-8', 'buffer']);42-43-const encodingEndStringGenerator = function * (stringDecoder, chunk) {44- yield stringDecoder.write(chunk);45-};46-47-const encodingEndStringFinal = function * (stringDecoder) {48- const lastChunk = stringDecoder.end();49- if (lastChunk !== '') {50- yield lastChunk;51- }52-};53-54-const encodingEndObjectGenerator = function * (stringDecoder, chunk) {55- yield isUint8Array(chunk) ? stringDecoder.end(chunk) : chunk;56-};57-58-/*59-When using generators, add an internal generator that converts chunks from `Buffer` to `string` or `Uint8Array`.60-This allows generator functions to operate with those types instead.61-Chunks 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 string65-66-However, those are converted to Buffer:67-- on writes: `Duplex.writable` `decodeStrings: true` default option68-- on reads: `Duplex.readable` `readableEncoding: null` default option69-*/70-export const getEncodingStartGenerator = encoding => {71- if (encoding === 'buffer') {72- return {transform: encodingStartBufferGenerator.bind(undefined, new TextEncoder())};73- }74-75- const textDecoder = new TextDecoder();76- return {77- transform: encodingStartStringGenerator.bind(undefined, textDecoder),78- final: encodingStartStringFinal.bind(undefined, textDecoder),79- };80-};81-82-const 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-};91-92-const encodingStartStringGenerator = function * (textDecoder, chunk) {93- yield Buffer.isBuffer(chunk) || isUint8Array(chunk)94- ? textDecoder.decode(chunk, {stream: true})95- : chunk;96-};97-98-const 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*`.4+export const forwardStdio = stdioStreamsGroups => stdioStreamsGroups.map(stdioStreams => forwardStdioItem(stdioStreams));5+6+// Whether `childProcess.std*` will be set7+export const willPipeStreams = stdioStreams => PIPED_STDIO_VALUES.has(forwardStdioItem(stdioStreams));8+9+const PIPED_STDIO_VALUES = new Set(['pipe', 'overlapped', undefined, null]);10+11+const forwardStdioItem = stdioStreams => {12+ if (stdioStreams.length > 1) {13+ return stdioStreams.some(({value}) => value === 'overlapped') ? 'overlapped' : 'pipe';14+ }15+16+ const [stdioStream] = stdioStreams;17+ return stdioStream.type !== 'native' && stdioStream.value !== 'overlapped' ? 'pipe' : stdioStream.value;18+};modified:lib/stdio/generator.js+2 added-29 removed
1 import {generatorsToTransform} from './transform.js';2-import {getEncodingStartGenerator} from './encoding.js';2+import {getEncodingStartGenerator} from './encoding-end.js';3 import {getLinesGenerator} from './lines.js';4 import {pipeStreams} from './pipeline.js';5 import {isGeneratorOptions, isAsyncGenerator} from './type.js';6-import {isBinary} from './utils.js';6+import {getValidateTransformReturn} from './validate.js';7 8 export const normalizeGenerators = stdioStreams => {9 const nonGenerators = stdioStreams.filter(({type}) => type !== 'generator');10 const generators = stdioStreams.filter(({type}) => type === 'generator');72 unmodified lines83 const duplexStream = generatorsToTransform(generators, {transformAsync, finalAsync, writableObjectMode, readableObjectMode});84 return {value: duplexStream};85 };86 87-const getValidateTransformReturn = (readableObjectMode, optionName) => readableObjectMode88- ? validateObjectTransformReturn.bind(undefined, optionName)89- : validateStringTransformReturn.bind(undefined, optionName);90-91-const validateObjectTransformReturn = function * (optionName, chunk) {92- validateEmptyReturn(optionName, chunk);93- yield chunk;94-};95-96-const validateStringTransformReturn = function * (optionName, chunk) {97- validateEmptyReturn(optionName, chunk);98-99- 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- }102-103- yield chunk;104-};105-106-const validateEmptyReturn = (optionName, chunk) => {107- if (chunk === null || chunk === undefined) {108- throw new TypeError(`The \`${optionName}\` option's function must not call \`yield ${chunk}\`.109-Instead, \`yield\` should either be called with a value, or not be called at all. For example:110- if (condition) { yield value; }`);111- }112-};113-87 // `childProcess.stdin|stdout|stderr|stdio` is directly mutated.88 export const pipeGenerator = (spawned, {value, direction, index}) => {89 if (direction === 'output') {90 pipeStreams([spawned.stdio[index]], value);13 unmodified linesmodified:lib/stdio/handle.js+4 added-4 removed
1 import {getStdioOptionType, isRegularUrl, isUnknownStdioString} from './type.js';2 import {addStreamDirection} from './direction.js';3-import {normalizeStdio} from './normalize.js';3+import {normalizeStdio} from './option.js';4 import {handleNativeStream} from './native.js';5 import {handleInputOptions} from './input.js';6 import {handleStreamsLines} from './lines.js';7-import {handleStreamsEncoding} from './encoding.js';7+import {handleStreamsEncoding} from './encoding-start.js';8 import {normalizeGenerators} from './generator.js';9-import {updateStdio} from './pipe.js';9+import {forwardStdio} from './forward.js';10 11 // Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, before spawning, in async/sync mode12 export const handleInput = (addProperties, options, isSync) => {13 const stdio = normalizeStdio(options);4 unmodified lines18 .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 };25 26 // We make sure passing an array with a single item behaves the same as passing that item without an array.70 unmodified linesmodified:lib/stdio/input.js+1 added-1 removed
1 import {isReadableStream} from 'is-stream';2+import {isUint8Array} from '../utils.js';3 import {isUrl, isFilePathString} from './type.js';3-import {isUint8Array} from './utils.js';4 5 // Append the `stdin` option with the `input` and `inputFile` options6 export const handleInputOptions = ({input, inputFile}) => [7 handleInputOption(input),43 unmodified linesmodified:lib/stdio/lines.js+2 added-2 removed
1-import {isUint8Array} from './utils.js';2-import {willPipeStreams} from './pipe.js';1+import {isUint8Array} from '../utils.js';2+import {willPipeStreams} from './forward.js';3 4 // 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.6 export const handleStreamsLines = (stdioStreams, {lines}, isSync) => shouldSplitLines(stdioStreams, lines, isSync)94 unmodified linesmodified:lib/stdio/native.js+1 added-1 removed
1 import {isStream as isNodeStream} from 'is-stream';2-import {STANDARD_STREAMS} from './utils.js';2+import {STANDARD_STREAMS} from '../utils.js';3 4 // 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 linesdeleted:lib/stdio/normalize.js-32 removed
1-import {STANDARD_STREAMS_ALIASES} from './utils.js';2-3-// Add support for `stdin`/`stdout`/`stderr` as an alias for `stdio`4-export const normalizeStdio = ({stdio, ipc, ...options}) => {5- const stdioArray = getStdioArray(stdio, options);6- return ipc && !stdioArray.includes('ipc')7- ? [...stdioArray, 'ipc']8- : stdioArray;9-};10-11-const getStdioArray = (stdio, options) => {12- if (stdio === undefined) {13- return STANDARD_STREAMS_ALIASES.map(alias => options[alias]);14- }15-16- 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- }19-20- if (typeof stdio === 'string') {21- return [stdio, stdio, stdio];22- }23-24- if (!Array.isArray(stdio)) {25- throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof stdio}\``);26- }27-28- const length = Math.max(stdio.length, STANDARD_STREAMS_ALIASES.length);29- return Array.from({length}, (value, index) => stdio[index]);30-};31-32-const hasAlias = options => STANDARD_STREAMS_ALIASES.some(alias => options[alias] !== undefined);added:lib/stdio/option.js+32 added
1+import {STANDARD_STREAMS_ALIASES} from '../utils.js';2+3+// Add support for `stdin`/`stdout`/`stderr` as an alias for `stdio`4+export const normalizeStdio = ({stdio, ipc, ...options}) => {5+ const stdioArray = getStdioArray(stdio, options);6+ return ipc && !stdioArray.includes('ipc')7+ ? [...stdioArray, 'ipc']8+ : stdioArray;9+};10+11+const getStdioArray = (stdio, options) => {12+ if (stdio === undefined) {13+ return STANDARD_STREAMS_ALIASES.map(alias => options[alias]);14+ }15+16+ 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+ }19+20+ if (typeof stdio === 'string') {21+ return [stdio, stdio, stdio];22+ }23+24+ if (!Array.isArray(stdio)) {25+ throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof stdio}\``);26+ }27+28+ const length = Math.max(stdio.length, STANDARD_STREAMS_ALIASES.length);29+ return Array.from({length}, (value, index) => stdio[index]);30+};31+32+const 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*`.4-export const updateStdio = stdioStreamsGroups => stdioStreamsGroups.map(stdioStreams => updateStdioItem(stdioStreams));5-6-// Whether `childProcess.std*` will be set7-export const willPipeStreams = stdioStreams => PIPED_STDIO_VALUES.has(updateStdioItem(stdioStreams));8-9-const PIPED_STDIO_VALUES = new Set(['pipe', 'overlapped', undefined, null]);10-11-const updateStdioItem = stdioStreams => {12- if (stdioStreams.length > 1) {13- return stdioStreams.some(({value}) => value === 'overlapped') ? 'overlapped' : 'pipe';14- }15-16- const [stdioStream] = stdioStreams;17- return stdioStream.type !== 'native' && stdioStream.value !== 'overlapped' ? 'pipe' : stdioStream.value;18-};modified:lib/stdio/pipeline.js+2 added-2 removed
1 import {finished} from 'node:stream/promises';2 import mergeStreams from '@sindresorhus/merge-streams';3-import {isStreamAbort} from '../wait.js';4-import {isStandardStream} from './utils.js';3+import {isStreamAbort} from '../stream/wait.js';4+import {isStandardStream} from '../utils.js';5 6 // 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`.8 export const pipeStreams = (sources, destination) => {52 unmodified linesmodified:lib/stdio/sync.js+1 added-1 removed
1 import {readFileSync, writeFileSync} from 'node:fs';2+import {bufferToUint8Array, binaryToString} from '../utils.js';3 import {handleInput} from './handle.js';4 import {TYPE_TO_MESSAGE} from './type.js';4-import {bufferToUint8Array, binaryToString} from './utils.js';5 6 // Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, before spawning, in sync mode7 export const handleInputSync = options => {8 const stdioStreamsGroups = handleInput(addPropertiesSync, options, true);62 unmodified linesmodified:lib/stdio/type.js+1 added-1 removed
1 import {isStream as isNodeStream} from 'is-stream';2-import {isUint8Array} from './utils.js';2+import {isUint8Array} from '../utils.js';3 4 // The `stdin`/`stdout`/`stderr` option can be of many types. This detects it.5 export const getStdioOptionType = (stdioOption, optionName) => {6 if (isGenerator(stdioOption)) {94 unmodified linesdeleted:lib/stdio/utils.js-27 removed
1-import {Buffer} from 'node:buffer';2-import {addAbortListener} from 'node:events';3-import process from 'node:process';4-5-export const bufferToUint8Array = buffer => new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);6-7-export const isUint8Array = value => Object.prototype.toString.call(value) === '[object Uint8Array]' && !Buffer.isBuffer(value);8-export const isBinary = value => isUint8Array(value) || Buffer.isBuffer(value);9-10-const textDecoder = new TextDecoder();11-export const binaryToString = uint8ArrayOrBuffer => textDecoder.decode(uint8ArrayOrBuffer);12-13-export const isStandardStream = stream => STANDARD_STREAMS.includes(stream);14-export const STANDARD_STREAMS = [process.stdin, process.stdout, process.stderr];15-export const STANDARD_STREAMS_ALIASES = ['stdin', 'stdout', 'stderr'];16-17-export const incrementMaxListeners = (eventEmitter, maxListenersIncrement, signal) => {18- const maxListeners = eventEmitter.getMaxListeners();19- if (maxListeners === 0 || maxListeners === Number.POSITIVE_INFINITY) {20- return;21- }22-23- eventEmitter.setMaxListeners(maxListeners + maxListenersIncrement);24- addAbortListener(signal, () => {25- eventEmitter.setMaxListeners(eventEmitter.getMaxListeners() - maxListenersIncrement);26- });27-};added:lib/stdio/validate.js+28 added
1+import {isBinary} from '../utils.js';2+3+export const getValidateTransformReturn = (readableObjectMode, optionName) => readableObjectMode4+ ? validateObjectTransformReturn.bind(undefined, optionName)5+ : validateStringTransformReturn.bind(undefined, optionName);6+7+const validateObjectTransformReturn = function * (optionName, chunk) {8+ validateEmptyReturn(optionName, chunk);9+ yield chunk;10+};11+12+const validateStringTransformReturn = function * (optionName, chunk) {13+ validateEmptyReturn(optionName, chunk);14+15+ 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+ }18+19+ yield chunk;20+};21+22+const validateEmptyReturn = (optionName, chunk) => {23+ if (chunk === null || chunk === undefined) {24+ throw new TypeError(`The \`${optionName}\` option's function must not call \`yield ${chunk}\`.25+Instead, \`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
1+import mergeStreams from '@sindresorhus/merge-streams';2+import {generatorToDuplexStream} from '../stdio/generator.js';3+import {waitForChildStream} from './child.js';4+5+// `all` interleaves `stdout` and `stderr`6+export const makeAllStream = ({stdout, stderr}, {all}) => all && (stdout || stderr)7+ ? mergeStreams([stdout, stderr].filter(Boolean))8+ : undefined;9+10+// Read the contents of `childProcess.all` and|or wait for its completion11+export 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+});20+21+// 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.25+const getAllStream = ({all, stdout, stderr}, encoding) => all && stdout && stderr && stdout.readableObjectMode !== stderr.readableObjectMode26+ ? all.pipe(generatorToDuplexStream({value: allStreamGenerator, encoding}).value)27+ : all;28+29+const 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
1+import {setImmediate} from 'node:timers/promises';2+import getStream, {getStreamAsArrayBuffer, getStreamAsArray, MaxBufferError} from 'get-stream';3+import {waitForStream, handleStreamError, isInputFileDescriptor} from './wait.js';4+5+export const waitForChildStream = async ({stream, spawned, index, encoding, buffer, maxBuffer, streamInfo}) => {6+ if (!stream) {7+ return;8+ }9+10+ if (isInputFileDescriptor(index, streamInfo.stdioStreamsGroups)) {11+ await waitForStream(stream, index, streamInfo);12+ return;13+ }14+15+ if (!buffer) {16+ await Promise.all([17+ waitForStream(stream, index, streamInfo),18+ resumeStream(stream),19+ ]);20+ return;21+ }22+23+ try {24+ return await getAnyStream(stream, encoding, maxBuffer);25+ } catch (error) {26+ if (error instanceof MaxBufferError) {27+ spawned.kill();28+ }29+30+ handleStreamError(error, index, streamInfo);31+ return handleBufferedData(error, encoding);32+ }33+};34+35+// 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_r146549631037+const resumeStream = async stream => {38+ await setImmediate();39+ if (stream.readableFlowing === null) {40+ stream.resume();41+ }42+};43+44+const getAnyStream = async (stream, encoding, maxBuffer) => {45+ if (stream.readableObjectMode) {46+ return getStreamAsArray(stream, {maxBuffer});47+ }48+49+ const contents = encoding === 'buffer'50+ ? await getStreamAsArrayBuffer(stream, {maxBuffer})51+ : await getStream(stream, {maxBuffer});52+ return applyEncoding(contents, encoding);53+};54+55+// 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 retrieve58+export const getBufferedData = async (streamPromise, encoding) => {59+ try {60+ return await streamPromise;61+ } catch (error) {62+ return handleBufferedData(error, encoding);63+ }64+};65+66+const handleBufferedData = (error, encoding) => error.bufferedData === undefined || Array.isArray(error.bufferedData)67+ ? error.bufferedData68+ : applyEncoding(error.bufferedData, encoding);69+70+const applyEncoding = (contents, encoding) => encoding === 'buffer' ? new Uint8Array(contents) : contents;added:lib/stream/exit.js+31 added
1+import {once} from 'node:events';2+3+// 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 times10+export const waitForExit = async spawned => {11+ const [spawnPayload, exitPayload] = await Promise.allSettled([12+ once(spawned, 'spawn'),13+ once(spawned, 'exit'),14+ ]);15+16+ if (spawnPayload.status === 'rejected') {17+ return [];18+ }19+20+ return exitPayload.status === 'rejected'21+ ? waitForProcessExit(spawned)22+ : exitPayload.value;23+};24+25+const 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
1+import {once} from 'node:events';2+import {isStream} from 'is-stream';3+import {waitForSuccessfulExit} from '../exit/code.js';4+import {errorSignal} from '../exit/kill.js';5+import {throwOnTimeout} from '../exit/timeout.js';6+import {isStandardStream} from '../utils.js';7+import {waitForAllStream} from './all.js';8+import {waitForChildStream, getBufferedData} from './child.js';9+import {waitForExit} from './exit.js';10+import {waitForStream} from './wait.js';11+12+// Retrieve result of child process: exit code, signal, error, streams (stdout/stderr/all)13+export 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([])};23+24+ 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);28+29+ 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+};54+55+// Read the contents of `childProcess.std*` and|or wait for its completion56+const waitForChildStreams = ({spawned, encoding, buffer, maxBuffer, streamInfo}) =>57+ spawned.stdio.map((stream, index) => waitForChildStream({stream, spawned, index, encoding, buffer, maxBuffer, streamInfo}));58+59+// Transforms replace `childProcess.std*`, which means they are not exposed to users.60+// However, we still want to wait for their completion.61+const waitForOriginalStreams = (originalStreams, spawned, streamInfo) =>62+ originalStreams.map((stream, index) => stream === spawned.stdio[index]63+ ? undefined64+ : waitForStream(stream, index, streamInfo));65+66+// 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.69+const 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+ })));75+76+const throwOnProcessError = async (spawned, {signal}) => {77+ const [error] = await once(spawned, 'error', {signal});78+ throw error;79+};80+81+const throwOnInternalError = async (spawned, {signal}) => {82+ const [error] = await once(spawned, errorSignal, {signal});83+ throw error;84+};added:lib/stream/wait.js+61 added
1+import {finished} from 'node:stream/promises';2+3+// 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.6+export const waitForStream = async (stream, index, streamInfo, {isSameDirection, stopOnExit = false} = {}) => {7+ const {originalStreams: [originalStdin], exitPromise} = streamInfo;8+9+ 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+};21+22+// 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.27+export const handleStreamError = (error, index, streamInfo, isSameDirection) => {28+ if (!shouldIgnoreStreamError(error, index, streamInfo, isSameDirection)) {29+ throw error;30+ }31+};32+33+const shouldIgnoreStreamError = (error, index, {stdioStreamsGroups, propagating}, isSameDirection = true) => {34+ if (propagating.has(index)) {35+ return isStreamEpipe(error) || isStreamAbort(error);36+ }37+38+ propagating.add(index);39+ return isInputFileDescriptor(index, stdioStreamsGroups) === isSameDirection40+ ? isStreamEpipe(error)41+ : isStreamAbort(error);42+};43+44+// 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.49+export const isInputFileDescriptor = (index, stdioStreamsGroups) => stdioStreamsGroups[index][0].direction === 'input';50+51+// 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.54+export const isStreamAbort = error => error?.code === 'ERR_STREAM_PREMATURE_CLOSE';55+56+// 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.61+const isStreamEpipe = error => error?.code === 'EPIPE';added:lib/async.js+94 added
1+import {setMaxListeners} from 'node:events';2+import childProcess from 'node:child_process';3+import {handleOptionalArguments, handleArguments} from './arguments/options.js';4+import {makeError, makeEarlyError, makeSuccessResult} from './return/error.js';5+import {handleOutput} from './return/output.js';6+import {handleInputAsync, pipeOutputAsync, cleanupStdioStreams} from './stdio/async.js';7+import {spawnedKill} from './exit/kill.js';8+import {cleanupOnExit} from './exit/cleanup.js';9+import {pipeToProcess} from './pipe/setup.js';10+import {makeAllStream} from './stream/all.js';11+import {getSpawnedResult} from './stream/resolve.js';12+import {mergePromise} from './promise.js';13+14+export const execa = (rawFile, rawArgs, rawOptions) => {15+ const {file, args, command, escapedCommand, options} = handleAsyncArguments(rawFile, rawArgs, rawOptions);16+ const stdioStreamsGroups = handleInputAsync(options);17+18+ 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+ }30+31+ const controller = new AbortController();32+ setMaxListeners(Number.POSITIVE_INFINITY, controller.signal);33+34+ const originalStreams = [...spawned.stdio];35+ pipeOutputAsync(spawned, stdioStreamsGroups, controller);36+ cleanupOnExit(spawned, options, controller);37+38+ 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});41+42+ const promise = handlePromise({spawned, options, stdioStreamsGroups, originalStreams, command, escapedCommand, controller});43+ mergePromise(spawned, promise);44+ return spawned;45+};46+47+const 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+};53+54+// Prevent passing the `timeout` option directly to `child_process.spawn()`55+const handleAsyncOptions = ({timeout, ...options}) => ({...options, timeoutDuration: timeout});56+57+const handlePromise = async ({spawned, options, stdioStreamsGroups, originalStreams, command, escapedCommand, controller}) => {58+ const context = {timedOut: false};59+60+ const [61+ errorInfo,62+ [exitCode, signal],63+ stdioResults,64+ allResult,65+ ] = await getSpawnedResult({spawned, options, context, stdioStreamsGroups, originalStreams, controller});66+ controller.abort();67+68+ const stdio = stdioResults.map(stdioResult => handleOutput(options, stdioResult));69+ const all = handleOutput(options, allResult);70+71+ 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+ });85+86+ if (!options.reject) {87+ return returnedError;88+ }89+90+ throw returnedError;91+ }92+93+ return makeSuccessResult({command, escapedCommand, stdio, all, options});94+};deleted:lib/clone.js-70 removed
1-export const getFinalError = (initialError, message) => {2- const error = createFinalError(initialError, message);3- previousErrors.add(error);4- return error;5-};6-7-const createFinalError = (error, message) => {8- if (!isErrorInstance(error)) {9- return new Error(message);10- }11-12- return previousErrors.has(error)13- ? cloneError(error, message)14- : setErrorMessage(error, message);15-};16-17-export const isErrorInstance = value => Object.prototype.toString.call(value) === '[object Error]';18-19-const 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-};27-28-const 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-};36-37-// Known error properties38-const COPIED_ERROR_PROPERTIES = [39- 'cause',40- 'errors',41- 'code',42- 'errno',43- 'syscall',44- 'path',45- 'dest',46- 'address',47- 'port',48- 'info',49-];50-51-// 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/5171555-const setErrorMessage = (error, newMessage) => {56- const {message, stack} = error;57- error.message = newMessage;58- error.stack = fixStack(stack, message, newMessage);59- return error;60-};61-62-const fixStack = (stack, message, newMessage) => stack.includes(newMessage)63- ? stack64- : stack.replace(`: ${message}`, `: ${newMessage}`);65-66-// Two `execa()` calls might return the same error.67-// So we must close those before directly mutating them.68-export const isPreviousError = error => previousErrors.has(error);69-70-const previousErrors = new WeakSet();modified:lib/command.js+15 added-3 removed
1-const SPACES_REGEXP = / +/g;1+import {execa} from './async.js';2+import {execaSync} from './sync.js';3 3-// Handle `execaCommand()`4-export const parseCommand = command => {4+export function execaCommand(command, options) {5+ const [file, ...args] = parseCommand(command);6+ return execa(file, args, options);7+}8+9+export function execaCommandSync(command, options) {10+ const [file, ...args] = parseCommand(command);11+ return execaSync(file, args, options);12+}13+14+const 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 lines25 }26 27 return tokens;28 };29+30+const SPACES_REGEXP = / +/g;deleted:lib/cwd.js-49 removed
1-import {statSync} from 'node:fs';2-import {resolve} from 'node:path';3-import {fileURLToPath} from 'node:url';4-import process from 'node:process';5-6-export const normalizeCwd = (cwd = getDefaultCwd()) => {7- const cwdString = safeNormalizeFileUrl(cwd, 'The "cwd" option');8- return resolve(cwdString);9-};10-11-const 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-};19-20-export const safeNormalizeFileUrl = (file, name) => {21- const fileString = normalizeFileUrl(file);22-23- if (typeof fileString !== 'string') {24- throw new TypeError(`${name} must be a string or a file URL: ${fileString}.`);25- }26-27- return fileString;28-};29-30-export const normalizeFileUrl = file => file instanceof URL ? fileURLToPath(file) : file;31-32-export const fixCwdError = (originalMessage, cwd) => {33- if (cwd === getDefaultCwd()) {34- return originalMessage;35- }36-37- 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- }43-44- if (!cwdStat.isDirectory()) {45- return `The "cwd" option is not a directory: ${cwd}.\n${originalMessage}`;46- }47-48- return originalMessage;49-};deleted:lib/error.js-191 removed
1-import {signalsByName} from 'human-signals';2-import stripFinalNewline from 'strip-final-newline';3-import {isBinary, binaryToString} from './stdio/utils.js';4-import {fixCwdError} from './cwd.js';5-import {getFinalError, isPreviousError} from './clone.js';6-7-const 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-};32-33-const getErrorPrefix = ({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled}) => {34- if (timedOut) {35- return `Command timed out after ${timeout} milliseconds`;36- }37-38- if (isCanceled) {39- return 'Command was canceled';40- }41-42- if (errorCode !== undefined) {43- return `Command failed with ${errorCode}`;44- }45-46- if (signal !== undefined) {47- return `Command was killed with ${signal} (${signalDescription})`;48- }49-50- if (exitCode !== undefined) {51- return `Command failed with exit code ${exitCode}`;52- }53-54- return 'Command failed';55-};56-57-const getOriginalMessage = (error, cwd) => {58- if (error === undefined) {59- return '';60- }61-62- const originalMessage = isPreviousError(error) ? error.originalMessage : String(error?.message ?? error);63- return fixCwdError(originalMessage, cwd);64-};65-66-const serializeMessagePart = messagePart => Array.isArray(messagePart)67- ? messagePart.map(messageItem => serializeMessageItem(messageItem)).join('')68- : serializeMessageItem(messagePart);69-70-const serializeMessageItem = messageItem => {71- if (typeof messageItem === 'string') {72- return messageItem;73- }74-75- if (isBinary(messageItem)) {76- return binaryToString(messageItem);77- }78-79- return '';80-};81-82-// Indicates that the error is used only to interrupt control flow, but not in the return value83-export class DiscardedError extends Error {}84-85-// `signal` and `exitCode` emitted on `spawned.on('exit')` event can be `null`.86-// We normalize them to `undefined`87-const 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-};93-94-export 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);122-123- error.shortMessage = shortMessage;124- error.originalMessage = originalMessage;125- error.command = command;126- error.escapedCommand = escapedCommand;127- error.cwd = cwd;128-129- 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;136-137- error.stdout = stdio[1];138- error.stderr = stdio[2];139-140- if (all !== undefined) {141- error.all = all;142- }143-144- error.stdio = stdio;145-146- if ('bufferedData' in error) {147- delete error.bufferedData;148- }149-150- error.pipedFrom = [];151-152- return error;153-};154-155-export 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-});170-171-export 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
1-export 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-};7-8-const escapeArg = arg => typeof arg === 'string' && !NO_ESCAPE_REGEXP.test(arg)9- ? `"${arg.replaceAll('"', '\\"')}"`10- : arg;11-12-const NO_ESCAPE_REGEXP = /^[\w.-]+$/;deleted:lib/kill.js-124 removed
1-import {addAbortListener} from 'node:events';2-import os from 'node:os';3-import {setTimeout} from 'node:timers/promises';4-import {onExit} from 'signal-exit';5-import {isErrorInstance} from './clone.js';6-import {DiscardedError} from './error.js';7-8-const DEFAULT_FORCE_KILL_TIMEOUT = 1000 * 5;9-10-// Monkey-patches `childProcess.kill()` to add `forceKillAfterDelay` behavior and `.kill(error)`11-export 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-};18-19-const parseKillArguments = (signalOrError, errorArgument, killSignal) => {20- const [signal = killSignal, error] = isErrorInstance(signalOrError)21- ? [undefined, signalOrError]22- : [signalOrError, errorArgument];23-24- 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- }27-28- if (error !== undefined && !isErrorInstance(error)) {29- throw new TypeError(`The second argument is optional. If specified, it must be an error instance: ${error}`);30- }31-32- return {signal, error};33-};34-35-const emitKillError = (spawned, error) => {36- if (error !== undefined) {37- spawned.emit(errorSignal, error);38- }39-};40-41-// Like `error` signal but internal to Execa.42-// E.g. does not make process crash when no `error` listener is set.43-export const errorSignal = Symbol('error');44-45-const setKillTimeout = async ({kill, signal, forceKillAfterDelay, killSignal, killResult, controller}) => {46- if (!shouldForceKill(signal, forceKillAfterDelay, killSignal, killResult)) {47- return;48- }49-50- try {51- await setTimeout(forceKillAfterDelay, undefined, {signal: controller.signal});52- kill('SIGKILL');53- } catch {}54-};55-56-const shouldForceKill = (signal, forceKillAfterDelay, killSignal, killResult) =>57- normalizeSignal(signal) === normalizeSignal(killSignal)58- && forceKillAfterDelay !== false59- && killResult;60-61-const normalizeSignal = signal => typeof signal === 'string'62- ? os.constants.signals[signal.toUpperCase()]63- : signal;64-65-export const normalizeForceKillAfterDelay = forceKillAfterDelay => {66- if (forceKillAfterDelay === false) {67- return forceKillAfterDelay;68- }69-70- if (forceKillAfterDelay === true) {71- return DEFAULT_FORCE_KILL_TIMEOUT;72- }73-74- 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- }77-78- return forceKillAfterDelay;79-};80-81-export const waitForSuccessfulExit = async exitPromise => {82- const [exitCode, signal] = await exitPromise;83-84- if (!isProcessErrorExit(exitCode, signal) && isFailedExit(exitCode, signal)) {85- throw new DiscardedError();86- }87-88- return [exitCode, signal];89-};90-91-const isProcessErrorExit = (exitCode, signal) => exitCode === undefined && signal === undefined;92-export const isFailedExit = (exitCode, signal) => exitCode !== 0 || signal !== null;93-94-const killAfterTimeout = async (spawned, timeout, context, {signal}) => {95- await setTimeout(timeout, undefined, {signal});96- context.timedOut = true;97- spawned.kill();98- throw new DiscardedError();99-};100-101-// `timeout` option handling102-export const throwOnTimeout = (spawned, timeout, context, controller) => timeout === 0 || timeout === undefined103- ? []104- : [killAfterTimeout(spawned, timeout, context, controller)];105-106-export 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-};111-112-// `cleanup` option handling113-export const cleanupOnExit = (spawned, {cleanup, detached}, {signal}) => {114- if (!cleanup || detached) {115- return;116- }117-118- const removeExitHandler = onExit(() => {119- spawned.kill();120- });121- addAbortListener(signal, () => {122- removeExitHandler();123- });124-};deleted:lib/node.js-34 removed
1-import {execPath, execArgv} from 'node:process';2-import {basename, resolve} from 'node:path';3-import {safeNormalizeFileUrl} from './cwd.js';4-5-export 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- }16-17- const normalizedNodePath = safeNormalizeFileUrl(nodePath, 'The "nodePath" option');18- const resolvedNodePath = resolve(cwd, normalizedNodePath);19- const newOptions = {...options, nodePath: resolvedNodePath, cwd};20-21- if (!shouldHandleNode) {22- return [file, args, newOptions];23- }24-25- 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- }28-29- 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-await2-const nativePromisePrototype = (async () => {})().constructor.prototype;3-4-const descriptors = ['then', 'catch', 'finally'].map(property => [5- property,6- Reflect.getOwnPropertyDescriptor(nativePromisePrototype, property),7-]);8-1 // The return value is a mixin of `childProcess` and `Promise`2 export 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 };8+9+// eslint-disable-next-line unicorn/prefer-top-level-await10+const nativePromisePrototype = (async () => {})().constructor.prototype;11+12+const descriptors = ['then', 'catch', 'finally'].map(property => [13+ property,14+ Reflect.getOwnPropertyDescriptor(nativePromisePrototype, property),15+]);modified:lib/script.js+75 added-38 removed
1 import {ChildProcess} from 'node:child_process';2-import {isBinary, binaryToString} from './stdio/utils.js';2+import {isBinary, binaryToString} from './utils.js';3+import {execa} from './async.js';4+import {execaSync} from './sync.js';5 4-const parseExpression = expression => {5- const typeOfExpression = typeof expression;6+const create$ = options => {7+ function $(templatesOrOptions, ...expressions) {8+ if (!Array.isArray(templatesOrOptions)) {9+ return create$({...options, ...templatesOrOptions});10+ }11 7- if (typeOfExpression === 'string') {8- return expression;12+ const [file, ...args] = parseTemplates(templatesOrOptions, expressions);13+ return execa(file, args, normalizeScriptOptions(options));14 }15 11- if (typeOfExpression === 'number') {12- return String(expression);13- }14-15- if (16- typeOfExpression === 'object'17- && expression !== null18- && !(expression instanceof ChildProcess)19- && 'stdout' in expression20- ) {21- const typeOfStdout = typeof expression.stdout;22-23- 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 }20 27- 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+ };24 31- throw new TypeError(`Unexpected "${typeOfStdout}" stdout in template expression`);32- }25+ $.s = $.sync;26 34- throw new TypeError(`Unexpected "${typeOfExpression}" in template expression`);27+ return $;28 };29 37-const 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- ];30+export const $ = create$();31 45-const SPACES_REGEXP = / +/g;32+const parseTemplates = (templates, expressions) => {33+ let tokens = [];34 35+ for (const [index, template] of templates.entries()) {36+ tokens = parseTemplate({templates, expressions, tokens, index, template});37+ }38+39+ return tokens;40+};41+42 const 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 lines62 templateString.endsWith(' '),63 );64 };65 71-export const parseTemplates = (templates, expressions) => {72- let tokens = [];66+const SPACES_REGEXP = / +/g;67 74- for (const [index, template] of templates.entries()) {75- tokens = parseTemplate({templates, expressions, tokens, index, template});68+const 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+ ];75+76+const parseExpression = expression => {77+ const typeOfExpression = typeof expression;78+79+ if (typeOfExpression === 'string') {80+ return expression;81 }82 78- return tokens;83+ if (typeOfExpression === 'number') {84+ return String(expression);85+ }86+87+ if (88+ typeOfExpression === 'object'89+ && expression !== null90+ && !(expression instanceof ChildProcess)91+ && 'stdout' in expression92+ ) {93+ const typeOfStdout = typeof expression.stdout;94+95+ if (typeOfStdout === 'string') {96+ return expression.stdout;97+ }98+99+ if (isBinary(expression.stdout)) {100+ return binaryToString(expression.stdout);101+ }102+103+ throw new TypeError(`Unexpected "${typeOfStdout}" stdout in template expression`);104+ }105+106+ throw new TypeError(`Unexpected "${typeOfExpression}" in template expression`);107 };108 109+const normalizeScriptOptions = (options = {}) => ({110+ preferLocal: true,111+ ...normalizeScriptStdin(options),112+ ...options,113+});114+115+const normalizeScriptStdin = ({input, inputFile, stdio}) => input === undefined && inputFile === undefined && stdio === undefined116+ ? {stdin: 'inherit'}117+ : {};deleted:lib/stream.js-220 removed
1-import {once} from 'node:events';2-import {setImmediate} from 'node:timers/promises';3-import getStream, {getStreamAsArrayBuffer, getStreamAsArray, MaxBufferError} from 'get-stream';4-import {isStream} from 'is-stream';5-import mergeStreams from '@sindresorhus/merge-streams';6-import {waitForSuccessfulExit, throwOnTimeout, errorSignal} from './kill.js';7-import {isStandardStream} from './stdio/utils.js';8-import {generatorToDuplexStream} from './stdio/generator.js';9-import {waitForStream, handleStreamError, isInputFileDescriptor} from './wait.js';10-11-// `all` interleaves `stdout` and `stderr`12-export const makeAllStream = ({stdout, stderr}, {all}) => all && (stdout || stderr)13- ? mergeStreams([stdout, stderr].filter(Boolean))14- : undefined;15-16-// 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 retrieve19-const getBufferedData = async (streamPromise, encoding) => {20- try {21- return await streamPromise;22- } catch (error) {23- return handleBufferedData(error, encoding);24- }25-};26-27-const handleBufferedData = (error, encoding) => error.bufferedData === undefined || Array.isArray(error.bufferedData)28- ? error.bufferedData29- : applyEncoding(error.bufferedData, encoding);30-31-// Read the contents of `childProcess.std*` and|or wait for its completion32-const 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-}));41-42-// Read the contents of `childProcess.all` and|or wait for its completion43-const 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-});52-53-// 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.57-const getAllStream = ({all, stdout, stderr}, encoding) => all && stdout && stderr && stdout.readableObjectMode !== stderr.readableObjectMode58- ? all.pipe(generatorToDuplexStream({value: allStreamGenerator, encoding}).value)59- : all;60-61-const allStreamGenerator = {62- * transform(chunk) {63- yield chunk;64- },65- binary: true,66- writableObjectMode: true,67- readableObjectMode: true,68-};69-70-const waitForChildStream = async ({stream, spawned, index, encoding, buffer, maxBuffer, streamInfo}) => {71- if (!stream) {72- return;73- }74-75- if (isInputFileDescriptor(index, streamInfo.stdioStreamsGroups)) {76- await waitForStream(stream, index, streamInfo);77- return;78- }79-80- if (!buffer) {81- await Promise.all([82- waitForStream(stream, index, streamInfo),83- resumeStream(stream),84- ]);85- return;86- }87-88- try {89- return await getAnyStream(stream, encoding, maxBuffer);90- } catch (error) {91- if (error instanceof MaxBufferError) {92- spawned.kill();93- }94-95- handleStreamError(error, index, streamInfo);96- return handleBufferedData(error, encoding);97- }98-};99-100-// 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_r1465496310102-const resumeStream = async stream => {103- await setImmediate();104- if (stream.readableFlowing === null) {105- stream.resume();106- }107-};108-109-const getAnyStream = async (stream, encoding, maxBuffer) => {110- if (stream.readableObjectMode) {111- return getStreamAsArray(stream, {maxBuffer});112- }113-114- const contents = encoding === 'buffer'115- ? await getStreamAsArrayBuffer(stream, {maxBuffer})116- : await getStream(stream, {maxBuffer});117- return applyEncoding(contents, encoding);118-};119-120-const applyEncoding = (contents, encoding) => encoding === 'buffer' ? new Uint8Array(contents) : contents;121-122-// Transforms replace `childProcess.std*`, which means they are not exposed to users.123-// However, we still want to wait for their completion.124-const waitForOriginalStreams = (originalStreams, spawned, streamInfo) =>125- originalStreams.map((stream, index) => stream === spawned.stdio[index]126- ? undefined127- : waitForStream(stream, index, streamInfo));128-129-// 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.132-const 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- })));138-139-const throwOnProcessError = async (spawned, {signal}) => {140- const [error] = await once(spawned, 'error', {signal});141- throw error;142-};143-144-const throwOnInternalError = async (spawned, {signal}) => {145- const [error] = await once(spawned, errorSignal, {signal});146- throw error;147-};148-149-// 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 times156-const waitForExit = async spawned => {157- const [spawnPayload, exitPayload] = await Promise.allSettled([158- once(spawned, 'spawn'),159- once(spawned, 'exit'),160- ]);161-162- if (spawnPayload.status === 'rejected') {163- return [];164- }165-166- return exitPayload.status === 'rejected'167- ? waitForProcessExit(spawned)168- : exitPayload.value;169-};170-171-const waitForProcessExit = async spawned => {172- try {173- return await once(spawned, 'exit');174- } catch {175- return waitForProcessExit(spawned);176- }177-};178-179-// Retrieve result of child process: exit code, signal, error, streams (stdout/stderr/all)180-export 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([])};190-191- 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);195-196- 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
1+import childProcess from 'node:child_process';2+import {handleOptionalArguments, handleArguments} from './arguments/options.js';3+import {makeError, makeEarlyError, makeSuccessResult} from './return/error.js';4+import {handleOutput} from './return/output.js';5+import {handleInputSync, pipeOutputSync} from './stdio/sync.js';6+import {isFailedExit} from './exit/code.js';7+8+export const execaSync = (rawFile, rawArgs, rawOptions) => {9+ const {file, args, command, escapedCommand, options} = handleSyncArguments(rawFile, rawArgs, rawOptions);10+ const stdioStreamsGroups = handleInputSync(options);11+12+ let result;13+ try {14+ result = childProcess.spawnSync(file, args, options);15+ } catch (error) {16+ const errorInstance = makeEarlyError({error, command, escapedCommand, stdioStreamsGroups, options});17+18+ if (!options.reject) {19+ return errorInstance;20+ }21+22+ throw errorInstance;23+ }24+25+ pipeOutputSync(stdioStreamsGroups, result);26+27+ const output = result.output || Array.from({length: 3});28+ const stdio = output.map(stdioOutput => handleOutput(options, stdioOutput));29+30+ 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+ });42+43+ if (!options.reject) {44+ return error;45+ }46+47+ throw error;48+ }49+50+ return makeSuccessResult({command, escapedCommand, stdio, options});51+};52+53+const 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+};60+61+const normalizeSyncOptions = options => options.node && !options.ipc ? {...options, ipc: false} : options;62+63+const 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
1+import {Buffer} from 'node:buffer';2+import {addAbortListener} from 'node:events';3+import process from 'node:process';4+5+export const bufferToUint8Array = buffer => new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);6+7+export const isUint8Array = value => Object.prototype.toString.call(value) === '[object Uint8Array]' && !Buffer.isBuffer(value);8+export const isBinary = value => isUint8Array(value) || Buffer.isBuffer(value);9+10+const textDecoder = new TextDecoder();11+export const binaryToString = uint8ArrayOrBuffer => textDecoder.decode(uint8ArrayOrBuffer);12+13+export const isStandardStream = stream => STANDARD_STREAMS.includes(stream);14+export const STANDARD_STREAMS = [process.stdin, process.stdout, process.stderr];15+export const STANDARD_STREAMS_ALIASES = ['stdin', 'stdout', 'stderr'];16+17+export const incrementMaxListeners = (eventEmitter, maxListenersIncrement, signal) => {18+ const maxListeners = eventEmitter.getMaxListeners();19+ if (maxListeners === 0 || maxListeners === Number.POSITIVE_INFINITY) {20+ return;21+ }22+23+ eventEmitter.setMaxListeners(maxListeners + maxListenersIncrement);24+ addAbortListener(signal, () => {25+ eventEmitter.setMaxListeners(eventEmitter.getMaxListeners() - maxListenersIncrement);26+ });27+};deleted:lib/verbose.js-22 removed
1-import {writeFileSync} from 'node:fs';2-import {debuglog} from 'node:util';3-import process from 'node:process';4-5-export const verboseDefault = debuglog('execa').enabled;6-7-const padField = (field, padding) => String(field).padStart(padding, '0');8-9-const 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-};13-14-export const logCommand = (escapedCommand, {verbose}) => {15- if (!verbose) {16- return;17- }18-19- // 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
1-import {finished} from 'node:stream/promises';2-3-// 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.6-export const waitForStream = async (stream, index, streamInfo, {isSameDirection, stopOnExit = false} = {}) => {7- const {originalStreams: [originalStdin], exitPromise} = streamInfo;8-9- 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-};21-22-// 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.27-export const handleStreamError = (error, index, streamInfo, isSameDirection) => {28- if (!shouldIgnoreStreamError(error, index, streamInfo, isSameDirection)) {29- throw error;30- }31-};32-33-const shouldIgnoreStreamError = (error, index, {stdioStreamsGroups, propagating}, isSameDirection = true) => {34- if (propagating.has(index)) {35- return isStreamEpipe(error) || isStreamAbort(error);36- }37-38- propagating.add(index);39- return isInputFileDescriptor(index, stdioStreamsGroups) === isSameDirection40- ? isStreamEpipe(error)41- : isStreamAbort(error);42-};43-44-// 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.49-export const isInputFileDescriptor = (index, stdioStreamsGroups) => stdioStreamsGroups[index][0].direction === 'input';50-51-// 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.54-export const isStreamAbort = error => error?.code === 'ERR_STREAM_PREMATURE_CLOSE';55-56-// 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.61-const isStreamEpipe = error => error?.code === 'EPIPE';added:test/arguments/cwd.js+103 added
1+import {mkdir, rmdir} from 'node:fs/promises';2+import {relative, toNamespacedPath} from 'node:path';3+import process from 'node:process';4+import {pathToFileURL, fileURLToPath} from 'node:url';5+import tempfile from 'tempfile';6+import test from 'ava';7+import {execa, execaSync} from '../../index.js';8+import {FIXTURES_DIR, setFixtureDir} from '../helpers/fixtures-dir.js';9+10+setFixtureDir();11+12+const isWindows = process.platform === 'win32';13+14+const 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+};19+20+test('The "cwd" option can be a string', testOptionCwdString, execa);21+test('The "cwd" option can be a string - sync', testOptionCwdString, execaSync);22+23+const 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+};29+30+test('The "cwd" option can be a URL', testOptionCwdUrl, execa);31+test('The "cwd" option can be a URL - sync', testOptionCwdUrl, execaSync);32+33+const 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+};38+39+test('The "cwd" option cannot be an invalid type', testOptionCwdInvalid, execa);40+test('The "cwd" option cannot be an invalid type - sync', testOptionCwdInvalid, execaSync);41+42+const testErrorCwdDefault = async (t, execaMethod) => {43+ const {cwd} = await execaMethod('empty.js');44+ t.is(cwd, process.cwd());45+};46+47+test('The "cwd" option defaults to process.cwd()', testErrorCwdDefault, execa);48+test('The "cwd" option defaults to process.cwd() - sync', testErrorCwdDefault, execaSync);49+50+// Windows does not allow removing a directory used as `cwd` of a running process51+if (!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);58+59+ try {60+ t.throws(() => {61+ execaMethod('empty.js');62+ }, {message: /The current directory does not exist/});63+ } finally {64+ process.chdir(currentCwd);65+ }66+ };67+68+ 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+}71+72+const cwdNotExisting = {cwd: 'does_not_exist', expectedCode: 'ENOENT', expectedMessage: 'The "cwd" option is invalid'};73+const cwdTooLong = {cwd: '.'.repeat(1e5), expectedCode: 'ENAMETOOLONG', expectedMessage: 'The "cwd" option is invalid'};74+const cwdNotDir = {cwd: fileURLToPath(import.meta.url), expectedCode: isWindows ? 'ENOENT' : 'ENOTDIR', expectedMessage: 'The "cwd" option is not a directory'};75+76+const 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+};83+84+test('The "cwd" option must be an existing file', testCwdPostSpawn, cwdNotExisting, execa);85+test('The "cwd" option must be an existing file - sync', testCwdPostSpawn, cwdNotExisting, execaSync);86+test('The "cwd" option must not be too long', testCwdPostSpawn, cwdTooLong, execa);87+test('The "cwd" option must not be too long - sync', testCwdPostSpawn, cwdTooLong, execaSync);88+test('The "cwd" option must be a directory', testCwdPostSpawn, cwdNotDir, execa);89+test('The "cwd" option must be a directory - sync', testCwdPostSpawn, cwdNotDir, execaSync);90+91+const successProperties = {fixtureName: 'empty.js', expectedFailed: false};92+const errorProperties = {fixtureName: 'fail.js', expectedFailed: true};93+94+const 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+};99+100+test('result.cwd is defined', testErrorCwd, execa, successProperties);101+test('result.cwd is defined - sync', testErrorCwd, execaSync, successProperties);102+test('error.cwd is defined', testErrorCwd, execa, errorProperties);103+test('error.cwd is defined - sync', testErrorCwd, execaSync, errorProperties);added:test/arguments/escape.js+52 added
1+import test from 'ava';2+import {execa, execaSync} from '../../index.js';3+import {setFixtureDir} from '../helpers/fixtures-dir.js';4+5+setFixtureDir();6+7+const testResultCommand = async (t, expected, ...args) => {8+ const {command: failCommand} = await t.throwsAsync(execa('fail.js', args));9+ t.is(failCommand, `fail.js${expected}`);10+11+ const {command} = await execa('noop.js', args);12+ t.is(command, `noop.js${expected}`);13+};14+15+testResultCommand.title = (message, expected) => `result.command is: ${JSON.stringify(expected)}`;16+17+test(testResultCommand, ' foo bar', 'foo', 'bar');18+test(testResultCommand, ' baz quz', 'baz', 'quz');19+test(testResultCommand, '');20+21+const testEscapedCommand = async (t, expected, args) => {22+ const {escapedCommand: failEscapedCommand} = await t.throwsAsync(execa('fail.js', args));23+ t.is(failEscapedCommand, `fail.js ${expected}`);24+25+ const {escapedCommand: failEscapedCommandSync} = t.throws(() => {26+ execaSync('fail.js', args);27+ });28+ t.is(failEscapedCommandSync, `fail.js ${expected}`);29+30+ const {escapedCommand} = await execa('noop.js', args);31+ t.is(escapedCommand, `noop.js ${expected}`);32+33+ const {escapedCommand: escapedCommandSync} = execaSync('noop.js', args);34+ t.is(escapedCommandSync, `noop.js ${expected}`);35+};36+37+testEscapedCommand.title = (message, expected) => `result.escapedCommand is: ${JSON.stringify(expected)}`;38+39+test(testEscapedCommand, 'foo bar', ['foo', 'bar']);40+test(testEscapedCommand, '"foo bar"', ['foo bar']);41+test(testEscapedCommand, '"\\"foo\\""', ['"foo"']);42+test(testEscapedCommand, '"*"', ['*']);43+44+test('allow commands with spaces and no array arguments', async t => {45+ const {stdout} = await execa('command with space.js');46+ t.is(stdout, '');47+});48+49+test('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
1+import {dirname, relative} from 'node:path';2+import process from 'node:process';3+import {pathToFileURL} from 'node:url';4+import test from 'ava';5+import getNode from 'get-node';6+import {pEvent} from 'p-event';7+import {execa, execaSync, execaNode} from '../../index.js';8+import {FIXTURES_DIR} from '../helpers/fixtures-dir.js';9+import {identity, fullStdio} from '../helpers/stdio.js';10+import {foobarString} from '../helpers/input.js';11+12+process.chdir(FIXTURES_DIR);13+14+const runWithNodeOption = (file, args, options) => Array.isArray(args)15+ ? execa(file, args, {...options, node: true})16+ : execa(file, {...options, node: true});17+const runWithNodeOptionSync = (file, args, options) => Array.isArray(args)18+ ? execaSync(file, args, {...options, node: true})19+ : execaSync(file, {...options, node: true});20+const runWithIpc = (file, options) => execa('node', [file], {...options, ipc: true});21+22+const testNodeSuccess = async (t, execaMethod) => {23+ const {exitCode, stdout} = await execaMethod('noop.js', [foobarString]);24+ t.is(exitCode, 0);25+ t.is(stdout, foobarString);26+};27+28+test('execaNode() succeeds', testNodeSuccess, execaNode);29+test('The "node" option succeeds', testNodeSuccess, runWithNodeOption);30+test('The "node" option succeeds - sync', testNodeSuccess, runWithNodeOptionSync);31+32+test('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+});37+38+const testDoubleNode = (t, nodePath, execaMethod) => {39+ t.throws(() => {40+ execaMethod(nodePath, ['noop.js']);41+ }, {message: /does not need to be "node"/});42+};43+44+test('Cannot use "node" as binary - execaNode()', testDoubleNode, 'node', execaNode);45+test('Cannot use "node" as binary - "node" option', testDoubleNode, 'node', runWithNodeOption);46+test('Cannot use "node" as binary - "node" option sync', testDoubleNode, 'node', runWithNodeOptionSync);47+test('Cannot use path to "node" as binary - execaNode()', testDoubleNode, process.execPath, execaNode);48+test('Cannot use path to "node" as binary - "node" option', testDoubleNode, process.execPath, runWithNodeOption);49+test('Cannot use path to "node" as binary - "node" option sync', testDoubleNode, process.execPath, runWithNodeOptionSync);50+51+const getNodePath = async () => {52+ const {path} = await getNode(TEST_NODE_VERSION);53+ return path;54+};55+56+const TEST_NODE_VERSION = '16.0.0';57+58+const 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+};63+64+test.serial('The "nodePath" option can be used - execaNode()', testNodePath, execaNode, identity);65+test.serial('The "nodePath" option can be a file URL - execaNode()', testNodePath, execaNode, pathToFileURL);66+test.serial('The "nodePath" option can be used - "node" option', testNodePath, runWithNodeOption, identity);67+test.serial('The "nodePath" option can be a file URL - "node" option', testNodePath, runWithNodeOption, pathToFileURL);68+test.serial('The "nodePath" option can be used - "node" option sync', testNodePath, runWithNodeOptionSync, identity);69+test.serial('The "nodePath" option can be a file URL - "node" option sync', testNodePath, runWithNodeOptionSync, pathToFileURL);70+71+const testNodePathDefault = async (t, execaMethod) => {72+ const {stdout} = await execaMethod('--version');73+ t.is(stdout, process.version);74+};75+76+test('The "nodePath" option defaults to the current Node.js binary - execaNode()', testNodePathDefault, execaNode);77+test('The "nodePath" option defaults to the current Node.js binary - "node" option', testNodePathDefault, runWithNodeOption);78+test('The "nodePath" option defaults to the current Node.js binary - "node" option sync', testNodePathDefault, runWithNodeOptionSync);79+80+const 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+};85+86+test('The "nodePath" option must be a string or URL - execaNode()', testNodePathInvalid, execaNode);87+test('The "nodePath" option must be a string or URL - "node" option', testNodePathInvalid, runWithNodeOption);88+test('The "nodePath" option must be a string or URL - "node" option sync', testNodePathInvalid, runWithNodeOptionSync);89+90+const testFormerNodePath = (t, execaMethod) => {91+ t.throws(() => {92+ execaMethod('noop.js', [], {execPath: process.execPath});93+ }, {message: /The "execPath" option has been removed/});94+};95+96+test('The "execPath" option cannot be used - execaNode()', testFormerNodePath, execaNode);97+test('The "execPath" option cannot be used - "node" option', testFormerNodePath, runWithNodeOption);98+test('The "execPath" option cannot be used - "node" option sync', testFormerNodePath, runWithNodeOptionSync);99+100+const nodePathArguments = ['node', ['-p', 'process.env.Path || process.env.PATH']];101+102+const 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+};107+108+test.serial('The "nodePath" option impacts the child process', testChildNodePath, identity);109+test.serial('The "nodePath" option can be a file URL', testChildNodePath, pathToFileURL);110+111+test('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+});115+116+test.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+});121+122+test.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+});129+130+const 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+};137+138+test.serial('The "nodePath" option is relative to "cwd" - execaNode()', testCwdNodePath, execaNode);139+test.serial('The "nodePath" option is relative to "cwd" - "node" option', testCwdNodePath, runWithNodeOption);140+test.serial('The "nodePath" option is relative to "cwd" - "node" option sync', testCwdNodePath, runWithNodeOptionSync);141+142+const testNodeOptions = async (t, execaMethod) => {143+ const {stdout} = await execaMethod('empty.js', [], {nodeOptions: ['--version']});144+ t.is(stdout, process.version);145+};146+147+test('The "nodeOptions" option can be used - execaNode()', testNodeOptions, execaNode);148+test('The "nodeOptions" option can be used - "node" option', testNodeOptions, runWithNodeOption);149+test('The "nodeOptions" option can be used - "node" option sync', testNodeOptions, runWithNodeOptionSync);150+151+const 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+);156+157+const testInspectRemoval = async (t, fakeExecArgv, execaMethod) => {158+ const {stdout, stdio} = await spawnNestedExecaNode([], fakeExecArgv, execaMethod, '');159+ t.is(stdout, foobarString);160+ t.is(stdio[3], '');161+};162+163+test('The "nodeOptions" option removes --inspect without a port when defined by parent process - execaNode()', testInspectRemoval, '--inspect', 'execaNode');164+test('The "nodeOptions" option removes --inspect without a port when defined by parent process - "node" option', testInspectRemoval, '--inspect', 'nodeOption');165+test('The "nodeOptions" option removes --inspect with a port when defined by parent process - execaNode()', testInspectRemoval, '--inspect=9222', 'execaNode');166+test('The "nodeOptions" option removes --inspect with a port when defined by parent process - "node" option', testInspectRemoval, '--inspect=9222', 'nodeOption');167+test('The "nodeOptions" option removes --inspect-brk without a port when defined by parent process - execaNode()', testInspectRemoval, '--inspect-brk', 'execaNode');168+test('The "nodeOptions" option removes --inspect-brk without a port when defined by parent process - "node" option', testInspectRemoval, '--inspect-brk', 'nodeOption');169+test('The "nodeOptions" option removes --inspect-brk with a port when defined by parent process - execaNode()', testInspectRemoval, '--inspect-brk=9223', 'execaNode');170+test('The "nodeOptions" option removes --inspect-brk with a port when defined by parent process - "node" option', testInspectRemoval, '--inspect-brk=9223', 'nodeOption');171+172+const 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+};177+178+test.serial('The "nodeOptions" option allows --inspect with a different port even when defined by parent process - execaNode()', testInspectDifferentPort, 'execaNode');179+test.serial('The "nodeOptions" option allows --inspect with a different port even when defined by parent process - "node" option', testInspectDifferentPort, 'nodeOption');180+181+const 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+};186+187+test.serial('The "nodeOptions" option forbids --inspect with the same port when defined by parent process - execaNode()', testInspectSamePort, 'execaNode');188+test.serial('The "nodeOptions" option forbids --inspect with the same port when defined by parent process - "node" option', testInspectSamePort, 'nodeOption');189+190+const 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+};199+200+test('execaNode() adds an ipc channel', testIpc, execaNode, {});201+test('The "node" option adds an ipc channel', testIpc, runWithNodeOption, {});202+test('The "ipc" option adds an ipc channel', testIpc, runWithIpc, {});203+test('The "ipc" option works with "stdio: \'pipe\'"', testIpc, runWithIpc, {stdio: 'pipe'});204+test('The "ipc" option works with "stdio: [\'pipe\', \'pipe\', \'pipe\']"', testIpc, runWithIpc, {stdio: ['pipe', 'pipe', 'pipe']});205+test('The "ipc" option works with "stdio: [\'pipe\', \'pipe\', \'pipe\', \'ipc\']"', testIpc, runWithIpc, {stdio: ['pipe', 'pipe', 'pipe', 'ipc']});206+test('The "ipc" option works with "stdout: \'pipe\'"', testIpc, runWithIpc, {stdout: 'pipe'});207+208+test('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+});212+213+const 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+};219+220+test('Can disable "ipc" - execaNode()', testDisableIpc, execaNode);221+test('Can disable "ipc" - "node" option', testDisableIpc, runWithNodeOption);222+test('Can disable "ipc" - "node" option sync', testDisableIpc, runWithNodeOptionSync);223+224+const NO_IPC_MESSAGE = /The "ipc: true" option cannot be used/;225+226+const testNoIpcSync = (t, node) => {227+ t.throws(() => {228+ execaSync('node', ['send.js'], {ipc: true, node});229+ }, {message: NO_IPC_MESSAGE});230+};231+232+test('Cannot use "ipc: true" with execaSync()', testNoIpcSync, undefined);233+test('Cannot use "ipc: true" with execaSync() - "node: false"', testNoIpcSync, false);234+235+test('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+});240+241+const 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+};246+247+test('Cannot use "shell: true" - execaNode()', testNoShell, execaNode);248+test('Cannot use "shell: true" - "node" option', testNoShell, runWithNodeOption);249+test('Cannot use "shell: true" - "node" option sync', testNoShell, runWithNodeOptionSync);added:test/arguments/options.js+130 added
1+import {delimiter, join, basename} from 'node:path';2+import process from 'node:process';3+import {pathToFileURL, fileURLToPath} from 'node:url';4+import test from 'ava';5+import which from 'which';6+import {execa, $, execaSync, execaNode} from '../../index.js';7+import {setFixtureDir, FIXTURES_DIR_URL, PATH_KEY} from '../helpers/fixtures-dir.js';8+import {identity} from '../helpers/stdio.js';9+10+setFixtureDir();11+process.env.FOO = 'foo';12+13+const isWindows = process.platform === 'win32';14+const ENOENT_REGEXP = isWindows ? /failed with exit code 1/ : /spawn.* ENOENT/;15+16+const 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+};20+21+const BIN_DIR_REGEXP = /node_modules[\\/]\.bin/;22+23+test('preferLocal: true', async t => {24+ await t.notThrowsAsync(execa('ava', ['--version'], {preferLocal: true, env: getPathWithoutLocalDir()}));25+});26+27+test('preferLocal: false', async t => {28+ await t.throwsAsync(execa('ava', ['--version'], {preferLocal: false, env: getPathWithoutLocalDir()}), {message: ENOENT_REGEXP});29+});30+31+test('preferLocal: undefined', async t => {32+ await t.throwsAsync(execa('ava', ['--version'], {env: getPathWithoutLocalDir()}), {message: ENOENT_REGEXP});33+});34+35+test('preferLocal: undefined with $', async t => {36+ await t.notThrowsAsync($({env: getPathWithoutLocalDir()})`ava --version`);37+});38+39+test('preferLocal: undefined with $.sync', t => {40+ t.notThrows(() => $({env: getPathWithoutLocalDir()}).sync`ava --version`);41+});42+43+test('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+});49+50+test('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+});56+57+test('use environment variables by default', async t => {58+ const {stdout} = await execa('environment.js');59+ t.deepEqual(stdout.split('\n'), ['foo', 'undefined']);60+});61+62+test('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+});66+67+test('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+});71+72+test('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+});79+80+test('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+});84+85+const 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+};91+92+test('can use `options.shell: string`', testShellPath, identity);93+test('can use `options.shell: file URL`', testShellPath, pathToFileURL);94+95+const 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+};100+101+test('execa()\'s command argument can be a file URL', testFileUrl, execa);102+test('execaSync()\'s command argument can be a file URL', testFileUrl, execaSync);103+test('execaNode()\'s command argument can be a file URL', testFileUrl, execaNode);104+105+const 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+};111+112+test('execa()\'s command argument cannot be a non-file URL', testInvalidFileUrl, execa);113+test('execaSync()\'s command argument cannot be a non-file URL', testInvalidFileUrl, execaSync);114+test('execaNode()\'s command argument cannot be a non-file URL', testInvalidFileUrl, execaNode);115+116+const testInvalidCommand = async (t, execaMethod) => {117+ t.throws(() => {118+ execaMethod(['command', 'arg']);119+ }, {message: /First argument must be a string or a file URL/});120+};121+122+test('execa()\'s command argument must be a string or file URL', testInvalidCommand, execa);123+test('execaSync()\'s command argument must be a string or file URL', testInvalidCommand, execaSync);124+test('execaNode()\'s command argument must be a string or file URL', testInvalidCommand, execaNode);125+126+test('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
1+import test from 'ava';2+import {execa} from '../../index.js';3+import {setFixtureDir} from '../helpers/fixtures-dir.js';4+5+setFixtureDir();6+7+const normalizeTimestamp = output => output.replaceAll(/\d/g, '0');8+const testTimestamp = '[00:00:00.000]';9+10+test('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+});15+16+test('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+});21+22+test('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+});26+27+test('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\\")"30+one31+${testTimestamp} node -e "console.error(\\"two\\")"32+two`);33+});added:test/exit/cleanup.js+89 added
1+import process from 'node:process';2+import {setTimeout} from 'node:timers/promises';3+import test from 'ava';4+import {pEvent} from 'p-event';5+import isRunning from 'is-running';6+import {execa} from '../../index.js';7+import {setFixtureDir} from '../helpers/fixtures-dir.js';8+9+setFixtureDir();10+11+const isWindows = process.platform === 'win32';12+13+// When child process exits before parent process14+const spawnAndExit = async (t, cleanup, detached) => {15+ await t.notThrowsAsync(execa('nested.js', [JSON.stringify({cleanup, detached}), 'noop.js']));16+};17+18+test('spawnAndExit', spawnAndExit, false, false);19+test('spawnAndExit cleanup', spawnAndExit, true, false);20+test('spawnAndExit detached', spawnAndExit, false, true);21+test('spawnAndExit cleanup detached', spawnAndExit, true, true);22+23+// When parent process exits before child process24+const spawnAndKill = async (t, [signal, cleanup, detached, isKilled]) => {25+ const subprocess = execa('sub-process.js', [cleanup, detached], {stdio: 'ignore', ipc: true});26+27+ const pid = await pEvent(subprocess, 'message');28+ t.true(Number.isInteger(pid));29+ t.true(isRunning(pid));30+31+ process.kill(subprocess.pid, signal);32+33+ await t.throwsAsync(subprocess);34+ t.false(isRunning(subprocess.pid));35+36+ 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+};47+48+const pollForProcessExit = async pid => {49+ while (isRunning(pid)) {50+ // eslint-disable-next-line no-await-in-loop51+ await setTimeout(100);52+ }53+};54+55+// 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 handled61+test('spawnAndKill SIGTERM', spawnAndKill, ['SIGTERM', false, false, isWindows]);62+test('spawnAndKill SIGKILL', spawnAndKill, ['SIGKILL', false, false, isWindows]);63+test('spawnAndKill cleanup SIGTERM', spawnAndKill, ['SIGTERM', true, false, true]);64+test('spawnAndKill cleanup SIGKILL', spawnAndKill, ['SIGKILL', true, false, isWindows]);65+test('spawnAndKill detached SIGTERM', spawnAndKill, ['SIGTERM', false, true, false]);66+test('spawnAndKill detached SIGKILL', spawnAndKill, ['SIGKILL', false, true, false]);67+test('spawnAndKill cleanup detached SIGTERM', spawnAndKill, ['SIGTERM', true, true, false]);68+test('spawnAndKill cleanup detached SIGKILL', spawnAndKill, ['SIGKILL', true, true, false]);69+70+// See #12871+test('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;74+75+ const subprocess = execa('noop.js');76+ const listener = exitListeners.at(-1);77+78+ await subprocess;79+ t.false(exitListeners.includes(listener));80+});81+82+test('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));87+88+ process.kill(pid, 'SIGKILL');89+});added:test/exit/code.js+85 added
1+import process from 'node:process';2+import test from 'ava';3+import {execa} from '../../index.js';4+import {setFixtureDir} from '../helpers/fixtures-dir.js';5+6+const isWindows = process.platform === 'win32';7+8+setFixtureDir();9+10+test('exitCode is 0 on success', async t => {11+ const {exitCode} = await execa('noop.js', ['foo']);12+ t.is(exitCode, 0);13+});14+15+const 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+};24+25+test('exitCode is 2', testExitCode, 2);26+test('exitCode is 3', testExitCode, 3);27+test('exitCode is 4', testExitCode, 4);28+29+if (!isWindows) {30+ test('error.signal is SIGINT', async t => {31+ const subprocess = execa('forever.js');32+33+ process.kill(subprocess.pid, 'SIGINT');34+35+ const {signal} = await t.throwsAsync(subprocess, {message: /was killed with SIGINT/});36+ t.is(signal, 'SIGINT');37+ });38+39+ test('error.signalDescription is defined', async t => {40+ const subprocess = execa('forever.js');41+42+ process.kill(subprocess.pid, 'SIGINT');43+44+ const {signalDescription} = await t.throwsAsync(subprocess, {message: /User interruption with CTRL-C/});45+ t.is(signalDescription, 'User interruption with CTRL-C');46+ });47+48+ test('error.signal is SIGTERM', async t => {49+ const subprocess = execa('forever.js');50+51+ process.kill(subprocess.pid, 'SIGTERM');52+53+ const {signal} = await t.throwsAsync(subprocess, {message: /was killed with SIGTERM/});54+ t.is(signal, 'SIGTERM');55+ });56+57+ 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+ });61+62+ test('exitCode is undefined on signal termination', async t => {63+ const subprocess = execa('forever.js');64+65+ process.kill(subprocess.pid);66+67+ const {exitCode} = await t.throwsAsync(subprocess);68+ t.is(exitCode, undefined);69+ });70+}71+72+test('result.signal is undefined for successful execution', async t => {73+ const {signal} = await execa('noop.js');74+ t.is(signal, undefined);75+});76+77+test('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+});81+82+test('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
1+import process from 'node:process';2+import {once, defaultMaxListeners} from 'node:events';3+import {constants} from 'node:os';4+import {setTimeout, setImmediate} from 'node:timers/promises';5+import test from 'ava';6+import {pEvent} from 'p-event';7+import isRunning from 'is-running';8+import {execa} from '../../index.js';9+import {setFixtureDir} from '../helpers/fixtures-dir.js';10+import {assertMaxListeners} from '../helpers/listeners.js';11+12+setFixtureDir();13+14+const isWindows = process.platform === 'win32';15+16+const 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+};25+26+const spawnNoKillableSimple = options => execa('forever.js', {killSignal: 'SIGWINCH', forceKillAfterDelay: 1, ...options});27+28+const spawnNoKillableOutput = options => execa('noop-forever.js', ['.'], {killSignal: 'SIGWINCH', forceKillAfterDelay: 1, ...options});29+30+test('kill("SIGKILL") should terminate cleanly', async t => {31+ const {subprocess} = await spawnNoKillable();32+33+ subprocess.kill('SIGKILL');34+35+ const {isTerminated, signal} = await t.throwsAsync(subprocess);36+ t.true(isTerminated);37+ t.is(signal, 'SIGKILL');38+});39+40+const testInvalidForceKill = async (t, forceKillAfterDelay) => {41+ t.throws(() => {42+ execa('empty.js', {forceKillAfterDelay});43+ }, {instanceOf: TypeError, message: /non-negative integer/});44+};45+46+test('`forceKillAfterDelay` should not be NaN', testInvalidForceKill, Number.NaN);47+test('`forceKillAfterDelay` should not be negative', testInvalidForceKill, -1);48+49+// `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.51+if (isWindows) {52+ test('Can call `.kill()` with `forceKillAfterDelay` on Windows', async t => {53+ const {subprocess} = await spawnNoKillable(1);54+ subprocess.kill();55+56+ 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);63+64+ subprocess.kill(killArgument);65+66+ await setTimeout(6e3);67+ t.true(isRunning(subprocess.pid));68+ subprocess.kill('SIGKILL');69+70+ const {isTerminated, signal} = await t.throwsAsync(subprocess);71+ t.true(isTerminated);72+ t.is(signal, 'SIGKILL');73+ };74+75+ 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});79+80+ const testForceKill = async (t, forceKillAfterDelay, killArgument, options) => {81+ const {subprocess} = await spawnNoKillable(forceKillAfterDelay, options);82+83+ subprocess.kill(killArgument);84+85+ const {isTerminated, signal} = await t.throwsAsync(subprocess);86+ t.true(isTerminated);87+ t.is(signal, 'SIGKILL');88+ };89+90+ 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'});98+99+ 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+ });109+110+ 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+ });117+118+ 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+ });124+125+ test.serial('Can call `.kill()` with `forceKillAfterDelay` many times without triggering the maxListeners warning', async t => {126+ const checkMaxListeners = assertMaxListeners(t);127+128+ const subprocess = spawnNoKillableSimple();129+ for (let index = 0; index < defaultMaxListeners + 1; index += 1) {130+ subprocess.kill();131+ }132+133+ const {isTerminated, signal} = await t.throwsAsync(subprocess);134+ t.true(isTerminated);135+ t.is(signal, 'SIGKILL');136+137+ checkMaxListeners();138+ });139+140+ test('Can call `.kill()` with `forceKillAfterDelay` multiple times', async t => {141+ const subprocess = spawnNoKillableSimple();142+ subprocess.kill();143+ subprocess.kill();144+145+ const {isTerminated, signal} = await t.throwsAsync(subprocess);146+ t.true(isTerminated);147+ t.is(signal, 'SIGKILL');148+ });149+}150+151+test('Can call `.kill()` multiple times', async t => {152+ const subprocess = execa('forever.js');153+ subprocess.kill();154+ subprocess.kill();155+156+ const {isTerminated, signal} = await t.throwsAsync(subprocess);157+ t.true(isTerminated);158+ t.is(signal, 'SIGTERM');159+});160+161+test('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+});166+167+const 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+};177+178+test('Cannot call .kill(null)', testInvalidKillArgument, null);179+test('Cannot call .kill(0n)', testInvalidKillArgument, 0n);180+test('Cannot call .kill(true)', testInvalidKillArgument, true);181+test('Cannot call .kill(errorObject)', testInvalidKillArgument, {name: '', message: '', stack: ''});182+test('Cannot call .kill([error])', testInvalidKillArgument, [new Error('test')]);183+test('Cannot call .kill(undefined, true)', testInvalidKillArgument, undefined, true);184+test('Cannot call .kill("SIGTERM", true)', testInvalidKillArgument, 'SIGTERM', true);185+test('Cannot call .kill(true, error)', testInvalidKillArgument, true, new Error('test'));186+187+test('.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+});201+202+test('.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+});209+210+test('.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+});217+218+test('.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+});224+225+test('.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+});238+239+test('.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+});248+249+test('.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+});255+256+test('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+});267+268+test('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+});280+281+test('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+});295+296+test('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
1+import {once} from 'node:events';2+import test from 'ava';3+import {execa, execaSync} from '../../index.js';4+import {setFixtureDir} from '../helpers/fixtures-dir.js';5+6+setFixtureDir();7+8+test('result.isCanceled is false when abort isn\'t called (success)', async t => {9+ const {isCanceled} = await execa('noop.js');10+ t.false(isCanceled);11+});12+13+test('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+});17+18+test('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+});22+23+test('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+});29+30+test('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+});37+38+test('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+});45+46+test('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+});55+56+test('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+});62+63+test('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+});71+72+test('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
1+import test from 'ava';2+import {execa, execaSync} from '../../index.js';3+import {setFixtureDir, FIXTURES_DIR} from '../helpers/fixtures-dir.js';4+5+setFixtureDir();6+7+test('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+});16+17+test('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+});28+29+test('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+});33+34+test('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+});40+41+const INVALID_TIMEOUT_REGEXP = /`timeout` option to be a non-negative integer/;42+43+const testTimeoutValidation = (t, timeout, execaMethod) => {44+ t.throws(() => {45+ execaMethod('empty.js', {timeout});46+ }, {message: INVALID_TIMEOUT_REGEXP});47+};48+49+test('timeout must not be negative', testTimeoutValidation, -1, execa);50+test('timeout must be an integer', testTimeoutValidation, false, execa);51+test('timeout must not be negative - sync', testTimeoutValidation, -1, execaSync);52+test('timeout must be an integer - sync', testTimeoutValidation, false, execaSync);53+54+test('timedOut is false if timeout is undefined', async t => {55+ const {timedOut} = await execa('noop.js');56+ t.false(timedOut);57+});58+59+test('timedOut is false if timeout is 0', async t => {60+ const {timedOut} = await execa('noop.js', {timeout: 0});61+ t.false(timedOut);62+});63+64+test('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+});68+69+test('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
1+import test from 'ava';2+import {execa} from '../../index.js';3+import {setFixtureDir} from '../helpers/fixtures-dir.js';4+import {foobarString} from '../helpers/input.js';5+6+setFixtureDir();7+8+const 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+};16+17+test('error instance can be null', testUnusualError, null);18+test('error instance can be false', testUnusualError, false);19+test('error instance can be a string', testUnusualError, 'test');20+test('error instance can be a number', testUnusualError, 0);21+test('error instance can be a BigInt', testUnusualError, 0n);22+test('error instance can be a symbol', testUnusualError, Symbol('test'));23+test('error instance can be a function', testUnusualError, () => {});24+test('error instance can be an array', testUnusualError, ['test', 'test']);25+// eslint-disable-next-line unicorn/error-message26+test('error instance can be an error with an empty message', testUnusualError, new Error(''), '');27+test('error instance can be undefined', testUnusualError, undefined, '');28+29+test('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+});34+35+const runAndFail = (t, fixtureName, argument, error) => {36+ const childProcess = execa(fixtureName, [argument]);37+ childProcess.emit('error', error);38+ return t.throwsAsync(childProcess);39+};40+41+const runAndClone = async (t, initialError) => {42+ const previousError = await runAndFail(t, 'empty.js', 'foo', initialError);43+ t.is(previousError, initialError);44+45+ return runAndFail(t, 'empty.js', 'bar', previousError);46+};47+48+const testErrorCopy = async (t, getPreviousArgument, argument = 'two') => {49+ const fixtureName = 'empty.js';50+ const firstArgument = 'foo';51+52+ 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}`;56+57+ 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+};65+66+test('error instance can be shared', testErrorCopy, () => new Error(foobarString));67+test('error TypeError can be shared', testErrorCopy, () => new TypeError(foobarString));68+test('error string can be shared', testErrorCopy, () => foobarString);69+test('error copy can be shared', testErrorCopy, (t, fixtureName) => runAndFail(t, fixtureName, 'bar', new Error(foobarString)));70+test('error with same message can be shared', testErrorCopy, () => new Error(foobarString), 'foo');71+72+const testErrorCopyProperty = async (t, propertyName, isCopied) => {73+ const propertyValue = 'test';74+ const initialError = new Error(foobarString);75+ initialError[propertyName] = propertyValue;76+77+ const error = await runAndClone(t, initialError);78+ t.is(error[propertyName] === propertyValue, isCopied);79+};80+81+test('error.code can be copied', testErrorCopyProperty, 'code', true);82+test('error.errno can be copied', testErrorCopyProperty, 'errno', true);83+test('error.syscall can be copied', testErrorCopyProperty, 'syscall', true);84+test('error.path can be copied', testErrorCopyProperty, 'path', true);85+test('error.dest can be copied', testErrorCopyProperty, 'dest', true);86+test('error.address can be copied', testErrorCopyProperty, 'address', true);87+test('error.port can be copied', testErrorCopyProperty, 'port', true);88+test('error.info can be copied', testErrorCopyProperty, 'info', true);89+test('error.other cannot be copied', testErrorCopyProperty, 'other', false);90+91+test('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+});96+97+test('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+});102+103+test('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+});108+109+test('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');113+114+ const newMessage = 'newTest';115+ error.message = newMessage;116+ t.false(error.stack.includes(newMessage));117+ error.message = message;118+119+ 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+});125+126+test('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+});133+134+test('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');138+139+ const childProcess = execa('empty.js');140+ childProcess.emit('error', error);141+ t.is(await t.throwsAsync(childProcess), error);142+143+ 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
1+import process from 'node:process';2+import test from 'ava';3+import {execa, execaSync} from '../../index.js';4+import {setFixtureDir} from '../helpers/fixtures-dir.js';5+6+setFixtureDir();7+8+const isWindows = process.platform === 'win32';9+const ENOENT_REGEXP = isWindows ? /failed with exit code 1/ : /spawn.* ENOENT/;10+11+test('execaSync() throws error if ENOENT', t => {12+ t.throws(() => {13+ execaSync('foo');14+ }, {message: ENOENT_REGEXP});15+});16+17+const testEarlyErrorShape = async (t, reject) => {18+ const subprocess = execa('', {reject});19+ t.notThrows(() => {20+ subprocess.catch(() => {});21+ subprocess.unref();22+ subprocess.on('error', () => {});23+ });24+};25+26+test('child_process.spawn() early errors have correct shape', testEarlyErrorShape, true);27+test('child_process.spawn() early errors have correct shape - reject false', testEarlyErrorShape, false);28+29+test('child_process.spawn() early errors are propagated', async t => {30+ const {failed} = await t.throwsAsync(execa(''));31+ t.true(failed);32+});33+34+test('child_process.spawn() early errors are returned', async t => {35+ const {failed} = await execa('', {reject: false});36+ t.true(failed);37+});38+39+test('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+});45+46+test('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+});50+51+if (!isWindows) {52+ test('execa() rejects if running non-executable', async t => {53+ await t.throwsAsync(execa('non-executable.js'));54+ });55+56+ 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+ });59+60+ 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
1+import process from 'node:process';2+import test from 'ava';3+import {execa, execaSync} from '../../index.js';4+import {setFixtureDir} from '../helpers/fixtures-dir.js';5+import {fullStdio, getStdio} from '../helpers/stdio.js';6+import {noopGenerator, outputObjectGenerator} from '../helpers/generator.js';7+8+const isWindows = process.platform === 'win32';9+10+setFixtureDir();11+12+test('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+});30+31+test('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+});55+56+test('error.message contains the command', async t => {57+ await t.throwsAsync(execa('exit.js', ['2', 'foo', 'bar']), {message: /exit.js 2 foo bar/});58+});59+60+const 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+};65+66+test('error.message contains stdout/stderr/stdio if available', testStdioMessage, 'utf8', false, false);67+test('error.message contains stdout/stderr/stdio even with encoding "buffer"', testStdioMessage, 'buffer', false, false);68+test('error.message contains all if available', testStdioMessage, 'utf8', true, false);69+test('error.message contains all even with encoding "buffer"', testStdioMessage, 'buffer', true, false);70+test('error.message contains stdout/stderr/stdio if available, objectMode', testStdioMessage, 'utf8', false, true);71+test('error.message contains stdout/stderr/stdio even with encoding "buffer", objectMode', testStdioMessage, 'buffer', false, true);72+test('error.message contains all if available, objectMode', testStdioMessage, 'utf8', true, true);73+test('error.message contains all even with encoding "buffer", objectMode', testStdioMessage, 'buffer', true, true);74+75+const 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+};79+80+test('error.message does not contain stdout if not available', testPartialIgnoreMessage, 1, 'ignore', 'stderr');81+test('error.message does not contain stderr if not available', testPartialIgnoreMessage, 2, 'ignore', 'stdout');82+test('error.message does not contain stdout if it is an object', testPartialIgnoreMessage, 1, outputObjectGenerator, 'stderr');83+test('error.message does not contain stderr if it is an object', testPartialIgnoreMessage, 2, outputObjectGenerator, 'stdout');84+85+const 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+};91+92+test('error.message does not contain stdout/stderr/stdio if not available', testFullIgnoreMessage, {stdio: 'ignore'}, 'message');93+test('error.shortMessage does not contain stdout/stderr/stdio', testFullIgnoreMessage, fullStdio, 'shortMessage');94+95+const 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+};99+100+test('error.message newlines are consistent - no newline', testErrorMessageConsistent, 'stdout');101+test('error.message newlines are consistent - newline', testErrorMessageConsistent, 'stdout\n');102+103+test('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+});107+108+test('failed is false on success', async t => {109+ const {failed} = await execa('noop.js', ['foo']);110+ t.false(failed);111+});112+113+test('failed is true on failure', async t => {114+ const {failed} = await t.throwsAsync(execa('fail.js'));115+ t.true(failed);116+});117+118+test('error.isTerminated is true if process was killed directly', async t => {119+ const subprocess = execa('forever.js', {killSignal: 'SIGINT'});120+121+ subprocess.kill();122+123+ 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+});130+131+test('error.isTerminated is true if process was killed indirectly', async t => {132+ const subprocess = execa('forever.js', {killSignal: 'SIGHUP'});133+134+ process.kill(subprocess.pid, 'SIGINT');135+136+ // `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+});147+148+test('result.isTerminated is false if not killed', async t => {149+ const {isTerminated} = await execa('noop.js');150+ t.false(isTerminated);151+});152+153+test('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+});160+161+test('result.isTerminated is false if not killed, in sync mode', t => {162+ const {isTerminated} = execaSync('noop.js');163+ t.false(isTerminated);164+});165+166+test('result.isTerminated is false on process error', async t => {167+ const {isTerminated} = await t.throwsAsync(execa('wrong command'));168+ t.false(isTerminated);169+});170+171+test('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+});177+178+test('error.code is undefined on success', async t => {179+ const {code} = await execa('noop.js');180+ t.is(code, undefined);181+});182+183+test('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
1+import test from 'ava';2+import {execa, execaSync} from '../../index.js';3+import {setFixtureDir} from '../helpers/fixtures-dir.js';4+import {fullStdio, getStdio} from '../helpers/stdio.js';5+import {noopGenerator} from '../helpers/generator.js';6+7+setFixtureDir();8+9+const testOutput = async (t, index, execaMethod) => {10+ const {stdout, stderr, stdio} = await execaMethod('noop-fd.js', [`${index}`, 'foobar'], fullStdio);11+ t.is(stdio[index], 'foobar');12+13+ if (index === 1) {14+ t.is(stdio[index], stdout);15+ } else if (index === 2) {16+ t.is(stdio[index], stderr);17+ }18+};19+20+test('can return stdout', testOutput, 1, execa);21+test('can return stderr', testOutput, 2, execa);22+test('can return output stdio[*]', testOutput, 3, execa);23+test('can return stdout - sync', testOutput, 1, execaSync);24+test('can return stderr - sync', testOutput, 2, execaSync);25+test('can return output stdio[*] - sync', testOutput, 3, execaSync);26+27+const testNoStdin = async (t, execaMethod) => {28+ const {stdio} = await execaMethod('noop.js', ['foobar']);29+ t.is(stdio[0], undefined);30+};31+32+test('cannot return stdin', testNoStdin, execa);33+test('cannot return stdin - sync', testNoStdin, execaSync);34+35+test('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+});39+40+test('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+});47+48+const 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+};55+56+test('empty error.stdout/stderr/stdio', testEmptyErrorStdio, execa);57+test('empty error.stdout/stderr/stdio - sync', testEmptyErrorStdio, execaSync);58+59+const 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+};65+66+test('undefined error.stdout/stderr/stdio', testUndefinedErrorStdio, execa);67+test('undefined error.stdout/stderr/stdio - sync', testUndefinedErrorStdio, execaSync);68+69+const testEmptyAll = async (t, options, expectedValue) => {70+ const {all} = await t.throwsAsync(execa('fail.js', options));71+ t.is(all, expectedValue);72+};73+74+test('empty error.all', testEmptyAll, {all: true}, '');75+test('undefined error.all', testEmptyAll, {}, undefined);76+test('ignored error.all', testEmptyAll, {all: true, stdio: 'ignore'}, undefined);77+78+test('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+});82+83+// `error.code` is OS-specific here84+const SPAWN_ERROR_CODES = new Set(['EINVAL', 'ENOTSUP', 'EPERM']);85+86+test('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+});93+94+test('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+});103+104+const 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+};111+112+test('error.stdout/stderr/stdio is defined', testErrorOutput, execa);113+test('error.stdout/stderr/stdio is defined - sync', testErrorOutput, execaSync);114+115+const 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+};119+120+test('stripFinalNewline: undefined with stdout', testStripFinalNewline, 1, undefined, execa);121+test('stripFinalNewline: true with stdout', testStripFinalNewline, 1, true, execa);122+test('stripFinalNewline: false with stdout', testStripFinalNewline, 1, false, execa);123+test('stripFinalNewline: undefined with stderr', testStripFinalNewline, 2, undefined, execa);124+test('stripFinalNewline: true with stderr', testStripFinalNewline, 2, true, execa);125+test('stripFinalNewline: false with stderr', testStripFinalNewline, 2, false, execa);126+test('stripFinalNewline: undefined with stdio[*]', testStripFinalNewline, 3, undefined, execa);127+test('stripFinalNewline: true with stdio[*]', testStripFinalNewline, 3, true, execa);128+test('stripFinalNewline: false with stdio[*]', testStripFinalNewline, 3, false, execa);129+test('stripFinalNewline: undefined with stdout - sync', testStripFinalNewline, 1, undefined, execaSync);130+test('stripFinalNewline: true with stdout - sync', testStripFinalNewline, 1, true, execaSync);131+test('stripFinalNewline: false with stdout - sync', testStripFinalNewline, 1, false, execaSync);132+test('stripFinalNewline: undefined with stderr - sync', testStripFinalNewline, 2, undefined, execaSync);133+test('stripFinalNewline: true with stderr - sync', testStripFinalNewline, 2, true, execaSync);134+test('stripFinalNewline: false with stderr - sync', testStripFinalNewline, 2, false, execaSync);135+test('stripFinalNewline: undefined with stdio[*] - sync', testStripFinalNewline, 3, undefined, execaSync);136+test('stripFinalNewline: true with stdio[*] - sync', testStripFinalNewline, 3, true, execaSync);137+test('stripFinalNewline: false with stdio[*] - sync', testStripFinalNewline, 3, false, execaSync);138+139+test('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
1-import {readFile, writeFile, rm} from 'node:fs/promises';2-import process from 'node:process';3-import test from 'ava';4-import tempfile from 'tempfile';5-import {execa, execaSync} from '../../index.js';6-import {fullStdio, getStdio, STANDARD_STREAMS} from '../helpers/stdio.js';7-import {setFixtureDir} from '../helpers/fixtures-dir.js';8-9-setFixtureDir();10-11-const 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-};16-17-test('Cannot pass an empty array to stdin', testEmptyArray, 0, 'stdin', execa);18-test('Cannot pass an empty array to stdout', testEmptyArray, 1, 'stdout', execa);19-test('Cannot pass an empty array to stderr', testEmptyArray, 2, 'stderr', execa);20-test('Cannot pass an empty array to stdio[*]', testEmptyArray, 3, 'stdio[3]', execa);21-test('Cannot pass an empty array to stdin - sync', testEmptyArray, 0, 'stdin', execaSync);22-test('Cannot pass an empty array to stdout - sync', testEmptyArray, 1, 'stdout', execaSync);23-test('Cannot pass an empty array to stderr - sync', testEmptyArray, 2, 'stderr', execaSync);24-test('Cannot pass an empty array to stdio[*] - sync', testEmptyArray, 3, 'stdio[3]', execaSync);25-26-const 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-};31-32-test('stdin can be "ignore"', testNoPipeOption, 'ignore', 0);33-test('stdin can be ["ignore"]', testNoPipeOption, ['ignore'], 0);34-test('stdin can be ["ignore", "ignore"]', testNoPipeOption, ['ignore', 'ignore'], 0);35-test('stdin can be "ipc"', testNoPipeOption, 'ipc', 0);36-test('stdin can be ["ipc"]', testNoPipeOption, ['ipc'], 0);37-test('stdin can be "inherit"', testNoPipeOption, 'inherit', 0);38-test('stdin can be ["inherit"]', testNoPipeOption, ['inherit'], 0);39-test('stdin can be 0', testNoPipeOption, 0, 0);40-test('stdin can be [0]', testNoPipeOption, [0], 0);41-test('stdout can be "ignore"', testNoPipeOption, 'ignore', 1);42-test('stdout can be ["ignore"]', testNoPipeOption, ['ignore'], 1);43-test('stdout can be ["ignore", "ignore"]', testNoPipeOption, ['ignore', 'ignore'], 1);44-test('stdout can be "ipc"', testNoPipeOption, 'ipc', 1);45-test('stdout can be ["ipc"]', testNoPipeOption, ['ipc'], 1);46-test('stdout can be "inherit"', testNoPipeOption, 'inherit', 1);47-test('stdout can be ["inherit"]', testNoPipeOption, ['inherit'], 1);48-test('stdout can be 1', testNoPipeOption, 1, 1);49-test('stdout can be [1]', testNoPipeOption, [1], 1);50-test('stderr can be "ignore"', testNoPipeOption, 'ignore', 2);51-test('stderr can be ["ignore"]', testNoPipeOption, ['ignore'], 2);52-test('stderr can be ["ignore", "ignore"]', testNoPipeOption, ['ignore', 'ignore'], 2);53-test('stderr can be "ipc"', testNoPipeOption, 'ipc', 2);54-test('stderr can be ["ipc"]', testNoPipeOption, ['ipc'], 2);55-test('stderr can be "inherit"', testNoPipeOption, 'inherit', 2);56-test('stderr can be ["inherit"]', testNoPipeOption, ['inherit'], 2);57-test('stderr can be 2', testNoPipeOption, 2, 2);58-test('stderr can be [2]', testNoPipeOption, [2], 2);59-test('stdio[*] can be "ignore"', testNoPipeOption, 'ignore', 3);60-test('stdio[*] can be ["ignore"]', testNoPipeOption, ['ignore'], 3);61-test('stdio[*] can be ["ignore", "ignore"]', testNoPipeOption, ['ignore', 'ignore'], 3);62-test('stdio[*] can be "ipc"', testNoPipeOption, 'ipc', 3);63-test('stdio[*] can be ["ipc"]', testNoPipeOption, ['ipc'], 3);64-test('stdio[*] can be "inherit"', testNoPipeOption, 'inherit', 3);65-test('stdio[*] can be ["inherit"]', testNoPipeOption, ['inherit'], 3);66-test('stdio[*] can be 3', testNoPipeOption, 3, 3);67-test('stdio[*] can be [3]', testNoPipeOption, [3], 3);68-69-const testInvalidArrayValue = (t, invalidStdio, index, execaMethod) => {70- t.throws(() => {71- execaMethod('empty.js', getStdio(index, ['pipe', invalidStdio]));72- }, {message: /must not include/});73-};74-75-test('Cannot pass "ignore" and another value to stdin', testInvalidArrayValue, 'ignore', 0, execa);76-test('Cannot pass "ignore" and another value to stdout', testInvalidArrayValue, 'ignore', 1, execa);77-test('Cannot pass "ignore" and another value to stderr', testInvalidArrayValue, 'ignore', 2, execa);78-test('Cannot pass "ignore" and another value to stdio[*]', testInvalidArrayValue, 'ignore', 3, execa);79-test('Cannot pass "ignore" and another value to stdin - sync', testInvalidArrayValue, 'ignore', 0, execaSync);80-test('Cannot pass "ignore" and another value to stdout - sync', testInvalidArrayValue, 'ignore', 1, execaSync);81-test('Cannot pass "ignore" and another value to stderr - sync', testInvalidArrayValue, 'ignore', 2, execaSync);82-test('Cannot pass "ignore" and another value to stdio[*] - sync', testInvalidArrayValue, 'ignore', 3, execaSync);83-test('Cannot pass "ipc" and another value to stdin', testInvalidArrayValue, 'ipc', 0, execa);84-test('Cannot pass "ipc" and another value to stdout', testInvalidArrayValue, 'ipc', 1, execa);85-test('Cannot pass "ipc" and another value to stderr', testInvalidArrayValue, 'ipc', 2, execa);86-test('Cannot pass "ipc" and another value to stdio[*]', testInvalidArrayValue, 'ipc', 3, execa);87-test('Cannot pass "ipc" and another value to stdin - sync', testInvalidArrayValue, 'ipc', 0, execaSync);88-test('Cannot pass "ipc" and another value to stdout - sync', testInvalidArrayValue, 'ipc', 1, execaSync);89-test('Cannot pass "ipc" and another value to stderr - sync', testInvalidArrayValue, 'ipc', 2, execaSync);90-test('Cannot pass "ipc" and another value to stdio[*] - sync', testInvalidArrayValue, 'ipc', 3, execaSync);91-92-const testInputOutput = (t, stdioOption, execaMethod) => {93- t.throws(() => {94- execaMethod('empty.js', getStdio(3, [new ReadableStream(), stdioOption]));95- }, {message: /readable and writable/});96-};97-98-test('Cannot pass both readable and writable values to stdio[*] - WritableStream', testInputOutput, new WritableStream(), execa);99-test('Cannot pass both readable and writable values to stdio[*] - 1', testInputOutput, 1, execa);100-test('Cannot pass both readable and writable values to stdio[*] - 2', testInputOutput, 2, execa);101-test('Cannot pass both readable and writable values to stdio[*] - process.stdout', testInputOutput, process.stdout, execa);102-test('Cannot pass both readable and writable values to stdio[*] - process.stderr', testInputOutput, process.stderr, execa);103-test('Cannot pass both readable and writable values to stdio[*] - WritableStream - sync', testInputOutput, new WritableStream(), execaSync);104-test('Cannot pass both readable and writable values to stdio[*] - 1 - sync', testInputOutput, 1, execaSync);105-test('Cannot pass both readable and writable values to stdio[*] - 2 - sync', testInputOutput, 2, execaSync);106-test('Cannot pass both readable and writable values to stdio[*] - process.stdout - sync', testInputOutput, process.stdout, execaSync);107-test('Cannot pass both readable and writable values to stdio[*] - process.stderr - sync', testInputOutput, process.stderr, execaSync);108-109-const 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-};118-119-test('stdio[*] default direction is output', testAmbiguousDirection, execa);120-test('stdio[*] default direction is output - sync', testAmbiguousDirection, execaSync);121-122-const 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-};129-130-test('stdin ambiguous direction is influenced by other values', testAmbiguousMultiple, 0);131-test('stdio[*] ambiguous direction is influenced by other values', testAmbiguousMultiple, 3);132-133-const 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-};141-142-const isStderrDescriptor = stdioOption => stdioOption === 2143- || stdioOption === 'stderr'144- || (Array.isArray(stdioOption) && isStderrDescriptor(stdioOption[0]));145-146-test.serial('stdio[*] can be 0', testRedirect, 0, 3, true);147-test.serial('stdio[*] can be [0]', testRedirect, [0], 3, true);148-test.serial('stdio[*] can be [0, "pipe"]', testRedirect, [0, 'pipe'], 3, true);149-test.serial('stdio[*] can be process.stdin', testRedirect, 'stdin', 3, true);150-test.serial('stdio[*] can be [process.stdin]', testRedirect, ['stdin'], 3, true);151-test.serial('stdio[*] can be [process.stdin, "pipe"]', testRedirect, ['stdin', 'pipe'], 3, true);152-test('stdout can be 2', testRedirect, 2, 1, false);153-test('stdout can be [2]', testRedirect, [2], 1, false);154-test('stdout can be [2, "pipe"]', testRedirect, [2, 'pipe'], 1, false);155-test('stdout can be process.stderr', testRedirect, 'stderr', 1, false);156-test('stdout can be [process.stderr]', testRedirect, ['stderr'], 1, false);157-test('stdout can be [process.stderr, "pipe"]', testRedirect, ['stderr', 'pipe'], 1, false);158-test('stderr can be 1', testRedirect, 1, 2, false);159-test('stderr can be [1]', testRedirect, [1], 2, false);160-test('stderr can be [1, "pipe"]', testRedirect, [1, 'pipe'], 2, false);161-test('stderr can be process.stdout', testRedirect, 'stdout', 2, false);162-test('stderr can be [process.stdout]', testRedirect, ['stdout'], 2, false);163-test('stderr can be [process.stdout, "pipe"]', testRedirect, ['stdout', 'pipe'], 2, false);164-test('stdio[*] can be 1', testRedirect, 1, 3, false);165-test('stdio[*] can be [1]', testRedirect, [1], 3, false);166-test('stdio[*] can be [1, "pipe"]', testRedirect, [1, 'pipe'], 3, false);167-test('stdio[*] can be 2', testRedirect, 2, 3, false);168-test('stdio[*] can be [2]', testRedirect, [2], 3, false);169-test('stdio[*] can be [2, "pipe"]', testRedirect, [2, 'pipe'], 3, false);170-test('stdio[*] can be process.stdout', testRedirect, 'stdout', 3, false);171-test('stdio[*] can be [process.stdout]', testRedirect, ['stdout'], 3, false);172-test('stdio[*] can be [process.stdout, "pipe"]', testRedirect, ['stdout', 'pipe'], 3, false);173-test('stdio[*] can be process.stderr', testRedirect, 'stderr', 3, false);174-test('stdio[*] can be [process.stderr]', testRedirect, ['stderr'], 3, false);175-test('stdio[*] can be [process.stderr, "pipe"]', testRedirect, ['stderr', 'pipe'], 3, false);176-177-const testInheritStdin = async (t, stdin) => {178- const {stdout} = await execa('nested-multiple-stdin.js', [JSON.stringify(stdin)], {input: 'foobar'});179- t.is(stdout, 'foobarfoobar');180-};181-182-test('stdin can be ["inherit", "pipe"]', testInheritStdin, ['inherit', 'pipe']);183-test('stdin can be [0, "pipe"]', testInheritStdin, [0, 'pipe']);184-185-const 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-};190-191-test('stdout can be ["inherit", "pipe"]', testInheritStdout, ['inherit', 'pipe']);192-test('stdout can be [1, "pipe"]', testInheritStdout, [1, 'pipe']);193-194-const 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-};199-200-test('stderr can be ["inherit", "pipe"]', testInheritStderr, ['inherit', 'pipe']);201-test('stderr can be [2, "pipe"]', testInheritStderr, [2, 'pipe']);202-203-const 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-};207-208-if (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-}218-219-test('stdio[*] can use "inherit"', testOverflowStream, 3, 'inherit');220-test('stdio[*] can use ["inherit"]', testOverflowStream, 3, ['inherit']);221-222-const testOverflowStreamArray = (t, index, stdioOption) => {223- t.throws(() => {224- execa('empty.js', getStdio(index, stdioOption));225- }, {message: /no such standard stream/});226-};227-228-test('stdin cannot use 4+ and another value', testOverflowStreamArray, 0, [4, 'pipe']);229-test('stdout cannot use 4+ and another value', testOverflowStreamArray, 1, [4, 'pipe']);230-test('stderr cannot use 4+ and another value', testOverflowStreamArray, 2, [4, 'pipe']);231-test('stdio[*] cannot use 4+ and another value', testOverflowStreamArray, 3, [4, 'pipe']);232-test('stdio[*] cannot use "inherit" and another value', testOverflowStreamArray, 3, ['inherit', 'pipe']);233-234-const testOverlapped = async (t, index) => {235- const {stdout} = await execa('noop.js', ['foobar'], getStdio(index, ['overlapped', 'pipe']));236- t.is(stdout, 'foobar');237-};238-239-test('stdin can be ["overlapped", "pipe"]', testOverlapped, 0);240-test('stdout can be ["overlapped", "pipe"]', testOverlapped, 1);241-test('stderr can be ["overlapped", "pipe"]', testOverlapped, 2);242-test('stdio[*] can be ["overlapped", "pipe"]', testOverlapped, 3);243-244-const 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-};249-250-test('Does not destroy process.stdin on child process errors', testDestroyStandard, 0);251-test('Does not destroy process.stdout on child process errors', testDestroyStandard, 1);252-test('Does not destroy process.stderr on child process errors', testDestroyStandard, 2);253-254-const 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-};258-259-test('Does not destroy process.stdin on spawn process errors', testDestroyStandardSpawn, 0);260-test('Does not destroy process.stdout on spawn process errors', testDestroyStandardSpawn, 1);261-test('Does not destroy process.stderr on spawn process errors', testDestroyStandardSpawn, 2);262-263-const 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-};272-273-test('Does not destroy process.stdin on stream process errors', testDestroyStandardStream, 0);274-test('Does not destroy process.stdout on stream process errors', testDestroyStandardStream, 1);275-test('Does not destroy process.stderr on stream process errors', testDestroyStandardStream, 2);added:test/stdio/direction.js+50 added
1+import {readFile, writeFile, rm} from 'node:fs/promises';2+import process from 'node:process';3+import test from 'ava';4+import tempfile from 'tempfile';5+import {execa, execaSync} from '../../index.js';6+import {getStdio} from '../helpers/stdio.js';7+import {setFixtureDir} from '../helpers/fixtures-dir.js';8+9+setFixtureDir();10+11+const testInputOutput = (t, stdioOption, execaMethod) => {12+ t.throws(() => {13+ execaMethod('empty.js', getStdio(3, [new ReadableStream(), stdioOption]));14+ }, {message: /readable and writable/});15+};16+17+test('Cannot pass both readable and writable values to stdio[*] - WritableStream', testInputOutput, new WritableStream(), execa);18+test('Cannot pass both readable and writable values to stdio[*] - 1', testInputOutput, 1, execa);19+test('Cannot pass both readable and writable values to stdio[*] - 2', testInputOutput, 2, execa);20+test('Cannot pass both readable and writable values to stdio[*] - process.stdout', testInputOutput, process.stdout, execa);21+test('Cannot pass both readable and writable values to stdio[*] - process.stderr', testInputOutput, process.stderr, execa);22+test('Cannot pass both readable and writable values to stdio[*] - WritableStream - sync', testInputOutput, new WritableStream(), execaSync);23+test('Cannot pass both readable and writable values to stdio[*] - 1 - sync', testInputOutput, 1, execaSync);24+test('Cannot pass both readable and writable values to stdio[*] - 2 - sync', testInputOutput, 2, execaSync);25+test('Cannot pass both readable and writable values to stdio[*] - process.stdout - sync', testInputOutput, process.stdout, execaSync);26+test('Cannot pass both readable and writable values to stdio[*] - process.stderr - sync', testInputOutput, process.stderr, execaSync);27+28+const 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+};37+38+test('stdio[*] default direction is output', testAmbiguousDirection, execa);39+test('stdio[*] default direction is output - sync', testAmbiguousDirection, execaSync);40+41+const 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+};48+49+test('stdin ambiguous direction is influenced by other values', testAmbiguousMultiple, 0);50+test('stdio[*] ambiguous direction is influenced by other values', testAmbiguousMultiple, 3);added:test/stdio/encoding-end.js+196 added
1+import {Buffer} from 'node:buffer';2+import {exec} from 'node:child_process';3+import process from 'node:process';4+import {promisify} from 'node:util';5+import test from 'ava';6+import getStream, {getStreamAsBuffer} from 'get-stream';7+import {execa, execaSync} from '../../index.js';8+import {setFixtureDir, FIXTURES_DIR} from '../helpers/fixtures-dir.js';9+import {fullStdio} from '../helpers/stdio.js';10+import {outputObjectGenerator, getChunksGenerator} from '../helpers/generator.js';11+import {foobarObject} from '../helpers/input.js';12+13+const pExec = promisify(exec);14+15+setFixtureDir();16+17+const 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);20+21+ 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+ }28+29+ if (index === 3) {30+ return;31+ }32+33+ 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+};36+37+const 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+};45+46+// This string gives different outputs with each encoding type47+const STRING_TO_ENCODE = '\u1000.';48+const BUFFER_TO_ENCODE = Buffer.from(STRING_TO_ENCODE);49+50+/* eslint-disable unicorn/text-encoding-identifier-case */51+test('can pass encoding "buffer" to stdout', checkEncoding, 'buffer', 1, execa);52+test('can pass encoding "utf8" to stdout', checkEncoding, 'utf8', 1, execa);53+test('can pass encoding "utf-8" to stdout', checkEncoding, 'utf-8', 1, execa);54+test('can pass encoding "utf16le" to stdout', checkEncoding, 'utf16le', 1, execa);55+test('can pass encoding "utf-16le" to stdout', checkEncoding, 'utf-16le', 1, execa);56+test('can pass encoding "ucs2" to stdout', checkEncoding, 'ucs2', 1, execa);57+test('can pass encoding "ucs-2" to stdout', checkEncoding, 'ucs-2', 1, execa);58+test('can pass encoding "latin1" to stdout', checkEncoding, 'latin1', 1, execa);59+test('can pass encoding "binary" to stdout', checkEncoding, 'binary', 1, execa);60+test('can pass encoding "ascii" to stdout', checkEncoding, 'ascii', 1, execa);61+test('can pass encoding "hex" to stdout', checkEncoding, 'hex', 1, execa);62+test('can pass encoding "base64" to stdout', checkEncoding, 'base64', 1, execa);63+test('can pass encoding "base64url" to stdout', checkEncoding, 'base64url', 1, execa);64+test('can pass encoding "buffer" to stderr', checkEncoding, 'buffer', 2, execa);65+test('can pass encoding "utf8" to stderr', checkEncoding, 'utf8', 2, execa);66+test('can pass encoding "utf-8" to stderr', checkEncoding, 'utf-8', 2, execa);67+test('can pass encoding "utf16le" to stderr', checkEncoding, 'utf16le', 2, execa);68+test('can pass encoding "utf-16le" to stderr', checkEncoding, 'utf-16le', 2, execa);69+test('can pass encoding "ucs2" to stderr', checkEncoding, 'ucs2', 2, execa);70+test('can pass encoding "ucs-2" to stderr', checkEncoding, 'ucs-2', 2, execa);71+test('can pass encoding "latin1" to stderr', checkEncoding, 'latin1', 2, execa);72+test('can pass encoding "binary" to stderr', checkEncoding, 'binary', 2, execa);73+test('can pass encoding "ascii" to stderr', checkEncoding, 'ascii', 2, execa);74+test('can pass encoding "hex" to stderr', checkEncoding, 'hex', 2, execa);75+test('can pass encoding "base64" to stderr', checkEncoding, 'base64', 2, execa);76+test('can pass encoding "base64url" to stderr', checkEncoding, 'base64url', 2, execa);77+test('can pass encoding "buffer" to stdio[*]', checkEncoding, 'buffer', 3, execa);78+test('can pass encoding "utf8" to stdio[*]', checkEncoding, 'utf8', 3, execa);79+test('can pass encoding "utf-8" to stdio[*]', checkEncoding, 'utf-8', 3, execa);80+test('can pass encoding "utf16le" to stdio[*]', checkEncoding, 'utf16le', 3, execa);81+test('can pass encoding "utf-16le" to stdio[*]', checkEncoding, 'utf-16le', 3, execa);82+test('can pass encoding "ucs2" to stdio[*]', checkEncoding, 'ucs2', 3, execa);83+test('can pass encoding "ucs-2" to stdio[*]', checkEncoding, 'ucs-2', 3, execa);84+test('can pass encoding "latin1" to stdio[*]', checkEncoding, 'latin1', 3, execa);85+test('can pass encoding "binary" to stdio[*]', checkEncoding, 'binary', 3, execa);86+test('can pass encoding "ascii" to stdio[*]', checkEncoding, 'ascii', 3, execa);87+test('can pass encoding "hex" to stdio[*]', checkEncoding, 'hex', 3, execa);88+test('can pass encoding "base64" to stdio[*]', checkEncoding, 'base64', 3, execa);89+test('can pass encoding "base64url" to stdio[*]', checkEncoding, 'base64url', 3, execa);90+test('can pass encoding "buffer" to stdout - sync', checkEncoding, 'buffer', 1, execaSync);91+test('can pass encoding "utf8" to stdout - sync', checkEncoding, 'utf8', 1, execaSync);92+test('can pass encoding "utf-8" to stdout - sync', checkEncoding, 'utf-8', 1, execaSync);93+test('can pass encoding "utf16le" to stdout - sync', checkEncoding, 'utf16le', 1, execaSync);94+test('can pass encoding "utf-16le" to stdout - sync', checkEncoding, 'utf-16le', 1, execaSync);95+test('can pass encoding "ucs2" to stdout - sync', checkEncoding, 'ucs2', 1, execaSync);96+test('can pass encoding "ucs-2" to stdout - sync', checkEncoding, 'ucs-2', 1, execaSync);97+test('can pass encoding "latin1" to stdout - sync', checkEncoding, 'latin1', 1, execaSync);98+test('can pass encoding "binary" to stdout - sync', checkEncoding, 'binary', 1, execaSync);99+test('can pass encoding "ascii" to stdout - sync', checkEncoding, 'ascii', 1, execaSync);100+test('can pass encoding "hex" to stdout - sync', checkEncoding, 'hex', 1, execaSync);101+test('can pass encoding "base64" to stdout - sync', checkEncoding, 'base64', 1, execaSync);102+test('can pass encoding "base64url" to stdout - sync', checkEncoding, 'base64url', 1, execaSync);103+test('can pass encoding "buffer" to stderr - sync', checkEncoding, 'buffer', 2, execaSync);104+test('can pass encoding "utf8" to stderr - sync', checkEncoding, 'utf8', 2, execaSync);105+test('can pass encoding "utf-8" to stderr - sync', checkEncoding, 'utf-8', 2, execaSync);106+test('can pass encoding "utf16le" to stderr - sync', checkEncoding, 'utf16le', 2, execaSync);107+test('can pass encoding "utf-16le" to stderr - sync', checkEncoding, 'utf-16le', 2, execaSync);108+test('can pass encoding "ucs2" to stderr - sync', checkEncoding, 'ucs2', 2, execaSync);109+test('can pass encoding "ucs-2" to stderr - sync', checkEncoding, 'ucs-2', 2, execaSync);110+test('can pass encoding "latin1" to stderr - sync', checkEncoding, 'latin1', 2, execaSync);111+test('can pass encoding "binary" to stderr - sync', checkEncoding, 'binary', 2, execaSync);112+test('can pass encoding "ascii" to stderr - sync', checkEncoding, 'ascii', 2, execaSync);113+test('can pass encoding "hex" to stderr - sync', checkEncoding, 'hex', 2, execaSync);114+test('can pass encoding "base64" to stderr - sync', checkEncoding, 'base64', 2, execaSync);115+test('can pass encoding "base64url" to stderr - sync', checkEncoding, 'base64url', 2, execaSync);116+test('can pass encoding "buffer" to stdio[*] - sync', checkEncoding, 'buffer', 3, execaSync);117+test('can pass encoding "utf8" to stdio[*] - sync', checkEncoding, 'utf8', 3, execaSync);118+test('can pass encoding "utf-8" to stdio[*] - sync', checkEncoding, 'utf-8', 3, execaSync);119+test('can pass encoding "utf16le" to stdio[*] - sync', checkEncoding, 'utf16le', 3, execaSync);120+test('can pass encoding "utf-16le" to stdio[*] - sync', checkEncoding, 'utf-16le', 3, execaSync);121+test('can pass encoding "ucs2" to stdio[*] - sync', checkEncoding, 'ucs2', 3, execaSync);122+test('can pass encoding "ucs-2" to stdio[*] - sync', checkEncoding, 'ucs-2', 3, execaSync);123+test('can pass encoding "latin1" to stdio[*] - sync', checkEncoding, 'latin1', 3, execaSync);124+test('can pass encoding "binary" to stdio[*] - sync', checkEncoding, 'binary', 3, execaSync);125+test('can pass encoding "ascii" to stdio[*] - sync', checkEncoding, 'ascii', 3, execaSync);126+test('can pass encoding "hex" to stdio[*] - sync', checkEncoding, 'hex', 3, execaSync);127+test('can pass encoding "base64" to stdio[*] - sync', checkEncoding, 'base64', 3, execaSync);128+test('can pass encoding "base64url" to stdio[*] - sync', checkEncoding, 'base64url', 3, execaSync);129+/* eslint-enable unicorn/text-encoding-identifier-case */130+131+test('validate unknown encodings', t => {132+ t.throws(() => {133+ execa('noop.js', {encoding: 'unknownEncoding'});134+ }, {code: 'ERR_UNKNOWN_ENCODING'});135+});136+137+const foobarArray = ['fo', 'ob', 'ar', '..'];138+139+test('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+});143+144+test('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+});148+149+test('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+});153+154+const testIgnoredEncoding = async (t, stdoutOption, isUndefined, options) => {155+ const {stdout} = await execa('empty.js', {stdout: stdoutOption, ...options});156+ t.is(stdout === undefined, isUndefined);157+};158+159+const base64Options = {encoding: 'base64'};160+const linesOptions = {lines: true};161+test('Is ignored with other encodings and "ignore"', testIgnoredEncoding, 'ignore', true, base64Options);162+test('Is ignored with other encodings and ["ignore"]', testIgnoredEncoding, ['ignore'], true, base64Options);163+test('Is ignored with other encodings and "ipc"', testIgnoredEncoding, 'ipc', true, base64Options);164+test('Is ignored with other encodings and ["ipc"]', testIgnoredEncoding, ['ipc'], true, base64Options);165+test('Is ignored with other encodings and "inherit"', testIgnoredEncoding, 'inherit', true, base64Options);166+test('Is ignored with other encodings and ["inherit"]', testIgnoredEncoding, ['inherit'], true, base64Options);167+test('Is ignored with other encodings and 1', testIgnoredEncoding, 1, true, base64Options);168+test('Is ignored with other encodings and [1]', testIgnoredEncoding, [1], true, base64Options);169+test('Is ignored with other encodings and process.stdout', testIgnoredEncoding, process.stdout, true, base64Options);170+test('Is ignored with other encodings and [process.stdout]', testIgnoredEncoding, [process.stdout], true, base64Options);171+test('Is not ignored with other encodings and "pipe"', testIgnoredEncoding, 'pipe', false, base64Options);172+test('Is not ignored with other encodings and ["pipe"]', testIgnoredEncoding, ['pipe'], false, base64Options);173+test('Is not ignored with other encodings and "overlapped"', testIgnoredEncoding, 'overlapped', false, base64Options);174+test('Is not ignored with other encodings and ["overlapped"]', testIgnoredEncoding, ['overlapped'], false, base64Options);175+test('Is not ignored with other encodings and ["inherit", "pipe"]', testIgnoredEncoding, ['inherit', 'pipe'], false, base64Options);176+test('Is not ignored with other encodings and undefined', testIgnoredEncoding, undefined, false, base64Options);177+test('Is not ignored with other encodings and null', testIgnoredEncoding, null, false, base64Options);178+test('Is ignored with "lines: true" and "ignore"', testIgnoredEncoding, 'ignore', true, linesOptions);179+test('Is ignored with "lines: true" and ["ignore"]', testIgnoredEncoding, ['ignore'], true, linesOptions);180+test('Is ignored with "lines: true" and "ipc"', testIgnoredEncoding, 'ipc', true, linesOptions);181+test('Is ignored with "lines: true" and ["ipc"]', testIgnoredEncoding, ['ipc'], true, linesOptions);182+test('Is ignored with "lines: true" and "inherit"', testIgnoredEncoding, 'inherit', true, linesOptions);183+test('Is ignored with "lines: true" and ["inherit"]', testIgnoredEncoding, ['inherit'], true, linesOptions);184+test('Is ignored with "lines: true" and 1', testIgnoredEncoding, 1, true, linesOptions);185+test('Is ignored with "lines: true" and [1]', testIgnoredEncoding, [1], true, linesOptions);186+test('Is ignored with "lines: true" and process.stdout', testIgnoredEncoding, process.stdout, true, linesOptions);187+test('Is ignored with "lines: true" and [process.stdout]', testIgnoredEncoding, [process.stdout], true, linesOptions);188+test('Is not ignored with "lines: true" and "pipe"', testIgnoredEncoding, 'pipe', false, linesOptions);189+test('Is not ignored with "lines: true" and ["pipe"]', testIgnoredEncoding, ['pipe'], false, linesOptions);190+test('Is not ignored with "lines: true" and "overlapped"', testIgnoredEncoding, 'overlapped', false, linesOptions);191+test('Is not ignored with "lines: true" and ["overlapped"]', testIgnoredEncoding, ['overlapped'], false, linesOptions);192+test('Is not ignored with "lines: true" and ["inherit", "pipe"]', testIgnoredEncoding, ['inherit', 'pipe'], false, linesOptions);193+test('Is not ignored with "lines: true" and undefined', testIgnoredEncoding, undefined, false, linesOptions);194+test('Is not ignored with "lines: true" and null', testIgnoredEncoding, null, false, linesOptions);195+test('Is ignored with "lines: true", other encodings and "ignore"', testIgnoredEncoding, 'ignore', true, {...base64Options, ...linesOptions});196+test('Is not ignored with "lines: true", other encodings and "pipe"', testIgnoredEncoding, 'pipe', false, {...base64Options, ...linesOptions});added:test/stdio/encoding-start.js+188 added
1+import {Buffer} from 'node:buffer';2+import {scheduler} from 'node:timers/promises';3+import test from 'ava';4+import {execa} from '../../index.js';5+import {setFixtureDir} from '../helpers/fixtures-dir.js';6+import {getStdio} from '../helpers/stdio.js';7+import {foobarString, foobarUint8Array, foobarBuffer, foobarObject} from '../helpers/input.js';8+import {noopGenerator, getOutputGenerator, convertTransformToFinal} from '../helpers/generator.js';9+10+setFixtureDir();11+12+const textEncoder = new TextEncoder();13+14+const getTypeofGenerator = objectMode => ({15+ * transform(line) {16+ yield Object.prototype.toString.call(line);17+ },18+ objectMode,19+});20+21+// eslint-disable-next-line max-params22+const 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+};29+30+test('First generator argument is string with default encoding, with string writes', testGeneratorFirstEncoding, foobarString, 'utf8', '[object String]', false);31+test('First generator argument is string with default encoding, with Buffer writes', testGeneratorFirstEncoding, foobarBuffer, 'utf8', '[object String]', false);32+test('First generator argument is string with default encoding, with Uint8Array writes', testGeneratorFirstEncoding, foobarUint8Array, 'utf8', '[object String]', false);33+test('First generator argument is Uint8Array with encoding "buffer", with string writes', testGeneratorFirstEncoding, foobarString, 'buffer', '[object Uint8Array]', false);34+test('First generator argument is Uint8Array with encoding "buffer", with Buffer writes', testGeneratorFirstEncoding, foobarBuffer, 'buffer', '[object Uint8Array]', false);35+test('First generator argument is Uint8Array with encoding "buffer", with Uint8Array writes', testGeneratorFirstEncoding, foobarUint8Array, 'buffer', '[object Uint8Array]', false);36+test('First generator argument is Uint8Array with encoding "hex", with string writes', testGeneratorFirstEncoding, foobarString, 'hex', '[object String]', false);37+test('First generator argument is Uint8Array with encoding "hex", with Buffer writes', testGeneratorFirstEncoding, foobarBuffer, 'hex', '[object String]', false);38+test('First generator argument is Uint8Array with encoding "hex", with Uint8Array writes', testGeneratorFirstEncoding, foobarUint8Array, 'hex', '[object String]', false);39+test('First generator argument can be string with objectMode', testGeneratorFirstEncoding, foobarString, 'utf8', '[object String]', true);40+test('First generator argument can be objects with objectMode', testGeneratorFirstEncoding, foobarObject, 'utf8', '[object Object]', true);41+42+const 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+};49+50+test('Write call encoding "utf8" is ignored with objectMode', testEncodingIgnored, 'utf8');51+test('Write call encoding "utf16le" is ignored with objectMode', testEncodingIgnored, 'utf16le');52+test('Write call encoding "hex" is ignored with objectMode', testEncodingIgnored, 'hex');53+test('Write call encoding "base64" is ignored with objectMode', testEncodingIgnored, 'base64');54+55+// eslint-disable-next-line max-params56+const 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+};68+69+test('Next generator argument is string with default encoding, with string writes', testGeneratorNextEncoding, foobarString, 'utf8', false, false, 'String');70+test('Next generator argument is string with default encoding, with string writes, objectMode first', testGeneratorNextEncoding, foobarString, 'utf8', true, false, 'String');71+test('Next generator argument is string with default encoding, with string writes, objectMode both', testGeneratorNextEncoding, foobarString, 'utf8', true, true, 'String');72+test('Next generator argument is string with default encoding, with Buffer writes', testGeneratorNextEncoding, foobarBuffer, 'utf8', false, false, 'String');73+test('Next generator argument is string with default encoding, with Buffer writes, objectMode first', testGeneratorNextEncoding, foobarBuffer, 'utf8', true, false, 'String');74+test('Next generator argument is string with default encoding, with Buffer writes, objectMode both', testGeneratorNextEncoding, foobarBuffer, 'utf8', true, true, 'String');75+test('Next generator argument is string with default encoding, with Uint8Array writes', testGeneratorNextEncoding, foobarUint8Array, 'utf8', false, false, 'String');76+test('Next generator argument is string with default encoding, with Uint8Array writes, objectMode first', testGeneratorNextEncoding, foobarUint8Array, 'utf8', true, false, 'String');77+test('Next generator argument is string with default encoding, with Uint8Array writes, objectMode both', testGeneratorNextEncoding, foobarUint8Array, 'utf8', true, true, 'String');78+test('Next generator argument is Uint8Array with encoding "buffer", with string writes', testGeneratorNextEncoding, foobarString, 'buffer', false, false, 'Uint8Array');79+test('Next generator argument is Uint8Array with encoding "buffer", with string writes, objectMode first', testGeneratorNextEncoding, foobarString, 'buffer', true, false, 'Uint8Array');80+test('Next generator argument is Uint8Array with encoding "buffer", with string writes, objectMode both', testGeneratorNextEncoding, foobarString, 'buffer', true, true, 'Uint8Array');81+test('Next generator argument is Uint8Array with encoding "buffer", with Buffer writes', testGeneratorNextEncoding, foobarBuffer, 'buffer', false, false, 'Uint8Array');82+test('Next generator argument is Uint8Array with encoding "buffer", with Buffer writes, objectMode first', testGeneratorNextEncoding, foobarBuffer, 'buffer', true, false, 'Uint8Array');83+test('Next generator argument is Uint8Array with encoding "buffer", with Buffer writes, objectMode both', testGeneratorNextEncoding, foobarBuffer, 'buffer', true, true, 'Uint8Array');84+test('Next generator argument is Uint8Array with encoding "buffer", with Uint8Array writes', testGeneratorNextEncoding, foobarUint8Array, 'buffer', false, false, 'Uint8Array');85+test('Next generator argument is Uint8Array with encoding "buffer", with Uint8Array writes, objectMode first', testGeneratorNextEncoding, foobarUint8Array, 'buffer', true, false, 'Uint8Array');86+test('Next generator argument is Uint8Array with encoding "buffer", with Uint8Array writes, objectMode both', testGeneratorNextEncoding, foobarUint8Array, 'buffer', true, true, 'Uint8Array');87+test('Next generator argument is Uint8Array with encoding "hex", with string writes', testGeneratorNextEncoding, foobarString, 'hex', false, false, 'String');88+test('Next generator argument is Uint8Array with encoding "hex", with Buffer writes', testGeneratorNextEncoding, foobarBuffer, 'hex', false, false, 'String');89+test('Next generator argument is Uint8Array with encoding "hex", with Uint8Array writes', testGeneratorNextEncoding, foobarUint8Array, 'hex', false, false, 'String');90+test('Next generator argument is object with default encoding, with object writes, objectMode first', testGeneratorNextEncoding, foobarObject, 'utf8', true, false, 'Object');91+test('Next generator argument is object with default encoding, with object writes, objectMode both', testGeneratorNextEncoding, foobarObject, 'utf8', true, true, 'Object');92+93+const 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+};97+98+test('The first generator with result.stdout does not receive an object argument even in objectMode', testFirstOutputGeneratorArgument, 1);99+test('The first generator with result.stderr does not receive an object argument even in objectMode', testFirstOutputGeneratorArgument, 2);100+test('The first generator with result.stdio[*] does not receive an object argument even in objectMode', testFirstOutputGeneratorArgument, 3);101+102+// eslint-disable-next-line max-params103+const 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+};114+115+test('Generator can return string with default encoding', testGeneratorReturnType, foobarString, 'utf8', true, false, false);116+test('Generator can return Uint8Array with default encoding', testGeneratorReturnType, foobarUint8Array, 'utf8', true, false, false);117+test('Generator can return string with encoding "buffer"', testGeneratorReturnType, foobarString, 'buffer', true, false, false);118+test('Generator can return Uint8Array with encoding "buffer"', testGeneratorReturnType, foobarUint8Array, 'buffer', true, false, false);119+test('Generator can return string with encoding "hex"', testGeneratorReturnType, foobarString, 'hex', true, false, false);120+test('Generator can return Uint8Array with encoding "hex"', testGeneratorReturnType, foobarUint8Array, 'hex', true, false, false);121+test('Generator can return string with default encoding, failure', testGeneratorReturnType, foobarString, 'utf8', false, false, false);122+test('Generator can return Uint8Array with default encoding, failure', testGeneratorReturnType, foobarUint8Array, 'utf8', false, false, false);123+test('Generator can return string with encoding "buffer", failure', testGeneratorReturnType, foobarString, 'buffer', false, false, false);124+test('Generator can return Uint8Array with encoding "buffer", failure', testGeneratorReturnType, foobarUint8Array, 'buffer', false, false, false);125+test('Generator can return string with encoding "hex", failure', testGeneratorReturnType, foobarString, 'hex', false, false, false);126+test('Generator can return Uint8Array with encoding "hex", failure', testGeneratorReturnType, foobarUint8Array, 'hex', false, false, false);127+test('Generator can return string with default encoding, objectMode', testGeneratorReturnType, foobarString, 'utf8', true, true, false);128+test('Generator can return Uint8Array with default encoding, objectMode', testGeneratorReturnType, foobarUint8Array, 'utf8', true, true, false);129+test('Generator can return string with encoding "buffer", objectMode', testGeneratorReturnType, foobarString, 'buffer', true, true, false);130+test('Generator can return Uint8Array with encoding "buffer", objectMode', testGeneratorReturnType, foobarUint8Array, 'buffer', true, true, false);131+test('Generator can return string with encoding "hex", objectMode', testGeneratorReturnType, foobarString, 'hex', true, true, false);132+test('Generator can return Uint8Array with encoding "hex", objectMode', testGeneratorReturnType, foobarUint8Array, 'hex', true, true, false);133+test('Generator can return string with default encoding, objectMode, failure', testGeneratorReturnType, foobarString, 'utf8', false, true, false);134+test('Generator can return Uint8Array with default encoding, objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'utf8', false, true, false);135+test('Generator can return string with encoding "buffer", objectMode, failure', testGeneratorReturnType, foobarString, 'buffer', false, true, false);136+test('Generator can return Uint8Array with encoding "buffer", objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'buffer', false, true, false);137+test('Generator can return string with encoding "hex", objectMode, failure', testGeneratorReturnType, foobarString, 'hex', false, true, false);138+test('Generator can return Uint8Array with encoding "hex", objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'hex', false, true, false);139+test('Generator can return final string with default encoding', testGeneratorReturnType, foobarString, 'utf8', true, false, true);140+test('Generator can return final Uint8Array with default encoding', testGeneratorReturnType, foobarUint8Array, 'utf8', true, false, true);141+test('Generator can return final string with encoding "buffer"', testGeneratorReturnType, foobarString, 'buffer', true, false, true);142+test('Generator can return final Uint8Array with encoding "buffer"', testGeneratorReturnType, foobarUint8Array, 'buffer', true, false, true);143+test('Generator can return final string with encoding "hex"', testGeneratorReturnType, foobarString, 'hex', true, false, true);144+test('Generator can return final Uint8Array with encoding "hex"', testGeneratorReturnType, foobarUint8Array, 'hex', true, false, true);145+test('Generator can return final string with default encoding, failure', testGeneratorReturnType, foobarString, 'utf8', false, false, true);146+test('Generator can return final Uint8Array with default encoding, failure', testGeneratorReturnType, foobarUint8Array, 'utf8', false, false, true);147+test('Generator can return final string with encoding "buffer", failure', testGeneratorReturnType, foobarString, 'buffer', false, false, true);148+test('Generator can return final Uint8Array with encoding "buffer", failure', testGeneratorReturnType, foobarUint8Array, 'buffer', false, false, true);149+test('Generator can return final string with encoding "hex", failure', testGeneratorReturnType, foobarString, 'hex', false, false, true);150+test('Generator can return final Uint8Array with encoding "hex", failure', testGeneratorReturnType, foobarUint8Array, 'hex', false, false, true);151+test('Generator can return final string with default encoding, objectMode', testGeneratorReturnType, foobarString, 'utf8', true, true, true);152+test('Generator can return final Uint8Array with default encoding, objectMode', testGeneratorReturnType, foobarUint8Array, 'utf8', true, true, true);153+test('Generator can return final string with encoding "buffer", objectMode', testGeneratorReturnType, foobarString, 'buffer', true, true, true);154+test('Generator can return final Uint8Array with encoding "buffer", objectMode', testGeneratorReturnType, foobarUint8Array, 'buffer', true, true, true);155+test('Generator can return final string with encoding "hex", objectMode', testGeneratorReturnType, foobarString, 'hex', true, true, true);156+test('Generator can return final Uint8Array with encoding "hex", objectMode', testGeneratorReturnType, foobarUint8Array, 'hex', true, true, true);157+test('Generator can return final string with default encoding, objectMode, failure', testGeneratorReturnType, foobarString, 'utf8', false, true, true);158+test('Generator can return final Uint8Array with default encoding, objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'utf8', false, true, true);159+test('Generator can return final string with encoding "buffer", objectMode, failure', testGeneratorReturnType, foobarString, 'buffer', false, true, true);160+test('Generator can return final Uint8Array with encoding "buffer", objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'buffer', false, true, true);161+test('Generator can return final string with encoding "hex", objectMode, failure', testGeneratorReturnType, foobarString, 'hex', false, true, true);162+test('Generator can return final Uint8Array with encoding "hex", objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'hex', false, true, true);163+164+const multibyteChar = '\u{1F984}';165+const multibyteString = `${multibyteChar}${multibyteChar}`;166+const multibyteUint8Array = textEncoder.encode(multibyteString);167+const breakingLength = multibyteUint8Array.length * 0.75;168+const brokenSymbol = '\uFFFD';169+170+const 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+};178+179+test('Generator handles multibyte characters with Uint8Array', testMultibyte, false);180+test('Generator handles multibyte characters with Uint8Array, objectMode', testMultibyte, true);181+182+const 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+};186+187+test('Generator handles partial multibyte characters with Uint8Array', testMultibytePartial, false);188+test('Generator handles partial multibyte characters with Uint8Array, objectMode', testMultibytePartial, true);deleted:test/stdio/encoding.js-196 removed
1-import {Buffer} from 'node:buffer';2-import {exec} from 'node:child_process';3-import process from 'node:process';4-import {promisify} from 'node:util';5-import test from 'ava';6-import getStream, {getStreamAsBuffer} from 'get-stream';7-import {execa, execaSync} from '../../index.js';8-import {setFixtureDir, FIXTURES_DIR} from '../helpers/fixtures-dir.js';9-import {fullStdio} from '../helpers/stdio.js';10-import {outputObjectGenerator, getChunksGenerator} from '../helpers/generator.js';11-import {foobarObject} from '../helpers/input.js';12-13-const pExec = promisify(exec);14-15-setFixtureDir();16-17-const 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);20-21- 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- }28-29- if (index === 3) {30- return;31- }32-33- 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-};36-37-const 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-};45-46-// This string gives different outputs with each encoding type47-const STRING_TO_ENCODE = '\u1000.';48-const BUFFER_TO_ENCODE = Buffer.from(STRING_TO_ENCODE);49-50-/* eslint-disable unicorn/text-encoding-identifier-case */51-test('can pass encoding "buffer" to stdout', checkEncoding, 'buffer', 1, execa);52-test('can pass encoding "utf8" to stdout', checkEncoding, 'utf8', 1, execa);53-test('can pass encoding "utf-8" to stdout', checkEncoding, 'utf-8', 1, execa);54-test('can pass encoding "utf16le" to stdout', checkEncoding, 'utf16le', 1, execa);55-test('can pass encoding "utf-16le" to stdout', checkEncoding, 'utf-16le', 1, execa);56-test('can pass encoding "ucs2" to stdout', checkEncoding, 'ucs2', 1, execa);57-test('can pass encoding "ucs-2" to stdout', checkEncoding, 'ucs-2', 1, execa);58-test('can pass encoding "latin1" to stdout', checkEncoding, 'latin1', 1, execa);59-test('can pass encoding "binary" to stdout', checkEncoding, 'binary', 1, execa);60-test('can pass encoding "ascii" to stdout', checkEncoding, 'ascii', 1, execa);61-test('can pass encoding "hex" to stdout', checkEncoding, 'hex', 1, execa);62-test('can pass encoding "base64" to stdout', checkEncoding, 'base64', 1, execa);63-test('can pass encoding "base64url" to stdout', checkEncoding, 'base64url', 1, execa);64-test('can pass encoding "buffer" to stderr', checkEncoding, 'buffer', 2, execa);65-test('can pass encoding "utf8" to stderr', checkEncoding, 'utf8', 2, execa);66-test('can pass encoding "utf-8" to stderr', checkEncoding, 'utf-8', 2, execa);67-test('can pass encoding "utf16le" to stderr', checkEncoding, 'utf16le', 2, execa);68-test('can pass encoding "utf-16le" to stderr', checkEncoding, 'utf-16le', 2, execa);69-test('can pass encoding "ucs2" to stderr', checkEncoding, 'ucs2', 2, execa);70-test('can pass encoding "ucs-2" to stderr', checkEncoding, 'ucs-2', 2, execa);71-test('can pass encoding "latin1" to stderr', checkEncoding, 'latin1', 2, execa);72-test('can pass encoding "binary" to stderr', checkEncoding, 'binary', 2, execa);73-test('can pass encoding "ascii" to stderr', checkEncoding, 'ascii', 2, execa);74-test('can pass encoding "hex" to stderr', checkEncoding, 'hex', 2, execa);75-test('can pass encoding "base64" to stderr', checkEncoding, 'base64', 2, execa);76-test('can pass encoding "base64url" to stderr', checkEncoding, 'base64url', 2, execa);77-test('can pass encoding "buffer" to stdio[*]', checkEncoding, 'buffer', 3, execa);78-test('can pass encoding "utf8" to stdio[*]', checkEncoding, 'utf8', 3, execa);79-test('can pass encoding "utf-8" to stdio[*]', checkEncoding, 'utf-8', 3, execa);80-test('can pass encoding "utf16le" to stdio[*]', checkEncoding, 'utf16le', 3, execa);81-test('can pass encoding "utf-16le" to stdio[*]', checkEncoding, 'utf-16le', 3, execa);82-test('can pass encoding "ucs2" to stdio[*]', checkEncoding, 'ucs2', 3, execa);83-test('can pass encoding "ucs-2" to stdio[*]', checkEncoding, 'ucs-2', 3, execa);84-test('can pass encoding "latin1" to stdio[*]', checkEncoding, 'latin1', 3, execa);85-test('can pass encoding "binary" to stdio[*]', checkEncoding, 'binary', 3, execa);86-test('can pass encoding "ascii" to stdio[*]', checkEncoding, 'ascii', 3, execa);87-test('can pass encoding "hex" to stdio[*]', checkEncoding, 'hex', 3, execa);88-test('can pass encoding "base64" to stdio[*]', checkEncoding, 'base64', 3, execa);89-test('can pass encoding "base64url" to stdio[*]', checkEncoding, 'base64url', 3, execa);90-test('can pass encoding "buffer" to stdout - sync', checkEncoding, 'buffer', 1, execaSync);91-test('can pass encoding "utf8" to stdout - sync', checkEncoding, 'utf8', 1, execaSync);92-test('can pass encoding "utf-8" to stdout - sync', checkEncoding, 'utf-8', 1, execaSync);93-test('can pass encoding "utf16le" to stdout - sync', checkEncoding, 'utf16le', 1, execaSync);94-test('can pass encoding "utf-16le" to stdout - sync', checkEncoding, 'utf-16le', 1, execaSync);95-test('can pass encoding "ucs2" to stdout - sync', checkEncoding, 'ucs2', 1, execaSync);96-test('can pass encoding "ucs-2" to stdout - sync', checkEncoding, 'ucs-2', 1, execaSync);97-test('can pass encoding "latin1" to stdout - sync', checkEncoding, 'latin1', 1, execaSync);98-test('can pass encoding "binary" to stdout - sync', checkEncoding, 'binary', 1, execaSync);99-test('can pass encoding "ascii" to stdout - sync', checkEncoding, 'ascii', 1, execaSync);100-test('can pass encoding "hex" to stdout - sync', checkEncoding, 'hex', 1, execaSync);101-test('can pass encoding "base64" to stdout - sync', checkEncoding, 'base64', 1, execaSync);102-test('can pass encoding "base64url" to stdout - sync', checkEncoding, 'base64url', 1, execaSync);103-test('can pass encoding "buffer" to stderr - sync', checkEncoding, 'buffer', 2, execaSync);104-test('can pass encoding "utf8" to stderr - sync', checkEncoding, 'utf8', 2, execaSync);105-test('can pass encoding "utf-8" to stderr - sync', checkEncoding, 'utf-8', 2, execaSync);106-test('can pass encoding "utf16le" to stderr - sync', checkEncoding, 'utf16le', 2, execaSync);107-test('can pass encoding "utf-16le" to stderr - sync', checkEncoding, 'utf-16le', 2, execaSync);108-test('can pass encoding "ucs2" to stderr - sync', checkEncoding, 'ucs2', 2, execaSync);109-test('can pass encoding "ucs-2" to stderr - sync', checkEncoding, 'ucs-2', 2, execaSync);110-test('can pass encoding "latin1" to stderr - sync', checkEncoding, 'latin1', 2, execaSync);111-test('can pass encoding "binary" to stderr - sync', checkEncoding, 'binary', 2, execaSync);112-test('can pass encoding "ascii" to stderr - sync', checkEncoding, 'ascii', 2, execaSync);113-test('can pass encoding "hex" to stderr - sync', checkEncoding, 'hex', 2, execaSync);114-test('can pass encoding "base64" to stderr - sync', checkEncoding, 'base64', 2, execaSync);115-test('can pass encoding "base64url" to stderr - sync', checkEncoding, 'base64url', 2, execaSync);116-test('can pass encoding "buffer" to stdio[*] - sync', checkEncoding, 'buffer', 3, execaSync);117-test('can pass encoding "utf8" to stdio[*] - sync', checkEncoding, 'utf8', 3, execaSync);118-test('can pass encoding "utf-8" to stdio[*] - sync', checkEncoding, 'utf-8', 3, execaSync);119-test('can pass encoding "utf16le" to stdio[*] - sync', checkEncoding, 'utf16le', 3, execaSync);120-test('can pass encoding "utf-16le" to stdio[*] - sync', checkEncoding, 'utf-16le', 3, execaSync);121-test('can pass encoding "ucs2" to stdio[*] - sync', checkEncoding, 'ucs2', 3, execaSync);122-test('can pass encoding "ucs-2" to stdio[*] - sync', checkEncoding, 'ucs-2', 3, execaSync);123-test('can pass encoding "latin1" to stdio[*] - sync', checkEncoding, 'latin1', 3, execaSync);124-test('can pass encoding "binary" to stdio[*] - sync', checkEncoding, 'binary', 3, execaSync);125-test('can pass encoding "ascii" to stdio[*] - sync', checkEncoding, 'ascii', 3, execaSync);126-test('can pass encoding "hex" to stdio[*] - sync', checkEncoding, 'hex', 3, execaSync);127-test('can pass encoding "base64" to stdio[*] - sync', checkEncoding, 'base64', 3, execaSync);128-test('can pass encoding "base64url" to stdio[*] - sync', checkEncoding, 'base64url', 3, execaSync);129-/* eslint-enable unicorn/text-encoding-identifier-case */130-131-test('validate unknown encodings', t => {132- t.throws(() => {133- execa('noop.js', {encoding: 'unknownEncoding'});134- }, {code: 'ERR_UNKNOWN_ENCODING'});135-});136-137-const foobarArray = ['fo', 'ob', 'ar', '..'];138-139-test('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-});143-144-test('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-});148-149-test('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-});153-154-const testIgnoredEncoding = async (t, stdoutOption, isUndefined, options) => {155- const {stdout} = await execa('empty.js', {stdout: stdoutOption, ...options});156- t.is(stdout === undefined, isUndefined);157-};158-159-const base64Options = {encoding: 'base64'};160-const linesOptions = {lines: true};161-test('Is ignored with other encodings and "ignore"', testIgnoredEncoding, 'ignore', true, base64Options);162-test('Is ignored with other encodings and ["ignore"]', testIgnoredEncoding, ['ignore'], true, base64Options);163-test('Is ignored with other encodings and "ipc"', testIgnoredEncoding, 'ipc', true, base64Options);164-test('Is ignored with other encodings and ["ipc"]', testIgnoredEncoding, ['ipc'], true, base64Options);165-test('Is ignored with other encodings and "inherit"', testIgnoredEncoding, 'inherit', true, base64Options);166-test('Is ignored with other encodings and ["inherit"]', testIgnoredEncoding, ['inherit'], true, base64Options);167-test('Is ignored with other encodings and 1', testIgnoredEncoding, 1, true, base64Options);168-test('Is ignored with other encodings and [1]', testIgnoredEncoding, [1], true, base64Options);169-test('Is ignored with other encodings and process.stdout', testIgnoredEncoding, process.stdout, true, base64Options);170-test('Is ignored with other encodings and [process.stdout]', testIgnoredEncoding, [process.stdout], true, base64Options);171-test('Is not ignored with other encodings and "pipe"', testIgnoredEncoding, 'pipe', false, base64Options);172-test('Is not ignored with other encodings and ["pipe"]', testIgnoredEncoding, ['pipe'], false, base64Options);173-test('Is not ignored with other encodings and "overlapped"', testIgnoredEncoding, 'overlapped', false, base64Options);174-test('Is not ignored with other encodings and ["overlapped"]', testIgnoredEncoding, ['overlapped'], false, base64Options);175-test('Is not ignored with other encodings and ["inherit", "pipe"]', testIgnoredEncoding, ['inherit', 'pipe'], false, base64Options);176-test('Is not ignored with other encodings and undefined', testIgnoredEncoding, undefined, false, base64Options);177-test('Is not ignored with other encodings and null', testIgnoredEncoding, null, false, base64Options);178-test('Is ignored with "lines: true" and "ignore"', testIgnoredEncoding, 'ignore', true, linesOptions);179-test('Is ignored with "lines: true" and ["ignore"]', testIgnoredEncoding, ['ignore'], true, linesOptions);180-test('Is ignored with "lines: true" and "ipc"', testIgnoredEncoding, 'ipc', true, linesOptions);181-test('Is ignored with "lines: true" and ["ipc"]', testIgnoredEncoding, ['ipc'], true, linesOptions);182-test('Is ignored with "lines: true" and "inherit"', testIgnoredEncoding, 'inherit', true, linesOptions);183-test('Is ignored with "lines: true" and ["inherit"]', testIgnoredEncoding, ['inherit'], true, linesOptions);184-test('Is ignored with "lines: true" and 1', testIgnoredEncoding, 1, true, linesOptions);185-test('Is ignored with "lines: true" and [1]', testIgnoredEncoding, [1], true, linesOptions);186-test('Is ignored with "lines: true" and process.stdout', testIgnoredEncoding, process.stdout, true, linesOptions);187-test('Is ignored with "lines: true" and [process.stdout]', testIgnoredEncoding, [process.stdout], true, linesOptions);188-test('Is not ignored with "lines: true" and "pipe"', testIgnoredEncoding, 'pipe', false, linesOptions);189-test('Is not ignored with "lines: true" and ["pipe"]', testIgnoredEncoding, ['pipe'], false, linesOptions);190-test('Is not ignored with "lines: true" and "overlapped"', testIgnoredEncoding, 'overlapped', false, linesOptions);191-test('Is not ignored with "lines: true" and ["overlapped"]', testIgnoredEncoding, ['overlapped'], false, linesOptions);192-test('Is not ignored with "lines: true" and ["inherit", "pipe"]', testIgnoredEncoding, ['inherit', 'pipe'], false, linesOptions);193-test('Is not ignored with "lines: true" and undefined', testIgnoredEncoding, undefined, false, linesOptions);194-test('Is not ignored with "lines: true" and null', testIgnoredEncoding, null, false, linesOptions);195-test('Is ignored with "lines: true", other encodings and "ignore"', testIgnoredEncoding, 'ignore', true, {...base64Options, ...linesOptions});196-test('Is not ignored with "lines: true", other encodings and "pipe"', testIgnoredEncoding, 'pipe', false, {...base64Options, ...linesOptions});added:test/stdio/forward.js+16 added
1+import test from 'ava';2+import {execa} from '../../index.js';3+import {getStdio} from '../helpers/stdio.js';4+import {setFixtureDir} from '../helpers/fixtures-dir.js';5+6+setFixtureDir();7+8+const testOverlapped = async (t, index) => {9+ const {stdout} = await execa('noop.js', ['foobar'], getStdio(index, ['overlapped', 'pipe']));10+ t.is(stdout, 'foobar');11+};12+13+test('stdin can be ["overlapped", "pipe"]', testOverlapped, 0);14+test('stdout can be ["overlapped", "pipe"]', testOverlapped, 1);15+test('stderr can be ["overlapped", "pipe"]', testOverlapped, 2);16+test('stdio[*] can be ["overlapped", "pipe"]', testOverlapped, 3);modified:test/stdio/generator.js+3 added-447 removed
1-import {Buffer} from 'node:buffer';2-import {once} from 'node:events';1 import {readFile, writeFile, rm} from 'node:fs/promises';4-import {getDefaultHighWaterMark, PassThrough} from 'node:stream';5-import {setTimeout, scheduler} from 'node:timers/promises';2+import {PassThrough} from 'node:stream';3 import test from 'ava';4 import getStream, {getStreamAsArray} from 'get-stream';5 import tempfile from 'tempfile';9-import {execa, execaSync} from '../../index.js';6+import {execa} from '../../index.js';7 import {setFixtureDir} from '../helpers/fixtures-dir.js';8 import {getStdio} from '../helpers/stdio.js';9 import {foobarString, foobarUint8Array, foobarBuffer, foobarObject, foobarObjectString} from '../helpers/input.js';13-import {14- serializeGenerator,15- noopGenerator,16- getOutputsGenerator,17- getOutputGenerator,18- outputObjectGenerator,19- noYieldGenerator,20- convertTransformToFinal,21- infiniteGenerator,22-} from '../helpers/generator.js';10+import {serializeGenerator, outputObjectGenerator} from '../helpers/generator.js';11 12 setFixtureDir();13 14 const textEncoder = new TextEncoder();58 unmodified lines73 test('Can use generators with childProcess.stdio[*] as input', testGeneratorStdioInputPipe, false);74 test('Can use generators with childProcess.stdio[*] as input, objectMode', testGeneratorStdioInputPipe, true);75 76 // eslint-disable-next-line max-params89-const 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-};94-95-const lastInputGenerator = (input, objectMode) => [foobarUint8Array, getOutputGenerator(input, objectMode)];96-const inputGenerator = (input, objectMode) => [...lastInputGenerator(input, objectMode), serializeGenerator];97-98-test('Generators with result.stdin cannot return an object if not in objectMode', testGeneratorReturn, 0, inputGenerator(foobarObject, false), 'stdin-fd.js', false);99-test('Generators with result.stdio[*] as input cannot return an object if not in objectMode', testGeneratorReturn, 3, inputGenerator(foobarObject, false), 'stdin-fd.js', false);100-test('The last generator with result.stdin cannot return an object even in objectMode', testGeneratorReturn, 0, lastInputGenerator(foobarObject, true), 'stdin-fd.js', false);101-test('The last generator with result.stdio[*] as input cannot return an object even in objectMode', testGeneratorReturn, 3, lastInputGenerator(foobarObject, true), 'stdin-fd.js', false);102-test('Generators with result.stdout cannot return an object if not in objectMode', testGeneratorReturn, 1, getOutputGenerator(foobarObject, false), 'noop-fd.js', false);103-test('Generators with result.stderr cannot return an object if not in objectMode', testGeneratorReturn, 2, getOutputGenerator(foobarObject, false), 'noop-fd.js', false);104-test('Generators with result.stdio[*] as output cannot return an object if not in objectMode', testGeneratorReturn, 3, getOutputGenerator(foobarObject, false), 'noop-fd.js', false);105-test('Generators with result.stdin cannot return null if not in objectMode', testGeneratorReturn, 0, inputGenerator(null, false), 'stdin-fd.js', true);106-test('Generators with result.stdin cannot return null if in objectMode', testGeneratorReturn, 0, inputGenerator(null, true), 'stdin-fd.js', true);107-test('Generators with result.stdout cannot return null if not in objectMode', testGeneratorReturn, 1, getOutputGenerator(null, false), 'noop-fd.js', true);108-test('Generators with result.stdout cannot return null if in objectMode', testGeneratorReturn, 1, getOutputGenerator(null, true), 'noop-fd.js', true);109-test('Generators with result.stdin cannot return undefined if not in objectMode', testGeneratorReturn, 0, inputGenerator(undefined, false), 'stdin-fd.js', true);110-test('Generators with result.stdin cannot return undefined if in objectMode', testGeneratorReturn, 0, inputGenerator(undefined, true), 'stdin-fd.js', true);111-test('Generators with result.stdout cannot return undefined if not in objectMode', testGeneratorReturn, 1, getOutputGenerator(undefined, false), 'noop-fd.js', true);112-test('Generators with result.stdout cannot return undefined if in objectMode', testGeneratorReturn, 1, getOutputGenerator(undefined, true), 'noop-fd.js', true);113-114-const testGeneratorFinal = async (t, fixtureName) => {115- const {stdout} = await execa(fixtureName, {stdout: convertTransformToFinal(getOutputGenerator(foobarString), true)});116- t.is(stdout, foobarString);117-};118-119-test('Generators "final" can be used', testGeneratorFinal, 'noop.js');120-test('Generators "final" is used even on empty streams', testGeneratorFinal, 'empty.js');121-122-test('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-});126-127-// eslint-disable-next-line max-params77 const 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 lines202 const {stdout} = await execa('stdin-fd.js', ['0'], {stdin: uppercaseGenerator, input: foobarUint8Array});203 t.is(stdout, foobarUppercase);204 });205 257-const testInvalidGenerator = (t, index, stdioOption) => {258- t.throws(() => {259- execa('empty.js', getStdio(index, {...noopGenerator(), ...stdioOption}));260- }, {message: /must be a generator/});261-};262-263-test('Cannot use invalid "transform" with stdin', testInvalidGenerator, 0, {transform: true});264-test('Cannot use invalid "transform" with stdout', testInvalidGenerator, 1, {transform: true});265-test('Cannot use invalid "transform" with stderr', testInvalidGenerator, 2, {transform: true});266-test('Cannot use invalid "transform" with stdio[*]', testInvalidGenerator, 3, {transform: true});267-test('Cannot use invalid "final" with stdin', testInvalidGenerator, 0, {final: true});268-test('Cannot use invalid "final" with stdout', testInvalidGenerator, 1, {final: true});269-test('Cannot use invalid "final" with stderr', testInvalidGenerator, 2, {final: true});270-test('Cannot use invalid "final" with stdio[*]', testInvalidGenerator, 3, {final: true});271-272-const testInvalidBinary = (t, index, optionName) => {273- t.throws(() => {274- execa('empty.js', getStdio(index, {transform: uppercaseGenerator, [optionName]: 'true'}));275- }, {message: /a boolean/});276-};277-278-test('Cannot use invalid "binary" with stdin', testInvalidBinary, 0, 'binary');279-test('Cannot use invalid "binary" with stdout', testInvalidBinary, 1, 'binary');280-test('Cannot use invalid "binary" with stderr', testInvalidBinary, 2, 'binary');281-test('Cannot use invalid "binary" with stdio[*]', testInvalidBinary, 3, 'binary');282-test('Cannot use invalid "objectMode" with stdin', testInvalidBinary, 0, 'objectMode');283-test('Cannot use invalid "objectMode" with stdout', testInvalidBinary, 1, 'objectMode');284-test('Cannot use invalid "objectMode" with stderr', testInvalidBinary, 2, 'objectMode');285-test('Cannot use invalid "objectMode" with stdio[*]', testInvalidBinary, 3, 'objectMode');286-287-const testSyncMethods = (t, index) => {288- t.throws(() => {289- execaSync('empty.js', getStdio(index, uppercaseGenerator));290- }, {message: /cannot be a generator/});291-};292-293-test('Cannot use generators with sync methods and stdin', testSyncMethods, 0);294-test('Cannot use generators with sync methods and stdout', testSyncMethods, 1);295-test('Cannot use generators with sync methods and stderr', testSyncMethods, 2);296-test('Cannot use generators with sync methods and stdio[*]', testSyncMethods, 3);297-298-const repeatCount = getDefaultHighWaterMark() * 3;299-300-const writerGenerator = function * () {301- for (let index = 0; index < repeatCount; index += 1) {302- yield '\n';303- }304-};305-306-const getLengthGenerator = function * (t, chunk) {307- t.is(chunk.length, 1);308- yield chunk;309-};310-311-const 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-};323-324-test('Synchronous yields are not buffered, no passThrough', testHighWaterMark, false, false, false);325-test('Synchronous yields are not buffered, line-wise passThrough', testHighWaterMark, true, false, false);326-test('Synchronous yields are not buffered, binary passThrough', testHighWaterMark, true, true, false);327-test('Synchronous yields are not buffered, objectMode as input but not output', testHighWaterMark, false, false, true);328-329-const getTypeofGenerator = objectMode => ({330- * transform(line) {331- yield Object.prototype.toString.call(line);332- },333- objectMode,334-});335-336-// eslint-disable-next-line max-params337-const 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-};344-345-test('First generator argument is string with default encoding, with string writes', testGeneratorFirstEncoding, foobarString, 'utf8', '[object String]', false);346-test('First generator argument is string with default encoding, with Buffer writes', testGeneratorFirstEncoding, foobarBuffer, 'utf8', '[object String]', false);347-test('First generator argument is string with default encoding, with Uint8Array writes', testGeneratorFirstEncoding, foobarUint8Array, 'utf8', '[object String]', false);348-test('First generator argument is Uint8Array with encoding "buffer", with string writes', testGeneratorFirstEncoding, foobarString, 'buffer', '[object Uint8Array]', false);349-test('First generator argument is Uint8Array with encoding "buffer", with Buffer writes', testGeneratorFirstEncoding, foobarBuffer, 'buffer', '[object Uint8Array]', false);350-test('First generator argument is Uint8Array with encoding "buffer", with Uint8Array writes', testGeneratorFirstEncoding, foobarUint8Array, 'buffer', '[object Uint8Array]', false);351-test('First generator argument is Uint8Array with encoding "hex", with string writes', testGeneratorFirstEncoding, foobarString, 'hex', '[object String]', false);352-test('First generator argument is Uint8Array with encoding "hex", with Buffer writes', testGeneratorFirstEncoding, foobarBuffer, 'hex', '[object String]', false);353-test('First generator argument is Uint8Array with encoding "hex", with Uint8Array writes', testGeneratorFirstEncoding, foobarUint8Array, 'hex', '[object String]', false);354-test('First generator argument can be string with objectMode', testGeneratorFirstEncoding, foobarString, 'utf8', '[object String]', true);355-test('First generator argument can be objects with objectMode', testGeneratorFirstEncoding, foobarObject, 'utf8', '[object Object]', true);356-357-const 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-};364-365-test('Write call encoding "utf8" is ignored with objectMode', testEncodingIgnored, 'utf8');366-test('Write call encoding "utf16le" is ignored with objectMode', testEncodingIgnored, 'utf16le');367-test('Write call encoding "hex" is ignored with objectMode', testEncodingIgnored, 'hex');368-test('Write call encoding "base64" is ignored with objectMode', testEncodingIgnored, 'base64');369-370-// eslint-disable-next-line max-params371-const 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-};383-384-test('Next generator argument is string with default encoding, with string writes', testGeneratorNextEncoding, foobarString, 'utf8', false, false, 'String');385-test('Next generator argument is string with default encoding, with string writes, objectMode first', testGeneratorNextEncoding, foobarString, 'utf8', true, false, 'String');386-test('Next generator argument is string with default encoding, with string writes, objectMode both', testGeneratorNextEncoding, foobarString, 'utf8', true, true, 'String');387-test('Next generator argument is string with default encoding, with Buffer writes', testGeneratorNextEncoding, foobarBuffer, 'utf8', false, false, 'String');388-test('Next generator argument is string with default encoding, with Buffer writes, objectMode first', testGeneratorNextEncoding, foobarBuffer, 'utf8', true, false, 'String');389-test('Next generator argument is string with default encoding, with Buffer writes, objectMode both', testGeneratorNextEncoding, foobarBuffer, 'utf8', true, true, 'String');390-test('Next generator argument is string with default encoding, with Uint8Array writes', testGeneratorNextEncoding, foobarUint8Array, 'utf8', false, false, 'String');391-test('Next generator argument is string with default encoding, with Uint8Array writes, objectMode first', testGeneratorNextEncoding, foobarUint8Array, 'utf8', true, false, 'String');392-test('Next generator argument is string with default encoding, with Uint8Array writes, objectMode both', testGeneratorNextEncoding, foobarUint8Array, 'utf8', true, true, 'String');393-test('Next generator argument is Uint8Array with encoding "buffer", with string writes', testGeneratorNextEncoding, foobarString, 'buffer', false, false, 'Uint8Array');394-test('Next generator argument is Uint8Array with encoding "buffer", with string writes, objectMode first', testGeneratorNextEncoding, foobarString, 'buffer', true, false, 'Uint8Array');395-test('Next generator argument is Uint8Array with encoding "buffer", with string writes, objectMode both', testGeneratorNextEncoding, foobarString, 'buffer', true, true, 'Uint8Array');396-test('Next generator argument is Uint8Array with encoding "buffer", with Buffer writes', testGeneratorNextEncoding, foobarBuffer, 'buffer', false, false, 'Uint8Array');397-test('Next generator argument is Uint8Array with encoding "buffer", with Buffer writes, objectMode first', testGeneratorNextEncoding, foobarBuffer, 'buffer', true, false, 'Uint8Array');398-test('Next generator argument is Uint8Array with encoding "buffer", with Buffer writes, objectMode both', testGeneratorNextEncoding, foobarBuffer, 'buffer', true, true, 'Uint8Array');399-test('Next generator argument is Uint8Array with encoding "buffer", with Uint8Array writes', testGeneratorNextEncoding, foobarUint8Array, 'buffer', false, false, 'Uint8Array');400-test('Next generator argument is Uint8Array with encoding "buffer", with Uint8Array writes, objectMode first', testGeneratorNextEncoding, foobarUint8Array, 'buffer', true, false, 'Uint8Array');401-test('Next generator argument is Uint8Array with encoding "buffer", with Uint8Array writes, objectMode both', testGeneratorNextEncoding, foobarUint8Array, 'buffer', true, true, 'Uint8Array');402-test('Next generator argument is Uint8Array with encoding "hex", with string writes', testGeneratorNextEncoding, foobarString, 'hex', false, false, 'String');403-test('Next generator argument is Uint8Array with encoding "hex", with Buffer writes', testGeneratorNextEncoding, foobarBuffer, 'hex', false, false, 'String');404-test('Next generator argument is Uint8Array with encoding "hex", with Uint8Array writes', testGeneratorNextEncoding, foobarUint8Array, 'hex', false, false, 'String');405-test('Next generator argument is object with default encoding, with object writes, objectMode first', testGeneratorNextEncoding, foobarObject, 'utf8', true, false, 'Object');406-test('Next generator argument is object with default encoding, with object writes, objectMode both', testGeneratorNextEncoding, foobarObject, 'utf8', true, true, 'Object');407-408-const 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-};412-413-test('The first generator with result.stdout does not receive an object argument even in objectMode', testFirstOutputGeneratorArgument, 1);414-test('The first generator with result.stderr does not receive an object argument even in objectMode', testFirstOutputGeneratorArgument, 2);415-test('The first generator with result.stdio[*] does not receive an object argument even in objectMode', testFirstOutputGeneratorArgument, 3);416-417-// eslint-disable-next-line max-params418-const 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-};429-430-test('Generator can return string with default encoding', testGeneratorReturnType, foobarString, 'utf8', true, false, false);431-test('Generator can return Uint8Array with default encoding', testGeneratorReturnType, foobarUint8Array, 'utf8', true, false, false);432-test('Generator can return string with encoding "buffer"', testGeneratorReturnType, foobarString, 'buffer', true, false, false);433-test('Generator can return Uint8Array with encoding "buffer"', testGeneratorReturnType, foobarUint8Array, 'buffer', true, false, false);434-test('Generator can return string with encoding "hex"', testGeneratorReturnType, foobarString, 'hex', true, false, false);435-test('Generator can return Uint8Array with encoding "hex"', testGeneratorReturnType, foobarUint8Array, 'hex', true, false, false);436-test('Generator can return string with default encoding, failure', testGeneratorReturnType, foobarString, 'utf8', false, false, false);437-test('Generator can return Uint8Array with default encoding, failure', testGeneratorReturnType, foobarUint8Array, 'utf8', false, false, false);438-test('Generator can return string with encoding "buffer", failure', testGeneratorReturnType, foobarString, 'buffer', false, false, false);439-test('Generator can return Uint8Array with encoding "buffer", failure', testGeneratorReturnType, foobarUint8Array, 'buffer', false, false, false);440-test('Generator can return string with encoding "hex", failure', testGeneratorReturnType, foobarString, 'hex', false, false, false);441-test('Generator can return Uint8Array with encoding "hex", failure', testGeneratorReturnType, foobarUint8Array, 'hex', false, false, false);442-test('Generator can return string with default encoding, objectMode', testGeneratorReturnType, foobarString, 'utf8', true, true, false);443-test('Generator can return Uint8Array with default encoding, objectMode', testGeneratorReturnType, foobarUint8Array, 'utf8', true, true, false);444-test('Generator can return string with encoding "buffer", objectMode', testGeneratorReturnType, foobarString, 'buffer', true, true, false);445-test('Generator can return Uint8Array with encoding "buffer", objectMode', testGeneratorReturnType, foobarUint8Array, 'buffer', true, true, false);446-test('Generator can return string with encoding "hex", objectMode', testGeneratorReturnType, foobarString, 'hex', true, true, false);447-test('Generator can return Uint8Array with encoding "hex", objectMode', testGeneratorReturnType, foobarUint8Array, 'hex', true, true, false);448-test('Generator can return string with default encoding, objectMode, failure', testGeneratorReturnType, foobarString, 'utf8', false, true, false);449-test('Generator can return Uint8Array with default encoding, objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'utf8', false, true, false);450-test('Generator can return string with encoding "buffer", objectMode, failure', testGeneratorReturnType, foobarString, 'buffer', false, true, false);451-test('Generator can return Uint8Array with encoding "buffer", objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'buffer', false, true, false);452-test('Generator can return string with encoding "hex", objectMode, failure', testGeneratorReturnType, foobarString, 'hex', false, true, false);453-test('Generator can return Uint8Array with encoding "hex", objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'hex', false, true, false);454-test('Generator can return final string with default encoding', testGeneratorReturnType, foobarString, 'utf8', true, false, true);455-test('Generator can return final Uint8Array with default encoding', testGeneratorReturnType, foobarUint8Array, 'utf8', true, false, true);456-test('Generator can return final string with encoding "buffer"', testGeneratorReturnType, foobarString, 'buffer', true, false, true);457-test('Generator can return final Uint8Array with encoding "buffer"', testGeneratorReturnType, foobarUint8Array, 'buffer', true, false, true);458-test('Generator can return final string with encoding "hex"', testGeneratorReturnType, foobarString, 'hex', true, false, true);459-test('Generator can return final Uint8Array with encoding "hex"', testGeneratorReturnType, foobarUint8Array, 'hex', true, false, true);460-test('Generator can return final string with default encoding, failure', testGeneratorReturnType, foobarString, 'utf8', false, false, true);461-test('Generator can return final Uint8Array with default encoding, failure', testGeneratorReturnType, foobarUint8Array, 'utf8', false, false, true);462-test('Generator can return final string with encoding "buffer", failure', testGeneratorReturnType, foobarString, 'buffer', false, false, true);463-test('Generator can return final Uint8Array with encoding "buffer", failure', testGeneratorReturnType, foobarUint8Array, 'buffer', false, false, true);464-test('Generator can return final string with encoding "hex", failure', testGeneratorReturnType, foobarString, 'hex', false, false, true);465-test('Generator can return final Uint8Array with encoding "hex", failure', testGeneratorReturnType, foobarUint8Array, 'hex', false, false, true);466-test('Generator can return final string with default encoding, objectMode', testGeneratorReturnType, foobarString, 'utf8', true, true, true);467-test('Generator can return final Uint8Array with default encoding, objectMode', testGeneratorReturnType, foobarUint8Array, 'utf8', true, true, true);468-test('Generator can return final string with encoding "buffer", objectMode', testGeneratorReturnType, foobarString, 'buffer', true, true, true);469-test('Generator can return final Uint8Array with encoding "buffer", objectMode', testGeneratorReturnType, foobarUint8Array, 'buffer', true, true, true);470-test('Generator can return final string with encoding "hex", objectMode', testGeneratorReturnType, foobarString, 'hex', true, true, true);471-test('Generator can return final Uint8Array with encoding "hex", objectMode', testGeneratorReturnType, foobarUint8Array, 'hex', true, true, true);472-test('Generator can return final string with default encoding, objectMode, failure', testGeneratorReturnType, foobarString, 'utf8', false, true, true);473-test('Generator can return final Uint8Array with default encoding, objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'utf8', false, true, true);474-test('Generator can return final string with encoding "buffer", objectMode, failure', testGeneratorReturnType, foobarString, 'buffer', false, true, true);475-test('Generator can return final Uint8Array with encoding "buffer", objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'buffer', false, true, true);476-test('Generator can return final string with encoding "hex", objectMode, failure', testGeneratorReturnType, foobarString, 'hex', false, true, true);477-test('Generator can return final Uint8Array with encoding "hex", objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'hex', false, true, true);478-479-const multibyteChar = '\u{1F984}';480-const multibyteString = `${multibyteChar}${multibyteChar}`;481-const multibyteUint8Array = textEncoder.encode(multibyteString);482-const breakingLength = multibyteUint8Array.length * 0.75;483-const brokenSymbol = '\uFFFD';484-485-const 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-};493-494-test('Generator handles multibyte characters with Uint8Array', testMultibyte, false);495-test('Generator handles multibyte characters with Uint8Array, objectMode', testMultibyte, true);496-497-const 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-};501-502-test('Generator handles partial multibyte characters with Uint8Array', testMultibytePartial, false);503-test('Generator handles partial multibyte characters with Uint8Array, objectMode', testMultibytePartial, true);504-505-const testNoYield = async (t, objectMode, final, output) => {506- const {stdout} = await execa('noop.js', {stdout: convertTransformToFinal(noYieldGenerator(objectMode), final)});507- t.deepEqual(stdout, output);508-};509-510-test('Generator can filter "transform" by not calling yield', testNoYield, false, false, '');511-test('Generator can filter "transform" by not calling yield, objectMode', testNoYield, true, false, []);512-test('Generator can filter "final" by not calling yield', testNoYield, false, false, '');513-test('Generator can filter "final" by not calling yield, objectMode', testNoYield, true, false, []);514-515-const prefix = '> ';516-const suffix = ' <';517-518-const multipleYieldGenerator = async function * (line = foobarString) {519- yield prefix;520- await scheduler.yield();521- yield line;522- await scheduler.yield();523- yield suffix;524-};525-526-const 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-};530-531-test('Generator can yield "transform" multiple times at different moments', testMultipleYields, false);532-test('Generator can yield "final" multiple times at different moments', testMultipleYields, true);533-534-const partsPerChunk = 4;535-const chunksPerCall = 10;536-const callCount = 5;537-const fullString = '\n'.repeat(getDefaultHighWaterMark(false) / partsPerChunk);538-539-const yieldFullStrings = function * () {540- yield * Array.from({length: partsPerChunk * chunksPerCall}).fill(fullString);541-};542-543-const 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-};550-551-const 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-};557-558-test('Generator "transform" yields are sent right away', testManyYields, false);559-test('Generator "final" yields are sent right away', testManyYields, true);560-206 const testInputFile = async (t, getOptions, reversed) => {207 const filePath = tempfile();208 await writeFile(filePath, foobarString);209 const {stdin, ...options} = getOptions(filePath);74 unmodified lines284 test('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 });643-644-const maxBuffer = 10;645-646-test('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);650-651- await t.throwsAsync(execa('noop.js', {maxBuffer, stdout: getOutputGenerator(`${bigString}.`, false)}));652-});653-654-test('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);658-659- await t.throwsAsync(execa('noop.js', {maxBuffer, stdout: getOutputsGenerator([...bigArray, ''], true)}));660-});661-662-const timeoutGenerator = async function * (timeout) {663- await setTimeout(timeout);664- yield foobarString;665-};666-667-const 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-};674-675-test('Generators "transform" is awaited on success', testAsyncGenerators, false);676-test('Generators "final" is awaited on success', testAsyncGenerators, true);677-678-// eslint-disable-next-line require-yield679-const throwingGenerator = function * () {680- throw new Error('Generator error');681-};682-683-const GENERATOR_ERROR_REGEXP = /Generator error/;684-685-const 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-};691-692-test('Generators "transform" errors make process fail', testThrowingGenerator, false);693-test('Generators "final" errors make process fail', testThrowingGenerator, true);694-695-test('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-});701-702-test('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-});707-708-const 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-};714-715-test('Running generators are canceled on process abort', testGeneratorCancel, undefined);716-test('Running generators are canceled on process error', testGeneratorCancel, new Error('test'));717-718-const 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-};725-726-test('Generators are destroyed on process error, sync', testGeneratorDestroy, noopGenerator(false));727-test('Generators are destroyed on process error, async', testGeneratorDestroy, infiniteGenerator);728-729-test('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
1+import test from 'ava';2+import {execa, execaSync} from '../../index.js';3+import {getStdio} from '../helpers/stdio.js';4+import {setFixtureDir} from '../helpers/fixtures-dir.js';5+6+setFixtureDir();7+8+const 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+};13+14+test('Cannot pass an empty array to stdin', testEmptyArray, 0, 'stdin', execa);15+test('Cannot pass an empty array to stdout', testEmptyArray, 1, 'stdout', execa);16+test('Cannot pass an empty array to stderr', testEmptyArray, 2, 'stderr', execa);17+test('Cannot pass an empty array to stdio[*]', testEmptyArray, 3, 'stdio[3]', execa);18+test('Cannot pass an empty array to stdin - sync', testEmptyArray, 0, 'stdin', execaSync);19+test('Cannot pass an empty array to stdout - sync', testEmptyArray, 1, 'stdout', execaSync);20+test('Cannot pass an empty array to stderr - sync', testEmptyArray, 2, 'stderr', execaSync);21+test('Cannot pass an empty array to stdio[*] - sync', testEmptyArray, 3, 'stdio[3]', execaSync);22+23+const 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+};28+29+test('stdin can be "ignore"', testNoPipeOption, 'ignore', 0);30+test('stdin can be ["ignore"]', testNoPipeOption, ['ignore'], 0);31+test('stdin can be ["ignore", "ignore"]', testNoPipeOption, ['ignore', 'ignore'], 0);32+test('stdin can be "ipc"', testNoPipeOption, 'ipc', 0);33+test('stdin can be ["ipc"]', testNoPipeOption, ['ipc'], 0);34+test('stdin can be "inherit"', testNoPipeOption, 'inherit', 0);35+test('stdin can be ["inherit"]', testNoPipeOption, ['inherit'], 0);36+test('stdin can be 0', testNoPipeOption, 0, 0);37+test('stdin can be [0]', testNoPipeOption, [0], 0);38+test('stdout can be "ignore"', testNoPipeOption, 'ignore', 1);39+test('stdout can be ["ignore"]', testNoPipeOption, ['ignore'], 1);40+test('stdout can be ["ignore", "ignore"]', testNoPipeOption, ['ignore', 'ignore'], 1);41+test('stdout can be "ipc"', testNoPipeOption, 'ipc', 1);42+test('stdout can be ["ipc"]', testNoPipeOption, ['ipc'], 1);43+test('stdout can be "inherit"', testNoPipeOption, 'inherit', 1);44+test('stdout can be ["inherit"]', testNoPipeOption, ['inherit'], 1);45+test('stdout can be 1', testNoPipeOption, 1, 1);46+test('stdout can be [1]', testNoPipeOption, [1], 1);47+test('stderr can be "ignore"', testNoPipeOption, 'ignore', 2);48+test('stderr can be ["ignore"]', testNoPipeOption, ['ignore'], 2);49+test('stderr can be ["ignore", "ignore"]', testNoPipeOption, ['ignore', 'ignore'], 2);50+test('stderr can be "ipc"', testNoPipeOption, 'ipc', 2);51+test('stderr can be ["ipc"]', testNoPipeOption, ['ipc'], 2);52+test('stderr can be "inherit"', testNoPipeOption, 'inherit', 2);53+test('stderr can be ["inherit"]', testNoPipeOption, ['inherit'], 2);54+test('stderr can be 2', testNoPipeOption, 2, 2);55+test('stderr can be [2]', testNoPipeOption, [2], 2);56+test('stdio[*] can be "ignore"', testNoPipeOption, 'ignore', 3);57+test('stdio[*] can be ["ignore"]', testNoPipeOption, ['ignore'], 3);58+test('stdio[*] can be ["ignore", "ignore"]', testNoPipeOption, ['ignore', 'ignore'], 3);59+test('stdio[*] can be "ipc"', testNoPipeOption, 'ipc', 3);60+test('stdio[*] can be ["ipc"]', testNoPipeOption, ['ipc'], 3);61+test('stdio[*] can be "inherit"', testNoPipeOption, 'inherit', 3);62+test('stdio[*] can be ["inherit"]', testNoPipeOption, ['inherit'], 3);63+test('stdio[*] can be 3', testNoPipeOption, 3, 3);64+test('stdio[*] can be [3]', testNoPipeOption, [3], 3);65+66+const testInvalidArrayValue = (t, invalidStdio, index, execaMethod) => {67+ t.throws(() => {68+ execaMethod('empty.js', getStdio(index, ['pipe', invalidStdio]));69+ }, {message: /must not include/});70+};71+72+test('Cannot pass "ignore" and another value to stdin', testInvalidArrayValue, 'ignore', 0, execa);73+test('Cannot pass "ignore" and another value to stdout', testInvalidArrayValue, 'ignore', 1, execa);74+test('Cannot pass "ignore" and another value to stderr', testInvalidArrayValue, 'ignore', 2, execa);75+test('Cannot pass "ignore" and another value to stdio[*]', testInvalidArrayValue, 'ignore', 3, execa);76+test('Cannot pass "ignore" and another value to stdin - sync', testInvalidArrayValue, 'ignore', 0, execaSync);77+test('Cannot pass "ignore" and another value to stdout - sync', testInvalidArrayValue, 'ignore', 1, execaSync);78+test('Cannot pass "ignore" and another value to stderr - sync', testInvalidArrayValue, 'ignore', 2, execaSync);79+test('Cannot pass "ignore" and another value to stdio[*] - sync', testInvalidArrayValue, 'ignore', 3, execaSync);80+test('Cannot pass "ipc" and another value to stdin', testInvalidArrayValue, 'ipc', 0, execa);81+test('Cannot pass "ipc" and another value to stdout', testInvalidArrayValue, 'ipc', 1, execa);82+test('Cannot pass "ipc" and another value to stderr', testInvalidArrayValue, 'ipc', 2, execa);83+test('Cannot pass "ipc" and another value to stdio[*]', testInvalidArrayValue, 'ipc', 3, execa);84+test('Cannot pass "ipc" and another value to stdin - sync', testInvalidArrayValue, 'ipc', 0, execaSync);85+test('Cannot pass "ipc" and another value to stdout - sync', testInvalidArrayValue, 'ipc', 1, execaSync);86+test('Cannot pass "ipc" and another value to stderr - sync', testInvalidArrayValue, 'ipc', 2, execaSync);87+test('Cannot pass "ipc" and another value to stdio[*] - sync', testInvalidArrayValue, 'ipc', 3, execaSync);added:test/stdio/native.js+108 added
1+import {platform} from 'node:process';2+import test from 'ava';3+import {execa} from '../../index.js';4+import {getStdio, fullStdio} from '../helpers/stdio.js';5+import {setFixtureDir} from '../helpers/fixtures-dir.js';6+7+setFixtureDir();8+9+const 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+};17+18+const isStderrDescriptor = stdioOption => stdioOption === 219+ || stdioOption === 'stderr'20+ || (Array.isArray(stdioOption) && isStderrDescriptor(stdioOption[0]));21+22+test.serial('stdio[*] can be 0', testRedirect, 0, 3, true);23+test.serial('stdio[*] can be [0]', testRedirect, [0], 3, true);24+test.serial('stdio[*] can be [0, "pipe"]', testRedirect, [0, 'pipe'], 3, true);25+test.serial('stdio[*] can be process.stdin', testRedirect, 'stdin', 3, true);26+test.serial('stdio[*] can be [process.stdin]', testRedirect, ['stdin'], 3, true);27+test.serial('stdio[*] can be [process.stdin, "pipe"]', testRedirect, ['stdin', 'pipe'], 3, true);28+test('stdout can be 2', testRedirect, 2, 1, false);29+test('stdout can be [2]', testRedirect, [2], 1, false);30+test('stdout can be [2, "pipe"]', testRedirect, [2, 'pipe'], 1, false);31+test('stdout can be process.stderr', testRedirect, 'stderr', 1, false);32+test('stdout can be [process.stderr]', testRedirect, ['stderr'], 1, false);33+test('stdout can be [process.stderr, "pipe"]', testRedirect, ['stderr', 'pipe'], 1, false);34+test('stderr can be 1', testRedirect, 1, 2, false);35+test('stderr can be [1]', testRedirect, [1], 2, false);36+test('stderr can be [1, "pipe"]', testRedirect, [1, 'pipe'], 2, false);37+test('stderr can be process.stdout', testRedirect, 'stdout', 2, false);38+test('stderr can be [process.stdout]', testRedirect, ['stdout'], 2, false);39+test('stderr can be [process.stdout, "pipe"]', testRedirect, ['stdout', 'pipe'], 2, false);40+test('stdio[*] can be 1', testRedirect, 1, 3, false);41+test('stdio[*] can be [1]', testRedirect, [1], 3, false);42+test('stdio[*] can be [1, "pipe"]', testRedirect, [1, 'pipe'], 3, false);43+test('stdio[*] can be 2', testRedirect, 2, 3, false);44+test('stdio[*] can be [2]', testRedirect, [2], 3, false);45+test('stdio[*] can be [2, "pipe"]', testRedirect, [2, 'pipe'], 3, false);46+test('stdio[*] can be process.stdout', testRedirect, 'stdout', 3, false);47+test('stdio[*] can be [process.stdout]', testRedirect, ['stdout'], 3, false);48+test('stdio[*] can be [process.stdout, "pipe"]', testRedirect, ['stdout', 'pipe'], 3, false);49+test('stdio[*] can be process.stderr', testRedirect, 'stderr', 3, false);50+test('stdio[*] can be [process.stderr]', testRedirect, ['stderr'], 3, false);51+test('stdio[*] can be [process.stderr, "pipe"]', testRedirect, ['stderr', 'pipe'], 3, false);52+53+const testInheritStdin = async (t, stdin) => {54+ const {stdout} = await execa('nested-multiple-stdin.js', [JSON.stringify(stdin)], {input: 'foobar'});55+ t.is(stdout, 'foobarfoobar');56+};57+58+test('stdin can be ["inherit", "pipe"]', testInheritStdin, ['inherit', 'pipe']);59+test('stdin can be [0, "pipe"]', testInheritStdin, [0, 'pipe']);60+61+const 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+};66+67+test('stdout can be ["inherit", "pipe"]', testInheritStdout, ['inherit', 'pipe']);68+test('stdout can be [1, "pipe"]', testInheritStdout, [1, 'pipe']);69+70+const 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+};75+76+test('stderr can be ["inherit", "pipe"]', testInheritStderr, ['inherit', 'pipe']);77+test('stderr can be [2, "pipe"]', testInheritStderr, [2, 'pipe']);78+79+const 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+};83+84+if (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+}94+95+test('stdio[*] can use "inherit"', testOverflowStream, 3, 'inherit');96+test('stdio[*] can use ["inherit"]', testOverflowStream, 3, ['inherit']);97+98+const testOverflowStreamArray = (t, index, stdioOption) => {99+ t.throws(() => {100+ execa('empty.js', getStdio(index, stdioOption));101+ }, {message: /no such standard stream/});102+};103+104+test('stdin cannot use 4+ and another value', testOverflowStreamArray, 0, [4, 'pipe']);105+test('stdout cannot use 4+ and another value', testOverflowStreamArray, 1, [4, 'pipe']);106+test('stderr cannot use 4+ and another value', testOverflowStreamArray, 2, [4, 'pipe']);107+test('stdio[*] cannot use 4+ and another value', testOverflowStreamArray, 3, [4, 'pipe']);108+test('stdio[*] cannot use "inherit" and another value', testOverflowStreamArray, 3, ['inherit', 'pipe']);deleted:test/stdio/normalize.js-45 removed
1-import {inspect} from 'node:util';2-import test from 'ava';3-import {normalizeStdio} from '../../lib/stdio/normalize.js';4-5-const macro = (t, input, expected, func) => {6- if (expected instanceof Error) {7- t.throws(() => {8- normalizeStdio(input);9- }, {message: expected.message});10- return;11- }12-13- t.deepEqual(func(input), expected);14-};15-16-const macroTitle = name => (title, input) => `${name} ${(inspect(input))}`;17-18-const stdioMacro = (...args) => macro(...args, normalizeStdio);19-stdioMacro.title = macroTitle('execa()');20-21-test(stdioMacro, {stdio: 'inherit'}, ['inherit', 'inherit', 'inherit']);22-test(stdioMacro, {stdio: 'pipe'}, ['pipe', 'pipe', 'pipe']);23-test(stdioMacro, {stdio: 'ignore'}, ['ignore', 'ignore', 'ignore']);24-test(stdioMacro, {stdio: [0, 1, 2]}, [0, 1, 2]);25-26-test(stdioMacro, {}, [undefined, undefined, undefined]);27-test(stdioMacro, {stdio: []}, [undefined, undefined, undefined]);28-test(stdioMacro, {stdin: 'pipe'}, ['pipe', undefined, undefined]);29-test(stdioMacro, {stdout: 'ignore'}, [undefined, 'ignore', undefined]);30-test(stdioMacro, {stderr: 'inherit'}, [undefined, undefined, 'inherit']);31-test(stdioMacro, {stdin: 'pipe', stdout: 'ignore', stderr: 'inherit'}, ['pipe', 'ignore', 'inherit']);32-test(stdioMacro, {stdin: 'pipe', stdout: 'ignore'}, ['pipe', 'ignore', undefined]);33-test(stdioMacro, {stdin: 'pipe', stderr: 'inherit'}, ['pipe', undefined, 'inherit']);34-test(stdioMacro, {stdout: 'ignore', stderr: 'inherit'}, [undefined, 'ignore', 'inherit']);35-test(stdioMacro, {stdin: 0, stdout: 1, stderr: 2}, [0, 1, 2]);36-test(stdioMacro, {stdin: 0, stdout: 1}, [0, 1, undefined]);37-test(stdioMacro, {stdin: 0, stderr: 2}, [0, undefined, 2]);38-test(stdioMacro, {stdout: 1, stderr: 2}, [undefined, 1, 2]);39-40-test(stdioMacro, {stdio: {foo: 'bar'}}, new TypeError('Expected `stdio` to be of type `string` or `Array`, got `object`'));41-42-test(stdioMacro, {stdin: 'inherit', stdio: 'pipe'}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`'));43-test(stdioMacro, {stdin: 'inherit', stdio: ['pipe']}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`'));44-test(stdioMacro, {stdin: 'inherit', stdio: [undefined, 'pipe']}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`'));45-test(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
1+import {inspect} from 'node:util';2+import test from 'ava';3+import {normalizeStdio} from '../../lib/stdio/option.js';4+5+const macro = (t, input, expected, func) => {6+ if (expected instanceof Error) {7+ t.throws(() => {8+ normalizeStdio(input);9+ }, {message: expected.message});10+ return;11+ }12+13+ t.deepEqual(func(input), expected);14+};15+16+const macroTitle = name => (title, input) => `${name} ${(inspect(input))}`;17+18+const stdioMacro = (...args) => macro(...args, normalizeStdio);19+stdioMacro.title = macroTitle('execa()');20+21+test(stdioMacro, {stdio: 'inherit'}, ['inherit', 'inherit', 'inherit']);22+test(stdioMacro, {stdio: 'pipe'}, ['pipe', 'pipe', 'pipe']);23+test(stdioMacro, {stdio: 'ignore'}, ['ignore', 'ignore', 'ignore']);24+test(stdioMacro, {stdio: [0, 1, 2]}, [0, 1, 2]);25+26+test(stdioMacro, {}, [undefined, undefined, undefined]);27+test(stdioMacro, {stdio: []}, [undefined, undefined, undefined]);28+test(stdioMacro, {stdin: 'pipe'}, ['pipe', undefined, undefined]);29+test(stdioMacro, {stdout: 'ignore'}, [undefined, 'ignore', undefined]);30+test(stdioMacro, {stderr: 'inherit'}, [undefined, undefined, 'inherit']);31+test(stdioMacro, {stdin: 'pipe', stdout: 'ignore', stderr: 'inherit'}, ['pipe', 'ignore', 'inherit']);32+test(stdioMacro, {stdin: 'pipe', stdout: 'ignore'}, ['pipe', 'ignore', undefined]);33+test(stdioMacro, {stdin: 'pipe', stderr: 'inherit'}, ['pipe', undefined, 'inherit']);34+test(stdioMacro, {stdout: 'ignore', stderr: 'inherit'}, [undefined, 'ignore', 'inherit']);35+test(stdioMacro, {stdin: 0, stdout: 1, stderr: 2}, [0, 1, 2]);36+test(stdioMacro, {stdin: 0, stdout: 1}, [0, 1, undefined]);37+test(stdioMacro, {stdin: 0, stderr: 2}, [0, undefined, 2]);38+test(stdioMacro, {stdout: 1, stderr: 2}, [undefined, 1, 2]);39+40+test(stdioMacro, {stdio: {foo: 'bar'}}, new TypeError('Expected `stdio` to be of type `string` or `Array`, got `object`'));41+42+test(stdioMacro, {stdin: 'inherit', stdio: 'pipe'}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`'));43+test(stdioMacro, {stdin: 'inherit', stdio: ['pipe']}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`'));44+test(stdioMacro, {stdin: 'inherit', stdio: [undefined, 'pipe']}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`'));45+test(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
1+import test from 'ava';2+import {execa} from '../../index.js';3+import {getStdio, STANDARD_STREAMS} from '../helpers/stdio.js';4+import {setFixtureDir} from '../helpers/fixtures-dir.js';5+6+setFixtureDir();7+8+const 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+};13+14+test('Does not destroy process.stdin on child process errors', testDestroyStandard, 0);15+test('Does not destroy process.stdout on child process errors', testDestroyStandard, 1);16+test('Does not destroy process.stderr on child process errors', testDestroyStandard, 2);17+18+const 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+};22+23+test('Does not destroy process.stdin on spawn process errors', testDestroyStandardSpawn, 0);24+test('Does not destroy process.stdout on spawn process errors', testDestroyStandardSpawn, 1);25+test('Does not destroy process.stderr on spawn process errors', testDestroyStandardSpawn, 2);26+27+const 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+};36+37+test('Does not destroy process.stdin on stream process errors', testDestroyStandardStream, 0);38+test('Does not destroy process.stdout on stream process errors', testDestroyStandardStream, 1);39+test('Does not destroy process.stderr on stream process errors', testDestroyStandardStream, 2);added:test/stdio/transform.js+204 added
1+import {Buffer} from 'node:buffer';2+import {once} from 'node:events';3+import {setTimeout, scheduler} from 'node:timers/promises';4+import {getDefaultHighWaterMark} from 'node:stream';5+import test from 'ava';6+import {getStreamAsArray} from 'get-stream';7+import {execa} from '../../index.js';8+import {foobarString} from '../helpers/input.js';9+import {10+ noopGenerator,11+ getOutputsGenerator,12+ getOutputGenerator,13+ infiniteGenerator,14+ outputObjectGenerator,15+ convertTransformToFinal,16+ noYieldGenerator,17+} from '../helpers/generator.js';18+import {setFixtureDir} from '../helpers/fixtures-dir.js';19+20+setFixtureDir();21+22+const testGeneratorFinal = async (t, fixtureName) => {23+ const {stdout} = await execa(fixtureName, {stdout: convertTransformToFinal(getOutputGenerator(foobarString), true)});24+ t.is(stdout, foobarString);25+};26+27+test('Generators "final" can be used', testGeneratorFinal, 'noop.js');28+test('Generators "final" is used even on empty streams', testGeneratorFinal, 'empty.js');29+30+const repeatCount = getDefaultHighWaterMark() * 3;31+32+const writerGenerator = function * () {33+ for (let index = 0; index < repeatCount; index += 1) {34+ yield '\n';35+ }36+};37+38+const getLengthGenerator = function * (t, chunk) {39+ t.is(chunk.length, 1);40+ yield chunk;41+};42+43+const 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+};55+56+test('Synchronous yields are not buffered, no passThrough', testHighWaterMark, false, false, false);57+test('Synchronous yields are not buffered, line-wise passThrough', testHighWaterMark, true, false, false);58+test('Synchronous yields are not buffered, binary passThrough', testHighWaterMark, true, true, false);59+test('Synchronous yields are not buffered, objectMode as input but not output', testHighWaterMark, false, false, true);60+61+const testNoYield = async (t, objectMode, final, output) => {62+ const {stdout} = await execa('noop.js', {stdout: convertTransformToFinal(noYieldGenerator(objectMode), final)});63+ t.deepEqual(stdout, output);64+};65+66+test('Generator can filter "transform" by not calling yield', testNoYield, false, false, '');67+test('Generator can filter "transform" by not calling yield, objectMode', testNoYield, true, false, []);68+test('Generator can filter "final" by not calling yield', testNoYield, false, false, '');69+test('Generator can filter "final" by not calling yield, objectMode', testNoYield, true, false, []);70+71+const prefix = '> ';72+const suffix = ' <';73+74+const multipleYieldGenerator = async function * (line = foobarString) {75+ yield prefix;76+ await scheduler.yield();77+ yield line;78+ await scheduler.yield();79+ yield suffix;80+};81+82+const 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+};86+87+test('Generator can yield "transform" multiple times at different moments', testMultipleYields, false);88+test('Generator can yield "final" multiple times at different moments', testMultipleYields, true);89+90+const partsPerChunk = 4;91+const chunksPerCall = 10;92+const callCount = 5;93+const fullString = '\n'.repeat(getDefaultHighWaterMark(false) / partsPerChunk);94+95+const yieldFullStrings = function * () {96+ yield * Array.from({length: partsPerChunk * chunksPerCall}).fill(fullString);97+};98+99+const 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+};106+107+const 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+};113+114+test('Generator "transform" yields are sent right away', testManyYields, false);115+test('Generator "final" yields are sent right away', testManyYields, true);116+117+const maxBuffer = 10;118+119+test('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);123+124+ await t.throwsAsync(execa('noop.js', {maxBuffer, stdout: getOutputGenerator(`${bigString}.`, false)}));125+});126+127+test('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);131+132+ await t.throwsAsync(execa('noop.js', {maxBuffer, stdout: getOutputsGenerator([...bigArray, ''], true)}));133+});134+135+const timeoutGenerator = async function * (timeout) {136+ await setTimeout(timeout);137+ yield foobarString;138+};139+140+const 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+};147+148+test('Generators "transform" is awaited on success', testAsyncGenerators, false);149+test('Generators "final" is awaited on success', testAsyncGenerators, true);150+151+// eslint-disable-next-line require-yield152+const throwingGenerator = function * () {153+ throw new Error('Generator error');154+};155+156+const GENERATOR_ERROR_REGEXP = /Generator error/;157+158+const 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+};164+165+test('Generators "transform" errors make process fail', testThrowingGenerator, false);166+test('Generators "final" errors make process fail', testThrowingGenerator, true);167+168+test('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+});174+175+test('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+});180+181+const 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+};187+188+test('Running generators are canceled on process abort', testGeneratorCancel, undefined);189+test('Running generators are canceled on process error', testGeneratorCancel, new Error('test'));190+191+const 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+};198+199+test('Generators are destroyed on process error, sync', testGeneratorDestroy, noopGenerator(false));200+test('Generators are destroyed on process error, async', testGeneratorDestroy, infiniteGenerator);201+202+test('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
1+import test from 'ava';2+import {execa, execaSync} from '../../index.js';3+import {getStdio} from '../helpers/stdio.js';4+import {noopGenerator} from '../helpers/generator.js';5+import {setFixtureDir} from '../helpers/fixtures-dir.js';6+7+setFixtureDir();8+9+const uppercaseGenerator = function * (line) {10+ yield line.toUpperCase();11+};12+13+const testInvalidGenerator = (t, index, stdioOption) => {14+ t.throws(() => {15+ execa('empty.js', getStdio(index, {...noopGenerator(), ...stdioOption}));16+ }, {message: /must be a generator/});17+};18+19+test('Cannot use invalid "transform" with stdin', testInvalidGenerator, 0, {transform: true});20+test('Cannot use invalid "transform" with stdout', testInvalidGenerator, 1, {transform: true});21+test('Cannot use invalid "transform" with stderr', testInvalidGenerator, 2, {transform: true});22+test('Cannot use invalid "transform" with stdio[*]', testInvalidGenerator, 3, {transform: true});23+test('Cannot use invalid "final" with stdin', testInvalidGenerator, 0, {final: true});24+test('Cannot use invalid "final" with stdout', testInvalidGenerator, 1, {final: true});25+test('Cannot use invalid "final" with stderr', testInvalidGenerator, 2, {final: true});26+test('Cannot use invalid "final" with stdio[*]', testInvalidGenerator, 3, {final: true});27+28+const testInvalidBinary = (t, index, optionName) => {29+ t.throws(() => {30+ execa('empty.js', getStdio(index, {transform: uppercaseGenerator, [optionName]: 'true'}));31+ }, {message: /a boolean/});32+};33+34+test('Cannot use invalid "binary" with stdin', testInvalidBinary, 0, 'binary');35+test('Cannot use invalid "binary" with stdout', testInvalidBinary, 1, 'binary');36+test('Cannot use invalid "binary" with stderr', testInvalidBinary, 2, 'binary');37+test('Cannot use invalid "binary" with stdio[*]', testInvalidBinary, 3, 'binary');38+test('Cannot use invalid "objectMode" with stdin', testInvalidBinary, 0, 'objectMode');39+test('Cannot use invalid "objectMode" with stdout', testInvalidBinary, 1, 'objectMode');40+test('Cannot use invalid "objectMode" with stderr', testInvalidBinary, 2, 'objectMode');41+test('Cannot use invalid "objectMode" with stdio[*]', testInvalidBinary, 3, 'objectMode');42+43+const testSyncMethods = (t, index) => {44+ t.throws(() => {45+ execaSync('empty.js', getStdio(index, uppercaseGenerator));46+ }, {message: /cannot be a generator/});47+};48+49+test('Cannot use generators with sync methods and stdin', testSyncMethods, 0);50+test('Cannot use generators with sync methods and stdout', testSyncMethods, 1);51+test('Cannot use generators with sync methods and stderr', testSyncMethods, 2);52+test('Cannot use generators with sync methods and stdio[*]', testSyncMethods, 3);added:test/stdio/validate.js+39 added
1+import test from 'ava';2+import {execa} from '../../index.js';3+import {setFixtureDir} from '../helpers/fixtures-dir.js';4+import {getStdio} from '../helpers/stdio.js';5+import {foobarUint8Array, foobarObject} from '../helpers/input.js';6+import {serializeGenerator, getOutputGenerator, convertTransformToFinal} from '../helpers/generator.js';7+8+setFixtureDir();9+10+// eslint-disable-next-line max-params11+const 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+};16+17+const lastInputGenerator = (input, objectMode) => [foobarUint8Array, getOutputGenerator(input, objectMode)];18+const inputGenerator = (input, objectMode) => [...lastInputGenerator(input, objectMode), serializeGenerator];19+20+test('Generators with result.stdin cannot return an object if not in objectMode', testGeneratorReturn, 0, inputGenerator(foobarObject, false), 'stdin-fd.js', false);21+test('Generators with result.stdio[*] as input cannot return an object if not in objectMode', testGeneratorReturn, 3, inputGenerator(foobarObject, false), 'stdin-fd.js', false);22+test('The last generator with result.stdin cannot return an object even in objectMode', testGeneratorReturn, 0, lastInputGenerator(foobarObject, true), 'stdin-fd.js', false);23+test('The last generator with result.stdio[*] as input cannot return an object even in objectMode', testGeneratorReturn, 3, lastInputGenerator(foobarObject, true), 'stdin-fd.js', false);24+test('Generators with result.stdout cannot return an object if not in objectMode', testGeneratorReturn, 1, getOutputGenerator(foobarObject, false), 'noop-fd.js', false);25+test('Generators with result.stderr cannot return an object if not in objectMode', testGeneratorReturn, 2, getOutputGenerator(foobarObject, false), 'noop-fd.js', false);26+test('Generators with result.stdio[*] as output cannot return an object if not in objectMode', testGeneratorReturn, 3, getOutputGenerator(foobarObject, false), 'noop-fd.js', false);27+test('Generators with result.stdin cannot return null if not in objectMode', testGeneratorReturn, 0, inputGenerator(null, false), 'stdin-fd.js', true);28+test('Generators with result.stdin cannot return null if in objectMode', testGeneratorReturn, 0, inputGenerator(null, true), 'stdin-fd.js', true);29+test('Generators with result.stdout cannot return null if not in objectMode', testGeneratorReturn, 1, getOutputGenerator(null, false), 'noop-fd.js', true);30+test('Generators with result.stdout cannot return null if in objectMode', testGeneratorReturn, 1, getOutputGenerator(null, true), 'noop-fd.js', true);31+test('Generators with result.stdin cannot return undefined if not in objectMode', testGeneratorReturn, 0, inputGenerator(undefined, false), 'stdin-fd.js', true);32+test('Generators with result.stdin cannot return undefined if in objectMode', testGeneratorReturn, 0, inputGenerator(undefined, true), 'stdin-fd.js', true);33+test('Generators with result.stdout cannot return undefined if not in objectMode', testGeneratorReturn, 1, getOutputGenerator(undefined, false), 'noop-fd.js', true);34+test('Generators with result.stdout cannot return undefined if in objectMode', testGeneratorReturn, 1, getOutputGenerator(undefined, true), 'noop-fd.js', true);35+36+test('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
1-import {platform} from 'node:process';2-import {setImmediate} from 'node:timers/promises';3-import test from 'ava';4-import {execa} from '../../index.js';5-import {setFixtureDir} from '../helpers/fixtures-dir.js';6-import {getStdio, prematureClose} from '../helpers/stdio.js';7-import {foobarString} from '../helpers/input.js';8-import {noopGenerator} from '../helpers/generator.js';9-import {noopReadable, noopWritable, noopDuplex} from '../helpers/stream.js';10-11-setFixtureDir();12-13-const isWindows = platform === 'win32';14-15-const noop = () => {};16-17-const endOptionStream = ({stream}) => {18- stream.end();19-};20-21-const destroyOptionStream = ({stream, error}) => {22- stream.destroy(error);23-};24-25-const destroyChildStream = ({childProcess, index, error}) => {26- childProcess.stdio[index].destroy(error);27-};28-29-const getStreamStdio = (index, stream, useTransform) => getStdio(index, [stream, useTransform ? noopGenerator(false) : 'pipe']);30-31-// eslint-disable-next-line max-params32-const 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();38-39- const {stdout} = await childProcess;40- t.is(stdout, '');41- t.true(stream.destroyed);42-};43-44-test('Keeps running when stdin option is used and childProcess.stdin ends', testStreamAbortWait, noop, noopReadable(), 0, false);45-test('Keeps running when stdin option is used and childProcess.stdin Duplex ends', testStreamAbortWait, noop, noopDuplex(), 0, false);46-test('Keeps running when input stdio[*] option is used and input childProcess.stdio[*] ends', testStreamAbortWait, noop, noopReadable(), 3, false);47-test('Keeps running when stdin option is used and childProcess.stdin ends, with a transform', testStreamAbortWait, noop, noopReadable(), 0, true);48-test('Keeps running when stdin option is used and childProcess.stdin Duplex ends, with a transform', testStreamAbortWait, noop, noopDuplex(), 0, true);49-test('Keeps running when input stdio[*] option is used and input childProcess.stdio[*] ends, with a transform', testStreamAbortWait, noop, noopReadable(), 3, true);50-51-// eslint-disable-next-line max-params52-const 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();56-57- const {stdout} = await childProcess;58- t.is(stdout, '');59- t.true(stream.destroyed);60-};61-62-test('Passes when stdin option aborts', testStreamAbortSuccess, destroyOptionStream, noopReadable(), 0, false);63-test('Passes when stdin option Duplex aborts', testStreamAbortSuccess, destroyOptionStream, noopDuplex(), 0, false);64-test('Passes when input stdio[*] option aborts', testStreamAbortSuccess, destroyOptionStream, noopReadable(), 3, false);65-test('Passes when stdout option ends with no more writes', testStreamAbortSuccess, endOptionStream, noopWritable(), 1, false);66-test('Passes when stderr option ends with no more writes', testStreamAbortSuccess, endOptionStream, noopWritable(), 2, false);67-test('Passes when output stdio[*] option ends with no more writes', testStreamAbortSuccess, endOptionStream, noopWritable(), 3, false);68-test('Passes when childProcess.stdout aborts with no more writes', testStreamAbortSuccess, destroyChildStream, noopWritable(), 1, false);69-test('Passes when childProcess.stdout Duplex aborts with no more writes', testStreamAbortSuccess, destroyChildStream, noopDuplex(), 1, false);70-test('Passes when childProcess.stderr aborts with no more writes', testStreamAbortSuccess, destroyChildStream, noopWritable(), 2, false);71-test('Passes when childProcess.stderr Duplex aborts with no more writes', testStreamAbortSuccess, destroyChildStream, noopDuplex(), 2, false);72-test('Passes when output childProcess.stdio[*] aborts with no more writes', testStreamAbortSuccess, destroyChildStream, noopWritable(), 3, false);73-test('Passes when output childProcess.stdio[*] Duplex aborts with no more writes', testStreamAbortSuccess, destroyChildStream, noopDuplex(), 3, false);74-test('Passes when stdin option aborts, with a transform', testStreamAbortSuccess, destroyOptionStream, noopReadable(), 0, true);75-test('Passes when stdin option Duplex aborts, with a transform', testStreamAbortSuccess, destroyOptionStream, noopDuplex(), 0, true);76-test('Passes when input stdio[*] option aborts, with a transform', testStreamAbortSuccess, destroyOptionStream, noopReadable(), 3, true);77-test('Passes when stdout option ends with no more writes, with a transform', testStreamAbortSuccess, endOptionStream, noopWritable(), 1, true);78-test('Passes when stderr option ends with no more writes, with a transform', testStreamAbortSuccess, endOptionStream, noopWritable(), 2, true);79-test('Passes when output stdio[*] option ends with no more writes, with a transform', testStreamAbortSuccess, endOptionStream, noopWritable(), 3, true);80-test('Passes when childProcess.stdout aborts with no more writes, with a transform', testStreamAbortSuccess, destroyChildStream, noopWritable(), 1, true);81-test('Passes when childProcess.stdout Duplex aborts with no more writes, with a transform', testStreamAbortSuccess, destroyChildStream, noopDuplex(), 1, true);82-test('Passes when childProcess.stderr aborts with no more writes, with a transform', testStreamAbortSuccess, destroyChildStream, noopWritable(), 2, true);83-test('Passes when childProcess.stderr Duplex aborts with no more writes, with a transform', testStreamAbortSuccess, destroyChildStream, noopDuplex(), 2, true);84-test('Passes when output childProcess.stdio[*] aborts with no more writes, with a transform', testStreamAbortSuccess, destroyChildStream, noopWritable(), 3, true);85-test('Passes when output childProcess.stdio[*] Duplex aborts with no more writes, with a transform', testStreamAbortSuccess, destroyChildStream, noopDuplex(), 3, true);86-87-// eslint-disable-next-line max-params88-const 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- }94-95- const error = await t.throwsAsync(childProcess);96- t.like(error, {...prematureClose, exitCode: 0});97- t.true(stream.destroyed);98-};99-100-test('Throws abort error when childProcess.stdin aborts', testStreamAbortFail, destroyChildStream, noopReadable(), 0, false);101-test('Throws abort error when childProcess.stdin Duplex aborts', testStreamAbortFail, destroyChildStream, noopDuplex(), 0, false);102-test('Throws abort error when input childProcess.stdio[*] aborts', testStreamAbortFail, destroyChildStream, noopReadable(), 3, false);103-test('Throws abort error when stdout option aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopWritable(), 1, false);104-test('Throws abort error when stdout option Duplex aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopDuplex(), 1, false);105-test('Throws abort error when stderr option aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopWritable(), 2, false);106-test('Throws abort error when stderr option Duplex aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopDuplex(), 2, false);107-test('Throws abort error when output stdio[*] option aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopWritable(), 3, false);108-test('Throws abort error when output stdio[*] Duplex option aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopDuplex(), 3, false);109-test('Throws abort error when childProcess.stdin aborts, with a transform', testStreamAbortFail, destroyChildStream, noopReadable(), 0, true);110-test('Throws abort error when childProcess.stdin Duplex aborts, with a transform', testStreamAbortFail, destroyChildStream, noopDuplex(), 0, true);111-test('Throws abort error when input childProcess.stdio[*] aborts, with a transform', testStreamAbortFail, destroyChildStream, noopReadable(), 3, true);112-test('Throws abort error when stdout option aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopWritable(), 1, true);113-test('Throws abort error when stdout option Duplex aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopDuplex(), 1, true);114-test('Throws abort error when stderr option aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopWritable(), 2, true);115-test('Throws abort error when stderr option Duplex aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopDuplex(), 2, true);116-test('Throws abort error when output stdio[*] option aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopWritable(), 3, true);117-test('Throws abort error when output stdio[*] Duplex option aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopDuplex(), 3, true);118-119-// eslint-disable-next-line max-params120-const 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);124-125- const {stdio} = await childProcess;126- t.is(stdio[index], foobarString);127- t.true(stream.destroyed);128-};129-130-test('Passes when stdout option ends with more writes', testStreamEpipeSuccess, endOptionStream, noopWritable(), 1, false);131-test('Passes when stderr option ends with more writes', testStreamEpipeSuccess, endOptionStream, noopWritable(), 2, false);132-test('Passes when output stdio[*] option ends with more writes', testStreamEpipeSuccess, endOptionStream, noopWritable(), 3, false);133-test('Passes when stdout option ends with more writes, with a transform', testStreamEpipeSuccess, endOptionStream, noopWritable(), 1, true);134-test('Passes when stderr option ends with more writes, with a transform', testStreamEpipeSuccess, endOptionStream, noopWritable(), 2, true);135-test('Passes when output stdio[*] option ends with more writes, with a transform', testStreamEpipeSuccess, endOptionStream, noopWritable(), 3, true);136-137-// eslint-disable-next-line max-params138-const 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);143-144- 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-};152-153-test('Throws EPIPE when stdout option aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopWritable(), 1, false);154-test('Throws EPIPE when stdout option Duplex aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 1, false);155-test('Throws EPIPE when stderr option aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopWritable(), 2, false);156-test('Throws EPIPE when stderr option Duplex aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 2, false);157-test('Throws EPIPE when output stdio[*] option aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopWritable(), 3, false);158-test('Throws EPIPE when output stdio[*] option Duplex aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 3, false);159-test('Throws EPIPE when childProcess.stdout aborts with more writes', testStreamEpipeFail, destroyChildStream, noopWritable(), 1, false);160-test('Throws EPIPE when childProcess.stdout Duplex aborts with more writes', testStreamEpipeFail, destroyChildStream, noopDuplex(), 1, false);161-test('Throws EPIPE when childProcess.stderr aborts with more writes', testStreamEpipeFail, destroyChildStream, noopWritable(), 2, false);162-test('Throws EPIPE when childProcess.stderr Duplex aborts with more writes', testStreamEpipeFail, destroyChildStream, noopDuplex(), 2, false);163-test('Throws EPIPE when output childProcess.stdio[*] aborts with more writes', testStreamEpipeFail, destroyChildStream, noopWritable(), 3, false);164-test('Throws EPIPE when output childProcess.stdio[*] Duplex aborts with more writes', testStreamEpipeFail, destroyChildStream, noopDuplex(), 3, false);165-test('Throws EPIPE when stdout option aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopWritable(), 1, true);166-test('Throws EPIPE when stdout option Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 1, true);167-test('Throws EPIPE when stderr option aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopWritable(), 2, true);168-test('Throws EPIPE when stderr option Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 2, true);169-test('Throws EPIPE when output stdio[*] option aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopWritable(), 3, true);170-test('Throws EPIPE when output stdio[*] option Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 3, true);171-test('Throws EPIPE when childProcess.stdout aborts with more writes, with a transform', testStreamEpipeFail, destroyChildStream, noopWritable(), 1, true);172-test('Throws EPIPE when childProcess.stdout Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroyChildStream, noopDuplex(), 1, true);173-test('Throws EPIPE when childProcess.stderr aborts with more writes, with a transform', testStreamEpipeFail, destroyChildStream, noopWritable(), 2, true);174-test('Throws EPIPE when childProcess.stderr Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroyChildStream, noopDuplex(), 2, true);175-test('Throws EPIPE when output childProcess.stdio[*] aborts with more writes, with a transform', testStreamEpipeFail, destroyChildStream, noopWritable(), 3, true);176-test('Throws EPIPE when output childProcess.stdio[*] Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroyChildStream, noopDuplex(), 3, true);177-178-// eslint-disable-next-line max-params179-const 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});183-184- 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-};192-193-test('Throws stream error when stdin option errors', testStreamError, destroyOptionStream, noopReadable(), 0, false);194-test('Throws stream error when stdin option Duplex errors', testStreamError, destroyOptionStream, noopDuplex(), 0, false);195-test('Throws stream error when stdout option errors', testStreamError, destroyOptionStream, noopWritable(), 1, false);196-test('Throws stream error when stdout option Duplex errors', testStreamError, destroyOptionStream, noopDuplex(), 1, false);197-test('Throws stream error when stderr option errors', testStreamError, destroyOptionStream, noopWritable(), 2, false);198-test('Throws stream error when stderr option Duplex errors', testStreamError, destroyOptionStream, noopDuplex(), 2, false);199-test('Throws stream error when output stdio[*] option errors', testStreamError, destroyOptionStream, noopWritable(), 3, false);200-test('Throws stream error when output stdio[*] Duplex option errors', testStreamError, destroyOptionStream, noopDuplex(), 3, false);201-test('Throws stream error when input stdio[*] option errors', testStreamError, destroyOptionStream, noopReadable(), 3, false);202-test('Throws stream error when childProcess.stdin errors', testStreamError, destroyChildStream, noopReadable(), 0, false);203-test('Throws stream error when childProcess.stdin Duplex errors', testStreamError, destroyChildStream, noopDuplex(), 0, false);204-test('Throws stream error when childProcess.stdout errors', testStreamError, destroyChildStream, noopWritable(), 1, false);205-test('Throws stream error when childProcess.stdout Duplex errors', testStreamError, destroyChildStream, noopDuplex(), 1, false);206-test('Throws stream error when childProcess.stderr errors', testStreamError, destroyChildStream, noopWritable(), 2, false);207-test('Throws stream error when childProcess.stderr Duplex errors', testStreamError, destroyChildStream, noopDuplex(), 2, false);208-test('Throws stream error when output childProcess.stdio[*] errors', testStreamError, destroyChildStream, noopWritable(), 3, false);209-test('Throws stream error when output childProcess.stdio[*] Duplex errors', testStreamError, destroyChildStream, noopDuplex(), 3, false);210-test('Throws stream error when input childProcess.stdio[*] errors', testStreamError, destroyChildStream, noopReadable(), 3, false);211-test('Throws stream error when stdin option errors, with a transform', testStreamError, destroyOptionStream, noopReadable(), 0, true);212-test('Throws stream error when stdin option Duplex errors, with a transform', testStreamError, destroyOptionStream, noopDuplex(), 0, true);213-test('Throws stream error when stdout option errors, with a transform', testStreamError, destroyOptionStream, noopWritable(), 1, true);214-test('Throws stream error when stdout option Duplex errors, with a transform', testStreamError, destroyOptionStream, noopDuplex(), 1, true);215-test('Throws stream error when stderr option errors, with a transform', testStreamError, destroyOptionStream, noopWritable(), 2, true);216-test('Throws stream error when stderr option Duplex errors, with a transform', testStreamError, destroyOptionStream, noopDuplex(), 2, true);217-test('Throws stream error when output stdio[*] option errors, with a transform', testStreamError, destroyOptionStream, noopWritable(), 3, true);218-test('Throws stream error when output stdio[*] Duplex option errors, with a transform', testStreamError, destroyOptionStream, noopDuplex(), 3, true);219-test('Throws stream error when input stdio[*] option errors, with a transform', testStreamError, destroyOptionStream, noopReadable(), 3, true);220-test('Throws stream error when childProcess.stdin errors, with a transform', testStreamError, destroyChildStream, noopReadable(), 0, true);221-test('Throws stream error when childProcess.stdin Duplex errors, with a transform', testStreamError, destroyChildStream, noopDuplex(), 0, true);222-test('Throws stream error when childProcess.stdout errors, with a transform', testStreamError, destroyChildStream, noopWritable(), 1, true);223-test('Throws stream error when childProcess.stdout Duplex errors, with a transform', testStreamError, destroyChildStream, noopDuplex(), 1, true);224-test('Throws stream error when childProcess.stderr errors, with a transform', testStreamError, destroyChildStream, noopWritable(), 2, true);225-test('Throws stream error when childProcess.stderr Duplex errors, with a transform', testStreamError, destroyChildStream, noopDuplex(), 2, true);226-test('Throws stream error when output childProcess.stdio[*] errors, with a transform', testStreamError, destroyChildStream, noopWritable(), 3, true);227-test('Throws stream error when output childProcess.stdio[*] Duplex errors, with a transform', testStreamError, destroyChildStream, noopDuplex(), 3, true);228-test('Throws stream error when input childProcess.stdio[*] errors, with a transform', testStreamError, destroyChildStream, noopReadable(), 3, true);added:test/stream/all.js+61 added
1+import {getDefaultHighWaterMark} from 'node:stream';2+import test from 'ava';3+import {execa} from '../../index.js';4+import {setFixtureDir} from '../helpers/fixtures-dir.js';5+6+setFixtureDir();7+8+test.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+});12+13+test('result.all is undefined unless opts.all is true', async t => {14+ const {all} = await execa('noop.js');15+ t.is(all, undefined);16+});17+18+test('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+});22+23+const 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+};29+30+test('childProcess.all has the right objectMode and highWaterMark - stdout + stderr', testAllProperties, {});31+test('childProcess.all has the right objectMode and highWaterMark - stdout only', testAllProperties, {stderr: 'ignore'});32+test('childProcess.all has the right objectMode and highWaterMark - stderr only', testAllProperties, {stdout: 'ignore'});33+34+const 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);41+42+ const result = await childProcess;43+ t.is(result[otherStreamName], undefined);44+ t.is(result[streamName], 'foobar');45+ t.is(result.all, 'foobar');46+};47+48+test('can use all: true with stdout: ignore', testAllIgnore, 'stderr', 'stdout');49+test('can use all: true with stderr: ignore', testAllIgnore, 'stdout', 'stderr');50+51+test('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);56+57+ 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
1+import {platform} from 'node:process';2+import {setTimeout} from 'node:timers/promises';3+import test from 'ava';4+import {execa} from '../../index.js';5+import {setFixtureDir} from '../helpers/fixtures-dir.js';6+import {fullStdio, getStdio, prematureClose} from '../helpers/stdio.js';7+import {infiniteGenerator} from '../helpers/generator.js';8+9+setFixtureDir();10+11+const isWindows = platform === 'win32';12+13+const getStreamInputProcess = index => execa('stdin-fd.js', [`${index}`], index === 314+ ? getStdio(3, [new Uint8Array(), infiniteGenerator])15+ : {});16+const getStreamOutputProcess = index => execa('noop-repeat.js', [`${index}`], index === 3 ? fullStdio : {});17+18+const 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+};24+25+const assertStreamOutputError = (t, index, {exitCode, signal, isTerminated, failed, stderr}) => {26+ if (index !== 3) {27+ t.is(exitCode, 1);28+ }29+30+ t.is(signal, undefined);31+ t.false(isTerminated);32+ t.true(failed);33+34+ if (index === 1 && !isWindows) {35+ t.true(stderr.includes('EPIPE'));36+ }37+};38+39+const 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+};45+46+test('Aborting stdin should not make the process exit', testStreamInputAbort, 0);47+test('Aborting input stdio[*] should not make the process exit', testStreamInputAbort, 3);48+49+const 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+};55+56+test('Aborting stdout should not make the process exit', testStreamOutputAbort, 1);57+test('Aborting stderr should not make the process exit', testStreamOutputAbort, 2);58+test('Aborting output stdio[*] should not make the process exit', testStreamOutputAbort, 3);59+60+const 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+};67+68+test('Destroying stdin should not make the process exit', testStreamInputDestroy, 0);69+test('Destroying input stdio[*] should not make the process exit', testStreamInputDestroy, 3);70+71+const 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+};78+79+test('Destroying stdout should not make the process exit', testStreamOutputDestroy, 1);80+test('Destroying stderr should not make the process exit', testStreamOutputDestroy, 2);81+test('Destroying output stdio[*] should not make the process exit', testStreamOutputDestroy, 3);82+83+const 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+};92+93+test('Errors on stdin should not make the process exit', testStreamInputError, 0);94+test('Errors on input stdio[*] should not make the process exit', testStreamInputError, 3);95+96+const 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+};104+105+test('Errors on stdout should not make the process exit', testStreamOutputError, 1);106+test('Errors on stderr should not make the process exit', testStreamOutputError, 2);107+test('Errors on output stdio[*] should not make the process exit', testStreamOutputError, 3);108+109+const 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+};116+117+test('Process waits on stdin before exiting', testWaitOnStreamEnd, 0);118+test('Process waits on stdio[*] before exiting', testWaitOnStreamEnd, 3);added:test/stream/exit.js+78 added
1+import {once} from 'node:events';2+import {setTimeout} from 'node:timers/promises';3+import test from 'ava';4+import {execa} from '../../index.js';5+import {setFixtureDir} from '../helpers/fixtures-dir.js';6+import {fullStdio, getStdio} from '../helpers/stdio.js';7+8+setFixtureDir();9+10+const testBufferIgnore = async (t, index, all) => {11+ await t.notThrowsAsync(execa('max-buffer.js', [`${index}`], {...getStdio(index, 'ignore'), buffer: false, all}));12+};13+14+test('Process buffers stdout, which does not prevent exit if ignored', testBufferIgnore, 1, false);15+test('Process buffers stderr, which does not prevent exit if ignored', testBufferIgnore, 2, false);16+test('Process buffers all, which does not prevent exit if ignored', testBufferIgnore, 1, true);17+18+const testBufferNotRead = async (t, index, all) => {19+ const subprocess = execa('max-buffer.js', [`${index}`], {...fullStdio, buffer: false, all});20+ await t.notThrowsAsync(subprocess);21+};22+23+test('Process buffers stdout, which does not prevent exit if not read and buffer is false', testBufferNotRead, 1, false);24+test('Process buffers stderr, which does not prevent exit if not read and buffer is false', testBufferNotRead, 2, false);25+test('Process buffers stdio[*], which does not prevent exit if not read and buffer is false', testBufferNotRead, 3, false);26+test('Process buffers all, which does not prevent exit if not read and buffer is false', testBufferNotRead, 1, true);27+28+const 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+};34+35+test('Process buffers stdout, which does not prevent exit if read and buffer is false', testBufferRead, 1, false);36+test('Process buffers stderr, which does not prevent exit if read and buffer is false', testBufferRead, 2, false);37+test('Process buffers stdio[*], which does not prevent exit if read and buffer is false', testBufferRead, 3, false);38+test('Process buffers all, which does not prevent exit if read and buffer is false', testBufferRead, 1, true);39+40+const 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+};46+47+test('Process buffers stdout before it is read', testBufferExit, 1, 'noop-delay.js', true);48+test('Process buffers stderr before it is read', testBufferExit, 2, 'noop-delay.js', true);49+test('Process buffers stdio[*] before it is read', testBufferExit, 3, 'noop-delay.js', true);50+test('Process buffers stdout right away, on successfully exit', testBufferExit, 1, 'noop-fd.js', true);51+test('Process buffers stderr right away, on successfully exit', testBufferExit, 2, 'noop-fd.js', true);52+test('Process buffers stdio[*] right away, on successfully exit', testBufferExit, 3, 'noop-fd.js', true);53+test('Process buffers stdout right away, on failure', testBufferExit, 1, 'noop-fail.js', false);54+test('Process buffers stderr right away, on failure', testBufferExit, 2, 'noop-fail.js', false);55+test('Process buffers stdio[*] right away, on failure', testBufferExit, 3, 'noop-fail.js', false);56+57+const 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+};64+65+test('Process buffers stdout right away, even if directly read', testBufferDirect, 1);66+test('Process buffers stderr right away, even if directly read', testBufferDirect, 2);67+test('Process buffers stdio[*] right away, even if directly read', testBufferDirect, 3);68+69+const 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+};75+76+test('childProcess.stdout must be read right away', testBufferDestroyOnEnd, 1);77+test('childProcess.stderr must be read right away', testBufferDestroyOnEnd, 2);78+test('childProcess.stdio[*] must be read right away', testBufferDestroyOnEnd, 3);added:test/stream/max-buffer.js+108 added
1+import {Buffer} from 'node:buffer';2+import test from 'ava';3+import getStream from 'get-stream';4+import {execa} from '../../index.js';5+import {setFixtureDir} from '../helpers/fixtures-dir.js';6+import {fullStdio} from '../helpers/stdio.js';7+8+setFixtureDir();9+10+const maxBuffer = 10;11+12+const testMaxBufferSuccess = async (t, index, all) => {13+ await t.notThrowsAsync(execa('max-buffer.js', [`${index}`, `${maxBuffer}`], {...fullStdio, maxBuffer, all}));14+};15+16+test('maxBuffer does not affect stdout if too high', testMaxBufferSuccess, 1, false);17+test('maxBuffer does not affect stderr if too high', testMaxBufferSuccess, 2, false);18+test('maxBuffer does not affect stdio[*] if too high', testMaxBufferSuccess, 3, false);19+test('maxBuffer does not affect all if too high', testMaxBufferSuccess, 1, true);20+21+test('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+});29+30+const 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+};38+39+test('maxBuffer affects stdout', testMaxBufferLimit, 1, false);40+test('maxBuffer affects stderr', testMaxBufferLimit, 2, false);41+test('maxBuffer affects stdio[*]', testMaxBufferLimit, 3, false);42+test('maxBuffer affects all', testMaxBufferLimit, 1, true);43+44+const 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+};52+53+test('maxBuffer works with encoding buffer and stdout', testMaxBufferEncoding, 1);54+test('maxBuffer works with encoding buffer and stderr', testMaxBufferEncoding, 2);55+test('maxBuffer works with encoding buffer and stdio[*]', testMaxBufferEncoding, 3);56+57+const 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+};64+65+test('maxBuffer works with other encodings and stdout', testMaxBufferHex, 1);66+test('maxBuffer works with other encodings and stderr', testMaxBufferHex, 2);67+test('maxBuffer works with other encodings and stdio[*]', testMaxBufferHex, 3);68+69+const 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+};78+79+test('do not buffer stdout when `buffer` set to `false`', testNoMaxBuffer, 1);80+test('do not buffer stderr when `buffer` set to `false`', testNoMaxBuffer, 2);81+test('do not buffer stdio[*] when `buffer` set to `false`', testNoMaxBuffer, 3);82+83+const 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+};93+94+test('do not hit maxBuffer when `buffer` is `false` with stdout', testNoMaxBufferOption, 1);95+test('do not hit maxBuffer when `buffer` is `false` with stderr', testNoMaxBufferOption, 2);96+test('do not hit maxBuffer when `buffer` is `false` with stdio[*]', testNoMaxBufferOption, 3);97+98+const 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+};105+106+test('abort stream when hitting maxBuffer with stdout', testMaxBufferAbort, 1);107+test('abort stream when hitting maxBuffer with stderr', testMaxBufferAbort, 2);108+test('abort stream when hitting maxBuffer with stdio[*]', testMaxBufferAbort, 3);added:test/stream/no-buffer.js+111 added
1+import {once} from 'node:events';2+import test from 'ava';3+import getStream from 'get-stream';4+import {execa} from '../../index.js';5+import {setFixtureDir} from '../helpers/fixtures-dir.js';6+import {fullStdio, getStdio} from '../helpers/stdio.js';7+import {foobarString} from '../helpers/input.js';8+9+setFixtureDir();10+11+const 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+ ]);19+20+ t.is(output, '');21+22+ if (all) {23+ t.is(allOutput, '');24+ }25+};26+27+test('Lacks some data when stdout is read too late `buffer` set to `false`', testLateStream, 1, false);28+test('Lacks some data when stderr is read too late `buffer` set to `false`', testLateStream, 2, false);29+test('Lacks some data when stdio[*] is read too late `buffer` set to `false`', testLateStream, 3, false);30+test('Lacks some data when all is read too late `buffer` set to `false`', testLateStream, 1, true);31+32+const getFirstDataEvent = async stream => {33+ const [output] = await once(stream, 'data');34+ return output.toString();35+};36+37+// eslint-disable-next-line max-params38+const 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+ ]);46+47+ const expectedProcessResult = buffer ? foobarString : undefined;48+ const expectedOutput = !buffer || useDataEvents ? foobarString : '';49+50+ t.is(result.stdio[index], expectedProcessResult);51+ t.is(output, expectedOutput);52+53+ if (all) {54+ t.is(result.all, expectedProcessResult);55+ t.is(allOutput, expectedOutput);56+ }57+};58+59+test('Can iterate stdout when `buffer` set to `false`', testIterationBuffer, 1, false, false, false);60+test('Can iterate stderr when `buffer` set to `false`', testIterationBuffer, 2, false, false, false);61+test('Can iterate stdio[*] when `buffer` set to `false`', testIterationBuffer, 3, false, false, false);62+test('Can iterate all when `buffer` set to `false`', testIterationBuffer, 1, false, false, true);63+test('Cannot iterate stdout when `buffer` set to `true`', testIterationBuffer, 1, true, false, false);64+test('Cannot iterate stderr when `buffer` set to `true`', testIterationBuffer, 2, true, false, false);65+test('Cannot iterate stdio[*] when `buffer` set to `true`', testIterationBuffer, 3, true, false, false);66+test('Cannot iterate all when `buffer` set to `true`', testIterationBuffer, 1, true, false, true);67+test('Can listen to `data` events on stdout when `buffer` set to `false`', testIterationBuffer, 1, false, true, false);68+test('Can listen to `data` events on stderr when `buffer` set to `false`', testIterationBuffer, 2, false, true, false);69+test('Can listen to `data` events on stdio[*] when `buffer` set to `false`', testIterationBuffer, 3, false, true, false);70+test('Can listen to `data` events on all when `buffer` set to `false`', testIterationBuffer, 1, false, true, true);71+test('Can listen to `data` events on stdout when `buffer` set to `true`', testIterationBuffer, 1, true, true, false);72+test('Can listen to `data` events on stderr when `buffer` set to `true`', testIterationBuffer, 2, true, true, false);73+test('Can listen to `data` events on stdio[*] when `buffer` set to `true`', testIterationBuffer, 3, true, true, false);74+test('Can listen to `data` events on all when `buffer` set to `true`', testIterationBuffer, 1, true, true, true);75+76+const 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+};83+84+test('Listen to stdout errors even when `buffer` is `false`', testNoBufferStreamError, 1, false);85+test('Listen to stderr errors even when `buffer` is `false`', testNoBufferStreamError, 2, false);86+test('Listen to stdio[*] errors even when `buffer` is `false`', testNoBufferStreamError, 3, false);87+test('Listen to all errors even when `buffer` is `false`', testNoBufferStreamError, 1, true);88+89+test('buffer: false > promise resolves', async t => {90+ await t.notThrowsAsync(execa('noop.js', {buffer: false}));91+});92+93+test('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+});97+98+const 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+};105+106+test('buffer: false > emits end event on stdout when promise is rejected', testStreamEnd, 1, false);107+test('buffer: false > emits end event on stderr when promise is rejected', testStreamEnd, 2, false);108+test('buffer: false > emits end event on stdio[*] when promise is rejected', testStreamEnd, 3, false);109+test('buffer: true > emits end event on stdout when promise is rejected', testStreamEnd, 1, true);110+test('buffer: true > emits end event on stderr when promise is rejected', testStreamEnd, 2, true);111+test('buffer: true > emits end event on stdio[*] when promise is rejected', testStreamEnd, 3, true);added:test/stream/resolve.js+49 added
1+import test from 'ava';2+import {execa, execaSync} from '../../index.js';3+import {setFixtureDir} from '../helpers/fixtures-dir.js';4+import {getStdio} from '../helpers/stdio.js';5+6+setFixtureDir();7+8+const testIgnore = async (t, index, execaMethod) => {9+ const result = await execaMethod('noop.js', getStdio(index, 'ignore'));10+ t.is(result.stdio[index], undefined);11+};12+13+test('stdout is undefined if ignored', testIgnore, 1, execa);14+test('stderr is undefined if ignored', testIgnore, 2, execa);15+test('stdio[*] is undefined if ignored', testIgnore, 3, execa);16+test('stdout is undefined if ignored - sync', testIgnore, 1, execaSync);17+test('stderr is undefined if ignored - sync', testIgnore, 2, execaSync);18+test('stdio[*] is undefined if ignored - sync', testIgnore, 3, execaSync);19+20+const 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+};26+27+test('childProcess listeners are cleaned up on success', testProcessEventsCleanup, 'empty.js');28+test('childProcess listeners are cleaned up on failure', testProcessEventsCleanup, 'fail.js');29+30+test('Aborting stdout should not abort stderr nor all', async t => {31+ const subprocess = execa('empty.js', {all: true});32+33+ subprocess.stdout.destroy();34+ t.false(subprocess.stdout.readable);35+ t.true(subprocess.stderr.readable);36+ t.true(subprocess.all.readable);37+38+ await subprocess;39+40+ 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
1+import {platform} from 'node:process';2+import {setImmediate} from 'node:timers/promises';3+import test from 'ava';4+import {execa} from '../../index.js';5+import {setFixtureDir} from '../helpers/fixtures-dir.js';6+import {getStdio, prematureClose} from '../helpers/stdio.js';7+import {foobarString} from '../helpers/input.js';8+import {noopGenerator} from '../helpers/generator.js';9+import {noopReadable, noopWritable, noopDuplex} from '../helpers/stream.js';10+11+setFixtureDir();12+13+const isWindows = platform === 'win32';14+15+const noop = () => {};16+17+const endOptionStream = ({stream}) => {18+ stream.end();19+};20+21+const destroyOptionStream = ({stream, error}) => {22+ stream.destroy(error);23+};24+25+const destroyChildStream = ({childProcess, index, error}) => {26+ childProcess.stdio[index].destroy(error);27+};28+29+const getStreamStdio = (index, stream, useTransform) => getStdio(index, [stream, useTransform ? noopGenerator(false) : 'pipe']);30+31+// eslint-disable-next-line max-params32+const 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();38+39+ const {stdout} = await childProcess;40+ t.is(stdout, '');41+ t.true(stream.destroyed);42+};43+44+test('Keeps running when stdin option is used and childProcess.stdin ends', testStreamAbortWait, noop, noopReadable(), 0, false);45+test('Keeps running when stdin option is used and childProcess.stdin Duplex ends', testStreamAbortWait, noop, noopDuplex(), 0, false);46+test('Keeps running when input stdio[*] option is used and input childProcess.stdio[*] ends', testStreamAbortWait, noop, noopReadable(), 3, false);47+test('Keeps running when stdin option is used and childProcess.stdin ends, with a transform', testStreamAbortWait, noop, noopReadable(), 0, true);48+test('Keeps running when stdin option is used and childProcess.stdin Duplex ends, with a transform', testStreamAbortWait, noop, noopDuplex(), 0, true);49+test('Keeps running when input stdio[*] option is used and input childProcess.stdio[*] ends, with a transform', testStreamAbortWait, noop, noopReadable(), 3, true);50+51+// eslint-disable-next-line max-params52+const 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();56+57+ const {stdout} = await childProcess;58+ t.is(stdout, '');59+ t.true(stream.destroyed);60+};61+62+test('Passes when stdin option aborts', testStreamAbortSuccess, destroyOptionStream, noopReadable(), 0, false);63+test('Passes when stdin option Duplex aborts', testStreamAbortSuccess, destroyOptionStream, noopDuplex(), 0, false);64+test('Passes when input stdio[*] option aborts', testStreamAbortSuccess, destroyOptionStream, noopReadable(), 3, false);65+test('Passes when stdout option ends with no more writes', testStreamAbortSuccess, endOptionStream, noopWritable(), 1, false);66+test('Passes when stderr option ends with no more writes', testStreamAbortSuccess, endOptionStream, noopWritable(), 2, false);67+test('Passes when output stdio[*] option ends with no more writes', testStreamAbortSuccess, endOptionStream, noopWritable(), 3, false);68+test('Passes when childProcess.stdout aborts with no more writes', testStreamAbortSuccess, destroyChildStream, noopWritable(), 1, false);69+test('Passes when childProcess.stdout Duplex aborts with no more writes', testStreamAbortSuccess, destroyChildStream, noopDuplex(), 1, false);70+test('Passes when childProcess.stderr aborts with no more writes', testStreamAbortSuccess, destroyChildStream, noopWritable(), 2, false);71+test('Passes when childProcess.stderr Duplex aborts with no more writes', testStreamAbortSuccess, destroyChildStream, noopDuplex(), 2, false);72+test('Passes when output childProcess.stdio[*] aborts with no more writes', testStreamAbortSuccess, destroyChildStream, noopWritable(), 3, false);73+test('Passes when output childProcess.stdio[*] Duplex aborts with no more writes', testStreamAbortSuccess, destroyChildStream, noopDuplex(), 3, false);74+test('Passes when stdin option aborts, with a transform', testStreamAbortSuccess, destroyOptionStream, noopReadable(), 0, true);75+test('Passes when stdin option Duplex aborts, with a transform', testStreamAbortSuccess, destroyOptionStream, noopDuplex(), 0, true);76+test('Passes when input stdio[*] option aborts, with a transform', testStreamAbortSuccess, destroyOptionStream, noopReadable(), 3, true);77+test('Passes when stdout option ends with no more writes, with a transform', testStreamAbortSuccess, endOptionStream, noopWritable(), 1, true);78+test('Passes when stderr option ends with no more writes, with a transform', testStreamAbortSuccess, endOptionStream, noopWritable(), 2, true);79+test('Passes when output stdio[*] option ends with no more writes, with a transform', testStreamAbortSuccess, endOptionStream, noopWritable(), 3, true);80+test('Passes when childProcess.stdout aborts with no more writes, with a transform', testStreamAbortSuccess, destroyChildStream, noopWritable(), 1, true);81+test('Passes when childProcess.stdout Duplex aborts with no more writes, with a transform', testStreamAbortSuccess, destroyChildStream, noopDuplex(), 1, true);82+test('Passes when childProcess.stderr aborts with no more writes, with a transform', testStreamAbortSuccess, destroyChildStream, noopWritable(), 2, true);83+test('Passes when childProcess.stderr Duplex aborts with no more writes, with a transform', testStreamAbortSuccess, destroyChildStream, noopDuplex(), 2, true);84+test('Passes when output childProcess.stdio[*] aborts with no more writes, with a transform', testStreamAbortSuccess, destroyChildStream, noopWritable(), 3, true);85+test('Passes when output childProcess.stdio[*] Duplex aborts with no more writes, with a transform', testStreamAbortSuccess, destroyChildStream, noopDuplex(), 3, true);86+87+// eslint-disable-next-line max-params88+const 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+ }94+95+ const error = await t.throwsAsync(childProcess);96+ t.like(error, {...prematureClose, exitCode: 0});97+ t.true(stream.destroyed);98+};99+100+test('Throws abort error when childProcess.stdin aborts', testStreamAbortFail, destroyChildStream, noopReadable(), 0, false);101+test('Throws abort error when childProcess.stdin Duplex aborts', testStreamAbortFail, destroyChildStream, noopDuplex(), 0, false);102+test('Throws abort error when input childProcess.stdio[*] aborts', testStreamAbortFail, destroyChildStream, noopReadable(), 3, false);103+test('Throws abort error when stdout option aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopWritable(), 1, false);104+test('Throws abort error when stdout option Duplex aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopDuplex(), 1, false);105+test('Throws abort error when stderr option aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopWritable(), 2, false);106+test('Throws abort error when stderr option Duplex aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopDuplex(), 2, false);107+test('Throws abort error when output stdio[*] option aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopWritable(), 3, false);108+test('Throws abort error when output stdio[*] Duplex option aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopDuplex(), 3, false);109+test('Throws abort error when childProcess.stdin aborts, with a transform', testStreamAbortFail, destroyChildStream, noopReadable(), 0, true);110+test('Throws abort error when childProcess.stdin Duplex aborts, with a transform', testStreamAbortFail, destroyChildStream, noopDuplex(), 0, true);111+test('Throws abort error when input childProcess.stdio[*] aborts, with a transform', testStreamAbortFail, destroyChildStream, noopReadable(), 3, true);112+test('Throws abort error when stdout option aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopWritable(), 1, true);113+test('Throws abort error when stdout option Duplex aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopDuplex(), 1, true);114+test('Throws abort error when stderr option aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopWritable(), 2, true);115+test('Throws abort error when stderr option Duplex aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopDuplex(), 2, true);116+test('Throws abort error when output stdio[*] option aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopWritable(), 3, true);117+test('Throws abort error when output stdio[*] Duplex option aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopDuplex(), 3, true);118+119+// eslint-disable-next-line max-params120+const 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);124+125+ const {stdio} = await childProcess;126+ t.is(stdio[index], foobarString);127+ t.true(stream.destroyed);128+};129+130+test('Passes when stdout option ends with more writes', testStreamEpipeSuccess, endOptionStream, noopWritable(), 1, false);131+test('Passes when stderr option ends with more writes', testStreamEpipeSuccess, endOptionStream, noopWritable(), 2, false);132+test('Passes when output stdio[*] option ends with more writes', testStreamEpipeSuccess, endOptionStream, noopWritable(), 3, false);133+test('Passes when stdout option ends with more writes, with a transform', testStreamEpipeSuccess, endOptionStream, noopWritable(), 1, true);134+test('Passes when stderr option ends with more writes, with a transform', testStreamEpipeSuccess, endOptionStream, noopWritable(), 2, true);135+test('Passes when output stdio[*] option ends with more writes, with a transform', testStreamEpipeSuccess, endOptionStream, noopWritable(), 3, true);136+137+// eslint-disable-next-line max-params138+const 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);143+144+ 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+};152+153+test('Throws EPIPE when stdout option aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopWritable(), 1, false);154+test('Throws EPIPE when stdout option Duplex aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 1, false);155+test('Throws EPIPE when stderr option aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopWritable(), 2, false);156+test('Throws EPIPE when stderr option Duplex aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 2, false);157+test('Throws EPIPE when output stdio[*] option aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopWritable(), 3, false);158+test('Throws EPIPE when output stdio[*] option Duplex aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 3, false);159+test('Throws EPIPE when childProcess.stdout aborts with more writes', testStreamEpipeFail, destroyChildStream, noopWritable(), 1, false);160+test('Throws EPIPE when childProcess.stdout Duplex aborts with more writes', testStreamEpipeFail, destroyChildStream, noopDuplex(), 1, false);161+test('Throws EPIPE when childProcess.stderr aborts with more writes', testStreamEpipeFail, destroyChildStream, noopWritable(), 2, false);162+test('Throws EPIPE when childProcess.stderr Duplex aborts with more writes', testStreamEpipeFail, destroyChildStream, noopDuplex(), 2, false);163+test('Throws EPIPE when output childProcess.stdio[*] aborts with more writes', testStreamEpipeFail, destroyChildStream, noopWritable(), 3, false);164+test('Throws EPIPE when output childProcess.stdio[*] Duplex aborts with more writes', testStreamEpipeFail, destroyChildStream, noopDuplex(), 3, false);165+test('Throws EPIPE when stdout option aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopWritable(), 1, true);166+test('Throws EPIPE when stdout option Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 1, true);167+test('Throws EPIPE when stderr option aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopWritable(), 2, true);168+test('Throws EPIPE when stderr option Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 2, true);169+test('Throws EPIPE when output stdio[*] option aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopWritable(), 3, true);170+test('Throws EPIPE when output stdio[*] option Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 3, true);171+test('Throws EPIPE when childProcess.stdout aborts with more writes, with a transform', testStreamEpipeFail, destroyChildStream, noopWritable(), 1, true);172+test('Throws EPIPE when childProcess.stdout Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroyChildStream, noopDuplex(), 1, true);173+test('Throws EPIPE when childProcess.stderr aborts with more writes, with a transform', testStreamEpipeFail, destroyChildStream, noopWritable(), 2, true);174+test('Throws EPIPE when childProcess.stderr Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroyChildStream, noopDuplex(), 2, true);175+test('Throws EPIPE when output childProcess.stdio[*] aborts with more writes, with a transform', testStreamEpipeFail, destroyChildStream, noopWritable(), 3, true);176+test('Throws EPIPE when output childProcess.stdio[*] Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroyChildStream, noopDuplex(), 3, true);177+178+// eslint-disable-next-line max-params179+const 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});183+184+ 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+};192+193+test('Throws stream error when stdin option errors', testStreamError, destroyOptionStream, noopReadable(), 0, false);194+test('Throws stream error when stdin option Duplex errors', testStreamError, destroyOptionStream, noopDuplex(), 0, false);195+test('Throws stream error when stdout option errors', testStreamError, destroyOptionStream, noopWritable(), 1, false);196+test('Throws stream error when stdout option Duplex errors', testStreamError, destroyOptionStream, noopDuplex(), 1, false);197+test('Throws stream error when stderr option errors', testStreamError, destroyOptionStream, noopWritable(), 2, false);198+test('Throws stream error when stderr option Duplex errors', testStreamError, destroyOptionStream, noopDuplex(), 2, false);199+test('Throws stream error when output stdio[*] option errors', testStreamError, destroyOptionStream, noopWritable(), 3, false);200+test('Throws stream error when output stdio[*] Duplex option errors', testStreamError, destroyOptionStream, noopDuplex(), 3, false);201+test('Throws stream error when input stdio[*] option errors', testStreamError, destroyOptionStream, noopReadable(), 3, false);202+test('Throws stream error when childProcess.stdin errors', testStreamError, destroyChildStream, noopReadable(), 0, false);203+test('Throws stream error when childProcess.stdin Duplex errors', testStreamError, destroyChildStream, noopDuplex(), 0, false);204+test('Throws stream error when childProcess.stdout errors', testStreamError, destroyChildStream, noopWritable(), 1, false);205+test('Throws stream error when childProcess.stdout Duplex errors', testStreamError, destroyChildStream, noopDuplex(), 1, false);206+test('Throws stream error when childProcess.stderr errors', testStreamError, destroyChildStream, noopWritable(), 2, false);207+test('Throws stream error when childProcess.stderr Duplex errors', testStreamError, destroyChildStream, noopDuplex(), 2, false);208+test('Throws stream error when output childProcess.stdio[*] errors', testStreamError, destroyChildStream, noopWritable(), 3, false);209+test('Throws stream error when output childProcess.stdio[*] Duplex errors', testStreamError, destroyChildStream, noopDuplex(), 3, false);210+test('Throws stream error when input childProcess.stdio[*] errors', testStreamError, destroyChildStream, noopReadable(), 3, false);211+test('Throws stream error when stdin option errors, with a transform', testStreamError, destroyOptionStream, noopReadable(), 0, true);212+test('Throws stream error when stdin option Duplex errors, with a transform', testStreamError, destroyOptionStream, noopDuplex(), 0, true);213+test('Throws stream error when stdout option errors, with a transform', testStreamError, destroyOptionStream, noopWritable(), 1, true);214+test('Throws stream error when stdout option Duplex errors, with a transform', testStreamError, destroyOptionStream, noopDuplex(), 1, true);215+test('Throws stream error when stderr option errors, with a transform', testStreamError, destroyOptionStream, noopWritable(), 2, true);216+test('Throws stream error when stderr option Duplex errors, with a transform', testStreamError, destroyOptionStream, noopDuplex(), 2, true);217+test('Throws stream error when output stdio[*] option errors, with a transform', testStreamError, destroyOptionStream, noopWritable(), 3, true);218+test('Throws stream error when output stdio[*] Duplex option errors, with a transform', testStreamError, destroyOptionStream, noopDuplex(), 3, true);219+test('Throws stream error when input stdio[*] option errors, with a transform', testStreamError, destroyOptionStream, noopReadable(), 3, true);220+test('Throws stream error when childProcess.stdin errors, with a transform', testStreamError, destroyChildStream, noopReadable(), 0, true);221+test('Throws stream error when childProcess.stdin Duplex errors, with a transform', testStreamError, destroyChildStream, noopDuplex(), 0, true);222+test('Throws stream error when childProcess.stdout errors, with a transform', testStreamError, destroyChildStream, noopWritable(), 1, true);223+test('Throws stream error when childProcess.stdout Duplex errors, with a transform', testStreamError, destroyChildStream, noopDuplex(), 1, true);224+test('Throws stream error when childProcess.stderr errors, with a transform', testStreamError, destroyChildStream, noopWritable(), 2, true);225+test('Throws stream error when childProcess.stderr Duplex errors, with a transform', testStreamError, destroyChildStream, noopDuplex(), 2, true);226+test('Throws stream error when output childProcess.stdio[*] errors, with a transform', testStreamError, destroyChildStream, noopWritable(), 3, true);227+test('Throws stream error when output childProcess.stdio[*] Duplex errors, with a transform', testStreamError, destroyChildStream, noopDuplex(), 3, true);228+test('Throws stream error when input childProcess.stdio[*] errors, with a transform', testStreamError, destroyChildStream, noopReadable(), 3, true);added:test/async.js+36 added
1+import process from 'node:process';2+import test from 'ava';3+import {execa, execaSync} from '../index.js';4+import {setFixtureDir} from './helpers/fixtures-dir.js';5+6+setFixtureDir();7+8+const isWindows = process.platform === 'win32';9+10+if (isWindows) {11+ test('execa() - cmd file', async t => {12+ const {stdout} = await execa('hello.cmd');13+ t.is(stdout, 'Hello World');14+ });15+16+ test('execa() - run cmd command', async t => {17+ const {stdout} = await execa('cmd', ['/c', 'hello.cmd']);18+ t.is(stdout, 'Hello World');19+ });20+}21+22+test('skip throwing when using reject option', async t => {23+ const {exitCode} = await execa('fail.js', {reject: false});24+ t.is(exitCode, 2);25+});26+27+test('skip throwing when using reject option in sync mode', t => {28+ const {exitCode} = execaSync('fail.js', {reject: false});29+ t.is(exitCode, 2);30+});31+32+test('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
1-import test from 'ava';2-import {execa} from '../index.js';3-import {setFixtureDir} from './helpers/fixtures-dir.js';4-import {foobarString} from './helpers/input.js';5-6-setFixtureDir();7-8-const 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-};16-17-test('error instance can be null', testUnusualError, null);18-test('error instance can be false', testUnusualError, false);19-test('error instance can be a string', testUnusualError, 'test');20-test('error instance can be a number', testUnusualError, 0);21-test('error instance can be a BigInt', testUnusualError, 0n);22-test('error instance can be a symbol', testUnusualError, Symbol('test'));23-test('error instance can be a function', testUnusualError, () => {});24-test('error instance can be an array', testUnusualError, ['test', 'test']);25-// eslint-disable-next-line unicorn/error-message26-test('error instance can be an error with an empty message', testUnusualError, new Error(''), '');27-test('error instance can be undefined', testUnusualError, undefined, '');28-29-test('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-});34-35-const runAndFail = (t, fixtureName, argument, error) => {36- const childProcess = execa(fixtureName, [argument]);37- childProcess.emit('error', error);38- return t.throwsAsync(childProcess);39-};40-41-const runAndClone = async (t, initialError) => {42- const previousError = await runAndFail(t, 'empty.js', 'foo', initialError);43- t.is(previousError, initialError);44-45- return runAndFail(t, 'empty.js', 'bar', previousError);46-};47-48-const testErrorCopy = async (t, getPreviousArgument, argument = 'two') => {49- const fixtureName = 'empty.js';50- const firstArgument = 'foo';51-52- 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}`;56-57- 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-};65-66-test('error instance can be shared', testErrorCopy, () => new Error(foobarString));67-test('error TypeError can be shared', testErrorCopy, () => new TypeError(foobarString));68-test('error string can be shared', testErrorCopy, () => foobarString);69-test('error copy can be shared', testErrorCopy, (t, fixtureName) => runAndFail(t, fixtureName, 'bar', new Error(foobarString)));70-test('error with same message can be shared', testErrorCopy, () => new Error(foobarString), 'foo');71-72-const testErrorCopyProperty = async (t, propertyName, isCopied) => {73- const propertyValue = 'test';74- const initialError = new Error(foobarString);75- initialError[propertyName] = propertyValue;76-77- const error = await runAndClone(t, initialError);78- t.is(error[propertyName] === propertyValue, isCopied);79-};80-81-test('error.code can be copied', testErrorCopyProperty, 'code', true);82-test('error.errno can be copied', testErrorCopyProperty, 'errno', true);83-test('error.syscall can be copied', testErrorCopyProperty, 'syscall', true);84-test('error.path can be copied', testErrorCopyProperty, 'path', true);85-test('error.dest can be copied', testErrorCopyProperty, 'dest', true);86-test('error.address can be copied', testErrorCopyProperty, 'address', true);87-test('error.port can be copied', testErrorCopyProperty, 'port', true);88-test('error.info can be copied', testErrorCopyProperty, 'info', true);89-test('error.other cannot be copied', testErrorCopyProperty, 'other', false);90-91-test('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-});96-97-test('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-});102-103-test('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-});108-109-test('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');113-114- const newMessage = 'newTest';115- error.message = newMessage;116- t.false(error.stack.includes(newMessage));117- error.message = message;118-119- 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-});125-126-test('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-});133-134-test('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');138-139- const childProcess = execa('empty.js');140- childProcess.emit('error', error);141- t.is(await t.throwsAsync(childProcess), error);142-143- 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
1-import {mkdir, rmdir} from 'node:fs/promises';2-import {relative, toNamespacedPath} from 'node:path';3-import process from 'node:process';4-import {pathToFileURL, fileURLToPath} from 'node:url';5-import tempfile from 'tempfile';6-import test from 'ava';7-import {execa, execaSync} from '../index.js';8-import {FIXTURES_DIR, setFixtureDir} from './helpers/fixtures-dir.js';9-10-setFixtureDir();11-12-const isWindows = process.platform === 'win32';13-14-const 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-};19-20-test('The "cwd" option can be a string', testOptionCwdString, execa);21-test('The "cwd" option can be a string - sync', testOptionCwdString, execaSync);22-23-const 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-};29-30-test('The "cwd" option can be a URL', testOptionCwdUrl, execa);31-test('The "cwd" option can be a URL - sync', testOptionCwdUrl, execaSync);32-33-const 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-};38-39-test('The "cwd" option cannot be an invalid type', testOptionCwdInvalid, execa);40-test('The "cwd" option cannot be an invalid type - sync', testOptionCwdInvalid, execaSync);41-42-const testErrorCwdDefault = async (t, execaMethod) => {43- const {cwd} = await execaMethod('empty.js');44- t.is(cwd, process.cwd());45-};46-47-test('The "cwd" option defaults to process.cwd()', testErrorCwdDefault, execa);48-test('The "cwd" option defaults to process.cwd() - sync', testErrorCwdDefault, execaSync);49-50-// Windows does not allow removing a directory used as `cwd` of a running process51-if (!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);58-59- try {60- t.throws(() => {61- execaMethod('empty.js');62- }, {message: /The current directory does not exist/});63- } finally {64- process.chdir(currentCwd);65- }66- };67-68- 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-}71-72-const cwdNotExisting = {cwd: 'does_not_exist', expectedCode: 'ENOENT', expectedMessage: 'The "cwd" option is invalid'};73-const cwdTooLong = {cwd: '.'.repeat(1e5), expectedCode: 'ENAMETOOLONG', expectedMessage: 'The "cwd" option is invalid'};74-const cwdNotDir = {cwd: fileURLToPath(import.meta.url), expectedCode: isWindows ? 'ENOENT' : 'ENOTDIR', expectedMessage: 'The "cwd" option is not a directory'};75-76-const 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-};83-84-test('The "cwd" option must be an existing file', testCwdPostSpawn, cwdNotExisting, execa);85-test('The "cwd" option must be an existing file - sync', testCwdPostSpawn, cwdNotExisting, execaSync);86-test('The "cwd" option must not be too long', testCwdPostSpawn, cwdTooLong, execa);87-test('The "cwd" option must not be too long - sync', testCwdPostSpawn, cwdTooLong, execaSync);88-test('The "cwd" option must be a directory', testCwdPostSpawn, cwdNotDir, execa);89-test('The "cwd" option must be a directory - sync', testCwdPostSpawn, cwdNotDir, execaSync);90-91-const successProperties = {fixtureName: 'empty.js', expectedFailed: false};92-const errorProperties = {fixtureName: 'fail.js', expectedFailed: true};93-94-const 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-};99-100-test('result.cwd is defined', testErrorCwd, execa, successProperties);101-test('result.cwd is defined - sync', testErrorCwd, execaSync, successProperties);102-test('error.cwd is defined', testErrorCwd, execa, errorProperties);103-test('error.cwd is defined - sync', testErrorCwd, execaSync, errorProperties);deleted:test/error.js-332 removed
1-import process from 'node:process';2-import test from 'ava';3-import {execa, execaSync} from '../index.js';4-import {setFixtureDir} from './helpers/fixtures-dir.js';5-import {fullStdio, getStdio} from './helpers/stdio.js';6-import {noopGenerator, outputObjectGenerator} from './helpers/generator.js';7-8-const isWindows = process.platform === 'win32';9-10-setFixtureDir();11-12-const TIMEOUT_REGEXP = /timed out after/;13-14-test('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-});32-33-test('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-});57-58-const 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-};65-66-test('empty error.stdout/stderr/stdio', testEmptyErrorStdio, execa);67-test('empty error.stdout/stderr/stdio - sync', testEmptyErrorStdio, execaSync);68-69-const 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-};75-76-test('undefined error.stdout/stderr/stdio', testUndefinedErrorStdio, execa);77-test('undefined error.stdout/stderr/stdio - sync', testUndefinedErrorStdio, execaSync);78-79-const testEmptyAll = async (t, options, expectedValue) => {80- const {all} = await t.throwsAsync(execa('fail.js', options));81- t.is(all, expectedValue);82-};83-84-test('empty error.all', testEmptyAll, {all: true}, '');85-test('undefined error.all', testEmptyAll, {}, undefined);86-test('ignored error.all', testEmptyAll, {all: true, stdio: 'ignore'}, undefined);87-88-test('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-});92-93-// `error.code` is OS-specific here94-const SPAWN_ERROR_CODES = new Set(['EINVAL', 'ENOTSUP', 'EPERM']);95-96-test('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-});103-104-test('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-});113-114-const 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-};121-122-test('error.stdout/stderr/stdio is defined', testErrorOutput, execa);123-test('error.stdout/stderr/stdio is defined - sync', testErrorOutput, execaSync);124-125-test('exitCode is 0 on success', async t => {126- const {exitCode} = await execa('noop.js', ['foo']);127- t.is(exitCode, 0);128-});129-130-const 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-};139-140-test('exitCode is 2', testExitCode, 2);141-test('exitCode is 3', testExitCode, 3);142-test('exitCode is 4', testExitCode, 4);143-144-test('error.message contains the command', async t => {145- await t.throwsAsync(execa('exit.js', ['2', 'foo', 'bar']), {message: /exit.js 2 foo bar/});146-});147-148-const 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-};153-154-test('error.message contains stdout/stderr/stdio if available', testStdioMessage, 'utf8', false, false);155-test('error.message contains stdout/stderr/stdio even with encoding "buffer"', testStdioMessage, 'buffer', false, false);156-test('error.message contains all if available', testStdioMessage, 'utf8', true, false);157-test('error.message contains all even with encoding "buffer"', testStdioMessage, 'buffer', true, false);158-test('error.message contains stdout/stderr/stdio if available, objectMode', testStdioMessage, 'utf8', false, true);159-test('error.message contains stdout/stderr/stdio even with encoding "buffer", objectMode', testStdioMessage, 'buffer', false, true);160-test('error.message contains all if available, objectMode', testStdioMessage, 'utf8', true, true);161-test('error.message contains all even with encoding "buffer", objectMode', testStdioMessage, 'buffer', true, true);162-163-const 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-};167-168-test('error.message does not contain stdout if not available', testPartialIgnoreMessage, 1, 'ignore', 'stderr');169-test('error.message does not contain stderr if not available', testPartialIgnoreMessage, 2, 'ignore', 'stdout');170-test('error.message does not contain stdout if it is an object', testPartialIgnoreMessage, 1, outputObjectGenerator, 'stderr');171-test('error.message does not contain stderr if it is an object', testPartialIgnoreMessage, 2, outputObjectGenerator, 'stdout');172-173-const 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-};179-180-test('error.message does not contain stdout/stderr/stdio if not available', testFullIgnoreMessage, {stdio: 'ignore'}, 'message');181-test('error.shortMessage does not contain stdout/stderr/stdio', testFullIgnoreMessage, fullStdio, 'shortMessage');182-183-const 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-};187-188-test('error.message newlines are consistent - no newline', testErrorMessageConsistent, 'stdout');189-test('error.message newlines are consistent - newline', testErrorMessageConsistent, 'stdout\n');190-191-test('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-});195-196-test('failed is false on success', async t => {197- const {failed} = await execa('noop.js', ['foo']);198- t.false(failed);199-});200-201-test('failed is true on failure', async t => {202- const {failed} = await t.throwsAsync(execa('fail.js'));203- t.true(failed);204-});205-206-test('error.isTerminated is true if process was killed directly', async t => {207- const subprocess = execa('forever.js', {killSignal: 'SIGINT'});208-209- subprocess.kill();210-211- 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-});218-219-test('error.isTerminated is true if process was killed indirectly', async t => {220- const subprocess = execa('forever.js', {killSignal: 'SIGHUP'});221-222- process.kill(subprocess.pid, 'SIGINT');223-224- // `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-});235-236-test('result.isTerminated is false if not killed', async t => {237- const {isTerminated} = await execa('noop.js');238- t.false(isTerminated);239-});240-241-test('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-});248-249-test('result.isTerminated is false if not killed, in sync mode', t => {250- const {isTerminated} = execaSync('noop.js');251- t.false(isTerminated);252-});253-254-test('result.isTerminated is false on process error', async t => {255- const {isTerminated} = await t.throwsAsync(execa('wrong command'));256- t.false(isTerminated);257-});258-259-test('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-});265-266-if (!isWindows) {267- test('error.signal is SIGINT', async t => {268- const subprocess = execa('forever.js');269-270- process.kill(subprocess.pid, 'SIGINT');271-272- const {signal} = await t.throwsAsync(subprocess, {message: /was killed with SIGINT/});273- t.is(signal, 'SIGINT');274- });275-276- test('error.signalDescription is defined', async t => {277- const subprocess = execa('forever.js');278-279- process.kill(subprocess.pid, 'SIGINT');280-281- const {signalDescription} = await t.throwsAsync(subprocess, {message: /User interruption with CTRL-C/});282- t.is(signalDescription, 'User interruption with CTRL-C');283- });284-285- test('error.signal is SIGTERM', async t => {286- const subprocess = execa('forever.js');287-288- process.kill(subprocess.pid, 'SIGTERM');289-290- const {signal} = await t.throwsAsync(subprocess, {message: /was killed with SIGTERM/});291- t.is(signal, 'SIGTERM');292- });293-294- 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- });298-299- test('exitCode is undefined on signal termination', async t => {300- const subprocess = execa('forever.js');301-302- process.kill(subprocess.pid);303-304- const {exitCode} = await t.throwsAsync(subprocess);305- t.is(exitCode, undefined);306- });307-}308-309-test('result.signal is undefined for successful execution', async t => {310- const {signal} = await execa('noop.js');311- t.is(signal, undefined);312-});313-314-test('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-});318-319-test('result.signalDescription is undefined for successful execution', async t => {320- const {signalDescription} = await execa('noop.js');321- t.is(signalDescription, undefined);322-});323-324-test('error.code is undefined on success', async t => {325- const {code} = await execa('noop.js');326- t.is(code, undefined);327-});328-329-test('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
1-import test from 'ava';2-import {execa, execaSync} from '../index.js';3-import {setFixtureDir} from './helpers/fixtures-dir.js';4-5-setFixtureDir();6-7-const testResultCommand = async (t, expected, ...args) => {8- const {command: failCommand} = await t.throwsAsync(execa('fail.js', args));9- t.is(failCommand, `fail.js${expected}`);10-11- const {command} = await execa('noop.js', args);12- t.is(command, `noop.js${expected}`);13-};14-15-testResultCommand.title = (message, expected) => `result.command is: ${JSON.stringify(expected)}`;16-17-test(testResultCommand, ' foo bar', 'foo', 'bar');18-test(testResultCommand, ' baz quz', 'baz', 'quz');19-test(testResultCommand, '');20-21-const testEscapedCommand = async (t, expected, args) => {22- const {escapedCommand: failEscapedCommand} = await t.throwsAsync(execa('fail.js', args));23- t.is(failEscapedCommand, `fail.js ${expected}`);24-25- const {escapedCommand: failEscapedCommandSync} = t.throws(() => {26- execaSync('fail.js', args);27- });28- t.is(failEscapedCommandSync, `fail.js ${expected}`);29-30- const {escapedCommand} = await execa('noop.js', args);31- t.is(escapedCommand, `noop.js ${expected}`);32-33- const {escapedCommand: escapedCommandSync} = execaSync('noop.js', args);34- t.is(escapedCommandSync, `noop.js ${expected}`);35-};36-37-testEscapedCommand.title = (message, expected) => `result.escapedCommand is: ${JSON.stringify(expected)}`;38-39-test(testEscapedCommand, 'foo bar', ['foo', 'bar']);40-test(testEscapedCommand, '"foo bar"', ['foo bar']);41-test(testEscapedCommand, '"\\"foo\\""', ['"foo"']);42-test(testEscapedCommand, '"*"', ['*']);43-44-test('allow commands with spaces and no array arguments', async t => {45- const {stdout} = await execa('command with space.js');46- t.is(stdout, '');47-});48-49-test('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
1-import process from 'node:process';2-import {once, defaultMaxListeners} from 'node:events';3-import {constants} from 'node:os';4-import {setTimeout, setImmediate} from 'node:timers/promises';5-import test from 'ava';6-import {pEvent} from 'p-event';7-import isRunning from 'is-running';8-import {execa, execaSync} from '../index.js';9-import {setFixtureDir, FIXTURES_DIR} from './helpers/fixtures-dir.js';10-import {assertMaxListeners} from './helpers/listeners.js';11-12-setFixtureDir();13-14-const isWindows = process.platform === 'win32';15-16-const 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-};25-26-const spawnNoKillableSimple = options => execa('forever.js', {killSignal: 'SIGWINCH', forceKillAfterDelay: 1, ...options});27-28-const spawnNoKillableOutput = options => execa('noop-forever.js', ['.'], {killSignal: 'SIGWINCH', forceKillAfterDelay: 1, ...options});29-30-test('kill("SIGKILL") should terminate cleanly', async t => {31- const {subprocess} = await spawnNoKillable();32-33- subprocess.kill('SIGKILL');34-35- const {isTerminated, signal} = await t.throwsAsync(subprocess);36- t.true(isTerminated);37- t.is(signal, 'SIGKILL');38-});39-40-const testInvalidForceKill = async (t, forceKillAfterDelay) => {41- t.throws(() => {42- execa('empty.js', {forceKillAfterDelay});43- }, {instanceOf: TypeError, message: /non-negative integer/});44-};45-46-test('`forceKillAfterDelay` should not be NaN', testInvalidForceKill, Number.NaN);47-test('`forceKillAfterDelay` should not be negative', testInvalidForceKill, -1);48-49-// `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.51-if (isWindows) {52- test('Can call `.kill()` with `forceKillAfterDelay` on Windows', async t => {53- const {subprocess} = await spawnNoKillable(1);54- subprocess.kill();55-56- 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);63-64- subprocess.kill(killArgument);65-66- await setTimeout(6e3);67- t.true(isRunning(subprocess.pid));68- subprocess.kill('SIGKILL');69-70- const {isTerminated, signal} = await t.throwsAsync(subprocess);71- t.true(isTerminated);72- t.is(signal, 'SIGKILL');73- };74-75- 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});79-80- const testForceKill = async (t, forceKillAfterDelay, killArgument, options) => {81- const {subprocess} = await spawnNoKillable(forceKillAfterDelay, options);82-83- subprocess.kill(killArgument);84-85- const {isTerminated, signal} = await t.throwsAsync(subprocess);86- t.true(isTerminated);87- t.is(signal, 'SIGKILL');88- };89-90- 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'});98-99- 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- });109-110- 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- });117-118- 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- });124-125- test.serial('Can call `.kill()` with `forceKillAfterDelay` many times without triggering the maxListeners warning', async t => {126- const checkMaxListeners = assertMaxListeners(t);127-128- const subprocess = spawnNoKillableSimple();129- for (let index = 0; index < defaultMaxListeners + 1; index += 1) {130- subprocess.kill();131- }132-133- const {isTerminated, signal} = await t.throwsAsync(subprocess);134- t.true(isTerminated);135- t.is(signal, 'SIGKILL');136-137- checkMaxListeners();138- });139-140- test('Can call `.kill()` with `forceKillAfterDelay` multiple times', async t => {141- const subprocess = spawnNoKillableSimple();142- subprocess.kill();143- subprocess.kill();144-145- const {isTerminated, signal} = await t.throwsAsync(subprocess);146- t.true(isTerminated);147- t.is(signal, 'SIGKILL');148- });149-}150-151-test('Can call `.kill()` multiple times', async t => {152- const subprocess = execa('forever.js');153- subprocess.kill();154- subprocess.kill();155-156- const {isTerminated, signal} = await t.throwsAsync(subprocess);157- t.true(isTerminated);158- t.is(signal, 'SIGTERM');159-});160-161-test('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-});166-167-test('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-});176-177-test('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-});188-189-test('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-});193-194-test('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-});200-201-const INVALID_TIMEOUT_REGEXP = /`timeout` option to be a non-negative integer/;202-203-const testTimeoutValidation = (t, timeout, execaMethod) => {204- t.throws(() => {205- execaMethod('empty.js', {timeout});206- }, {message: INVALID_TIMEOUT_REGEXP});207-};208-209-test('timeout must not be negative', testTimeoutValidation, -1, execa);210-test('timeout must be an integer', testTimeoutValidation, false, execa);211-test('timeout must not be negative - sync', testTimeoutValidation, -1, execaSync);212-test('timeout must be an integer - sync', testTimeoutValidation, false, execaSync);213-214-test('timedOut is false if timeout is undefined', async t => {215- const {timedOut} = await execa('noop.js');216- t.false(timedOut);217-});218-219-test('timedOut is false if timeout is 0', async t => {220- const {timedOut} = await execa('noop.js', {timeout: 0});221- t.false(timedOut);222-});223-224-test('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-});228-229-test('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-});236-237-// When child process exits before parent process238-const spawnAndExit = async (t, cleanup, detached) => {239- await t.notThrowsAsync(execa('nested.js', [JSON.stringify({cleanup, detached}), 'noop.js']));240-};241-242-test('spawnAndExit', spawnAndExit, false, false);243-test('spawnAndExit cleanup', spawnAndExit, true, false);244-test('spawnAndExit detached', spawnAndExit, false, true);245-test('spawnAndExit cleanup detached', spawnAndExit, true, true);246-247-// When parent process exits before child process248-const spawnAndKill = async (t, [signal, cleanup, detached, isKilled]) => {249- const subprocess = execa('sub-process.js', [cleanup, detached], {stdio: 'ignore', ipc: true});250-251- const pid = await pEvent(subprocess, 'message');252- t.true(Number.isInteger(pid));253- t.true(isRunning(pid));254-255- process.kill(subprocess.pid, signal);256-257- await t.throwsAsync(subprocess);258- t.false(isRunning(subprocess.pid));259-260- 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-};271-272-const pollForProcessExit = async pid => {273- while (isRunning(pid)) {274- // eslint-disable-next-line no-await-in-loop275- await setTimeout(100);276- }277-};278-279-// 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 handled285-test('spawnAndKill SIGTERM', spawnAndKill, ['SIGTERM', false, false, isWindows]);286-test('spawnAndKill SIGKILL', spawnAndKill, ['SIGKILL', false, false, isWindows]);287-test('spawnAndKill cleanup SIGTERM', spawnAndKill, ['SIGTERM', true, false, true]);288-test('spawnAndKill cleanup SIGKILL', spawnAndKill, ['SIGKILL', true, false, isWindows]);289-test('spawnAndKill detached SIGTERM', spawnAndKill, ['SIGTERM', false, true, false]);290-test('spawnAndKill detached SIGKILL', spawnAndKill, ['SIGKILL', false, true, false]);291-test('spawnAndKill cleanup detached SIGTERM', spawnAndKill, ['SIGTERM', true, true, false]);292-test('spawnAndKill cleanup detached SIGKILL', spawnAndKill, ['SIGKILL', true, true, false]);293-294-// See #128295-test('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;298-299- const subprocess = execa('noop.js');300- const listener = exitListeners.at(-1);301-302- await subprocess;303- t.false(exitListeners.includes(listener));304-});305-306-test('result.isCanceled is false when abort isn\'t called (success)', async t => {307- const {isCanceled} = await execa('noop.js');308- t.false(isCanceled);309-});310-311-test('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-});315-316-test('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-});320-321-test('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-});327-328-test('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-});337-338-test('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-});345-346-test('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-});353-354-test('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-});360-361-test('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-});369-370-test('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-});377-378-test('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-});389-390-test('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-});402-403-test('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-});417-418-test('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-});429-430-const 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-};440-441-test('Cannot call .kill(null)', testInvalidKillArgument, null);442-test('Cannot call .kill(0n)', testInvalidKillArgument, 0n);443-test('Cannot call .kill(true)', testInvalidKillArgument, true);444-test('Cannot call .kill(errorObject)', testInvalidKillArgument, {name: '', message: '', stack: ''});445-test('Cannot call .kill([error])', testInvalidKillArgument, [new Error('test')]);446-test('Cannot call .kill(undefined, true)', testInvalidKillArgument, undefined, true);447-test('Cannot call .kill("SIGTERM", true)', testInvalidKillArgument, 'SIGTERM', true);448-test('Cannot call .kill(true, error)', testInvalidKillArgument, true, new Error('test'));449-450-test('.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-});464-465-test('.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-});472-473-test('.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-});480-481-test('.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-});487-488-test('.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-});501-502-test('.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-});511-512-test('.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
1-import {dirname, relative} from 'node:path';2-import process from 'node:process';3-import {pathToFileURL} from 'node:url';4-import test from 'ava';5-import getNode from 'get-node';6-import {pEvent} from 'p-event';7-import {execa, execaSync, execaNode} from '../index.js';8-import {FIXTURES_DIR} from './helpers/fixtures-dir.js';9-import {identity, fullStdio} from './helpers/stdio.js';10-import {foobarString} from './helpers/input.js';11-12-process.chdir(FIXTURES_DIR);13-14-const runWithNodeOption = (file, args, options) => Array.isArray(args)15- ? execa(file, args, {...options, node: true})16- : execa(file, {...options, node: true});17-const runWithNodeOptionSync = (file, args, options) => Array.isArray(args)18- ? execaSync(file, args, {...options, node: true})19- : execaSync(file, {...options, node: true});20-const runWithIpc = (file, options) => execa('node', [file], {...options, ipc: true});21-22-const testNodeSuccess = async (t, execaMethod) => {23- const {exitCode, stdout} = await execaMethod('noop.js', [foobarString]);24- t.is(exitCode, 0);25- t.is(stdout, foobarString);26-};27-28-test('execaNode() succeeds', testNodeSuccess, execaNode);29-test('The "node" option succeeds', testNodeSuccess, runWithNodeOption);30-test('The "node" option succeeds - sync', testNodeSuccess, runWithNodeOptionSync);31-32-test('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-});37-38-const testDoubleNode = (t, nodePath, execaMethod) => {39- t.throws(() => {40- execaMethod(nodePath, ['noop.js']);41- }, {message: /does not need to be "node"/});42-};43-44-test('Cannot use "node" as binary - execaNode()', testDoubleNode, 'node', execaNode);45-test('Cannot use "node" as binary - "node" option', testDoubleNode, 'node', runWithNodeOption);46-test('Cannot use "node" as binary - "node" option sync', testDoubleNode, 'node', runWithNodeOptionSync);47-test('Cannot use path to "node" as binary - execaNode()', testDoubleNode, process.execPath, execaNode);48-test('Cannot use path to "node" as binary - "node" option', testDoubleNode, process.execPath, runWithNodeOption);49-test('Cannot use path to "node" as binary - "node" option sync', testDoubleNode, process.execPath, runWithNodeOptionSync);50-51-const getNodePath = async () => {52- const {path} = await getNode(TEST_NODE_VERSION);53- return path;54-};55-56-const TEST_NODE_VERSION = '16.0.0';57-58-const 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-};63-64-test.serial('The "nodePath" option can be used - execaNode()', testNodePath, execaNode, identity);65-test.serial('The "nodePath" option can be a file URL - execaNode()', testNodePath, execaNode, pathToFileURL);66-test.serial('The "nodePath" option can be used - "node" option', testNodePath, runWithNodeOption, identity);67-test.serial('The "nodePath" option can be a file URL - "node" option', testNodePath, runWithNodeOption, pathToFileURL);68-test.serial('The "nodePath" option can be used - "node" option sync', testNodePath, runWithNodeOptionSync, identity);69-test.serial('The "nodePath" option can be a file URL - "node" option sync', testNodePath, runWithNodeOptionSync, pathToFileURL);70-71-const testNodePathDefault = async (t, execaMethod) => {72- const {stdout} = await execaMethod('--version');73- t.is(stdout, process.version);74-};75-76-test('The "nodePath" option defaults to the current Node.js binary - execaNode()', testNodePathDefault, execaNode);77-test('The "nodePath" option defaults to the current Node.js binary - "node" option', testNodePathDefault, runWithNodeOption);78-test('The "nodePath" option defaults to the current Node.js binary - "node" option sync', testNodePathDefault, runWithNodeOptionSync);79-80-const 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-};85-86-test('The "nodePath" option must be a string or URL - execaNode()', testNodePathInvalid, execaNode);87-test('The "nodePath" option must be a string or URL - "node" option', testNodePathInvalid, runWithNodeOption);88-test('The "nodePath" option must be a string or URL - "node" option sync', testNodePathInvalid, runWithNodeOptionSync);89-90-const testFormerNodePath = (t, execaMethod) => {91- t.throws(() => {92- execaMethod('noop.js', [], {execPath: process.execPath});93- }, {message: /The "execPath" option has been removed/});94-};95-96-test('The "execPath" option cannot be used - execaNode()', testFormerNodePath, execaNode);97-test('The "execPath" option cannot be used - "node" option', testFormerNodePath, runWithNodeOption);98-test('The "execPath" option cannot be used - "node" option sync', testFormerNodePath, runWithNodeOptionSync);99-100-const nodePathArguments = ['node', ['-p', 'process.env.Path || process.env.PATH']];101-102-const 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-};107-108-test.serial('The "nodePath" option impacts the child process', testChildNodePath, identity);109-test.serial('The "nodePath" option can be a file URL', testChildNodePath, pathToFileURL);110-111-test('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-});115-116-test.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-});121-122-test.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-});129-130-const 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-};137-138-test.serial('The "nodePath" option is relative to "cwd" - execaNode()', testCwdNodePath, execaNode);139-test.serial('The "nodePath" option is relative to "cwd" - "node" option', testCwdNodePath, runWithNodeOption);140-test.serial('The "nodePath" option is relative to "cwd" - "node" option sync', testCwdNodePath, runWithNodeOptionSync);141-142-const testNodeOptions = async (t, execaMethod) => {143- const {stdout} = await execaMethod('empty.js', [], {nodeOptions: ['--version']});144- t.is(stdout, process.version);145-};146-147-test('The "nodeOptions" option can be used - execaNode()', testNodeOptions, execaNode);148-test('The "nodeOptions" option can be used - "node" option', testNodeOptions, runWithNodeOption);149-test('The "nodeOptions" option can be used - "node" option sync', testNodeOptions, runWithNodeOptionSync);150-151-const 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-);156-157-const testInspectRemoval = async (t, fakeExecArgv, execaMethod) => {158- const {stdout, stdio} = await spawnNestedExecaNode([], fakeExecArgv, execaMethod, '');159- t.is(stdout, foobarString);160- t.is(stdio[3], '');161-};162-163-test('The "nodeOptions" option removes --inspect without a port when defined by parent process - execaNode()', testInspectRemoval, '--inspect', 'execaNode');164-test('The "nodeOptions" option removes --inspect without a port when defined by parent process - "node" option', testInspectRemoval, '--inspect', 'nodeOption');165-test('The "nodeOptions" option removes --inspect with a port when defined by parent process - execaNode()', testInspectRemoval, '--inspect=9222', 'execaNode');166-test('The "nodeOptions" option removes --inspect with a port when defined by parent process - "node" option', testInspectRemoval, '--inspect=9222', 'nodeOption');167-test('The "nodeOptions" option removes --inspect-brk without a port when defined by parent process - execaNode()', testInspectRemoval, '--inspect-brk', 'execaNode');168-test('The "nodeOptions" option removes --inspect-brk without a port when defined by parent process - "node" option', testInspectRemoval, '--inspect-brk', 'nodeOption');169-test('The "nodeOptions" option removes --inspect-brk with a port when defined by parent process - execaNode()', testInspectRemoval, '--inspect-brk=9223', 'execaNode');170-test('The "nodeOptions" option removes --inspect-brk with a port when defined by parent process - "node" option', testInspectRemoval, '--inspect-brk=9223', 'nodeOption');171-172-const 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-};177-178-test.serial('The "nodeOptions" option allows --inspect with a different port even when defined by parent process - execaNode()', testInspectDifferentPort, 'execaNode');179-test.serial('The "nodeOptions" option allows --inspect with a different port even when defined by parent process - "node" option', testInspectDifferentPort, 'nodeOption');180-181-const 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-};186-187-test.serial('The "nodeOptions" option forbids --inspect with the same port when defined by parent process - execaNode()', testInspectSamePort, 'execaNode');188-test.serial('The "nodeOptions" option forbids --inspect with the same port when defined by parent process - "node" option', testInspectSamePort, 'nodeOption');189-190-const 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-};199-200-test('execaNode() adds an ipc channel', testIpc, execaNode, {});201-test('The "node" option adds an ipc channel', testIpc, runWithNodeOption, {});202-test('The "ipc" option adds an ipc channel', testIpc, runWithIpc, {});203-test('The "ipc" option works with "stdio: \'pipe\'"', testIpc, runWithIpc, {stdio: 'pipe'});204-test('The "ipc" option works with "stdio: [\'pipe\', \'pipe\', \'pipe\']"', testIpc, runWithIpc, {stdio: ['pipe', 'pipe', 'pipe']});205-test('The "ipc" option works with "stdio: [\'pipe\', \'pipe\', \'pipe\', \'ipc\']"', testIpc, runWithIpc, {stdio: ['pipe', 'pipe', 'pipe', 'ipc']});206-test('The "ipc" option works with "stdout: \'pipe\'"', testIpc, runWithIpc, {stdout: 'pipe'});207-208-test('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-});212-213-const 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-};219-220-test('Can disable "ipc" - execaNode()', testDisableIpc, execaNode);221-test('Can disable "ipc" - "node" option', testDisableIpc, runWithNodeOption);222-test('Can disable "ipc" - "node" option sync', testDisableIpc, runWithNodeOptionSync);223-224-const NO_IPC_MESSAGE = /The "ipc: true" option cannot be used/;225-226-const testNoIpcSync = (t, node) => {227- t.throws(() => {228- execaSync('node', ['send.js'], {ipc: true, node});229- }, {message: NO_IPC_MESSAGE});230-};231-232-test('Cannot use "ipc: true" with execaSync()', testNoIpcSync, undefined);233-test('Cannot use "ipc: true" with execaSync() - "node: false"', testNoIpcSync, false);234-235-test('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-});240-241-const 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-};246-247-test('Cannot use "shell: true" - execaNode()', testNoShell, execaNode);248-test('Cannot use "shell: true" - "node" option', testNoShell, runWithNodeOption);249-test('Cannot use "shell: true" - "node" option sync', testNoShell, runWithNodeOptionSync);deleted:test/stream.js-493 removed
1-import {Buffer} from 'node:buffer';2-import {once} from 'node:events';3-import {platform} from 'node:process';4-import {getDefaultHighWaterMark} from 'node:stream';5-import {setTimeout} from 'node:timers/promises';6-import test from 'ava';7-import getStream from 'get-stream';8-import {execa, execaSync} from '../index.js';9-import {setFixtureDir} from './helpers/fixtures-dir.js';10-import {fullStdio, getStdio, prematureClose} from './helpers/stdio.js';11-import {foobarString} from './helpers/input.js';12-import {infiniteGenerator} from './helpers/generator.js';13-14-setFixtureDir();15-16-const isWindows = platform === 'win32';17-18-test.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-});22-23-test('result.all is undefined unless opts.all is true', async t => {24- const {all} = await execa('noop.js');25- t.is(all, undefined);26-});27-28-test('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-});32-33-const 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-};39-40-test('childProcess.all has the right objectMode and highWaterMark - stdout + stderr', testAllProperties, {});41-test('childProcess.all has the right objectMode and highWaterMark - stdout only', testAllProperties, {stderr: 'ignore'});42-test('childProcess.all has the right objectMode and highWaterMark - stderr only', testAllProperties, {stdout: 'ignore'});43-44-const 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);51-52- const result = await childProcess;53- t.is(result[otherStreamName], undefined);54- t.is(result[streamName], 'foobar');55- t.is(result.all, 'foobar');56-};57-58-test('can use all: true with stdout: ignore', testAllIgnore, 'stderr', 'stdout');59-test('can use all: true with stderr: ignore', testAllIgnore, 'stdout', 'stderr');60-61-test('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);66-67- const {stdout, stderr, all} = await childProcess;68- t.is(stdout, undefined);69- t.is(stderr, undefined);70- t.is(all, undefined);71-});72-73-const testIgnore = async (t, index, execaMethod) => {74- const result = await execaMethod('noop.js', getStdio(index, 'ignore'));75- t.is(result.stdio[index], undefined);76-};77-78-test('stdout is undefined if ignored', testIgnore, 1, execa);79-test('stderr is undefined if ignored', testIgnore, 2, execa);80-test('stdio[*] is undefined if ignored', testIgnore, 3, execa);81-test('stdout is undefined if ignored - sync', testIgnore, 1, execaSync);82-test('stderr is undefined if ignored - sync', testIgnore, 2, execaSync);83-test('stdio[*] is undefined if ignored - sync', testIgnore, 3, execaSync);84-85-const getFirstDataEvent = async stream => {86- const [output] = await once(stream, 'data');87- return output.toString();88-};89-90-const 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- ]);98-99- t.is(output, '');100-101- if (all) {102- t.is(allOutput, '');103- }104-};105-106-test('Lacks some data when stdout is read too late `buffer` set to `false`', testLateStream, 1, false);107-test('Lacks some data when stderr is read too late `buffer` set to `false`', testLateStream, 2, false);108-test('Lacks some data when stdio[*] is read too late `buffer` set to `false`', testLateStream, 3, false);109-test('Lacks some data when all is read too late `buffer` set to `false`', testLateStream, 1, true);110-111-// eslint-disable-next-line max-params112-const 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- ]);120-121- const expectedProcessResult = buffer ? foobarString : undefined;122- const expectedOutput = !buffer || useDataEvents ? foobarString : '';123-124- t.is(result.stdio[index], expectedProcessResult);125- t.is(output, expectedOutput);126-127- if (all) {128- t.is(result.all, expectedProcessResult);129- t.is(allOutput, expectedOutput);130- }131-};132-133-test('Can iterate stdout when `buffer` set to `false`', testIterationBuffer, 1, false, false, false);134-test('Can iterate stderr when `buffer` set to `false`', testIterationBuffer, 2, false, false, false);135-test('Can iterate stdio[*] when `buffer` set to `false`', testIterationBuffer, 3, false, false, false);136-test('Can iterate all when `buffer` set to `false`', testIterationBuffer, 1, false, false, true);137-test('Cannot iterate stdout when `buffer` set to `true`', testIterationBuffer, 1, true, false, false);138-test('Cannot iterate stderr when `buffer` set to `true`', testIterationBuffer, 2, true, false, false);139-test('Cannot iterate stdio[*] when `buffer` set to `true`', testIterationBuffer, 3, true, false, false);140-test('Cannot iterate all when `buffer` set to `true`', testIterationBuffer, 1, true, false, true);141-test('Can listen to `data` events on stdout when `buffer` set to `false`', testIterationBuffer, 1, false, true, false);142-test('Can listen to `data` events on stderr when `buffer` set to `false`', testIterationBuffer, 2, false, true, false);143-test('Can listen to `data` events on stdio[*] when `buffer` set to `false`', testIterationBuffer, 3, false, true, false);144-test('Can listen to `data` events on all when `buffer` set to `false`', testIterationBuffer, 1, false, true, true);145-test('Can listen to `data` events on stdout when `buffer` set to `true`', testIterationBuffer, 1, true, true, false);146-test('Can listen to `data` events on stderr when `buffer` set to `true`', testIterationBuffer, 2, true, true, false);147-test('Can listen to `data` events on stdio[*] when `buffer` set to `true`', testIterationBuffer, 3, true, true, false);148-test('Can listen to `data` events on all when `buffer` set to `true`', testIterationBuffer, 1, true, true, true);149-150-const 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-};157-158-test('Listen to stdout errors even when `buffer` is `false`', testNoBufferStreamError, 1, false);159-test('Listen to stderr errors even when `buffer` is `false`', testNoBufferStreamError, 2, false);160-test('Listen to stdio[*] errors even when `buffer` is `false`', testNoBufferStreamError, 3, false);161-test('Listen to all errors even when `buffer` is `false`', testNoBufferStreamError, 1, true);162-163-const maxBuffer = 10;164-165-const testMaxBufferSuccess = async (t, index, all) => {166- await t.notThrowsAsync(execa('max-buffer.js', [`${index}`, `${maxBuffer}`], {...fullStdio, maxBuffer, all}));167-};168-169-test('maxBuffer does not affect stdout if too high', testMaxBufferSuccess, 1, false);170-test('maxBuffer does not affect stderr if too high', testMaxBufferSuccess, 2, false);171-test('maxBuffer does not affect stdio[*] if too high', testMaxBufferSuccess, 3, false);172-test('maxBuffer does not affect all if too high', testMaxBufferSuccess, 1, true);173-174-test('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-});182-183-const 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-};191-192-test('maxBuffer affects stdout', testMaxBufferLimit, 1, false);193-test('maxBuffer affects stderr', testMaxBufferLimit, 2, false);194-test('maxBuffer affects stdio[*]', testMaxBufferLimit, 3, false);195-test('maxBuffer affects all', testMaxBufferLimit, 1, true);196-197-const 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-};205-206-test('maxBuffer works with encoding buffer and stdout', testMaxBufferEncoding, 1);207-test('maxBuffer works with encoding buffer and stderr', testMaxBufferEncoding, 2);208-test('maxBuffer works with encoding buffer and stdio[*]', testMaxBufferEncoding, 3);209-210-const 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-};217-218-test('maxBuffer works with other encodings and stdout', testMaxBufferHex, 1);219-test('maxBuffer works with other encodings and stderr', testMaxBufferHex, 2);220-test('maxBuffer works with other encodings and stdio[*]', testMaxBufferHex, 3);221-222-const 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-};231-232-test('do not buffer stdout when `buffer` set to `false`', testNoMaxBuffer, 1);233-test('do not buffer stderr when `buffer` set to `false`', testNoMaxBuffer, 2);234-test('do not buffer stdio[*] when `buffer` set to `false`', testNoMaxBuffer, 3);235-236-const 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-};246-247-test('do not hit maxBuffer when `buffer` is `false` with stdout', testNoMaxBufferOption, 1);248-test('do not hit maxBuffer when `buffer` is `false` with stderr', testNoMaxBufferOption, 2);249-test('do not hit maxBuffer when `buffer` is `false` with stdio[*]', testNoMaxBufferOption, 3);250-251-const 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-};258-259-test('abort stream when hitting maxBuffer with stdout', testMaxBufferAbort, 1);260-test('abort stream when hitting maxBuffer with stderr', testMaxBufferAbort, 2);261-test('abort stream when hitting maxBuffer with stdio[*]', testMaxBufferAbort, 3);262-263-test('buffer: false > promise resolves', async t => {264- await t.notThrowsAsync(execa('noop.js', {buffer: false}));265-});266-267-test('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-});271-272-const 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-};279-280-test('buffer: false > emits end event on stdout when promise is rejected', testStreamEnd, 1, false);281-test('buffer: false > emits end event on stderr when promise is rejected', testStreamEnd, 2, false);282-test('buffer: false > emits end event on stdio[*] when promise is rejected', testStreamEnd, 3, false);283-test('buffer: true > emits end event on stdout when promise is rejected', testStreamEnd, 1, true);284-test('buffer: true > emits end event on stderr when promise is rejected', testStreamEnd, 2, true);285-test('buffer: true > emits end event on stdio[*] when promise is rejected', testStreamEnd, 3, true);286-287-const testBufferIgnore = async (t, index, all) => {288- await t.notThrowsAsync(execa('max-buffer.js', [`${index}`], {...getStdio(index, 'ignore'), buffer: false, all}));289-};290-291-test('Process buffers stdout, which does not prevent exit if ignored', testBufferIgnore, 1, false);292-test('Process buffers stderr, which does not prevent exit if ignored', testBufferIgnore, 2, false);293-test('Process buffers all, which does not prevent exit if ignored', testBufferIgnore, 1, true);294-295-const testBufferNotRead = async (t, index, all) => {296- const subprocess = execa('max-buffer.js', [`${index}`], {...fullStdio, buffer: false, all});297- await t.notThrowsAsync(subprocess);298-};299-300-test('Process buffers stdout, which does not prevent exit if not read and buffer is false', testBufferNotRead, 1, false);301-test('Process buffers stderr, which does not prevent exit if not read and buffer is false', testBufferNotRead, 2, false);302-test('Process buffers stdio[*], which does not prevent exit if not read and buffer is false', testBufferNotRead, 3, false);303-test('Process buffers all, which does not prevent exit if not read and buffer is false', testBufferNotRead, 1, true);304-305-const 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-};311-312-test('Process buffers stdout, which does not prevent exit if read and buffer is false', testBufferRead, 1, false);313-test('Process buffers stderr, which does not prevent exit if read and buffer is false', testBufferRead, 2, false);314-test('Process buffers stdio[*], which does not prevent exit if read and buffer is false', testBufferRead, 3, false);315-test('Process buffers all, which does not prevent exit if read and buffer is false', testBufferRead, 1, true);316-317-test('Aborting stdout should not abort stderr nor all', async t => {318- const subprocess = execa('empty.js', {all: true});319-320- subprocess.stdout.destroy();321- t.false(subprocess.stdout.readable);322- t.true(subprocess.stderr.readable);323- t.true(subprocess.all.readable);324-325- await subprocess;326-327- 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-});337-338-const getStreamInputProcess = index => execa('stdin-fd.js', [`${index}`], index === 3339- ? getStdio(3, [new Uint8Array(), infiniteGenerator])340- : {});341-const getStreamOutputProcess = index => execa('noop-repeat.js', [`${index}`], index === 3 ? fullStdio : {});342-343-const 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-};349-350-const assertStreamOutputError = (t, index, {exitCode, signal, isTerminated, failed, stderr}) => {351- if (index !== 3) {352- t.is(exitCode, 1);353- }354-355- t.is(signal, undefined);356- t.false(isTerminated);357- t.true(failed);358-359- if (index === 1 && !isWindows) {360- t.true(stderr.includes('EPIPE'));361- }362-};363-364-const 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-};370-371-test('Aborting stdin should not make the process exit', testStreamInputAbort, 0);372-test('Aborting input stdio[*] should not make the process exit', testStreamInputAbort, 3);373-374-const 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-};380-381-test('Aborting stdout should not make the process exit', testStreamOutputAbort, 1);382-test('Aborting stderr should not make the process exit', testStreamOutputAbort, 2);383-test('Aborting output stdio[*] should not make the process exit', testStreamOutputAbort, 3);384-385-const 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-};392-393-test('Destroying stdin should not make the process exit', testStreamInputDestroy, 0);394-test('Destroying input stdio[*] should not make the process exit', testStreamInputDestroy, 3);395-396-const 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-};403-404-test('Destroying stdout should not make the process exit', testStreamOutputDestroy, 1);405-test('Destroying stderr should not make the process exit', testStreamOutputDestroy, 2);406-test('Destroying output stdio[*] should not make the process exit', testStreamOutputDestroy, 3);407-408-const 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-};417-418-test('Errors on stdin should not make the process exit', testStreamInputError, 0);419-test('Errors on input stdio[*] should not make the process exit', testStreamInputError, 3);420-421-const 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-};429-430-test('Errors on stdout should not make the process exit', testStreamOutputError, 1);431-test('Errors on stderr should not make the process exit', testStreamOutputError, 2);432-test('Errors on output stdio[*] should not make the process exit', testStreamOutputError, 3);433-434-const 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-};441-442-test('Process waits on stdin before exiting', testWaitOnStreamEnd, 0);443-test('Process waits on stdio[*] before exiting', testWaitOnStreamEnd, 3);444-445-const 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-};451-452-test('Process buffers stdout before it is read', testBufferExit, 1, 'noop-delay.js', true);453-test('Process buffers stderr before it is read', testBufferExit, 2, 'noop-delay.js', true);454-test('Process buffers stdio[*] before it is read', testBufferExit, 3, 'noop-delay.js', true);455-test('Process buffers stdout right away, on successfully exit', testBufferExit, 1, 'noop-fd.js', true);456-test('Process buffers stderr right away, on successfully exit', testBufferExit, 2, 'noop-fd.js', true);457-test('Process buffers stdio[*] right away, on successfully exit', testBufferExit, 3, 'noop-fd.js', true);458-test('Process buffers stdout right away, on failure', testBufferExit, 1, 'noop-fail.js', false);459-test('Process buffers stderr right away, on failure', testBufferExit, 2, 'noop-fail.js', false);460-test('Process buffers stdio[*] right away, on failure', testBufferExit, 3, 'noop-fail.js', false);461-462-const 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-};469-470-test('Process buffers stdout right away, even if directly read', testBufferDirect, 1);471-test('Process buffers stderr right away, even if directly read', testBufferDirect, 2);472-test('Process buffers stdio[*] right away, even if directly read', testBufferDirect, 3);473-474-const 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-};480-481-test('childProcess.stdout must be read right away', testBufferDestroyOnEnd, 1);482-test('childProcess.stderr must be read right away', testBufferDestroyOnEnd, 2);483-test('childProcess.stdio[*] must be read right away', testBufferDestroyOnEnd, 3);484-485-const 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-};491-492-test('childProcess listeners are cleaned up on success', testProcessEventsCleanup, 'empty.js');493-test('childProcess listeners are cleaned up on failure', testProcessEventsCleanup, 'fail.js');deleted:test/test.js-300 removed
1-import {delimiter, join, basename} from 'node:path';2-import process from 'node:process';3-import {fileURLToPath, pathToFileURL} from 'node:url';4-import test from 'ava';5-import isRunning from 'is-running';6-import which from 'which';7-import {execa, execaSync, execaNode, $} from '../index.js';8-import {setFixtureDir, PATH_KEY, FIXTURES_DIR_URL} from './helpers/fixtures-dir.js';9-import {identity, fullStdio, getStdio} from './helpers/stdio.js';10-import {noopGenerator} from './helpers/generator.js';11-12-setFixtureDir();13-process.env.FOO = 'foo';14-15-const isWindows = process.platform === 'win32';16-const ENOENT_REGEXP = isWindows ? /failed with exit code 1/ : /spawn.* ENOENT/;17-18-const testOutput = async (t, index, execaMethod) => {19- const {stdout, stderr, stdio} = await execaMethod('noop-fd.js', [`${index}`, 'foobar'], fullStdio);20- t.is(stdio[index], 'foobar');21-22- if (index === 1) {23- t.is(stdio[index], stdout);24- } else if (index === 2) {25- t.is(stdio[index], stderr);26- }27-};28-29-test('can return stdout', testOutput, 1, execa);30-test('can return stderr', testOutput, 2, execa);31-test('can return output stdio[*]', testOutput, 3, execa);32-test('can return stdout - sync', testOutput, 1, execaSync);33-test('can return stderr - sync', testOutput, 2, execaSync);34-test('can return output stdio[*] - sync', testOutput, 3, execaSync);35-36-const testNoStdin = async (t, execaMethod) => {37- const {stdio} = await execaMethod('noop.js', ['foobar']);38- t.is(stdio[0], undefined);39-};40-41-test('cannot return stdin', testNoStdin, execa);42-test('cannot return stdin - sync', testNoStdin, execaSync);43-44-test('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-});48-49-if (isWindows) {50- test('execa() - cmd file', async t => {51- const {stdout} = await execa('hello.cmd');52- t.is(stdout, 'Hello World');53- });54-55- test('execa() - run cmd command', async t => {56- const {stdout} = await execa('cmd', ['/c', 'hello.cmd']);57- t.is(stdout, 'Hello World');58- });59-}60-61-test('execaSync() throws error if ENOENT', t => {62- t.throws(() => {63- execaSync('foo');64- }, {message: ENOENT_REGEXP});65-});66-67-test('skip throwing when using reject option', async t => {68- const {exitCode} = await execa('fail.js', {reject: false});69- t.is(exitCode, 2);70-});71-72-test('skip throwing when using reject option in sync mode', t => {73- const {exitCode} = execaSync('fail.js', {reject: false});74- t.is(exitCode, 2);75-});76-77-const 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-};81-82-test('stripFinalNewline: undefined with stdout', testStripFinalNewline, 1, undefined, execa);83-test('stripFinalNewline: true with stdout', testStripFinalNewline, 1, true, execa);84-test('stripFinalNewline: false with stdout', testStripFinalNewline, 1, false, execa);85-test('stripFinalNewline: undefined with stderr', testStripFinalNewline, 2, undefined, execa);86-test('stripFinalNewline: true with stderr', testStripFinalNewline, 2, true, execa);87-test('stripFinalNewline: false with stderr', testStripFinalNewline, 2, false, execa);88-test('stripFinalNewline: undefined with stdio[*]', testStripFinalNewline, 3, undefined, execa);89-test('stripFinalNewline: true with stdio[*]', testStripFinalNewline, 3, true, execa);90-test('stripFinalNewline: false with stdio[*]', testStripFinalNewline, 3, false, execa);91-test('stripFinalNewline: undefined with stdout - sync', testStripFinalNewline, 1, undefined, execaSync);92-test('stripFinalNewline: true with stdout - sync', testStripFinalNewline, 1, true, execaSync);93-test('stripFinalNewline: false with stdout - sync', testStripFinalNewline, 1, false, execaSync);94-test('stripFinalNewline: undefined with stderr - sync', testStripFinalNewline, 2, undefined, execaSync);95-test('stripFinalNewline: true with stderr - sync', testStripFinalNewline, 2, true, execaSync);96-test('stripFinalNewline: false with stderr - sync', testStripFinalNewline, 2, false, execaSync);97-test('stripFinalNewline: undefined with stdio[*] - sync', testStripFinalNewline, 3, undefined, execaSync);98-test('stripFinalNewline: true with stdio[*] - sync', testStripFinalNewline, 3, true, execaSync);99-test('stripFinalNewline: false with stdio[*] - sync', testStripFinalNewline, 3, false, execaSync);100-101-test('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-});105-106-const 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-};110-111-const BIN_DIR_REGEXP = /node_modules[\\/]\.bin/;112-113-test('preferLocal: true', async t => {114- await t.notThrowsAsync(execa('ava', ['--version'], {preferLocal: true, env: getPathWithoutLocalDir()}));115-});116-117-test('preferLocal: false', async t => {118- await t.throwsAsync(execa('ava', ['--version'], {preferLocal: false, env: getPathWithoutLocalDir()}), {message: ENOENT_REGEXP});119-});120-121-test('preferLocal: undefined', async t => {122- await t.throwsAsync(execa('ava', ['--version'], {env: getPathWithoutLocalDir()}), {message: ENOENT_REGEXP});123-});124-125-test('preferLocal: undefined with $', async t => {126- await t.notThrowsAsync($({env: getPathWithoutLocalDir()})`ava --version`);127-});128-129-test('preferLocal: undefined with $.sync', t => {130- t.notThrows(() => $({env: getPathWithoutLocalDir()}).sync`ava --version`);131-});132-133-test('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-});139-140-test('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-});145-146-const testEarlyErrorShape = async (t, reject) => {147- const subprocess = execa('', {reject});148- t.notThrows(() => {149- subprocess.catch(() => {});150- subprocess.unref();151- subprocess.on('error', () => {});152- });153-};154-155-test('child_process.spawn() early errors have correct shape', testEarlyErrorShape, true);156-test('child_process.spawn() early errors have correct shape - reject false', testEarlyErrorShape, false);157-158-test('child_process.spawn() early errors are propagated', async t => {159- const {failed} = await t.throwsAsync(execa(''));160- t.true(failed);161-});162-163-test('child_process.spawn() early errors are returned', async t => {164- const {failed} = await execa('', {reject: false});165- t.true(failed);166-});167-168-test('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-});174-175-test('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-});179-180-test('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-});187-188-test('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-});193-194-if (!isWindows) {195- test('execa() rejects if running non-executable', async t => {196- await t.throwsAsync(execa('non-executable.js'));197- });198-199- 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-}203-204-if (!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-}216-217-test('use environment variables by default', async t => {218- const {stdout} = await execa('environment.js');219- t.deepEqual(stdout.split('\n'), ['foo', 'undefined']);220-});221-222-test('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-});226-227-test('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-});231-232-test('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-});238-239-test('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-});243-244-const 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-};250-251-test('can use `options.shell: string`', testShellPath, identity);252-test('can use `options.shell: file URL`', testShellPath, pathToFileURL);253-254-test('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-});261-262-test('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));267-268- process.kill(pid, 'SIGKILL');269-});270-271-const 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-};276-277-test('execa()\'s command argument can be a file URL', testFileUrl, execa);278-test('execaSync()\'s command argument can be a file URL', testFileUrl, execaSync);279-test('execaNode()\'s command argument can be a file URL', testFileUrl, execaNode);280-281-const 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-};287-288-test('execa()\'s command argument cannot be a non-file URL', testInvalidFileUrl, execa);289-test('execaSync()\'s command argument cannot be a non-file URL', testInvalidFileUrl, execaSync);290-test('execaNode()\'s command argument cannot be a non-file URL', testInvalidFileUrl, execaNode);291-292-const testInvalidCommand = async (t, execaMethod) => {293- t.throws(() => {294- execaMethod(['command', 'arg']);295- }, {message: /First argument must be a string or a file URL/});296-};297-298-test('execa()\'s command argument must be a string or file URL', testInvalidCommand, execa);299-test('execaSync()\'s command argument must be a string or file URL', testInvalidCommand, execaSync);300-test('execaNode()\'s command argument must be a string or file URL', testInvalidCommand, execaNode);deleted:test/verbose.js-33 removed
1-import test from 'ava';2-import {execa} from '../index.js';3-import {setFixtureDir} from './helpers/fixtures-dir.js';4-5-setFixtureDir();6-7-const normalizeTimestamp = output => output.replaceAll(/\d/g, '0');8-const testTimestamp = '[00:00:00.000]';9-10-test('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-});15-16-test('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-});21-22-test('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-});26-27-test('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\\")"30-one31-${testTimestamp} node -e "console.error(\\"two\\")"32-two`);33-});modified:index.js+5 added-318 removed
1-import {Buffer} from 'node:buffer';2-import {setMaxListeners} from 'node:events';3-import {basename} from 'node:path';4-import childProcess from 'node:child_process';5-import process from 'node:process';6-import crossSpawn from 'cross-spawn';7-import stripFinalNewline from 'strip-final-newline';8-import {npmRunPathEnv} from 'npm-run-path';9-import {makeError, makeEarlyError, makeSuccessResult} from './lib/error.js';10-import {handleNodeOption} from './lib/node.js';11-import {handleInputAsync, pipeOutputAsync, cleanupStdioStreams} from './lib/stdio/async.js';12-import {handleInputSync, pipeOutputSync} from './lib/stdio/sync.js';13-import {spawnedKill, validateTimeout, normalizeForceKillAfterDelay, cleanupOnExit, isFailedExit} from './lib/kill.js';14-import {pipeToProcess} from './lib/pipe/setup.js';15-import {getSpawnedResult, makeAllStream} from './lib/stream.js';16-import {mergePromise} from './lib/promise.js';17-import {joinCommand} from './lib/escape.js';18-import {parseCommand} from './lib/command.js';19-import {normalizeCwd, safeNormalizeFileUrl, normalizeFileUrl} from './lib/cwd.js';20-import {parseTemplates} from './lib/script.js';21-import {logCommand, verboseDefault} from './lib/verbose.js';22-import {bufferToUint8Array} from './lib/stdio/utils.js';23-24-const DEFAULT_MAX_BUFFER = 1000 * 1000 * 100;25-26-const getEnv = ({env: envOption, extendEnv, preferLocal, localDir, nodePath}) => {27- const env = extendEnv ? {...process.env, ...envOption} : envOption;28-29- if (preferLocal) {30- return npmRunPathEnv({env, cwd: localDir, execPath: nodePath});31- }32-33- return env;34-};35-36-const 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-};42-43-// Prevent passing the `timeout` option directly to `child_process.spawn()`44-const handleAsyncOptions = ({timeout, ...options}) => ({...options, timeoutDuration: timeout});45-46-const 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-};53-54-const normalizeSyncOptions = options => options.node && !options.ipc ? {...options, ipc: false} : options;55-56-const validateSyncOptions = ({ipc}) => {57- if (ipc) {58- throw new TypeError('The "ipc: true" option cannot be used with synchronous methods.');59- }60-};61-62-const handleOptionalArguments = (args = [], options = {}) => Array.isArray(args)63- ? [args, options]64- : [[], args];65-66-const handleArguments = (rawFile, rawArgs, rawOptions) => {67- const filePath = safeNormalizeFileUrl(rawFile, 'First argument');68- const {command, escapedCommand} = joinCommand(filePath, rawArgs);69-70- rawOptions.cwd = normalizeCwd(rawOptions.cwd);71- const [processedFile, processedArgs, processedOptions] = handleNodeOption(filePath, rawArgs, rawOptions);72-73- const {command: file, args, options: initialOptions} = crossSpawn._parse(processedFile, processedArgs, processedOptions);74-75- const options = addDefaultOptions(initialOptions);76- validateTimeout(options);77- options.shell = normalizeFileUrl(options.shell);78- options.env = getEnv(options);79- options.forceKillAfterDelay = normalizeForceKillAfterDelay(options.forceKillAfterDelay);80-81- if (process.platform === 'win32' && basename(file, '.exe') === 'cmd') {82- // #11683- args.unshift('/q');84- }85-86- logCommand(escapedCommand, options);87-88- return {file, args, command, escapedCommand, options};89-};90-91-const 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-});130-131-const handleOutput = (options, value) => {132- if (value === undefined || value === null) {133- return;134- }135-136- if (Array.isArray(value)) {137- return value;138- }139-140- if (Buffer.isBuffer(value)) {141- value = bufferToUint8Array(value);142- }143-144- return options.stripFinalNewline ? stripFinalNewline(value) : value;145-};146-147-export function execa(rawFile, rawArgs, rawOptions) {148- const {file, args, command, escapedCommand, options} = handleAsyncArguments(rawFile, rawArgs, rawOptions);149- const stdioStreamsGroups = handleInputAsync(options);150-151- 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- }163-164- const controller = new AbortController();165- setMaxListeners(Number.POSITIVE_INFINITY, controller.signal);166-167- const originalStreams = [...spawned.stdio];168- pipeOutputAsync(spawned, stdioStreamsGroups, controller);169- cleanupOnExit(spawned, options, controller);170-171- 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});174-175- const promise = handlePromise({spawned, options, stdioStreamsGroups, originalStreams, command, escapedCommand, controller});176- mergePromise(spawned, promise);177- return spawned;178-}179-180-const handlePromise = async ({spawned, options, stdioStreamsGroups, originalStreams, command, escapedCommand, controller}) => {181- const context = {timedOut: false};182-183- const [184- errorInfo,185- [exitCode, signal],186- stdioResults,187- allResult,188- ] = await getSpawnedResult({spawned, options, context, stdioStreamsGroups, originalStreams, controller});189- controller.abort();190-191- const stdio = stdioResults.map(stdioResult => handleOutput(options, stdioResult));192- const all = handleOutput(options, allResult);193-194- 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- });208-209- if (!options.reject) {210- return returnedError;211- }212-213- throw returnedError;214- }215-216- return makeSuccessResult({command, escapedCommand, stdio, all, options});217-};218-219-export function execaSync(rawFile, rawArgs, rawOptions) {220- const {file, args, command, escapedCommand, options} = handleSyncArguments(rawFile, rawArgs, rawOptions);221- const stdioStreamsGroups = handleInputSync(options);222-223- let result;224- try {225- result = childProcess.spawnSync(file, args, options);226- } catch (error) {227- const errorInstance = makeEarlyError({error, command, escapedCommand, stdioStreamsGroups, options});228-229- if (!options.reject) {230- return errorInstance;231- }232-233- throw errorInstance;234- }235-236- pipeOutputSync(stdioStreamsGroups, result);237-238- const output = result.output || Array.from({length: 3});239- const stdio = output.map(stdioOutput => handleOutput(options, stdioOutput));240-241- 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- });253-254- if (!options.reject) {255- return error;256- }257-258- throw error;259- }260-261- return makeSuccessResult({command, escapedCommand, stdio, options});262-}263-264-const normalizeScriptStdin = ({input, inputFile, stdio}) => input === undefined && inputFile === undefined && stdio === undefined265- ? {stdin: 'inherit'}266- : {};267-268-const normalizeScriptOptions = (options = {}) => ({269- preferLocal: true,270- ...normalizeScriptStdin(options),271- ...options,272-});273-274-function create$(options) {275- function $(templatesOrOptions, ...expressions) {276- if (!Array.isArray(templatesOrOptions)) {277- return create$({...options, ...templatesOrOptions});278- }279-280- const [file, ...args] = parseTemplates(templatesOrOptions, expressions);281- return execa(file, args, normalizeScriptOptions(options));282- }283-284- $.sync = (templates, ...expressions) => {285- if (!Array.isArray(templates)) {286- throw new TypeError('Please use $(options).sync`command` instead of $.sync(options)`command`.');287- }288-289- const [file, ...args] = parseTemplates(templates, expressions);290- return execaSync(file, args, normalizeScriptOptions(options));291- };292-293- $.s = $.sync;294-295- return $;296-}297-298-export const $ = create$();299-300-export function execaCommand(command, options) {301- const [file, ...args] = parseCommand(command);302- return execa(file, args, options);303-}304-305-export function execaCommandSync(command, options) {306- const [file, ...args] = parseCommand(command);307- return execaSync(file, args, options);308-}309-310-export function execaNode(file, args, options) {311- [args, options] = handleOptionalArguments(args, options);312-313- if (options.node === false) {314- throw new TypeError('The "node" option cannot be false with `execaNode()`.');315- }316-317- return execa(file, args, {...options, node: true});318-}1+export {execa} from './lib/async.js';2+export {execaSync} from './lib/sync.js';3+export {execaCommand, execaCommandSync} from './lib/command.js';4+export {execaNode} from './lib/arguments/node.js';5+export {$} from './lib/script.js';