// === keep your Queue, Node, pLimit, validateConcurrency exactly as-is === import { pLimit } from '@intlayer/config/utils'; // --- NEW: single, shared limiter for the whole process --- let _globalLimiter: ReturnType | null = null; /** Get (and optionally configure) the single, shared limiter. */ export const getGlobalLimiter = (concurrency?: number) => { if (!_globalLimiter) { _globalLimiter = pLimit(concurrency ?? 10); } else if (typeof concurrency === 'number') { (_globalLimiter as any).concurrency = concurrency; } return _globalLimiter!; }; // --- NEW: task limiter for gating task starts --- let _taskLimiter: ReturnType | null = null; /** Limits how many *tasks* run concurrently (independent from AI calls). */ export const getTaskLimiter = (concurrency?: number) => { if (!_taskLimiter) { _taskLimiter = pLimit(concurrency ?? 5); } else if (typeof concurrency === 'number') { (_taskLimiter as any).concurrency = concurrency; } return _taskLimiter!; }; // --- REPLACE your existing `parallelize` with this version --- export const parallelizeGlobal = async ( items: T[], callback: (item: T, index: number) => Promise = async (item) => item as unknown as Promise, options?: { /** Share a single limiter across the app. If omitted, uses global limiter. */ limiter?: ReturnType; /** If provided and no limiter is passed, configure the global limiter. */ concurrency?: number; /** * Whether to wrap *each* callback run in the limiter. * - For orchestration (outer loops): set `false` (don't burn limiter slots). * - For atomic work (AI calls, writes): leave `true` (default). */ wrapInLimiter?: boolean; } ): Promise => { const limiter = options?.limiter ?? getGlobalLimiter(options?.concurrency); const wrap = options?.wrapInLimiter ?? true; const run = wrap ? (fn: () => Promise) => limiter(fn) : (fn: () => Promise) => fn(); const promises = items.map((item, index) => run(() => callback(item, index))); return Promise.all(promises); };