| 1 |
import * as os from 'node:os'; |
| 2 |
// availableParallelism available only since node v19, for older versions use |
| 3 |
// cpus() cpus() can return an empty list if /proc is not mounted, use 1 in |
| 4 |
// this case |
| 5 |
/* c8 ignore start */ |
| 6 |
const defLimit = 'availableParallelism' in os ? |
| 7 |
Math.max(1, os.availableParallelism() - 1) |
| 8 |
: Math.max(1, os.cpus().length - 1); |
| 9 |
export const callLimit = (queue, { limit = defLimit, rejectLate } = {}) => new Promise((res, rej) => { |
| 10 |
let active = 0; |
| 11 |
let current = 0; |
| 12 |
const results = []; |
| 13 |
// Whether or not we rejected, distinct from the rejection just in case the rejection itself is falsey |
| 14 |
let rejected = false; |
| 15 |
let rejection; |
| 16 |
const reject = (er) => { |
| 17 |
if (rejected) |
| 18 |
return; |
| 19 |
rejected = true; |
| 20 |
rejection ??= er; |
| 21 |
if (!rejectLate) |
| 22 |
rej(rejection); |
| 23 |
}; |
| 24 |
let resolved = false; |
| 25 |
const resolve = () => { |
| 26 |
if (resolved || active > 0) |
| 27 |
return; |
| 28 |
resolved = true; |
| 29 |
res(results); |
| 30 |
}; |
| 31 |
const run = () => { |
| 32 |
const c = current++; |
| 33 |
if (c >= queue.length) |
| 34 |
return rejected ? reject() : resolve(); |
| 35 |
active++; |
| 36 |
const step = queue[c]; |
| 37 |
/* c8 ignore start */ |
| 38 |
if (!step) |
| 39 |
throw new Error('walked off queue'); |
| 40 |
/* c8 ignore stop */ |
| 41 |
results[c] = step() |
| 42 |
.then(result => { |
| 43 |
active--; |
| 44 |
results[c] = result; |
| 45 |
return result; |
| 46 |
}, er => { |
| 47 |
active--; |
| 48 |
reject(er); |
| 49 |
}) |
| 50 |
.then(result => { |
| 51 |
if (rejected && active === 0) |
| 52 |
return rej(rejection); |
| 53 |
run(); |
| 54 |
return result; |
| 55 |
}); |
| 56 |
}; |
| 57 |
for (let i = 0; i < limit; i++) |
| 58 |
run(); |
| 59 |
}); |
| 60 |
//# sourceMappingURL=index.js.map |