'use strict';12Object.defineProperty(exports, "__esModule", {3value: true4});5exports.default = autoInject;67var _auto = require('./auto.js');89var _auto2 = _interopRequireDefault(_auto);1011var _wrapAsync = require('./internal/wrapAsync.js');1213var _wrapAsync2 = _interopRequireDefault(_wrapAsync);1415function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }1617var FN_ARGS = /^(?:async\s+)?(?:function)?\s*\w*\s*\(\s*([^)]+)\s*\)(?:\s*{)/;18var ARROW_FN_ARGS = /^(?:async\s+)?\(?\s*([^)=]+)\s*\)?(?:\s*=>)/;19var FN_ARG_SPLIT = /,/;20var FN_ARG = /(=.+)?(\s*)$/;2122function stripComments(string) {23let stripped = '';24let index = 0;25let endBlockComment = string.indexOf('*/');26while (index < string.length) {27if (string[index] === '/' && string[index + 1] === '/') {28// inline comment29let endIndex = string.indexOf('\n', index);30index = endIndex === -1 ? string.length : endIndex;31} else if (endBlockComment !== -1 && string[index] === '/' && string[index + 1] === '*') {32// block comment33let endIndex = string.indexOf('*/', index);34if (endIndex !== -1) {35index = endIndex + 2;36endBlockComment = string.indexOf('*/', index);37} else {38stripped += string[index];39index++;40}41} else {42stripped += string[index];43index++;44}45}46return stripped;47}4849function parseParams(func) {50const src = stripComments(func.toString());51let match = src.match(FN_ARGS);52if (!match) {53match = src.match(ARROW_FN_ARGS);54}55if (!match) throw new Error('could not parse args in autoInject\nSource:\n' + src);56let [, args] = match;57return args.replace(/\s/g, '').split(FN_ARG_SPLIT).map(arg => arg.replace(FN_ARG, '').trim());58}5960/**61* A dependency-injected version of the [async.auto]{@link module:ControlFlow.auto} function. Dependent62* tasks are specified as parameters to the function, after the usual callback63* parameter, with the parameter names matching the names of the tasks it64* depends on. This can provide even more readable task graphs which can be65* easier to maintain.66*67* If a final callback is specified, the task results are similarly injected,68* specified as named parameters after the initial error parameter.69*70* The autoInject function is purely syntactic sugar and its semantics are71* otherwise equivalent to [async.auto]{@link module:ControlFlow.auto}.72*73* @name autoInject74* @static75* @memberOf module:ControlFlow76* @method77* @see [async.auto]{@link module:ControlFlow.auto}78* @category Control Flow79* @param {Object} tasks - An object, each of whose properties is an {@link AsyncFunction} of80* the form 'func([dependencies...], callback). The object's key of a property81* serves as the name of the task defined by that property, i.e. can be used82* when specifying requirements for other tasks.83* * The `callback` parameter is a `callback(err, result)` which must be called84* when finished, passing an `error` (which can be `null`) and the result of85* the function's execution. The remaining parameters name other tasks on86* which the task is dependent, and the results from those tasks are the87* arguments of those parameters.88* @param {Function} [callback] - An optional callback which is called when all89* the tasks have been completed. It receives the `err` argument if any `tasks`90* pass an error to their callback, and a `results` object with any completed91* task results, similar to `auto`.92* @returns {Promise} a promise, if no callback is passed93* @example94*95* // The example from `auto` can be rewritten as follows:96* async.autoInject({97* get_data: function(callback) {98* // async code to get some data99* callback(null, 'data', 'converted to array');100* },101* make_folder: function(callback) {102* // async code to create a directory to store a file in103* // this is run at the same time as getting the data104* callback(null, 'folder');105* },106* write_file: function(get_data, make_folder, callback) {107* // once there is some data and the directory exists,108* // write the data to a file in the directory109* callback(null, 'filename');110* },111* email_link: function(write_file, callback) {112* // once the file is written let's email a link to it...113* // write_file contains the filename returned by write_file.114* callback(null, {'file':write_file, 'email':'[email protected]'});115* }116* }, function(err, results) {117* console.log('err = ', err);118* console.log('email_link = ', results.email_link);119* });120*121* // If you are using a JS minifier that mangles parameter names, `autoInject`122* // will not work with plain functions, since the parameter names will be123* // collapsed to a single letter identifier. To work around this, you can124* // explicitly specify the names of the parameters your task function needs125* // in an array, similar to Angular.js dependency injection.126*127* // This still has an advantage over plain `auto`, since the results a task128* // depends on are still spread into arguments.129* async.autoInject({130* //...131* write_file: ['get_data', 'make_folder', function(get_data, make_folder, callback) {132* callback(null, 'filename');133* }],134* email_link: ['write_file', function(write_file, callback) {135* callback(null, {'file':write_file, 'email':'[email protected]'});136* }]137* //...138* }, function(err, results) {139* console.log('err = ', err);140* console.log('email_link = ', results.email_link);141* });142*/143function autoInject(tasks, callback) {144var newTasks = {};145146Object.keys(tasks).forEach(key => {147var taskFn = tasks[key];148var params;149var fnIsAsync = (0, _wrapAsync.isAsync)(taskFn);150var hasNoDeps = !fnIsAsync && taskFn.length === 1 || fnIsAsync && taskFn.length === 0;151152if (Array.isArray(taskFn)) {153params = [...taskFn];154taskFn = params.pop();155156newTasks[key] = params.concat(params.length > 0 ? newTask : taskFn);157} else if (hasNoDeps) {158// no dependencies, use the function as-is159newTasks[key] = taskFn;160} else {161params = parseParams(taskFn);162if (taskFn.length === 0 && !fnIsAsync && params.length === 0) {163throw new Error("autoInject task functions require explicit parameters.");164}165166// remove callback param167if (!fnIsAsync) params.pop();168169newTasks[key] = params.concat(newTask);170}171172function newTask(results, taskCb) {173var newArgs = params.map(name => results[name]);174newArgs.push(taskCb);175(0, _wrapAsync2.default)(taskFn)(...newArgs);176}177});178179return (0, _auto2.default)(newTasks, callback);180}181module.exports = exports['default'];182183