timeout.js
This file
Path
lib/terminate/timeout.js
27 lines · 1.1 KiB · JavaScript
Last changed by
Fix invalid `timeout` and `forceKillAfterDelay` valuesSindre Sorhusbefore adoptiond9a5689
History of this fileTake it
12345678910111213141516171819202122232425262728import {setTimeout} from 'node:timers/promises';import {DiscardedError} from '../return/final-error.js';
// Validate `timeout` optionexport const validateTimeout = ({timeout}) => { if (timeout !== undefined && !isValidDelay(timeout)) { throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer up to ${MAX_DELAY}, got \`${timeout}\` (${typeof timeout})`); }};
// Fractional numbers are excluded since `spawnSync()` requires an integer `timeout`export const isValidDelay = delay => Number.isInteger(delay) && delay >= 0 && delay <= MAX_DELAY;
// Timers fire right away when their delay is larger than thisexport const 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();};