timeout.js
This file
Path
lib/terminate/timeout.js
33 lines · 1.2 KiB · JavaScript
Last changed by
Fix wrong-typed options and arguments being silently ignored or coercedSindre Sorhusbefore adoptionb57d643
History of this fileTake it
12345678910111213141516171819202122232425262728293031323334import {setTimeout} from 'node:timers/promises';import {DiscardedError} from '../return/final-error.js';import {getTypeName} from '../utils/type-name.js';
// Validate `timeout` optionexport const validateTimeout = ({timeout}) => { if (timeout !== undefined) { validateDelay(timeout, 'timeout'); }};
// Used by the `timeout` and `forceKillAfterDelay` options.// Fractional numbers are excluded since `spawnSync()` requires an integer `timeout`.export const validateDelay = (delay, optionName) => { if (!Number.isInteger(delay) || delay < 0 || delay > MAX_DELAY) { throw new TypeError(`Expected the \`${optionName}\` option to be a non-negative integer up to ${MAX_DELAY}, got \`${delay}\` (${getTypeName(delay)})`); }};
// Timers fire right away when their delay is larger than thisconst MAX_DELAY = (2 ** 31) - 1;
// Fails when the `timeout` option is exceededexport const throwOnTimeout = (kill, timeout, context, controller) => timeout === 0 || timeout === undefined ? [] : [killAfterTimeout(kill, timeout, context, controller)];
const killAfterTimeout = async (kill, timeout, context, {signal}) => { await setTimeout(timeout, undefined, {signal}); context.terminationReason ??= 'timeout'; kill(); throw new DiscardedError();};