@webex/web-client-media-engine 1.41.0 → 1.42.0

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