@0xbow/privacy-pools-core-sdk 1.0.4 → 1.1.1

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.
Files changed (32) hide show
  1. package/dist/esm/{fetchArtifacts.esm-C_DNv-_D.js → fetchArtifacts.esm-DbVRphob.js} +2 -2
  2. package/dist/esm/{fetchArtifacts.esm-C_DNv-_D.js.map → fetchArtifacts.esm-DbVRphob.js.map} +1 -1
  3. package/dist/esm/{fetchArtifacts.node-BBPNjgiT.js → fetchArtifacts.node-D-fJGtzV.js} +2 -2
  4. package/dist/esm/{fetchArtifacts.node-BBPNjgiT.js.map → fetchArtifacts.node-D-fJGtzV.js.map} +1 -1
  5. package/dist/esm/{index-BxzIe_IR.js → index-DkNRxKxP.js} +2889 -109
  6. package/dist/esm/index-DkNRxKxP.js.map +1 -0
  7. package/dist/esm/index.mjs +1 -1
  8. package/dist/index.d.mts +87 -14
  9. package/dist/node/{fetchArtifacts.esm-l-EDo53-.js → fetchArtifacts.esm-BIT-b_1_.js} +2 -2
  10. package/dist/node/{fetchArtifacts.esm-l-EDo53-.js.map → fetchArtifacts.esm-BIT-b_1_.js.map} +1 -1
  11. package/dist/node/{fetchArtifacts.node-DYwQHSF4.js → fetchArtifacts.node-CKwwU50E.js} +2 -2
  12. package/dist/node/{fetchArtifacts.node-DYwQHSF4.js.map → fetchArtifacts.node-CKwwU50E.js.map} +1 -1
  13. package/dist/node/{index-DGsIfUGw.js → index-C3RV9Cri.js} +2889 -109
  14. package/dist/node/index-C3RV9Cri.js.map +1 -0
  15. package/dist/node/index.mjs +1 -1
  16. package/dist/types/core/account.service.d.ts +8 -6
  17. package/dist/types/core/data.service.d.ts +28 -8
  18. package/dist/types/{fetchArtifacts.esm-IMTIZwq7.js → fetchArtifacts.esm-DT5RuODl.js} +1 -1
  19. package/dist/types/{fetchArtifacts.node-BcXsBNCT.js → fetchArtifacts.node-D_iVIPqW.js} +1 -1
  20. package/dist/types/{index-DbuAhDci.js → index-CHy3YamH.js} +2888 -108
  21. package/dist/types/index.js +1 -1
  22. package/dist/types/types/index.d.ts +1 -0
  23. package/dist/types/types/rateLimit.d.ts +51 -0
  24. package/package.json +4 -2
  25. package/src/core/account.service.ts +52 -39
  26. package/src/core/data.service.ts +325 -95
  27. package/src/types/index.ts +1 -0
  28. package/src/types/rateLimit.ts +66 -0
  29. package/dist/esm/index-BxzIe_IR.js.map +0 -1
  30. package/dist/node/index-DGsIfUGw.js.map +0 -1
  31. package/dist/types/utils/concurrency.d.ts +0 -15
  32. package/src/utils/concurrency.ts +0 -32
@@ -21,6 +21,18 @@ import { O_TRUNC, O_CREAT, O_RDWR, O_RDONLY } from 'constants';
21
21
  import 'readline';
22
22
  import require$$1$3 from 'path';
23
23
 
24
+ /**
25
+ * Default log fetch configuration
26
+ */
27
+ const DEFAULT_LOG_FETCH_CONFIG = {
28
+ blockChunkSize: 10000,
29
+ concurrency: 3,
30
+ chunkDelayMs: 0,
31
+ retryOnFailure: true,
32
+ maxRetries: 3,
33
+ retryBaseDelayMs: 1000,
34
+ };
35
+
24
36
  const version$1 = '2.22.14';
25
37
 
