eslint-disable-next-line mocha/prefer-arrow-callback
13239
function sendBadge(format, badgeData) {
          if (serverUnresponsive) {
            return
          }
          clearTimeout(serverResponsive)
          // Check for a change in the data.
          let dataHasChanged = false
          if (
            cached !== undefined &&
            cached.data.badgeData.text[1] !== badgeData.text[1]
          ) {
            dataHasChanged = true
          }
          // Add format to badge data.
          badgeData.format = format
          // Update information in the cache.
          const updatedCache = {
            reqs: cached ? cached.reqs + 1 : 1,
            dataChange: cached
              ? cached.dataChange + (dataHasChanged ? 1 : 0)
              : 1,
            time: +reqTime,
            interval: cacheInterval,
            data: { format, badgeData },
          }
          requestCache.set(cacheIndex, updatedCache)
          if (!cachedVersionSent) {
            const svg = makeBadge(badgeData)
            setCacheHeadersOnResponse(ask.res, badgeData.cacheLengthSeconds)
            makeSend(format, ask.res, end)(svg)
          }
        }
751661
function findEslintEnv(text) {
    let match, retv;

    eslintEnvPattern.lastIndex = 0;

    while ((match = eslintEnvPattern.exec(text))) {
        retv = Object.assign(retv || {}, commentParser.parseListConfig(match[1]));
    }

    return retv;
}
519564
function nextup(inst, orig, argv, event, cb) {
    return function nextupCallback(err, data) {
        if (err) return cb(err, null);
        if (_isQuoted(data)) return cb(null, _unquote(data));
        if (_isValue(data)) return cb(null, _entityToValue(data, inst.library));
        // Remove any nulls or undefineds from the list
        var compact = _compactList(data);
        // Allow the programmer to opt out for _minor_ perf gains
        if (inst.options.doIrreducibleListCheck) {
            // If no change, we'll keep looping forever, so just return
            if (IsEqual(orig, compact)) {
                Console.printWarning(inst, 'Detected irreducible list; exiting...');
                return cb(null, compact);
            }
        }
        return exec(inst, compact, argv, event, cb);
    };
}
761748
function (_opts) {
    // XXX What part of the comment below is still true? (We no longer
    // have Spark)
    //
    // Nested flush could plausibly happen if, say, a flush causes
    // DOM mutation, which causes a "blur" event, which runs an
    // app event handler that calls Deps.flush.  At the moment
    // Spark blocks event handlers during DOM mutation anyway,
    // because the LiveRange tree isn't valid.  And we don't have
    // any useful notion of a nested flush.
    //
    // https://app.asana.com/0/159908330244/385138233856
    if (inFlush)
      throw new Error("Can't call Deps.flush while flushing");

    if (inCompute)
      throw new Error("Can't flush inside Deps.autorun");

    inFlush = true;
    willFlush = true;
    throwFirstError = !! (_opts && _opts._throwFirstError);

    var finishedTry = false;
    try {
      while (pendingComputations.length ||
             afterFlushCallbacks.length) {

        // recompute all pending computations
        while (pendingComputations.length) {
          var comp = pendingComputations.shift();
          comp._recompute();
        }

        if (afterFlushCallbacks.length) {
          // call one afterFlush callback, which may
          // invalidate more computations
          var func = afterFlushCallbacks.shift();
          try {
            func();
          } catch (e) {
            _throwOrLog("afterFlush function", e);
          }
        }
      }
      finishedTry = true;
    } finally {
      if (! finishedTry) {
        // we're erroring
        inFlush = false; // needed before calling `Deps.flush()` again
        Deps.flush({_throwFirstError: false}); // finish flushing
      }
      willFlush = false;
      inFlush = false;
    }
  }
900359
function(renderer, opts){
		// handle parameters
		opts		= opts		|| {};
		var charCode	= opts.charCode	|| 'p'.charCodeAt(0);
		var width	= opts.width;
		var height	= opts.height;
		var callback	= opts.callback	|| function(url){
			window.open(url, "name-"+Math.random());
		};

		// callback to handle keypress
		var __bind	= function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
		var onKeyPress	= __bind(function(event){
			// return now if the KeyPress isnt for the proper charCode
			if( event.which !== charCode )	return;
			// get the renderer output
			var dataUrl	= this.toDataURL(renderer);

			if( width === undefined && height === undefined ){
				callback( dataUrl )
			}else{
				// resize it and notify the callback
				// * resize == async so if callback is a window open, it triggers the pop blocker
				_aspectResize(dataUrl, width, height, callback);				
			}
		}, this);

		// listen to keypress
		// NOTE: for firefox it seems mandatory to listen to document directly
		document.addEventListener('keypress', onKeyPress, false);

		return {
			unbind	: function(){
				document.removeEventListener('keypress', onKeyPress, false);
			}
		};
	}
