UNPKG

@pm2/js-api

Version:

PM2.io API Client for Javascript

1,638 lines (1,488 loc) 523 kB
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Keymetrics = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){ (function (process){(function (){ "use strict"; var pkg = require('./package.json'); var config = { headers: { 'X-JS-API-Version': pkg.version }, services: { API: 'https://api.keymetrics.io', OAUTH: 'https://id.keymetrics.io' }, OAUTH_AUTHORIZE_ENDPOINT: '/api/oauth/authorize', OAUTH_CLIENT_ID: '795984050', ENVIRONNEMENT: process && process.versions && process.versions.node ? 'node' : 'browser', VERSION: pkg.version, // put in debug when using km.io with browser OR when DEBUG=true with nodejs IS_DEBUG: typeof window !== 'undefined' && window.location.host.match(/km.(io|local)/) || typeof process !== 'undefined' && process.env.DEBUG === 'true' }; module.exports = Object.assign({}, config); }).call(this)}).call(this,require('_process')) },{"./package.json":39,"_process":37}],2:[function(require,module,exports){ (function (process,global,setImmediate){(function (){ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (factory((global.async = global.async || {}))); }(this, (function (exports) { 'use strict'; function slice(arrayLike, start) { start = start|0; var newLen = Math.max(arrayLike.length - start, 0); var newArr = Array(newLen); for(var idx = 0; idx < newLen; idx++) { newArr[idx] = arrayLike[start + idx]; } return newArr; } /** * Creates a continuation function with some arguments already applied. * * Useful as a shorthand when combined with other control flow functions. Any * arguments passed to the returned function are added to the arguments * originally passed to apply. * * @name apply * @static * @memberOf module:Utils * @method * @category Util * @param {Function} fn - The function you want to eventually apply all * arguments to. Invokes with (arguments...). * @param {...*} arguments... - Any number of arguments to automatically apply * when the continuation is called. * @returns {Function} the partially-applied function * @example * * // using apply * async.parallel([ * async.apply(fs.writeFile, 'testfile1', 'test1'), * async.apply(fs.writeFile, 'testfile2', 'test2') * ]); * * * // the same process without using apply * async.parallel([ * function(callback) { * fs.writeFile('testfile1', 'test1', callback); * }, * function(callback) { * fs.writeFile('testfile2', 'test2', callback); * } * ]); * * // It's possible to pass any number of additional arguments when calling the * // continuation: * * node> var fn = async.apply(sys.puts, 'one'); * node> fn('two', 'three'); * one * two * three */ var apply = function(fn/*, ...args*/) { var args = slice(arguments, 1); return function(/*callArgs*/) { var callArgs = slice(arguments); return fn.apply(null, args.concat(callArgs)); }; }; var initialParams = function (fn) { return function (/*...args, callback*/) { var args = slice(arguments); var callback = args.pop(); fn.call(this, args, callback); }; }; /** * Checks if `value` is the * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(_.noop); * // => true * * _.isObject(null); * // => false */ function isObject(value) { var type = typeof value; return value != null && (type == 'object' || type == 'function'); } var hasSetImmediate = typeof setImmediate === 'function' && setImmediate; var hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function'; function fallback(fn) { setTimeout(fn, 0); } function wrap(defer) { return function (fn/*, ...args*/) { var args = slice(arguments, 1); defer(function () { fn.apply(null, args); }); }; } var _defer; if (hasSetImmediate) { _defer = setImmediate; } else if (hasNextTick) { _defer = process.nextTick; } else { _defer = fallback; } var setImmediate$1 = wrap(_defer); /** * Take a sync function and make it async, passing its return value to a * callback. This is useful for plugging sync functions into a waterfall, * series, or other async functions. Any arguments passed to the generated * function will be passed to the wrapped function (except for the final * callback argument). Errors thrown will be passed to the callback. * * If the function passed to `asyncify` returns a Promise, that promises's * resolved/rejected state will be used to call the callback, rather than simply * the synchronous return value. * * This also means you can asyncify ES2017 `async` functions. * * @name asyncify * @static * @memberOf module:Utils * @method * @alias wrapSync * @category Util * @param {Function} func - The synchronous function, or Promise-returning * function to convert to an {@link AsyncFunction}. * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be * invoked with `(args..., callback)`. * @example * * // passing a regular synchronous function * async.waterfall([ * async.apply(fs.readFile, filename, "utf8"), * async.asyncify(JSON.parse), * function (data, next) { * // data is the result of parsing the text. * // If there was a parsing error, it would have been caught. * } * ], callback); * * // passing a function returning a promise * async.waterfall([ * async.apply(fs.readFile, filename, "utf8"), * async.asyncify(function (contents) { * return db.model.create(contents); * }), * function (model, next) { * // `model` is the instantiated model object. * // If there was an error, this function would be skipped. * } * ], callback); * * // es2017 example, though `asyncify` is not needed if your JS environment * // supports async functions out of the box * var q = async.queue(async.asyncify(async function(file) { * var intermediateStep = await processFile(file); * return await somePromise(intermediateStep) * })); * * q.push(files); */ function asyncify(func) { return initialParams(function (args, callback) { var result; try { result = func.apply(this, args); } catch (e) { return callback(e); } // if result is Promise object if (isObject(result) && typeof result.then === 'function') { result.then(function(value) { invokeCallback(callback, null, value); }, function(err) { invokeCallback(callback, err.message ? err : new Error(err)); }); } else { callback(null, result); } }); } function invokeCallback(callback, error, value) { try { callback(error, value); } catch (e) { setImmediate$1(rethrow, e); } } function rethrow(error) { throw error; } var supportsSymbol = typeof Symbol === 'function'; function isAsync(fn) { return supportsSymbol && fn[Symbol.toStringTag] === 'AsyncFunction'; } function wrapAsync(asyncFn) { return isAsync(asyncFn) ? asyncify(asyncFn) : asyncFn; } function applyEach$1(eachfn) { return function(fns/*, ...args*/) { var args = slice(arguments, 1); var go = initialParams(function(args, callback) { var that = this; return eachfn(fns, function (fn, cb) { wrapAsync(fn).apply(that, args.concat(cb)); }, callback); }); if (args.length) { return go.apply(this, args); } else { return go; } }; } /** Detect free variable `global` from Node.js. */ var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; /** Detect free variable `self`. */ var freeSelf = typeof self == 'object' && self && self.Object === Object && self; /** Used as a reference to the global object. */ var root = freeGlobal || freeSelf || Function('return this')(); /** Built-in value references. */ var Symbol$1 = root.Symbol; /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto.toString; /** Built-in value references. */ var symToStringTag$1 = Symbol$1 ? Symbol$1.toStringTag : undefined; /** * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. * * @private * @param {*} value The value to query. * @returns {string} Returns the raw `toStringTag`. */ function getRawTag(value) { var isOwn = hasOwnProperty.call(value, symToStringTag$1), tag = value[symToStringTag$1]; try { value[symToStringTag$1] = undefined; var unmasked = true; } catch (e) {} var result = nativeObjectToString.call(value); if (unmasked) { if (isOwn) { value[symToStringTag$1] = tag; } else { delete value[symToStringTag$1]; } } return result; } /** Used for built-in method references. */ var objectProto$1 = Object.prototype; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString$1 = objectProto$1.toString; /** * Converts `value` to a string using `Object.prototype.toString`. * * @private * @param {*} value The value to convert. * @returns {string} Returns the converted string. */ function objectToString(value) { return nativeObjectToString$1.call(value); } /** `Object#toString` result references. */ var nullTag = '[object Null]'; var undefinedTag = '[object Undefined]'; /** Built-in value references. */ var symToStringTag = Symbol$1 ? Symbol$1.toStringTag : undefined; /** * The base implementation of `getTag` without fallbacks for buggy environments. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ function baseGetTag(value) { if (value == null) { return value === undefined ? undefinedTag : nullTag; } return (symToStringTag && symToStringTag in Object(value)) ? getRawTag(value) : objectToString(value); } /** `Object#toString` result references. */ var asyncTag = '[object AsyncFunction]'; var funcTag = '[object Function]'; var genTag = '[object GeneratorFunction]'; var proxyTag = '[object Proxy]'; /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a function, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { if (!isObject(value)) { return false; } // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 9 which returns 'object' for typed arrays and other constructors. var tag = baseGetTag(value); return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; } /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * Checks if `value` is a valid array-like length. * * **Note:** This method is loosely based on * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. * @example * * _.isLength(3); * // => true * * _.isLength(Number.MIN_VALUE); * // => false * * _.isLength(Infinity); * // => false * * _.isLength('3'); * // => false */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } /** * Checks if `value` is array-like. A value is considered array-like if it's * not a function and has a `value.length` that's an integer greater than or * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. * @example * * _.isArrayLike([1, 2, 3]); * // => true * * _.isArrayLike(document.body.children); * // => true * * _.isArrayLike('abc'); * // => true * * _.isArrayLike(_.noop); * // => false */ function isArrayLike(value) { return value != null && isLength(value.length) && !isFunction(value); } // A temporary value used to identify if the loop should be broken. // See #1064, #1293 var breakLoop = {}; /** * This method returns `undefined`. * * @static * @memberOf _ * @since 2.3.0 * @category Util * @example * * _.times(2, _.noop); * // => [undefined, undefined] */ function noop() { // No operation performed. } function once(fn) { return function () { if (fn === null) return; var callFn = fn; fn = null; callFn.apply(this, arguments); }; } var iteratorSymbol = typeof Symbol === 'function' && Symbol.iterator; var getIterator = function (coll) { return iteratorSymbol && coll[iteratorSymbol] && coll[iteratorSymbol](); }; /** * The base implementation of `_.times` without support for iteratee shorthands * or max array length checks. * * @private * @param {number} n The number of times to invoke `iteratee`. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the array of results. */ function baseTimes(n, iteratee) { var index = -1, result = Array(n); while (++index < n) { result[index] = iteratee(index); } return result; } /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return value != null && typeof value == 'object'; } /** `Object#toString` result references. */ var argsTag = '[object Arguments]'; /** * The base implementation of `_.isArguments`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, */ function baseIsArguments(value) { return isObjectLike(value) && baseGetTag(value) == argsTag; } /** Used for built-in method references. */ var objectProto$3 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$2 = objectProto$3.hasOwnProperty; /** Built-in value references. */ var propertyIsEnumerable = objectProto$3.propertyIsEnumerable; /** * Checks if `value` is likely an `arguments` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, * else `false`. * @example * * _.isArguments(function() { return arguments; }()); * // => true * * _.isArguments([1, 2, 3]); * // => false */ var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { return isObjectLike(value) && hasOwnProperty$2.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee'); }; /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(document.body.children); * // => false * * _.isArray('abc'); * // => false * * _.isArray(_.noop); * // => false */ var isArray = Array.isArray; /** * This method returns `false`. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {boolean} Returns `false`. * @example * * _.times(2, _.stubFalse); * // => [false, false] */ function stubFalse() { return false; } /** Detect free variable `exports`. */ var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Built-in value references. */ var Buffer = moduleExports ? root.Buffer : undefined; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined; /** * Checks if `value` is a buffer. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. * @example * * _.isBuffer(new Buffer(2)); * // => true * * _.isBuffer(new Uint8Array(2)); * // => false */ var isBuffer = nativeIsBuffer || stubFalse; /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER$1 = 9007199254740991; /** Used to detect unsigned integer values. */ var reIsUint = /^(?:0|[1-9]\d*)$/; /** * Checks if `value` is a valid array-like index. * * @private * @param {*} value The value to check. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ function isIndex(value, length) { var type = typeof value; length = length == null ? MAX_SAFE_INTEGER$1 : length; return !!length && (type == 'number' || (type != 'symbol' && reIsUint.test(value))) && (value > -1 && value % 1 == 0 && value < length); } /** `Object#toString` result references. */ var argsTag$1 = '[object Arguments]'; var arrayTag = '[object Array]'; var boolTag = '[object Boolean]'; var dateTag = '[object Date]'; var errorTag = '[object Error]'; var funcTag$1 = '[object Function]'; var mapTag = '[object Map]'; var numberTag = '[object Number]'; var objectTag = '[object Object]'; var regexpTag = '[object RegExp]'; var setTag = '[object Set]'; var stringTag = '[object String]'; var weakMapTag = '[object WeakMap]'; var arrayBufferTag = '[object ArrayBuffer]'; var dataViewTag = '[object DataView]'; var float32Tag = '[object Float32Array]'; var float64Tag = '[object Float64Array]'; var int8Tag = '[object Int8Array]'; var int16Tag = '[object Int16Array]'; var int32Tag = '[object Int32Array]'; var uint8Tag = '[object Uint8Array]'; var uint8ClampedTag = '[object Uint8ClampedArray]'; var uint16Tag = '[object Uint16Array]'; var uint32Tag = '[object Uint32Array]'; /** Used to identify `toStringTag` values of typed arrays. */ var typedArrayTags = {}; typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag$1] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; /** * The base implementation of `_.isTypedArray` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. */ function baseIsTypedArray(value) { return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; } /** * The base implementation of `_.unary` without support for storing metadata. * * @private * @param {Function} func The function to cap arguments for. * @returns {Function} Returns the new capped function. */ function baseUnary(func) { return function(value) { return func(value); }; } /** Detect free variable `exports`. */ var freeExports$1 = typeof exports == 'object' && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule$1 = freeExports$1 && typeof module == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports$1 = freeModule$1 && freeModule$1.exports === freeExports$1; /** Detect free variable `process` from Node.js. */ var freeProcess = moduleExports$1 && freeGlobal.process; /** Used to access faster Node.js helpers. */ var nodeUtil = (function() { try { // Use `util.types` for Node.js 10+. var types = freeModule$1 && freeModule$1.require && freeModule$1.require('util').types; if (types) { return types; } // Legacy `process.binding('util')` for Node.js < 10. return freeProcess && freeProcess.binding && freeProcess.binding('util'); } catch (e) {} }()); /* Node.js helper references. */ var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; /** * Checks if `value` is classified as a typed array. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. * @example * * _.isTypedArray(new Uint8Array); * // => true * * _.isTypedArray([]); * // => false */ var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; /** Used for built-in method references. */ var objectProto$2 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$1 = objectProto$2.hasOwnProperty; /** * Creates an array of the enumerable property names of the array-like `value`. * * @private * @param {*} value The value to query. * @param {boolean} inherited Specify returning inherited property names. * @returns {Array} Returns the array of property names. */ function arrayLikeKeys(value, inherited) { var isArr = isArray(value), isArg = !isArr && isArguments(value), isBuff = !isArr && !isArg && isBuffer(value), isType = !isArr && !isArg && !isBuff && isTypedArray(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? baseTimes(value.length, String) : [], length = result.length; for (var key in value) { if ((inherited || hasOwnProperty$1.call(value, key)) && !(skipIndexes && ( // Safari 9 has enumerable `arguments.length` in strict mode. key == 'length' || // Node.js 0.10 has enumerable non-index properties on buffers. (isBuff && (key == 'offset' || key == 'parent')) || // PhantomJS 2 has enumerable non-index properties on typed arrays. (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || // Skip index properties. isIndex(key, length) ))) { result.push(key); } } return result; } /** Used for built-in method references. */ var objectProto$5 = Object.prototype; /** * Checks if `value` is likely a prototype object. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. */ function isPrototype(value) { var Ctor = value && value.constructor, proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$5; return value === proto; } /** * Creates a unary function that invokes `func` with its argument transformed. * * @private * @param {Function} func The function to wrap. * @param {Function} transform The argument transform. * @returns {Function} Returns the new function. */ function overArg(func, transform) { return function(arg) { return func(transform(arg)); }; } /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeKeys = overArg(Object.keys, Object); /** Used for built-in method references. */ var objectProto$4 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$3 = objectProto$4.hasOwnProperty; /** * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeys(object) { if (!isPrototype(object)) { return nativeKeys(object); } var result = []; for (var key in Object(object)) { if (hasOwnProperty$3.call(object, key) && key != 'constructor') { result.push(key); } } return result; } /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * for more details. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keys(new Foo); * // => ['a', 'b'] (iteration order is not guaranteed) * * _.keys('hi'); * // => ['0', '1'] */ function keys(object) { return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); } function createArrayIterator(coll) { var i = -1; var len = coll.length; return function next() { return ++i < len ? {value: coll[i], key: i} : null; } } function createES2015Iterator(iterator) { var i = -1; return function next() { var item = iterator.next(); if (item.done) return null; i++; return {value: item.value, key: i}; } } function createObjectIterator(obj) { var okeys = keys(obj); var i = -1; var len = okeys.length; return function next() { var key = okeys[++i]; if (key === '__proto__') { return next(); } return i < len ? {value: obj[key], key: key} : null; }; } function iterator(coll) { if (isArrayLike(coll)) { return createArrayIterator(coll); } var iterator = getIterator(coll); return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll); } function onlyOnce(fn) { return function() { if (fn === null) throw new Error("Callback was already called."); var callFn = fn; fn = null; callFn.apply(this, arguments); }; } function _eachOfLimit(limit) { return function (obj, iteratee, callback) { callback = once(callback || noop); if (limit <= 0 || !obj) { return callback(null); } var nextElem = iterator(obj); var done = false; var running = 0; var looping = false; function iterateeCallback(err, value) { running -= 1; if (err) { done = true; callback(err); } else if (value === breakLoop || (done && running <= 0)) { done = true; return callback(null); } else if (!looping) { replenish(); } } function replenish () { looping = true; while (running < limit && !done) { var elem = nextElem(); if (elem === null) { done = true; if (running <= 0) { callback(null); } return; } running += 1; iteratee(elem.value, elem.key, onlyOnce(iterateeCallback)); } looping = false; } replenish(); }; } /** * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a * time. * * @name eachOfLimit * @static * @memberOf module:Collections * @method * @see [async.eachOf]{@link module:Collections.eachOf} * @alias forEachOfLimit * @category Collection * @param {Array|Iterable|Object} coll - A collection to iterate over. * @param {number} limit - The maximum number of async operations at a time. * @param {AsyncFunction} iteratee - An async function to apply to each * item in `coll`. The `key` is the item's key, or index in the case of an * array. * Invoked with (item, key, callback). * @param {Function} [callback] - A callback which is called when all * `iteratee` functions have finished, or an error occurs. Invoked with (err). */ function eachOfLimit(coll, limit, iteratee, callback) { _eachOfLimit(limit)(coll, wrapAsync(iteratee), callback); } function doLimit(fn, limit) { return function (iterable, iteratee, callback) { return fn(iterable, limit, iteratee, callback); }; } // eachOf implementation optimized for array-likes function eachOfArrayLike(coll, iteratee, callback) { callback = once(callback || noop); var index = 0, completed = 0, length = coll.length; if (length === 0) { callback(null); } function iteratorCallback(err, value) { if (err) { callback(err); } else if ((++completed === length) || value === breakLoop) { callback(null); } } for (; index < length; index++) { iteratee(coll[index], index, onlyOnce(iteratorCallback)); } } // a generic version of eachOf which can handle array, object, and iterator cases. var eachOfGeneric = doLimit(eachOfLimit, Infinity); /** * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument * to the iteratee. * * @name eachOf * @static * @memberOf module:Collections * @method * @alias forEachOf * @category Collection * @see [async.each]{@link module:Collections.each} * @param {Array|Iterable|Object} coll - A collection to iterate over. * @param {AsyncFunction} iteratee - A function to apply to each * item in `coll`. * The `key` is the item's key, or index in the case of an array. * Invoked with (item, key, callback). * @param {Function} [callback] - A callback which is called when all * `iteratee` functions have finished, or an error occurs. Invoked with (err). * @example * * var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"}; * var configs = {}; * * async.forEachOf(obj, function (value, key, callback) { * fs.readFile(__dirname + value, "utf8", function (err, data) { * if (err) return callback(err); * try { * configs[key] = JSON.parse(data); * } catch (e) { * return callback(e); * } * callback(); * }); * }, function (err) { * if (err) console.error(err.message); * // configs is now a map of JSON data * doSomethingWith(configs); * }); */ var eachOf = function(coll, iteratee, callback) { var eachOfImplementation = isArrayLike(coll) ? eachOfArrayLike : eachOfGeneric; eachOfImplementation(coll, wrapAsync(iteratee), callback); }; function doParallel(fn) { return function (obj, iteratee, callback) { return fn(eachOf, obj, wrapAsync(iteratee), callback); }; } function _asyncMap(eachfn, arr, iteratee, callback) { callback = callback || noop; arr = arr || []; var results = []; var counter = 0; var _iteratee = wrapAsync(iteratee); eachfn(arr, function (value, _, callback) { var index = counter++; _iteratee(value, function (err, v) { results[index] = v; callback(err); }); }, function (err) { callback(err, results); }); } /** * Produces a new collection of values by mapping each value in `coll` through * the `iteratee` function. The `iteratee` is called with an item from `coll` * and a callback for when it has finished processing. Each of these callback * takes 2 arguments: an `error`, and the transformed item from `coll`. If * `iteratee` passes an error to its callback, the main `callback` (for the * `map` function) is immediately called with the error. * * Note, that since this function applies the `iteratee` to each item in * parallel, there is no guarantee that the `iteratee` functions will complete * in order. However, the results array will be in the same order as the * original `coll`. * * If `map` is passed an Object, the results will be an Array. The results * will roughly be in the order of the original Objects' keys (but this can * vary across JavaScript engines). * * @name map * @static * @memberOf module:Collections * @method * @category Collection * @param {Array|Iterable|Object} coll - A collection to iterate over. * @param {AsyncFunction} iteratee - An async function to apply to each item in * `coll`. * The iteratee should complete with the transformed item. * Invoked with (item, callback). * @param {Function} [callback] - A callback which is called when all `iteratee` * functions have finished, or an error occurs. Results is an Array of the * transformed items from the `coll`. Invoked with (err, results). * @example * * async.map(['file1','file2','file3'], fs.stat, function(err, results) { * // results is now an array of stats for each file * }); */ var map = doParallel(_asyncMap); /** * Applies the provided arguments to each function in the array, calling * `callback` after all functions have completed. If you only provide the first * argument, `fns`, then it will return a function which lets you pass in the * arguments as if it were a single function call. If more arguments are * provided, `callback` is required while `args` is still optional. * * @name applyEach * @static * @memberOf module:ControlFlow * @method * @category Control Flow * @param {Array|Iterable|Object} fns - A collection of {@link AsyncFunction}s * to all call with the same arguments * @param {...*} [args] - any number of separate arguments to pass to the * function. * @param {Function} [callback] - the final argument should be the callback, * called when all functions have completed processing. * @returns {Function} - If only the first argument, `fns`, is provided, it will * return a function which lets you pass in the arguments as if it were a single * function call. The signature is `(..args, callback)`. If invoked with any * arguments, `callback` is required. * @example * * async.applyEach([enableSearch, updateSchema], 'bucket', callback); * * // partial application example: * async.each( * buckets, * async.applyEach([enableSearch, updateSchema]), * callback * ); */ var applyEach = applyEach$1(map); function doParallelLimit(fn) { return function (obj, limit, iteratee, callback) { return fn(_eachOfLimit(limit), obj, wrapAsync(iteratee), callback); }; } /** * The same as [`map`]{@link module:Collections.map} but runs a maximum of `limit` async operations at a time. * * @name mapLimit * @static * @memberOf module:Collections * @method * @see [async.map]{@link module:Collections.map} * @category Collection * @param {Array|Iterable|Object} coll - A collection to iterate over. * @param {number} limit - The maximum number of async operations at a time. * @param {AsyncFunction} iteratee - An async function to apply to each item in * `coll`. * The iteratee should complete with the transformed item. * Invoked with (item, callback). * @param {Function} [callback] - A callback which is called when all `iteratee` * functions have finished, or an error occurs. Results is an array of the * transformed items from the `coll`. Invoked with (err, results). */ var mapLimit = doParallelLimit(_asyncMap); /** * The same as [`map`]{@link module:Collections.map} but runs only a single async operation at a time. * * @name mapSeries * @static * @memberOf module:Collections * @method * @see [async.map]{@link module:Collections.map} * @category Collection * @param {Array|Iterable|Object} coll - A collection to iterate over. * @param {AsyncFunction} iteratee - An async function to apply to each item in * `coll`. * The iteratee should complete with the transformed item. * Invoked with (item, callback). * @param {Function} [callback] - A callback which is called when all `iteratee` * functions have finished, or an error occurs. Results is an array of the * transformed items from the `coll`. Invoked with (err, results). */ var mapSeries = doLimit(mapLimit, 1); /** * The same as [`applyEach`]{@link module:ControlFlow.applyEach} but runs only a single async operation at a time. * * @name applyEachSeries * @static * @memberOf module:ControlFlow * @method * @see [async.applyEach]{@link module:ControlFlow.applyEach} * @category Control Flow * @param {Array|Iterable|Object} fns - A collection of {@link AsyncFunction}s to all * call with the same arguments * @param {...*} [args] - any number of separate arguments to pass to the * function. * @param {Function} [callback] - the final argument should be the callback, * called when all functions have completed processing. * @returns {Function} - If only the first argument is provided, it will return * a function which lets you pass in the arguments as if it were a single * function call. */ var applyEachSeries = applyEach$1(mapSeries); /** * A specialized version of `_.forEach` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns `array`. */ function arrayEach(array, iteratee) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (iteratee(array[index], index, array) === false) { break; } } return array; } /** * Creates a base function for methods like `_.forIn` and `_.forOwn`. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseFor(fromRight) { return function(object, iteratee, keysFunc) { var index = -1, iterable = Object(object), props = keysFunc(object), length = props.length; while (length--) { var key = props[fromRight ? length : ++index]; if (iteratee(iterable[key], key, iterable) === false) { break; } } return object; }; } /** * The base implementation of `baseForOwn` which iterates over `object` * properties returned by `keysFunc` and invokes `iteratee` for each property. * Iteratee functions may exit iteration early by explicitly returning `false`. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} keysFunc The function to get the keys of `object`. * @returns {Object} Returns `object`. */ var baseFor = createBaseFor(); /** * The base implementation of `_.forOwn` without support for iteratee shorthands. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForOwn(object, iteratee) { return object && baseFor(object, iteratee, keys); } /** * The base implementation of `_.findIndex` and `_.findLastIndex` without * support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} predicate The function invoked per iteration. * @param {number} fromIndex The index to search from. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseFindIndex(array, predicate, fromIndex, fromRight) { var length = array.length, index = fromIndex + (fromRight ? 1 : -1); while ((fromRight ? index-- : ++index < length)) { if (predicate(array[index], index, array)) { return index; } } return -1; } /** * The base implementation of `_.isNaN` without support for number objects. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. */ function baseIsNaN(value) { return value !== value; } /** * A specialized version of `_.indexOf` which performs strict equality * comparisons of values, i.e. `===`. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function strictIndexOf(array, value, fromIndex) { var index = fromIndex - 1, length = array.length; while (++index < length) { if (array[index] === value) { return index; } } return -1; } /** * The base implementation of `_.indexOf` without `fromIndex` bounds checks. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseIndexOf(array, value, fromIndex) { return value === value ? strictIndexOf(array, value, fromIndex) : baseFindIndex(array, baseIsNaN, fromIndex); } /** * Determines the best order for running the {@link AsyncFunction}s in `tasks`, based on * their requirements. Each function can optionally depend on other functions * being completed first, and each function is run as soon as its requirements * are satisfied. * * If any of the {@link AsyncFunction}s pass an error to their callback, the `auto` sequence * will stop. Further tasks will not execute (so any other functions depending * on it will not run), and the main `callback` is immediately called with the * error. * * {@link AsyncFunction}s also receive an object containing the results of functions which * have completed so far as the first argument, if they have dependencies. If a * task function has no dependencies, it will only be passed a callback. * * @name auto * @static * @memberOf module:ControlFlow * @method * @category Control Flow * @param {Object} tasks - An object. Each of its properties is either a * function or an array of requirements, with the {@link AsyncFunction} itself the last item * in the array. The object's key of a property serves as the name of the task * defined by that property, i.e. can be used when specifying requirements for * other tasks. The function receives one or two arguments: * * a `results` object, containing the results of the previously executed * functions, only passed if the task has any dependencies, * * a `callback(err, result)` function, which must be called when finished, * passing an `error` (which can be `null`) and the result of the function's * execution. * @param {number} [concurrency=Infinity] - An optional `integer` for * determining the maximum number of tasks that can be run in parallel. By * default, as many as possible. * @param {Function} [callback] - An optional callback which is called when all * the tasks have been completed. It receives the `err` argument if any `tasks` * pass an error to their callback. Results are always returned; however, if an * error occurs, no further `tasks` will be performed, and the results object * will only contain partial results. Invoked with (err, results). * @returns undefined * @example * * async.auto({ * // this function will just be passed a callback * readData: async.apply(fs.readFile, 'data.txt', 'utf-8'), * showData: ['readData', function(results, cb) { * // results.readData is the file's contents * // ... * }] * }, callback); * * async.auto({ * get_data: function(callback) { * console.log('in get_data'); * // async code to get some data * callback(null, 'data', 'converted to array'); * }, * make_folder: function(callback) { * console.log('in make_folder'); * // async code to create a directory to store a file in * // this is run at the same time as getting the data * callback(null, 'folder'); * }, * write_file: ['get_data', 'make_folder', function(results, callback) { * console.log('in write_file', JSON.stringify(results)); * // once there is some data and the directory exists, * // write the data to a file in the directory * callback(null, 'filename'); * }], * email_link: ['write_file', function(results, callback) { * console.log('in email_link', JSON.stringify(results)); * // once the file is written let's email a link to it... * // results.write_file contains the filename returned by write_file. * callback(null, {'file':results.write_file, 'email':'user@example.com'}); * }] * }, function(err, results) { * console.log('err = ', err); * console.log('results = ', results); * }); */ var auto = function (tasks, concurrency, callback) { if (typeof concurrency === 'function') { // concurrency is optional, shift the args. callback = concurrency; concurrency = null; } callback = once(callback || noop); var keys$$1 = keys(tasks); var numTasks = keys$$1.length; if (!numTasks) { return callback(null); } if (!concurrency) { concurrency = numTasks; } var results = {}; var runningTasks = 0; var hasError = false; var listeners = Object.create(null); var readyTasks = []; // for cycle detection: var readyToCheck = []; // tasks that have been identified as reachable // without the possibility of returning to an ancestor task var uncheckedDependencies = {}; baseForOwn(tasks, function (task, key) { if (!isArray(task)) { // no dependencies enqueueTask(key, [task]); readyToCheck.push(key); return; } var dependencies = task.slice(0, task.length - 1); var remainingDependencies = dependencies.length; if (remainingDependencies === 0) { enqueueTask(key, task); readyToCheck.push(key); return; } uncheckedDependencies[key] = remainingDependencies; arrayEach(dependencies, function (dependencyName) { if (!tasks[dependencyName]) { throw new Error('async.auto task `' + key + '` has a non-existent dependency `' + dependencyName + '` in ' + dependencies.join(', ')); } addListener(dependencyName, function () { remainingDependencies--; if (remainingDependencies === 0) { enqueueTask(key, task); } }); }); }); checkForDeadlocks(); processQueue(); function enqueueTask(key, task) { readyTasks.push(function () { runTask(key, task); }); } function processQueue() { if (readyTasks.length === 0 && runningTasks === 0) { return callback(null, results); } while(readyTasks.length && runningTasks < concurrency) { var run = readyTasks.shift(); run(); } } function addListener(taskName, fn) { var taskListeners = listeners[taskName]; if (!taskListeners) { taskListeners = listeners[taskName] = []; } taskListeners.push(fn); } function taskComplete(taskName) { var taskListeners = listeners[taskName] || []; arrayEach(taskListeners, function (fn) { fn(); }); processQueue(); } function runTask(key, task) { if (hasError) return; var taskCallback = onlyOnce(function(err, result) { runningTasks--; if (arguments