26
38
  let errorConfig = {
@@ -51070,10 +51082,10 @@ const circuitToAsset = {
51070
51082
 
51071
51083
  async function importFetchVersionedArtifact(isBrowser) {
51072
51084
  if (isBrowser) {
51073
- return import('./fetchArtifacts.esm-l-EDo53-.js');
51085
+ return import('./fetchArtifacts.esm-BIT-b_1_.js');
51074
51086
  }
51075
51087
  else {
51076
- return import('./fetchArtifacts.node-DYwQHSF4.js');
51088
+ return import('./fetchArtifacts.node-CKwwU50E.js');
51077
51089
  }
51078
51090
  }
51079
51091
 
@@ -76330,6 +76342,2675 @@ class AccountError extends SDKError {
76330
76342
  }
76331
76343
  }
76332
76344
 
76345
+ /**
76346
+ * Creates a continuation function with some arguments already applied.
76347
+ *
76348
+ * Useful as a shorthand when combined with other control flow functions. Any
76349
+ * arguments passed to the returned function are added to the arguments
76350
+ * originally passed to apply.
76351
+ *
76352
+ * @name apply
76353
+ * @static
76354
+ * @memberOf module:Utils
76355
+ * @method
76356
+ * @category Util
76357
+ * @param {Function} fn - The function you want to eventually apply all
76358
+ * arguments to. Invokes with (arguments...).
76359
+ * @param {...*} arguments... - Any number of arguments to automatically apply
76360
+ * when the continuation is called.
76361
+ * @returns {Function} the partially-applied function
76362
+ * @example
76363
+ *
76364
+ * // using apply
76365
+ * async.parallel([
76366
+ * async.apply(fs.writeFile, 'testfile1', 'test1'),
76367
+ * async.apply(fs.writeFile, 'testfile2', 'test2')
76368
+ * ]);
76369
+ *
76370
+ *
76371
+ * // the same process without using apply
76372
+ * async.parallel([
76373
+ * function(callback) {
76374
+ * fs.writeFile('testfile1', 'test1', callback);
76375
+ * },
76376
+ * function(callback) {
76377
+ * fs.writeFile('testfile2', 'test2', callback);
76378
+ * }
76379
+ * ]);
76380
+ *
76381
+ * // It's possible to pass any number of additional arguments when calling the
76382
+ * // continuation:
76383
+ *
76384
+ * node> var fn = async.apply(sys.puts, 'one');
76385
+ * node> fn('two', 'three');
76386
+ * one
76387
+ * two
76388
+ * three
76389
+ */
76390
+
76391
+ function initialParams (fn) {
76392
+ return function (...args/*, callback*/) {
76393
+ var callback = args.pop();
76394
+ return fn.call(this, args, callback);
76395
+ };
76396
+ }
76397
+
76398
+ /* istanbul ignore file */
76399
+
76400
+ var hasQueueMicrotask = typeof queueMicrotask === 'function' && queueMicrotask;
76401
+ var hasSetImmediate = typeof setImmediate === 'function' && setImmediate;
76402
+ var hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function';
76403
+
76404
+ function fallback(fn) {
76405
+ setTimeout(fn, 0);
76406
+ }
76407
+
76408
+ function wrap(defer) {
76409
+ return (fn, ...args) => defer(() => fn(...args));
76410
+ }
76411
+
76412
+ var _defer$1;
76413
+
76414
+ if (hasQueueMicrotask) {
76415
+ _defer$1 = queueMicrotask;
76416
+ } else if (hasSetImmediate) {
76417
+ _defer$1 = setImmediate;
76418
+ } else if (hasNextTick) {
76419
+ _defer$1 = process.nextTick;
76420
+ } else {
76421
+ _defer$1 = fallback;
76422
+ }
76423
+
76424
+ var setImmediate$1 = wrap(_defer$1);
76425
+
76426
+ /**
76427
+ * Take a sync function and make it async, passing its return value to a
76428
+ * callback. This is useful for plugging sync functions into a waterfall,
76429
+ * series, or other async functions. Any arguments passed to the generated
76430
+ * function will be passed to the wrapped function (except for the final
76431
+ * callback argument). Errors thrown will be passed to the callback.
76432
+ *
76433
+ * If the function passed to `asyncify` returns a Promise, that promises's
76434
+ * resolved/rejected state will be used to call the callback, rather than simply
76435
+ * the synchronous return value.
76436
+ *
76437
+ * This also means you can asyncify ES2017 `async` functions.
76438
+ *
76439
+ * @name asyncify
76440
+ * @static
76441
+ * @memberOf module:Utils
76442
+ * @method
76443
+ * @alias wrapSync
76444
+ * @category Util
76445
+ * @param {Function} func - The synchronous function, or Promise-returning
76446
+ * function to convert to an {@link AsyncFunction}.
76447
+ * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be
76448
+ * invoked with `(args..., callback)`.
76449
+ * @example
76450
+ *
76451
+ * // passing a regular synchronous function
76452
+ * async.waterfall([
76453
+ * async.apply(fs.readFile, filename, "utf8"),
76454
+ * async.asyncify(JSON.parse),
76455
+ * function (data, next) {
76456
+ * // data is the result of parsing the text.
76457
+ * // If there was a parsing error, it would have been caught.
76458
+ * }
76459
+ * ], callback);
76460
+ *
76461
+ * // passing a function returning a promise
76462
+ * async.waterfall([
76463
+ * async.apply(fs.readFile, filename, "utf8"),
76464
+ * async.asyncify(function (contents) {
76465
+ * return db.model.create(contents);
76466
+ * }),
76467
+ * function (model, next) {
76468
+ * // `model` is the instantiated model object.
76469
+ * // If there was an error, this function would be skipped.
76470
+ * }
76471
+ * ], callback);
76472
+ *
76473
+ * // es2017 example, though `asyncify` is not needed if your JS environment
76474
+ * // supports async functions out of the box
76475
+ * var q = async.queue(async.asyncify(async function(file) {
76476
+ * var intermediateStep = await processFile(file);
76477
+ * return await somePromise(intermediateStep)
76478
+ * }));
76479
+ *
76480
+ * q.push(files);
76481
+ */
76482
+ function asyncify(func) {
76483
+ if (isAsync(func)) {
76484
+ return function (...args/*, callback*/) {
76485
+ const callback = args.pop();
76486
+ const promise = func.apply(this, args);
76487
+ return handlePromise(promise, callback)
76488
+ }
76489
+ }
76490
+
76491
+ return initialParams(function (args, callback) {
76492
+ var result;
76493
+ try {
76494
+ result = func.apply(this, args);
76495
+ } catch (e) {
76496
+ return callback(e);
76497
+ }
76498
+ // if result is Promise object
76499
+ if (result && typeof result.then === 'function') {
76500
+ return handlePromise(result, callback)
76501
+ } else {
76502
+ callback(null, result);
76503
+ }
76504
+ });
76505
+ }
76506
+
76507
+ function handlePromise(promise, callback) {
76508
+ return promise.then(value => {
76509
+ invokeCallback(callback, null, value);
76510
+ }, err => {
76511
+ invokeCallback(callback, err && (err instanceof Error || err.message) ? err : new Error(err));
76512
+ });
76513
+ }
76514
+
76515
+ function invokeCallback(callback, error, value) {
76516
+ try {
76517
+ callback(error, value);
76518
+ } catch (err) {
76519
+ setImmediate$1(e => { throw e }, err);
76520
+ }
76521
+ }
76522
+
76523
+ function isAsync(fn) {
76524
+ return fn[Symbol.toStringTag] === 'AsyncFunction';
76525
+ }
76526
+
76527
+ function isAsyncGenerator(fn) {
76528
+ return fn[Symbol.toStringTag] === 'AsyncGenerator';
76529
+ }
76530
+
76531
+ function isAsyncIterable(obj) {
76532
+ return typeof obj[Symbol.asyncIterator] === 'function';
76533
+ }
76534
+
76535
+ function wrapAsync(asyncFn) {
76536
+ if (typeof asyncFn !== 'function') throw new Error('expected a function')
76537
+ return isAsync(asyncFn) ? asyncify(asyncFn) : asyncFn;
76538
+ }
76539
+
76540
+ // conditionally promisify a function.
76541
+ // only return a promise if a callback is omitted
76542
+ function awaitify (asyncFn, arity) {
76543
+ if (!arity) arity = asyncFn.length;
76544
+ if (!arity) throw new Error('arity is undefined')
76545
+ function awaitable (...args) {
76546
+ if (typeof args[arity - 1] === 'function') {
76547
+ return asyncFn.apply(this, args)
76548
+ }
76549
+
76550
+ return new Promise((resolve, reject) => {
76551
+ args[arity - 1] = (err, ...cbArgs) => {
76552
+ if (err) return reject(err)
76553
+ resolve(cbArgs.length > 1 ? cbArgs : cbArgs[0]);
76554
+ };
76555
+ asyncFn.apply(this, args);
76556
+ })
76557
+ }
76558
+
76559
+ return awaitable
76560
+ }
76561
+
76562
+ function _asyncMap(eachfn, arr, iteratee, callback) {
76563
+ arr = arr || [];
76564
+ var results = [];
76565
+ var counter = 0;
76566
+ var _iteratee = wrapAsync(iteratee);
76567
+
76568
+ return eachfn(arr, (value, _, iterCb) => {
76569
+ var index = counter++;
76570
+ _iteratee(value, (err, v) => {
76571
+ results[index] = v;
76572
+ iterCb(err);
76573
+ });
76574
+ }, err => {
76575
+ callback(err, results);
76576
+ });
76577
+ }
76578
+
76579
+ function isArrayLike(value) {
76580
+ return value &&
76581
+ typeof value.length === 'number' &&
76582
+ value.length >= 0 &&
76583
+ value.length % 1 === 0;
76584
+ }
76585
+
76586
+ // A temporary value used to identify if the loop should be broken.
76587
+ // See #1064, #1293
76588
+ const breakLoop = {};
76589
+
76590
+ function once(fn) {
76591
+ function wrapper (...args) {
76592
+ if (fn === null) return;
76593
+ var callFn = fn;
76594
+ fn = null;
76595
+ callFn.apply(this, args);
76596
+ }
76597
+ Object.assign(wrapper, fn);
76598
+ return wrapper
76599
+ }
76600
+
76601
+ function getIterator (coll) {
76602
+ return coll[Symbol.iterator] && coll[Symbol.iterator]();
76603
+ }
76604
+
76605
+ function createArrayIterator(coll) {
76606
+ var i = -1;
76607
+ var len = coll.length;
76608
+ return function next() {
76609
+ return ++i < len ? {value: coll[i], key: i} : null;
76610
+ }
76611
+ }
76612
+
76613
+ function createES2015Iterator(iterator) {
76614
+ var i = -1;
76615
+ return function next() {
76616
+ var item = iterator.next();
76617
+ if (item.done)
76618
+ return null;
76619
+ i++;
76620
+ return {value: item.value, key: i};
76621
+ }
76622
+ }
76623
+
76624
+ function createObjectIterator(obj) {
76625
+ var okeys = obj ? Object.keys(obj) : [];
76626
+ var i = -1;
76627
+ var len = okeys.length;
76628
+ return function next() {
76629
+ var key = okeys[++i];
76630
+ if (key === '__proto__') {
76631
+ return next();
76632
+ }
76633
+ return i < len ? {value: obj[key], key} : null;
76634
+ };
76635
+ }
76636
+
76637
+ function createIterator(coll) {
76638
+ if (isArrayLike(coll)) {
76639
+ return createArrayIterator(coll);
76640
+ }
76641
+
76642
+ var iterator = getIterator(coll);
76643
+ return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll);
76644
+ }
76645
+
76646
+ function onlyOnce(fn) {
76647
+ return function (...args) {
76648
+ if (fn === null) throw new Error("Callback was already called.");
76649
+ var callFn = fn;
76650
+ fn = null;
76651
+ callFn.apply(this, args);
76652
+ };
76653
+ }
76654
+
76655
+ // for async generators
76656
+ function asyncEachOfLimit(generator, limit, iteratee, callback) {
76657
+ let done = false;
76658
+ let canceled = false;
76659
+ let awaiting = false;
76660
+ let running = 0;
76661
+ let idx = 0;
76662
+
76663
+ function replenish() {
76664
+ //console.log('replenish')
76665
+ if (running >= limit || awaiting || done) return
76666
+ //console.log('replenish awaiting')
76667
+ awaiting = true;
76668
+ generator.next().then(({value, done: iterDone}) => {
76669
+ //console.log('got value', value)
76670
+ if (canceled || done) return
76671
+ awaiting = false;
76672
+ if (iterDone) {
76673
+ done = true;
76674
+ if (running <= 0) {
76675
+ //console.log('done nextCb')
76676
+ callback(null);
76677
+ }
76678
+ return;
76679
+ }
76680
+ running++;
76681
+ iteratee(value, idx, iterateeCallback);
76682
+ idx++;
76683
+ replenish();
76684
+ }).catch(handleError);
76685
+ }
76686
+
76687
+ function iterateeCallback(err, result) {
76688
+ //console.log('iterateeCallback')
76689
+ running -= 1;
76690
+ if (canceled) return
76691
+ if (err) return handleError(err)
76692
+
76693
+ if (err === false) {
76694
+ done = true;
76695
+ canceled = true;
76696
+ return
76697
+ }
76698
+
76699
+ if (result === breakLoop || (done && running <= 0)) {
76700
+ done = true;
76701
+ //console.log('done iterCb')
76702
+ return callback(null);
76703
+ }
76704
+ replenish();
76705
+ }
76706
+
76707
+ function handleError(err) {
76708
+ if (canceled) return
76709
+ awaiting = false;
76710
+ done = true;
76711
+ callback(err);
76712
+ }
76713
+
76714
+ replenish();
76715
+ }
76716
+
76717
+ var eachOfLimit$2 = (limit) => {
76718
+ return (obj, iteratee, callback) => {
76719
+ callback = once(callback);
76720
+ if (limit <= 0) {
76721
+ throw new RangeError('concurrency limit cannot be less than 1')
76722
+ }
76723
+ if (!obj) {
76724
+ return callback(null);
76725
+ }
76726
+ if (isAsyncGenerator(obj)) {
76727
+ return asyncEachOfLimit(obj, limit, iteratee, callback)
76728
+ }
76729
+ if (isAsyncIterable(obj)) {
76730
+ return asyncEachOfLimit(obj[Symbol.asyncIterator](), limit, iteratee, callback)
76731
+ }
76732
+ var nextElem = createIterator(obj);
76733
+ var done = false;
76734
+ var canceled = false;
76735
+ var running = 0;
76736
+ var looping = false;
76737
+
76738
+ function iterateeCallback(err, value) {
76739
+ if (canceled) return
76740
+ running -= 1;
76741
+ if (err) {
76742
+ done = true;
76743
+ callback(err);
76744
+ }
76745
+ else if (err === false) {
76746
+ done = true;
76747
+ canceled = true;
76748
+ }
76749
+ else if (value === breakLoop || (done && running <= 0)) {
76750
+ done = true;
76751
+ return callback(null);
76752
+ }
76753
+ else if (!looping) {
76754
+ replenish();
76755
+ }
76756
+ }
76757
+
76758
+ function replenish () {
76759
+ looping = true;
76760
+ while (running < limit && !done) {
76761
+ var elem = nextElem();
76762
+ if (elem === null) {
76763
+ done = true;
76764
+ if (running <= 0) {
76765
+ callback(null);
76766
+ }
76767
+ return;
76768
+ }
76769
+ running += 1;
76770
+ iteratee(elem.value, elem.key, onlyOnce(iterateeCallback));
76771
+ }
76772
+ looping = false;
76773
+ }
76774
+
76775
+ replenish();
76776
+ };
76777
+ };
76778
+
76779
+ /**
76780
+ * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a
76781
+ * time.
76782
+ *
76783
+ * @name eachOfLimit
76784
+ * @static
76785
+ * @memberOf module:Collections
76786
+ * @method
76787
+ * @see [async.eachOf]{@link module:Collections.eachOf}
76788
+ * @alias forEachOfLimit
76789
+ * @category Collection
76790
+ * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
76791
+ * @param {number} limit - The maximum number of async operations at a time.
76792
+ * @param {AsyncFunction} iteratee - An async function to apply to each
76793
+ * item in `coll`. The `key` is the item's key, or index in the case of an
76794
+ * array.
76795
+ * Invoked with (item, key, callback).
76796
+ * @param {Function} [callback] - A callback which is called when all
76797
+ * `iteratee` functions have finished, or an error occurs. Invoked with (err).
76798
+ * @returns {Promise} a promise, if a callback is omitted
76799
+ */
76800
+ function eachOfLimit(coll, limit, iteratee, callback) {
76801
+ return eachOfLimit$2(limit)(coll, wrapAsync(iteratee), callback);
76802
+ }
76803
+
76804
+ var eachOfLimit$1 = awaitify(eachOfLimit, 4);
76805
+
76806
+ // eachOf implementation optimized for array-likes
76807
+ function eachOfArrayLike(coll, iteratee, callback) {
76808
+ callback = once(callback);
76809
+ var index = 0,
76810
+ completed = 0,
76811
+ {length} = coll,
76812
+ canceled = false;
76813
+ if (length === 0) {
76814
+ callback(null);
76815
+ }
76816
+
76817
+ function iteratorCallback(err, value) {
76818
+ if (err === false) {
76819
+ canceled = true;
76820
+ }
76821
+ if (canceled === true) return
76822
+ if (err) {
76823
+ callback(err);
76824
+ } else if ((++completed === length) || value === breakLoop) {
76825
+ callback(null);
76826
+ }
76827
+ }
76828
+
76829
+ for (; index < length; index++) {
76830
+ iteratee(coll[index], index, onlyOnce(iteratorCallback));
76831
+ }
76832
+ }
76833
+
76834
+ // a generic version of eachOf which can handle array, object, and iterator cases.
76835
+ function eachOfGeneric (coll, iteratee, callback) {
76836
+ return eachOfLimit$1(coll, Infinity, iteratee, callback);
76837
+ }
76838
+
76839
+ /**
76840
+ * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument
76841
+ * to the iteratee.
76842
+ *
76843
+ * @name eachOf
76844
+ * @static
76845
+ * @memberOf module:Collections
76846
+ * @method
76847
+ * @alias forEachOf
76848
+ * @category Collection
76849
+ * @see [async.each]{@link module:Collections.each}
76850
+ * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
76851
+ * @param {AsyncFunction} iteratee - A function to apply to each
76852
+ * item in `coll`.
76853
+ * The `key` is the item's key, or index in the case of an array.
76854
+ * Invoked with (item, key, callback).
76855
+ * @param {Function} [callback] - A callback which is called when all
76856
+ * `iteratee` functions have finished, or an error occurs. Invoked with (err).
76857
+ * @returns {Promise} a promise, if a callback is omitted
76858
+ * @example
76859
+ *
76860
+ * // dev.json is a file containing a valid json object config for dev environment
76861
+ * // dev.json is a file containing a valid json object config for test environment
76862
+ * // prod.json is a file containing a valid json object config for prod environment
76863
+ * // invalid.json is a file with a malformed json object
76864
+ *
76865
+ * let configs = {}; //global variable
76866
+ * let validConfigFileMap = {dev: 'dev.json', test: 'test.json', prod: 'prod.json'};
76867
+ * let invalidConfigFileMap = {dev: 'dev.json', test: 'test.json', invalid: 'invalid.json'};
76868
+ *
76869
+ * // asynchronous function that reads a json file and parses the contents as json object
76870
+ * function parseFile(file, key, callback) {
76871
+ * fs.readFile(file, "utf8", function(err, data) {
76872
+ * if (err) return calback(err);
76873
+ * try {
76874
+ * configs[key] = JSON.parse(data);
76875
+ * } catch (e) {
76876
+ * return callback(e);
76877
+ * }
76878
+ * callback();
76879
+ * });
76880
+ * }
76881
+ *
76882
+ * // Using callbacks
76883
+ * async.forEachOf(validConfigFileMap, parseFile, function (err) {
76884
+ * if (err) {
76885
+ * console.error(err);
76886
+ * } else {
76887
+ * console.log(configs);
76888
+ * // configs is now a map of JSON data, e.g.
76889
+ * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json}
76890
+ * }
76891
+ * });
76892
+ *
76893
+ * //Error handing
76894
+ * async.forEachOf(invalidConfigFileMap, parseFile, function (err) {
76895
+ * if (err) {
76896
+ * console.error(err);
76897
+ * // JSON parse error exception
76898
+ * } else {
76899
+ * console.log(configs);
76900
+ * }
76901
+ * });
76902
+ *
76903
+ * // Using Promises
76904
+ * async.forEachOf(validConfigFileMap, parseFile)
76905
+ * .then( () => {
76906
+ * console.log(configs);
76907
+ * // configs is now a map of JSON data, e.g.
76908
+ * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json}
76909
+ * }).catch( err => {
76910
+ * console.error(err);
76911
+ * });
76912
+ *
76913
+ * //Error handing
76914
+ * async.forEachOf(invalidConfigFileMap, parseFile)
76915
+ * .then( () => {
76916
+ * console.log(configs);
76917
+ * }).catch( err => {
76918
+ * console.error(err);
76919
+ * // JSON parse error exception
76920
+ * });
76921
+ *
76922
+ * // Using async/await
76923
+ * async () => {
76924
+ * try {
76925
+ * let result = await async.forEachOf(validConfigFileMap, parseFile);
76926
+ * console.log(configs);
76927
+ * // configs is now a map of JSON data, e.g.
76928
+ * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json}
76929
+ * }
76930
+ * catch (err) {
76931
+ * console.log(err);
76932
+ * }
76933
+ * }
76934
+ *
76935
+ * //Error handing
76936
+ * async () => {
76937
+ * try {
76938
+ * let result = await async.forEachOf(invalidConfigFileMap, parseFile);
76939
+ * console.log(configs);
76940
+ * }
76941
+ * catch (err) {
76942
+ * console.log(err);
76943
+ * // JSON parse error exception
76944
+ * }
76945
+ * }
76946
+ *
76947
+ */
76948
+ function eachOf(coll, iteratee, callback) {
76949
+ var eachOfImplementation = isArrayLike(coll) ? eachOfArrayLike : eachOfGeneric;
76950
+ return eachOfImplementation(coll, wrapAsync(iteratee), callback);
76951
+ }
76952
+
76953
+ var eachOf$1 = awaitify(eachOf, 3);
76954
+
76955
+ /**
76956
+ * Produces a new collection of values by mapping each value in `coll` through
76957
+ * the `iteratee` function. The `iteratee` is called with an item from `coll`
76958
+ * and a callback for when it has finished processing. Each of these callbacks
76959
+ * takes 2 arguments: an `error`, and the transformed item from `coll`. If
76960
+ * `iteratee` passes an error to its callback, the main `callback` (for the
76961
+ * `map` function) is immediately called with the error.
76962
+ *
76963
+ * Note, that since this function applies the `iteratee` to each item in
76964
+ * parallel, there is no guarantee that the `iteratee` functions will complete
76965
+ * in order. However, the results array will be in the same order as the
76966
+ * original `coll`.
76967
+ *
76968
+ * If `map` is passed an Object, the results will be an Array. The results
76969
+ * will roughly be in the order of the original Objects' keys (but this can
76970
+ * vary across JavaScript engines).
76971
+ *
76972
+ * @name map
76973
+ * @static
76974
+ * @memberOf module:Collections
76975
+ * @method
76976
+ * @category Collection
76977
+ * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
76978
+ * @param {AsyncFunction} iteratee - An async function to apply to each item in
76979
+ * `coll`.
76980
+ * The iteratee should complete with the transformed item.
76981
+ * Invoked with (item, callback).
76982
+ * @param {Function} [callback] - A callback which is called when all `iteratee`
76983
+ * functions have finished, or an error occurs. Results is an Array of the
76984
+ * transformed items from the `coll`. Invoked with (err, results).
76985
+ * @returns {Promise} a promise, if no callback is passed
76986
+ * @example
76987
+ *
76988
+ * // file1.txt is a file that is 1000 bytes in size
76989
+ * // file2.txt is a file that is 2000 bytes in size
76990
+ * // file3.txt is a file that is 3000 bytes in size
76991
+ * // file4.txt does not exist
76992
+ *
76993
+ * const fileList = ['file1.txt','file2.txt','file3.txt'];
76994
+ * const withMissingFileList = ['file1.txt','file2.txt','file4.txt'];
76995
+ *
76996
+ * // asynchronous function that returns the file size in bytes
76997
+ * function getFileSizeInBytes(file, callback) {
76998
+ * fs.stat(file, function(err, stat) {
76999
+ * if (err) {
77000
+ * return callback(err);
77001
+ * }
77002
+ * callback(null, stat.size);
77003
+ * });
77004
+ * }
77005
+ *
77006
+ * // Using callbacks
77007
+ * async.map(fileList, getFileSizeInBytes, function(err, results) {
77008
+ * if (err) {
77009
+ * console.log(err);
77010
+ * } else {
77011
+ * console.log(results);
77012
+ * // results is now an array of the file size in bytes for each file, e.g.
77013
+ * // [ 1000, 2000, 3000]
77014
+ * }
77015
+ * });
77016
+ *
77017
+ * // Error Handling
77018
+ * async.map(withMissingFileList, getFileSizeInBytes, function(err, results) {
77019
+ * if (err) {
77020
+ * console.log(err);
77021
+ * // [ Error: ENOENT: no such file or directory ]
77022
+ * } else {
77023
+ * console.log(results);
77024
+ * }
77025
+ * });
77026
+ *
77027
+ * // Using Promises
77028
+ * async.map(fileList, getFileSizeInBytes)
77029
+ * .then( results => {
77030
+ * console.log(results);
77031
+ * // results is now an array of the file size in bytes for each file, e.g.
77032
+ * // [ 1000, 2000, 3000]
77033
+ * }).catch( err => {
77034
+ * console.log(err);
77035
+ * });
77036
+ *
77037
+ * // Error Handling
77038
+ * async.map(withMissingFileList, getFileSizeInBytes)
77039
+ * .then( results => {
77040
+ * console.log(results);
77041
+ * }).catch( err => {
77042
+ * console.log(err);
77043
+ * // [ Error: ENOENT: no such file or directory ]
77044
+ * });
77045
+ *
77046
+ * // Using async/await
77047
+ * async () => {
77048
+ * try {
77049
+ * let results = await async.map(fileList, getFileSizeInBytes);
77050
+ * console.log(results);
77051
+ * // results is now an array of the file size in bytes for each file, e.g.
77052
+ * // [ 1000, 2000, 3000]
77053
+ * }
77054
+ * catch (err) {
77055
+ * console.log(err);
77056
+ * }
77057
+ * }
77058
+ *
77059
+ * // Error Handling
77060
+ * async () => {
77061
+ * try {
77062
+ * let results = await async.map(withMissingFileList, getFileSizeInBytes);
77063
+ * console.log(results);
77064
+ * }
77065
+ * catch (err) {
77066
+ * console.log(err);
77067
+ * // [ Error: ENOENT: no such file or directory ]
77068
+ * }
77069
+ * }
77070
+ *
77071
+ */
77072
+ function map (coll, iteratee, callback) {
77073
+ return _asyncMap(eachOf$1, coll, iteratee, callback)
77074
+ }
77075
+ var map$1 = awaitify(map, 3);
77076
+
77077
+ /**
77078
+ * The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time.
77079
+ *
77080
+ * @name eachOfSeries
77081
+ * @static
77082
+ * @memberOf module:Collections
77083
+ * @method
77084
+ * @see [async.eachOf]{@link module:Collections.eachOf}
77085
+ * @alias forEachOfSeries
77086
+ * @category Collection
77087
+ * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
77088
+ * @param {AsyncFunction} iteratee - An async function to apply to each item in
77089
+ * `coll`.
77090
+ * Invoked with (item, key, callback).
77091
+ * @param {Function} [callback] - A callback which is called when all `iteratee`
77092
+ * functions have finished, or an error occurs. Invoked with (err).
77093
+ * @returns {Promise} a promise, if a callback is omitted
77094
+ */
77095
+ function eachOfSeries(coll, iteratee, callback) {
77096
+ return eachOfLimit$1(coll, 1, iteratee, callback)
77097
+ }
77098
+ var eachOfSeries$1 = awaitify(eachOfSeries, 3);
77099
+
77100
+ /**
77101
+ * The same as [`map`]{@link module:Collections.map} but runs only a single async operation at a time.
77102
+ *
77103
+ * @name mapSeries
77104
+ * @static
77105
+ * @memberOf module:Collections
77106
+ * @method
77107
+ * @see [async.map]{@link module:Collections.map}
77108
+ * @category Collection
77109
+ * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
77110
+ * @param {AsyncFunction} iteratee - An async function to apply to each item in
77111
+ * `coll`.
77112
+ * The iteratee should complete with the transformed item.
77113
+ * Invoked with (item, callback).
77114
+ * @param {Function} [callback] - A callback which is called when all `iteratee`
77115
+ * functions have finished, or an error occurs. Results is an array of the
77116
+ * transformed items from the `coll`. Invoked with (err, results).
77117
+ * @returns {Promise} a promise, if no callback is passed
77118
+ */
77119
+ function mapSeries (coll, iteratee, callback) {
77120
+ return _asyncMap(eachOfSeries$1, coll, iteratee, callback)
77121
+ }
77122
+ awaitify(mapSeries, 3);
77123
+
77124
+ /**
77125
+ * Reduces `coll` into a single value using an async `iteratee` to return each
77126
+ * successive step. `memo` is the initial state of the reduction. This function
77127
+ * only operates in series.
77128
+ *
77129
+ * For performance reasons, it may make sense to split a call to this function
77130
+ * into a parallel map, and then use the normal `Array.prototype.reduce` on the
77131
+ * results. This function is for situations where each step in the reduction
77132
+ * needs to be async; if you can get the data before reducing it, then it's
77133
+ * probably a good idea to do so.
77134
+ *
77135
+ * @name reduce
77136
+ * @static
77137
+ * @memberOf module:Collections
77138
+ * @method
77139
+ * @alias inject
77140
+ * @alias foldl
77141
+ * @category Collection
77142
+ * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
77143
+ * @param {*} memo - The initial state of the reduction.
77144
+ * @param {AsyncFunction} iteratee - A function applied to each item in the
77145
+ * array to produce the next step in the reduction.
77146
+ * The `iteratee` should complete with the next state of the reduction.
77147
+ * If the iteratee completes with an error, the reduction is stopped and the
77148
+ * main `callback` is immediately called with the error.
77149
+ * Invoked with (memo, item, callback).
77150
+ * @param {Function} [callback] - A callback which is called after all the
77151
+ * `iteratee` functions have finished. Result is the reduced value. Invoked with
77152
+ * (err, result).
77153
+ * @returns {Promise} a promise, if no callback is passed
77154
+ * @example
77155
+ *
77156
+ * // file1.txt is a file that is 1000 bytes in size
77157
+ * // file2.txt is a file that is 2000 bytes in size
77158
+ * // file3.txt is a file that is 3000 bytes in size
77159
+ * // file4.txt does not exist
77160
+ *
77161
+ * const fileList = ['file1.txt','file2.txt','file3.txt'];
77162
+ * const withMissingFileList = ['file1.txt','file2.txt','file3.txt', 'file4.txt'];
77163
+ *
77164
+ * // asynchronous function that computes the file size in bytes
77165
+ * // file size is added to the memoized value, then returned
77166
+ * function getFileSizeInBytes(memo, file, callback) {
77167
+ * fs.stat(file, function(err, stat) {
77168
+ * if (err) {
77169
+ * return callback(err);
77170
+ * }
77171
+ * callback(null, memo + stat.size);
77172
+ * });
77173
+ * }
77174
+ *
77175
+ * // Using callbacks
77176
+ * async.reduce(fileList, 0, getFileSizeInBytes, function(err, result) {
77177
+ * if (err) {
77178
+ * console.log(err);
77179
+ * } else {
77180
+ * console.log(result);
77181
+ * // 6000
77182
+ * // which is the sum of the file sizes of the three files
77183
+ * }
77184
+ * });
77185
+ *
77186
+ * // Error Handling
77187
+ * async.reduce(withMissingFileList, 0, getFileSizeInBytes, function(err, result) {
77188
+ * if (err) {
77189
+ * console.log(err);
77190
+ * // [ Error: ENOENT: no such file or directory ]
77191
+ * } else {
77192
+ * console.log(result);
77193
+ * }
77194
+ * });
77195
+ *
77196
+ * // Using Promises
77197
+ * async.reduce(fileList, 0, getFileSizeInBytes)
77198
+ * .then( result => {
77199
+ * console.log(result);
77200
+ * // 6000
77201
+ * // which is the sum of the file sizes of the three files
77202
+ * }).catch( err => {
77203
+ * console.log(err);
77204
+ * });
77205
+ *
77206
+ * // Error Handling
77207
+ * async.reduce(withMissingFileList, 0, getFileSizeInBytes)
77208
+ * .then( result => {
77209
+ * console.log(result);
77210
+ * }).catch( err => {
77211
+ * console.log(err);
77212
+ * // [ Error: ENOENT: no such file or directory ]
77213
+ * });
77214
+ *
77215
+ * // Using async/await
77216
+ * async () => {
77217
+ * try {
77218
+ * let result = await async.reduce(fileList, 0, getFileSizeInBytes);
77219
+ * console.log(result);
77220
+ * // 6000
77221
+ * // which is the sum of the file sizes of the three files
77222
+ * }
77223
+ * catch (err) {
77224
+ * console.log(err);
77225
+ * }
77226
+ * }
77227
+ *
77228
+ * // Error Handling
77229
+ * async () => {
77230
+ * try {
77231
+ * let result = await async.reduce(withMissingFileList, 0, getFileSizeInBytes);
77232
+ * console.log(result);
77233
+ * }
77234
+ * catch (err) {
77235
+ * console.log(err);
77236
+ * // [ Error: ENOENT: no such file or directory ]
77237
+ * }
77238
+ * }
77239
+ *
77240
+ */
77241
+ function reduce(coll, memo, iteratee, callback) {
77242
+ callback = once(callback);
77243
+ var _iteratee = wrapAsync(iteratee);
77244
+ return eachOfSeries$1(coll, (x, i, iterCb) => {
77245
+ _iteratee(memo, x, (err, v) => {
77246
+ memo = v;
77247
+ iterCb(err);
77248
+ });
77249
+ }, err => callback(err, memo));
77250
+ }
77251
+ awaitify(reduce, 4);
77252
+
77253
+ /**
77254
+ * The same as [`map`]{@link module:Collections.map} but runs a maximum of `limit` async operations at a time.
77255
+ *
77256
+ * @name mapLimit
77257
+ * @static
77258
+ * @memberOf module:Collections
77259
+ * @method
77260
+ * @see [async.map]{@link module:Collections.map}
77261
+ * @category Collection
77262
+ * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
77263
+ * @param {number} limit - The maximum number of async operations at a time.
77264
+ * @param {AsyncFunction} iteratee - An async function to apply to each item in
77265
+ * `coll`.
77266
+ * The iteratee should complete with the transformed item.
77267
+ * Invoked with (item, callback).
77268
+ * @param {Function} [callback] - A callback which is called when all `iteratee`
77269
+ * functions have finished, or an error occurs. Results is an array of the
77270
+ * transformed items from the `coll`. Invoked with (err, results).
77271
+ * @returns {Promise} a promise, if no callback is passed
77272
+ */
77273
+ function mapLimit (coll, limit, iteratee, callback) {
77274
+ return _asyncMap(eachOfLimit$2(limit), coll, iteratee, callback)
77275
+ }
77276
+ var mapLimit$1 = awaitify(mapLimit, 4);
77277
+
77278
+ /**
77279
+ * The same as [`concat`]{@link module:Collections.concat} but runs a maximum of `limit` async operations at a time.
77280
+ *
77281
+ * @name concatLimit
77282
+ * @static
77283
+ * @memberOf module:Collections
77284
+ * @method
77285
+ * @see [async.concat]{@link module:Collections.concat}
77286
+ * @category Collection
77287
+ * @alias flatMapLimit
77288
+ * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
77289
+ * @param {number} limit - The maximum number of async operations at a time.
77290
+ * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`,
77291
+ * which should use an array as its result. Invoked with (item, callback).
77292
+ * @param {Function} [callback] - A callback which is called after all the
77293
+ * `iteratee` functions have finished, or an error occurs. Results is an array
77294
+ * containing the concatenated results of the `iteratee` function. Invoked with
77295
+ * (err, results).
77296
+ * @returns A Promise, if no callback is passed
77297
+ */
77298
+ function concatLimit(coll, limit, iteratee, callback) {
77299
+ var _iteratee = wrapAsync(iteratee);
77300
+ return mapLimit$1(coll, limit, (val, iterCb) => {
77301
+ _iteratee(val, (err, ...args) => {
77302
+ if (err) return iterCb(err);
77303
+ return iterCb(err, args);
77304
+ });
77305
+ }, (err, mapResults) => {
77306
+ var result = [];
77307
+ for (var i = 0; i < mapResults.length; i++) {
77308
+ if (mapResults[i]) {
77309
+ result = result.concat(...mapResults[i]);
77310
+ }
77311
+ }
77312
+
77313
+ return callback(err, result);
77314
+ });
77315
+ }
77316
+ var concatLimit$1 = awaitify(concatLimit, 4);
77317
+
77318
+ /**
77319
+ * Applies `iteratee` to each item in `coll`, concatenating the results. Returns
77320
+ * the concatenated list. The `iteratee`s are called in parallel, and the
77321
+ * results are concatenated as they return. The results array will be returned in
77322
+ * the original order of `coll` passed to the `iteratee` function.
77323
+ *
77324
+ * @name concat
77325
+ * @static
77326
+ * @memberOf module:Collections
77327
+ * @method
77328
+ * @category Collection
77329
+ * @alias flatMap
77330
+ * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
77331
+ * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`,
77332
+ * which should use an array as its result. Invoked with (item, callback).
77333
+ * @param {Function} [callback] - A callback which is called after all the
77334
+ * `iteratee` functions have finished, or an error occurs. Results is an array
77335
+ * containing the concatenated results of the `iteratee` function. Invoked with
77336
+ * (err, results).
77337
+ * @returns A Promise, if no callback is passed
77338
+ * @example
77339
+ *
77340
+ * // dir1 is a directory that contains file1.txt, file2.txt
77341
+ * // dir2 is a directory that contains file3.txt, file4.txt
77342
+ * // dir3 is a directory that contains file5.txt
77343
+ * // dir4 does not exist
77344
+ *
77345
+ * let directoryList = ['dir1','dir2','dir3'];
77346
+ * let withMissingDirectoryList = ['dir1','dir2','dir3', 'dir4'];
77347
+ *
77348
+ * // Using callbacks
77349
+ * async.concat(directoryList, fs.readdir, function(err, results) {
77350
+ * if (err) {
77351
+ * console.log(err);
77352
+ * } else {
77353
+ * console.log(results);
77354
+ * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ]
77355
+ * }
77356
+ * });
77357
+ *
77358
+ * // Error Handling
77359
+ * async.concat(withMissingDirectoryList, fs.readdir, function(err, results) {
77360
+ * if (err) {
77361
+ * console.log(err);
77362
+ * // [ Error: ENOENT: no such file or directory ]
77363
+ * // since dir4 does not exist
77364
+ * } else {
77365
+ * console.log(results);
77366
+ * }
77367
+ * });
77368
+ *
77369
+ * // Using Promises
77370
+ * async.concat(directoryList, fs.readdir)
77371
+ * .then(results => {
77372
+ * console.log(results);
77373
+ * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ]
77374
+ * }).catch(err => {
77375
+ * console.log(err);
77376
+ * });
77377
+ *
77378
+ * // Error Handling
77379
+ * async.concat(withMissingDirectoryList, fs.readdir)
77380
+ * .then(results => {
77381
+ * console.log(results);
77382
+ * }).catch(err => {
77383
+ * console.log(err);
77384
+ * // [ Error: ENOENT: no such file or directory ]
77385
+ * // since dir4 does not exist
77386
+ * });
77387
+ *
77388
+ * // Using async/await
77389
+ * async () => {
77390
+ * try {
77391
+ * let results = await async.concat(directoryList, fs.readdir);
77392
+ * console.log(results);
77393
+ * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ]
77394
+ * } catch (err) {
77395
+ * console.log(err);
77396
+ * }
77397
+ * }
77398
+ *
77399
+ * // Error Handling
77400
+ * async () => {
77401
+ * try {
77402
+ * let results = await async.concat(withMissingDirectoryList, fs.readdir);
77403
+ * console.log(results);
77404
+ * } catch (err) {
77405
+ * console.log(err);
77406
+ * // [ Error: ENOENT: no such file or directory ]
77407
+ * // since dir4 does not exist
77408
+ * }
77409
+ * }
77410
+ *
77411
+ */
77412
+ function concat(coll, iteratee, callback) {
77413
+ return concatLimit$1(coll, Infinity, iteratee, callback)
77414
+ }
77415
+ awaitify(concat, 3);
77416
+
77417
+ /**
77418
+ * The same as [`concat`]{@link module:Collections.concat} but runs only a single async operation at a time.
77419
+ *
77420
+ * @name concatSeries
77421
+ * @static
77422
+ * @memberOf module:Collections
77423
+ * @method
77424
+ * @see [async.concat]{@link module:Collections.concat}
77425
+ * @category Collection
77426
+ * @alias flatMapSeries
77427
+ * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
77428
+ * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`.
77429
+ * The iteratee should complete with an array an array of results.
77430
+ * Invoked with (item, callback).
77431
+ * @param {Function} [callback] - A callback which is called after all the
77432
+ * `iteratee` functions have finished, or an error occurs. Results is an array
77433
+ * containing the concatenated results of the `iteratee` function. Invoked with
77434
+ * (err, results).
77435
+ * @returns A Promise, if no callback is passed
77436
+ */
77437
+ function concatSeries(coll, iteratee, callback) {
77438
+ return concatLimit$1(coll, 1, iteratee, callback)
77439
+ }
77440
+ awaitify(concatSeries, 3);
77441
+
77442
+ function _createTester(check, getResult) {
77443
+ return (eachfn, arr, _iteratee, cb) => {
77444
+ var testPassed = false;
77445
+ var testResult;
77446
+ const iteratee = wrapAsync(_iteratee);
77447
+ eachfn(arr, (value, _, callback) => {
77448
+ iteratee(value, (err, result) => {
77449
+ if (err || err === false) return callback(err);
77450
+
77451
+ if (check(result) && !testResult) {
77452
+ testPassed = true;
77453
+ testResult = getResult(true, value);
77454
+ return callback(null, breakLoop);
77455
+ }
77456
+ callback();
77457
+ });
77458
+ }, err => {
77459
+ if (err) return cb(err);
77460
+ cb(null, testPassed ? testResult : getResult(false));
77461
+ });
77462
+ };
77463
+ }
77464
+
77465
+ /**
77466
+ * Returns the first value in `coll` that passes an async truth test. The
77467
+ * `iteratee` is applied in parallel, meaning the first iteratee to return
77468
+ * `true` will fire the detect `callback` with that result. That means the
77469
+ * result might not be the first item in the original `coll` (in terms of order)
77470
+ * that passes the test.
77471
+
77472
+ * If order within the original `coll` is important, then look at
77473
+ * [`detectSeries`]{@link module:Collections.detectSeries}.
77474
+ *
77475
+ * @name detect
77476
+ * @static
77477
+ * @memberOf module:Collections
77478
+ * @method
77479
+ * @alias find
77480
+ * @category Collections
77481
+ * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
77482
+ * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`.
77483
+ * The iteratee must complete with a boolean value as its result.
77484
+ * Invoked with (item, callback).
77485
+ * @param {Function} [callback] - A callback which is called as soon as any
77486
+ * iteratee returns `true`, or after all the `iteratee` functions have finished.
77487
+ * Result will be the first item in the array that passes the truth test
77488
+ * (iteratee) or the value `undefined` if none passed. Invoked with
77489
+ * (err, result).
77490
+ * @returns {Promise} a promise, if a callback is omitted
77491
+ * @example
77492
+ *
77493
+ * // dir1 is a directory that contains file1.txt, file2.txt
77494
+ * // dir2 is a directory that contains file3.txt, file4.txt
77495
+ * // dir3 is a directory that contains file5.txt
77496
+ *
77497
+ * // asynchronous function that checks if a file exists
77498
+ * function fileExists(file, callback) {
77499
+ * fs.access(file, fs.constants.F_OK, (err) => {
77500
+ * callback(null, !err);
77501
+ * });
77502
+ * }
77503
+ *
77504
+ * async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists,
77505
+ * function(err, result) {
77506
+ * console.log(result);
77507
+ * // dir1/file1.txt
77508
+ * // result now equals the first file in the list that exists
77509
+ * }
77510
+ *);
77511
+ *
77512
+ * // Using Promises
77513
+ * async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists)
77514
+ * .then(result => {
77515
+ * console.log(result);
77516
+ * // dir1/file1.txt
77517
+ * // result now equals the first file in the list that exists
77518
+ * }).catch(err => {
77519
+ * console.log(err);
77520
+ * });
77521
+ *
77522
+ * // Using async/await
77523
+ * async () => {
77524
+ * try {
77525
+ * let result = await async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists);
77526
+ * console.log(result);
77527
+ * // dir1/file1.txt
77528
+ * // result now equals the file in the list that exists
77529
+ * }
77530
+ * catch (err) {
77531
+ * console.log(err);
77532
+ * }
77533
+ * }
77534
+ *
77535
+ */
77536
+ function detect(coll, iteratee, callback) {
77537
+ return _createTester(bool => bool, (res, item) => item)(eachOf$1, coll, iteratee, callback)
77538
+ }
77539
+ awaitify(detect, 3);
77540
+
77541
+ /**
77542
+ * The same as [`detect`]{@link module:Collections.detect} but runs a maximum of `limit` async operations at a
77543
+ * time.
77544
+ *
77545
+ * @name detectLimit
77546
+ * @static
77547
+ * @memberOf module:Collections
77548
+ * @method
77549
+ * @see [async.detect]{@link module:Collections.detect}
77550
+ * @alias findLimit
77551
+ * @category Collections
77552
+ * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
77553
+ * @param {number} limit - The maximum number of async operations at a time.
77554
+ * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`.
77555
+ * The iteratee must complete with a boolean value as its result.
77556
+ * Invoked with (item, callback).
77557
+ * @param {Function} [callback] - A callback which is called as soon as any
77558
+ * iteratee returns `true`, or after all the `iteratee` functions have finished.
77559
+ * Result will be the first item in the array that passes the truth test
77560
+ * (iteratee) or the value `undefined` if none passed. Invoked with
77561
+ * (err, result).
77562
+ * @returns {Promise} a promise, if a callback is omitted
77563
+ */
77564
+ function detectLimit(coll, limit, iteratee, callback) {
77565
+ return _createTester(bool => bool, (res, item) => item)(eachOfLimit$2(limit), coll, iteratee, callback)
77566
+ }
77567
+ awaitify(detectLimit, 4);
77568
+
77569
+ /**
77570
+ * The same as [`detect`]{@link module:Collections.detect} but runs only a single async operation at a time.
77571
+ *
77572
+ * @name detectSeries
77573
+ * @static
77574
+ * @memberOf module:Collections
77575
+ * @method
77576
+ * @see [async.detect]{@link module:Collections.detect}
77577
+ * @alias findSeries
77578
+ * @category Collections
77579
+ * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
77580
+ * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`.
77581
+ * The iteratee must complete with a boolean value as its result.
77582
+ * Invoked with (item, callback).
77583
+ * @param {Function} [callback] - A callback which is called as soon as any
77584
+ * iteratee returns `true`, or after all the `iteratee` functions have finished.
77585
+ * Result will be the first item in the array that passes the truth test
77586
+ * (iteratee) or the value `undefined` if none passed. Invoked with
77587
+ * (err, result).
77588
+ * @returns {Promise} a promise, if a callback is omitted
77589
+ */
77590
+ function detectSeries(coll, iteratee, callback) {
77591
+ return _createTester(bool => bool, (res, item) => item)(eachOfLimit$2(1), coll, iteratee, callback)
77592
+ }
77593
+
77594
+ awaitify(detectSeries, 3);
77595
+
77596
+ /**
77597
+ * The post-check version of [`whilst`]{@link module:ControlFlow.whilst}. To reflect the difference in
77598
+ * the order of operations, the arguments `test` and `iteratee` are switched.
77599
+ *
77600
+ * `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript.
77601
+ *
77602
+ * @name doWhilst
77603
+ * @static
77604
+ * @memberOf module:ControlFlow
77605
+ * @method
77606
+ * @see [async.whilst]{@link module:ControlFlow.whilst}
77607
+ * @category Control Flow
77608
+ * @param {AsyncFunction} iteratee - A function which is called each time `test`
77609
+ * passes. Invoked with (callback).
77610
+ * @param {AsyncFunction} test - asynchronous truth test to perform after each
77611
+ * execution of `iteratee`. Invoked with (...args, callback), where `...args` are the
77612
+ * non-error args from the previous callback of `iteratee`.
77613
+ * @param {Function} [callback] - A callback which is called after the test
77614
+ * function has failed and repeated execution of `iteratee` has stopped.
77615
+ * `callback` will be passed an error and any arguments passed to the final
77616
+ * `iteratee`'s callback. Invoked with (err, [results]);
77617
+ * @returns {Promise} a promise, if no callback is passed
77618
+ */
77619
+ function doWhilst(iteratee, test, callback) {
77620
+ callback = onlyOnce(callback);
77621
+ var _fn = wrapAsync(iteratee);
77622
+ var _test = wrapAsync(test);
77623
+ var results;
77624
+
77625
+ function next(err, ...args) {
77626
+ if (err) return callback(err);
77627
+ if (err === false) return;
77628
+ results = args;
77629
+ _test(...args, check);
77630
+ }
77631
+
77632
+ function check(err, truth) {
77633
+ if (err) return callback(err);
77634
+ if (err === false) return;
77635
+ if (!truth) return callback(null, ...results);
77636
+ _fn(next);
77637
+ }
77638
+
77639
+ return check(null, true);
77640
+ }
77641
+
77642
+ awaitify(doWhilst, 3);
77643
+
77644
+ function _withoutIndex(iteratee) {
77645
+ return (value, index, callback) => iteratee(value, callback);
77646
+ }
77647
+
77648
+ /**
77649
+ * Applies the function `iteratee` to each item in `coll`, in parallel.
77650
+ * The `iteratee` is called with an item from the list, and a callback for when
77651
+ * it has finished. If the `iteratee` passes an error to its `callback`, the
77652
+ * main `callback` (for the `each` function) is immediately called with the
77653
+ * error.
77654
+ *
77655
+ * Note, that since this function applies `iteratee` to each item in parallel,
77656
+ * there is no guarantee that the iteratee functions will complete in order.
77657
+ *
77658
+ * @name each
77659
+ * @static
77660
+ * @memberOf module:Collections
77661
+ * @method
77662
+ * @alias forEach
77663
+ * @category Collection
77664
+ * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
77665
+ * @param {AsyncFunction} iteratee - An async function to apply to
77666
+ * each item in `coll`. Invoked with (item, callback).
77667
+ * The array index is not passed to the iteratee.
77668
+ * If you need the index, use `eachOf`.
77669
+ * @param {Function} [callback] - A callback which is called when all
77670
+ * `iteratee` functions have finished, or an error occurs. Invoked with (err).
77671
+ * @returns {Promise} a promise, if a callback is omitted
77672
+ * @example
77673
+ *
77674
+ * // dir1 is a directory that contains file1.txt, file2.txt
77675
+ * // dir2 is a directory that contains file3.txt, file4.txt
77676
+ * // dir3 is a directory that contains file5.txt
77677
+ * // dir4 does not exist
77678
+ *
77679
+ * const fileList = [ 'dir1/file2.txt', 'dir2/file3.txt', 'dir/file5.txt'];
77680
+ * const withMissingFileList = ['dir1/file1.txt', 'dir4/file2.txt'];
77681
+ *
77682
+ * // asynchronous function that deletes a file
77683
+ * const deleteFile = function(file, callback) {
77684
+ * fs.unlink(file, callback);
77685
+ * };
77686
+ *
77687
+ * // Using callbacks
77688
+ * async.each(fileList, deleteFile, function(err) {
77689
+ * if( err ) {
77690
+ * console.log(err);
77691
+ * } else {
77692
+ * console.log('All files have been deleted successfully');
77693
+ * }
77694
+ * });
77695
+ *
77696
+ * // Error Handling
77697
+ * async.each(withMissingFileList, deleteFile, function(err){
77698
+ * console.log(err);
77699
+ * // [ Error: ENOENT: no such file or directory ]
77700
+ * // since dir4/file2.txt does not exist
77701
+ * // dir1/file1.txt could have been deleted
77702
+ * });
77703
+ *
77704
+ * // Using Promises
77705
+ * async.each(fileList, deleteFile)
77706
+ * .then( () => {
77707
+ * console.log('All files have been deleted successfully');
77708
+ * }).catch( err => {
77709
+ * console.log(err);
77710
+ * });
77711
+ *
77712
+ * // Error Handling
77713
+ * async.each(fileList, deleteFile)
77714
+ * .then( () => {
77715
+ * console.log('All files have been deleted successfully');
77716
+ * }).catch( err => {
77717
+ * console.log(err);
77718
+ * // [ Error: ENOENT: no such file or directory ]
77719
+ * // since dir4/file2.txt does not exist
77720
+ * // dir1/file1.txt could have been deleted
77721
+ * });
77722
+ *
77723
+ * // Using async/await
77724
+ * async () => {
77725
+ * try {
77726
+ * await async.each(files, deleteFile);
77727
+ * }
77728
+ * catch (err) {
77729
+ * console.log(err);
77730
+ * }
77731
+ * }
77732
+ *
77733
+ * // Error Handling
77734
+ * async () => {
77735
+ * try {
77736
+ * await async.each(withMissingFileList, deleteFile);
77737
+ * }
77738
+ * catch (err) {
77739
+ * console.log(err);
77740
+ * // [ Error: ENOENT: no such file or directory ]
77741
+ * // since dir4/file2.txt does not exist
77742
+ * // dir1/file1.txt could have been deleted
77743
+ * }
77744
+ * }
77745
+ *
77746
+ */
77747
+ function eachLimit$2(coll, iteratee, callback) {
77748
+ return eachOf$1(coll, _withoutIndex(wrapAsync(iteratee)), callback);
77749
+ }
77750
+
77751
+ awaitify(eachLimit$2, 3);
77752
+
77753
+ /**
77754
+ * The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time.
77755
+ *
77756
+ * @name eachLimit
77757
+ * @static
77758
+ * @memberOf module:Collections
77759
+ * @method
77760
+ * @see [async.each]{@link module:Collections.each}
77761
+ * @alias forEachLimit
77762
+ * @category Collection
77763
+ * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
77764
+ * @param {number} limit - The maximum number of async operations at a time.
77765
+ * @param {AsyncFunction} iteratee - An async function to apply to each item in
77766
+ * `coll`.
77767
+ * The array index is not passed to the iteratee.
77768
+ * If you need the index, use `eachOfLimit`.
77769
+ * Invoked with (item, callback).
77770
+ * @param {Function} [callback] - A callback which is called when all
77771
+ * `iteratee` functions have finished, or an error occurs. Invoked with (err).
77772
+ * @returns {Promise} a promise, if a callback is omitted
77773
+ */
77774
+ function eachLimit(coll, limit, iteratee, callback) {
77775
+ return eachOfLimit$2(limit)(coll, _withoutIndex(wrapAsync(iteratee)), callback);
77776
+ }
77777
+ var eachLimit$1 = awaitify(eachLimit, 4);
77778
+
77779
+ /**
77780
+ * The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time.
77781
+ *
77782
+ * Note, that unlike [`each`]{@link module:Collections.each}, this function applies iteratee to each item
77783
+ * in series and therefore the iteratee functions will complete in order.
77784
+
77785
+ * @name eachSeries
77786
+ * @static
77787
+ * @memberOf module:Collections
77788
+ * @method
77789
+ * @see [async.each]{@link module:Collections.each}
77790
+ * @alias forEachSeries
77791
+ * @category Collection
77792
+ * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
77793
+ * @param {AsyncFunction} iteratee - An async function to apply to each
77794
+ * item in `coll`.
77795
+ * The array index is not passed to the iteratee.
77796
+ * If you need the index, use `eachOfSeries`.
77797
+ * Invoked with (item, callback).
77798
+ * @param {Function} [callback] - A callback which is called when all
77799
+ * `iteratee` functions have finished, or an error occurs. Invoked with (err).
77800
+ * @returns {Promise} a promise, if a callback is omitted
77801
+ */
77802
+ function eachSeries(coll, iteratee, callback) {
77803
+ return eachLimit$1(coll, 1, iteratee, callback)
77804
+ }
77805
+ var eachSeries$1 = awaitify(eachSeries, 3);
77806
+
77807
+ /**
77808
+ * Wrap an async function and ensure it calls its callback on a later tick of
77809
+ * the event loop. If the function already calls its callback on a next tick,
77810
+ * no extra deferral is added. This is useful for preventing stack overflows
77811
+ * (`RangeError: Maximum call stack size exceeded`) and generally keeping
77812
+ * [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony)
77813
+ * contained. ES2017 `async` functions are returned as-is -- they are immune
77814
+ * to Zalgo's corrupting influences, as they always resolve on a later tick.
77815
+ *
77816
+ * @name ensureAsync
77817
+ * @static
77818
+ * @memberOf module:Utils
77819
+ * @method
77820
+ * @category Util
77821
+ * @param {AsyncFunction} fn - an async function, one that expects a node-style
77822
+ * callback as its last argument.
77823
+ * @returns {AsyncFunction} Returns a wrapped function with the exact same call
77824
+ * signature as the function passed in.
77825
+ * @example
77826
+ *
77827
+ * function sometimesAsync(arg, callback) {
77828
+ * if (cache[arg]) {
77829
+ * return callback(null, cache[arg]); // this would be synchronous!!
77830
+ * } else {
77831
+ * doSomeIO(arg, callback); // this IO would be asynchronous
77832
+ * }
77833
+ * }
77834
+ *
77835
+ * // this has a risk of stack overflows if many results are cached in a row
77836
+ * async.mapSeries(args, sometimesAsync, done);
77837
+ *
77838
+ * // this will defer sometimesAsync's callback if necessary,
77839
+ * // preventing stack overflows
77840
+ * async.mapSeries(args, async.ensureAsync(sometimesAsync), done);
77841
+ */
77842
+ function ensureAsync(fn) {
77843
+ if (isAsync(fn)) return fn;
77844
+ return function (...args/*, callback*/) {
77845
+ var callback = args.pop();
77846
+ var sync = true;
77847
+ args.push((...innerArgs) => {
77848
+ if (sync) {
77849
+ setImmediate$1(() => callback(...innerArgs));
77850
+ } else {
77851
+ callback(...innerArgs);
77852
+ }
77853
+ });
77854
+ fn.apply(this, args);
77855
+ sync = false;
77856
+ };
77857
+ }
77858
+
77859
+ /**
77860
+ * Returns `true` if every element in `coll` satisfies an async test. If any
77861
+ * iteratee call returns `false`, the main `callback` is immediately called.
77862
+ *
77863
+ * @name every
77864
+ * @static
77865
+ * @memberOf module:Collections
77866
+ * @method
77867
+ * @alias all
77868
+ * @category Collection
77869
+ * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
77870
+ * @param {AsyncFunction} iteratee - An async truth test to apply to each item
77871
+ * in the collection in parallel.
77872
+ * The iteratee must complete with a boolean result value.
77873
+ * Invoked with (item, callback).
77874
+ * @param {Function} [callback] - A callback which is called after all the
77875
+ * `iteratee` functions have finished. Result will be either `true` or `false`
77876
+ * depending on the values of the async tests. Invoked with (err, result).
77877
+ * @returns {Promise} a promise, if no callback provided
77878
+ * @example
77879
+ *
77880
+ * // dir1 is a directory that contains file1.txt, file2.txt
77881
+ * // dir2 is a directory that contains file3.txt, file4.txt
77882
+ * // dir3 is a directory that contains file5.txt
77883
+ * // dir4 does not exist
77884
+ *
77885
+ * const fileList = ['dir1/file1.txt','dir2/file3.txt','dir3/file5.txt'];
77886
+ * const withMissingFileList = ['file1.txt','file2.txt','file4.txt'];
77887
+ *
77888
+ * // asynchronous function that checks if a file exists
77889
+ * function fileExists(file, callback) {
77890
+ * fs.access(file, fs.constants.F_OK, (err) => {
77891
+ * callback(null, !err);
77892
+ * });
77893
+ * }
77894
+ *
77895
+ * // Using callbacks
77896
+ * async.every(fileList, fileExists, function(err, result) {
77897
+ * console.log(result);
77898
+ * // true
77899
+ * // result is true since every file exists
77900
+ * });
77901
+ *
77902
+ * async.every(withMissingFileList, fileExists, function(err, result) {
77903
+ * console.log(result);
77904
+ * // false
77905
+ * // result is false since NOT every file exists
77906
+ * });
77907
+ *
77908
+ * // Using Promises
77909
+ * async.every(fileList, fileExists)
77910
+ * .then( result => {
77911
+ * console.log(result);
77912
+ * // true
77913
+ * // result is true since every file exists
77914
+ * }).catch( err => {
77915
+ * console.log(err);
77916
+ * });
77917
+ *
77918
+ * async.every(withMissingFileList, fileExists)
77919
+ * .then( result => {
77920
+ * console.log(result);
77921
+ * // false
77922
+ * // result is false since NOT every file exists
77923
+ * }).catch( err => {
77924
+ * console.log(err);
77925
+ * });
77926
+ *
77927
+ * // Using async/await
77928
+ * async () => {
77929
+ * try {
77930
+ * let result = await async.every(fileList, fileExists);
77931
+ * console.log(result);
77932
+ * // true
77933
+ * // result is true since every file exists
77934
+ * }
77935
+ * catch (err) {
77936
+ * console.log(err);
77937
+ * }
77938
+ * }
77939
+ *
77940
+ * async () => {
77941
+ * try {
77942
+ * let result = await async.every(withMissingFileList, fileExists);
77943
+ * console.log(result);
77944
+ * // false
77945
+ * // result is false since NOT every file exists
77946
+ * }
77947
+ * catch (err) {
77948
+ * console.log(err);
77949
+ * }
77950
+ * }
77951
+ *
77952
+ */
77953
+ function every(coll, iteratee, callback) {
77954
+ return _createTester(bool => !bool, res => !res)(eachOf$1, coll, iteratee, callback)
77955
+ }
77956
+ awaitify(every, 3);
77957
+
77958
+ /**
77959
+ * The same as [`every`]{@link module:Collections.every} but runs a maximum of `limit` async operations at a time.
77960
+ *
77961
+ * @name everyLimit
77962
+ * @static
77963
+ * @memberOf module:Collections
77964
+ * @method
77965
+ * @see [async.every]{@link module:Collections.every}
77966
+ * @alias allLimit
77967
+ * @category Collection
77968
+ * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
77969
+ * @param {number} limit - The maximum number of async operations at a time.
77970
+ * @param {AsyncFunction} iteratee - An async truth test to apply to each item
77971
+ * in the collection in parallel.
77972
+ * The iteratee must complete with a boolean result value.
77973
+ * Invoked with (item, callback).
77974
+ * @param {Function} [callback] - A callback which is called after all the
77975
+ * `iteratee` functions have finished. Result will be either `true` or `false`
77976
+ * depending on the values of the async tests. Invoked with (err, result).
77977
+ * @returns {Promise} a promise, if no callback provided
77978
+ */
77979
+ function everyLimit(coll, limit, iteratee, callback) {
77980
+ return _createTester(bool => !bool, res => !res)(eachOfLimit$2(limit), coll, iteratee, callback)
77981
+ }
77982
+ awaitify(everyLimit, 4);
77983
+
77984
+ /**
77985
+ * The same as [`every`]{@link module:Collections.every} but runs only a single async operation at a time.
77986
+ *
77987
+ * @name everySeries
77988
+ * @static
77989
+ * @memberOf module:Collections
77990
+ * @method
77991
+ * @see [async.every]{@link module:Collections.every}
77992
+ * @alias allSeries
77993
+ * @category Collection
77994
+ * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
77995
+ * @param {AsyncFunction} iteratee - An async truth test to apply to each item
77996
+ * in the collection in series.
77997
+ * The iteratee must complete with a boolean result value.
77998
+ * Invoked with (item, callback).
77999
+ * @param {Function} [callback] - A callback which is called after all the
78000
+ * `iteratee` functions have finished. Result will be either `true` or `false`
78001
+ * depending on the values of the async tests. Invoked with (err, result).
78002
+ * @returns {Promise} a promise, if no callback provided
78003
+ */
78004
+ function everySeries(coll, iteratee, callback) {
78005
+ return _createTester(bool => !bool, res => !res)(eachOfSeries$1, coll, iteratee, callback)
78006
+ }
78007
+ awaitify(everySeries, 3);
78008
+
78009
+ function filterArray(eachfn, arr, iteratee, callback) {
78010
+ var truthValues = new Array(arr.length);
78011
+ eachfn(arr, (x, index, iterCb) => {
78012
+ iteratee(x, (err, v) => {
78013
+ truthValues[index] = !!v;
78014
+ iterCb(err);
78015
+ });
78016
+ }, err => {
78017
+ if (err) return callback(err);
78018
+ var results = [];
78019
+ for (var i = 0; i < arr.length; i++) {
78020
+ if (truthValues[i]) results.push(arr[i]);
78021
+ }
78022
+ callback(null, results);
78023
+ });
78024
+ }
78025
+
78026
+ function filterGeneric(eachfn, coll, iteratee, callback) {
78027
+ var results = [];
78028
+ eachfn(coll, (x, index, iterCb) => {
78029
+ iteratee(x, (err, v) => {
78030
+ if (err) return iterCb(err);
78031
+ if (v) {
78032
+ results.push({index, value: x});
78033
+ }
78034
+ iterCb(err);
78035
+ });
78036
+ }, err => {
78037
+ if (err) return callback(err);
78038
+ callback(null, results
78039
+ .sort((a, b) => a.index - b.index)
78040
+ .map(v => v.value));
78041
+ });
78042
+ }
78043
+
78044
+ function _filter(eachfn, coll, iteratee, callback) {
78045
+ var filter = isArrayLike(coll) ? filterArray : filterGeneric;
78046
+ return filter(eachfn, coll, wrapAsync(iteratee), callback);
78047
+ }
78048
+
78049
+ /**
78050
+ * Returns a new array of all the values in `coll` which pass an async truth
78051
+ * test. This operation is performed in parallel, but the results array will be
78052
+ * in the same order as the original.
78053
+ *
78054
+ * @name filter
78055
+ * @static
78056
+ * @memberOf module:Collections
78057
+ * @method
78058
+ * @alias select
78059
+ * @category Collection
78060
+ * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
78061
+ * @param {Function} iteratee - A truth test to apply to each item in `coll`.
78062
+ * The `iteratee` is passed a `callback(err, truthValue)`, which must be called
78063
+ * with a boolean argument once it has completed. Invoked with (item, callback).
78064
+ * @param {Function} [callback] - A callback which is called after all the
78065
+ * `iteratee` functions have finished. Invoked with (err, results).
78066
+ * @returns {Promise} a promise, if no callback provided
78067
+ * @example
78068
+ *
78069
+ * // dir1 is a directory that contains file1.txt, file2.txt
78070
+ * // dir2 is a directory that contains file3.txt, file4.txt
78071
+ * // dir3 is a directory that contains file5.txt
78072
+ *
78073
+ * const files = ['dir1/file1.txt','dir2/file3.txt','dir3/file6.txt'];
78074
+ *
78075
+ * // asynchronous function that checks if a file exists
78076
+ * function fileExists(file, callback) {
78077
+ * fs.access(file, fs.constants.F_OK, (err) => {
78078
+ * callback(null, !err);
78079
+ * });
78080
+ * }
78081
+ *
78082
+ * // Using callbacks
78083
+ * async.filter(files, fileExists, function(err, results) {
78084
+ * if(err) {
78085
+ * console.log(err);
78086
+ * } else {
78087
+ * console.log(results);
78088
+ * // [ 'dir1/file1.txt', 'dir2/file3.txt' ]
78089
+ * // results is now an array of the existing files
78090
+ * }
78091
+ * });
78092
+ *
78093
+ * // Using Promises
78094
+ * async.filter(files, fileExists)
78095
+ * .then(results => {
78096
+ * console.log(results);
78097
+ * // [ 'dir1/file1.txt', 'dir2/file3.txt' ]
78098
+ * // results is now an array of the existing files
78099
+ * }).catch(err => {
78100
+ * console.log(err);
78101
+ * });
78102
+ *
78103
+ * // Using async/await
78104
+ * async () => {
78105
+ * try {
78106
+ * let results = await async.filter(files, fileExists);
78107
+ * console.log(results);
78108
+ * // [ 'dir1/file1.txt', 'dir2/file3.txt' ]
78109
+ * // results is now an array of the existing files
78110
+ * }
78111
+ * catch (err) {
78112
+ * console.log(err);
78113
+ * }
78114
+ * }
78115
+ *
78116
+ */
78117
+ function filter (coll, iteratee, callback) {
78118
+ return _filter(eachOf$1, coll, iteratee, callback)
78119
+ }
78120
+ awaitify(filter, 3);
78121
+
78122
+ /**
78123
+ * The same as [`filter`]{@link module:Collections.filter} but runs a maximum of `limit` async operations at a
78124
+ * time.
78125
+ *
78126
+ * @name filterLimit
78127
+ * @static
78128
+ * @memberOf module:Collections
78129
+ * @method
78130
+ * @see [async.filter]{@link module:Collections.filter}
78131
+ * @alias selectLimit
78132
+ * @category Collection
78133
+ * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
78134
+ * @param {number} limit - The maximum number of async operations at a time.
78135
+ * @param {Function} iteratee - A truth test to apply to each item in `coll`.
78136
+ * The `iteratee` is passed a `callback(err, truthValue)`, which must be called
78137
+ * with a boolean argument once it has completed. Invoked with (item, callback).
78138
+ * @param {Function} [callback] - A callback which is called after all the
78139
+ * `iteratee` functions have finished. Invoked with (err, results).
78140
+ * @returns {Promise} a promise, if no callback provided
78141
+ */
78142
+ function filterLimit (coll, limit, iteratee, callback) {
78143
+ return _filter(eachOfLimit$2(limit), coll, iteratee, callback)
78144
+ }
78145
+ awaitify(filterLimit, 4);
78146
+
78147
+ /**
78148
+ * The same as [`filter`]{@link module:Collections.filter} but runs only a single async operation at a time.
78149
+ *
78150
+ * @name filterSeries
78151
+ * @static
78152
+ * @memberOf module:Collections
78153
+ * @method
78154
+ * @see [async.filter]{@link module:Collections.filter}
78155
+ * @alias selectSeries
78156
+ * @category Collection
78157
+ * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
78158
+ * @param {Function} iteratee - A truth test to apply to each item in `coll`.
78159
+ * The `iteratee` is passed a `callback(err, truthValue)`, which must be called
78160
+ * with a boolean argument once it has completed. Invoked with (item, callback).
78161
+ * @param {Function} [callback] - A callback which is called after all the
78162
+ * `iteratee` functions have finished. Invoked with (err, results)
78163
+ * @returns {Promise} a promise, if no callback provided
78164
+ */
78165
+ function filterSeries (coll, iteratee, callback) {
78166
+ return _filter(eachOfSeries$1, coll, iteratee, callback)
78167
+ }
78168
+ awaitify(filterSeries, 3);
78169
+
78170
+ /**
78171
+ * Calls the asynchronous function `fn` with a callback parameter that allows it
78172
+ * to call itself again, in series, indefinitely.
78173
+
78174
+ * If an error is passed to the callback then `errback` is called with the
78175
+ * error, and execution stops, otherwise it will never be called.
78176
+ *
78177
+ * @name forever
78178
+ * @static
78179
+ * @memberOf module:ControlFlow
78180
+ * @method
78181
+ * @category Control Flow
78182
+ * @param {AsyncFunction} fn - an async function to call repeatedly.
78183
+ * Invoked with (next).
78184
+ * @param {Function} [errback] - when `fn` passes an error to it's callback,
78185
+ * this function will be called, and execution stops. Invoked with (err).
78186
+ * @returns {Promise} a promise that rejects if an error occurs and an errback
78187
+ * is not passed
78188
+ * @example
78189
+ *
78190
+ * async.forever(
78191
+ * function(next) {
78192
+ * // next is suitable for passing to things that need a callback(err [, whatever]);
78193
+ * // it will result in this function being called again.
78194
+ * },
78195
+ * function(err) {
78196
+ * // if next is called with a value in its first parameter, it will appear
78197
+ * // in here as 'err', and execution will stop.
78198
+ * }
78199
+ * );
78200
+ */
78201
+ function forever(fn, errback) {
78202
+ var done = onlyOnce(errback);
78203
+ var task = wrapAsync(ensureAsync(fn));
78204
+
78205
+ function next(err) {
78206
+ if (err) return done(err);
78207
+ if (err === false) return;
78208
+ task(next);
78209
+ }
78210
+ return next();
78211
+ }
78212
+ awaitify(forever, 2);
78213
+
78214
+ /**
78215
+ * The same as [`groupBy`]{@link module:Collections.groupBy} but runs a maximum of `limit` async operations at a time.
78216
+ *
78217
+ * @name groupByLimit
78218
+ * @static
78219
+ * @memberOf module:Collections
78220
+ * @method
78221
+ * @see [async.groupBy]{@link module:Collections.groupBy}
78222
+ * @category Collection
78223
+ * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
78224
+ * @param {number} limit - The maximum number of async operations at a time.
78225
+ * @param {AsyncFunction} iteratee - An async function to apply to each item in
78226
+ * `coll`.
78227
+ * The iteratee should complete with a `key` to group the value under.
78228
+ * Invoked with (value, callback).
78229
+ * @param {Function} [callback] - A callback which is called when all `iteratee`
78230
+ * functions have finished, or an error occurs. Result is an `Object` whoses
78231
+ * properties are arrays of values which returned the corresponding key.
78232
+ * @returns {Promise} a promise, if no callback is passed
78233
+ */
78234
+ function groupByLimit(coll, limit, iteratee, callback) {
78235
+ var _iteratee = wrapAsync(iteratee);
78236
+ return mapLimit$1(coll, limit, (val, iterCb) => {
78237
+ _iteratee(val, (err, key) => {
78238
+ if (err) return iterCb(err);
78239
+ return iterCb(err, {key, val});
78240
+ });
78241
+ }, (err, mapResults) => {
78242
+ var result = {};
78243
+ // from MDN, handle object having an `hasOwnProperty` prop
78244
+ var {hasOwnProperty} = Object.prototype;
78245
+
78246
+ for (var i = 0; i < mapResults.length; i++) {
78247
+ if (mapResults[i]) {
78248
+ var {key} = mapResults[i];
78249
+ var {val} = mapResults[i];
78250
+
78251
+ if (hasOwnProperty.call(result, key)) {
78252
+ result[key].push(val);
78253
+ } else {
78254
+ result[key] = [val];
78255
+ }
78256
+ }
78257
+ }
78258
+
78259
+ return callback(err, result);
78260
+ });
78261
+ }
78262
+
78263
+ awaitify(groupByLimit, 4);
78264
+
78265
+ /**
78266
+ * The same as [`mapValues`]{@link module:Collections.mapValues} but runs a maximum of `limit` async operations at a
78267
+ * time.
78268
+ *
78269
+ * @name mapValuesLimit
78270
+ * @static
78271
+ * @memberOf module:Collections
78272
+ * @method
78273
+ * @see [async.mapValues]{@link module:Collections.mapValues}
78274
+ * @category Collection
78275
+ * @param {Object} obj - A collection to iterate over.
78276
+ * @param {number} limit - The maximum number of async operations at a time.
78277
+ * @param {AsyncFunction} iteratee - A function to apply to each value and key
78278
+ * in `coll`.
78279
+ * The iteratee should complete with the transformed value as its result.
78280
+ * Invoked with (value, key, callback).
78281
+ * @param {Function} [callback] - A callback which is called when all `iteratee`
78282
+ * functions have finished, or an error occurs. `result` is a new object consisting
78283
+ * of each key from `obj`, with each transformed value on the right-hand side.
78284
+ * Invoked with (err, result).
78285
+ * @returns {Promise} a promise, if no callback is passed
78286
+ */
78287
+ function mapValuesLimit(obj, limit, iteratee, callback) {
78288
+ callback = once(callback);
78289
+ var newObj = {};
78290
+ var _iteratee = wrapAsync(iteratee);
78291
+ return eachOfLimit$2(limit)(obj, (val, key, next) => {
78292
+ _iteratee(val, key, (err, result) => {
78293
+ if (err) return next(err);
78294
+ newObj[key] = result;
78295
+ next(err);
78296
+ });
78297
+ }, err => callback(err, newObj));
78298
+ }
78299
+
78300
+ awaitify(mapValuesLimit, 4);
78301
+
78302
+ if (hasNextTick) {
78303
+ process.nextTick;
78304
+ } else if (hasSetImmediate) {
78305
+ setImmediate;
78306
+ } else ;
78307
+
78308
+ awaitify((eachfn, tasks, callback) => {
78309
+ var results = isArrayLike(tasks) ? [] : {};
78310
+
78311
+ eachfn(tasks, (task, key, taskCb) => {
78312
+ wrapAsync(task)((err, ...result) => {
78313
+ if (result.length < 2) {
78314
+ [result] = result;
78315
+ }
78316
+ results[key] = result;
78317
+ taskCb(err);
78318
+ });
78319
+ }, err => callback(err, results));
78320
+ }, 3);
78321
+
78322
+ /**
78323
+ * Runs the `tasks` array of functions in parallel, without waiting until the
78324
+ * previous function has completed. Once any of the `tasks` complete or pass an
78325
+ * error to its callback, the main `callback` is immediately called. It's
78326
+ * equivalent to `Promise.race()`.
78327
+ *
78328
+ * @name race
78329
+ * @static
78330
+ * @memberOf module:ControlFlow
78331
+ * @method
78332
+ * @category Control Flow
78333
+ * @param {Array} tasks - An array containing [async functions]{@link AsyncFunction}
78334
+ * to run. Each function can complete with an optional `result` value.
78335
+ * @param {Function} callback - A callback to run once any of the functions have
78336
+ * completed. This function gets an error or result from the first function that
78337
+ * completed. Invoked with (err, result).
78338
+ * @returns {Promise} a promise, if a callback is omitted
78339
+ * @example
78340
+ *
78341
+ * async.race([
78342
+ * function(callback) {
78343
+ * setTimeout(function() {
78344
+ * callback(null, 'one');
78345
+ * }, 200);
78346
+ * },
78347
+ * function(callback) {
78348
+ * setTimeout(function() {
78349
+ * callback(null, 'two');
78350
+ * }, 100);
78351
+ * }
78352
+ * ],
78353
+ * // main callback
78354
+ * function(err, result) {
78355
+ * // the result will be equal to 'two' as it finishes earlier
78356
+ * });
78357
+ */
78358
+ function race(tasks, callback) {
78359
+ callback = once(callback);
78360
+ if (!Array.isArray(tasks)) return callback(new TypeError('First argument to race must be an array of functions'));
78361
+ if (!tasks.length) return callback();
78362
+ for (var i = 0, l = tasks.length; i < l; i++) {
78363
+ wrapAsync(tasks[i])(callback);
78364
+ }
78365
+ }
78366
+
78367
+ awaitify(race, 2);
78368
+
78369
+ function reject$2(eachfn, arr, _iteratee, callback) {
78370
+ const iteratee = wrapAsync(_iteratee);
78371
+ return _filter(eachfn, arr, (value, cb) => {
78372
+ iteratee(value, (err, v) => {
78373
+ cb(err, !v);
78374
+ });
78375
+ }, callback);
78376
+ }
78377
+
78378
+ /**
78379
+ * The opposite of [`filter`]{@link module:Collections.filter}. Removes values that pass an `async` truth test.
78380
+ *
78381
+ * @name reject
78382
+ * @static
78383
+ * @memberOf module:Collections
78384
+ * @method
78385
+ * @see [async.filter]{@link module:Collections.filter}
78386
+ * @category Collection
78387
+ * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
78388
+ * @param {Function} iteratee - An async truth test to apply to each item in
78389
+ * `coll`.
78390
+ * The should complete with a boolean value as its `result`.
78391
+ * Invoked with (item, callback).
78392
+ * @param {Function} [callback] - A callback which is called after all the
78393
+ * `iteratee` functions have finished. Invoked with (err, results).
78394
+ * @returns {Promise} a promise, if no callback is passed
78395
+ * @example
78396
+ *
78397
+ * // dir1 is a directory that contains file1.txt, file2.txt
78398
+ * // dir2 is a directory that contains file3.txt, file4.txt
78399
+ * // dir3 is a directory that contains file5.txt
78400
+ *
78401
+ * const fileList = ['dir1/file1.txt','dir2/file3.txt','dir3/file6.txt'];
78402
+ *
78403
+ * // asynchronous function that checks if a file exists
78404
+ * function fileExists(file, callback) {
78405
+ * fs.access(file, fs.constants.F_OK, (err) => {
78406
+ * callback(null, !err);
78407
+ * });
78408
+ * }
78409
+ *
78410
+ * // Using callbacks
78411
+ * async.reject(fileList, fileExists, function(err, results) {
78412
+ * // [ 'dir3/file6.txt' ]
78413
+ * // results now equals an array of the non-existing files
78414
+ * });
78415
+ *
78416
+ * // Using Promises
78417
+ * async.reject(fileList, fileExists)
78418
+ * .then( results => {
78419
+ * console.log(results);
78420
+ * // [ 'dir3/file6.txt' ]
78421
+ * // results now equals an array of the non-existing files
78422
+ * }).catch( err => {
78423
+ * console.log(err);
78424
+ * });
78425
+ *
78426
+ * // Using async/await
78427
+ * async () => {
78428
+ * try {
78429
+ * let results = await async.reject(fileList, fileExists);
78430
+ * console.log(results);
78431
+ * // [ 'dir3/file6.txt' ]
78432
+ * // results now equals an array of the non-existing files
78433
+ * }
78434
+ * catch (err) {
78435
+ * console.log(err);
78436
+ * }
78437
+ * }
78438
+ *
78439
+ */
78440
+ function reject (coll, iteratee, callback) {
78441
+ return reject$2(eachOf$1, coll, iteratee, callback)
78442
+ }
78443
+ awaitify(reject, 3);
78444
+
78445
+ /**
78446
+ * The same as [`reject`]{@link module:Collections.reject} but runs a maximum of `limit` async operations at a
78447
+ * time.
78448
+ *
78449
+ * @name rejectLimit
78450
+ * @static
78451
+ * @memberOf module:Collections
78452
+ * @method
78453
+ * @see [async.reject]{@link module:Collections.reject}
78454
+ * @category Collection
78455
+ * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
78456
+ * @param {number} limit - The maximum number of async operations at a time.
78457
+ * @param {Function} iteratee - An async truth test to apply to each item in
78458
+ * `coll`.
78459
+ * The should complete with a boolean value as its `result`.
78460
+ * Invoked with (item, callback).
78461
+ * @param {Function} [callback] - A callback which is called after all the
78462
+ * `iteratee` functions have finished. Invoked with (err, results).
78463
+ * @returns {Promise} a promise, if no callback is passed
78464
+ */
78465
+ function rejectLimit (coll, limit, iteratee, callback) {
78466
+ return reject$2(eachOfLimit$2(limit), coll, iteratee, callback)
78467
+ }
78468
+ awaitify(rejectLimit, 4);
78469
+
78470
+ /**
78471
+ * The same as [`reject`]{@link module:Collections.reject} but runs only a single async operation at a time.
78472
+ *
78473
+ * @name rejectSeries
78474
+ * @static
78475
+ * @memberOf module:Collections
78476
+ * @method
78477
+ * @see [async.reject]{@link module:Collections.reject}
78478
+ * @category Collection
78479
+ * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
78480
+ * @param {Function} iteratee - An async truth test to apply to each item in
78481
+ * `coll`.
78482
+ * The should complete with a boolean value as its `result`.
78483
+ * Invoked with (item, callback).
78484
+ * @param {Function} [callback] - A callback which is called after all the
78485
+ * `iteratee` functions have finished. Invoked with (err, results).
78486
+ * @returns {Promise} a promise, if no callback is passed
78487
+ */
78488
+ function rejectSeries (coll, iteratee, callback) {
78489
+ return reject$2(eachOfSeries$1, coll, iteratee, callback)
78490
+ }
78491
+ awaitify(rejectSeries, 3);
78492
+
78493
+ /**
78494
+ * Returns `true` if at least one element in the `coll` satisfies an async test.
78495
+ * If any iteratee call returns `true`, the main `callback` is immediately
78496
+ * called.
78497
+ *
78498
+ * @name some
78499
+ * @static
78500
+ * @memberOf module:Collections
78501
+ * @method
78502
+ * @alias any
78503
+ * @category Collection
78504
+ * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
78505
+ * @param {AsyncFunction} iteratee - An async truth test to apply to each item
78506
+ * in the collections in parallel.
78507
+ * The iteratee should complete with a boolean `result` value.
78508
+ * Invoked with (item, callback).
78509
+ * @param {Function} [callback] - A callback which is called as soon as any
78510
+ * iteratee returns `true`, or after all the iteratee functions have finished.
78511
+ * Result will be either `true` or `false` depending on the values of the async
78512
+ * tests. Invoked with (err, result).
78513
+ * @returns {Promise} a promise, if no callback provided
78514
+ * @example
78515
+ *
78516
+ * // dir1 is a directory that contains file1.txt, file2.txt
78517
+ * // dir2 is a directory that contains file3.txt, file4.txt
78518
+ * // dir3 is a directory that contains file5.txt
78519
+ * // dir4 does not exist
78520
+ *
78521
+ * // asynchronous function that checks if a file exists
78522
+ * function fileExists(file, callback) {
78523
+ * fs.access(file, fs.constants.F_OK, (err) => {
78524
+ * callback(null, !err);
78525
+ * });
78526
+ * }
78527
+ *
78528
+ * // Using callbacks
78529
+ * async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists,
78530
+ * function(err, result) {
78531
+ * console.log(result);
78532
+ * // true
78533
+ * // result is true since some file in the list exists
78534
+ * }
78535
+ *);
78536
+ *
78537
+ * async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists,
78538
+ * function(err, result) {
78539
+ * console.log(result);
78540
+ * // false
78541
+ * // result is false since none of the files exists
78542
+ * }
78543
+ *);
78544
+ *
78545
+ * // Using Promises
78546
+ * async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists)
78547
+ * .then( result => {
78548
+ * console.log(result);
78549
+ * // true
78550
+ * // result is true since some file in the list exists
78551
+ * }).catch( err => {
78552
+ * console.log(err);
78553
+ * });
78554
+ *
78555
+ * async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists)
78556
+ * .then( result => {
78557
+ * console.log(result);
78558
+ * // false
78559
+ * // result is false since none of the files exists
78560
+ * }).catch( err => {
78561
+ * console.log(err);
78562
+ * });
78563
+ *
78564
+ * // Using async/await
78565
+ * async () => {
78566
+ * try {
78567
+ * let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists);
78568
+ * console.log(result);
78569
+ * // true
78570
+ * // result is true since some file in the list exists
78571
+ * }
78572
+ * catch (err) {
78573
+ * console.log(err);
78574
+ * }
78575
+ * }
78576
+ *
78577
+ * async () => {
78578
+ * try {
78579
+ * let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists);
78580
+ * console.log(result);
78581
+ * // false
78582
+ * // result is false since none of the files exists
78583
+ * }
78584
+ * catch (err) {
78585
+ * console.log(err);
78586
+ * }
78587
+ * }
78588
+ *
78589
+ */
78590
+ function some(coll, iteratee, callback) {
78591
+ return _createTester(Boolean, res => res)(eachOf$1, coll, iteratee, callback)
78592
+ }
78593
+ awaitify(some, 3);
78594
+
78595
+ /**
78596
+ * The same as [`some`]{@link module:Collections.some} but runs a maximum of `limit` async operations at a time.
78597
+ *
78598
+ * @name someLimit
78599
+ * @static
78600
+ * @memberOf module:Collections
78601
+ * @method
78602
+ * @see [async.some]{@link module:Collections.some}
78603
+ * @alias anyLimit
78604
+ * @category Collection
78605
+ * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
78606
+ * @param {number} limit - The maximum number of async operations at a time.
78607
+ * @param {AsyncFunction} iteratee - An async truth test to apply to each item
78608
+ * in the collections in parallel.
78609
+ * The iteratee should complete with a boolean `result` value.
78610
+ * Invoked with (item, callback).
78611
+ * @param {Function} [callback] - A callback which is called as soon as any
78612
+ * iteratee returns `true`, or after all the iteratee functions have finished.
78613
+ * Result will be either `true` or `false` depending on the values of the async
78614
+ * tests. Invoked with (err, result).
78615
+ * @returns {Promise} a promise, if no callback provided
78616
+ */
78617
+ function someLimit(coll, limit, iteratee, callback) {
78618
+ return _createTester(Boolean, res => res)(eachOfLimit$2(limit), coll, iteratee, callback)
78619
+ }
78620
+ awaitify(someLimit, 4);
78621
+
78622
+ /**
78623
+ * The same as [`some`]{@link module:Collections.some} but runs only a single async operation at a time.
78624
+ *
78625
+ * @name someSeries
78626
+ * @static
78627
+ * @memberOf module:Collections
78628
+ * @method
78629
+ * @see [async.some]{@link module:Collections.some}
78630
+ * @alias anySeries
78631
+ * @category Collection
78632
+ * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
78633
+ * @param {AsyncFunction} iteratee - An async truth test to apply to each item
78634
+ * in the collections in series.
78635
+ * The iteratee should complete with a boolean `result` value.
78636
+ * Invoked with (item, callback).
78637
+ * @param {Function} [callback] - A callback which is called as soon as any
78638
+ * iteratee returns `true`, or after all the iteratee functions have finished.
78639
+ * Result will be either `true` or `false` depending on the values of the async
78640
+ * tests. Invoked with (err, result).
78641
+ * @returns {Promise} a promise, if no callback provided
78642
+ */
78643
+ function someSeries(coll, iteratee, callback) {
78644
+ return _createTester(Boolean, res => res)(eachOfSeries$1, coll, iteratee, callback)
78645
+ }
78646
+ awaitify(someSeries, 3);
78647
+
78648
+ /**
78649
+ * Sorts a list by the results of running each `coll` value through an async
78650
+ * `iteratee`.
78651
+ *
78652
+ * @name sortBy
78653
+ * @static
78654
+ * @memberOf module:Collections
78655
+ * @method
78656
+ * @category Collection
78657
+ * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
78658
+ * @param {AsyncFunction} iteratee - An async function to apply to each item in
78659
+ * `coll`.
78660
+ * The iteratee should complete with a value to use as the sort criteria as
78661
+ * its `result`.
78662
+ * Invoked with (item, callback).
78663
+ * @param {Function} callback - A callback which is called after all the
78664
+ * `iteratee` functions have finished, or an error occurs. Results is the items
78665
+ * from the original `coll` sorted by the values returned by the `iteratee`
78666
+ * calls. Invoked with (err, results).
78667
+ * @returns {Promise} a promise, if no callback passed
78668
+ * @example
78669
+ *
78670
+ * // bigfile.txt is a file that is 251100 bytes in size
78671
+ * // mediumfile.txt is a file that is 11000 bytes in size
78672
+ * // smallfile.txt is a file that is 121 bytes in size
78673
+ *
78674
+ * // asynchronous function that returns the file size in bytes
78675
+ * function getFileSizeInBytes(file, callback) {
78676
+ * fs.stat(file, function(err, stat) {
78677
+ * if (err) {
78678
+ * return callback(err);
78679
+ * }
78680
+ * callback(null, stat.size);
78681
+ * });
78682
+ * }
78683
+ *
78684
+ * // Using callbacks
78685
+ * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], getFileSizeInBytes,
78686
+ * function(err, results) {
78687
+ * if (err) {
78688
+ * console.log(err);
78689
+ * } else {
78690
+ * console.log(results);
78691
+ * // results is now the original array of files sorted by
78692
+ * // file size (ascending by default), e.g.
78693
+ * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt']
78694
+ * }
78695
+ * }
78696
+ * );
78697
+ *
78698
+ * // By modifying the callback parameter the
78699
+ * // sorting order can be influenced:
78700
+ *
78701
+ * // ascending order
78702
+ * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], function(file, callback) {
78703
+ * getFileSizeInBytes(file, function(getFileSizeErr, fileSize) {
78704
+ * if (getFileSizeErr) return callback(getFileSizeErr);
78705
+ * callback(null, fileSize);
78706
+ * });
78707
+ * }, function(err, results) {
78708
+ * if (err) {
78709
+ * console.log(err);
78710
+ * } else {
78711
+ * console.log(results);
78712
+ * // results is now the original array of files sorted by
78713
+ * // file size (ascending by default), e.g.
78714
+ * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt']
78715
+ * }
78716
+ * }
78717
+ * );
78718
+ *
78719
+ * // descending order
78720
+ * async.sortBy(['bigfile.txt','mediumfile.txt','smallfile.txt'], function(file, callback) {
78721
+ * getFileSizeInBytes(file, function(getFileSizeErr, fileSize) {
78722
+ * if (getFileSizeErr) {
78723
+ * return callback(getFileSizeErr);
78724
+ * }
78725
+ * callback(null, fileSize * -1);
78726
+ * });
78727
+ * }, function(err, results) {
78728
+ * if (err) {
78729
+ * console.log(err);
78730
+ * } else {
78731
+ * console.log(results);
78732
+ * // results is now the original array of files sorted by
78733
+ * // file size (ascending by default), e.g.
78734
+ * // [ 'bigfile.txt', 'mediumfile.txt', 'smallfile.txt']
78735
+ * }
78736
+ * }
78737
+ * );
78738
+ *
78739
+ * // Error handling
78740
+ * async.sortBy(['mediumfile.txt','smallfile.txt','missingfile.txt'], getFileSizeInBytes,
78741
+ * function(err, results) {
78742
+ * if (err) {
78743
+ * console.log(err);
78744
+ * // [ Error: ENOENT: no such file or directory ]
78745
+ * } else {
78746
+ * console.log(results);
78747
+ * }
78748
+ * }
78749
+ * );
78750
+ *
78751
+ * // Using Promises
78752
+ * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], getFileSizeInBytes)
78753
+ * .then( results => {
78754
+ * console.log(results);
78755
+ * // results is now the original array of files sorted by
78756
+ * // file size (ascending by default), e.g.
78757
+ * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt']
78758
+ * }).catch( err => {
78759
+ * console.log(err);
78760
+ * });
78761
+ *
78762
+ * // Error handling
78763
+ * async.sortBy(['mediumfile.txt','smallfile.txt','missingfile.txt'], getFileSizeInBytes)
78764
+ * .then( results => {
78765
+ * console.log(results);
78766
+ * }).catch( err => {
78767
+ * console.log(err);
78768
+ * // [ Error: ENOENT: no such file or directory ]
78769
+ * });
78770
+ *
78771
+ * // Using async/await
78772
+ * (async () => {
78773
+ * try {
78774
+ * let results = await async.sortBy(['bigfile.txt','mediumfile.txt','smallfile.txt'], getFileSizeInBytes);
78775
+ * console.log(results);
78776
+ * // results is now the original array of files sorted by
78777
+ * // file size (ascending by default), e.g.
78778
+ * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt']
78779
+ * }
78780
+ * catch (err) {
78781
+ * console.log(err);
78782
+ * }
78783
+ * })();
78784
+ *
78785
+ * // Error handling
78786
+ * async () => {
78787
+ * try {
78788
+ * let results = await async.sortBy(['missingfile.txt','mediumfile.txt','smallfile.txt'], getFileSizeInBytes);
78789
+ * console.log(results);
78790
+ * }
78791
+ * catch (err) {
78792
+ * console.log(err);
78793
+ * // [ Error: ENOENT: no such file or directory ]
78794
+ * }
78795
+ * }
78796
+ *
78797
+ */
78798
+ function sortBy (coll, iteratee, callback) {
78799
+ var _iteratee = wrapAsync(iteratee);
78800
+ return map$1(coll, (x, iterCb) => {
78801
+ _iteratee(x, (err, criteria) => {
78802
+ if (err) return iterCb(err);
78803
+ iterCb(err, {value: x, criteria});
78804
+ });
78805
+ }, (err, results) => {
78806
+ if (err) return callback(err);
78807
+ callback(null, results.sort(comparator).map(v => v.value));
78808
+ });
78809
+
78810
+ function comparator(left, right) {
78811
+ var a = left.criteria, b = right.criteria;
78812
+ return a < b ? -1 : a > b ? 1 : 0;
78813
+ }
78814
+ }
78815
+ awaitify(sortBy, 3);
78816
+
78817
+ /**
78818
+ * It runs each task in series but stops whenever any of the functions were
78819
+ * successful. If one of the tasks were successful, the `callback` will be
78820
+ * passed the result of the successful task. If all tasks fail, the callback
78821
+ * will be passed the error and result (if any) of the final attempt.
78822
+ *
78823
+ * @name tryEach
78824
+ * @static
78825
+ * @memberOf module:ControlFlow
78826
+ * @method
78827
+ * @category Control Flow
78828
+ * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing functions to
78829
+ * run, each function is passed a `callback(err, result)` it must call on
78830
+ * completion with an error `err` (which can be `null`) and an optional `result`
78831
+ * value.
78832
+ * @param {Function} [callback] - An optional callback which is called when one
78833
+ * of the tasks has succeeded, or all have failed. It receives the `err` and
78834
+ * `result` arguments of the last attempt at completing the `task`. Invoked with
78835
+ * (err, results).
78836
+ * @returns {Promise} a promise, if no callback is passed
78837
+ * @example
78838
+ * async.tryEach([
78839
+ * function getDataFromFirstWebsite(callback) {
78840
+ * // Try getting the data from the first website
78841
+ * callback(err, data);
78842
+ * },
78843
+ * function getDataFromSecondWebsite(callback) {
78844
+ * // First website failed,
78845
+ * // Try getting the data from the backup website
78846
+ * callback(err, data);
78847
+ * }
78848
+ * ],
78849
+ * // optional callback
78850
+ * function(err, results) {
78851
+ * Now do something with the data.
78852
+ * });
78853
+ *
78854
+ */
78855
+ function tryEach(tasks, callback) {
78856
+ var error = null;
78857
+ var result;
78858
+ return eachSeries$1(tasks, (task, taskCb) => {
78859
+ wrapAsync(task)((err, ...args) => {
78860
+ if (err === false) return taskCb(err);
78861
+
78862
+ if (args.length < 2) {
78863
+ [result] = args;
78864
+ } else {
78865
+ result = args;
78866
+ }
78867
+ error = err;
78868
+ taskCb(err ? null : {});
78869
+ });
78870
+ }, () => callback(error, result));
78871
+ }
78872
+
78873
+ awaitify(tryEach);
78874
+
78875
+ /**
78876
+ * Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when
78877
+ * stopped, or an error occurs.
78878
+ *
78879
+ * @name whilst
78880
+ * @static
78881
+ * @memberOf module:ControlFlow
78882
+ * @method
78883
+ * @category Control Flow
78884
+ * @param {AsyncFunction} test - asynchronous truth test to perform before each
78885
+ * execution of `iteratee`. Invoked with (callback).
78886
+ * @param {AsyncFunction} iteratee - An async function which is called each time
78887
+ * `test` passes. Invoked with (callback).
78888
+ * @param {Function} [callback] - A callback which is called after the test
78889
+ * function has failed and repeated execution of `iteratee` has stopped. `callback`
78890
+ * will be passed an error and any arguments passed to the final `iteratee`'s
78891
+ * callback. Invoked with (err, [results]);
78892
+ * @returns {Promise} a promise, if no callback is passed
78893
+ * @example
78894
+ *
78895
+ * var count = 0;
78896
+ * async.whilst(
78897
+ * function test(cb) { cb(null, count < 5); },
78898
+ * function iter(callback) {
78899
+ * count++;
78900
+ * setTimeout(function() {
78901
+ * callback(null, count);
78902
+ * }, 1000);
78903
+ * },
78904
+ * function (err, n) {
78905
+ * // 5 seconds have passed, n = 5
78906
+ * }
78907
+ * );
78908
+ */
78909
+ function whilst(test, iteratee, callback) {
78910
+ callback = onlyOnce(callback);
78911
+ var _fn = wrapAsync(iteratee);
78912
+ var _test = wrapAsync(test);
78913
+ var results = [];
78914
+
78915
+ function next(err, ...rest) {
78916
+ if (err) return callback(err);
78917
+ results = rest;
78918
+ if (err === false) return;
78919
+ _test(check);
78920
+ }
78921
+
78922
+ function check(err, truth) {
78923
+ if (err) return callback(err);
78924
+ if (err === false) return;
78925
+ if (!truth) return callback(null, ...results);
78926
+ _fn(next);
78927
+ }
78928
+
78929
+ return _test(check);
78930
+ }
78931
+ awaitify(whilst, 3);
78932
+
78933
+ /**
78934
+ * Runs the `tasks` array of functions in series, each passing their results to
78935
+ * the next in the array. However, if any of the `tasks` pass an error to their
78936
+ * own callback, the next function is not executed, and the main `callback` is
78937
+ * immediately called with the error.
78938
+ *
78939
+ * @name waterfall
78940
+ * @static
78941
+ * @memberOf module:ControlFlow
78942
+ * @method
78943
+ * @category Control Flow
78944
+ * @param {Array} tasks - An array of [async functions]{@link AsyncFunction}
78945
+ * to run.
78946
+ * Each function should complete with any number of `result` values.
78947
+ * The `result` values will be passed as arguments, in order, to the next task.
78948
+ * @param {Function} [callback] - An optional callback to run once all the
78949
+ * functions have completed. This will be passed the results of the last task's
78950
+ * callback. Invoked with (err, [results]).
78951
+ * @returns {Promise} a promise, if a callback is omitted
78952
+ * @example
78953
+ *
78954
+ * async.waterfall([
78955
+ * function(callback) {
78956
+ * callback(null, 'one', 'two');
78957
+ * },
78958
+ * function(arg1, arg2, callback) {
78959
+ * // arg1 now equals 'one' and arg2 now equals 'two'
78960
+ * callback(null, 'three');
78961
+ * },
78962
+ * function(arg1, callback) {
78963
+ * // arg1 now equals 'three'
78964
+ * callback(null, 'done');
78965
+ * }
78966
+ * ], function (err, result) {
78967
+ * // result now equals 'done'
78968
+ * });
78969
+ *
78970
+ * // Or, with named functions:
78971
+ * async.waterfall([
78972
+ * myFirstFunction,
78973
+ * mySecondFunction,
78974
+ * myLastFunction,
78975
+ * ], function (err, result) {
78976
+ * // result now equals 'done'
78977
+ * });
78978
+ * function myFirstFunction(callback) {
78979
+ * callback(null, 'one', 'two');
78980
+ * }
78981
+ * function mySecondFunction(arg1, arg2, callback) {
78982
+ * // arg1 now equals 'one' and arg2 now equals 'two'
78983
+ * callback(null, 'three');
78984
+ * }
78985
+ * function myLastFunction(arg1, callback) {
78986
+ * // arg1 now equals 'three'
78987
+ * callback(null, 'done');
78988
+ * }
78989
+ */
78990
+ function waterfall (tasks, callback) {
78991
+ callback = once(callback);
78992
+ if (!Array.isArray(tasks)) return callback(new Error('First argument to waterfall must be an array of functions'));
78993
+ if (!tasks.length) return callback();
78994
+ var taskIndex = 0;
78995
+
78996
+ function nextTask(args) {
78997
+ var task = wrapAsync(tasks[taskIndex++]);
78998
+ task(...args, onlyOnce(next));
78999
+ }
79000
+
79001
+ function next(err, ...args) {
79002
+ if (err === false) return
79003
+ if (err || taskIndex === tasks.length) {
79004
+ return callback(err, ...args);
79005
+ }
79006
+ nextTask(args);
79007
+ }
79008
+
79009
+ nextTask([]);
79010
+ }
79011
+
79012
+ awaitify(waterfall);
79013
+
76333
79014
  var LogLevel;
