Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 20 additions & 3 deletions lib/asyncbox.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {limitFunction} from 'p-limit';
import type {limitFunction} from 'p-limit';

import type {
CancellablePromise,
Expand All @@ -11,6 +11,17 @@ import type {

const LONG_SLEEP_THRESHOLD = 5000; // anything over 5000ms will turn into a spin

type PLimitModule = {limitFunction: typeof limitFunction};

// p-limit is ESM-only. tsc downlevels a plain `import()` in CommonJS output into a
// require()-in-a-microtask, which still hits Node's require(esm) interop and can race with a
// concurrent dynamic import() of the same module elsewhere in the process
// (ERR_REQUIRE_ESM_RACE_CONDITION). Route through `new Function` so tsc can't see or rewrite the
// import() call, keeping it a genuine native dynamic import in both the ESM and CJS builds.
const dynamicImport = new Function('specifier', 'return import(specifier)') as (
specifier: string,
) => Promise<PLimitModule>;

/** Error thrown by {@link withTimeout} when the deadline is exceeded. */
export class TimeoutError extends Error {
constructor(message?: string) {
Expand Down Expand Up @@ -241,7 +252,7 @@ export async function asyncmap<T, R>(
);
}
const adjustedMapper =
options === true ? mapperAsync : limitFunction(mapperAsync, {concurrency: options.concurrency});
options === true ? mapperAsync : (await getLimitFunction())(mapperAsync, {concurrency: options.concurrency});
return Promise.all(coll.map(adjustedMapper));
}

Expand Down Expand Up @@ -271,7 +282,7 @@ export async function asyncfilter<T>(
}, Promise.resolve([]));
}
const adjustedFilter =
options === true ? filterAsync : limitFunction(filterAsync, {concurrency: options.concurrency});
options === true ? filterAsync : (await getLimitFunction())(filterAsync, {concurrency: options.concurrency});
const bools = await Promise.all(coll.map(adjustedFilter));
return coll.reduce<T[]>((acc, item, i) => {
if (bools[i]) {
Expand Down Expand Up @@ -363,3 +374,9 @@ function parseSleepArg(arg: SleepArg): {ms: number; cancelError?: string | Error
}
throw new TypeError('sleep: expected a finite number or an object with ms');
}

let limitFunctionPromise: Promise<PLimitModule> | undefined;
async function getLimitFunction() {
limitFunctionPromise ??= dynamicImport('p-limit');
return (await limitFunctionPromise).limitFunction;
}