1173076
function(next){
				if ( !options.translate )
					return next();
				l10ns('compile',  function(err, time){
					console.log("     l10ns compiled...".gray + time.green );
					return next();
				});
			}
810362
function (source, opts, cb) {
        var callback,
            options;

        if (arguments.length === 2) {
            options = defaults();
            callback = opts;
        } else {
            options = defaults(opts);
            callback = cb;
        }

        try {
            source = api.clean(source);
            callback(null, api.insert(source, getToc(source, options)));
        } catch (err) {
            callback(err, null);
        }
    }
1161472
function helpConsole() {
    /* eslint-disable no-console */
    console.log('  Examples:');
    console.log('');
    console.log('    $ renovate --token abc123 singapore/lint-condo');
    console.log(
      '    $ renovate --labels=renovate,dependency --ignore-unstable=false --log-level debug singapore/lint-condo'
    );
    console.log('    $ renovate singapore/lint-condo singapore/package-test');
    /* eslint-enable no-console */
  }
983757
function (subtype, context, done) {
    var types = this.types
      , loaded = {};
    this.allExtensions(function (type, id, plugin, next) {
      if (!plugin[subtype]) return next();
      if ('string' === typeof plugin[subtype]) {
        try {
          plugin[subtype] = require(path.resolve(path.join(plugin.dir, plugin[subtype])));
        } catch (e) {
          // eslint-disable-next-line no-console
          console.log('failed to load plugin', id, e.message, e.stack);
          e.message += '; error loading plugin ' + id;
          return next(e);
        }
      }

      if (!loaded[type]) loaded[type] = {};
      if (!types[type][subtype]) {
        loaded[type][id] = plugin[subtype];
        return next();
      }
      types[type][subtype](id, plugin[subtype], plugin, context, function (err, initialized) {
        loaded[type][id] = initialized;
        next(err);
      });
    }, function (err) {
      done(err, loaded);
    });
  }
1141416
function betterIndexOf(arr, value) {
    if (value != value || value === 0) { // eslint-disable-line eqeqeq
        var i = arr.length;
        while (i-- && !is(arr[i], value)) {
            // eslint-disable-line no-empty
        }
    } else {
        i = [].indexOf.call(arr, value);
    }
    return i;
}
1002147
function (next) {

            var reqOpts = {
                method: 'GET',
                url: helpers.makeAliasUri(options)
            }

            if(options.auth) {
                reqOpts.auth = {
                    user: options.auth.user,
                    pass: options.auth.password,
                    sendImmediately: false
                };
            }

            helpers.backOffRequest(reqOpts, function (err, res, body) {
                if (err) {
                    return next(err)
                }

                var existingIndices = Object.keys(body)

                // console.log('\nexistingIndices', body)

                var aliasName = helpers.makeIndexName(options)

                // get all aliases pertaining to this collection & are not the index we just created
                // we will remove all of them
                indicesToRemove = existingIndices.filter(function (indexName) {
                    return (indexName.indexOf(aliasName) === 0 && indexName !== versionedIndexName)
                })

                // console.log('\nindicesToRemove', indicesToRemove)

                // generate elasticsearch request body to atomically remove old indices and add the new one
                var requestBody = {
                    actions: [
                        {
                            add: {
                                alias: aliasName,
                                index: versionedIndexName
                            }
                        }
                    ]
                }

                indicesToRemove.forEach(function (indexToRemove) {
                    var removeObj = {
                        remove: {
                            alias: aliasName,
                            index: indexToRemove
                        }
                    }

                    requestBody.actions.unshift(removeObj)
                })

                var reqOpts = {
                    method: 'POST',
                    url: helpers.makeAliasUri(options),
                    body: JSON.stringify(requestBody)
                }

                if(options.auth) {
                    reqOpts.auth = {
                        user: options.auth.user,
                        pass: options.auth.password,
                        sendImmediately: false
                    };
                }

                helpers.backOffRequest(reqOpts, function (err, res, body) {
                    if (err) {
                        return next(err)
                    }

                    if (!helpers.elasticsearchBodyOk(body)) {
                        var error = new Error('Alias deletion error. Elasticsearch reply:'+util.inspect(body, true, 10, true))
                        error.elasticsearchReply = body
                        error.elasticsearchRequestBody = requestBody
                        return next(error)
                    }

                    return next()
                })
            })
        }
