Skip to content
Myr

Improve validation and typing of signals (#1025)

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

authored by ehmicky · committed by GitHub · parent 9d7eed8 · Browse files · 16 files+245 added−32 removed
This commit

State

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

Diff stats

16 files+245 added−32 removed

  • tests:+145 added−13 removed
  • other:+100 added−19 removed

16 files+245 added−32 removed

modified:lib/arguments/options.js+2 added
modified:lib/terminate/kill.js+5 added-10 removed
added:lib/terminate/signal.js+66 added
1import {constants} from 'node:os';23// Normalize signals for comparison purpose.4// Also validate the signal exists.5export const normalizeKillSignal = killSignal => {6 const optionName = 'option `killSignal`';7 if (killSignal === 0) {8 throw new TypeError(`Invalid ${optionName}: 0 cannot be used.`);9 }1011 return normalizeSignal(killSignal, optionName);12};1314export const normalizeSignalArgument = signal => signal === 015 ? signal16 : normalizeSignal(signal, '`subprocess.kill()`\'s argument');1718const normalizeSignal = (signalNameOrInteger, optionName) => {19 if (Number.isInteger(signalNameOrInteger)) {20 return normalizeSignalInteger(signalNameOrInteger, optionName);21 }2223 if (typeof signalNameOrInteger === 'string') {24 return normalizeSignalName(signalNameOrInteger, optionName);25 }2627 throw new TypeError(`Invalid ${optionName} ${String(signalNameOrInteger)}: it must be a string or an integer.\n${getAvailableSignals()}`);28};2930const normalizeSignalInteger = (signalInteger, optionName) => {31 if (signalsIntegerToName.has(signalInteger)) {32 return signalsIntegerToName.get(signalInteger);33 }3435 throw new TypeError(`Invalid ${optionName} ${signalInteger}: this signal integer does not exist.\n${getAvailableSignals()}`);36};3738const getSignalsIntegerToName = () => new Map(Object.entries(constants.signals)39 .reverse()40 .map(([signalName, signalInteger]) => [signalInteger, signalName]));4142const signalsIntegerToName = getSignalsIntegerToName();4344const normalizeSignalName = (signalName, optionName) => {45 if (signalName in constants.signals) {46 return signalName;47 }4849 if (signalName.toUpperCase() in constants.signals) {50 throw new TypeError(`Invalid ${optionName} '${signalName}': please rename it to '${signalName.toUpperCase()}'.`);51 }5253 throw new TypeError(`Invalid ${optionName} '${signalName}': this signal name does not exist.\n${getAvailableSignals()}`);54};5556const getAvailableSignals = () => `Available signal names: ${getAvailableSignalNames()}.57Available signal numbers: ${getAvailableSignalIntegers()}.`;5859const getAvailableSignalNames = () => Object.keys(constants.signals)60 .sort()61 .map(signalName => `'${signalName}'`)62 .join(', ');6364const getAvailableSignalIntegers = () => [...new Set(Object.values(constants.signals)65 .sort((signalInteger, signalIntegerTwo) => signalInteger - signalIntegerTwo))]66 .join(', ');
modified:test/helpers/early-error.js+4 added-2 removed
modified:test/io/max-buffer.js+4 added-6 removed
2 unmodified lines
3import getStream from 'get-stream';4import {execa, execaSync} from '../../index.js';5import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6import {fullStdio} from '../helpers/stdio.js';7import {getEarlyErrorSubprocess, getEarlyErrorSubprocessSync} from '../helpers/early-error.js';7import {getEarlyErrorSubprocess} from '../helpers/early-error.js';8import {maxBuffer, assertErrorMessage} from '../helpers/max-buffer.js';910setFixtureDirectory();11
247 unmodified lines
259test('abort stream when hitting maxBuffer with stdout', testMaxBufferAbort, 1);260test('abort stream when hitting maxBuffer with stderr', testMaxBufferAbort, 2);261test('abort stream when hitting maxBuffer with stdio[*]', testMaxBufferAbort, 3);262263const testEarlyError = async (t, getSubprocess) => {264 const {failed, isMaxBuffer} = await getSubprocess({reject: false, maxBuffer: 1});263test('error.isMaxBuffer is false on early errors', async t => {264 const {failed, isMaxBuffer} = await getEarlyErrorSubprocess({reject: false, maxBuffer: 1});265 t.true(failed);266 t.false(isMaxBuffer);267};267});268269test('error.isMaxBuffer is false on early errors', testEarlyError, getEarlyErrorSubprocess);270test('error.isMaxBuffer is false on early errors, sync', testEarlyError, getEarlyErrorSubprocessSync);
modified:test/return/early-error.js+2 added-1 removed
6 unmodified lines
7 earlyErrorOptions,8 getEarlyErrorSubprocess,9 getEarlyErrorSubprocessSync,10 expectedEarlyError,11 expectedEarlyErrorSync,12} from '../helpers/early-error.js';1314setFixtureDirectory();15
27 unmodified lines
43 t.true(failed);44});4546test('child_process.spawnSync() early errors are propagated with a correct shape', t => {46 t.throws(getEarlyErrorSubprocessSync, expectedEarlyError);47 t.throws(getEarlyErrorSubprocessSync, expectedEarlyErrorSync);48});4950test('child_process.spawnSync() early errors are propagated with a correct shape - reject false', t => {51 const {failed} = getEarlyErrorSubprocessSync({reject: false});
63 unmodified lines
modified:test/terminate/kill-force.js+2 added
88 unmodified lines
89 test('`forceKillAfterDelay: true` should kill after a timeout', testForceKill, true);90 test('`forceKillAfterDelay: undefined` should kill after a timeout', testForceKill, undefined);91 test('`forceKillAfterDelay` should kill after a timeout with SIGTERM', testForceKill, 50, 'SIGTERM');92 test('`forceKillAfterDelay` should kill after a timeout with the killSignal string', testForceKill, 50, 'SIGINT', {killSignal: 'SIGINT'});93 test('`forceKillAfterDelay` should kill after a timeout with the killSignal string, mixed', testForceKill, 50, 'SIGINT', {killSignal: constants.signals.SIGINT});94 test('`forceKillAfterDelay` should kill after a timeout with the killSignal number', testForceKill, 50, constants.signals.SIGINT, {killSignal: constants.signals.SIGINT});95 test('`forceKillAfterDelay` should kill after a timeout with the killSignal number, mixed', testForceKill, 50, constants.signals.SIGINT, {killSignal: 'SIGINT'});96 test('`forceKillAfterDelay` should kill after a timeout with an error', testForceKill, 50, new Error('test'));97 test('`forceKillAfterDelay` should kill after a timeout with an error and a killSignal', testForceKill, 50, new Error('test'), {killSignal: 'SIGINT'});9899 test('`forceKillAfterDelay` works with the "signal" option', async t => {
43 unmodified lines
modified:test/terminate/kill-signal.js+46 added-4 removed
1import {once} from 'node:events';2import {platform, version} from 'node:process';3import {constants} from 'node:os';4import {setImmediate} from 'node:timers/promises';5import test from 'ava';5import {execa} from '../../index.js';6import {execa, execaSync} from '../../index.js';7import {setFixtureDirectory} from '../helpers/fixtures-directory.js';89setFixtureDirectory();1011const isWindows = platform === 'win32';12const majorNodeVersion = Number(version.split('.')[0].slice(1));1314const testKillSignal = async (t, killSignal) => {15 const {isTerminated, signal} = await t.throwsAsync(execa('forever.js', {killSignal, timeout: 1}));16 t.true(isTerminated);17 t.is(signal, 'SIGINT');18};1920test('Can use killSignal: "SIGINT"', testKillSignal, 'SIGINT');21test('Can use killSignal: 2', testKillSignal, constants.signals.SIGINT);2223const testKillSignalSync = (t, killSignal) => {24 const {isTerminated, signal} = t.throws(() => {25 execaSync('forever.js', {killSignal, timeout: 1});26 });27 t.true(isTerminated);28 t.is(signal, 'SIGINT');29};3031test('Can use killSignal: "SIGINT", sync', testKillSignalSync, 'SIGINT');32test('Can use killSignal: 2, sync', testKillSignalSync, constants.signals.SIGINT);3334test('Can call .kill("SIGTERM")', async t => {35 const subprocess = execa('forever.js');36 subprocess.kill('SIGTERM');37 const {isTerminated, signal} = await t.throwsAsync(subprocess);38 t.true(isTerminated);39 t.is(signal, 'SIGTERM');40});4142test('Can call .kill(15)', async t => {43 const subprocess = execa('forever.js');44 subprocess.kill(constants.signals.SIGTERM);45 const {isTerminated, signal} = await t.throwsAsync(subprocess);46 t.true(isTerminated);47 t.is(signal, 'SIGTERM');48});4950test('Can call .kill(0)', async t => {51 const subprocess = execa('forever.js');52 t.true(subprocess.kill(0));53 subprocess.kill();54 await t.throwsAsync(subprocess);55 t.false(subprocess.kill(0));56});5758test('Can call `.kill()` multiple times', async t => {59 const subprocess = execa('forever.js');60 subprocess.kill();61 subprocess.kill();
32 unmodified lines
94 }, {message});95 await subprocess;96};9753test('Cannot call .kill(null)', testInvalidKillArgument, null);54test('Cannot call .kill(0n)', testInvalidKillArgument, 0n);55test('Cannot call .kill(true)', testInvalidKillArgument, true);98test('Cannot call .kill(errorObject)', testInvalidKillArgument, {name: '', message: '', stack: ''});99test('Cannot call .kill(errorArray)', testInvalidKillArgument, [new Error('test')]);100test('Cannot call .kill(undefined, true)', testInvalidKillArgument, undefined, true);101test('Cannot call .kill("SIGTERM", true)', testInvalidKillArgument, 'SIGTERM', true);
53 unmodified lines
added:test/terminate/signal.js+87 added
1import test from 'ava';2import {execa, execaSync} from '../../index.js';3import {setFixtureDirectory} from '../helpers/fixtures-directory.js';45setFixtureDirectory();67const VALIDATION_MESSAGES = {8 string: 'this signal name does not exist',9 integer: 'this signal integer does not exist',10 other: 'it must be a string or an integer',11 rename: 'please rename it to',12 zero: '0 cannot be used',13};1415const validateMessage = (t, message, type) => {16 t.true(message.includes(VALIDATION_MESSAGES[type]));1718 if (type !== 'rename' && type !== 'zero') {19 t.true(message.includes('Available signal names: \'SIGABRT\', '));20 t.true(message.includes('Available signal numbers: 1, '));21 }22};2324const testInvalidKillSignal = (t, killSignal, type, execaMethod) => {25 const {message} = t.throws(() => {26 execaMethod('empty.js', {killSignal});27 });28 t.true(message.includes('Invalid option `killSignal`'));29 validateMessage(t, message, type);30};3132test('Cannot use killSignal: "SIGOTHER"', testInvalidKillSignal, 'SIGOTHER', 'string', execa);33test('Cannot use killSignal: "Sigterm"', testInvalidKillSignal, 'Sigterm', 'rename', execa);34test('Cannot use killSignal: "sigterm"', testInvalidKillSignal, 'sigterm', 'rename', execa);35test('Cannot use killSignal: -1', testInvalidKillSignal, -1, 'integer', execa);36test('Cannot use killSignal: 200', testInvalidKillSignal, 200, 'integer', execa);37test('Cannot use killSignal: 1n', testInvalidKillSignal, 1n, 'other', execa);38test('Cannot use killSignal: 1.5', testInvalidKillSignal, 1.5, 'other', execa);39test('Cannot use killSignal: Infinity', testInvalidKillSignal, Number.POSITIVE_INFINITY, 'other', execa);40test('Cannot use killSignal: NaN', testInvalidKillSignal, Number.NaN, 'other', execa);41test('Cannot use killSignal: false', testInvalidKillSignal, false, 'other', execa);42test('Cannot use killSignal: null', testInvalidKillSignal, null, 'other', execa);43test('Cannot use killSignal: symbol', testInvalidKillSignal, Symbol('test'), 'other', execa);44test('Cannot use killSignal: {}', testInvalidKillSignal, {}, 'other', execa);45test('Cannot use killSignal: 0', testInvalidKillSignal, 0, 'zero', execa);46test('Cannot use killSignal: "SIGOTHER", sync', testInvalidKillSignal, 'SIGOTHER', 'string', execaSync);47test('Cannot use killSignal: "Sigterm", sync', testInvalidKillSignal, 'Sigterm', 'rename', execaSync);48test('Cannot use killSignal: "sigterm", sync', testInvalidKillSignal, 'sigterm', 'rename', execaSync);49test('Cannot use killSignal: -1, sync', testInvalidKillSignal, -1, 'integer', execaSync);50test('Cannot use killSignal: 200, sync', testInvalidKillSignal, 200, 'integer', execaSync);51test('Cannot use killSignal: 1.5, sync', testInvalidKillSignal, 1.5, 'other', execaSync);52test('Cannot use killSignal: Infinity, sync', testInvalidKillSignal, Number.POSITIVE_INFINITY, 'other', execaSync);53test('Cannot use killSignal: NaN, sync', testInvalidKillSignal, Number.NaN, 'other', execaSync);54test('Cannot use killSignal: null, sync', testInvalidKillSignal, null, 'other', execaSync);55test('Cannot use killSignal: symbol, sync', testInvalidKillSignal, Symbol('test'), 'other', execaSync);56test('Cannot use killSignal: {}, sync', testInvalidKillSignal, {}, 'other', execaSync);57test('Cannot use killSignal: 0, sync', testInvalidKillSignal, 0, 'zero', execaSync);5859const testInvalidSignalArgument = async (t, signal, type) => {60 const subprocess = execa('empty.js');61 const {message} = t.throws(() => {62 subprocess.kill(signal);63 });6465 if (type === 'other') {66 t.true(message.includes('must be an error instance or a signal name string/integer'));67 } else {68 t.true(message.includes('Invalid `subprocess.kill()`\'s argument'));69 validateMessage(t, message, type);70 }7172 await subprocess;73};7475test('Cannot use subprocess.kill("SIGOTHER")', testInvalidSignalArgument, 'SIGOTHER', 'string');76test('Cannot use subprocess.kill("Sigterm")', testInvalidSignalArgument, 'Sigterm', 'rename');77test('Cannot use subprocess.kill("sigterm")', testInvalidSignalArgument, 'sigterm', 'rename');78test('Cannot use subprocess.kill(-1)', testInvalidSignalArgument, -1, 'integer');79test('Cannot use subprocess.kill(200)', testInvalidSignalArgument, 200, 'integer');80test('Cannot use subprocess.kill(1n)', testInvalidSignalArgument, 1n, 'other');81test('Cannot use subprocess.kill(1.5)', testInvalidSignalArgument, 1.5, 'other');82test('Cannot use subprocess.kill(Infinity)', testInvalidSignalArgument, Number.POSITIVE_INFINITY, 'other');83test('Cannot use subprocess.kill(NaN)', testInvalidSignalArgument, Number.NaN, 'other');84test('Cannot use subprocess.kill(false)', testInvalidSignalArgument, false, 'other');85test('Cannot use subprocess.kill(null)', testInvalidSignalArgument, null, 'other');86test('Cannot use subprocess.kill(symbol)', testInvalidSignalArgument, Symbol('test'), 'other');87test('Cannot use subprocess.kill({})', testInvalidSignalArgument, {}, 'other');
modified:test-d/arguments/options.test-d.ts+12 added
133 unmodified lines
134await execa('unicorns', {killSignal: 9});135execaSync('unicorns', {killSignal: 9});136expectError(await execa('unicorns', {killSignal: false}));137expectError(execaSync('unicorns', {killSignal: false}));138expectError(await execa('unicorns', {killSignal: 'Sigterm'}));139expectError(execaSync('unicorns', {killSignal: 'Sigterm'}));140expectError(await execa('unicorns', {killSignal: 'sigterm'}));141expectError(execaSync('unicorns', {killSignal: 'sigterm'}));142expectError(await execa('unicorns', {killSignal: 'SIGOTHER'}));143expectError(execaSync('unicorns', {killSignal: 'SIGOTHER'}));144expectError(await execa('unicorns', {killSignal: 'SIGEMT'}));145expectError(execaSync('unicorns', {killSignal: 'SIGEMT'}));146expectError(await execa('unicorns', {killSignal: 'SIGCLD'}));147expectError(execaSync('unicorns', {killSignal: 'SIGCLD'}));148expectError(await execa('unicorns', {killSignal: 'SIGRT1'}));149expectError(execaSync('unicorns', {killSignal: 'SIGRT1'}));150151await execa('unicorns', {forceKillAfterDelay: false});152expectError(execaSync('unicorns', {forceKillAfterDelay: false}));153await execa('unicorns', {forceKillAfterDelay: 42});
59 unmodified lines
modified:test-d/return/result-main.test-d.ts+4 added-4 removed
26 unmodified lines
27expectType<boolean>(unicornsResult.timedOut);28expectType<boolean>(unicornsResult.isCanceled);29expectType<boolean>(unicornsResult.isTerminated);30expectType<boolean>(unicornsResult.isMaxBuffer);31expectType<string | undefined>(unicornsResult.signal);31expectType<NodeJS.Signals | undefined>(unicornsResult.signal);32expectType<string | undefined>(unicornsResult.signalDescription);33expectType<string>(unicornsResult.cwd);34expectType<number>(unicornsResult.durationMs);35expectType<Result[]>(unicornsResult.pipedFrom);
7 unmodified lines
43expectType<boolean>(unicornsResultSync.timedOut);44expectType<boolean>(unicornsResultSync.isCanceled);45expectType<boolean>(unicornsResultSync.isTerminated);46expectType<boolean>(unicornsResultSync.isMaxBuffer);47expectType<string | undefined>(unicornsResultSync.signal);47expectType<NodeJS.Signals | undefined>(unicornsResultSync.signal);48expectType<string | undefined>(unicornsResultSync.signalDescription);49expectType<string>(unicornsResultSync.cwd);50expectType<number>(unicornsResultSync.durationMs);51expectType<[]>(unicornsResultSync.pipedFrom);
8 unmodified lines
60 expectType<boolean>(error.timedOut);61 expectType<boolean>(error.isCanceled);62 expectType<boolean>(error.isTerminated);63 expectType<boolean>(error.isMaxBuffer);64 expectType<string | undefined>(error.signal);64 expectType<NodeJS.Signals | undefined>(error.signal);65 expectType<string | undefined>(error.signalDescription);66 expectType<string>(error.cwd);67 expectType<number>(error.durationMs);68 expectType<string>(error.shortMessage);
13 unmodified lines
82 expectType<boolean>(errorSync.timedOut);83 expectType<boolean>(errorSync.isCanceled);84 expectType<boolean>(errorSync.isTerminated);85 expectType<boolean>(errorSync.isMaxBuffer);86 expectType<string | undefined>(errorSync.signal);86 expectType<NodeJS.Signals | undefined>(errorSync.signal);87 expectType<string | undefined>(errorSync.signalDescription);88 expectType<string>(errorSync.cwd);89 expectType<number>(errorSync.durationMs);90 expectType<string>(errorSync.shortMessage);
5 unmodified lines
modified:test-d/subprocess/subprocess.test-d.ts+6 added
12 unmodified lines
13subprocess.kill('SIGKILL', new Error('test'));14subprocess.kill(undefined, new Error('test'));15expectError(subprocess.kill(null));16expectError(subprocess.kill(0n));17expectError(subprocess.kill('Sigkill'));18expectError(subprocess.kill('sigkill'));19expectError(subprocess.kill('SIGOTHER'));20expectError(subprocess.kill('SIGEMT'));21expectError(subprocess.kill('SIGCLD'));22expectError(subprocess.kill('SIGRT1'));23expectError(subprocess.kill([new Error('test')]));24expectError(subprocess.kill({message: 'test'}));25expectError(subprocess.kill(undefined, {}));26expectError(subprocess.kill('SIGKILL', {}));
14 unmodified lines
modified:types/arguments/options.d.ts+1 added-1 removed
276 unmodified lines
277 This can be either a name (like `'SIGTERM'`) or a number (like `9`).278279 @default 'SIGTERM'280 */281 readonly killSignal?: string | number;281 readonly killSignal?: NodeJS.Signals | number;282283 /**284 Run the subprocess independently from the current process.285
85 unmodified lines
modified:types/return/result.d.ts+1 added-1 removed
115 unmodified lines
116 - Another process. This case is [not supported on Windows](https://nodejs.org/api/process.html#signal-events).117118 If a signal terminated the subprocess, this property is defined and included in the error message. Otherwise it is `undefined`.119 */120 signal?: string;120 signal?: NodeJS.Signals;121122 /**123 A human-friendly description of the signal that was used to terminate the subprocess.124
65 unmodified lines
modified:types/subprocess/subprocess.d.ts+2 added-2 removed
84 unmodified lines
85 When an error is passed as argument, it is set to the subprocess' `error.cause`. The subprocess is then terminated with the default signal. This does not emit the [`error` event](https://nodejs.org/api/child_process.html#event-error).8687 [More info.](https://nodejs.org/api/child_process.html#subprocesskillsignal)88 */89 kill(signal: Parameters<ChildProcess['kill']>[0], error?: Error): ReturnType<ChildProcess['kill']>;90 kill(error?: Error): ReturnType<ChildProcess['kill']>;89 kill(signal?: NodeJS.Signals | number, error?: Error): boolean;90 kill(error?: Error): boolean;9192 /**93 Subprocesses are [async iterables](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/asyncIterator). They iterate over each output line.94 */
38 unmodified lines
modified:package.json+1 added-1 removed
50 unmodified lines
51 "@sindresorhus/merge-streams": "^4.0.0",52 "cross-spawn": "^7.0.3",53 "figures": "^6.1.0",54 "get-stream": "^9.0.0",55 "human-signals": "^6.0.0",55 "human-signals": "^7.0.0",56 "is-plain-obj": "^4.1.0",57 "is-stream": "^4.0.1",58 "npm-run-path": "^5.2.0",59 "pretty-ms": "^9.0.0",
41 unmodified lines