76334
79015
  (function (LogLevel) {
76335
79016
  LogLevel[LogLevel["DEBUG"] = 0] = "DEBUG";
@@ -76371,31 +79052,6 @@ class Logger {
76371
79052
  }
76372
79053
  }
76373
79054
 
76374
- /**
76375
- * Executes an array of promise-returning functions with a maximum concurrency limit.
76376
- * This prevents overwhelming RPC endpoints with too many concurrent requests.
76377
- *
76378
- * @param tasks - Array of functions that return promises
76379
- * @param maxConcurrency - Maximum number of concurrent executions (default: 5)
76380
- * @returns Promise that resolves to an array of settled results
76381
- *
76382
- * @example
76383
- * ```typescript
76384
- * const tasks = pools.map(pool => () => fetchPoolData(pool));
76385
- * const results = await batchWithConcurrency(tasks, 5);
76386
- * ```
76387
- */
76388
- async function batchWithConcurrency(tasks, maxConcurrency = 5) {
76389
- const results = [];
76390
- // Process tasks in batches
76391
- for (let i = 0; i < tasks.length; i += maxConcurrency) {
76392
- const batch = tasks.slice(i, i + maxConcurrency);
76393
- const batchResults = await Promise.allSettled(batch.map(task => task()));
76394
- results.push(...batchResults);
76395
- }
76396
- return results;
76397
- }
76398
-
76399
79055
  class DataError extends SDKError {
76400
79056
  constructor(message, code = ErrorCode.NETWORK_ERROR, details) {
76401
79057
  super(message, code, details);
@@ -76440,6 +79096,7 @@ class AccountService {
76440
79096
  dataService;
76441
79097
  account;
76442
79098
  logger;
79099
+ poolConcurrency;
76443
79100
  /**
76444
79101
  * Creates a new AccountService instance.
76445
79102
  *
@@ -76447,12 +79104,14 @@ class AccountService {
76447
79104
  * @param config - Configuration for the account service (either mnemonic or existing account)
76448
79105
  * @param config.mnemonic - Optional mnemonic for deterministic key generation
76449
79106
  * @param config.account - Optional existing account to initialize with
79107
+ * @param config.poolConcurrency - Optional maximum number of pools to fetch events for concurrently (default: 2)
76450
79108
  *
76451
79109
  * @throws {AccountError} If account initialization fails
76452
79110
  */
76453
79111
  constructor(dataService, config) {
76454
79112
  this.dataService = dataService;
76455
79113
  this.logger = new Logger({ prefix: "Account" });
79114
+ this.poolConcurrency = config.poolConcurrency ?? 2;
76456
79115
  if ("mnemonic" in config) {
76457
79116
  this.account = this._initializeAccount(config.mnemonic);
76458
79117
  }
@@ -76839,36 +79498,44 @@ class AccountService {
76839
79498
  }
76840
79499
  }
76841
79500
  /**
76842
- * Fetches events for a given set of pools with concurrency control
79501
+ * Fetches events for a given set of pools
76843
79502
  *
76844
79503
  * @param pools - The pools to fetch events for
76845
- * @param maxConcurrency - Maximum number of concurrent pool fetches (default: 5)
76846
79504
  *
76847
79505
  * @returns A map of pool scopes to their events
76848
79506
  */
76849
- async getEvents(pools, maxConcurrency = 5) {
79507
+ async getEvents(pools) {
76850
79508
  const events = new Map();
76851
- // Create tasks for batched execution
76852
- const tasks = pools.map((pool) => async () => {
76853
- this.logger.info(`Fetching events for pool`, {
76854
- poolAddress: pool.address,
76855
- poolChainId: pool.chainId,
76856
- poolDeploymentBlock: pool.deploymentBlock,
76857
- });
76858
- const [depositEvents, withdrawalEvents, ragequitEvents] = await Promise.all([
76859
- this.getDepositEvents(pool),
76860
- this.getWithdrawalEvents(pool),
76861
- this.getRagequitEvents(pool),
76862
- ]);
76863
- return {
76864
- scope: pool.scope,
76865
- depositEvents,
76866
- withdrawalEvents,
76867
- ragequitEvents,
76868
- };
79509
+ // Use mapLimit to control concurrency at pool level
79510
+ const poolEventResults = await mapLimit$1(pools, this.poolConcurrency, async (pool) => {
79511
+ try {
79512
+ this.logger.info(`Fetching events for pool`, {
79513
+ poolAddress: pool.address,
79514
+ poolChainId: pool.chainId,
79515
+ poolDeploymentBlock: pool.deploymentBlock,
79516
+ });
79517
+ const [depositEvents, withdrawalEvents, ragequitEvents] = await Promise.all([
79518
+ this.getDepositEvents(pool),
79519
+ this.getWithdrawalEvents(pool),
79520
+ this.getRagequitEvents(pool),
79521
+ ]);
79522
+ return {
79523
+ status: "fulfilled",
79524
+ value: {
79525
+ scope: pool.scope,
79526
+ depositEvents,
79527
+ withdrawalEvents,
79528
+ ragequitEvents,
79529
+ },
79530
+ };
79531
+ }
79532
+ catch (error) {
79533
+ return {
79534
+ status: "rejected",
79535
+ reason: error,
79536
+ };
79537
+ }
76869
79538
  });
76870
- // Execute with concurrency control
76871
- const poolEventResults = await batchWithConcurrency(tasks, maxConcurrency);
76872
79539
  for (const result of poolEventResults) {
76873
79540
  if (result.status === "fulfilled") {
76874
79541
  const { scope, depositEvents, withdrawalEvents, ragequitEvents } = result.value;
@@ -76879,9 +79546,11 @@ class AccountService {
76879
79546
  });
76880
79547
  }
76881
79548
  else {
76882
- events.set(result.reason.details?.scope, {
79549
+ const errorWithDetails = result.reason;
79550
+ const scope = errorWithDetails.details?.scope;
79551
+ events.set(scope, {
76883
79552
  reason: result.reason.message,
76884
- scope: result.reason.details?.scope,
79553
+ scope: scope,
76885
79554
  });
76886
79555
  }
76887
79556
  }
@@ -77007,11 +79676,10 @@ class AccountService {
77007
79676
  * @param dataService - The data service to use for fetching events
77008
79677
  * @param source - The source to use for initializing the account. Either a mnemonic or an existing account service instance
77009
79678
  * @param pools - The pools to fetch events for
77010
- * @param maxConcurrency - Maximum number of concurrent pool fetches (default: 5)
77011
79679
  *
77012
79680
  * @remarks
77013
79681
  * This method performs the following steps for each pool:
77014
- * 1. Fetches deposit, withdrawal, and ragequit events for each pool (with concurrency control)
79682
+ * 1. Fetches deposit, withdrawal, and ragequit events for each pool
77015
79683
  * 2. Processes deposit events and creates pool accounts
77016
79684
  * 3. Processes withdrawal events and adds commitments to pool accounts
77017
79685
  * 4. Processes ragequit events and adds ragequit to pool accounts
@@ -77023,7 +79691,7 @@ class AccountService {
77023
79691
  *
77024
79692
  * @throws {AccountError} If account state reconstruction fails or if duplicate pools are found
77025
79693
  */
77026
- static async initializeWithEvents(dataService, source, pools, maxConcurrency = 5) {
79694
+ static async initializeWithEvents(dataService, source, pools) {
77027
79695
  // Log the start of the history retrieval process
77028
79696
  const logger = new Logger({ prefix: "Account" });
77029
79697
  logger.info(`Fetching events for pools`, { poolLength: pools.length });
@@ -77039,7 +79707,7 @@ class AccountService {
77039
79707
  const account = new AccountService(dataService, "mnemonic" in source
77040
79708
  ? { mnemonic: source.mnemonic }
77041
79709
  : { account: source.service.account });
77042
- const events = await account.getEvents(pools, maxConcurrency);
79710
+ const events = await account.getEvents(pools);
77043
79711
  for (const [scope, result] of events.entries()) {
77044
79712
  if ("reason" in result) {
77045
79713
  errors.push(result);
@@ -77235,24 +79903,31 @@ class DataService {
77235
79903
  chainConfigs;
77236
79904
  clients = new Map();
77237
79905
  logger;
79906
+ logFetchConfigs;
77238
79907
  /**
77239
79908
  * Initialize the data service with chain configurations
77240
79909
  *
77241
79910
  * @param chainConfigs - Array of chain configurations containing chainId, RPC URL, and API key
79911
+ * @param logFetchConfig - Per-chain configuration for rate-limited log fetching as a Map<chainId, config>.
79912
+ * Each chain can have its own specific settings (e.g., different block chunk sizes).
77242
79913
  * @throws {DataError} If client initialization fails for any chain
77243
79914
  */
77244
- constructor(chainConfigs) {
79915
+ constructor(chainConfigs, logFetchConfig = new Map()) {
77245
79916
  this.chainConfigs = chainConfigs;
77246
- this.logger = new Logger({ prefix: "Data" });
79917
+ this.logger = new Logger({ prefix: "Data", level: LogLevel.DEBUG });
79918
+ // Initialize per-chain configs with defaults merged with chain-specific overrides
79919
+ this.logFetchConfigs = new Map();
79920
+ for (const config of chainConfigs) {
79921
+ const chainSpecificConfig = logFetchConfig.get(config.chainId);
79922
+ this.logFetchConfigs.set(config.chainId, { ...DEFAULT_LOG_FETCH_CONFIG, ...chainSpecificConfig });
79923
+ }
77247
79924
  try {
77248
79925
  for (const config of chainConfigs) {
77249
79926
  if (!config.rpcUrl) {
77250
79927
  throw new Error(`Missing RPC URL for chain ${config.chainId}`);
77251
79928
  }
77252
79929
  const client = createPublicClient({
77253
- transport: http(config.rpcUrl, {
77254
- timeout: 20_000,
77255
- }),
79930
+ transport: http(config.rpcUrl),
77256
79931
  });
77257
79932
  this.clients.set(config.chainId, client);
77258
79933
  }
@@ -77264,29 +79939,41 @@ class DataService {
77264
79939
  /**
77265
79940
  * Get deposit events for a specific chain
77266
79941
  *
77267
- * @param chainId - Chain ID to fetch events from
77268
- * @param options - Event filter options including fromBlock, toBlock, and other filters
79942
+ * @param pool - Pool info containing chainId, address, and deployment block
77269
79943
  * @returns Array of deposit events with properly typed fields (bigint for numbers, Hash for commitments)
77270
79944
  * @throws {DataError} If client is not configured, network error occurs, or event data is invalid
77271
79945
  */
77272
79946
  async getDeposits(pool) {
77273
79947
  try {
77274
79948
  const client = this.getClientForChain(pool.chainId);
77275
- const config = this.getConfigForChain(pool.chainId);
77276
- const logs = await client.getLogs({
77277
- address: pool.address,
77278
- event: DEPOSIT_EVENT,
77279
- fromBlock: pool.deploymentBlock ?? config.startBlock
77280
- }).catch(error => {
77281
- throw new DataError("Failed to fetch deposit logs", ErrorCode.NETWORK_ERROR, { error: error instanceof Error ? error.message : "Unknown error" });
79949
+ const chainConfig = this.getConfigForChain(pool.chainId);
79950
+ const logConfig = this.getLogFetchConfigForChain(pool.chainId);
79951
+ const fromBlock = pool.deploymentBlock ?? chainConfig.startBlock;
79952
+ const toBlock = await this.getCurrentBlock(pool.chainId);
79953
+ const ranges = this.generateBlockRanges(fromBlock, toBlock, logConfig.blockChunkSize);
79954
+ this.logger.info(`Fetching deposits in ${ranges.length} chunks for pool ${pool.address}, chunk size is: ${logConfig.blockChunkSize}`);
79955
+ // Use async.mapLimit for controlled concurrency
79956
+ const allLogs = await mapLimit$1(ranges, logConfig.concurrency, async (range) => {
79957
+ if (logConfig.chunkDelayMs > 0) {
79958
+ await this.sleep(logConfig.chunkDelayMs);
79959
+ }
79960
+ return this.fetchLogsWithRetry(client, pool.address, DEPOSIT_EVENT, range, logConfig);
77282
79961
  });
77283
- return logs.map((log) => {
79962
+ // Flatten and parse results
79963
+ const flatLogs = allLogs.flat();
79964
+ return flatLogs.map((log) => {
77284
79965
  try {
77285
- if (!log.args) {
79966
+ const typedLog = log;
79967
+ if (!typedLog.args) {
77286
79968
  throw DataError.invalidLog("deposit", "missing args");
77287
79969
  }
77288
- const { _depositor: depositor, _commitment: commitment, _label: label, _value: value, _merkleRoot: precommitment, } = log.args;
77289
- if (!depositor || !commitment || !label || !precommitment || !log.blockNumber || !log.transactionHash) {
79970
+ const { _depositor: depositor, _commitment: commitment, _label: label, _value: value, _merkleRoot: precommitment, } = typedLog.args;
79971
+ if (!depositor ||
79972
+ !commitment ||
79973
+ !label ||
79974
+ !precommitment ||
79975
+ !typedLog.blockNumber ||
79976
+ !typedLog.transactionHash) {
77290
79977
  throw DataError.invalidLog("deposit", "missing required fields");
77291
79978
  }
77292
79979
  return {
@@ -77295,8 +79982,8 @@ class DataService {
77295
79982
  label: label,
77296
79983
  value: value || BigInt(0),
77297
79984
  precommitment: precommitment,
77298
- blockNumber: BigInt(log.blockNumber),
77299
- transactionHash: log.transactionHash,
79985
+ blockNumber: BigInt(typedLog.blockNumber),
79986
+ transactionHash: typedLog.transactionHash,
77300
79987
  };
77301
79988
  }
77302
79989
  catch (error) {
@@ -77315,37 +80002,50 @@ class DataService {
77315
80002
  /**
77316
80003
  * Get withdrawal events for a specific chain
77317
80004
  *
77318
- * @param chainId - Chain ID to fetch events from
77319
- * @param options - Event filter options including fromBlock, toBlock, and other filters
80005
+ * @param pool - Pool info containing chainId, address, and deployment block
80006
+ * @param fromBlock - Optional starting block (defaults to pool deployment block)
77320
80007
  * @returns Array of withdrawal events with properly typed fields (bigint for numbers, Hash for commitments)
77321
80008
  * @throws {DataError} If client is not configured, network error occurs, or event data is invalid
77322
80009
  */
77323
80010
  async getWithdrawals(pool, fromBlock = pool.deploymentBlock) {
77324
80011
  try {
77325
80012
  const client = this.getClientForChain(pool.chainId);
77326
- const config = this.getConfigForChain(pool.chainId);
77327
- const logs = await client.getLogs({
77328
- address: pool.address,
77329
- event: WITHDRAWAL_EVENT,
77330
- fromBlock: fromBlock ?? config.startBlock,
77331
- }).catch(error => {
77332
- throw new DataError("Failed to fetch withdrawal logs", ErrorCode.NETWORK_ERROR, { error: error instanceof Error ? error.message : "Unknown error" });
80013
+ const chainConfig = this.getConfigForChain(pool.chainId);
80014
+ const logConfig = this.getLogFetchConfigForChain(pool.chainId);
80015
+ const startBlock = fromBlock ?? chainConfig.startBlock;
80016
+ const toBlock = await this.getCurrentBlock(pool.chainId);
80017
+ const ranges = this.generateBlockRanges(startBlock, toBlock, logConfig.blockChunkSize);
80018
+ this.logger.debug(`Fetching withdrawals in ${ranges.length} chunks for pool ${pool.address}`);
80019
+ // Use async.mapLimit for controlled concurrency
80020
+ const allLogs = await mapLimit$1(ranges, logConfig.concurrency, async (range) => {
80021
+ if (logConfig.chunkDelayMs > 0) {
80022
+ await this.sleep(logConfig.chunkDelayMs);
80023
+ }
80024
+ return this.fetchLogsWithRetry(client, pool.address, WITHDRAWAL_EVENT, range, logConfig);
77333
80025
  });
77334
- return logs.map((log) => {
80026
+ // Flatten and parse results
80027
+ const flatLogs = allLogs.flat();
80028
+ return flatLogs.map((log) => {
77335
80029
  try {
77336
- if (!log.args) {
80030
+ const typedLog = log;
80031
+ if (!typedLog.args) {
77337
80032
  throw DataError.invalidLog("withdrawal", "missing args");
77338
80033
  }
77339
- const { _value: value, _spentNullifier: spentNullifier, _newCommitment: newCommitment, } = log.args;
77340
- if (!value || !spentNullifier || !newCommitment || !log.blockNumber || !log.transactionHash) {
80034
+ const { _value: value, _spentNullifier: spentNullifier, _newCommitment: newCommitment, } = typedLog.args;
80035
+ if (value === undefined ||
80036
+ value === null ||
80037
+ !spentNullifier ||
80038
+ !newCommitment ||
80039
+ !typedLog.blockNumber ||
80040
+ !typedLog.transactionHash) {
77341
80041
  throw DataError.invalidLog("withdrawal", "missing required fields");
77342
80042
  }
77343
80043
  return {
77344
80044
  withdrawn: value,
77345
80045
  spentNullifier: spentNullifier,
77346
80046
  newCommitment: newCommitment,
77347
- blockNumber: BigInt(log.blockNumber),
77348
- transactionHash: log.transactionHash,
80047
+ blockNumber: BigInt(typedLog.blockNumber),
80048
+ transactionHash: typedLog.transactionHash,
77349
80049
  };
77350
80050
  }
77351
80051
  catch (error) {
@@ -77364,29 +80064,41 @@ class DataService {
77364
80064
  /**
77365
80065
  * Get ragequit events for a specific chain
77366
80066
  *
77367
- * @param chainId - Chain ID to fetch events from
77368
- * @param options - Event filter options including fromBlock, toBlock, and other filters
80067
+ * @param pool - Pool info containing chainId, address, and deployment block
80068
+ * @param fromBlock - Optional starting block (defaults to pool deployment block)
77369
80069
  * @returns Array of ragequit events with properly typed fields (bigint for numbers, Hash for commitments)
77370
80070
  * @throws {DataError} If client is not configured, network error occurs, or event data is invalid
77371
80071
  */
77372
80072
  async getRagequits(pool, fromBlock = pool.deploymentBlock) {
77373
80073
  try {
77374
80074
  const client = this.getClientForChain(pool.chainId);
77375
- const config = this.getConfigForChain(pool.chainId);
77376
- const logs = await client.getLogs({
77377
- address: pool.address,
77378
- event: RAGEQUIT_EVENT,
77379
- fromBlock: fromBlock ?? config.startBlock,
77380
- }).catch(error => {
77381
- throw new DataError("Failed to fetch ragequit logs", ErrorCode.NETWORK_ERROR, { error: error instanceof Error ? error.message : "Unknown error" });
80075
+ const chainConfig = this.getConfigForChain(pool.chainId);
80076
+ const logConfig = this.getLogFetchConfigForChain(pool.chainId);
80077
+ const startBlock = fromBlock ?? chainConfig.startBlock;
80078
+ const toBlock = await this.getCurrentBlock(pool.chainId);
80079
+ const ranges = this.generateBlockRanges(startBlock, toBlock, logConfig.blockChunkSize);
80080
+ this.logger.debug(`Fetching ragequits in ${ranges.length} chunks for pool ${pool.address}`);
80081
+ // Use async.mapLimit for controlled concurrency
80082
+ const allLogs = await mapLimit$1(ranges, logConfig.concurrency, async (range) => {
80083
+ if (logConfig.chunkDelayMs > 0) {
80084
+ await this.sleep(logConfig.chunkDelayMs);
80085
+ }
80086
+ return this.fetchLogsWithRetry(client, pool.address, RAGEQUIT_EVENT, range, logConfig);
77382
80087
  });
77383
- return logs.map((log) => {
80088
+ // Flatten and parse results
80089
+ const flatLogs = allLogs.flat();
80090
+ return flatLogs.map((log) => {
77384
80091
  try {
77385
- if (!log.args) {
80092
+ const typedLog = log;
80093
+ if (!typedLog.args) {
77386
80094
  throw DataError.invalidLog("ragequit", "missing args");
77387
80095
  }
77388
- const { _ragequitter: ragequitter, _commitment: commitment, _label: label, _value: value, } = log.args;
77389
- if (!ragequitter || !commitment || !label || !log.blockNumber || !log.transactionHash) {
80096
+ const { _ragequitter: ragequitter, _commitment: commitment, _label: label, _value: value, } = typedLog.args;
80097
+ if (!ragequitter ||
80098
+ !commitment ||
80099
+ !label ||
80100
+ !typedLog.blockNumber ||
80101
+ !typedLog.transactionHash) {
77390
80102
  throw DataError.invalidLog("ragequit", "missing required fields");
77391
80103
  }
77392
80104
  return {
@@ -77394,8 +80106,8 @@ class DataService {
77394
80106
  commitment: commitment,
77395
80107
  label: label,
77396
80108
  value: value || BigInt(0),
77397
- blockNumber: BigInt(log.blockNumber),
77398
- transactionHash: log.transactionHash,
80109
+ blockNumber: BigInt(typedLog.blockNumber),
80110
+ transactionHash: typedLog.transactionHash,
77399
80111
  };
77400
80112
  }
77401
80113
  catch (error) {
@@ -77411,6 +80123,66 @@ class DataService {
77411
80123
  throw DataError.networkError(pool.chainId, error instanceof Error ? error : new Error(String(error)));
77412
80124
  }
77413
80125
  }
80126
+ /**
80127
+ * Gets the current block number for a chain
80128
+ */
80129
+ async getCurrentBlock(chainId) {
80130
+ const client = this.getClientForChain(chainId);
80131
+ return client.getBlockNumber();
80132
+ }
80133
+ /**
80134
+ * Generates block ranges for chunked fetching
80135
+ */
80136
+ generateBlockRanges(fromBlock, toBlock, chunkSize) {
80137
+ const ranges = [];
80138
+ let current = fromBlock;
80139
+ while (current <= toBlock) {
80140
+ const end = current + BigInt(chunkSize) - 1n;
80141
+ ranges.push({
80142
+ fromBlock: current,
80143
+ toBlock: end > toBlock ? toBlock : end,
80144
+ });
80145
+ current = end + 1n;
80146
+ }
80147
+ return ranges;
80148
+ }
80149
+ /**
80150
+ * Fetches logs for a single block range with retry logic
80151
+ */
80152
+ async fetchLogsWithRetry(client, address,
80153
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
80154
+ event, range, logConfig) {
80155
+ const maxRetries = logConfig.retryOnFailure
80156
+ ? logConfig.maxRetries
80157
+ : 0;
80158
+ let lastError;
80159
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
80160
+ try {
80161
+ const logs = await client.getLogs({
80162
+ address: address,
80163
+ event,
80164
+ fromBlock: range.fromBlock,
80165
+ toBlock: range.toBlock,
80166
+ });
80167
+ return logs;
80168
+ }
80169
+ catch (error) {
80170
+ lastError = error instanceof Error ? error : new Error(String(error));
80171
+ if (attempt < maxRetries) {
80172
+ const delay = logConfig.retryBaseDelayMs * Math.pow(2, attempt);
80173
+ this.logger.warn(`Log fetch failed, retrying in ${delay}ms (attempt ${attempt + 1}/${maxRetries})`, { error: lastError.message, range });
80174
+ await this.sleep(delay);
80175
+ }
80176
+ }
80177
+ }
80178
+ throw lastError;
80179
+ }
80180
+ /**
80181
+ * Helper to add delay between requests
80182
+ */
80183
+ sleep(ms) {
80184
+ return new Promise((resolve) => setTimeout(resolve, ms));
80185
+ }
77414
80186
  getClientForChain(chainId) {
77415
80187
  const client = this.clients.get(chainId);
77416
80188
  if (!client) {
@@ -77419,13 +80191,21 @@ class DataService {
77419
80191
  return client;
77420
80192
  }
77421
80193
  getConfigForChain(chainId) {
77422
- const config = this.chainConfigs.find(c => c.chainId === chainId);
80194
+ const config = this.chainConfigs.find((c) => c.chainId === chainId);
77423
80195
  if (!config) {
77424
80196
  throw DataError.chainNotConfigured(chainId);
77425
80197
  }
77426
80198
  return config;
77427
80199
  }
80200
+ getLogFetchConfigForChain(chainId) {
80201
+ const config = this.logFetchConfigs.get(chainId);
80202
+ if (!config) {
80203
+ // Fallback to default if not found (shouldn't happen if constructor is correct)
80204
+ return DEFAULT_LOG_FETCH_CONFIG;
80205
+ }
80206
+ return config;
80207
+ }
77428
80208
  }
77429
80209
 
77430
- export { AccountService as A, BlockchainProvider as B, CommitmentService as C, DataService as D, ErrorCode as E, FetchArtifact as F, InvalidRpcUrl as I, PrivacyPoolSDK as P, SDKError as S, WithdrawalService as W, generateDepositSecrets as a, generateWithdrawalSecrets as b, getCommitment as c, generateMerkleProof as d, bigintToHash as e, bigintToHex as f, generateMasterKeys as g, hashPrecommitment as h, calculateContext as i, Circuits as j, ContractInteractionsService as k, ProofError as l, ContractError as m, AccountError as n, CircuitName as o };
77431
- //# sourceMappingURL=index-DGsIfUGw.js.map
80210
+ export { AccountService as A, BlockchainProvider as B, CommitmentService as C, DataService as D, ErrorCode as E, FetchArtifact as F, InvalidRpcUrl as I, PrivacyPoolSDK as P, SDKError as S, WithdrawalService as W, DEFAULT_LOG_FETCH_CONFIG as a, generateDepositSecrets as b, generateWithdrawalSecrets as c, getCommitment as d, generateMerkleProof as e, bigintToHash as f, generateMasterKeys as g, hashPrecommitment as h, bigintToHex as i, calculateContext as j, Circuits as k, ContractInteractionsService as l, ProofError as m, ContractError as n, AccountError as o, CircuitName as p };
80211
+ //# sourceMappingURL=index-C3RV9Cri.js.map