@common.js/p-queue 8.0.1 → 9.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -2,15 +2,34 @@
2
2
  Object.defineProperty(exports, "__esModule", {
3
3
  value: true
4
4
  });
5
- Object.defineProperty(exports, "default", {
6
- enumerable: true,
7
- get: function() {
5
+ function _export(target, all) {
6
+ for(var name in all)Object.defineProperty(target, name, {
7
+ enumerable: true,
8
+ get: all[name]
9
+ });
10
+ }
11
+ _export(exports, {
12
+ default: function() {
8
13
  return PQueue;
14
+ },
15
+ PriorityQueue: function() {
16
+ return _priorityQueueJs.default;
17
+ },
18
+ TimeoutError: function() {
19
+ return _pTimeout.TimeoutError;
9
20
  }
10
21
  });
11
22
  var _eventemitter3 = require("eventemitter3");
12
23
  var _pTimeout = /*#__PURE__*/ _interopRequireWildcard(require("p-timeout"));
13
24
  var _priorityQueueJs = /*#__PURE__*/ _interopRequireDefault(require("./priority-queue.js"));
25
+ function _arrayLikeToArray(arr, len) {
26
+ if (len == null || len > arr.length) len = arr.length;
27
+ for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
28
+ return arr2;
29
+ }
30
+ function _arrayWithoutHoles(arr) {
31
+ if (Array.isArray(arr)) return _arrayLikeToArray(arr);
32
+ }
14
33
  function _assertThisInitialized(self) {
15
34
  if (self === void 0) {
16
35
  throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
@@ -222,6 +241,12 @@ function _interopRequireWildcard(obj, nodeInterop) {
222
241
  }
223
242
  return newObj;
224
243
  }
244
+ function _iterableToArray(iter) {
245
+ if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
246
+ }
247
+ function _nonIterableSpread() {
248
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
249
+ }
225
250
  function _objectSpread(target) {
226
251
  for(var i = 1; i < arguments.length; i++){
227
252
  var source = arguments[i] != null ? arguments[i] : {};
@@ -237,6 +262,30 @@ function _objectSpread(target) {
237
262
  }
238
263
  return target;
239
264
  }
265
+ function ownKeys(object, enumerableOnly) {
266
+ var keys = Object.keys(object);
267
+ if (Object.getOwnPropertySymbols) {
268
+ var symbols = Object.getOwnPropertySymbols(object);
269
+ if (enumerableOnly) {
270
+ symbols = symbols.filter(function(sym) {
271
+ return Object.getOwnPropertyDescriptor(object, sym).enumerable;
272
+ });
273
+ }
274
+ keys.push.apply(keys, symbols);
275
+ }
276
+ return keys;
277
+ }
278
+ function _objectSpreadProps(target, source) {
279
+ source = source != null ? source : {};
280
+ if (Object.getOwnPropertyDescriptors) {
281
+ Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
282
+ } else {
283
+ ownKeys(Object(source)).forEach(function(key) {
284
+ Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
285
+ });
286
+ }
287
+ return target;
288
+ }
240
289
  function _possibleConstructorReturn(self, call) {
241
290
  if (call && (_typeof(call) === "object" || typeof call === "function")) {
242
291
  return call;
@@ -250,10 +299,21 @@ function _setPrototypeOf(o, p) {
250
299
  };
251
300
  return _setPrototypeOf(o, p);
252
301
  }
302
+ function _toConsumableArray(arr) {
303
+ return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
304
+ }
253
305
  var _typeof = function(obj) {
254
306
  "@swc/helpers - typeof";
255
307
  return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
256
308
  };
309
+ function _unsupportedIterableToArray(o, minLen) {
310
+ if (!o) return;
311
+ if (typeof o === "string") return _arrayLikeToArray(o, minLen);
312
+ var n = Object.prototype.toString.call(o).slice(8, -1);
313
+ if (n === "Object" && o.constructor) n = o.constructor.name;
314
+ if (n === "Map" || n === "Set") return Array.from(n);
315
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
316
+ }
257
317
  function _isNativeReflectConstruct() {
258
318
  if (typeof Reflect === "undefined" || !Reflect.construct) return false;
259
319
  if (Reflect.construct.sham) return false;
@@ -373,10 +433,14 @@ var __generator = (void 0) && (void 0).__generator || function(thisArg, body) {
373
433
  };
374
434
  }
375
435
  };
376
- var _carryoverConcurrencyCount = /*#__PURE__*/ new WeakMap(), _isIntervalIgnored = /*#__PURE__*/ new WeakMap(), _intervalCount = /*#__PURE__*/ new WeakMap(), _intervalCap = /*#__PURE__*/ new WeakMap(), _interval = /*#__PURE__*/ new WeakMap(), _intervalEnd = /*#__PURE__*/ new WeakMap(), _intervalId = /*#__PURE__*/ new WeakMap(), _timeoutId = /*#__PURE__*/ new WeakMap(), _queue = /*#__PURE__*/ new WeakMap(), _queueClass = /*#__PURE__*/ new WeakMap(), _pending = /*#__PURE__*/ new WeakMap(), // The `!` is needed because of https://github.com/microsoft/TypeScript/issues/32194
377
- _concurrency = /*#__PURE__*/ new WeakMap(), _isPaused = /*#__PURE__*/ new WeakMap(), _throwOnTimeout = /*#__PURE__*/ new WeakMap(), _doesIntervalAllowAnother = /*#__PURE__*/ new WeakMap(), _doesConcurrentAllowAnother = /*#__PURE__*/ new WeakMap(), _next = /*#__PURE__*/ new WeakSet(), _onResumeInterval = /*#__PURE__*/ new WeakSet(), _isIntervalPaused = /*#__PURE__*/ new WeakMap(), _tryToStartAnother = /*#__PURE__*/ new WeakSet(), _initializeIntervalIfNeeded = /*#__PURE__*/ new WeakSet(), _onInterval = /*#__PURE__*/ new WeakSet(), /**
436
+ var _carryoverIntervalCount = /*#__PURE__*/ new WeakMap(), _isIntervalIgnored = /*#__PURE__*/ new WeakMap(), _intervalCount = /*#__PURE__*/ new WeakMap(), _intervalCap = /*#__PURE__*/ new WeakMap(), _rateLimitedInInterval = /*#__PURE__*/ new WeakMap(), _rateLimitFlushScheduled = /*#__PURE__*/ new WeakMap(), _interval = /*#__PURE__*/ new WeakMap(), _intervalEnd = /*#__PURE__*/ new WeakMap(), _lastExecutionTime = /*#__PURE__*/ new WeakMap(), _intervalId = /*#__PURE__*/ new WeakMap(), _timeoutId = /*#__PURE__*/ new WeakMap(), _strict = /*#__PURE__*/ new WeakMap(), // Circular buffer implementation for better performance
437
+ _strictTicks = /*#__PURE__*/ new WeakMap(), _strictTicksStartIndex = /*#__PURE__*/ new WeakMap(), _queue = /*#__PURE__*/ new WeakMap(), _queueClass = /*#__PURE__*/ new WeakMap(), _pending = /*#__PURE__*/ new WeakMap(), // The `!` is needed because of https://github.com/microsoft/TypeScript/issues/32194
438
+ _concurrency = /*#__PURE__*/ new WeakMap(), _isPaused = /*#__PURE__*/ new WeakMap(), // Use to assign a unique identifier to a promise function, if not explicitly specified
439
+ _idAssigner = /*#__PURE__*/ new WeakMap(), // Track currently running tasks for debugging
440
+ _runningTasks = /*#__PURE__*/ new WeakMap(), _queueAbortListenerCleanupFunctions = /*#__PURE__*/ new WeakMap(), _cleanupStrictTicks = /*#__PURE__*/ new WeakSet(), // Helper methods for interval consumption
441
+ _consumeIntervalSlot = /*#__PURE__*/ new WeakSet(), _rollbackIntervalSlot = /*#__PURE__*/ new WeakSet(), _getActiveTicksCount = /*#__PURE__*/ new WeakSet(), _doesIntervalAllowAnother = /*#__PURE__*/ new WeakMap(), _doesConcurrentAllowAnother = /*#__PURE__*/ new WeakMap(), _next = /*#__PURE__*/ new WeakSet(), _onResumeInterval = /*#__PURE__*/ new WeakSet(), _isIntervalPausedAt = /*#__PURE__*/ new WeakSet(), _createIntervalTimeout = /*#__PURE__*/ new WeakSet(), _clearIntervalTimer = /*#__PURE__*/ new WeakSet(), _clearTimeoutTimer = /*#__PURE__*/ new WeakSet(), _tryToStartAnother = /*#__PURE__*/ new WeakSet(), _initializeIntervalIfNeeded = /*#__PURE__*/ new WeakSet(), _onInterval = /*#__PURE__*/ new WeakSet(), /**
378
442
  Executes all queued functions until it reaches the limit.
379
- */ _processQueue = /*#__PURE__*/ new WeakSet(), _throwOnAbort = /*#__PURE__*/ new WeakSet(), _onEvent = /*#__PURE__*/ new WeakSet();
443
+ */ _processQueue = /*#__PURE__*/ new WeakSet(), _onEvent = /*#__PURE__*/ new WeakSet(), _setupRateLimitTracking = /*#__PURE__*/ new WeakSet(), _scheduleRateLimitUpdate = /*#__PURE__*/ new WeakSet(), _rollbackIntervalConsumption = /*#__PURE__*/ new WeakSet(), _updateRateLimitState = /*#__PURE__*/ new WeakSet();
380
444
  var PQueue = /*#__PURE__*/ function(EventEmitter) {
381
445
  "use strict";
382
446
  _inherits(PQueue, EventEmitter);
@@ -385,6 +449,10 @@ var PQueue = /*#__PURE__*/ function(EventEmitter) {
385
449
  _classCallCheck(this, PQueue);
386
450
  var _this;
387
451
  _this = _super.call(this);
452
+ _classPrivateMethodInit(_assertThisInitialized(_this), _cleanupStrictTicks);
453
+ _classPrivateMethodInit(_assertThisInitialized(_this), _consumeIntervalSlot);
454
+ _classPrivateMethodInit(_assertThisInitialized(_this), _rollbackIntervalSlot);
455
+ _classPrivateMethodInit(_assertThisInitialized(_this), _getActiveTicksCount);
388
456
  _classPrivateFieldInit(_assertThisInitialized(_this), _doesIntervalAllowAnother, {
389
457
  get: get_doesIntervalAllowAnother,
390
458
  set: void 0
@@ -395,17 +463,20 @@ var PQueue = /*#__PURE__*/ function(EventEmitter) {
395
463
  });
396
464
  _classPrivateMethodInit(_assertThisInitialized(_this), _next);
397
465
  _classPrivateMethodInit(_assertThisInitialized(_this), _onResumeInterval);
398
- _classPrivateFieldInit(_assertThisInitialized(_this), _isIntervalPaused, {
399
- get: get_isIntervalPaused,
400
- set: void 0
401
- });
466
+ _classPrivateMethodInit(_assertThisInitialized(_this), _isIntervalPausedAt);
467
+ _classPrivateMethodInit(_assertThisInitialized(_this), _createIntervalTimeout);
468
+ _classPrivateMethodInit(_assertThisInitialized(_this), _clearIntervalTimer);
469
+ _classPrivateMethodInit(_assertThisInitialized(_this), _clearTimeoutTimer);
402
470
  _classPrivateMethodInit(_assertThisInitialized(_this), _tryToStartAnother);
403
471
  _classPrivateMethodInit(_assertThisInitialized(_this), _initializeIntervalIfNeeded);
404
472
  _classPrivateMethodInit(_assertThisInitialized(_this), _onInterval);
405
473
  _classPrivateMethodInit(_assertThisInitialized(_this), _processQueue);
406
- _classPrivateMethodInit(_assertThisInitialized(_this), _throwOnAbort);
407
474
  _classPrivateMethodInit(_assertThisInitialized(_this), _onEvent);
408
- _classPrivateFieldInit(_assertThisInitialized(_this), _carryoverConcurrencyCount, {
475
+ _classPrivateMethodInit(_assertThisInitialized(_this), _setupRateLimitTracking);
476
+ _classPrivateMethodInit(_assertThisInitialized(_this), _scheduleRateLimitUpdate);
477
+ _classPrivateMethodInit(_assertThisInitialized(_this), _rollbackIntervalConsumption);
478
+ _classPrivateMethodInit(_assertThisInitialized(_this), _updateRateLimitState);
479
+ _classPrivateFieldInit(_assertThisInitialized(_this), _carryoverIntervalCount, {
409
480
  writable: true,
410
481
  value: void 0
411
482
  });
@@ -421,6 +492,14 @@ var PQueue = /*#__PURE__*/ function(EventEmitter) {
421
492
  writable: true,
422
493
  value: void 0
423
494
  });
495
+ _classPrivateFieldInit(_assertThisInitialized(_this), _rateLimitedInInterval, {
496
+ writable: true,
497
+ value: false
498
+ });
499
+ _classPrivateFieldInit(_assertThisInitialized(_this), _rateLimitFlushScheduled, {
500
+ writable: true,
501
+ value: false
502
+ });
424
503
  _classPrivateFieldInit(_assertThisInitialized(_this), _interval, {
425
504
  writable: true,
426
505
  value: void 0
@@ -429,6 +508,10 @@ var PQueue = /*#__PURE__*/ function(EventEmitter) {
429
508
  writable: true,
430
509
  value: 0
431
510
  });
511
+ _classPrivateFieldInit(_assertThisInitialized(_this), _lastExecutionTime, {
512
+ writable: true,
513
+ value: 0
514
+ });
432
515
  _classPrivateFieldInit(_assertThisInitialized(_this), _intervalId, {
433
516
  writable: true,
434
517
  value: void 0
@@ -437,6 +520,18 @@ var PQueue = /*#__PURE__*/ function(EventEmitter) {
437
520
  writable: true,
438
521
  value: void 0
439
522
  });
523
+ _classPrivateFieldInit(_assertThisInitialized(_this), _strict, {
524
+ writable: true,
525
+ value: void 0
526
+ });
527
+ _classPrivateFieldInit(_assertThisInitialized(_this), _strictTicks, {
528
+ writable: true,
529
+ value: []
530
+ });
531
+ _classPrivateFieldInit(_assertThisInitialized(_this), _strictTicksStartIndex, {
532
+ writable: true,
533
+ value: 0
534
+ });
440
535
  _classPrivateFieldInit(_assertThisInitialized(_this), _queue, {
441
536
  writable: true,
442
537
  value: void 0
@@ -457,23 +552,42 @@ var PQueue = /*#__PURE__*/ function(EventEmitter) {
457
552
  writable: true,
458
553
  value: void 0
459
554
  });
460
- _classPrivateFieldInit(_assertThisInitialized(_this), _throwOnTimeout, {
555
+ _classPrivateFieldInit(_assertThisInitialized(_this), _idAssigner, {
461
556
  writable: true,
462
- value: void 0
557
+ value: 1n
558
+ });
559
+ _classPrivateFieldInit(_assertThisInitialized(_this), _runningTasks, {
560
+ writable: true,
561
+ value: new Map()
562
+ });
563
+ _classPrivateFieldInit(_assertThisInitialized(_this), _queueAbortListenerCleanupFunctions, {
564
+ writable: true,
565
+ value: new Set()
463
566
  });
464
567
  /**
465
- Per-operation timeout in milliseconds. Operations fulfill once `timeout` elapses if they haven't already.
568
+ Get or set the default timeout for all tasks. Can be changed at runtime.
569
+
570
+ Operations will throw a `TimeoutError` if they don't complete within the specified time.
571
+
572
+ The timeout begins when the operation is dequeued and starts execution, not while it's waiting in the queue.
573
+
574
+ @example
575
+ ```
576
+ const queue = new PQueue({timeout: 5000});
466
577
 
467
- Applies to each future operation.
578
+ // Change timeout for all future tasks
579
+ queue.timeout = 10000;
580
+ ```
468
581
  */ _defineProperty(_assertThisInitialized(_this), "timeout", void 0);
469
582
  // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
470
583
  options = _objectSpread({
471
- carryoverConcurrencyCount: false,
584
+ carryoverIntervalCount: false,
472
585
  intervalCap: Number.POSITIVE_INFINITY,
473
586
  interval: 0,
474
587
  concurrency: Number.POSITIVE_INFINITY,
475
588
  autoStart: true,
476
- queueClass: _priorityQueueJs.default
589
+ queueClass: _priorityQueueJs.default,
590
+ strict: false
477
591
  }, options);
478
592
  if (!(typeof options.intervalCap === "number" && options.intervalCap >= 1)) {
479
593
  var ref;
@@ -485,16 +599,27 @@ var PQueue = /*#__PURE__*/ function(EventEmitter) {
485
599
  var ref3;
486
600
  throw new TypeError("Expected `interval` to be a finite number >= 0, got `".concat((ref3 = (ref2 = options.interval) === null || ref2 === void 0 ? void 0 : ref2.toString()) !== null && ref3 !== void 0 ? ref3 : "", "` (").concat(_typeof(options.interval), ")"));
487
601
  }
488
- _classPrivateFieldSet(_assertThisInitialized(_this), _carryoverConcurrencyCount, options.carryoverConcurrencyCount);
602
+ if (options.strict && options.interval === 0) {
603
+ throw new TypeError("The `strict` option requires a non-zero `interval`");
604
+ }
605
+ if (options.strict && options.intervalCap === Number.POSITIVE_INFINITY) {
606
+ throw new TypeError("The `strict` option requires a finite `intervalCap`");
607
+ }
608
+ var _carryoverIntervalCount1, ref4;
609
+ _classPrivateFieldSet(_assertThisInitialized(_this), _carryoverIntervalCount, (ref4 = (_carryoverIntervalCount1 = options.carryoverIntervalCount) !== null && _carryoverIntervalCount1 !== void 0 ? _carryoverIntervalCount1 : options.carryoverConcurrencyCount) !== null && ref4 !== void 0 ? ref4 : false);
489
610
  _classPrivateFieldSet(_assertThisInitialized(_this), _isIntervalIgnored, options.intervalCap === Number.POSITIVE_INFINITY || options.interval === 0);
490
611
  _classPrivateFieldSet(_assertThisInitialized(_this), _intervalCap, options.intervalCap);
491
612
  _classPrivateFieldSet(_assertThisInitialized(_this), _interval, options.interval);
613
+ _classPrivateFieldSet(_assertThisInitialized(_this), _strict, options.strict);
492
614
  _classPrivateFieldSet(_assertThisInitialized(_this), _queue, new options.queueClass());
493
615
  _classPrivateFieldSet(_assertThisInitialized(_this), _queueClass, options.queueClass);
494
616
  _this.concurrency = options.concurrency;
617
+ if (options.timeout !== undefined && !(Number.isFinite(options.timeout) && options.timeout > 0)) {
618
+ throw new TypeError("Expected `timeout` to be a positive finite number, got `".concat(options.timeout, "` (").concat(_typeof(options.timeout), ")"));
619
+ }
495
620
  _this.timeout = options.timeout;
496
- _classPrivateFieldSet(_assertThisInitialized(_this), _throwOnTimeout, options.throwOnTimeout === true);
497
621
  _classPrivateFieldSet(_assertThisInitialized(_this), _isPaused, options.autoStart === false);
622
+ _classPrivateMethodGet(_this, _setupRateLimitTracking, setupRateLimitTracking).call(_assertThisInitialized(_this));
498
623
  return _this;
499
624
  }
500
625
  _createClass(PQueue, [
@@ -511,88 +636,210 @@ var PQueue = /*#__PURE__*/ function(EventEmitter) {
511
636
  _classPrivateMethodGet(this, _processQueue, processQueue).call(this);
512
637
  }
513
638
  },
639
+ {
640
+ /**
641
+ Updates the priority of a promise function by its id, affecting its execution order. Requires a defined concurrency limit to take effect.
642
+
643
+ For example, this can be used to prioritize a promise function to run earlier.
644
+
645
+ ```js
646
+ import PQueue from 'p-queue';
647
+
648
+ const queue = new PQueue({concurrency: 1});
649
+
650
+ queue.add(async () => '🦄', {priority: 1});
651
+ queue.add(async () => '🦀', {priority: 0, id: '🦀'});
652
+ queue.add(async () => '🦄', {priority: 1});
653
+ queue.add(async () => '🦄', {priority: 1});
654
+
655
+ queue.setPriority('🦀', 2);
656
+ ```
657
+
658
+ In this case, the promise function with `id: '🦀'` runs second.
659
+
660
+ You can also deprioritize a promise function to delay its execution:
661
+
662
+ ```js
663
+ import PQueue from 'p-queue';
664
+
665
+ const queue = new PQueue({concurrency: 1});
666
+
667
+ queue.add(async () => '🦄', {priority: 1});
668
+ queue.add(async () => '🦀', {priority: 1, id: '🦀'});
669
+ queue.add(async () => '🦄');
670
+ queue.add(async () => '🦄', {priority: 0});
671
+
672
+ queue.setPriority('🦀', -1);
673
+ ```
674
+ Here, the promise function with `id: '🦀'` executes last.
675
+ */ key: "setPriority",
676
+ value: function setPriority(id, priority) {
677
+ if (typeof priority !== "number" || !Number.isFinite(priority)) {
678
+ throw new TypeError("Expected `priority` to be a finite number, got `".concat(priority, "` (").concat(typeof priority === "undefined" ? "undefined" : _typeof(priority), ")"));
679
+ }
680
+ _classPrivateFieldGet(this, _queue).setPriority(id, priority);
681
+ }
682
+ },
514
683
  {
515
684
  key: "add",
516
685
  value: function add(function_) {
517
686
  var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
518
687
  var _this = this;
519
688
  return _asyncToGenerator(function() {
689
+ var _id;
520
690
  return __generator(this, function(_state) {
521
- options = _objectSpread({
522
- timeout: _this.timeout,
523
- throwOnTimeout: _classPrivateFieldGet(_this, _throwOnTimeout)
524
- }, options);
691
+ // Create a copy to avoid mutating the original options object
692
+ options = _objectSpreadProps(_objectSpread({
693
+ timeout: _this.timeout
694
+ }, options), {
695
+ // Assign unique ID if not provided
696
+ id: (_id = options.id) !== null && _id !== void 0 ? _id : (_classPrivateFieldUpdate(_this, _idAssigner).value++).toString()
697
+ });
525
698
  return [
526
699
  2,
527
700
  new Promise(function(resolve, reject) {
528
- _classPrivateFieldGet(_this, _queue).enqueue(/*#__PURE__*/ _asyncToGenerator(function() {
529
- var ref, operation, result, error;
530
- return __generator(this, function(_state) {
531
- switch(_state.label){
532
- case 0:
533
- _classPrivateFieldUpdate(_this, _pending).value++;
534
- _classPrivateFieldUpdate(_this, _intervalCount).value++;
535
- _state.label = 1;
536
- case 1:
537
- _state.trys.push([
538
- 1,
539
- 3,
540
- 4,
541
- 5
542
- ]);
543
- (ref = options.signal) === null || ref === void 0 ? void 0 : ref.throwIfAborted();
544
- operation = function_({
545
- signal: options.signal
546
- });
547
- if (options.timeout) {
548
- operation = (0, _pTimeout.default)(Promise.resolve(operation), {
549
- milliseconds: options.timeout
701
+ // Create a unique symbol for tracking this task
702
+ var taskSymbol = Symbol("task-".concat(options.id));
703
+ var cleanupQueueAbortHandler = function() {
704
+ return undefined;
705
+ };
706
+ var run = function() {
707
+ var _ref = _asyncToGenerator(function() {
708
+ var _priority, eventListener, ref, operation, signal, result, error, ref1;
709
+ return __generator(this, function(_state) {
710
+ switch(_state.label){
711
+ case 0:
712
+ // Task is now running — remove the queued-state abort listener
713
+ cleanupQueueAbortHandler();
714
+ _classPrivateFieldUpdate(_this, _pending).value++;
715
+ // Track this running task
716
+ _classPrivateFieldGet(_this, _runningTasks).set(taskSymbol, {
717
+ id: options.id,
718
+ priority: (_priority = options.priority) !== null && _priority !== void 0 ? _priority : 0,
719
+ startTime: Date.now(),
720
+ timeout: options.timeout
550
721
  });
551
- }
552
- if (options.signal) {
553
- operation = Promise.race([
554
- operation,
555
- _classPrivateMethodGet(_this, _throwOnAbort, throwOnAbort).call(_this, options.signal)
722
+ _state.label = 1;
723
+ case 1:
724
+ _state.trys.push([
725
+ 1,
726
+ 3,
727
+ 4,
728
+ 5
556
729
  ]);
557
- }
558
- return [
559
- 4,
560
- operation
561
- ];
562
- case 2:
563
- result = _state.sent();
564
- resolve(result);
565
- _this.emit("completed", result);
566
- return [
567
- 3,
568
- 5
569
- ];
570
- case 3:
571
- error = _state.sent();
572
- if (_instanceof(error, _pTimeout.TimeoutError) && !options.throwOnTimeout) {
573
- resolve();
730
+ // Check abort signal - if aborted, need to decrement the counter
731
+ // that was incremented in tryToStartAnother
732
+ try {
733
+ ;
734
+ (ref = options.signal) === null || ref === void 0 ? void 0 : ref.throwIfAborted();
735
+ } catch (error1) {
736
+ _classPrivateMethodGet(_this, _rollbackIntervalConsumption, rollbackIntervalConsumption).call(_this);
737
+ // Clean up tracking before throwing
738
+ _classPrivateFieldGet(_this, _runningTasks).delete(taskSymbol);
739
+ throw error1;
740
+ }
741
+ _classPrivateFieldSet(_this, _lastExecutionTime, Date.now());
742
+ operation = function_({
743
+ signal: options.signal
744
+ });
745
+ if (options.timeout) {
746
+ operation = (0, _pTimeout.default)(Promise.resolve(operation), {
747
+ milliseconds: options.timeout,
748
+ message: "Task timed out after ".concat(options.timeout, "ms (queue has ").concat(_classPrivateFieldGet(_this, _pending), " running, ").concat(_classPrivateFieldGet(_this, _queue).size, " waiting)")
749
+ });
750
+ }
751
+ if (options.signal) {
752
+ signal = options.signal;
753
+ operation = Promise.race([
754
+ operation,
755
+ new Promise(function(_resolve, reject) {
756
+ eventListener = function() {
757
+ reject(signal.reason);
758
+ };
759
+ signal.addEventListener("abort", eventListener, {
760
+ once: true
761
+ });
762
+ })
763
+ ]);
764
+ }
765
+ return [
766
+ 4,
767
+ operation
768
+ ];
769
+ case 2:
770
+ result = _state.sent();
771
+ resolve(result);
772
+ _this.emit("completed", result);
773
+ return [
774
+ 3,
775
+ 5
776
+ ];
777
+ case 3:
778
+ error = _state.sent();
779
+ reject(error);
780
+ _this.emit("error", error);
781
+ return [
782
+ 3,
783
+ 5
784
+ ];
785
+ case 4:
786
+ // Clean up abort event listener
787
+ if (eventListener) {
788
+ ;
789
+ (ref1 = options.signal) === null || ref1 === void 0 ? void 0 : ref1.removeEventListener("abort", eventListener);
790
+ }
791
+ // Remove from running tasks
792
+ _classPrivateFieldGet(_this, _runningTasks).delete(taskSymbol);
793
+ // Use queueMicrotask to prevent deep recursion while maintaining timing
794
+ queueMicrotask(function() {
795
+ _classPrivateMethodGet(_this, _next, next).call(_this);
796
+ });
797
+ return [
798
+ 7
799
+ ];
800
+ case 5:
574
801
  return [
575
802
  2
576
803
  ];
577
- }
578
- reject(error);
579
- _this.emit("error", error);
580
- return [
581
- 3,
582
- 5
583
- ];
584
- case 4:
585
- _classPrivateMethodGet(_this, _next, next).call(_this);
586
- return [
587
- 7
588
- ];
589
- case 5:
590
- return [
591
- 2
592
- ];
593
- }
804
+ }
805
+ });
806
+ });
807
+ return function run() {
808
+ return _ref.apply(this, arguments);
809
+ };
810
+ }();
811
+ _classPrivateFieldGet(_this, _queue).enqueue(run, options);
812
+ var removeQueuedTask = function() {
813
+ var _obj, ref;
814
+ if (_instanceof(_classPrivateFieldGet(_this, _queue), _priorityQueueJs.default)) {
815
+ _classPrivateFieldGet(_this, _queue).remove(run);
816
+ return;
817
+ }
818
+ (ref = (_obj = _classPrivateFieldGet(_this, _queue)).remove) === null || ref === void 0 ? void 0 : ref.call(_obj, options.id); // Intentionally best-effort: queued abort removal is only supported for queue classes that implement `.remove()`.
819
+ };
820
+ // Handle abort while task is waiting in the queue
821
+ if (options.signal) {
822
+ var signal = options.signal;
823
+ var queueAbortHandler = function() {
824
+ cleanupQueueAbortHandler();
825
+ removeQueuedTask();
826
+ reject(signal.reason);
827
+ _classPrivateMethodGet(_this, _tryToStartAnother, tryToStartAnother).call(_this);
828
+ _this.emit("next");
829
+ };
830
+ cleanupQueueAbortHandler = function() {
831
+ signal.removeEventListener("abort", queueAbortHandler);
832
+ _classPrivateFieldGet(_this, _queueAbortListenerCleanupFunctions).delete(cleanupQueueAbortHandler);
833
+ };
834
+ if (signal.aborted) {
835
+ queueAbortHandler();
836
+ return;
837
+ }
838
+ signal.addEventListener("abort", queueAbortHandler, {
839
+ once: true
594
840
  });
595
- }), options);
841
+ _classPrivateFieldGet(_this, _queueAbortListenerCleanupFunctions).add(cleanupQueueAbortHandler);
842
+ }
596
843
  _this.emit("add");
597
844
  _classPrivateMethodGet(_this, _tryToStartAnother, tryToStartAnother).call(_this);
598
845
  })
@@ -653,7 +900,43 @@ var PQueue = /*#__PURE__*/ function(EventEmitter) {
653
900
  Clear the queue.
654
901
  */ key: "clear",
655
902
  value: function clear() {
903
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
904
+ try {
905
+ for(var _iterator = _classPrivateFieldGet(this, _queueAbortListenerCleanupFunctions)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
906
+ var cleanupQueueAbortHandler = _step.value;
907
+ cleanupQueueAbortHandler();
908
+ }
909
+ } catch (err) {
910
+ _didIteratorError = true;
911
+ _iteratorError = err;
912
+ } finally{
913
+ try {
914
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
915
+ _iterator.return();
916
+ }
917
+ } finally{
918
+ if (_didIteratorError) {
919
+ throw _iteratorError;
920
+ }
921
+ }
922
+ }
656
923
  _classPrivateFieldSet(this, _queue, new (_classPrivateFieldGet(this, _queueClass))());
924
+ // Clear interval timer since queue is now empty (consistent with #tryToStartAnother)
925
+ _classPrivateMethodGet(this, _clearIntervalTimer, clearIntervalTimer).call(this);
926
+ // Note: We preserve strict mode rate-limiting state (ticks and timeout)
927
+ // because clear() only clears queued tasks, not rate limit history.
928
+ // This ensures that rate limits are still enforced after clearing the queue.
929
+ // Note: We don't clear #runningTasks as those tasks are still running
930
+ // They will be removed when they complete in the finally block
931
+ // Force synchronous update since clear() should have immediate effect
932
+ _classPrivateMethodGet(this, _updateRateLimitState, updateRateLimitState).call(this);
933
+ // Emit events so waiters (onEmpty, onIdle, onSizeLessThan) can resolve
934
+ this.emit("empty");
935
+ if (_classPrivateFieldGet(this, _pending) === 0) {
936
+ _classPrivateMethodGet(this, _clearTimeoutTimer, clearTimeoutTimer).call(this);
937
+ this.emit("idle");
938
+ }
939
+ this.emit("next");
657
940
  }
658
941
  },
659
942
  {
@@ -702,15 +985,21 @@ var PQueue = /*#__PURE__*/ function(EventEmitter) {
702
985
  return __generator(this, function(_state) {
703
986
  switch(_state.label){
704
987
  case 0:
705
- // Instantly resolve if the queue is empty.
988
+ // Instantly resolve if the size is already below the limit.
706
989
  if (_classPrivateFieldGet(_this, _queue).size < limit) {
707
990
  return [
708
991
  2
709
992
  ];
710
993
  }
994
+ // Listen on both `'next'` (task completion, queued abort, `clear()`) and `'active'` (every dequeue),
995
+ // so waiters wake even when the queue drains without a completion (`start()`, a runtime `concurrency`
996
+ // increase, or an interval tick).
711
997
  return [
712
998
  4,
713
- _classPrivateMethodGet(_this, _onEvent, onEvent).call(_this, "next", function() {
999
+ _classPrivateMethodGet(_this, _onEvent, onEvent).call(_this, [
1000
+ "next",
1001
+ "active"
1002
+ ], function() {
714
1003
  return _classPrivateFieldGet(_this, _queue).size < limit;
715
1004
  })
716
1005
  ];
@@ -756,6 +1045,137 @@ var PQueue = /*#__PURE__*/ function(EventEmitter) {
756
1045
  })();
757
1046
  }
758
1047
  },
1048
+ {
1049
+ key: "onPendingZero",
1050
+ value: /**
1051
+ The difference with `.onIdle` is that `.onPendingZero` only waits for currently running tasks to finish, ignoring queued tasks.
1052
+
1053
+ @returns A promise that settles when all currently running tasks have completed; `queue.pending === 0`.
1054
+ */ function onPendingZero() {
1055
+ var _this = this;
1056
+ return _asyncToGenerator(function() {
1057
+ return __generator(this, function(_state) {
1058
+ switch(_state.label){
1059
+ case 0:
1060
+ if (_classPrivateFieldGet(_this, _pending) === 0) {
1061
+ return [
1062
+ 2
1063
+ ];
1064
+ }
1065
+ return [
1066
+ 4,
1067
+ _classPrivateMethodGet(_this, _onEvent, onEvent).call(_this, "pendingZero")
1068
+ ];
1069
+ case 1:
1070
+ _state.sent();
1071
+ return [
1072
+ 2
1073
+ ];
1074
+ }
1075
+ });
1076
+ })();
1077
+ }
1078
+ },
1079
+ {
1080
+ key: "onRateLimit",
1081
+ value: /**
1082
+ @returns A promise that settles when the queue becomes rate-limited due to intervalCap.
1083
+ */ function onRateLimit() {
1084
+ var _this = this;
1085
+ return _asyncToGenerator(function() {
1086
+ return __generator(this, function(_state) {
1087
+ switch(_state.label){
1088
+ case 0:
1089
+ if (_this.isRateLimited) {
1090
+ return [
1091
+ 2
1092
+ ];
1093
+ }
1094
+ return [
1095
+ 4,
1096
+ _classPrivateMethodGet(_this, _onEvent, onEvent).call(_this, "rateLimit")
1097
+ ];
1098
+ case 1:
1099
+ _state.sent();
1100
+ return [
1101
+ 2
1102
+ ];
1103
+ }
1104
+ });
1105
+ })();
1106
+ }
1107
+ },
1108
+ {
1109
+ key: "onRateLimitCleared",
1110
+ value: /**
1111
+ @returns A promise that settles when the queue is no longer rate-limited.
1112
+ */ function onRateLimitCleared() {
1113
+ var _this = this;
1114
+ return _asyncToGenerator(function() {
1115
+ return __generator(this, function(_state) {
1116
+ switch(_state.label){
1117
+ case 0:
1118
+ if (!_this.isRateLimited) {
1119
+ return [
1120
+ 2
1121
+ ];
1122
+ }
1123
+ return [
1124
+ 4,
1125
+ _classPrivateMethodGet(_this, _onEvent, onEvent).call(_this, "rateLimitCleared")
1126
+ ];
1127
+ case 1:
1128
+ _state.sent();
1129
+ return [
1130
+ 2
1131
+ ];
1132
+ }
1133
+ });
1134
+ })();
1135
+ }
1136
+ },
1137
+ {
1138
+ /**
1139
+ @returns A promise that rejects when any task in the queue errors.
1140
+
1141
+ Use with `Promise.race([queue.onError(), queue.onIdle()])` to fail fast on the first error while still resolving normally when the queue goes idle.
1142
+
1143
+ Important: The promise returned by `add()` still rejects. You must handle each `add()` promise (for example, `.catch(() => {})`) to avoid unhandled rejections.
1144
+
1145
+ @example
1146
+ ```
1147
+ import PQueue from 'p-queue';
1148
+
1149
+ const queue = new PQueue({concurrency: 2});
1150
+
1151
+ queue.add(() => fetchData(1)).catch(() => {});
1152
+ queue.add(() => fetchData(2)).catch(() => {});
1153
+ queue.add(() => fetchData(3)).catch(() => {});
1154
+
1155
+ // Stop processing on first error
1156
+ try {
1157
+ await Promise.race([
1158
+ queue.onError(),
1159
+ queue.onIdle()
1160
+ ]);
1161
+ } catch (error) {
1162
+ queue.pause(); // Stop processing remaining tasks
1163
+ console.error('Queue failed:', error);
1164
+ }
1165
+ ```
1166
+ */ // eslint-disable-next-line @typescript-eslint/promise-function-async
1167
+ key: "onError",
1168
+ value: function onError() {
1169
+ var _this = this;
1170
+ return new Promise(function(_resolve, reject) {
1171
+ var handleError = function(error) {
1172
+ _this.off("error", handleError);
1173
+ reject(error);
1174
+ };
1175
+ _this.on("error", handleError);
1176
+ });
1177
+ }
1178
+ },
759
1179
  {
760
1180
  key: "size",
761
1181
  get: /**
@@ -790,126 +1210,292 @@ var PQueue = /*#__PURE__*/ function(EventEmitter) {
790
1210
  */ function get() {
791
1211
  return _classPrivateFieldGet(this, _isPaused);
792
1212
  }
1213
+ },
1214
+ {
1215
+ key: "isRateLimited",
1216
+ get: /**
1217
+ Whether the queue is currently rate-limited due to intervalCap.
1218
+ */ function get() {
1219
+ return _classPrivateFieldGet(this, _rateLimitedInInterval);
1220
+ }
1221
+ },
1222
+ {
1223
+ key: "isSaturated",
1224
+ get: /**
1225
+ Whether the queue is saturated. Returns `true` when:
1226
+ - All concurrency slots are occupied and tasks are waiting, OR
1227
+ - The queue is rate-limited and tasks are waiting
1228
+
1229
+ Useful for detecting backpressure and potential hanging tasks.
1230
+
1231
+ ```js
1232
+ import PQueue from 'p-queue';
1233
+
1234
+ const queue = new PQueue({concurrency: 2});
1235
+
1236
+ // Backpressure handling
1237
+ if (queue.isSaturated) {
1238
+ console.log('Queue is saturated, waiting for capacity...');
1239
+ await queue.onSizeLessThan(queue.concurrency);
1240
+ }
1241
+
1242
+ // Monitoring for stuck tasks
1243
+ setInterval(() => {
1244
+ if (queue.isSaturated) {
1245
+ console.warn(`Queue saturated: ${queue.pending} running, ${queue.size} waiting`);
1246
+ }
1247
+ }, 60000);
1248
+ ```
1249
+ */ function get() {
1250
+ return _classPrivateFieldGet(this, _pending) === _classPrivateFieldGet(this, _concurrency) && _classPrivateFieldGet(this, _queue).size > 0 || this.isRateLimited && _classPrivateFieldGet(this, _queue).size > 0;
1251
+ }
1252
+ },
1253
+ {
1254
+ key: "runningTasks",
1255
+ get: /**
1256
+ The tasks currently being executed. Each task includes its `id`, `priority`, `startTime`, `timeout` (if set), and `timeoutRemaining` (milliseconds until the task times out, or `undefined` if no timeout is set).
1257
+
1258
+ Returns an array of task info objects.
1259
+
1260
+ ```js
1261
+ import PQueue from 'p-queue';
1262
+
1263
+ const queue = new PQueue({concurrency: 2, timeout: 10000});
1264
+
1265
+ // Add tasks with IDs for better debugging
1266
+ queue.add(() => fetchUser(123), {id: 'user-123'});
1267
+ queue.add(() => fetchPosts(456), {id: 'posts-456', priority: 1});
1268
+
1269
+ // Check what's running
1270
+ console.log(queue.runningTasks);
1271
+ // => [{
1272
+ // id: 'user-123',
1273
+ // priority: 0,
1274
+ // startTime: 1759253001716,
1275
+ // timeout: 10000,
1276
+ // timeoutRemaining: 9700
1277
+ // }, {
1278
+ // id: 'posts-456',
1279
+ // priority: 1,
1280
+ // startTime: 1759253001916,
1281
+ // timeout: 10000,
1282
+ // timeoutRemaining: 9900
1283
+ // }]
1284
+ ```
1285
+ */ function get() {
1286
+ // Return fresh array with fresh objects to prevent mutations
1287
+ return _toConsumableArray(_classPrivateFieldGet(this, _runningTasks).values()).map(function(task) {
1288
+ return _objectSpreadProps(_objectSpread({}, task), {
1289
+ timeoutRemaining: task.timeout ? Math.max(0, task.startTime + task.timeout - Date.now()) : undefined
1290
+ });
1291
+ });
1292
+ }
793
1293
  }
794
1294
  ]);
795
1295
  return PQueue;
796
1296
  }(_eventemitter3.EventEmitter);
1297
+ function cleanupStrictTicks(now) {
1298
+ // Remove ticks outside the current interval window using circular buffer approach
1299
+ while(_classPrivateFieldGet(this, _strictTicksStartIndex) < _classPrivateFieldGet(this, _strictTicks).length){
1300
+ var oldestTick = _classPrivateFieldGet(this, _strictTicks)[_classPrivateFieldGet(this, _strictTicksStartIndex)];
1301
+ if (oldestTick !== undefined && now - oldestTick >= _classPrivateFieldGet(this, _interval)) {
1302
+ _classPrivateFieldUpdate(this, _strictTicksStartIndex).value++;
1303
+ } else {
1304
+ break;
1305
+ }
1306
+ }
1307
+ // Compact the array when it becomes inefficient or fully consumed
1308
+ // Compact when: (start index is large AND more than half wasted) OR all ticks expired
1309
+ var shouldCompact = _classPrivateFieldGet(this, _strictTicksStartIndex) > 100 && _classPrivateFieldGet(this, _strictTicksStartIndex) > _classPrivateFieldGet(this, _strictTicks).length / 2 || _classPrivateFieldGet(this, _strictTicksStartIndex) === _classPrivateFieldGet(this, _strictTicks).length;
1310
+ if (shouldCompact) {
1311
+ _classPrivateFieldSet(this, _strictTicks, _classPrivateFieldGet(this, _strictTicks).slice(_classPrivateFieldGet(this, _strictTicksStartIndex)));
1312
+ _classPrivateFieldSet(this, _strictTicksStartIndex, 0);
1313
+ }
1314
+ }
1315
+ function consumeIntervalSlot(now) {
1316
+ if (_classPrivateFieldGet(this, _strict)) {
1317
+ _classPrivateFieldGet(this, _strictTicks).push(now);
1318
+ } else {
1319
+ _classPrivateFieldUpdate(this, _intervalCount).value++;
1320
+ }
1321
+ }
1322
+ function rollbackIntervalSlot() {
1323
+ if (_classPrivateFieldGet(this, _strict)) {
1324
+ // Pop from the end of the actual data (not from start index)
1325
+ if (_classPrivateFieldGet(this, _strictTicks).length > _classPrivateFieldGet(this, _strictTicksStartIndex)) {
1326
+ _classPrivateFieldGet(this, _strictTicks).pop();
1327
+ }
1328
+ } else if (_classPrivateFieldGet(this, _intervalCount) > 0) {
1329
+ _classPrivateFieldUpdate(this, _intervalCount).value--;
1330
+ }
1331
+ }
1332
+ function getActiveTicksCount() {
1333
+ return _classPrivateFieldGet(this, _strictTicks).length - _classPrivateFieldGet(this, _strictTicksStartIndex);
1334
+ }
797
1335
  function get_doesIntervalAllowAnother() {
798
- return _classPrivateFieldGet(this, _isIntervalIgnored) || _classPrivateFieldGet(this, _intervalCount) < _classPrivateFieldGet(this, _intervalCap);
1336
+ if (_classPrivateFieldGet(this, _isIntervalIgnored)) {
1337
+ return true;
1338
+ }
1339
+ if (_classPrivateFieldGet(this, _strict)) {
1340
+ // Cleanup already done by #isIntervalPausedAt before this is called
1341
+ return _classPrivateMethodGet(this, _getActiveTicksCount, getActiveTicksCount).call(this) < _classPrivateFieldGet(this, _intervalCap);
1342
+ }
1343
+ return _classPrivateFieldGet(this, _intervalCount) < _classPrivateFieldGet(this, _intervalCap);
799
1344
  }
800
1345
  function get_doesConcurrentAllowAnother() {
801
1346
  return _classPrivateFieldGet(this, _pending) < _classPrivateFieldGet(this, _concurrency);
802
1347
  }
803
1348
  function next() {
804
1349
  _classPrivateFieldUpdate(this, _pending).value--;
1350
+ if (_classPrivateFieldGet(this, _pending) === 0) {
1351
+ this.emit("pendingZero");
1352
+ }
805
1353
  _classPrivateMethodGet(this, _tryToStartAnother, tryToStartAnother).call(this);
806
1354
  this.emit("next");
807
1355
  }
808
1356
  function onResumeInterval() {
1357
+ _classPrivateFieldSet(this, _timeoutId, undefined);
809
1358
  _classPrivateMethodGet(this, _onInterval, onInterval).call(this);
810
1359
  _classPrivateMethodGet(this, _initializeIntervalIfNeeded, initializeIntervalIfNeeded).call(this);
811
- _classPrivateFieldSet(this, _timeoutId, undefined);
812
1360
  }
813
- function get_isIntervalPaused() {
814
- var _this = this;
815
- var now = Date.now();
1361
+ function isIntervalPausedAt(now) {
1362
+ // Strict mode: check if we need to wait for oldest tick to age out
1363
+ if (_classPrivateFieldGet(this, _strict)) {
1364
+ _classPrivateMethodGet(this, _cleanupStrictTicks, cleanupStrictTicks).call(this, now);
1365
+ // If at capacity, need to wait for oldest tick to age out
1366
+ var activeTicksCount = _classPrivateMethodGet(this, _getActiveTicksCount, getActiveTicksCount).call(this);
1367
+ if (activeTicksCount >= _classPrivateFieldGet(this, _intervalCap)) {
1368
+ var oldestTick = _classPrivateFieldGet(this, _strictTicks)[_classPrivateFieldGet(this, _strictTicksStartIndex)];
1369
+ // After cleanup, remaining ticks are within interval, so delay is always > 0
1370
+ var delay = _classPrivateFieldGet(this, _interval) - (now - oldestTick);
1371
+ _classPrivateMethodGet(this, _createIntervalTimeout, createIntervalTimeout).call(this, delay);
1372
+ return true;
1373
+ }
1374
+ return false;
1375
+ }
1376
+ // Fixed window mode (original logic)
816
1377
  if (_classPrivateFieldGet(this, _intervalId) === undefined) {
817
- var delay = _classPrivateFieldGet(this, _intervalEnd) - now;
818
- if (delay < 0) {
819
- _classPrivateFieldSet(this, _intervalCount, _classPrivateFieldGet(this, _carryoverConcurrencyCount) ? _classPrivateFieldGet(this, _pending) : 0);
1378
+ var delay1 = _classPrivateFieldGet(this, _intervalEnd) - now;
1379
+ if (delay1 < 0) {
1380
+ // If the interval has expired while idle, check if we should enforce the interval
1381
+ // from the last task execution. This ensures proper spacing between tasks even
1382
+ // when the queue becomes empty and then new tasks are added.
1383
+ if (_classPrivateFieldGet(this, _lastExecutionTime) > 0) {
1384
+ var timeSinceLastExecution = now - _classPrivateFieldGet(this, _lastExecutionTime);
1385
+ if (timeSinceLastExecution < _classPrivateFieldGet(this, _interval)) {
1386
+ // Not enough time has passed since the last task execution
1387
+ _classPrivateMethodGet(this, _createIntervalTimeout, createIntervalTimeout).call(this, _classPrivateFieldGet(this, _interval) - timeSinceLastExecution);
1388
+ return true;
1389
+ }
1390
+ }
1391
+ _classPrivateFieldSet(this, _intervalCount, _classPrivateFieldGet(this, _carryoverIntervalCount) ? _classPrivateFieldGet(this, _pending) : 0);
820
1392
  } else {
821
1393
  // Act as the interval is pending
822
- if (_classPrivateFieldGet(this, _timeoutId) === undefined) {
823
- _classPrivateFieldSet(this, _timeoutId, setTimeout(function() {
824
- _classPrivateMethodGet(_this, _onResumeInterval, onResumeInterval).call(_this);
825
- }, delay));
826
- }
1394
+ _classPrivateMethodGet(this, _createIntervalTimeout, createIntervalTimeout).call(this, delay1);
827
1395
  return true;
828
1396
  }
829
1397
  }
830
1398
  return false;
831
1399
  }
1400
+ function createIntervalTimeout(delay) {
1401
+ var _this = this;
1402
+ if (_classPrivateFieldGet(this, _timeoutId) !== undefined) {
1403
+ return;
1404
+ }
1405
+ _classPrivateFieldSet(this, _timeoutId, setTimeout(function() {
1406
+ _classPrivateMethodGet(_this, _onResumeInterval, onResumeInterval).call(_this);
1407
+ }, delay));
1408
+ }
1409
+ function clearIntervalTimer() {
1410
+ if (_classPrivateFieldGet(this, _intervalId)) {
1411
+ clearInterval(_classPrivateFieldGet(this, _intervalId));
1412
+ _classPrivateFieldSet(this, _intervalId, undefined);
1413
+ }
1414
+ }
1415
+ function clearTimeoutTimer() {
1416
+ if (_classPrivateFieldGet(this, _timeoutId)) {
1417
+ clearTimeout(_classPrivateFieldGet(this, _timeoutId));
1418
+ _classPrivateFieldSet(this, _timeoutId, undefined);
1419
+ }
1420
+ }
832
1421
  function tryToStartAnother() {
833
1422
  if (_classPrivateFieldGet(this, _queue).size === 0) {
834
1423
  // We can clear the interval ("pause")
835
1424
  // Because we can redo it later ("resume")
836
- if (_classPrivateFieldGet(this, _intervalId)) {
837
- clearInterval(_classPrivateFieldGet(this, _intervalId));
838
- }
839
- _classPrivateFieldSet(this, _intervalId, undefined);
1425
+ _classPrivateMethodGet(this, _clearIntervalTimer, clearIntervalTimer).call(this);
840
1426
  this.emit("empty");
841
1427
  if (_classPrivateFieldGet(this, _pending) === 0) {
1428
+ // Clear timeout as well when completely idle
1429
+ _classPrivateMethodGet(this, _clearTimeoutTimer, clearTimeoutTimer).call(this);
1430
+ // Compact strict ticks when idle to free memory
1431
+ if (_classPrivateFieldGet(this, _strict) && _classPrivateFieldGet(this, _strictTicksStartIndex) > 0) {
1432
+ var now = Date.now();
1433
+ _classPrivateMethodGet(this, _cleanupStrictTicks, cleanupStrictTicks).call(this, now);
1434
+ }
842
1435
  this.emit("idle");
843
1436
  }
844
1437
  return false;
845
1438
  }
1439
+ var taskStarted = false;
846
1440
  if (!_classPrivateFieldGet(this, _isPaused)) {
847
- var canInitializeInterval = !_classPrivateFieldGet(this, _isIntervalPaused);
1441
+ var now1 = Date.now();
1442
+ var canInitializeInterval = !_classPrivateMethodGet(this, _isIntervalPausedAt, isIntervalPausedAt).call(this, now1);
848
1443
  if (_classPrivateFieldGet(this, _doesIntervalAllowAnother) && _classPrivateFieldGet(this, _doesConcurrentAllowAnother)) {
849
1444
  var job = _classPrivateFieldGet(this, _queue).dequeue();
850
- if (!job) {
851
- return false;
1445
+ if (!_classPrivateFieldGet(this, _isIntervalIgnored)) {
1446
+ _classPrivateMethodGet(this, _consumeIntervalSlot, consumeIntervalSlot).call(this, now1);
1447
+ _classPrivateMethodGet(this, _scheduleRateLimitUpdate, scheduleRateLimitUpdate).call(this);
852
1448
  }
853
1449
  this.emit("active");
854
1450
  job();
855
1451
  if (canInitializeInterval) {
856
1452
  _classPrivateMethodGet(this, _initializeIntervalIfNeeded, initializeIntervalIfNeeded).call(this);
857
1453
  }
858
- return true;
1454
+ taskStarted = true;
859
1455
  }
860
1456
  }
861
- return false;
1457
+ return taskStarted;
862
1458
  }
863
1459
  function initializeIntervalIfNeeded() {
864
1460
  var _this = this;
865
1461
  if (_classPrivateFieldGet(this, _isIntervalIgnored) || _classPrivateFieldGet(this, _intervalId) !== undefined) {
866
1462
  return;
867
1463
  }
1464
+ // Strict mode uses timeouts instead of interval timers
1465
+ if (_classPrivateFieldGet(this, _strict)) {
1466
+ return;
1467
+ }
868
1468
  _classPrivateFieldSet(this, _intervalId, setInterval(function() {
869
1469
  _classPrivateMethodGet(_this, _onInterval, onInterval).call(_this);
870
1470
  }, _classPrivateFieldGet(this, _interval)));
871
1471
  _classPrivateFieldSet(this, _intervalEnd, Date.now() + _classPrivateFieldGet(this, _interval));
872
1472
  }
873
1473
  function onInterval() {
874
- if (_classPrivateFieldGet(this, _intervalCount) === 0 && _classPrivateFieldGet(this, _pending) === 0 && _classPrivateFieldGet(this, _intervalId)) {
875
- clearInterval(_classPrivateFieldGet(this, _intervalId));
876
- _classPrivateFieldSet(this, _intervalId, undefined);
1474
+ // Non-strict mode uses interval timers and intervalCount
1475
+ if (!_classPrivateFieldGet(this, _strict)) {
1476
+ if (_classPrivateFieldGet(this, _intervalCount) === 0 && _classPrivateFieldGet(this, _pending) === 0 && _classPrivateFieldGet(this, _intervalId)) {
1477
+ _classPrivateMethodGet(this, _clearIntervalTimer, clearIntervalTimer).call(this);
1478
+ }
1479
+ _classPrivateFieldSet(this, _intervalCount, _classPrivateFieldGet(this, _carryoverIntervalCount) ? _classPrivateFieldGet(this, _pending) : 0);
877
1480
  }
878
- _classPrivateFieldSet(this, _intervalCount, _classPrivateFieldGet(this, _carryoverConcurrencyCount) ? _classPrivateFieldGet(this, _pending) : 0);
879
1481
  _classPrivateMethodGet(this, _processQueue, processQueue).call(this);
1482
+ _classPrivateMethodGet(this, _scheduleRateLimitUpdate, scheduleRateLimitUpdate).call(this);
880
1483
  }
881
1484
  function processQueue() {
882
1485
  // eslint-disable-next-line no-empty
883
1486
  while(_classPrivateMethodGet(this, _tryToStartAnother, tryToStartAnother).call(this)){}
884
1487
  }
885
- function throwOnAbort(signal) {
886
- return _throwOnAbort1.apply(this, arguments);
887
- }
888
- function _throwOnAbort1() {
889
- _throwOnAbort1 = _asyncToGenerator(function(signal) {
890
- return __generator(this, function(_state) {
891
- return [
892
- 2,
893
- new Promise(function(_resolve, reject) {
894
- signal.addEventListener("abort", function() {
895
- reject(signal.reason);
896
- }, {
897
- once: true
898
- });
899
- })
900
- ];
901
- });
902
- });
903
- return _throwOnAbort1.apply(this, arguments);
904
- }
905
- function onEvent(event, filter) {
1488
+ function onEvent(events, filter) {
906
1489
  return _onEvent1.apply(this, arguments);
907
1490
  }
908
1491
  function _onEvent1() {
909
- _onEvent1 = _asyncToGenerator(function(event, filter) {
910
- var _this;
1492
+ _onEvent1 = _asyncToGenerator(function(events, filter) {
1493
+ var _this, eventList;
911
1494
  return __generator(this, function(_state) {
912
1495
  _this = this;
1496
+ eventList = Array.isArray(events) ? events : [
1497
+ events
1498
+ ];
913
1499
  return [
914
1500
  2,
915
1501
  new Promise(function(resolve) {
@@ -917,13 +1503,112 @@ function _onEvent1() {
917
1503
  if (filter && !filter()) {
918
1504
  return;
919
1505
  }
920
- _this.off(event, listener);
1506
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
1507
+ try {
1508
+ for(var _iterator = eventList[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
1509
+ var event = _step.value;
1510
+ _this.off(event, listener);
1511
+ }
1512
+ } catch (err) {
1513
+ _didIteratorError = true;
1514
+ _iteratorError = err;
1515
+ } finally{
1516
+ try {
1517
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
1518
+ _iterator.return();
1519
+ }
1520
+ } finally{
1521
+ if (_didIteratorError) {
1522
+ throw _iteratorError;
1523
+ }
1524
+ }
1525
+ }
921
1526
  resolve();
922
1527
  };
923
- _this.on(event, listener);
1528
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
1529
+ try {
1530
+ for(var _iterator = eventList[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
1531
+ var event = _step.value;
1532
+ _this.on(event, listener);
1533
+ }
1534
+ } catch (err) {
1535
+ _didIteratorError = true;
1536
+ _iteratorError = err;
1537
+ } finally{
1538
+ try {
1539
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
1540
+ _iterator.return();
1541
+ }
1542
+ } finally{
1543
+ if (_didIteratorError) {
1544
+ throw _iteratorError;
1545
+ }
1546
+ }
1547
+ }
924
1548
  })
925
1549
  ];
926
1550
  });
927
1551
  });
928
1552
  return _onEvent1.apply(this, arguments);
929
1553
  }
1554
+ function setupRateLimitTracking() {
1555
+ var _this = this;
1556
+ // Only schedule updates when rate limiting is enabled
1557
+ if (_classPrivateFieldGet(this, _isIntervalIgnored)) {
1558
+ return;
1559
+ }
1560
+ // Wire up to lifecycle events that affect rate limit state
1561
+ // Only 'add' and 'next' can actually change rate limit state
1562
+ this.on("add", function() {
1563
+ if (_classPrivateFieldGet(_this, _queue).size > 0) {
1564
+ _classPrivateMethodGet(_this, _scheduleRateLimitUpdate, scheduleRateLimitUpdate).call(_this);
1565
+ }
1566
+ });
1567
+ this.on("next", function() {
1568
+ _classPrivateMethodGet(_this, _scheduleRateLimitUpdate, scheduleRateLimitUpdate).call(_this);
1569
+ });
1570
+ }
1571
+ function scheduleRateLimitUpdate() {
1572
+ var _this = this;
1573
+ // Skip if rate limiting is not enabled or already scheduled
1574
+ if (_classPrivateFieldGet(this, _isIntervalIgnored) || _classPrivateFieldGet(this, _rateLimitFlushScheduled)) {
1575
+ return;
1576
+ }
1577
+ _classPrivateFieldSet(this, _rateLimitFlushScheduled, true);
1578
+ queueMicrotask(function() {
1579
+ _classPrivateFieldSet(_this, _rateLimitFlushScheduled, false);
1580
+ _classPrivateMethodGet(_this, _updateRateLimitState, updateRateLimitState).call(_this);
1581
+ });
1582
+ }
1583
+ function rollbackIntervalConsumption() {
1584
+ if (_classPrivateFieldGet(this, _isIntervalIgnored)) {
1585
+ return;
1586
+ }
1587
+ _classPrivateMethodGet(this, _rollbackIntervalSlot, rollbackIntervalSlot).call(this);
1588
+ _classPrivateMethodGet(this, _scheduleRateLimitUpdate, scheduleRateLimitUpdate).call(this);
1589
+ }
1590
+ function updateRateLimitState() {
1591
+ var previous = _classPrivateFieldGet(this, _rateLimitedInInterval);
1592
+ // Early exit if rate limiting is disabled or queue is empty
1593
+ if (_classPrivateFieldGet(this, _isIntervalIgnored) || _classPrivateFieldGet(this, _queue).size === 0) {
1594
+ if (previous) {
1595
+ _classPrivateFieldSet(this, _rateLimitedInInterval, false);
1596
+ this.emit("rateLimitCleared");
1597
+ }
1598
+ return;
1599
+ }
1600
+ // Get the current count based on mode
1601
+ var count;
1602
+ if (_classPrivateFieldGet(this, _strict)) {
1603
+ var now = Date.now();
1604
+ _classPrivateMethodGet(this, _cleanupStrictTicks, cleanupStrictTicks).call(this, now);
1605
+ count = _classPrivateMethodGet(this, _getActiveTicksCount, getActiveTicksCount).call(this);
1606
+ } else {
1607
+ count = _classPrivateFieldGet(this, _intervalCount);
1608
+ }
1609
+ var shouldBeRateLimited = count >= _classPrivateFieldGet(this, _intervalCap);
1610
+ if (shouldBeRateLimited !== previous) {
1611
+ _classPrivateFieldSet(this, _rateLimitedInInterval, shouldBeRateLimited);
1612
+ this.emit(shouldBeRateLimited ? "rateLimit" : "rateLimitCleared");
1613
+ }
1614
+ }