@webex/web-client-media-engine 1.41.0 → 1.41.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.
package/dist/esm/index.js CHANGED
@@ -645,7 +645,7 @@ function EventEmitter$1$1() {
645
645
  EventEmitter$1$1.init.call(this);
646
646
  }
647
647
  events$1.exports = EventEmitter$1$1;
648
- events$1.exports.once = once$1;
648
+ events$1.exports.once = once$2;
649
649
 
650
650
  // Backwards-compat with node 0.10.x
651
651
  EventEmitter$1$1.EventEmitter = EventEmitter$1$1;
@@ -1037,7 +1037,7 @@ function unwrapListeners$1(arr) {
1037
1037
  return ret;
1038
1038
  }
1039
1039
 
1040
- function once$1(emitter, name) {
1040
+ function once$2(emitter, name) {
1041
1041
  return new Promise(function (resolve, reject) {
1042
1042
  function errorListener(err) {
1043
1043
  emitter.removeListener(name, resolver);
@@ -8179,6 +8179,3210 @@ function hasCodec(codecName, mLine) {
8179
8179
  return [...mLine.codecs.values()].some((ci) => { var _a; return ((_a = ci.name) === null || _a === void 0 ? void 0 : _a.toLowerCase()) === codecName.toLowerCase(); });
8180
8180
  }
8181
8181
 
8182
+ /**
8183
+ * Creates a continuation function with some arguments already applied.
8184
+ *
8185
+ * Useful as a shorthand when combined with other control flow functions. Any
8186
+ * arguments passed to the returned function are added to the arguments
8187
+ * originally passed to apply.
8188
+ *
8189
+ * @name apply
8190
+ * @static
8191
+ * @memberOf module:Utils
8192
+ * @method
8193
+ * @category Util
8194
+ * @param {Function} fn - The function you want to eventually apply all
8195
+ * arguments to. Invokes with (arguments...).
8196
+ * @param {...*} arguments... - Any number of arguments to automatically apply
8197
+ * when the continuation is called.
8198
+ * @returns {Function} the partially-applied function
8199
+ * @example
8200
+ *
8201
+ * // using apply
8202
+ * async.parallel([
8203
+ * async.apply(fs.writeFile, 'testfile1', 'test1'),
8204
+ * async.apply(fs.writeFile, 'testfile2', 'test2')
8205
+ * ]);
8206
+ *
8207
+ *
8208
+ * // the same process without using apply
8209
+ * async.parallel([
8210
+ * function(callback) {
8211
+ * fs.writeFile('testfile1', 'test1', callback);
8212
+ * },
8213
+ * function(callback) {
8214
+ * fs.writeFile('testfile2', 'test2', callback);
8215
+ * }
8216
+ * ]);
8217
+ *
8218
+ * // It's possible to pass any number of additional arguments when calling the
8219
+ * // continuation:
8220
+ *
8221
+ * node> var fn = async.apply(sys.puts, 'one');
8222
+ * node> fn('two', 'three');
8223
+ * one
8224
+ * two
8225
+ * three
8226
+ */
8227
+
8228
+ function initialParams (fn) {
8229
+ return function (...args/*, callback*/) {
8230
+ var callback = args.pop();
8231
+ return fn.call(this, args, callback);
8232
+ };
8233
+ }
8234
+
8235
+ /* istanbul ignore file */
8236
+
8237
+ var hasQueueMicrotask = typeof queueMicrotask === 'function' && queueMicrotask;
8238
+ var hasSetImmediate = typeof setImmediate === 'function' && setImmediate;
8239
+ var hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function';
8240
+
8241
+ function fallback(fn) {
8242
+ setTimeout(fn, 0);
8243
+ }
8244
+
8245
+ function wrap(defer) {
8246
+ return (fn, ...args) => defer(() => fn(...args));
8247
+ }
8248
+
8249
+ var _defer;
8250
+
8251
+ if (hasQueueMicrotask) {
8252
+ _defer = queueMicrotask;
8253
+ } else if (hasSetImmediate) {
8254
+ _defer = setImmediate;
8255
+ } else if (hasNextTick) {
8256
+ _defer = process.nextTick;
8257
+ } else {
8258
+ _defer = fallback;
8259
+ }
8260
+
8261
+ var setImmediate$1 = wrap(_defer);
8262
+
8263
+ /**
8264
+ * Take a sync function and make it async, passing its return value to a
8265
+ * callback. This is useful for plugging sync functions into a waterfall,
8266
+ * series, or other async functions. Any arguments passed to the generated
8267
+ * function will be passed to the wrapped function (except for the final
8268
+ * callback argument). Errors thrown will be passed to the callback.
8269
+ *
8270
+ * If the function passed to `asyncify` returns a Promise, that promises's
8271
+ * resolved/rejected state will be used to call the callback, rather than simply
8272
+ * the synchronous return value.
8273
+ *
8274
+ * This also means you can asyncify ES2017 `async` functions.
8275
+ *
8276
+ * @name asyncify
8277
+ * @static
8278
+ * @memberOf module:Utils
8279
+ * @method
8280
+ * @alias wrapSync
8281
+ * @category Util
8282
+ * @param {Function} func - The synchronous function, or Promise-returning
8283
+ * function to convert to an {@link AsyncFunction}.
8284
+ * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be
8285
+ * invoked with `(args..., callback)`.
8286
+ * @example
8287
+ *
8288
+ * // passing a regular synchronous function
8289
+ * async.waterfall([
8290
+ * async.apply(fs.readFile, filename, "utf8"),
8291
+ * async.asyncify(JSON.parse),
8292
+ * function (data, next) {
8293
+ * // data is the result of parsing the text.
8294
+ * // If there was a parsing error, it would have been caught.
8295
+ * }
8296
+ * ], callback);
8297
+ *
8298
+ * // passing a function returning a promise
8299
+ * async.waterfall([
8300
+ * async.apply(fs.readFile, filename, "utf8"),
8301
+ * async.asyncify(function (contents) {
8302
+ * return db.model.create(contents);
8303
+ * }),
8304
+ * function (model, next) {
8305
+ * // `model` is the instantiated model object.
8306
+ * // If there was an error, this function would be skipped.
8307
+ * }
8308
+ * ], callback);
8309
+ *
8310
+ * // es2017 example, though `asyncify` is not needed if your JS environment
8311
+ * // supports async functions out of the box
8312
+ * var q = async.queue(async.asyncify(async function(file) {
8313
+ * var intermediateStep = await processFile(file);
8314
+ * return await somePromise(intermediateStep)
8315
+ * }));
8316
+ *
8317
+ * q.push(files);
8318
+ */
8319
+ function asyncify(func) {
8320
+ if (isAsync(func)) {
8321
+ return function (...args/*, callback*/) {
8322
+ const callback = args.pop();
8323
+ const promise = func.apply(this, args);
8324
+ return handlePromise(promise, callback)
8325
+ }
8326
+ }
8327
+
8328
+ return initialParams(function (args, callback) {
8329
+ var result;
8330
+ try {
8331
+ result = func.apply(this, args);
8332
+ } catch (e) {
8333
+ return callback(e);
8334
+ }
8335
+ // if result is Promise object
8336
+ if (result && typeof result.then === 'function') {
8337
+ return handlePromise(result, callback)
8338
+ } else {
8339
+ callback(null, result);
8340
+ }
8341
+ });
8342
+ }
8343
+
8344
+ function handlePromise(promise, callback) {
8345
+ return promise.then(value => {
8346
+ invokeCallback(callback, null, value);
8347
+ }, err => {
8348
+ invokeCallback(callback, err && err.message ? err : new Error(err));
8349
+ });
8350
+ }
8351
+
8352
+ function invokeCallback(callback, error, value) {
8353
+ try {
8354
+ callback(error, value);
8355
+ } catch (err) {
8356
+ setImmediate$1(e => { throw e }, err);
8357
+ }
8358
+ }
8359
+
8360
+ function isAsync(fn) {
8361
+ return fn[Symbol.toStringTag] === 'AsyncFunction';
8362
+ }
8363
+
8364
+ function isAsyncGenerator(fn) {
8365
+ return fn[Symbol.toStringTag] === 'AsyncGenerator';
8366
+ }
8367
+
8368
+ function isAsyncIterable(obj) {
8369
+ return typeof obj[Symbol.asyncIterator] === 'function';
8370
+ }
8371
+
8372
+ function wrapAsync(asyncFn) {
8373
+ if (typeof asyncFn !== 'function') throw new Error('expected a function')
8374
+ return isAsync(asyncFn) ? asyncify(asyncFn) : asyncFn;
8375
+ }
8376
+
8377
+ // conditionally promisify a function.
8378
+ // only return a promise if a callback is omitted
8379
+ function awaitify (asyncFn, arity = asyncFn.length) {
8380
+ if (!arity) throw new Error('arity is undefined')
8381
+ function awaitable (...args) {
8382
+ if (typeof args[arity - 1] === 'function') {
8383
+ return asyncFn.apply(this, args)
8384
+ }
8385
+
8386
+ return new Promise((resolve, reject) => {
8387
+ args[arity - 1] = (err, ...cbArgs) => {
8388
+ if (err) return reject(err)
8389
+ resolve(cbArgs.length > 1 ? cbArgs : cbArgs[0]);
8390
+ };
8391
+ asyncFn.apply(this, args);
8392
+ })
8393
+ }
8394
+
8395
+ return awaitable
8396
+ }
8397
+
8398
+ function _asyncMap(eachfn, arr, iteratee, callback) {
8399
+ arr = arr || [];
8400
+ var results = [];
8401
+ var counter = 0;
8402
+ var _iteratee = wrapAsync(iteratee);
8403
+
8404
+ return eachfn(arr, (value, _, iterCb) => {
8405
+ var index = counter++;
8406
+ _iteratee(value, (err, v) => {
8407
+ results[index] = v;
8408
+ iterCb(err);
8409
+ });
8410
+ }, err => {
8411
+ callback(err, results);
8412
+ });
8413
+ }
8414
+
8415
+ function isArrayLike(value) {
8416
+ return value &&
8417
+ typeof value.length === 'number' &&
8418
+ value.length >= 0 &&
8419
+ value.length % 1 === 0;
8420
+ }
8421
+
8422
+ // A temporary value used to identify if the loop should be broken.
8423
+ // See #1064, #1293
8424
+ const breakLoop = {};
8425
+
8426
+ function once$1(fn) {
8427
+ function wrapper (...args) {
8428
+ if (fn === null) return;
8429
+ var callFn = fn;
8430
+ fn = null;
8431
+ callFn.apply(this, args);
8432
+ }
8433
+ Object.assign(wrapper, fn);
8434
+ return wrapper
8435
+ }
8436
+
8437
+ function getIterator (coll) {
8438
+ return coll[Symbol.iterator] && coll[Symbol.iterator]();
8439
+ }
8440
+
8441
+ function createArrayIterator(coll) {
8442
+ var i = -1;
8443
+ var len = coll.length;
8444
+ return function next() {
8445
+ return ++i < len ? {value: coll[i], key: i} : null;
8446
+ }
8447
+ }
8448
+
8449
+ function createES2015Iterator(iterator) {
8450
+ var i = -1;
8451
+ return function next() {
8452
+ var item = iterator.next();
8453
+ if (item.done)
8454
+ return null;
8455
+ i++;
8456
+ return {value: item.value, key: i};
8457
+ }
8458
+ }
8459
+
8460
+ function createObjectIterator(obj) {
8461
+ var okeys = obj ? Object.keys(obj) : [];
8462
+ var i = -1;
8463
+ var len = okeys.length;
8464
+ return function next() {
8465
+ var key = okeys[++i];
8466
+ if (key === '__proto__') {
8467
+ return next();
8468
+ }
8469
+ return i < len ? {value: obj[key], key} : null;
8470
+ };
8471
+ }
8472
+
8473
+ function createIterator(coll) {
8474
+ if (isArrayLike(coll)) {
8475
+ return createArrayIterator(coll);
8476
+ }
8477
+
8478
+ var iterator = getIterator(coll);
8479
+ return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll);
8480
+ }
8481
+
8482
+ function onlyOnce(fn) {
8483
+ return function (...args) {
8484
+ if (fn === null) throw new Error("Callback was already called.");
8485
+ var callFn = fn;
8486
+ fn = null;
8487
+ callFn.apply(this, args);
8488
+ };
8489
+ }
8490
+
8491
+ // for async generators
8492
+ function asyncEachOfLimit(generator, limit, iteratee, callback) {
8493
+ let done = false;
8494
+ let canceled = false;
8495
+ let awaiting = false;
8496
+ let running = 0;
8497
+ let idx = 0;
8498
+
8499
+ function replenish() {
8500
+ //console.log('replenish')
8501
+ if (running >= limit || awaiting || done) return
8502
+ //console.log('replenish awaiting')
8503
+ awaiting = true;
8504
+ generator.next().then(({value, done: iterDone}) => {
8505
+ //console.log('got value', value)
8506
+ if (canceled || done) return
8507
+ awaiting = false;
8508
+ if (iterDone) {
8509
+ done = true;
8510
+ if (running <= 0) {
8511
+ //console.log('done nextCb')
8512
+ callback(null);
8513
+ }
8514
+ return;
8515
+ }
8516
+ running++;
8517
+ iteratee(value, idx, iterateeCallback);
8518
+ idx++;
8519
+ replenish();
8520
+ }).catch(handleError);
8521
+ }
8522
+
8523
+ function iterateeCallback(err, result) {
8524
+ //console.log('iterateeCallback')
8525
+ running -= 1;
8526
+ if (canceled) return
8527
+ if (err) return handleError(err)
8528
+
8529
+ if (err === false) {
8530
+ done = true;
8531
+ canceled = true;
8532
+ return
8533
+ }
8534
+
8535
+ if (result === breakLoop || (done && running <= 0)) {
8536
+ done = true;
8537
+ //console.log('done iterCb')
8538
+ return callback(null);
8539
+ }
8540
+ replenish();
8541
+ }
8542
+
8543
+ function handleError(err) {
8544
+ if (canceled) return
8545
+ awaiting = false;
8546
+ done = true;
8547
+ callback(err);
8548
+ }
8549
+
8550
+ replenish();
8551
+ }
8552
+
8553
+ var eachOfLimit = (limit) => {
8554
+ return (obj, iteratee, callback) => {
8555
+ callback = once$1(callback);
8556
+ if (limit <= 0) {
8557
+ throw new RangeError('concurrency limit cannot be less than 1')
8558
+ }
8559
+ if (!obj) {
8560
+ return callback(null);
8561
+ }
8562
+ if (isAsyncGenerator(obj)) {
8563
+ return asyncEachOfLimit(obj, limit, iteratee, callback)
8564
+ }
8565
+ if (isAsyncIterable(obj)) {
8566
+ return asyncEachOfLimit(obj[Symbol.asyncIterator](), limit, iteratee, callback)
8567
+ }
8568
+ var nextElem = createIterator(obj);
8569
+ var done = false;
8570
+ var canceled = false;
8571
+ var running = 0;
8572
+ var looping = false;
8573
+
8574
+ function iterateeCallback(err, value) {
8575
+ if (canceled) return
8576
+ running -= 1;
8577
+ if (err) {
8578
+ done = true;
8579
+ callback(err);
8580
+ }
8581
+ else if (err === false) {
8582
+ done = true;
8583
+ canceled = true;
8584
+ }
8585
+ else if (value === breakLoop || (done && running <= 0)) {
8586
+ done = true;
8587
+ return callback(null);
8588
+ }
8589
+ else if (!looping) {
8590
+ replenish();
8591
+ }
8592
+ }
8593
+
8594
+ function replenish () {
8595
+ looping = true;
8596
+ while (running < limit && !done) {
8597
+ var elem = nextElem();
8598
+ if (elem === null) {
8599
+ done = true;
8600
+ if (running <= 0) {
8601
+ callback(null);
8602
+ }
8603
+ return;
8604
+ }
8605
+ running += 1;
8606
+ iteratee(elem.value, elem.key, onlyOnce(iterateeCallback));
8607
+ }
8608
+ looping = false;
8609
+ }
8610
+
8611
+ replenish();
8612
+ };
8613
+ };
8614
+
8615
+ /**
8616
+ * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a
8617
+ * time.
8618
+ *
8619
+ * @name eachOfLimit
8620
+ * @static
8621
+ * @memberOf module:Collections
8622
+ * @method
8623
+ * @see [async.eachOf]{@link module:Collections.eachOf}
8624
+ * @alias forEachOfLimit
8625
+ * @category Collection
8626
+ * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
8627
+ * @param {number} limit - The maximum number of async operations at a time.
8628
+ * @param {AsyncFunction} iteratee - An async function to apply to each
8629
+ * item in `coll`. The `key` is the item's key, or index in the case of an
8630
+ * array.
8631
+ * Invoked with (item, key, callback).
8632
+ * @param {Function} [callback] - A callback which is called when all
8633
+ * `iteratee` functions have finished, or an error occurs. Invoked with (err).
8634
+ * @returns {Promise} a promise, if a callback is omitted
8635
+ */
8636
+ function eachOfLimit$1(coll, limit, iteratee, callback) {
8637
+ return eachOfLimit(limit)(coll, wrapAsync(iteratee), callback);
8638
+ }
8639
+
8640
+ var eachOfLimit$2 = awaitify(eachOfLimit$1, 4);
8641
+
8642
+ // eachOf implementation optimized for array-likes
8643
+ function eachOfArrayLike(coll, iteratee, callback) {
8644
+ callback = once$1(callback);
8645
+ var index = 0,
8646
+ completed = 0,
8647
+ {length} = coll,
8648
+ canceled = false;
8649
+ if (length === 0) {
8650
+ callback(null);
8651
+ }
8652
+
8653
+ function iteratorCallback(err, value) {
8654
+ if (err === false) {
8655
+ canceled = true;
8656
+ }
8657
+ if (canceled === true) return
8658
+ if (err) {
8659
+ callback(err);
8660
+ } else if ((++completed === length) || value === breakLoop) {
8661
+ callback(null);
8662
+ }
8663
+ }
8664
+
8665
+ for (; index < length; index++) {
8666
+ iteratee(coll[index], index, onlyOnce(iteratorCallback));
8667
+ }
8668
+ }
8669
+
8670
+ // a generic version of eachOf which can handle array, object, and iterator cases.
8671
+ function eachOfGeneric (coll, iteratee, callback) {
8672
+ return eachOfLimit$2(coll, Infinity, iteratee, callback);
8673
+ }
8674
+
8675
+ /**
8676
+ * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument
8677
+ * to the iteratee.
8678
+ *
8679
+ * @name eachOf
8680
+ * @static
8681
+ * @memberOf module:Collections
8682
+ * @method
8683
+ * @alias forEachOf
8684
+ * @category Collection
8685
+ * @see [async.each]{@link module:Collections.each}
8686
+ * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
8687
+ * @param {AsyncFunction} iteratee - A function to apply to each
8688
+ * item in `coll`.
8689
+ * The `key` is the item's key, or index in the case of an array.
8690
+ * Invoked with (item, key, callback).
8691
+ * @param {Function} [callback] - A callback which is called when all
8692
+ * `iteratee` functions have finished, or an error occurs. Invoked with (err).
8693
+ * @returns {Promise} a promise, if a callback is omitted
8694
+ * @example
8695
+ *
8696
+ * // dev.json is a file containing a valid json object config for dev environment
8697
+ * // dev.json is a file containing a valid json object config for test environment
8698
+ * // prod.json is a file containing a valid json object config for prod environment
8699
+ * // invalid.json is a file with a malformed json object
8700
+ *
8701
+ * let configs = {}; //global variable
8702
+ * let validConfigFileMap = {dev: 'dev.json', test: 'test.json', prod: 'prod.json'};
8703
+ * let invalidConfigFileMap = {dev: 'dev.json', test: 'test.json', invalid: 'invalid.json'};
8704
+ *
8705
+ * // asynchronous function that reads a json file and parses the contents as json object
8706
+ * function parseFile(file, key, callback) {
8707
+ * fs.readFile(file, "utf8", function(err, data) {
8708
+ * if (err) return calback(err);
8709
+ * try {
8710
+ * configs[key] = JSON.parse(data);
8711
+ * } catch (e) {
8712
+ * return callback(e);
8713
+ * }
8714
+ * callback();
8715
+ * });
8716
+ * }
8717
+ *
8718
+ * // Using callbacks
8719
+ * async.forEachOf(validConfigFileMap, parseFile, function (err) {
8720
+ * if (err) {
8721
+ * console.error(err);
8722
+ * } else {
8723
+ * console.log(configs);
8724
+ * // configs is now a map of JSON data, e.g.
8725
+ * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json}
8726
+ * }
8727
+ * });
8728
+ *
8729
+ * //Error handing
8730
+ * async.forEachOf(invalidConfigFileMap, parseFile, function (err) {
8731
+ * if (err) {
8732
+ * console.error(err);
8733
+ * // JSON parse error exception
8734
+ * } else {
8735
+ * console.log(configs);
8736
+ * }
8737
+ * });
8738
+ *
8739
+ * // Using Promises
8740
+ * async.forEachOf(validConfigFileMap, parseFile)
8741
+ * .then( () => {
8742
+ * console.log(configs);
8743
+ * // configs is now a map of JSON data, e.g.
8744
+ * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json}
8745
+ * }).catch( err => {
8746
+ * console.error(err);
8747
+ * });
8748
+ *
8749
+ * //Error handing
8750
+ * async.forEachOf(invalidConfigFileMap, parseFile)
8751
+ * .then( () => {
8752
+ * console.log(configs);
8753
+ * }).catch( err => {
8754
+ * console.error(err);
8755
+ * // JSON parse error exception
8756
+ * });
8757
+ *
8758
+ * // Using async/await
8759
+ * async () => {
8760
+ * try {
8761
+ * let result = await async.forEachOf(validConfigFileMap, parseFile);
8762
+ * console.log(configs);
8763
+ * // configs is now a map of JSON data, e.g.
8764
+ * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json}
8765
+ * }
8766
+ * catch (err) {
8767
+ * console.log(err);
8768
+ * }
8769
+ * }
8770
+ *
8771
+ * //Error handing
8772
+ * async () => {
8773
+ * try {
8774
+ * let result = await async.forEachOf(invalidConfigFileMap, parseFile);
8775
+ * console.log(configs);
8776
+ * }
8777
+ * catch (err) {
8778
+ * console.log(err);
8779
+ * // JSON parse error exception
8780
+ * }
8781
+ * }
8782
+ *
8783
+ */
8784
+ function eachOf(coll, iteratee, callback) {
8785
+ var eachOfImplementation = isArrayLike(coll) ? eachOfArrayLike : eachOfGeneric;
8786
+ return eachOfImplementation(coll, wrapAsync(iteratee), callback);
8787
+ }
8788
+
8789
+ var eachOf$1 = awaitify(eachOf, 3);
8790
+
8791
+ /**
8792
+ * Produces a new collection of values by mapping each value in `coll` through
8793
+ * the `iteratee` function. The `iteratee` is called with an item from `coll`
8794
+ * and a callback for when it has finished processing. Each of these callbacks
8795
+ * takes 2 arguments: an `error`, and the transformed item from `coll`. If
8796
+ * `iteratee` passes an error to its callback, the main `callback` (for the
8797
+ * `map` function) is immediately called with the error.
8798
+ *
8799
+ * Note, that since this function applies the `iteratee` to each item in
8800
+ * parallel, there is no guarantee that the `iteratee` functions will complete
8801
+ * in order. However, the results array will be in the same order as the
8802
+ * original `coll`.
8803
+ *
8804
+ * If `map` is passed an Object, the results will be an Array. The results
8805
+ * will roughly be in the order of the original Objects' keys (but this can
8806
+ * vary across JavaScript engines).
8807
+ *
8808
+ * @name map
8809
+ * @static
8810
+ * @memberOf module:Collections
8811
+ * @method
8812
+ * @category Collection
8813
+ * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
8814
+ * @param {AsyncFunction} iteratee - An async function to apply to each item in
8815
+ * `coll`.
8816
+ * The iteratee should complete with the transformed item.
8817
+ * Invoked with (item, callback).
8818
+ * @param {Function} [callback] - A callback which is called when all `iteratee`
8819
+ * functions have finished, or an error occurs. Results is an Array of the
8820
+ * transformed items from the `coll`. Invoked with (err, results).
8821
+ * @returns {Promise} a promise, if no callback is passed
8822
+ * @example
8823
+ *
8824
+ * // file1.txt is a file that is 1000 bytes in size
8825
+ * // file2.txt is a file that is 2000 bytes in size
8826
+ * // file3.txt is a file that is 3000 bytes in size
8827
+ * // file4.txt does not exist
8828
+ *
8829
+ * const fileList = ['file1.txt','file2.txt','file3.txt'];
8830
+ * const withMissingFileList = ['file1.txt','file2.txt','file4.txt'];
8831
+ *
8832
+ * // asynchronous function that returns the file size in bytes
8833
+ * function getFileSizeInBytes(file, callback) {
8834
+ * fs.stat(file, function(err, stat) {
8835
+ * if (err) {
8836
+ * return callback(err);
8837
+ * }
8838
+ * callback(null, stat.size);
8839
+ * });
8840
+ * }
8841
+ *
8842
+ * // Using callbacks
8843
+ * async.map(fileList, getFileSizeInBytes, function(err, results) {
8844
+ * if (err) {
8845
+ * console.log(err);
8846
+ * } else {
8847
+ * console.log(results);
8848
+ * // results is now an array of the file size in bytes for each file, e.g.
8849
+ * // [ 1000, 2000, 3000]
8850
+ * }
8851
+ * });
8852
+ *
8853
+ * // Error Handling
8854
+ * async.map(withMissingFileList, getFileSizeInBytes, function(err, results) {
8855
+ * if (err) {
8856
+ * console.log(err);
8857
+ * // [ Error: ENOENT: no such file or directory ]
8858
+ * } else {
8859
+ * console.log(results);
8860
+ * }
8861
+ * });
8862
+ *
8863
+ * // Using Promises
8864
+ * async.map(fileList, getFileSizeInBytes)
8865
+ * .then( results => {
8866
+ * console.log(results);
8867
+ * // results is now an array of the file size in bytes for each file, e.g.
8868
+ * // [ 1000, 2000, 3000]
8869
+ * }).catch( err => {
8870
+ * console.log(err);
8871
+ * });
8872
+ *
8873
+ * // Error Handling
8874
+ * async.map(withMissingFileList, getFileSizeInBytes)
8875
+ * .then( results => {
8876
+ * console.log(results);
8877
+ * }).catch( err => {
8878
+ * console.log(err);
8879
+ * // [ Error: ENOENT: no such file or directory ]
8880
+ * });
8881
+ *
8882
+ * // Using async/await
8883
+ * async () => {
8884
+ * try {
8885
+ * let results = await async.map(fileList, getFileSizeInBytes);
8886
+ * console.log(results);
8887
+ * // results is now an array of the file size in bytes for each file, e.g.
8888
+ * // [ 1000, 2000, 3000]
8889
+ * }
8890
+ * catch (err) {
8891
+ * console.log(err);
8892
+ * }
8893
+ * }
8894
+ *
8895
+ * // Error Handling
8896
+ * async () => {
8897
+ * try {
8898
+ * let results = await async.map(withMissingFileList, getFileSizeInBytes);
8899
+ * console.log(results);
8900
+ * }
8901
+ * catch (err) {
8902
+ * console.log(err);
8903
+ * // [ Error: ENOENT: no such file or directory ]
8904
+ * }
8905
+ * }
8906
+ *
8907
+ */
8908
+ function map (coll, iteratee, callback) {
8909
+ return _asyncMap(eachOf$1, coll, iteratee, callback)
8910
+ }
8911
+ var map$1 = awaitify(map, 3);
8912
+
8913
+ /**
8914
+ * The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time.
8915
+ *
8916
+ * @name eachOfSeries
8917
+ * @static
8918
+ * @memberOf module:Collections
8919
+ * @method
8920
+ * @see [async.eachOf]{@link module:Collections.eachOf}
8921
+ * @alias forEachOfSeries
8922
+ * @category Collection
8923
+ * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
8924
+ * @param {AsyncFunction} iteratee - An async function to apply to each item in
8925
+ * `coll`.
8926
+ * Invoked with (item, key, callback).
8927
+ * @param {Function} [callback] - A callback which is called when all `iteratee`
8928
+ * functions have finished, or an error occurs. Invoked with (err).
8929
+ * @returns {Promise} a promise, if a callback is omitted
8930
+ */
8931
+ function eachOfSeries(coll, iteratee, callback) {
8932
+ return eachOfLimit$2(coll, 1, iteratee, callback)
8933
+ }
8934
+ var eachOfSeries$1 = awaitify(eachOfSeries, 3);
8935
+
8936
+ /**
8937
+ * The same as [`map`]{@link module:Collections.map} but runs only a single async operation at a time.
8938
+ *
8939
+ * @name mapSeries
8940
+ * @static
8941
+ * @memberOf module:Collections
8942
+ * @method
8943
+ * @see [async.map]{@link module:Collections.map}
8944
+ * @category Collection
8945
+ * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
8946
+ * @param {AsyncFunction} iteratee - An async function to apply to each item in
8947
+ * `coll`.
8948
+ * The iteratee should complete with the transformed item.
8949
+ * Invoked with (item, callback).
8950
+ * @param {Function} [callback] - A callback which is called when all `iteratee`
8951
+ * functions have finished, or an error occurs. Results is an array of the
8952
+ * transformed items from the `coll`. Invoked with (err, results).
8953
+ * @returns {Promise} a promise, if no callback is passed
8954
+ */
8955
+ function mapSeries (coll, iteratee, callback) {
8956
+ return _asyncMap(eachOfSeries$1, coll, iteratee, callback)
8957
+ }
8958
+ awaitify(mapSeries, 3);
8959
+
8960
+ // Simple doubly linked list (https://en.wikipedia.org/wiki/Doubly_linked_list) implementation
8961
+ // used for queues. This implementation assumes that the node provided by the user can be modified
8962
+ // to adjust the next and last properties. We implement only the minimal functionality
8963
+ // for queue support.
8964
+ class DLL {
8965
+ constructor() {
8966
+ this.head = this.tail = null;
8967
+ this.length = 0;
8968
+ }
8969
+
8970
+ removeLink(node) {
8971
+ if (node.prev) node.prev.next = node.next;
8972
+ else this.head = node.next;
8973
+ if (node.next) node.next.prev = node.prev;
8974
+ else this.tail = node.prev;
8975
+
8976
+ node.prev = node.next = null;
8977
+ this.length -= 1;
8978
+ return node;
8979
+ }
8980
+
8981
+ empty () {
8982
+ while(this.head) this.shift();
8983
+ return this;
8984
+ }
8985
+
8986
+ insertAfter(node, newNode) {
8987
+ newNode.prev = node;
8988
+ newNode.next = node.next;
8989
+ if (node.next) node.next.prev = newNode;
8990
+ else this.tail = newNode;
8991
+ node.next = newNode;
8992
+ this.length += 1;
8993
+ }
8994
+
8995
+ insertBefore(node, newNode) {
8996
+ newNode.prev = node.prev;
8997
+ newNode.next = node;
8998
+ if (node.prev) node.prev.next = newNode;
8999
+ else this.head = newNode;
9000
+ node.prev = newNode;
9001
+ this.length += 1;
9002
+ }
9003
+
9004
+ unshift(node) {
9005
+ if (this.head) this.insertBefore(this.head, node);
9006
+ else setInitial(this, node);
9007
+ }
9008
+
9009
+ push(node) {
9010
+ if (this.tail) this.insertAfter(this.tail, node);
9011
+ else setInitial(this, node);
9012
+ }
9013
+
9014
+ shift() {
9015
+ return this.head && this.removeLink(this.head);
9016
+ }
9017
+
9018
+ pop() {
9019
+ return this.tail && this.removeLink(this.tail);
9020
+ }
9021
+
9022
+ toArray() {
9023
+ return [...this]
9024
+ }
9025
+
9026
+ *[Symbol.iterator] () {
9027
+ var cur = this.head;
9028
+ while (cur) {
9029
+ yield cur.data;
9030
+ cur = cur.next;
9031
+ }
9032
+ }
9033
+
9034
+ remove (testFn) {
9035
+ var curr = this.head;
9036
+ while(curr) {
9037
+ var {next} = curr;
9038
+ if (testFn(curr)) {
9039
+ this.removeLink(curr);
9040
+ }
9041
+ curr = next;
9042
+ }
9043
+ return this;
9044
+ }
9045
+ }
9046
+
9047
+ function setInitial(dll, node) {
9048
+ dll.length = 1;
9049
+ dll.head = dll.tail = node;
9050
+ }
9051
+
9052
+ function queue(worker, concurrency, payload) {
9053
+ if (concurrency == null) {
9054
+ concurrency = 1;
9055
+ }
9056
+ else if(concurrency === 0) {
9057
+ throw new RangeError('Concurrency must not be zero');
9058
+ }
9059
+
9060
+ var _worker = wrapAsync(worker);
9061
+ var numRunning = 0;
9062
+ var workersList = [];
9063
+ const events = {
9064
+ error: [],
9065
+ drain: [],
9066
+ saturated: [],
9067
+ unsaturated: [],
9068
+ empty: []
9069
+ };
9070
+
9071
+ function on (event, handler) {
9072
+ events[event].push(handler);
9073
+ }
9074
+
9075
+ function once (event, handler) {
9076
+ const handleAndRemove = (...args) => {
9077
+ off(event, handleAndRemove);
9078
+ handler(...args);
9079
+ };
9080
+ events[event].push(handleAndRemove);
9081
+ }
9082
+
9083
+ function off (event, handler) {
9084
+ if (!event) return Object.keys(events).forEach(ev => events[ev] = [])
9085
+ if (!handler) return events[event] = []
9086
+ events[event] = events[event].filter(ev => ev !== handler);
9087
+ }
9088
+
9089
+ function trigger (event, ...args) {
9090
+ events[event].forEach(handler => handler(...args));
9091
+ }
9092
+
9093
+ var processingScheduled = false;
9094
+ function _insert(data, insertAtFront, rejectOnError, callback) {
9095
+ if (callback != null && typeof callback !== 'function') {
9096
+ throw new Error('task callback must be a function');
9097
+ }
9098
+ q.started = true;
9099
+
9100
+ var res, rej;
9101
+ function promiseCallback (err, ...args) {
9102
+ // we don't care about the error, let the global error handler
9103
+ // deal with it
9104
+ if (err) return rejectOnError ? rej(err) : res()
9105
+ if (args.length <= 1) return res(args[0])
9106
+ res(args);
9107
+ }
9108
+
9109
+ var item = q._createTaskItem(
9110
+ data,
9111
+ rejectOnError ? promiseCallback :
9112
+ (callback || promiseCallback)
9113
+ );
9114
+
9115
+ if (insertAtFront) {
9116
+ q._tasks.unshift(item);
9117
+ } else {
9118
+ q._tasks.push(item);
9119
+ }
9120
+
9121
+ if (!processingScheduled) {
9122
+ processingScheduled = true;
9123
+ setImmediate$1(() => {
9124
+ processingScheduled = false;
9125
+ q.process();
9126
+ });
9127
+ }
9128
+
9129
+ if (rejectOnError || !callback) {
9130
+ return new Promise((resolve, reject) => {
9131
+ res = resolve;
9132
+ rej = reject;
9133
+ })
9134
+ }
9135
+ }
9136
+
9137
+ function _createCB(tasks) {
9138
+ return function (err, ...args) {
9139
+ numRunning -= 1;
9140
+
9141
+ for (var i = 0, l = tasks.length; i < l; i++) {
9142
+ var task = tasks[i];
9143
+
9144
+ var index = workersList.indexOf(task);
9145
+ if (index === 0) {
9146
+ workersList.shift();
9147
+ } else if (index > 0) {
9148
+ workersList.splice(index, 1);
9149
+ }
9150
+
9151
+ task.callback(err, ...args);
9152
+
9153
+ if (err != null) {
9154
+ trigger('error', err, task.data);
9155
+ }
9156
+ }
9157
+
9158
+ if (numRunning <= (q.concurrency - q.buffer) ) {
9159
+ trigger('unsaturated');
9160
+ }
9161
+
9162
+ if (q.idle()) {
9163
+ trigger('drain');
9164
+ }
9165
+ q.process();
9166
+ };
9167
+ }
9168
+
9169
+ function _maybeDrain(data) {
9170
+ if (data.length === 0 && q.idle()) {
9171
+ // call drain immediately if there are no tasks
9172
+ setImmediate$1(() => trigger('drain'));
9173
+ return true
9174
+ }
9175
+ return false
9176
+ }
9177
+
9178
+ const eventMethod = (name) => (handler) => {
9179
+ if (!handler) {
9180
+ return new Promise((resolve, reject) => {
9181
+ once(name, (err, data) => {
9182
+ if (err) return reject(err)
9183
+ resolve(data);
9184
+ });
9185
+ })
9186
+ }
9187
+ off(name);
9188
+ on(name, handler);
9189
+
9190
+ };
9191
+
9192
+ var isProcessing = false;
9193
+ var q = {
9194
+ _tasks: new DLL(),
9195
+ _createTaskItem (data, callback) {
9196
+ return {
9197
+ data,
9198
+ callback
9199
+ };
9200
+ },
9201
+ *[Symbol.iterator] () {
9202
+ yield* q._tasks[Symbol.iterator]();
9203
+ },
9204
+ concurrency,
9205
+ payload,
9206
+ buffer: concurrency / 4,
9207
+ started: false,
9208
+ paused: false,
9209
+ push (data, callback) {
9210
+ if (Array.isArray(data)) {
9211
+ if (_maybeDrain(data)) return
9212
+ return data.map(datum => _insert(datum, false, false, callback))
9213
+ }
9214
+ return _insert(data, false, false, callback);
9215
+ },
9216
+ pushAsync (data, callback) {
9217
+ if (Array.isArray(data)) {
9218
+ if (_maybeDrain(data)) return
9219
+ return data.map(datum => _insert(datum, false, true, callback))
9220
+ }
9221
+ return _insert(data, false, true, callback);
9222
+ },
9223
+ kill () {
9224
+ off();
9225
+ q._tasks.empty();
9226
+ },
9227
+ unshift (data, callback) {
9228
+ if (Array.isArray(data)) {
9229
+ if (_maybeDrain(data)) return
9230
+ return data.map(datum => _insert(datum, true, false, callback))
9231
+ }
9232
+ return _insert(data, true, false, callback);
9233
+ },
9234
+ unshiftAsync (data, callback) {
9235
+ if (Array.isArray(data)) {
9236
+ if (_maybeDrain(data)) return
9237
+ return data.map(datum => _insert(datum, true, true, callback))
9238
+ }
9239
+ return _insert(data, true, true, callback);
9240
+ },
9241
+ remove (testFn) {
9242
+ q._tasks.remove(testFn);
9243
+ },
9244
+ process () {
9245
+ // Avoid trying to start too many processing operations. This can occur
9246
+ // when callbacks resolve synchronously (#1267).
9247
+ if (isProcessing) {
9248
+ return;
9249
+ }
9250
+ isProcessing = true;
9251
+ while(!q.paused && numRunning < q.concurrency && q._tasks.length){
9252
+ var tasks = [], data = [];
9253
+ var l = q._tasks.length;
9254
+ if (q.payload) l = Math.min(l, q.payload);
9255
+ for (var i = 0; i < l; i++) {
9256
+ var node = q._tasks.shift();
9257
+ tasks.push(node);
9258
+ workersList.push(node);
9259
+ data.push(node.data);
9260
+ }
9261
+
9262
+ numRunning += 1;
9263
+
9264
+ if (q._tasks.length === 0) {
9265
+ trigger('empty');
9266
+ }
9267
+
9268
+ if (numRunning === q.concurrency) {
9269
+ trigger('saturated');
9270
+ }
9271
+
9272
+ var cb = onlyOnce(_createCB(tasks));
9273
+ _worker(data, cb);
9274
+ }
9275
+ isProcessing = false;
9276
+ },
9277
+ length () {
9278
+ return q._tasks.length;
9279
+ },
9280
+ running () {
9281
+ return numRunning;
9282
+ },
9283
+ workersList () {
9284
+ return workersList;
9285
+ },
9286
+ idle() {
9287
+ return q._tasks.length + numRunning === 0;
9288
+ },
9289
+ pause () {
9290
+ q.paused = true;
9291
+ },
9292
+ resume () {
9293
+ if (q.paused === false) { return; }
9294
+ q.paused = false;
9295
+ setImmediate$1(q.process);
9296
+ }
9297
+ };
9298
+ // define these as fixed properties, so people get useful errors when updating
9299
+ Object.defineProperties(q, {
9300
+ saturated: {
9301
+ writable: false,
9302
+ value: eventMethod('saturated')
9303
+ },
9304
+ unsaturated: {
9305
+ writable: false,
9306
+ value: eventMethod('unsaturated')
9307
+ },
9308
+ empty: {
9309
+ writable: false,
9310
+ value: eventMethod('empty')
9311
+ },
9312
+ drain: {
9313
+ writable: false,
9314
+ value: eventMethod('drain')
9315
+ },
9316
+ error: {
9317
+ writable: false,
9318
+ value: eventMethod('error')
9319
+ },
9320
+ });
9321
+ return q;
9322
+ }
9323
+
9324
+ /**
9325
+ * Reduces `coll` into a single value using an async `iteratee` to return each
9326
+ * successive step. `memo` is the initial state of the reduction. This function
9327
+ * only operates in series.
9328
+ *
9329
+ * For performance reasons, it may make sense to split a call to this function
9330
+ * into a parallel map, and then use the normal `Array.prototype.reduce` on the
9331
+ * results. This function is for situations where each step in the reduction
9332
+ * needs to be async; if you can get the data before reducing it, then it's
9333
+ * probably a good idea to do so.
9334
+ *
9335
+ * @name reduce
9336
+ * @static
9337
+ * @memberOf module:Collections
9338
+ * @method
9339
+ * @alias inject
9340
+ * @alias foldl
9341
+ * @category Collection
9342
+ * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
9343
+ * @param {*} memo - The initial state of the reduction.
9344
+ * @param {AsyncFunction} iteratee - A function applied to each item in the
9345
+ * array to produce the next step in the reduction.
9346
+ * The `iteratee` should complete with the next state of the reduction.
9347
+ * If the iteratee completes with an error, the reduction is stopped and the
9348
+ * main `callback` is immediately called with the error.
9349
+ * Invoked with (memo, item, callback).
9350
+ * @param {Function} [callback] - A callback which is called after all the
9351
+ * `iteratee` functions have finished. Result is the reduced value. Invoked with
9352
+ * (err, result).
9353
+ * @returns {Promise} a promise, if no callback is passed
9354
+ * @example
9355
+ *
9356
+ * // file1.txt is a file that is 1000 bytes in size
9357
+ * // file2.txt is a file that is 2000 bytes in size
9358
+ * // file3.txt is a file that is 3000 bytes in size
9359
+ * // file4.txt does not exist
9360
+ *
9361
+ * const fileList = ['file1.txt','file2.txt','file3.txt'];
9362
+ * const withMissingFileList = ['file1.txt','file2.txt','file3.txt', 'file4.txt'];
9363
+ *
9364
+ * // asynchronous function that computes the file size in bytes
9365
+ * // file size is added to the memoized value, then returned
9366
+ * function getFileSizeInBytes(memo, file, callback) {
9367
+ * fs.stat(file, function(err, stat) {
9368
+ * if (err) {
9369
+ * return callback(err);
9370
+ * }
9371
+ * callback(null, memo + stat.size);
9372
+ * });
9373
+ * }
9374
+ *
9375
+ * // Using callbacks
9376
+ * async.reduce(fileList, 0, getFileSizeInBytes, function(err, result) {
9377
+ * if (err) {
9378
+ * console.log(err);
9379
+ * } else {
9380
+ * console.log(result);
9381
+ * // 6000
9382
+ * // which is the sum of the file sizes of the three files
9383
+ * }
9384
+ * });
9385
+ *
9386
+ * // Error Handling
9387
+ * async.reduce(withMissingFileList, 0, getFileSizeInBytes, function(err, result) {
9388
+ * if (err) {
9389
+ * console.log(err);
9390
+ * // [ Error: ENOENT: no such file or directory ]
9391
+ * } else {
9392
+ * console.log(result);
9393
+ * }
9394
+ * });
9395
+ *
9396
+ * // Using Promises
9397
+ * async.reduce(fileList, 0, getFileSizeInBytes)
9398
+ * .then( result => {
9399
+ * console.log(result);
9400
+ * // 6000
9401
+ * // which is the sum of the file sizes of the three files
9402
+ * }).catch( err => {
9403
+ * console.log(err);
9404
+ * });
9405
+ *
9406
+ * // Error Handling
9407
+ * async.reduce(withMissingFileList, 0, getFileSizeInBytes)
9408
+ * .then( result => {
9409
+ * console.log(result);
9410
+ * }).catch( err => {
9411
+ * console.log(err);
9412
+ * // [ Error: ENOENT: no such file or directory ]
9413
+ * });
9414
+ *
9415
+ * // Using async/await
9416
+ * async () => {
9417
+ * try {
9418
+ * let result = await async.reduce(fileList, 0, getFileSizeInBytes);
9419
+ * console.log(result);
9420
+ * // 6000
9421
+ * // which is the sum of the file sizes of the three files
9422
+ * }
9423
+ * catch (err) {
9424
+ * console.log(err);
9425
+ * }
9426
+ * }
9427
+ *
9428
+ * // Error Handling
9429
+ * async () => {
9430
+ * try {
9431
+ * let result = await async.reduce(withMissingFileList, 0, getFileSizeInBytes);
9432
+ * console.log(result);
9433
+ * }
9434
+ * catch (err) {
9435
+ * console.log(err);
9436
+ * // [ Error: ENOENT: no such file or directory ]
9437
+ * }
9438
+ * }
9439
+ *
9440
+ */
9441
+ function reduce(coll, memo, iteratee, callback) {
9442
+ callback = once$1(callback);
9443
+ var _iteratee = wrapAsync(iteratee);
9444
+ return eachOfSeries$1(coll, (x, i, iterCb) => {
9445
+ _iteratee(memo, x, (err, v) => {
9446
+ memo = v;
9447
+ iterCb(err);
9448
+ });
9449
+ }, err => callback(err, memo));
9450
+ }
9451
+ awaitify(reduce, 4);
9452
+
9453
+ /**
9454
+ * The same as [`map`]{@link module:Collections.map} but runs a maximum of `limit` async operations at a time.
9455
+ *
9456
+ * @name mapLimit
9457
+ * @static
9458
+ * @memberOf module:Collections
9459
+ * @method
9460
+ * @see [async.map]{@link module:Collections.map}
9461
+ * @category Collection
9462
+ * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
9463
+ * @param {number} limit - The maximum number of async operations at a time.
9464
+ * @param {AsyncFunction} iteratee - An async function to apply to each item in
9465
+ * `coll`.
9466
+ * The iteratee should complete with the transformed item.
9467
+ * Invoked with (item, callback).
9468
+ * @param {Function} [callback] - A callback which is called when all `iteratee`
9469
+ * functions have finished, or an error occurs. Results is an array of the
9470
+ * transformed items from the `coll`. Invoked with (err, results).
9471
+ * @returns {Promise} a promise, if no callback is passed
9472
+ */
9473
+ function mapLimit (coll, limit, iteratee, callback) {
9474
+ return _asyncMap(eachOfLimit(limit), coll, iteratee, callback)
9475
+ }
9476
+ var mapLimit$1 = awaitify(mapLimit, 4);
9477
+
9478
+ /**
9479
+ * The same as [`concat`]{@link module:Collections.concat} but runs a maximum of `limit` async operations at a time.
9480
+ *
9481
+ * @name concatLimit
9482
+ * @static
9483
+ * @memberOf module:Collections
9484
+ * @method
9485
+ * @see [async.concat]{@link module:Collections.concat}
9486
+ * @category Collection
9487
+ * @alias flatMapLimit
9488
+ * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
9489
+ * @param {number} limit - The maximum number of async operations at a time.
9490
+ * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`,
9491
+ * which should use an array as its result. Invoked with (item, callback).
9492
+ * @param {Function} [callback] - A callback which is called after all the
9493
+ * `iteratee` functions have finished, or an error occurs. Results is an array
9494
+ * containing the concatenated results of the `iteratee` function. Invoked with
9495
+ * (err, results).
9496
+ * @returns A Promise, if no callback is passed
9497
+ */
9498
+ function concatLimit(coll, limit, iteratee, callback) {
9499
+ var _iteratee = wrapAsync(iteratee);
9500
+ return mapLimit$1(coll, limit, (val, iterCb) => {
9501
+ _iteratee(val, (err, ...args) => {
9502
+ if (err) return iterCb(err);
9503
+ return iterCb(err, args);
9504
+ });
9505
+ }, (err, mapResults) => {
9506
+ var result = [];
9507
+ for (var i = 0; i < mapResults.length; i++) {
9508
+ if (mapResults[i]) {
9509
+ result = result.concat(...mapResults[i]);
9510
+ }
9511
+ }
9512
+
9513
+ return callback(err, result);
9514
+ });
9515
+ }
9516
+ var concatLimit$1 = awaitify(concatLimit, 4);
9517
+
9518
+ /**
9519
+ * Applies `iteratee` to each item in `coll`, concatenating the results. Returns
9520
+ * the concatenated list. The `iteratee`s are called in parallel, and the
9521
+ * results are concatenated as they return. The results array will be returned in
9522
+ * the original order of `coll` passed to the `iteratee` function.
9523
+ *
9524
+ * @name concat
9525
+ * @static
9526
+ * @memberOf module:Collections
9527
+ * @method
9528
+ * @category Collection
9529
+ * @alias flatMap
9530
+ * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
9531
+ * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`,
9532
+ * which should use an array as its result. Invoked with (item, callback).
9533
+ * @param {Function} [callback] - A callback which is called after all the
9534
+ * `iteratee` functions have finished, or an error occurs. Results is an array
9535
+ * containing the concatenated results of the `iteratee` function. Invoked with
9536
+ * (err, results).
9537
+ * @returns A Promise, if no callback is passed
9538
+ * @example
9539
+ *
9540
+ * // dir1 is a directory that contains file1.txt, file2.txt
9541
+ * // dir2 is a directory that contains file3.txt, file4.txt
9542
+ * // dir3 is a directory that contains file5.txt
9543
+ * // dir4 does not exist
9544
+ *
9545
+ * let directoryList = ['dir1','dir2','dir3'];
9546
+ * let withMissingDirectoryList = ['dir1','dir2','dir3', 'dir4'];
9547
+ *
9548
+ * // Using callbacks
9549
+ * async.concat(directoryList, fs.readdir, function(err, results) {
9550
+ * if (err) {
9551
+ * console.log(err);
9552
+ * } else {
9553
+ * console.log(results);
9554
+ * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ]
9555
+ * }
9556
+ * });
9557
+ *
9558
+ * // Error Handling
9559
+ * async.concat(withMissingDirectoryList, fs.readdir, function(err, results) {
9560
+ * if (err) {
9561
+ * console.log(err);
9562
+ * // [ Error: ENOENT: no such file or directory ]
9563
+ * // since dir4 does not exist
9564
+ * } else {
9565
+ * console.log(results);
9566
+ * }
9567
+ * });
9568
+ *
9569
+ * // Using Promises
9570
+ * async.concat(directoryList, fs.readdir)
9571
+ * .then(results => {
9572
+ * console.log(results);
9573
+ * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ]
9574
+ * }).catch(err => {
9575
+ * console.log(err);
9576
+ * });
9577
+ *
9578
+ * // Error Handling
9579
+ * async.concat(withMissingDirectoryList, fs.readdir)
9580
+ * .then(results => {
9581
+ * console.log(results);
9582
+ * }).catch(err => {
9583
+ * console.log(err);
9584
+ * // [ Error: ENOENT: no such file or directory ]
9585
+ * // since dir4 does not exist
9586
+ * });
9587
+ *
9588
+ * // Using async/await
9589
+ * async () => {
9590
+ * try {
9591
+ * let results = await async.concat(directoryList, fs.readdir);
9592
+ * console.log(results);
9593
+ * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ]
9594
+ * } catch (err) {
9595
+ * console.log(err);
9596
+ * }
9597
+ * }
9598
+ *
9599
+ * // Error Handling
9600
+ * async () => {
9601
+ * try {
9602
+ * let results = await async.concat(withMissingDirectoryList, fs.readdir);
9603
+ * console.log(results);
9604
+ * } catch (err) {
9605
+ * console.log(err);
9606
+ * // [ Error: ENOENT: no such file or directory ]
9607
+ * // since dir4 does not exist
9608
+ * }
9609
+ * }
9610
+ *
9611
+ */
9612
+ function concat(coll, iteratee, callback) {
9613
+ return concatLimit$1(coll, Infinity, iteratee, callback)
9614
+ }
9615
+ awaitify(concat, 3);
9616
+
9617
+ /**
9618
+ * The same as [`concat`]{@link module:Collections.concat} but runs only a single async operation at a time.
9619
+ *
9620
+ * @name concatSeries
9621
+ * @static
9622
+ * @memberOf module:Collections
9623
+ * @method
9624
+ * @see [async.concat]{@link module:Collections.concat}
9625
+ * @category Collection
9626
+ * @alias flatMapSeries
9627
+ * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
9628
+ * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`.
9629
+ * The iteratee should complete with an array an array of results.
9630
+ * Invoked with (item, callback).
9631
+ * @param {Function} [callback] - A callback which is called after all the
9632
+ * `iteratee` functions have finished, or an error occurs. Results is an array
9633
+ * containing the concatenated results of the `iteratee` function. Invoked with
9634
+ * (err, results).
9635
+ * @returns A Promise, if no callback is passed
9636
+ */
9637
+ function concatSeries(coll, iteratee, callback) {
9638
+ return concatLimit$1(coll, 1, iteratee, callback)
9639
+ }
9640
+ awaitify(concatSeries, 3);
9641
+
9642
+ function _createTester(check, getResult) {
9643
+ return (eachfn, arr, _iteratee, cb) => {
9644
+ var testPassed = false;
9645
+ var testResult;
9646
+ const iteratee = wrapAsync(_iteratee);
9647
+ eachfn(arr, (value, _, callback) => {
9648
+ iteratee(value, (err, result) => {
9649
+ if (err || err === false) return callback(err);
9650
+
9651
+ if (check(result) && !testResult) {
9652
+ testPassed = true;
9653
+ testResult = getResult(true, value);
9654
+ return callback(null, breakLoop);
9655
+ }
9656
+ callback();
9657
+ });
9658
+ }, err => {
9659
+ if (err) return cb(err);
9660
+ cb(null, testPassed ? testResult : getResult(false));
9661
+ });
9662
+ };
9663
+ }
9664
+
9665
+ /**
9666
+ * Returns the first value in `coll` that passes an async truth test. The
9667
+ * `iteratee` is applied in parallel, meaning the first iteratee to return
9668
+ * `true` will fire the detect `callback` with that result. That means the
9669
+ * result might not be the first item in the original `coll` (in terms of order)
9670
+ * that passes the test.
9671
+
9672
+ * If order within the original `coll` is important, then look at
9673
+ * [`detectSeries`]{@link module:Collections.detectSeries}.
9674
+ *
9675
+ * @name detect
9676
+ * @static
9677
+ * @memberOf module:Collections
9678
+ * @method
9679
+ * @alias find
9680
+ * @category Collections
9681
+ * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
9682
+ * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`.
9683
+ * The iteratee must complete with a boolean value as its result.
9684
+ * Invoked with (item, callback).
9685
+ * @param {Function} [callback] - A callback which is called as soon as any
9686
+ * iteratee returns `true`, or after all the `iteratee` functions have finished.
9687
+ * Result will be the first item in the array that passes the truth test
9688
+ * (iteratee) or the value `undefined` if none passed. Invoked with
9689
+ * (err, result).
9690
+ * @returns {Promise} a promise, if a callback is omitted
9691
+ * @example
9692
+ *
9693
+ * // dir1 is a directory that contains file1.txt, file2.txt
9694
+ * // dir2 is a directory that contains file3.txt, file4.txt
9695
+ * // dir3 is a directory that contains file5.txt
9696
+ *
9697
+ * // asynchronous function that checks if a file exists
9698
+ * function fileExists(file, callback) {
9699
+ * fs.access(file, fs.constants.F_OK, (err) => {
9700
+ * callback(null, !err);
9701
+ * });
9702
+ * }
9703
+ *
9704
+ * async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists,
9705
+ * function(err, result) {
9706
+ * console.log(result);
9707
+ * // dir1/file1.txt
9708
+ * // result now equals the first file in the list that exists
9709
+ * }
9710
+ *);
9711
+ *
9712
+ * // Using Promises
9713
+ * async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists)
9714
+ * .then(result => {
9715
+ * console.log(result);
9716
+ * // dir1/file1.txt
9717
+ * // result now equals the first file in the list that exists
9718
+ * }).catch(err => {
9719
+ * console.log(err);
9720
+ * });
9721
+ *
9722
+ * // Using async/await
9723
+ * async () => {
9724
+ * try {
9725
+ * let result = await async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists);
9726
+ * console.log(result);
9727
+ * // dir1/file1.txt
9728
+ * // result now equals the file in the list that exists
9729
+ * }
9730
+ * catch (err) {
9731
+ * console.log(err);
9732
+ * }
9733
+ * }
9734
+ *
9735
+ */
9736
+ function detect(coll, iteratee, callback) {
9737
+ return _createTester(bool => bool, (res, item) => item)(eachOf$1, coll, iteratee, callback)
9738
+ }
9739
+ awaitify(detect, 3);
9740
+
9741
+ /**
9742
+ * The same as [`detect`]{@link module:Collections.detect} but runs a maximum of `limit` async operations at a
9743
+ * time.
9744
+ *
9745
+ * @name detectLimit
9746
+ * @static
9747
+ * @memberOf module:Collections
9748
+ * @method
9749
+ * @see [async.detect]{@link module:Collections.detect}
9750
+ * @alias findLimit
9751
+ * @category Collections
9752
+ * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
9753
+ * @param {number} limit - The maximum number of async operations at a time.
9754
+ * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`.
9755
+ * The iteratee must complete with a boolean value as its result.
9756
+ * Invoked with (item, callback).
9757
+ * @param {Function} [callback] - A callback which is called as soon as any
9758
+ * iteratee returns `true`, or after all the `iteratee` functions have finished.
9759
+ * Result will be the first item in the array that passes the truth test
9760
+ * (iteratee) or the value `undefined` if none passed. Invoked with
9761
+ * (err, result).
9762
+ * @returns {Promise} a promise, if a callback is omitted
9763
+ */
9764
+ function detectLimit(coll, limit, iteratee, callback) {
9765
+ return _createTester(bool => bool, (res, item) => item)(eachOfLimit(limit), coll, iteratee, callback)
9766
+ }
9767
+ awaitify(detectLimit, 4);
9768
+
9769
+ /**
9770
+ * The same as [`detect`]{@link module:Collections.detect} but runs only a single async operation at a time.
9771
+ *
9772
+ * @name detectSeries
9773
+ * @static
9774
+ * @memberOf module:Collections
9775
+ * @method
9776
+ * @see [async.detect]{@link module:Collections.detect}
9777
+ * @alias findSeries
9778
+ * @category Collections
9779
+ * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
9780
+ * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`.
9781
+ * The iteratee must complete with a boolean value as its result.
9782
+ * Invoked with (item, callback).
9783
+ * @param {Function} [callback] - A callback which is called as soon as any
9784
+ * iteratee returns `true`, or after all the `iteratee` functions have finished.
9785
+ * Result will be the first item in the array that passes the truth test
9786
+ * (iteratee) or the value `undefined` if none passed. Invoked with
9787
+ * (err, result).
9788
+ * @returns {Promise} a promise, if a callback is omitted
9789
+ */
9790
+ function detectSeries(coll, iteratee, callback) {
9791
+ return _createTester(bool => bool, (res, item) => item)(eachOfLimit(1), coll, iteratee, callback)
9792
+ }
9793
+
9794
+ awaitify(detectSeries, 3);
9795
+
9796
+ /**
9797
+ * The post-check version of [`whilst`]{@link module:ControlFlow.whilst}. To reflect the difference in
9798
+ * the order of operations, the arguments `test` and `iteratee` are switched.
9799
+ *
9800
+ * `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript.
9801
+ *
9802
+ * @name doWhilst
9803
+ * @static
9804
+ * @memberOf module:ControlFlow
9805
+ * @method
9806
+ * @see [async.whilst]{@link module:ControlFlow.whilst}
9807
+ * @category Control Flow
9808
+ * @param {AsyncFunction} iteratee - A function which is called each time `test`
9809
+ * passes. Invoked with (callback).
9810
+ * @param {AsyncFunction} test - asynchronous truth test to perform after each
9811
+ * execution of `iteratee`. Invoked with (...args, callback), where `...args` are the
9812
+ * non-error args from the previous callback of `iteratee`.
9813
+ * @param {Function} [callback] - A callback which is called after the test
9814
+ * function has failed and repeated execution of `iteratee` has stopped.
9815
+ * `callback` will be passed an error and any arguments passed to the final
9816
+ * `iteratee`'s callback. Invoked with (err, [results]);
9817
+ * @returns {Promise} a promise, if no callback is passed
9818
+ */
9819
+ function doWhilst(iteratee, test, callback) {
9820
+ callback = onlyOnce(callback);
9821
+ var _fn = wrapAsync(iteratee);
9822
+ var _test = wrapAsync(test);
9823
+ var results;
9824
+
9825
+ function next(err, ...args) {
9826
+ if (err) return callback(err);
9827
+ if (err === false) return;
9828
+ results = args;
9829
+ _test(...args, check);
9830
+ }
9831
+
9832
+ function check(err, truth) {
9833
+ if (err) return callback(err);
9834
+ if (err === false) return;
9835
+ if (!truth) return callback(null, ...results);
9836
+ _fn(next);
9837
+ }
9838
+
9839
+ return check(null, true);
9840
+ }
9841
+
9842
+ awaitify(doWhilst, 3);
9843
+
9844
+ function _withoutIndex(iteratee) {
9845
+ return (value, index, callback) => iteratee(value, callback);
9846
+ }
9847
+
9848
+ /**
9849
+ * Applies the function `iteratee` to each item in `coll`, in parallel.
9850
+ * The `iteratee` is called with an item from the list, and a callback for when
9851
+ * it has finished. If the `iteratee` passes an error to its `callback`, the
9852
+ * main `callback` (for the `each` function) is immediately called with the
9853
+ * error.
9854
+ *
9855
+ * Note, that since this function applies `iteratee` to each item in parallel,
9856
+ * there is no guarantee that the iteratee functions will complete in order.
9857
+ *
9858
+ * @name each
9859
+ * @static
9860
+ * @memberOf module:Collections
9861
+ * @method
9862
+ * @alias forEach
9863
+ * @category Collection
9864
+ * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
9865
+ * @param {AsyncFunction} iteratee - An async function to apply to
9866
+ * each item in `coll`. Invoked with (item, callback).
9867
+ * The array index is not passed to the iteratee.
9868
+ * If you need the index, use `eachOf`.
9869
+ * @param {Function} [callback] - A callback which is called when all
9870
+ * `iteratee` functions have finished, or an error occurs. Invoked with (err).
9871
+ * @returns {Promise} a promise, if a callback is omitted
9872
+ * @example
9873
+ *
9874
+ * // dir1 is a directory that contains file1.txt, file2.txt
9875
+ * // dir2 is a directory that contains file3.txt, file4.txt
9876
+ * // dir3 is a directory that contains file5.txt
9877
+ * // dir4 does not exist
9878
+ *
9879
+ * const fileList = [ 'dir1/file2.txt', 'dir2/file3.txt', 'dir/file5.txt'];
9880
+ * const withMissingFileList = ['dir1/file1.txt', 'dir4/file2.txt'];
9881
+ *
9882
+ * // asynchronous function that deletes a file
9883
+ * const deleteFile = function(file, callback) {
9884
+ * fs.unlink(file, callback);
9885
+ * };
9886
+ *
9887
+ * // Using callbacks
9888
+ * async.each(fileList, deleteFile, function(err) {
9889
+ * if( err ) {
9890
+ * console.log(err);
9891
+ * } else {
9892
+ * console.log('All files have been deleted successfully');
9893
+ * }
9894
+ * });
9895
+ *
9896
+ * // Error Handling
9897
+ * async.each(withMissingFileList, deleteFile, function(err){
9898
+ * console.log(err);
9899
+ * // [ Error: ENOENT: no such file or directory ]
9900
+ * // since dir4/file2.txt does not exist
9901
+ * // dir1/file1.txt could have been deleted
9902
+ * });
9903
+ *
9904
+ * // Using Promises
9905
+ * async.each(fileList, deleteFile)
9906
+ * .then( () => {
9907
+ * console.log('All files have been deleted successfully');
9908
+ * }).catch( err => {
9909
+ * console.log(err);
9910
+ * });
9911
+ *
9912
+ * // Error Handling
9913
+ * async.each(fileList, deleteFile)
9914
+ * .then( () => {
9915
+ * console.log('All files have been deleted successfully');
9916
+ * }).catch( err => {
9917
+ * console.log(err);
9918
+ * // [ Error: ENOENT: no such file or directory ]
9919
+ * // since dir4/file2.txt does not exist
9920
+ * // dir1/file1.txt could have been deleted
9921
+ * });
9922
+ *
9923
+ * // Using async/await
9924
+ * async () => {
9925
+ * try {
9926
+ * await async.each(files, deleteFile);
9927
+ * }
9928
+ * catch (err) {
9929
+ * console.log(err);
9930
+ * }
9931
+ * }
9932
+ *
9933
+ * // Error Handling
9934
+ * async () => {
9935
+ * try {
9936
+ * await async.each(withMissingFileList, deleteFile);
9937
+ * }
9938
+ * catch (err) {
9939
+ * console.log(err);
9940
+ * // [ Error: ENOENT: no such file or directory ]
9941
+ * // since dir4/file2.txt does not exist
9942
+ * // dir1/file1.txt could have been deleted
9943
+ * }
9944
+ * }
9945
+ *
9946
+ */
9947
+ function eachLimit(coll, iteratee, callback) {
9948
+ return eachOf$1(coll, _withoutIndex(wrapAsync(iteratee)), callback);
9949
+ }
9950
+
9951
+ awaitify(eachLimit, 3);
9952
+
9953
+ /**
9954
+ * The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time.
9955
+ *
9956
+ * @name eachLimit
9957
+ * @static
9958
+ * @memberOf module:Collections
9959
+ * @method
9960
+ * @see [async.each]{@link module:Collections.each}
9961
+ * @alias forEachLimit
9962
+ * @category Collection
9963
+ * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
9964
+ * @param {number} limit - The maximum number of async operations at a time.
9965
+ * @param {AsyncFunction} iteratee - An async function to apply to each item in
9966
+ * `coll`.
9967
+ * The array index is not passed to the iteratee.
9968
+ * If you need the index, use `eachOfLimit`.
9969
+ * Invoked with (item, callback).
9970
+ * @param {Function} [callback] - A callback which is called when all
9971
+ * `iteratee` functions have finished, or an error occurs. Invoked with (err).
9972
+ * @returns {Promise} a promise, if a callback is omitted
9973
+ */
9974
+ function eachLimit$1(coll, limit, iteratee, callback) {
9975
+ return eachOfLimit(limit)(coll, _withoutIndex(wrapAsync(iteratee)), callback);
9976
+ }
9977
+ var eachLimit$2 = awaitify(eachLimit$1, 4);
9978
+
9979
+ /**
9980
+ * The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time.
9981
+ *
9982
+ * Note, that unlike [`each`]{@link module:Collections.each}, this function applies iteratee to each item
9983
+ * in series and therefore the iteratee functions will complete in order.
9984
+
9985
+ * @name eachSeries
9986
+ * @static
9987
+ * @memberOf module:Collections
9988
+ * @method
9989
+ * @see [async.each]{@link module:Collections.each}
9990
+ * @alias forEachSeries
9991
+ * @category Collection
9992
+ * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
9993
+ * @param {AsyncFunction} iteratee - An async function to apply to each
9994
+ * item in `coll`.
9995
+ * The array index is not passed to the iteratee.
9996
+ * If you need the index, use `eachOfSeries`.
9997
+ * Invoked with (item, callback).
9998
+ * @param {Function} [callback] - A callback which is called when all
9999
+ * `iteratee` functions have finished, or an error occurs. Invoked with (err).
10000
+ * @returns {Promise} a promise, if a callback is omitted
10001
+ */
10002
+ function eachSeries(coll, iteratee, callback) {
10003
+ return eachLimit$2(coll, 1, iteratee, callback)
10004
+ }
10005
+ var eachSeries$1 = awaitify(eachSeries, 3);
10006
+
10007
+ /**
10008
+ * Wrap an async function and ensure it calls its callback on a later tick of
10009
+ * the event loop. If the function already calls its callback on a next tick,
10010
+ * no extra deferral is added. This is useful for preventing stack overflows
10011
+ * (`RangeError: Maximum call stack size exceeded`) and generally keeping
10012
+ * [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony)
10013
+ * contained. ES2017 `async` functions are returned as-is -- they are immune
10014
+ * to Zalgo's corrupting influences, as they always resolve on a later tick.
10015
+ *
10016
+ * @name ensureAsync
10017
+ * @static
10018
+ * @memberOf module:Utils
10019
+ * @method
10020
+ * @category Util
10021
+ * @param {AsyncFunction} fn - an async function, one that expects a node-style
10022
+ * callback as its last argument.
10023
+ * @returns {AsyncFunction} Returns a wrapped function with the exact same call
10024
+ * signature as the function passed in.
10025
+ * @example
10026
+ *
10027
+ * function sometimesAsync(arg, callback) {
10028
+ * if (cache[arg]) {
10029
+ * return callback(null, cache[arg]); // this would be synchronous!!
10030
+ * } else {
10031
+ * doSomeIO(arg, callback); // this IO would be asynchronous
10032
+ * }
10033
+ * }
10034
+ *
10035
+ * // this has a risk of stack overflows if many results are cached in a row
10036
+ * async.mapSeries(args, sometimesAsync, done);
10037
+ *
10038
+ * // this will defer sometimesAsync's callback if necessary,
10039
+ * // preventing stack overflows
10040
+ * async.mapSeries(args, async.ensureAsync(sometimesAsync), done);
10041
+ */
10042
+ function ensureAsync(fn) {
10043
+ if (isAsync(fn)) return fn;
10044
+ return function (...args/*, callback*/) {
10045
+ var callback = args.pop();
10046
+ var sync = true;
10047
+ args.push((...innerArgs) => {
10048
+ if (sync) {
10049
+ setImmediate$1(() => callback(...innerArgs));
10050
+ } else {
10051
+ callback(...innerArgs);
10052
+ }
10053
+ });
10054
+ fn.apply(this, args);
10055
+ sync = false;
10056
+ };
10057
+ }
10058
+
10059
+ /**
10060
+ * Returns `true` if every element in `coll` satisfies an async test. If any
10061
+ * iteratee call returns `false`, the main `callback` is immediately called.
10062
+ *
10063
+ * @name every
10064
+ * @static
10065
+ * @memberOf module:Collections
10066
+ * @method
10067
+ * @alias all
10068
+ * @category Collection
10069
+ * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
10070
+ * @param {AsyncFunction} iteratee - An async truth test to apply to each item
10071
+ * in the collection in parallel.
10072
+ * The iteratee must complete with a boolean result value.
10073
+ * Invoked with (item, callback).
10074
+ * @param {Function} [callback] - A callback which is called after all the
10075
+ * `iteratee` functions have finished. Result will be either `true` or `false`
10076
+ * depending on the values of the async tests. Invoked with (err, result).
10077
+ * @returns {Promise} a promise, if no callback provided
10078
+ * @example
10079
+ *
10080
+ * // dir1 is a directory that contains file1.txt, file2.txt
10081
+ * // dir2 is a directory that contains file3.txt, file4.txt
10082
+ * // dir3 is a directory that contains file5.txt
10083
+ * // dir4 does not exist
10084
+ *
10085
+ * const fileList = ['dir1/file1.txt','dir2/file3.txt','dir3/file5.txt'];
10086
+ * const withMissingFileList = ['file1.txt','file2.txt','file4.txt'];
10087
+ *
10088
+ * // asynchronous function that checks if a file exists
10089
+ * function fileExists(file, callback) {
10090
+ * fs.access(file, fs.constants.F_OK, (err) => {
10091
+ * callback(null, !err);
10092
+ * });
10093
+ * }
10094
+ *
10095
+ * // Using callbacks
10096
+ * async.every(fileList, fileExists, function(err, result) {
10097
+ * console.log(result);
10098
+ * // true
10099
+ * // result is true since every file exists
10100
+ * });
10101
+ *
10102
+ * async.every(withMissingFileList, fileExists, function(err, result) {
10103
+ * console.log(result);
10104
+ * // false
10105
+ * // result is false since NOT every file exists
10106
+ * });
10107
+ *
10108
+ * // Using Promises
10109
+ * async.every(fileList, fileExists)
10110
+ * .then( result => {
10111
+ * console.log(result);
10112
+ * // true
10113
+ * // result is true since every file exists
10114
+ * }).catch( err => {
10115
+ * console.log(err);
10116
+ * });
10117
+ *
10118
+ * async.every(withMissingFileList, fileExists)
10119
+ * .then( result => {
10120
+ * console.log(result);
10121
+ * // false
10122
+ * // result is false since NOT every file exists
10123
+ * }).catch( err => {
10124
+ * console.log(err);
10125
+ * });
10126
+ *
10127
+ * // Using async/await
10128
+ * async () => {
10129
+ * try {
10130
+ * let result = await async.every(fileList, fileExists);
10131
+ * console.log(result);
10132
+ * // true
10133
+ * // result is true since every file exists
10134
+ * }
10135
+ * catch (err) {
10136
+ * console.log(err);
10137
+ * }
10138
+ * }
10139
+ *
10140
+ * async () => {
10141
+ * try {
10142
+ * let result = await async.every(withMissingFileList, fileExists);
10143
+ * console.log(result);
10144
+ * // false
10145
+ * // result is false since NOT every file exists
10146
+ * }
10147
+ * catch (err) {
10148
+ * console.log(err);
10149
+ * }
10150
+ * }
10151
+ *
10152
+ */
10153
+ function every(coll, iteratee, callback) {
10154
+ return _createTester(bool => !bool, res => !res)(eachOf$1, coll, iteratee, callback)
10155
+ }
10156
+ awaitify(every, 3);
10157
+
10158
+ /**
10159
+ * The same as [`every`]{@link module:Collections.every} but runs a maximum of `limit` async operations at a time.
10160
+ *
10161
+ * @name everyLimit
10162
+ * @static
10163
+ * @memberOf module:Collections
10164
+ * @method
10165
+ * @see [async.every]{@link module:Collections.every}
10166
+ * @alias allLimit
10167
+ * @category Collection
10168
+ * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
10169
+ * @param {number} limit - The maximum number of async operations at a time.
10170
+ * @param {AsyncFunction} iteratee - An async truth test to apply to each item
10171
+ * in the collection in parallel.
10172
+ * The iteratee must complete with a boolean result value.
10173
+ * Invoked with (item, callback).
10174
+ * @param {Function} [callback] - A callback which is called after all the
10175
+ * `iteratee` functions have finished. Result will be either `true` or `false`
10176
+ * depending on the values of the async tests. Invoked with (err, result).
10177
+ * @returns {Promise} a promise, if no callback provided
10178
+ */
10179
+ function everyLimit(coll, limit, iteratee, callback) {
10180
+ return _createTester(bool => !bool, res => !res)(eachOfLimit(limit), coll, iteratee, callback)
10181
+ }
10182
+ awaitify(everyLimit, 4);
10183
+
10184
+ /**
10185
+ * The same as [`every`]{@link module:Collections.every} but runs only a single async operation at a time.
10186
+ *
10187
+ * @name everySeries
10188
+ * @static
10189
+ * @memberOf module:Collections
10190
+ * @method
10191
+ * @see [async.every]{@link module:Collections.every}
10192
+ * @alias allSeries
10193
+ * @category Collection
10194
+ * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
10195
+ * @param {AsyncFunction} iteratee - An async truth test to apply to each item
10196
+ * in the collection in series.
10197
+ * The iteratee must complete with a boolean result value.
10198
+ * Invoked with (item, callback).
10199
+ * @param {Function} [callback] - A callback which is called after all the
10200
+ * `iteratee` functions have finished. Result will be either `true` or `false`
10201
+ * depending on the values of the async tests. Invoked with (err, result).
10202
+ * @returns {Promise} a promise, if no callback provided
10203
+ */
10204
+ function everySeries(coll, iteratee, callback) {
10205
+ return _createTester(bool => !bool, res => !res)(eachOfSeries$1, coll, iteratee, callback)
10206
+ }
10207
+ awaitify(everySeries, 3);
10208
+
10209
+ function filterArray(eachfn, arr, iteratee, callback) {
10210
+ var truthValues = new Array(arr.length);
10211
+ eachfn(arr, (x, index, iterCb) => {
10212
+ iteratee(x, (err, v) => {
10213
+ truthValues[index] = !!v;
10214
+ iterCb(err);
10215
+ });
10216
+ }, err => {
10217
+ if (err) return callback(err);
10218
+ var results = [];
10219
+ for (var i = 0; i < arr.length; i++) {
10220
+ if (truthValues[i]) results.push(arr[i]);
10221
+ }
10222
+ callback(null, results);
10223
+ });
10224
+ }
10225
+
10226
+ function filterGeneric(eachfn, coll, iteratee, callback) {
10227
+ var results = [];
10228
+ eachfn(coll, (x, index, iterCb) => {
10229
+ iteratee(x, (err, v) => {
10230
+ if (err) return iterCb(err);
10231
+ if (v) {
10232
+ results.push({index, value: x});
10233
+ }
10234
+ iterCb(err);
10235
+ });
10236
+ }, err => {
10237
+ if (err) return callback(err);
10238
+ callback(null, results
10239
+ .sort((a, b) => a.index - b.index)
10240
+ .map(v => v.value));
10241
+ });
10242
+ }
10243
+
10244
+ function _filter(eachfn, coll, iteratee, callback) {
10245
+ var filter = isArrayLike(coll) ? filterArray : filterGeneric;
10246
+ return filter(eachfn, coll, wrapAsync(iteratee), callback);
10247
+ }
10248
+
10249
+ /**
10250
+ * Returns a new array of all the values in `coll` which pass an async truth
10251
+ * test. This operation is performed in parallel, but the results array will be
10252
+ * in the same order as the original.
10253
+ *
10254
+ * @name filter
10255
+ * @static
10256
+ * @memberOf module:Collections
10257
+ * @method
10258
+ * @alias select
10259
+ * @category Collection
10260
+ * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
10261
+ * @param {Function} iteratee - A truth test to apply to each item in `coll`.
10262
+ * The `iteratee` is passed a `callback(err, truthValue)`, which must be called
10263
+ * with a boolean argument once it has completed. Invoked with (item, callback).
10264
+ * @param {Function} [callback] - A callback which is called after all the
10265
+ * `iteratee` functions have finished. Invoked with (err, results).
10266
+ * @returns {Promise} a promise, if no callback provided
10267
+ * @example
10268
+ *
10269
+ * // dir1 is a directory that contains file1.txt, file2.txt
10270
+ * // dir2 is a directory that contains file3.txt, file4.txt
10271
+ * // dir3 is a directory that contains file5.txt
10272
+ *
10273
+ * const files = ['dir1/file1.txt','dir2/file3.txt','dir3/file6.txt'];
10274
+ *
10275
+ * // asynchronous function that checks if a file exists
10276
+ * function fileExists(file, callback) {
10277
+ * fs.access(file, fs.constants.F_OK, (err) => {
10278
+ * callback(null, !err);
10279
+ * });
10280
+ * }
10281
+ *
10282
+ * // Using callbacks
10283
+ * async.filter(files, fileExists, function(err, results) {
10284
+ * if(err) {
10285
+ * console.log(err);
10286
+ * } else {
10287
+ * console.log(results);
10288
+ * // [ 'dir1/file1.txt', 'dir2/file3.txt' ]
10289
+ * // results is now an array of the existing files
10290
+ * }
10291
+ * });
10292
+ *
10293
+ * // Using Promises
10294
+ * async.filter(files, fileExists)
10295
+ * .then(results => {
10296
+ * console.log(results);
10297
+ * // [ 'dir1/file1.txt', 'dir2/file3.txt' ]
10298
+ * // results is now an array of the existing files
10299
+ * }).catch(err => {
10300
+ * console.log(err);
10301
+ * });
10302
+ *
10303
+ * // Using async/await
10304
+ * async () => {
10305
+ * try {
10306
+ * let results = await async.filter(files, fileExists);
10307
+ * console.log(results);
10308
+ * // [ 'dir1/file1.txt', 'dir2/file3.txt' ]
10309
+ * // results is now an array of the existing files
10310
+ * }
10311
+ * catch (err) {
10312
+ * console.log(err);
10313
+ * }
10314
+ * }
10315
+ *
10316
+ */
10317
+ function filter (coll, iteratee, callback) {
10318
+ return _filter(eachOf$1, coll, iteratee, callback)
10319
+ }
10320
+ awaitify(filter, 3);
10321
+
10322
+ /**
10323
+ * The same as [`filter`]{@link module:Collections.filter} but runs a maximum of `limit` async operations at a
10324
+ * time.
10325
+ *
10326
+ * @name filterLimit
10327
+ * @static
10328
+ * @memberOf module:Collections
10329
+ * @method
10330
+ * @see [async.filter]{@link module:Collections.filter}
10331
+ * @alias selectLimit
10332
+ * @category Collection
10333
+ * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
10334
+ * @param {number} limit - The maximum number of async operations at a time.
10335
+ * @param {Function} iteratee - A truth test to apply to each item in `coll`.
10336
+ * The `iteratee` is passed a `callback(err, truthValue)`, which must be called
10337
+ * with a boolean argument once it has completed. Invoked with (item, callback).
10338
+ * @param {Function} [callback] - A callback which is called after all the
10339
+ * `iteratee` functions have finished. Invoked with (err, results).
10340
+ * @returns {Promise} a promise, if no callback provided
10341
+ */
10342
+ function filterLimit (coll, limit, iteratee, callback) {
10343
+ return _filter(eachOfLimit(limit), coll, iteratee, callback)
10344
+ }
10345
+ awaitify(filterLimit, 4);
10346
+
10347
+ /**
10348
+ * The same as [`filter`]{@link module:Collections.filter} but runs only a single async operation at a time.
10349
+ *
10350
+ * @name filterSeries
10351
+ * @static
10352
+ * @memberOf module:Collections
10353
+ * @method
10354
+ * @see [async.filter]{@link module:Collections.filter}
10355
+ * @alias selectSeries
10356
+ * @category Collection
10357
+ * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
10358
+ * @param {Function} iteratee - A truth test to apply to each item in `coll`.
10359
+ * The `iteratee` is passed a `callback(err, truthValue)`, which must be called
10360
+ * with a boolean argument once it has completed. Invoked with (item, callback).
10361
+ * @param {Function} [callback] - A callback which is called after all the
10362
+ * `iteratee` functions have finished. Invoked with (err, results)
10363
+ * @returns {Promise} a promise, if no callback provided
10364
+ */
10365
+ function filterSeries (coll, iteratee, callback) {
10366
+ return _filter(eachOfSeries$1, coll, iteratee, callback)
10367
+ }
10368
+ awaitify(filterSeries, 3);
10369
+
10370
+ /**
10371
+ * Calls the asynchronous function `fn` with a callback parameter that allows it
10372
+ * to call itself again, in series, indefinitely.
10373
+
10374
+ * If an error is passed to the callback then `errback` is called with the
10375
+ * error, and execution stops, otherwise it will never be called.
10376
+ *
10377
+ * @name forever
10378
+ * @static
10379
+ * @memberOf module:ControlFlow
10380
+ * @method
10381
+ * @category Control Flow
10382
+ * @param {AsyncFunction} fn - an async function to call repeatedly.
10383
+ * Invoked with (next).
10384
+ * @param {Function} [errback] - when `fn` passes an error to it's callback,
10385
+ * this function will be called, and execution stops. Invoked with (err).
10386
+ * @returns {Promise} a promise that rejects if an error occurs and an errback
10387
+ * is not passed
10388
+ * @example
10389
+ *
10390
+ * async.forever(
10391
+ * function(next) {
10392
+ * // next is suitable for passing to things that need a callback(err [, whatever]);
10393
+ * // it will result in this function being called again.
10394
+ * },
10395
+ * function(err) {
10396
+ * // if next is called with a value in its first parameter, it will appear
10397
+ * // in here as 'err', and execution will stop.
10398
+ * }
10399
+ * );
10400
+ */
10401
+ function forever(fn, errback) {
10402
+ var done = onlyOnce(errback);
10403
+ var task = wrapAsync(ensureAsync(fn));
10404
+
10405
+ function next(err) {
10406
+ if (err) return done(err);
10407
+ if (err === false) return;
10408
+ task(next);
10409
+ }
10410
+ return next();
10411
+ }
10412
+ awaitify(forever, 2);
10413
+
10414
+ /**
10415
+ * The same as [`groupBy`]{@link module:Collections.groupBy} but runs a maximum of `limit` async operations at a time.
10416
+ *
10417
+ * @name groupByLimit
10418
+ * @static
10419
+ * @memberOf module:Collections
10420
+ * @method
10421
+ * @see [async.groupBy]{@link module:Collections.groupBy}
10422
+ * @category Collection
10423
+ * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
10424
+ * @param {number} limit - The maximum number of async operations at a time.
10425
+ * @param {AsyncFunction} iteratee - An async function to apply to each item in
10426
+ * `coll`.
10427
+ * The iteratee should complete with a `key` to group the value under.
10428
+ * Invoked with (value, callback).
10429
+ * @param {Function} [callback] - A callback which is called when all `iteratee`
10430
+ * functions have finished, or an error occurs. Result is an `Object` whoses
10431
+ * properties are arrays of values which returned the corresponding key.
10432
+ * @returns {Promise} a promise, if no callback is passed
10433
+ */
10434
+ function groupByLimit(coll, limit, iteratee, callback) {
10435
+ var _iteratee = wrapAsync(iteratee);
10436
+ return mapLimit$1(coll, limit, (val, iterCb) => {
10437
+ _iteratee(val, (err, key) => {
10438
+ if (err) return iterCb(err);
10439
+ return iterCb(err, {key, val});
10440
+ });
10441
+ }, (err, mapResults) => {
10442
+ var result = {};
10443
+ // from MDN, handle object having an `hasOwnProperty` prop
10444
+ var {hasOwnProperty} = Object.prototype;
10445
+
10446
+ for (var i = 0; i < mapResults.length; i++) {
10447
+ if (mapResults[i]) {
10448
+ var {key} = mapResults[i];
10449
+ var {val} = mapResults[i];
10450
+
10451
+ if (hasOwnProperty.call(result, key)) {
10452
+ result[key].push(val);
10453
+ } else {
10454
+ result[key] = [val];
10455
+ }
10456
+ }
10457
+ }
10458
+
10459
+ return callback(err, result);
10460
+ });
10461
+ }
10462
+
10463
+ awaitify(groupByLimit, 4);
10464
+
10465
+ /**
10466
+ * The same as [`mapValues`]{@link module:Collections.mapValues} but runs a maximum of `limit` async operations at a
10467
+ * time.
10468
+ *
10469
+ * @name mapValuesLimit
10470
+ * @static
10471
+ * @memberOf module:Collections
10472
+ * @method
10473
+ * @see [async.mapValues]{@link module:Collections.mapValues}
10474
+ * @category Collection
10475
+ * @param {Object} obj - A collection to iterate over.
10476
+ * @param {number} limit - The maximum number of async operations at a time.
10477
+ * @param {AsyncFunction} iteratee - A function to apply to each value and key
10478
+ * in `coll`.
10479
+ * The iteratee should complete with the transformed value as its result.
10480
+ * Invoked with (value, key, callback).
10481
+ * @param {Function} [callback] - A callback which is called when all `iteratee`
10482
+ * functions have finished, or an error occurs. `result` is a new object consisting
10483
+ * of each key from `obj`, with each transformed value on the right-hand side.
10484
+ * Invoked with (err, result).
10485
+ * @returns {Promise} a promise, if no callback is passed
10486
+ */
10487
+ function mapValuesLimit(obj, limit, iteratee, callback) {
10488
+ callback = once$1(callback);
10489
+ var newObj = {};
10490
+ var _iteratee = wrapAsync(iteratee);
10491
+ return eachOfLimit(limit)(obj, (val, key, next) => {
10492
+ _iteratee(val, key, (err, result) => {
10493
+ if (err) return next(err);
10494
+ newObj[key] = result;
10495
+ next(err);
10496
+ });
10497
+ }, err => callback(err, newObj));
10498
+ }
10499
+
10500
+ awaitify(mapValuesLimit, 4);
10501
+
10502
+ if (hasNextTick) {
10503
+ process.nextTick;
10504
+ } else if (hasSetImmediate) {
10505
+ setImmediate;
10506
+ } else ;
10507
+
10508
+ awaitify((eachfn, tasks, callback) => {
10509
+ var results = isArrayLike(tasks) ? [] : {};
10510
+
10511
+ eachfn(tasks, (task, key, taskCb) => {
10512
+ wrapAsync(task)((err, ...result) => {
10513
+ if (result.length < 2) {
10514
+ [result] = result;
10515
+ }
10516
+ results[key] = result;
10517
+ taskCb(err);
10518
+ });
10519
+ }, err => callback(err, results));
10520
+ }, 3);
10521
+
10522
+ /**
10523
+ * A queue of tasks for the worker function to complete.
10524
+ * @typedef {Iterable} QueueObject
10525
+ * @memberOf module:ControlFlow
10526
+ * @property {Function} length - a function returning the number of items
10527
+ * waiting to be processed. Invoke with `queue.length()`.
10528
+ * @property {boolean} started - a boolean indicating whether or not any
10529
+ * items have been pushed and processed by the queue.
10530
+ * @property {Function} running - a function returning the number of items
10531
+ * currently being processed. Invoke with `queue.running()`.
10532
+ * @property {Function} workersList - a function returning the array of items
10533
+ * currently being processed. Invoke with `queue.workersList()`.
10534
+ * @property {Function} idle - a function returning false if there are items
10535
+ * waiting or being processed, or true if not. Invoke with `queue.idle()`.
10536
+ * @property {number} concurrency - an integer for determining how many `worker`
10537
+ * functions should be run in parallel. This property can be changed after a
10538
+ * `queue` is created to alter the concurrency on-the-fly.
10539
+ * @property {number} payload - an integer that specifies how many items are
10540
+ * passed to the worker function at a time. only applies if this is a
10541
+ * [cargo]{@link module:ControlFlow.cargo} object
10542
+ * @property {AsyncFunction} push - add a new task to the `queue`. Calls `callback`
10543
+ * once the `worker` has finished processing the task. Instead of a single task,
10544
+ * a `tasks` array can be submitted. The respective callback is used for every
10545
+ * task in the list. Invoke with `queue.push(task, [callback])`,
10546
+ * @property {AsyncFunction} unshift - add a new task to the front of the `queue`.
10547
+ * Invoke with `queue.unshift(task, [callback])`.
10548
+ * @property {AsyncFunction} pushAsync - the same as `q.push`, except this returns
10549
+ * a promise that rejects if an error occurs.
10550
+ * @property {AsyncFunction} unshiftAsync - the same as `q.unshift`, except this returns
10551
+ * a promise that rejects if an error occurs.
10552
+ * @property {Function} remove - remove items from the queue that match a test
10553
+ * function. The test function will be passed an object with a `data` property,
10554
+ * and a `priority` property, if this is a
10555
+ * [priorityQueue]{@link module:ControlFlow.priorityQueue} object.
10556
+ * Invoked with `queue.remove(testFn)`, where `testFn` is of the form
10557
+ * `function ({data, priority}) {}` and returns a Boolean.
10558
+ * @property {Function} saturated - a function that sets a callback that is
10559
+ * called when the number of running workers hits the `concurrency` limit, and
10560
+ * further tasks will be queued. If the callback is omitted, `q.saturated()`
10561
+ * returns a promise for the next occurrence.
10562
+ * @property {Function} unsaturated - a function that sets a callback that is
10563
+ * called when the number of running workers is less than the `concurrency` &
10564
+ * `buffer` limits, and further tasks will not be queued. If the callback is
10565
+ * omitted, `q.unsaturated()` returns a promise for the next occurrence.
10566
+ * @property {number} buffer - A minimum threshold buffer in order to say that
10567
+ * the `queue` is `unsaturated`.
10568
+ * @property {Function} empty - a function that sets a callback that is called
10569
+ * when the last item from the `queue` is given to a `worker`. If the callback
10570
+ * is omitted, `q.empty()` returns a promise for the next occurrence.
10571
+ * @property {Function} drain - a function that sets a callback that is called
10572
+ * when the last item from the `queue` has returned from the `worker`. If the
10573
+ * callback is omitted, `q.drain()` returns a promise for the next occurrence.
10574
+ * @property {Function} error - a function that sets a callback that is called
10575
+ * when a task errors. Has the signature `function(error, task)`. If the
10576
+ * callback is omitted, `error()` returns a promise that rejects on the next
10577
+ * error.
10578
+ * @property {boolean} paused - a boolean for determining whether the queue is
10579
+ * in a paused state.
10580
+ * @property {Function} pause - a function that pauses the processing of tasks
10581
+ * until `resume()` is called. Invoke with `queue.pause()`.
10582
+ * @property {Function} resume - a function that resumes the processing of
10583
+ * queued tasks when the queue is paused. Invoke with `queue.resume()`.
10584
+ * @property {Function} kill - a function that removes the `drain` callback and
10585
+ * empties remaining tasks from the queue forcing it to go idle. No more tasks
10586
+ * should be pushed to the queue after calling this function. Invoke with `queue.kill()`.
10587
+ *
10588
+ * @example
10589
+ * const q = async.queue(worker, 2)
10590
+ * q.push(item1)
10591
+ * q.push(item2)
10592
+ * q.push(item3)
10593
+ * // queues are iterable, spread into an array to inspect
10594
+ * const items = [...q] // [item1, item2, item3]
10595
+ * // or use for of
10596
+ * for (let item of q) {
10597
+ * console.log(item)
10598
+ * }
10599
+ *
10600
+ * q.drain(() => {
10601
+ * console.log('all done')
10602
+ * })
10603
+ * // or
10604
+ * await q.drain()
10605
+ */
10606
+
10607
+ /**
10608
+ * Creates a `queue` object with the specified `concurrency`. Tasks added to the
10609
+ * `queue` are processed in parallel (up to the `concurrency` limit). If all
10610
+ * `worker`s are in progress, the task is queued until one becomes available.
10611
+ * Once a `worker` completes a `task`, that `task`'s callback is called.
10612
+ *
10613
+ * @name queue
10614
+ * @static
10615
+ * @memberOf module:ControlFlow
10616
+ * @method
10617
+ * @category Control Flow
10618
+ * @param {AsyncFunction} worker - An async function for processing a queued task.
10619
+ * If you want to handle errors from an individual task, pass a callback to
10620
+ * `q.push()`. Invoked with (task, callback).
10621
+ * @param {number} [concurrency=1] - An `integer` for determining how many
10622
+ * `worker` functions should be run in parallel. If omitted, the concurrency
10623
+ * defaults to `1`. If the concurrency is `0`, an error is thrown.
10624
+ * @returns {module:ControlFlow.QueueObject} A queue object to manage the tasks. Callbacks can be
10625
+ * attached as certain properties to listen for specific events during the
10626
+ * lifecycle of the queue.
10627
+ * @example
10628
+ *
10629
+ * // create a queue object with concurrency 2
10630
+ * var q = async.queue(function(task, callback) {
10631
+ * console.log('hello ' + task.name);
10632
+ * callback();
10633
+ * }, 2);
10634
+ *
10635
+ * // assign a callback
10636
+ * q.drain(function() {
10637
+ * console.log('all items have been processed');
10638
+ * });
10639
+ * // or await the end
10640
+ * await q.drain()
10641
+ *
10642
+ * // assign an error callback
10643
+ * q.error(function(err, task) {
10644
+ * console.error('task experienced an error');
10645
+ * });
10646
+ *
10647
+ * // add some items to the queue
10648
+ * q.push({name: 'foo'}, function(err) {
10649
+ * console.log('finished processing foo');
10650
+ * });
10651
+ * // callback is optional
10652
+ * q.push({name: 'bar'});
10653
+ *
10654
+ * // add some items to the queue (batch-wise)
10655
+ * q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function(err) {
10656
+ * console.log('finished processing item');
10657
+ * });
10658
+ *
10659
+ * // add some items to the front of the queue
10660
+ * q.unshift({name: 'bar'}, function (err) {
10661
+ * console.log('finished processing bar');
10662
+ * });
10663
+ */
10664
+ function queue$1 (worker, concurrency) {
10665
+ var _worker = wrapAsync(worker);
10666
+ return queue((items, cb) => {
10667
+ _worker(items[0], cb);
10668
+ }, concurrency, 1);
10669
+ }
10670
+
10671
+ /**
10672
+ * Runs the `tasks` array of functions in parallel, without waiting until the
10673
+ * previous function has completed. Once any of the `tasks` complete or pass an
10674
+ * error to its callback, the main `callback` is immediately called. It's
10675
+ * equivalent to `Promise.race()`.
10676
+ *
10677
+ * @name race
10678
+ * @static
10679
+ * @memberOf module:ControlFlow
10680
+ * @method
10681
+ * @category Control Flow
10682
+ * @param {Array} tasks - An array containing [async functions]{@link AsyncFunction}
10683
+ * to run. Each function can complete with an optional `result` value.
10684
+ * @param {Function} callback - A callback to run once any of the functions have
10685
+ * completed. This function gets an error or result from the first function that
10686
+ * completed. Invoked with (err, result).
10687
+ * @returns {Promise} a promise, if a callback is omitted
10688
+ * @example
10689
+ *
10690
+ * async.race([
10691
+ * function(callback) {
10692
+ * setTimeout(function() {
10693
+ * callback(null, 'one');
10694
+ * }, 200);
10695
+ * },
10696
+ * function(callback) {
10697
+ * setTimeout(function() {
10698
+ * callback(null, 'two');
10699
+ * }, 100);
10700
+ * }
10701
+ * ],
10702
+ * // main callback
10703
+ * function(err, result) {
10704
+ * // the result will be equal to 'two' as it finishes earlier
10705
+ * });
10706
+ */
10707
+ function race(tasks, callback) {
10708
+ callback = once$1(callback);
10709
+ if (!Array.isArray(tasks)) return callback(new TypeError('First argument to race must be an array of functions'));
10710
+ if (!tasks.length) return callback();
10711
+ for (var i = 0, l = tasks.length; i < l; i++) {
10712
+ wrapAsync(tasks[i])(callback);
10713
+ }
10714
+ }
10715
+
10716
+ awaitify(race, 2);
10717
+
10718
+ function reject(eachfn, arr, _iteratee, callback) {
10719
+ const iteratee = wrapAsync(_iteratee);
10720
+ return _filter(eachfn, arr, (value, cb) => {
10721
+ iteratee(value, (err, v) => {
10722
+ cb(err, !v);
10723
+ });
10724
+ }, callback);
10725
+ }
10726
+
10727
+ /**
10728
+ * The opposite of [`filter`]{@link module:Collections.filter}. Removes values that pass an `async` truth test.
10729
+ *
10730
+ * @name reject
10731
+ * @static
10732
+ * @memberOf module:Collections
10733
+ * @method
10734
+ * @see [async.filter]{@link module:Collections.filter}
10735
+ * @category Collection
10736
+ * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
10737
+ * @param {Function} iteratee - An async truth test to apply to each item in
10738
+ * `coll`.
10739
+ * The should complete with a boolean value as its `result`.
10740
+ * Invoked with (item, callback).
10741
+ * @param {Function} [callback] - A callback which is called after all the
10742
+ * `iteratee` functions have finished. Invoked with (err, results).
10743
+ * @returns {Promise} a promise, if no callback is passed
10744
+ * @example
10745
+ *
10746
+ * // dir1 is a directory that contains file1.txt, file2.txt
10747
+ * // dir2 is a directory that contains file3.txt, file4.txt
10748
+ * // dir3 is a directory that contains file5.txt
10749
+ *
10750
+ * const fileList = ['dir1/file1.txt','dir2/file3.txt','dir3/file6.txt'];
10751
+ *
10752
+ * // asynchronous function that checks if a file exists
10753
+ * function fileExists(file, callback) {
10754
+ * fs.access(file, fs.constants.F_OK, (err) => {
10755
+ * callback(null, !err);
10756
+ * });
10757
+ * }
10758
+ *
10759
+ * // Using callbacks
10760
+ * async.reject(fileList, fileExists, function(err, results) {
10761
+ * // [ 'dir3/file6.txt' ]
10762
+ * // results now equals an array of the non-existing files
10763
+ * });
10764
+ *
10765
+ * // Using Promises
10766
+ * async.reject(fileList, fileExists)
10767
+ * .then( results => {
10768
+ * console.log(results);
10769
+ * // [ 'dir3/file6.txt' ]
10770
+ * // results now equals an array of the non-existing files
10771
+ * }).catch( err => {
10772
+ * console.log(err);
10773
+ * });
10774
+ *
10775
+ * // Using async/await
10776
+ * async () => {
10777
+ * try {
10778
+ * let results = await async.reject(fileList, fileExists);
10779
+ * console.log(results);
10780
+ * // [ 'dir3/file6.txt' ]
10781
+ * // results now equals an array of the non-existing files
10782
+ * }
10783
+ * catch (err) {
10784
+ * console.log(err);
10785
+ * }
10786
+ * }
10787
+ *
10788
+ */
10789
+ function reject$1 (coll, iteratee, callback) {
10790
+ return reject(eachOf$1, coll, iteratee, callback)
10791
+ }
10792
+ awaitify(reject$1, 3);
10793
+
10794
+ /**
10795
+ * The same as [`reject`]{@link module:Collections.reject} but runs a maximum of `limit` async operations at a
10796
+ * time.
10797
+ *
10798
+ * @name rejectLimit
10799
+ * @static
10800
+ * @memberOf module:Collections
10801
+ * @method
10802
+ * @see [async.reject]{@link module:Collections.reject}
10803
+ * @category Collection
10804
+ * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
10805
+ * @param {number} limit - The maximum number of async operations at a time.
10806
+ * @param {Function} iteratee - An async truth test to apply to each item in
10807
+ * `coll`.
10808
+ * The should complete with a boolean value as its `result`.
10809
+ * Invoked with (item, callback).
10810
+ * @param {Function} [callback] - A callback which is called after all the
10811
+ * `iteratee` functions have finished. Invoked with (err, results).
10812
+ * @returns {Promise} a promise, if no callback is passed
10813
+ */
10814
+ function rejectLimit (coll, limit, iteratee, callback) {
10815
+ return reject(eachOfLimit(limit), coll, iteratee, callback)
10816
+ }
10817
+ awaitify(rejectLimit, 4);
10818
+
10819
+ /**
10820
+ * The same as [`reject`]{@link module:Collections.reject} but runs only a single async operation at a time.
10821
+ *
10822
+ * @name rejectSeries
10823
+ * @static
10824
+ * @memberOf module:Collections
10825
+ * @method
10826
+ * @see [async.reject]{@link module:Collections.reject}
10827
+ * @category Collection
10828
+ * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
10829
+ * @param {Function} iteratee - An async truth test to apply to each item in
10830
+ * `coll`.
10831
+ * The should complete with a boolean value as its `result`.
10832
+ * Invoked with (item, callback).
10833
+ * @param {Function} [callback] - A callback which is called after all the
10834
+ * `iteratee` functions have finished. Invoked with (err, results).
10835
+ * @returns {Promise} a promise, if no callback is passed
10836
+ */
10837
+ function rejectSeries (coll, iteratee, callback) {
10838
+ return reject(eachOfSeries$1, coll, iteratee, callback)
10839
+ }
10840
+ awaitify(rejectSeries, 3);
10841
+
10842
+ /**
10843
+ * Returns `true` if at least one element in the `coll` satisfies an async test.
10844
+ * If any iteratee call returns `true`, the main `callback` is immediately
10845
+ * called.
10846
+ *
10847
+ * @name some
10848
+ * @static
10849
+ * @memberOf module:Collections
10850
+ * @method
10851
+ * @alias any
10852
+ * @category Collection
10853
+ * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
10854
+ * @param {AsyncFunction} iteratee - An async truth test to apply to each item
10855
+ * in the collections in parallel.
10856
+ * The iteratee should complete with a boolean `result` value.
10857
+ * Invoked with (item, callback).
10858
+ * @param {Function} [callback] - A callback which is called as soon as any
10859
+ * iteratee returns `true`, or after all the iteratee functions have finished.
10860
+ * Result will be either `true` or `false` depending on the values of the async
10861
+ * tests. Invoked with (err, result).
10862
+ * @returns {Promise} a promise, if no callback provided
10863
+ * @example
10864
+ *
10865
+ * // dir1 is a directory that contains file1.txt, file2.txt
10866
+ * // dir2 is a directory that contains file3.txt, file4.txt
10867
+ * // dir3 is a directory that contains file5.txt
10868
+ * // dir4 does not exist
10869
+ *
10870
+ * // asynchronous function that checks if a file exists
10871
+ * function fileExists(file, callback) {
10872
+ * fs.access(file, fs.constants.F_OK, (err) => {
10873
+ * callback(null, !err);
10874
+ * });
10875
+ * }
10876
+ *
10877
+ * // Using callbacks
10878
+ * async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists,
10879
+ * function(err, result) {
10880
+ * console.log(result);
10881
+ * // true
10882
+ * // result is true since some file in the list exists
10883
+ * }
10884
+ *);
10885
+ *
10886
+ * async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists,
10887
+ * function(err, result) {
10888
+ * console.log(result);
10889
+ * // false
10890
+ * // result is false since none of the files exists
10891
+ * }
10892
+ *);
10893
+ *
10894
+ * // Using Promises
10895
+ * async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists)
10896
+ * .then( result => {
10897
+ * console.log(result);
10898
+ * // true
10899
+ * // result is true since some file in the list exists
10900
+ * }).catch( err => {
10901
+ * console.log(err);
10902
+ * });
10903
+ *
10904
+ * async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists)
10905
+ * .then( result => {
10906
+ * console.log(result);
10907
+ * // false
10908
+ * // result is false since none of the files exists
10909
+ * }).catch( err => {
10910
+ * console.log(err);
10911
+ * });
10912
+ *
10913
+ * // Using async/await
10914
+ * async () => {
10915
+ * try {
10916
+ * let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists);
10917
+ * console.log(result);
10918
+ * // true
10919
+ * // result is true since some file in the list exists
10920
+ * }
10921
+ * catch (err) {
10922
+ * console.log(err);
10923
+ * }
10924
+ * }
10925
+ *
10926
+ * async () => {
10927
+ * try {
10928
+ * let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists);
10929
+ * console.log(result);
10930
+ * // false
10931
+ * // result is false since none of the files exists
10932
+ * }
10933
+ * catch (err) {
10934
+ * console.log(err);
10935
+ * }
10936
+ * }
10937
+ *
10938
+ */
10939
+ function some(coll, iteratee, callback) {
10940
+ return _createTester(Boolean, res => res)(eachOf$1, coll, iteratee, callback)
10941
+ }
10942
+ awaitify(some, 3);
10943
+
10944
+ /**
10945
+ * The same as [`some`]{@link module:Collections.some} but runs a maximum of `limit` async operations at a time.
10946
+ *
10947
+ * @name someLimit
10948
+ * @static
10949
+ * @memberOf module:Collections
10950
+ * @method
10951
+ * @see [async.some]{@link module:Collections.some}
10952
+ * @alias anyLimit
10953
+ * @category Collection
10954
+ * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
10955
+ * @param {number} limit - The maximum number of async operations at a time.
10956
+ * @param {AsyncFunction} iteratee - An async truth test to apply to each item
10957
+ * in the collections in parallel.
10958
+ * The iteratee should complete with a boolean `result` value.
10959
+ * Invoked with (item, callback).
10960
+ * @param {Function} [callback] - A callback which is called as soon as any
10961
+ * iteratee returns `true`, or after all the iteratee functions have finished.
10962
+ * Result will be either `true` or `false` depending on the values of the async
10963
+ * tests. Invoked with (err, result).
10964
+ * @returns {Promise} a promise, if no callback provided
10965
+ */
10966
+ function someLimit(coll, limit, iteratee, callback) {
10967
+ return _createTester(Boolean, res => res)(eachOfLimit(limit), coll, iteratee, callback)
10968
+ }
10969
+ awaitify(someLimit, 4);
10970
+
10971
+ /**
10972
+ * The same as [`some`]{@link module:Collections.some} but runs only a single async operation at a time.
10973
+ *
10974
+ * @name someSeries
10975
+ * @static
10976
+ * @memberOf module:Collections
10977
+ * @method
10978
+ * @see [async.some]{@link module:Collections.some}
10979
+ * @alias anySeries
10980
+ * @category Collection
10981
+ * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
10982
+ * @param {AsyncFunction} iteratee - An async truth test to apply to each item
10983
+ * in the collections in series.
10984
+ * The iteratee should complete with a boolean `result` value.
10985
+ * Invoked with (item, callback).
10986
+ * @param {Function} [callback] - A callback which is called as soon as any
10987
+ * iteratee returns `true`, or after all the iteratee functions have finished.
10988
+ * Result will be either `true` or `false` depending on the values of the async
10989
+ * tests. Invoked with (err, result).
10990
+ * @returns {Promise} a promise, if no callback provided
10991
+ */
10992
+ function someSeries(coll, iteratee, callback) {
10993
+ return _createTester(Boolean, res => res)(eachOfSeries$1, coll, iteratee, callback)
10994
+ }
10995
+ awaitify(someSeries, 3);
10996
+
10997
+ /**
10998
+ * Sorts a list by the results of running each `coll` value through an async
10999
+ * `iteratee`.
11000
+ *
11001
+ * @name sortBy
11002
+ * @static
11003
+ * @memberOf module:Collections
11004
+ * @method
11005
+ * @category Collection
11006
+ * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
11007
+ * @param {AsyncFunction} iteratee - An async function to apply to each item in
11008
+ * `coll`.
11009
+ * The iteratee should complete with a value to use as the sort criteria as
11010
+ * its `result`.
11011
+ * Invoked with (item, callback).
11012
+ * @param {Function} callback - A callback which is called after all the
11013
+ * `iteratee` functions have finished, or an error occurs. Results is the items
11014
+ * from the original `coll` sorted by the values returned by the `iteratee`
11015
+ * calls. Invoked with (err, results).
11016
+ * @returns {Promise} a promise, if no callback passed
11017
+ * @example
11018
+ *
11019
+ * // bigfile.txt is a file that is 251100 bytes in size
11020
+ * // mediumfile.txt is a file that is 11000 bytes in size
11021
+ * // smallfile.txt is a file that is 121 bytes in size
11022
+ *
11023
+ * // asynchronous function that returns the file size in bytes
11024
+ * function getFileSizeInBytes(file, callback) {
11025
+ * fs.stat(file, function(err, stat) {
11026
+ * if (err) {
11027
+ * return callback(err);
11028
+ * }
11029
+ * callback(null, stat.size);
11030
+ * });
11031
+ * }
11032
+ *
11033
+ * // Using callbacks
11034
+ * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], getFileSizeInBytes,
11035
+ * function(err, results) {
11036
+ * if (err) {
11037
+ * console.log(err);
11038
+ * } else {
11039
+ * console.log(results);
11040
+ * // results is now the original array of files sorted by
11041
+ * // file size (ascending by default), e.g.
11042
+ * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt']
11043
+ * }
11044
+ * }
11045
+ * );
11046
+ *
11047
+ * // By modifying the callback parameter the
11048
+ * // sorting order can be influenced:
11049
+ *
11050
+ * // ascending order
11051
+ * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], function(file, callback) {
11052
+ * getFileSizeInBytes(file, function(getFileSizeErr, fileSize) {
11053
+ * if (getFileSizeErr) return callback(getFileSizeErr);
11054
+ * callback(null, fileSize);
11055
+ * });
11056
+ * }, function(err, results) {
11057
+ * if (err) {
11058
+ * console.log(err);
11059
+ * } else {
11060
+ * console.log(results);
11061
+ * // results is now the original array of files sorted by
11062
+ * // file size (ascending by default), e.g.
11063
+ * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt']
11064
+ * }
11065
+ * }
11066
+ * );
11067
+ *
11068
+ * // descending order
11069
+ * async.sortBy(['bigfile.txt','mediumfile.txt','smallfile.txt'], function(file, callback) {
11070
+ * getFileSizeInBytes(file, function(getFileSizeErr, fileSize) {
11071
+ * if (getFileSizeErr) {
11072
+ * return callback(getFileSizeErr);
11073
+ * }
11074
+ * callback(null, fileSize * -1);
11075
+ * });
11076
+ * }, function(err, results) {
11077
+ * if (err) {
11078
+ * console.log(err);
11079
+ * } else {
11080
+ * console.log(results);
11081
+ * // results is now the original array of files sorted by
11082
+ * // file size (ascending by default), e.g.
11083
+ * // [ 'bigfile.txt', 'mediumfile.txt', 'smallfile.txt']
11084
+ * }
11085
+ * }
11086
+ * );
11087
+ *
11088
+ * // Error handling
11089
+ * async.sortBy(['mediumfile.txt','smallfile.txt','missingfile.txt'], getFileSizeInBytes,
11090
+ * function(err, results) {
11091
+ * if (err) {
11092
+ * console.log(err);
11093
+ * // [ Error: ENOENT: no such file or directory ]
11094
+ * } else {
11095
+ * console.log(results);
11096
+ * }
11097
+ * }
11098
+ * );
11099
+ *
11100
+ * // Using Promises
11101
+ * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], getFileSizeInBytes)
11102
+ * .then( results => {
11103
+ * console.log(results);
11104
+ * // results is now the original array of files sorted by
11105
+ * // file size (ascending by default), e.g.
11106
+ * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt']
11107
+ * }).catch( err => {
11108
+ * console.log(err);
11109
+ * });
11110
+ *
11111
+ * // Error handling
11112
+ * async.sortBy(['mediumfile.txt','smallfile.txt','missingfile.txt'], getFileSizeInBytes)
11113
+ * .then( results => {
11114
+ * console.log(results);
11115
+ * }).catch( err => {
11116
+ * console.log(err);
11117
+ * // [ Error: ENOENT: no such file or directory ]
11118
+ * });
11119
+ *
11120
+ * // Using async/await
11121
+ * (async () => {
11122
+ * try {
11123
+ * let results = await async.sortBy(['bigfile.txt','mediumfile.txt','smallfile.txt'], getFileSizeInBytes);
11124
+ * console.log(results);
11125
+ * // results is now the original array of files sorted by
11126
+ * // file size (ascending by default), e.g.
11127
+ * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt']
11128
+ * }
11129
+ * catch (err) {
11130
+ * console.log(err);
11131
+ * }
11132
+ * })();
11133
+ *
11134
+ * // Error handling
11135
+ * async () => {
11136
+ * try {
11137
+ * let results = await async.sortBy(['missingfile.txt','mediumfile.txt','smallfile.txt'], getFileSizeInBytes);
11138
+ * console.log(results);
11139
+ * }
11140
+ * catch (err) {
11141
+ * console.log(err);
11142
+ * // [ Error: ENOENT: no such file or directory ]
11143
+ * }
11144
+ * }
11145
+ *
11146
+ */
11147
+ function sortBy (coll, iteratee, callback) {
11148
+ var _iteratee = wrapAsync(iteratee);
11149
+ return map$1(coll, (x, iterCb) => {
11150
+ _iteratee(x, (err, criteria) => {
11151
+ if (err) return iterCb(err);
11152
+ iterCb(err, {value: x, criteria});
11153
+ });
11154
+ }, (err, results) => {
11155
+ if (err) return callback(err);
11156
+ callback(null, results.sort(comparator).map(v => v.value));
11157
+ });
11158
+
11159
+ function comparator(left, right) {
11160
+ var a = left.criteria, b = right.criteria;
11161
+ return a < b ? -1 : a > b ? 1 : 0;
11162
+ }
11163
+ }
11164
+ awaitify(sortBy, 3);
11165
+
11166
+ /**
11167
+ * It runs each task in series but stops whenever any of the functions were
11168
+ * successful. If one of the tasks were successful, the `callback` will be
11169
+ * passed the result of the successful task. If all tasks fail, the callback
11170
+ * will be passed the error and result (if any) of the final attempt.
11171
+ *
11172
+ * @name tryEach
11173
+ * @static
11174
+ * @memberOf module:ControlFlow
11175
+ * @method
11176
+ * @category Control Flow
11177
+ * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing functions to
11178
+ * run, each function is passed a `callback(err, result)` it must call on
11179
+ * completion with an error `err` (which can be `null`) and an optional `result`
11180
+ * value.
11181
+ * @param {Function} [callback] - An optional callback which is called when one
11182
+ * of the tasks has succeeded, or all have failed. It receives the `err` and
11183
+ * `result` arguments of the last attempt at completing the `task`. Invoked with
11184
+ * (err, results).
11185
+ * @returns {Promise} a promise, if no callback is passed
11186
+ * @example
11187
+ * async.tryEach([
11188
+ * function getDataFromFirstWebsite(callback) {
11189
+ * // Try getting the data from the first website
11190
+ * callback(err, data);
11191
+ * },
11192
+ * function getDataFromSecondWebsite(callback) {
11193
+ * // First website failed,
11194
+ * // Try getting the data from the backup website
11195
+ * callback(err, data);
11196
+ * }
11197
+ * ],
11198
+ * // optional callback
11199
+ * function(err, results) {
11200
+ * Now do something with the data.
11201
+ * });
11202
+ *
11203
+ */
11204
+ function tryEach(tasks, callback) {
11205
+ var error = null;
11206
+ var result;
11207
+ return eachSeries$1(tasks, (task, taskCb) => {
11208
+ wrapAsync(task)((err, ...args) => {
11209
+ if (err === false) return taskCb(err);
11210
+
11211
+ if (args.length < 2) {
11212
+ [result] = args;
11213
+ } else {
11214
+ result = args;
11215
+ }
11216
+ error = err;
11217
+ taskCb(err ? null : {});
11218
+ });
11219
+ }, () => callback(error, result));
11220
+ }
11221
+
11222
+ awaitify(tryEach);
11223
+
11224
+ /**
11225
+ * Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when
11226
+ * stopped, or an error occurs.
11227
+ *
11228
+ * @name whilst
11229
+ * @static
11230
+ * @memberOf module:ControlFlow
11231
+ * @method
11232
+ * @category Control Flow
11233
+ * @param {AsyncFunction} test - asynchronous truth test to perform before each
11234
+ * execution of `iteratee`. Invoked with ().
11235
+ * @param {AsyncFunction} iteratee - An async function which is called each time
11236
+ * `test` passes. Invoked with (callback).
11237
+ * @param {Function} [callback] - A callback which is called after the test
11238
+ * function has failed and repeated execution of `iteratee` has stopped. `callback`
11239
+ * will be passed an error and any arguments passed to the final `iteratee`'s
11240
+ * callback. Invoked with (err, [results]);
11241
+ * @returns {Promise} a promise, if no callback is passed
11242
+ * @example
11243
+ *
11244
+ * var count = 0;
11245
+ * async.whilst(
11246
+ * function test(cb) { cb(null, count < 5); },
11247
+ * function iter(callback) {
11248
+ * count++;
11249
+ * setTimeout(function() {
11250
+ * callback(null, count);
11251
+ * }, 1000);
11252
+ * },
11253
+ * function (err, n) {
11254
+ * // 5 seconds have passed, n = 5
11255
+ * }
11256
+ * );
11257
+ */
11258
+ function whilst(test, iteratee, callback) {
11259
+ callback = onlyOnce(callback);
11260
+ var _fn = wrapAsync(iteratee);
11261
+ var _test = wrapAsync(test);
11262
+ var results = [];
11263
+
11264
+ function next(err, ...rest) {
11265
+ if (err) return callback(err);
11266
+ results = rest;
11267
+ if (err === false) return;
11268
+ _test(check);
11269
+ }
11270
+
11271
+ function check(err, truth) {
11272
+ if (err) return callback(err);
11273
+ if (err === false) return;
11274
+ if (!truth) return callback(null, ...results);
11275
+ _fn(next);
11276
+ }
11277
+
11278
+ return _test(check);
11279
+ }
11280
+ awaitify(whilst, 3);
11281
+
11282
+ /**
11283
+ * Runs the `tasks` array of functions in series, each passing their results to
11284
+ * the next in the array. However, if any of the `tasks` pass an error to their
11285
+ * own callback, the next function is not executed, and the main `callback` is
11286
+ * immediately called with the error.
11287
+ *
11288
+ * @name waterfall
11289
+ * @static
11290
+ * @memberOf module:ControlFlow
11291
+ * @method
11292
+ * @category Control Flow
11293
+ * @param {Array} tasks - An array of [async functions]{@link AsyncFunction}
11294
+ * to run.
11295
+ * Each function should complete with any number of `result` values.
11296
+ * The `result` values will be passed as arguments, in order, to the next task.
11297
+ * @param {Function} [callback] - An optional callback to run once all the
11298
+ * functions have completed. This will be passed the results of the last task's
11299
+ * callback. Invoked with (err, [results]).
11300
+ * @returns {Promise} a promise, if a callback is omitted
11301
+ * @example
11302
+ *
11303
+ * async.waterfall([
11304
+ * function(callback) {
11305
+ * callback(null, 'one', 'two');
11306
+ * },
11307
+ * function(arg1, arg2, callback) {
11308
+ * // arg1 now equals 'one' and arg2 now equals 'two'
11309
+ * callback(null, 'three');
11310
+ * },
11311
+ * function(arg1, callback) {
11312
+ * // arg1 now equals 'three'
11313
+ * callback(null, 'done');
11314
+ * }
11315
+ * ], function (err, result) {
11316
+ * // result now equals 'done'
11317
+ * });
11318
+ *
11319
+ * // Or, with named functions:
11320
+ * async.waterfall([
11321
+ * myFirstFunction,
11322
+ * mySecondFunction,
11323
+ * myLastFunction,
11324
+ * ], function (err, result) {
11325
+ * // result now equals 'done'
11326
+ * });
11327
+ * function myFirstFunction(callback) {
11328
+ * callback(null, 'one', 'two');
11329
+ * }
11330
+ * function mySecondFunction(arg1, arg2, callback) {
11331
+ * // arg1 now equals 'one' and arg2 now equals 'two'
11332
+ * callback(null, 'three');
11333
+ * }
11334
+ * function myLastFunction(arg1, callback) {
11335
+ * // arg1 now equals 'three'
11336
+ * callback(null, 'done');
11337
+ * }
11338
+ */
11339
+ function waterfall (tasks, callback) {
11340
+ callback = once$1(callback);
11341
+ if (!Array.isArray(tasks)) return callback(new Error('First argument to waterfall must be an array of functions'));
11342
+ if (!tasks.length) return callback();
11343
+ var taskIndex = 0;
11344
+
11345
+ function nextTask(args) {
11346
+ var task = wrapAsync(tasks[taskIndex++]);
11347
+ task(...args, onlyOnce(next));
11348
+ }
11349
+
11350
+ function next(err, ...args) {
11351
+ if (err === false) return
11352
+ if (err || taskIndex === tasks.length) {
11353
+ return callback(err, ...args);
11354
+ }
11355
+ nextTask(args);
11356
+ }
11357
+
11358
+ nextTask([]);
11359
+ }
11360
+
11361
+ awaitify(waterfall);
11362
+
11363
+ function processTasks(task, finishedCallback) {
11364
+ return __awaiter(this, void 0, void 0, function* () {
11365
+ try {
11366
+ yield task();
11367
+ finishedCallback();
11368
+ }
11369
+ catch (e) {
11370
+ finishedCallback(e);
11371
+ }
11372
+ });
11373
+ }
11374
+ class AsyncQueue {
11375
+ constructor() {
11376
+ this.queue = queue$1(processTasks, 1);
11377
+ }
11378
+ push(task) {
11379
+ return this.queue.pushAsync(task);
11380
+ }
11381
+ empty() {
11382
+ return this.queue.empty();
11383
+ }
11384
+ }
11385
+
8182
11386
  var events = {exports: {}};
8183
11387
 
8184
11388
  var R = typeof Reflect === 'object' ? Reflect : null;
@@ -9792,6 +12996,7 @@ class MultistreamConnection extends EventEmitter {
9792
12996
  this.customCodecParameters = new Map();
9793
12997
  this.midMap = new Map();
9794
12998
  this.currentMid = 0;
12999
+ this.offerAnswerQueue = new AsyncQueue();
9795
13000
  this.options = Object.assign(Object.assign({}, defaultMultistreamConnectionOptions), userOptions);
9796
13001
  logger.info(`Creating multistream connection with options ${JSON.stringify(this.options)}`);
9797
13002
  this.initializePeerConnection();
@@ -10228,47 +13433,65 @@ class MultistreamConnection extends EventEmitter {
10228
13433
  if (!this.pc.getLocalDescription()) {
10229
13434
  this.currentMid++;
10230
13435
  }
10231
- return (this.pc
10232
- .createOffer()
10233
- .then((offer) => {
10234
- if (!offer.sdp) {
10235
- throw new Error('No SDP offer');
10236
- }
10237
- offer.sdp = this.preProcessLocalOffer(offer.sdp);
10238
- return this.pc.setLocalDescription(offer);
10239
- })
10240
- .then(() => getLocalDescriptionWithIceCandidates(this.pc))
10241
- .then((offerWithCandidates) => {
10242
- const sdp = this.prepareLocalOfferForRemoteServer(offerWithCandidates.sdp);
10243
- return {
10244
- sdp,
10245
- type: offerWithCandidates.type,
10246
- };
10247
- }));
13436
+ return new Promise((createOfferResolve) => {
13437
+ this.offerAnswerQueue.push(() => __awaiter(this, void 0, void 0, function* () {
13438
+ if (this.setAnswerResolve !== undefined) {
13439
+ throw new Error(`Tried to start a new createOffer flow before the old one had finished`);
13440
+ }
13441
+ const setAnswerPromise = new Promise((resolve) => {
13442
+ this.setAnswerResolve = resolve;
13443
+ });
13444
+ const offer = yield this.pc.createOffer();
13445
+ if (!offer.sdp) {
13446
+ throw new Error('No SDP offer');
13447
+ }
13448
+ offer.sdp = this.preProcessLocalOffer(offer.sdp);
13449
+ yield this.pc.setLocalDescription(offer);
13450
+ const offerWithCandidates = yield getLocalDescriptionWithIceCandidates(this.pc);
13451
+ const sdpToSend = this.prepareLocalOfferForRemoteServer(offerWithCandidates.sdp);
13452
+ createOfferResolve({
13453
+ sdp: sdpToSend,
13454
+ type: offerWithCandidates.type,
13455
+ });
13456
+ yield setAnswerPromise;
13457
+ }));
13458
+ });
10248
13459
  });
10249
13460
  }
10250
13461
  setAnswer(answer) {
10251
13462
  return __awaiter(this, void 0, void 0, function* () {
10252
13463
  const isInitialAnswer = !this.pc.getRemoteDescription();
10253
13464
  const sdp = this.preProcessRemoteAnswer(answer);
10254
- return this.pc.setRemoteDescription({ type: 'answer', sdp }).then(() => {
13465
+ if (!this.setAnswerResolve) {
13466
+ throw new Error(`Call to setAnswer without having previously called createOffer`);
13467
+ }
13468
+ return this.pc.setRemoteDescription({ type: 'answer', sdp }).then(() => __awaiter(this, void 0, void 0, function* () {
13469
+ if (this.setAnswerResolve) {
13470
+ this.setAnswerResolve();
13471
+ this.setAnswerResolve = undefined;
13472
+ }
13473
+ else {
13474
+ logger.debug(`setAnswerResolve function was cleared between setAnswer and result of setRemoteDescription`);
13475
+ }
10255
13476
  if (isInitialAnswer && this.customCodecParameters.size > 0) {
10256
- this.doLocalOfferAnswer();
13477
+ yield this.doLocalOfferAnswer();
10257
13478
  }
10258
- });
13479
+ }));
10259
13480
  });
10260
13481
  }
10261
13482
  doLocalOfferAnswer() {
10262
- var _a;
10263
13483
  return __awaiter(this, void 0, void 0, function* () {
10264
- const offer = yield this.pc.createOffer();
10265
- if (!offer.sdp) {
10266
- throw new Error('No SDP offer');
10267
- }
10268
- offer.sdp = this.preProcessLocalOffer(offer.sdp);
10269
- yield this.pc.setLocalDescription(offer);
10270
- const answer = this.preProcessRemoteAnswer((_a = this.pc.getRemoteDescription()) === null || _a === void 0 ? void 0 : _a.sdp);
10271
- return this.pc.setRemoteDescription({ type: 'answer', sdp: answer });
13484
+ return this.offerAnswerQueue.push(() => __awaiter(this, void 0, void 0, function* () {
13485
+ var _a;
13486
+ const offer = yield this.pc.createOffer();
13487
+ if (!offer.sdp) {
13488
+ throw new Error('No SDP offer');
13489
+ }
13490
+ offer.sdp = this.preProcessLocalOffer(offer.sdp);
13491
+ yield this.pc.setLocalDescription(offer);
13492
+ const answer = this.preProcessRemoteAnswer((_a = this.pc.getRemoteDescription()) === null || _a === void 0 ? void 0 : _a.sdp);
13493
+ return this.pc.setRemoteDescription({ type: 'answer', sdp: answer });
13494
+ }));
10272
13495
  });
10273
13496
  }
10274
13497
  enableMultistreamAudio(enabled) {