818037
function Slack(opts, debug) {
  if (!(this instanceof Slack)) return new Slack(opts);
  this.opts = opts;
  this.debug = debug;

  /**
   * Do everything.
   */

  this.import = function *() {
    try {
      console.log('Starting import');
      yield this.tokens();
      console.log('Got tokens');
      yield this.login();
      console.log('Logged in');
    } catch (e) {
      console.log('Uh oh! ' + e);
      throw e;
    }
    console.log('Getting emoji page');
    var emojiList = '';
    var aliasList = '';
    for (var i = 0; i < Object.keys(this.opts.emojis).length; i++) {
      var e = this.opts.emojis[i];
      if (e.src) {
        var uploadRes = yield this.upload(e.name, e.src);
        emojiList += ' :' + e.name + ':';
      }
      if (e.aliases) {
        for (var n = 0; n < e.aliases.length; n++) {
          yield this.alias(e.name, e.aliases[n]);
          aliasList += ' :' + e.aliases[n] + ':';
        }
      }
    }
    console.log('Uploaded emojis:' + emojiList);
    console.log('Uploaded emoji aliases:' + aliasList);
    return 'Success';
  };

  /**
   * Get login page (aka credentials).
   */

  this.tokens = function *() {
    var opts = this.opts;
    opts.jar = opts.jar || { _jar: { store: { idx: {} } } };
    var load = {
      url: opts.url + loginFormPath,
      headers: headers,
      jar: opts.jar,
      method: 'GET'
    };
    var res = yield request(load);
    var $ = cheerio.load(res[0].body);
    if (this.debug) write($('title').text(), $.html());
    opts.formData = {
      signin: $('#signin_form input[name="signin"]').attr('value'),
      redir: $('#signin_form input[name="redir"]').attr('value'),
      crumb: $('#signin_form input[name="crumb"]').attr('value'),
      remember: 'on',
      email: opts.email,
      password: opts.password
    };
    if (!opts.formData.signin && !opts.formData.redir && !opts.formData.crumb) throw new Error('Login error: could not get login form for ' + opts.url);
    return this.opts = opts;
  };

  /**
   * Log into Slack and populate cookies.
   */

  this.login = function *() {
    var opts = this.opts;
    var load = {
      url: opts.url + loginFormPath,
      headers: headers,
      jar: opts.jar,
      method: 'POST',
      followAllRedirects: true,
      formData: opts.formData
    };
    var res = yield request(load);
    if(res[0].body.indexOf("Sorry, you entered an incorrect email address or password.") != -1){
      throw new Error('Login error: incorrect username / password');
    }

    if(res[0].body.indexOf("Enter your authentication code") != -1){

      var $ = cheerio.load(res[0].body);

      var inputs = $("form input")

      var formData = {};

      inputs.each(function(i,v){
        formData[v.attribs.name] = v.attribs.value;
      })

      user_2fa_code = yield ask('2FA Code: ', isPassword, 'A password (as defined by this script) needs to have at least one character (not including you).');
      formData["2fa_code"] = user_2fa_code

      delete formData[undefined]
      delete formData['input']

      var load_2fa = {
        url: opts.url + "/",
        headers: headers,
        jar: opts.jar,
        method: 'POST',
        followAllRedirects: true,
        formData: formData
      };
      res = yield request(load_2fa);
    }

    //TODO: it may be necessary in the future to replace this with a user-supplied token
    var match = apiTokenRegex.exec(res[0].body);
    if (!match || !match[1]) {
      throw new Error('Application Error: unable to find api token on login page');
    }
    opts.apiToken = match[1];

    return this.opts = opts;
  };

  /**
   * Upload the emoji.
   */

  this.upload = function *(name, emoji) {
    console.log('Uploading %s with %s', name, emoji);
    return new Promise(function(resolve, reject, notify) {
      var opts = this.opts;
      var r = req({
        url: opts.url + emojiAddEndpoint,
        headers: headers,
        method: 'POST',
        jar: opts.jar,
        followAllRedirects: true
      }, function(err, res, body) {
        if (err || !body) return reject(err);
        resolve(body);
      });
      var form = r.form();
      form.append('name', name);
      form.append('mode', 'data');
      form.append('image', req(emoji));
      form.append('token', opts.apiToken);
    }.bind(this));
  };

  this.alias = function *(name, alias) {
    console.log('Aliasing %s to %s', alias, name);
    return new Promise(function(resolve, reject, notify) {
      var opts = this.opts;
      var r = req({
        url: opts.url + emojiAddEndpoint,
      headers: {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'},
        method: 'POST',
        jar: opts.jar,
        followAllRedirects: true
      }, function(err, res, body) {
        if (err || !body) return reject(err);
        resolve(body);
      });
      var form = r.form();
      form.append('name', alias);
      form.append('mode', 'alias');
      form.append('alias', name);
      form.append('token', opts.apiToken);
    }.bind(this));
  };
}
1286429
function f (data, opts, callback) {
  data = unpack(data)

  if (!callback) {
    [callback, opts] = [opts, {}]
  }

  let match = opts.match || /\sx($|\s)/
  let need = []

  for (let browser in data.stats) {
    let versions = data.stats[browser]
    for (let version in versions) {
      let support = versions[version]
      if (support.match(match)) {
        need.push(browser + ' ' + version)
      }
    }
  }

  callback(need.sort(browsersSort))
}
868241
async function asyncForEach(array, callback) {
  for (let index = 0; index < array.length; index++) {
    // eslint-disable-next-line no-await-in-loop
    await callback(array[index], index, array);
  }
}
559224
function breadthFirstSearch(obj, handler) {
  var childrenKey = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'children';
  var reverse = arguments[3];

  var rootChildren = hp.isArray(obj) ? obj : [obj];
  //
  var stack = rootChildren.map(function (v, i) {
    return { item: v, index: i };
  });
  if (reverse) {
    stack.reverse();
  }

  var _loop = function _loop() {
    var _stack$shift = stack.shift(),
        item = _stack$shift.item,
        index = _stack$shift.index,
        parent = _stack$shift.parent;

    var r = handler(item, index, parent);
    if (r === false) {
      // stop
      return {
        v: void 0
      };
    } else if (r === 'skip children') {
      return 'continue';
    } else if (r === 'skip siblings') {
      stack = stack.filter(function (v) {
        return v.parent !== parent;
      });
    }
    if (item.children) {
      var _stack;

      var children = item.children;
      if (reverse) {
        children = children.slice();
        children.reverse();
      }
      var pushStack = children.map(function (v, i) {
        return { item: v, index: i, parent: item };
      });
      (_stack = stack).push.apply(_stack, _toConsumableArray(pushStack));
    }
  };

  while (stack.length) {
    var _ret = _loop();

    switch (_ret) {
      case 'continue':
        continue;

      default:
        if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v;
    }
  }
}
798192
function nextTick (next, err) {
  return process.nextTick(function () {
    try {
      next(err)
    } catch (e) {
      // istanbul ignore next
      next(e)
    }
  })
}
759820
function gulpHtmlLint(options) {
	let htmlLintOptions = {},
		issueFileCount = 0,
		issueCount = 0;

	options = options || {};
	options.htmllintrc = options.htmllintrc || '.htmllintrc';
	options.useHtmllintrc = options.useHtmllintrc !== false;
	options.plugins = options.plugins || [];
	options.limitFiles = options.limitFiles || (options.bail ? 1 : Number.MAX_VALUE);
	options.limitIssuesPerFile = options.limitIssuesPerFile || Number.MAX_VALUE;
	options.limitIssues = options.limitIssues || Number.MAX_VALUE;

	// load htmllint rules
	if (options.useHtmllintrc && fs.existsSync(options.htmllintrc)) {
		htmlLintOptions = JSON.parse(fs.readFileSync(options.htmllintrc, 'utf8'));
	}
	if (options.rules && typeof options.rules === 'object') {
		Object.keys(options.rules).forEach((prop) => {
			htmlLintOptions[prop] = options.rules[prop];
		});
	}

	// use plugins
	htmllint.use(options.plugins);

	return transform((file, enc, cb) => {
		if (file.isNull()) return cb(null, file);
		if (file.isStream()) return cb(new gutil.PluginError(PLUGIN_NAME, 'Streaming not supported'));
		if (issueFileCount >= options.limitFiles ||
			issueCount >= options.limitIssues) return cb(null, file);
		const relativeFilePath = path.relative(process.cwd(), file.path);
		htmllint(file.contents.toString(), htmlLintOptions)
			.then((issues) => {
				if (issues && issues.length) {
					let errorCount = 0,
						warningCount = 0;
					issueFileCount++;
					issueCount += issues.length;
					issues.forEach((issue) => {
						if (issue.code.indexOf('E') === 0) {
							issue.error = true;
							errorCount++;
						} else {
							issue.error = false;
							warningCount++;
						}
						issue.warning = !issue.error;
						issue.message = issue.message || htmllint.messages.renderIssue(issue);
					});
					file.htmlLint = {
						filePath: file.path,
						issues: issues.splice(0, Math.min(issues.length, options.limitIssuesPerFile)),
						relativeFilePath,
						errorCount,
						warningCount
					};
				}
				cb(null, file);
			}, () => {
				return cb(new gutil.PluginError(PLUGIN_NAME, `Could not lint html file: ${relativeFilePath}`));
			});
	});
}