(function (native_require, this_module) {

// based on TJ Holowaychuk's commonjs require binding

function require(p, root) {
  // third-party module?  use native require
  if ('.' != p[0] && '/' != p[0])
    return native_require(p);

  root = root || 'root';

  var path = require.resolve(p);

  // if it's a non-registered json file, it
  // must be at the root of the project
  if (!path && /\.json$/i.test(p))
    return native_require('./' + require.basename(p));

  var module = require.cache[path];

  if (!module) {
    try {
      return native_require(p);
    } catch (err) {
      throw new Error('failed to require "' + p + '" from ' + root +'\n' + err.message + '\n' + err.stack);
    }
  }

  if (!module.exports) {
    module.exports = {};
    module.call(module.exports, module, module.exports,
      require.relative(path));
  }

  return module.exports;
}

// same as node's `require`
require.cache = {};

// node's native `path.basename`
require.basename = native_require('path').basename;

require.resolve = function (path) {
  // GH-12
  if ('.' != path[0]) return native_require.resolve(path);

  var pathWithSlash = path.slice(-1) === '/' ? path : path + '/';
  var paths = [
    path,
    path + '.js',
    pathWithSlash + 'index.js',
    path + '.json',
    pathWithSlash + 'index.json'
  ];

  for (var i = 0, p; p = paths[i]; i++) {
    if (require.cache[p]) return p;
  }
};

require.register = function (path, fn) {
  require.cache[path] = fn;
};

require.relative = function (parent) {
  function relative(p) {
    if ('.' != p[0]) return require(p);

    var path = parent.split('/');
    var segs = p.split('/');
    path.pop();

    for (var i = 0, len = segs.length; i < len; i += 1) {
      var seg = segs[i];
      if ('..' == seg) {
        path.pop();
      } else if ('.' != seg) {
        path.push(seg);
      }
    }

    return require(path.join('/'), parent);
  }

  relative.resolve = require.resolve;
  relative.cache = require.cache;
  return relative;
};

require.register("./index.js",function (module, exports, require) {require("coffee-script/register")
require("./lib/cypress").start(process.argv)
});
require.register("./lib/api.js",function (module, exports, require) {(function() {
  var Routes, errors, os, pkg, provider, r, rp;

  os = require("os");

  r = require("request");

  rp = require("request-promise");

  errors = require("request-promise/errors");

  Routes = require("./util/routes");

  pkg = require("../package.json");

  provider = require("./util/provider");

  module.exports = {
    ping: function() {
      return rp.get(Routes.ping());
    },
    createCi: function(options) {
      if (options == null) {
        options = {};
      }
      return rp.post({
        url: Routes.ci(options.projectId),
        json: true,
        headers: {
          "x-project-token": options.key,
          "x-project-name": options.projectName,
          "x-git-branch": options.branch,
          "x-git-author": options.author,
          "x-git-message": options.message,
          "x-version": pkg.version,
          "x-platform": os.platform(),
          "x-provider": provider.get()
        }
      }).promise().get("ci_guid");
    },
    updateCi: function(options) {
      if (options == null) {
        options = {};
      }
      return rp.put({
        url: Routes.ci(options.projectId),
        json: true,
        body: options.stats,
        timeout: 10000,
        headers: {
          "x-ci-id": options.ciId,
          "x-project-token": options.key,
          "x-project-name": options.projectName,
          "x-version": pkg.version,
          "x-platform": os.platform(),
          "x-provider": provider.get()
        }
      });
    },
    createRaygunException: function(body, session, timeout) {
      if (timeout == null) {
        timeout = 3000;
      }
      return rp.post({
        url: Routes.exceptions(),
        body: body,
        json: true,
        headers: {
          "x-session": session
        }
      }).promise().timeout(timeout);
    },
    createSignin: function(code) {
      return rp.post({
        url: Routes.signin({
          code: code
        }),
        json: true,
        headers: {
          "x-platform": os.platform(),
          "x-version": pkg.version
        }
      })["catch"](errors.StatusCodeError, function(err) {
        err.message = err.message.split(" - ").slice(1).join("");
        throw err;
      });
    },
    createSignout: function(session) {
      return rp.post({
        url: Routes.signout(),
        headers: {
          "x-session": session,
          "x-platform": os.platform(),
          "x-version": pkg.version
        }
      });
    },
    createProject: function(projectName, session) {
      return rp.post({
        url: Routes.projects(),
        json: true,
        headers: {
          "x-session": session,
          "x-platform": os.platform(),
          "x-version": pkg.version,
          "x-project-name": projectName
        }
      }).promise().get("uuid");
    },
    updateProject: function(projectId, type, projectName, session) {
      return rp.get({
        url: Routes.project(projectId),
        json: true,
        headers: {
          "x-type": type,
          "x-session": session,
          "x-platform": os.platform(),
          "x-version": pkg.version,
          "x-project-name": projectName
        }
      });
    },
    getBuilds: function(projectId, session) {
      return r.get({
        url: Routes.projectCi(projectId),
        json: true,
        headers: {
          "x-session": session
        }
      });
    },
    getLoginUrl: function() {
      return rp.get({
        url: Routes.auth(),
        json: true
      }).promise().get("url");
    },
    _token: function(method, session) {
      return rp({
        method: method,
        url: Routes.token(),
        json: true,
        headers: {
          "x-session": session
        }
      }).promise().get("api_token");
    },
    getToken: function(session) {
      return this._token("get", session);
    },
    updateToken: function() {
      return this._token("put", session);
    },
    _projectToken: function(method, projectId, session) {
      return rp({
        method: method,
        url: Routes.projectToken(projectId),
        json: true,
        headers: {
          "x-session": session
        }
      }).promise().get("api_token");
    },
    getProjectToken: function(projectId, session) {
      return this._projectToken("get", projectId, session);
    },
    updateProjectToken: function(projectId, session) {
      return this._projectToken("put", projectId, session);
    }
  };

}).call(this);

});
require.register("./lib/cache.js",function (module, exports, require) {(function() {
  var CACHE, PSemaphore, Promise, _, api, errors, fs, konfig, logger, path, queue, request,
    indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; },
    slice = [].slice;

  _ = require("lodash");

  fs = require("fs-extra");

  path = require("path");

  Promise = require("bluebird");

  PSemaphore = require("promise-semaphore");

  request = require("request-promise");

  errors = require("request-promise/errors");

  api = require("./api");

  konfig = require("./konfig");

  logger = require("./logger");

  CACHE = konfig("cache_path");

  fs = Promise.promisifyAll(fs);

  queue = new PSemaphore;

  module.exports = {
    path: CACHE,
    ensureExists: function() {
      return queue.add((function(_this) {
        return function() {
          return fs.readJsonAsync(CACHE).then(function(json) {
            if (!json.USER) {
              json.USER = {};
            }
            if (!json.PROJECTS) {
              json.PROJECTS = [];
            }
            return _this.write(json, false);
          }).then(function(json) {
            if (!_.isArray(json.PROJECTS)) {
              json = _this.convertLegacyCache(json);
              return _this.write(json, false);
            }
          })["return"](true)["catch"](function() {
            return _this.write(_this.defaults(), false);
          });
        };
      })(this));
    },
    exists: function() {
      return this.ensureExists()["return"](true)["catch"](false);
    },
    defaults: function() {
      return {
        USER: {},
        PROJECTS: []
      };
    },
    convertLegacyCache: function(json) {
      json.PROJECTS = _.chain(json.PROJECTS).values().map("PATH").compact().value();
      return json;
    },
    read: function() {
      return this.ensureExists().then(function() {
        return queue.add((function(_this) {
          return function() {
            return fs.readJsonAsync(CACHE);
          };
        })(this));
      });
    },
    write: function(obj, enableQueue) {
      var write;
      if (obj == null) {
        obj = {};
      }
      if (enableQueue == null) {
        enableQueue = true;
      }
      logger.info("writing to .cy cache", {
        cache: obj
      });
      write = function() {
        return fs.outputJsonAsync(CACHE, obj, {
          spaces: 2
        })["return"](obj);
      };
      if (enableQueue) {
        return queue.add(write);
      } else {
        return write();
      }
    },
    _mergeOrWrite: function(contents, key, val) {
      switch (false) {
        case !_.isString(key):
          if (contents[key] == null) {
            contents[key] = {};
          }
          _.extend(contents[key], val);
          break;
        case !_.isObject(key):
          _.extend(contents, key);
      }
      return this.write(contents);
    },
    _set: function(key, val) {
      return this.read().then((function(_this) {
        return function(contents) {
          return _this._mergeOrWrite(contents, key, val);
        };
      })(this));
    },
    _get: function(key) {
      return this.read().then(function(contents) {
        return contents[key];
      });
    },
    insertProject: function(path) {
      return this._getProjects().then((function(_this) {
        return function(projects) {
          if (indexOf.call(projects, path) >= 0) {
            return projects;
          }
          projects.push(path);
          return _this._set("PROJECTS", projects);
        };
      })(this));
    },
    _getProjects: function() {
      return this._get("PROJECTS");
    },
    _removeProjects: function(projects, paths) {
      projects = _.without.apply(_, [projects].concat(slice.call([].concat(paths))));
      return this._set({
        PROJECTS: projects
      });
    },
    getProjectPaths: function() {
      return this._getProjects().then((function(_this) {
        return function(projects) {
          var pathsToRemove;
          pathsToRemove = Promise.reduce(projects, function(memo, path) {
            return queue.add(function() {
              return fs.statAsync(path)["catch"](function() {
                return memo.push(path);
              })["return"](memo);
            });
          }, []);
          return pathsToRemove.then(function(removedPaths) {
            return _this._removeProjects(projects, removedPaths);
          }).then(function() {
            return _this._getProjects();
          });
        };
      })(this));
    },
    removeProject: function(path) {
      return this._getProjects().then((function(_this) {
        return function(projects) {
          return _this._removeProjects(projects, path);
        };
      })(this));
    },
    getUser: function() {
      logger.info("getting user");
      return this._get("USER");
    },
    setUser: function(user) {
      logger.info("setting user", {
        user: user
      });
      return this._set({
        USER: user
      });
    },
    removeUser: function() {
      return this._set({
        USER: {}
      });
    },
    remove: function() {
      return fs.removeAsync(CACHE);
    },
    removeSync: function() {
      return fs.removeSync(CACHE);
    }
  };

}).call(this);

});
require.register("./lib/config.js",function (module, exports, require) {(function() {
  var Promise, _, coerce, configKeys, convertRelativeToAbsolutePaths, cypressEnvRe, dashesOrUnderscoresRe, defaults, folders, isCypressEnvLike, path, scaffold, settings, str;

  _ = require("lodash");

  str = require("underscore.string");

  path = require("path");

  Promise = require("bluebird");

  coerce = require("./util/coerce");

  settings = require("./util/settings");

  scaffold = require("./scaffold");

  cypressEnvRe = /^(cypress_)/i;

  dashesOrUnderscoresRe = /^(_-)+/;

  folders = "fileServerFolder supportFolder fixturesFolder integrationFolder unitFolder".split(" ");

  configKeys = "port reporter baseUrl commandTimeout pageLoadTimeout requestTimeout responseTimeout waitForAnimations animationDistanceThreshold watchForFileChanges viewportWidth viewportHeight fileServerFolder supportFolder fixturesFolder integrationFolder environmentVariables".split(" ");

  isCypressEnvLike = function(key) {
    return cypressEnvRe.test(key) && key !== "CYPRESS_ENV";
  };

  defaults = {
    morgan: true,
    baseUrl: null,
    socketId: null,
    isHeadless: false,
    reporter: "spec",
    clientRoute: "/__/",
    xhrRoute: "/xhrs/",
    socketIoRoute: "/__socket.io",
    commandTimeout: 4000,
    pageLoadTimeout: 30000,
    requestTimeout: 5000,
    responseTimeout: 20000,
    port: 2020,
    waitForAnimations: true,
    animationDistanceThreshold: 5,
    watchForFileChanges: true,
    autoOpen: false,
    viewportWidth: 1000,
    viewportHeight: 660,
    fileServerFolder: "",
    supportFolder: "cypress/support",
    fixturesFolder: "cypress/fixtures",
    integrationFolder: "cypress/integration",
    javascripts: [],
    namespace: "__cypress"
  };

  convertRelativeToAbsolutePaths = function(projectRoot, obj, defaults) {
    if (defaults == null) {
      defaults = {};
    }
    return _.reduce(folders, function(memo, folder) {
      var def, val;
      val = obj[folder];
      if (val != null) {
        if (val === false && (def = defaults[folder])) {
          memo[folder + "Remove"] = true;
          memo[folder] = path.resolve(projectRoot, def);
        } else {
          memo[folder] = path.resolve(projectRoot, val);
        }
      }
      return memo;
    }, {});
  };

  module.exports = {
    getConfigKeys: function() {
      return configKeys;
    },
    whitelist: function(obj) {
      if (obj == null) {
        obj = {};
      }
      return _.pick(obj, configKeys);
    },
    get: function(projectRoot, options) {
      if (options == null) {
        options = {};
      }
      return Promise.all([settings.read(projectRoot), settings.readEnv(projectRoot)]).spread((function(_this) {
        return function(settings, envFile) {
          return _this.set({
            projectName: _this.getNameFromRoot(projectRoot),
            projectRoot: projectRoot,
            config: settings,
            envFile: envFile,
            options: options
          });
        };
      })(this));
    },
    set: function(obj) {
      var config, envFile, options, projectName, projectRoot;
      if (obj == null) {
        obj = {};
      }
      projectRoot = obj.projectRoot, projectName = obj.projectName, config = obj.config, envFile = obj.envFile, options = obj.options;
      if (config == null) {
        config = {};
      }
      config.envFile = envFile;
      config.projectRoot = projectRoot;
      config.projectName = projectName;
      return this.mergeDefaults(config, options);
    },
    mergeDefaults: function(config, options) {
      var resolved, url;
      if (config == null) {
        config = {};
      }
      if (options == null) {
        options = {};
      }
      resolved = {};
      _.extend(config, _.pick(options, "morgan", "isHeadless", "socketId", "report"));
      _.each(this.whitelist(options), function(val, key) {
        resolved[key] = "cli";
        config[key] = val;
      });
      if (url = config.baseUrl) {
        config.baseUrl = str.rtrim(url, "/");
      }
      _.defaults(config, defaults);
      config.environmentVariables = this.parseEnv(config, resolved);
      config.env = process.env["CYPRESS_ENV"];
      delete config.envFile;
      config = this.setResolvedConfigValues(config, defaults, resolved);
      config = this.setUrls(config);
      config = this.setAbsolutePaths(config, defaults);
      config = this.setParentTestsPaths(config);
      config = this.setScaffoldPaths(config);
      return config;
    },
    setResolvedConfigValues: function(config, defaults, resolved) {
      var obj;
      obj = _.clone(config);
      obj.resolved = this.resolveConfigValues(config, defaults, resolved);
      return obj;
    },
    resolveConfigValues: function(config, defaults, resolved) {
      if (resolved == null) {
        resolved = {};
      }
      return _.chain(config).pick(configKeys).mapValues(function(val, key) {
        var r, source;
        source = function(s) {
          return {
            value: val,
            from: s
          };
        };
        switch (false) {
          case !(r = resolved[key]):
            if (_.isObject(r)) {
              return r;
            } else {
              return source(r);
            }
            break;
          case !!_.isEqual(config[key], defaults[key]):
            return source("config");
          default:
            return source("default");
        }
      }).value();
    },
    setScaffoldPaths: function(obj) {
      var fileName;
      obj = _.clone(obj);
      fileName = scaffold.integrationExampleName();
      obj.integrationExampleFile = path.join(obj.integrationFolder, fileName);
      obj.integrationExampleName = fileName;
      return obj;
    },
    setParentTestsPaths: function(obj) {
      var prd, ptfd;
      obj = _.clone(obj);
      ptfd = obj.parentTestsFolder = path.dirname(obj.integrationFolder);
      prd = path.dirname(obj.projectRoot);
      obj.parentTestsFolderDisplay = path.relative(prd, ptfd);
      return obj;
    },
    setAbsolutePaths: function(obj, defaults) {
      var pr;
      obj = _.clone(obj);
      if (pr = obj.projectRoot) {
        _.extend(obj, convertRelativeToAbsolutePaths(pr, obj, defaults));
      }
      return obj;
    },
    setUrls: function(obj) {
      var rootUrl;
      obj = _.clone(obj);
      rootUrl = "http://localhost:" + obj.port;
      _.extend(obj, {
        clientUrlDisplay: rootUrl,
        clientUrl: rootUrl + obj.clientRoute,
        xhrUrl: obj.namespace + obj.xhrRoute
      });
      return obj;
    },
    parseEnv: function(cfg, resolved) {
      var configFromEnv, envCLI, envCfg, envFile, envProc, envVars, matchesConfigKey, ref, ref1, ref2, ref3, resolveFrom;
      if (resolved == null) {
        resolved = {};
      }
      envVars = resolved.environmentVariables = {};
      resolveFrom = function(from, obj) {
        if (obj == null) {
          obj = {};
        }
        return _.each(obj, function(val, key) {
          return envVars[key] = {
            value: val,
            from: from
          };
        });
      };
      envCfg = (ref = cfg.env) != null ? ref : {};
      envFile = (ref1 = cfg.envFile) != null ? ref1 : {};
      envProc = (ref2 = this.getProcessEnvVars(process.env)) != null ? ref2 : {};
      envCLI = (ref3 = cfg.environmentVariables) != null ? ref3 : {};
      matchesConfigKey = function(key) {
        if (_.has(cfg, key)) {
          return key;
        }
        key = key.toLowerCase().replace(dashesOrUnderscoresRe, "");
        key = str.camelize(key);
        if (_.has(cfg, key)) {
          return key;
        }
      };
      configFromEnv = _.reduce(envProc, function(memo, val, key) {
        var cfgKey;
        if (cfgKey = matchesConfigKey(key)) {
          if (resolved[cfgKey] !== "cli") {
            cfg[cfgKey] = val;
            resolved[cfgKey] = {
              value: val,
              from: "env"
            };
          }
          memo.push(key);
        }
        return memo;
      }, []);
      envProc = _.omit(envProc, configFromEnv);
      resolveFrom("config", envCfg);
      resolveFrom("envFile", envFile);
      resolveFrom("env", envProc);
      resolveFrom("cli", envCLI);
      return _.extend(envCfg, envFile, envProc, envCLI);
    },
    getProcessEnvVars: function(obj) {
      var normalize;
      if (obj == null) {
        obj = {};
      }
      normalize = function(key) {
        return key.replace(cypressEnvRe, "");
      };
      return _.reduce(obj, function(memo, value, key) {
        if (isCypressEnvLike(key)) {
          memo[normalize(key)] = coerce(value);
        }
        return memo;
      }, {});
    },
    getNameFromRoot: function(root) {
      if (root == null) {
        root = "";
      }
      return path.basename(root);
    }
  };

}).call(this);

});
require.register("./lib/controllers/builds.js",function (module, exports, require) {(function() {
  var api, request, user;

  request = require("request");

  api = require("../api");

  user = require("../user");

  module.exports = {
    handle: function(req, res, config, next) {
      return user.get().then((function(_this) {
        return function(user) {
          return api.getBuilds(config.projectId, user != null ? user.session_token : void 0).on("error", next).pipe(res);
        };
      })(this));
    }
  };

}).call(this);

});
require.register("./lib/controllers/files.js",function (module, exports, require) {(function() {
  var CacheBuster, Promise, _, cwd, glob, path, pathHelpers, str;

  _ = require("lodash");

  str = require("underscore.string");

  path = require("path");

  glob = require("glob");

  Promise = require("bluebird");

  cwd = require("../cwd");

  pathHelpers = require("../util/path_helpers");

  CacheBuster = require("../util/cache_buster");

  glob = Promise.promisify(glob);

  module.exports = {
    handleFiles: function(req, res, config) {
      return this.getTestFiles(config).then(function(files) {
        return res.json(files);
      });
    },
    handleIframe: function(req, res, config) {
      var iframePath, test;
      test = req.params[0];
      iframePath = cwd("lib", "html", "iframe.html");
      return this.getSpecs(test, config).then((function(_this) {
        return function(specs) {
          return _this.getJavascripts(config).then(function(js) {
            return res.render(iframePath, {
              title: _this.getTitle(test),
              javascripts: js,
              specs: specs
            });
          });
        };
      })(this));
    },
    getSpecs: function(spec, config) {
      var convertSpecPath, getSpecs;
      convertSpecPath = (function(_this) {
        return function(spec) {
          spec = pathHelpers.getAbsolutePathToSpec(spec, config);
          return _this.prepareForBrowser(spec, config.projectRoot);
        };
      })(this);
      getSpecs = (function(_this) {
        return function() {
          if (spec === "__all") {
            return _this.getTestFiles(config).map(function(spec) {
              return spec.name;
            }).map(convertSpecPath);
          } else {
            return [convertSpecPath(spec)];
          }
        };
      })(this);
      return Promise["try"]((function(_this) {
        return function() {
          return getSpecs();
        };
      })(this));
    },
    prepareForBrowser: function(filePath, projectRoot) {
      filePath = path.relative(projectRoot, filePath);
      return this.getTestUrl(filePath);
    },
    getTestUrl: function(file) {
      file += CacheBuster.get();
      return "/__cypress/tests?p=" + file;
    },
    getTitle: function(test) {
      if (test === "__all") {
        return "All Tests";
      } else {
        return test;
      }
    },
    getJavascripts: function(config) {
      var files, javascripts, paths, projectRoot, supportFolder;
      projectRoot = config.projectRoot, javascripts = config.javascripts, supportFolder = config.supportFolder;
      files = [].concat(path.join(supportFolder, "**", "*"), javascripts);
      paths = _.map(files, function(file) {
        return path.resolve(projectRoot, file);
      });
      return Promise.map(paths, function(p) {
        if (!p.includes("*")) {
          return p;
        }
        p = path.resolve(projectRoot, p);
        return glob(p);
      }).then(_.flatten).map((function(_this) {
        return function(filePath) {
          return _this.prepareForBrowser(filePath, projectRoot);
        };
      })(this));
    },
    getTestFiles: function(config) {
      var fixturesFolderPath, integrationFolderPath, javascriptsPath, options, prependIntegrationPath, supportFolderPath;
      integrationFolderPath = config.integrationFolder;
      fixturesFolderPath = path.join(config.fixturesFolder, "**", "*");
      supportFolderPath = path.join(config.supportFolder, "**", "*");
      javascriptsPath = _.map(config.javascripts, function(js) {
        return path.join(config.projectRoot, js);
      });
      options = {
        sort: true,
        realpath: true,
        cwd: integrationFolderPath,
        ignore: [].concat(javascriptsPath, supportFolderPath, fixturesFolderPath)
      };
      prependIntegrationPath = function(file) {
        return path.join("integration", path.relative(integrationFolderPath, file));
      };
      return glob("**/*.+(js|coffee)", options).map(function(file) {
        return {
          name: prependIntegrationPath(file)
        };
      });
    }
  };

}).call(this);

});
require.register("./lib/controllers/proxy.js",function (module, exports, require) {(function() {
  var Domain, UrlHelpers, _, badCookieParamRe, cwd, escapeRegExp, fs, headRe, htmlRe, jsUri, logger, mime, okStatusRe, path, request, through, trumpet, urlHelpers;

  _ = require("lodash");

  path = require("path");

  fs = require("fs");

  request = require("request");

  mime = require("mime");

  path = require("path");

  Domain = require("domain");

  through = require("through");

  jsUri = require("jsuri");

  trumpet = require("trumpet");

  urlHelpers = require("url");

  cwd = require("../cwd");

  logger = require("../logger");

  UrlHelpers = require("../util/url_helpers");

  escapeRegExp = require("../util/escape_regexp");

  headRe = /(<head.*?>)/;

  htmlRe = /(<html.*?>)/;

  okStatusRe = /^[2|3|4]\d+$/;

  badCookieParamRe = /^(httponly|secure|domain=.+)$/i;

  module.exports = {
    handle: function(req, res, config, app, next) {
      var d, getRemoteHost;
      if (req.cookies["__cypress.unload"]) {
        return res.redirect(config.clientRoute);
      }
      getRemoteHost = (function(_this) {
        return function(req) {
          var ref, ref1, ref2;
          return (ref = (ref1 = (ref2 = _this.getOriginFromFqdnUrl(req)) != null ? ref2 : req.cookies["__cypress.remoteHost"]) != null ? ref1 : config.baseUrl) != null ? ref : app.get("__cypress.remoteHost");
        };
      })(this);
      d = Domain.create();
      d.on('error', (function(_this) {
        return function(e) {
          return _this.errorHandler(e, req, res, getRemoteHost(req));
        };
      })(this));
      return d.run((function(_this) {
        return function() {
          var remoteHost, thr;
          remoteHost = getRemoteHost(req);
          logger.info("handling initial request", {
            url: req.url,
            remoteHost: remoteHost
          });
          if (!remoteHost) {
            return res.redirect(config.clientRoute);
          }
          thr = through(function(d) {
            return this.queue(d);
          });
          return _this.getContent(thr, req, res, remoteHost, app, config).on("error", function(e) {
            return _this.errorHandler(e, req, res, remoteHost);
          }).pipe(res);
        };
      })(this));
    },
    getOriginFromFqdnUrl: function(req) {
      var origin;
      if (origin = UrlHelpers.getOriginFromFqdnUrl(req.url)) {
        req.url = "/" + req.url.replace(origin, "").replace(/^\/+/, "");
        return origin;
      }
    },
    getContent: function(thr, req, res, remoteHost, app, config) {
      switch (remoteHost) {
        case "<root>":
          return this.getFileContent(thr, req, res, remoteHost, app, config);
        default:
          return this.getHttpContent(thr, req, res, remoteHost, app);
      }
    },
    getHttpContent: function(thr, req, res, remoteHost, app) {
      var opts, remoteUrl, rq, setCookies;
      process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
      remoteUrl = urlHelpers.resolve(remoteHost, req.url);
      setCookies = (function(_this) {
        return function(initial, remoteHost) {
          if (req.cookies["__cypress.initial"] !== "true") {
            return;
          }
          res.cookie("__cypress.initial", initial);
          res.cookie("__cypress.remoteHost", remoteHost);
          return app.set("__cypress.remoteHost", remoteHost);
        };
      })(this);
      opts = {
        url: remoteUrl,
        gzip: false,
        followRedirect: false,
        strictSSL: false
      };
      if (req.cookies["__cypress.initial"] === "true") {
        delete req.headers["accept-encoding"];
      }
      req.headers = this.mapHeaders(req.headers, req.protocol + "://" + req.get("host"), req.cookies["__cypress.remoteHost"]);
      rq = request(opts);
      rq.on("error", function(err) {
        return thr.emit("error", err);
      });
      rq.on("response", (function(_this) {
        return function(incomingRes) {
          var cookies, isInitial, newUrl;
          _this.setResHeaders(req, res, incomingRes, remoteHost);
          if (cookies = incomingRes.headers["set-cookie"]) {
            res.append("Set-Cookie", _this.stripCookieParams(cookies));
          }
          if (/^30(1|2|3|7|8)$/.test(incomingRes.statusCode)) {
            newUrl = new jsUri(UrlHelpers.mergeOrigin(remoteUrl, incomingRes.headers.location));
            setCookies(true, newUrl.origin());
            logger.info("redirecting to new url", {
              status: incomingRes.statusCode,
              url: newUrl.toString()
            });
            isInitial = req.cookies["__cypress.initial"] === "true";
            return res.redirect(_this.getUrlForRedirect(newUrl, req.cookies["__cypress.remoteHost"], isInitial));
          } else {
            res.status(incomingRes.statusCode);
            if (!okStatusRe.test(incomingRes.statusCode)) {
              return _this.errorHandler(null, req, res, remoteHost);
            }
            logger.info("received absolute file content");
            setCookies(false, remoteHost);
            if (req.cookies["__cypress.initial"] === "true") {
              return rq.pipe(_this.rewrite(req, res, remoteHost)).pipe(thr);
            } else {
              return rq.pipe(thr);
            }
          }
        };
      })(this));
      req.pipe(rq);
      return thr;
    },
    getFileContent: function(thr, req, res, remoteHost, app, config) {
      var args, file, stream;
      args = _.compact([config.fileServerFolder, req.url]);
      file = decodeURI(urlHelpers.parse(path.join.apply(path, args)).pathname);
      req.formattedUrl = file;
      logger.info("getting relative file content", {
        file: file
      });
      res.contentType(mime.lookup(file));
      res.cookie("__cypress.initial", false);
      res.cookie("__cypress.remoteHost", remoteHost);
      app.set("__cypress.remoteHost", remoteHost);
      stream = fs.createReadStream(file, "utf8");
      if (req.cookies["__cypress.initial"] === "true") {
        stream.pipe(this.rewrite(req, res, remoteHost)).pipe(thr);
      } else {
        stream.pipe(thr);
      }
      return thr;
    },
    errorHandler: function(e, req, res, remoteHost) {
      var f, filePath, htmlPath, url;
      url = urlHelpers.resolve(remoteHost, req.url);
      if (process.env["CYPRESS_ENV"] !== "production" && e && e.code !== "ENOENT") {
        console.error(e.stack);
        debugger;
      }
      logger.info("error handling initial request", {
        url: url,
        error: e
      });
      if (e) {
        res.set("x-cypress-error", e.message);
        res.set("x-cypress-stack", e.stack.replace("\n", "\\n"));
      }
      filePath = (function() {
        switch (false) {
          case !(f = req.formattedUrl):
            return "file://" + f;
          default:
            return url;
        }
      })();
      htmlPath = cwd("lib", "html", "initial_500.html");
      return res.status(500).render(htmlPath, {
        url: filePath,
        fromFile: !!req.formattedUrl
      });
    },
    mapHeaders: function(headers, currentHost, remoteHost) {
      var hostRe;
      hostRe = new RegExp(escapeRegExp(currentHost), "ig");
      return _.mapValues(headers, function(value, key) {
        key = key.toLowerCase();
        if (key === "referer" || key === "origin" || key.startsWith("x-")) {
          return value.replace(hostRe, remoteHost);
        } else {
          return value;
        }
      });
    },
    setResHeaders: function(req, res, incomingRes, remoteHost) {
      var headers;
      headers = _.omit(incomingRes.headers, "set-cookie", "x-frame-options", "content-length", "content-security-policy");
      headers = this.mapHeaders(headers, remoteHost, req.get("host"));
      headers["cache-control"] = "no-cache, no-store, must-revalidate";
      return res.set(headers);
    },
    getUrlForRedirect: function(newUrl, remoteHostCookie, isInitial) {
      if (isInitial || (newUrl.origin() === remoteHostCookie)) {
        return newUrl.toString().replace(newUrl.origin(), "");
      } else {
        return "/" + newUrl.toString();
      }
    },
    stripCookieParams: function(cookies) {
      var stripHttpOnlyAndSecure;
      stripHttpOnlyAndSecure = (function(_this) {
        return function(cookie) {
          var parts;
          parts = _.invoke(cookie.split(";"), "trim");
          parts = _.reject(parts, function(part) {
            return badCookieParamRe.test(part);
          });
          return parts.join("; ");
        };
      })(this);
      return _.map([].concat(cookies), stripHttpOnlyAndSecure);
    },
    rewrite: function(req, res, remoteHost) {
      var changeToAbsoluteRelative, removeRemoteHostOrMakeAbsoluteRelative, rewrite, tr;
      through = through;
      tr = trumpet();
      changeToAbsoluteRelative = function(str) {
        return "/" + req.protocol + ":" + str;
      };
      removeRemoteHostOrMakeAbsoluteRelative = function(str) {
        if (str.startsWith(remoteHost)) {
          return str.replace(remoteHost, "");
        } else {
          return "/" + str;
        }
      };
      rewrite = function(selector, type, attr, fn) {
        var options;
        options = {};
        switch (false) {
          case !_.isFunction(attr):
            fn = attr;
            attr = null;
            break;
          case !_.isPlainObject(attr):
            options = attr;
        }
        if (options.method == null) {
          options.method = "selectAll";
        }
        return tr[options.method](selector, function(elem) {
          var stream;
          switch (type) {
            case "attr":
              return elem.getAttribute(attr, function(val) {
                return elem.setAttribute(attr, fn(val));
              });
            case "removeAttr":
              return elem.removeAttribute(attr);
            case "html":
              if (options.outer == null) {
                options.outer = true;
              }
              stream = elem.createStream({
                outer: options.outer
              });
              return stream.pipe(through(function(buf) {
                return this.queue(fn(buf.toString()));
              })).pipe(stream);
          }
        });
      };
      rewrite("head", "html", (function(_this) {
        return function(str) {
          return str.replace(headRe, "$1 " + (_this.getHeadContent()));
        };
      })(this));
      rewrite("[href^='//']", "attr", "href", changeToAbsoluteRelative);
      rewrite("form[action^='//']", "attr", "action", changeToAbsoluteRelative);
      rewrite("form[action^='http']", "attr", "action", removeRemoteHostOrMakeAbsoluteRelative);
      rewrite("[href^='http']", "attr", "href", removeRemoteHostOrMakeAbsoluteRelative);
      return tr;
    },
    getHeadContent: function() {
      return "<script type='text/javascript'> window.onerror = function(){ parent.onerror.apply(parent, arguments); } </script> <script type='text/javascript' src='/__cypress/static/js/sinon.js'></script> <script type='text/javascript'> var Cypress = parent.Cypress; if (!Cypress){ throw new Error('Cypress must exist in the parent window!'); }; Cypress.onBeforeLoad(window); </script>";
    }
  };

}).call(this);

});
require.register("./lib/controllers/spec_processor.js",function (module, exports, require) {(function() {
  var Domain, Snockets, Stream, _, browserify, coffee, coffeeify, fs, gutil, path, requirejs;

  fs = require('fs');

  _ = require('lodash');

  path = require('path');

  gutil = require('gulp-util');

  Stream = require('stream');

  coffee = require('coffee-script');

  browserify = require('browserify');

  coffeeify = require('coffeeify');

  Domain = require('domain');

  Snockets = require('snockets');

  requirejs = require('requirejs');

  module.exports = {
    handle: function(spec, req, res, config, next) {
      var contents, dependencies, domain, filePath, options, snockets, stream;
      res.set({
        "Cache-Control": "no-cache, no-store, must-revalidate",
        "Pragma": "no-cache",
        "Expires": "0"
      });
      res.type("js");
      filePath = path.join(config.projectRoot, spec);
      options = {
        baseUrl: config.projectRoot,
        name: filePath,
        out: "main.js"
      };
      if (config.requirejs) {
        requirejs.optimize(options, function(buildResponse) {
          var contents;
          contents = fs.readFileSync(options.out, 'utf8');
          debugger;
        });
      }
      snockets = new Snockets();
      dependencies = snockets.getCompiledChain(filePath, {
        async: false
      });
      contents = _.pluck(dependencies, "js").join(";\n");
      stream = new Stream.Readable();
      stream.push(contents);
      stream.push(null);
      domain = Domain.create();
      domain.on('error', function() {
        gutil.beep();
        return next.apply(null, arguments);
      });
      return domain.run((function(_this) {
        return function() {
          var opts;
          if (opts = config.browserify) {
            return _this.browserify(opts, stream).pipe(res);
          } else {
            return stream.pipe(res);
          }
        };
      })(this));
    },
    browserify: function(opts, fileStream) {
      return browserify([fileStream], opts).transform({}, coffeeify).bundle();
    }
  };

}).call(this);

});
require.register("./lib/controllers/xhrs.js",function (module, exports, require) {(function() {
  var Promise, _, fixture, fixturesRe, htmlLikeRe, isValidJSON, mime, request, str;

  _ = require("lodash");

  mime = require("mime");

  request = require("request");

  str = require("string-to-stream");

  Promise = require("bluebird");

  fixture = require("../fixture");

  fixturesRe = /^(fx:|fixture:)/;

  htmlLikeRe = /<.+>[\s\S]+<\/.+>/;

  isValidJSON = function(text) {
    var error, o;
    if (_.isObject(text)) {
      return true;
    }
    try {
      o = JSON.parse(text);
      return _.isObject(o);
    } catch (error) {
      false;
    }
    return false;
  };

  module.exports = {
    handle: function(req, res, config, next) {
      var delay, headers, ref, ref1, ref2, respond, response, status;
      delay = ~~req.get("x-cypress-delay");
      status = (ref = req.get("x-cypress-status")) != null ? ref : 200;
      headers = (ref1 = req.get("x-cypress-headers")) != null ? ref1 : null;
      response = (ref2 = req.get("x-cypress-response")) != null ? ref2 : "";
      respond = (function(_this) {
        return function() {
          return _this.getResponse(response, config).then(function(resp) {
            headers = _this.parseHeaders(headers, resp);
            return res.set(headers).status(status).send(resp);
          })["catch"](function(err) {
            return res.status(400).send({
              __error: err.message
            });
          });
        };
      })(this);
      if (delay > 0) {
        return Promise.delay(delay).then(respond);
      } else {
        return respond();
      }
    },
    _get: function(resp, config) {
      var file;
      file = resp.replace(fixturesRe, "");
      return fixture.get(config.fixturesFolder, file);
    },
    getStream: function(resp) {
      if (fixturesRe.test(resp)) {
        return this._get(resp).then(function(contents) {
          return str(contents);
        });
      } else {
        return str(resp);
      }
    },
    getResponse: function(resp, config) {
      if (fixturesRe.test(resp)) {
        return this._get(resp, config);
      } else {
        return Promise.resolve(resp);
      }
    },
    parseContentType: function(response) {
      var ret;
      ret = function(type) {
        return mime.lookup(type);
      };
      switch (false) {
        case !isValidJSON(response):
          return ret("json");
        case !htmlLikeRe.test(response):
          return ret("html");
        default:
          return ret("text");
      }
    },
    parseHeaders: function(headers, response) {
      try {
        headers = JSON.parse(headers);
      } catch (undefined) {}
      if (headers == null) {
        headers = {};
      }
      if (headers["content-type"] == null) {
        headers["content-type"] = this.parseContentType(response);
      }
      return headers;
    }
  };

}).call(this);

});
require.register("./lib/cwd.js",function (module, exports, require) {(function() {
  var appPath, path,
    slice = [].slice;

  path = require("path");

  appPath = (function() {
    if (path.basename(__dirname) === "lib") {
      return path.join(__dirname, "..");
    } else {
      return __dirname;
    }
  })();

  if (process.cwd() !== appPath) {
    process.chdir(appPath);
  }

  module.exports = function() {
    var args;
    args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
    return path.join.apply(path, [appPath].concat(slice.call(args)));
  };

}).call(this);

});
require.register("./lib/cypress.js",function (module, exports, require) {(function() {
  var Project, Promise, _, api, argsUtil, cp, errors, exit, exit0, exitErr, logger, logs, path, returnPkg, smokeTest;

  require("./environment");

  _ = require("lodash");

  cp = require("child_process");

  path = require("path");

  Promise = require("bluebird");

  api = require("./api");

  logs = require("./electron/handlers/logs");

  logger = require("./logger");

  errors = require("./errors");

  Project = require("./project");

  argsUtil = require("./util/args");

  smokeTest = require("./modes/smoke_test");

  returnPkg = require("./modes/pkg");

  exit = function(code) {
    return process.exit(code);
  };

  exit0 = function() {
    return exit(0);
  };

  exitErr = function(err) {
    return errors.log(err).then(function() {
      return exit(1);
    });
  };

  module.exports = {
    isCurrentlyRunningElectron: function() {
      return !!(process.versions && process.versions.electron);
    },
    runElectron: function(mode, options) {
      return Promise["try"]((function(_this) {
        return function() {
          var args;
          if (_this.isCurrentlyRunningElectron()) {
            return require("./electron")(mode, options);
          } else {
            api.ping()["catch"](function(err) {
              console.log(err.message);
              return errors.warning("DEV_NO_SERVER");
            });
            args = ["."].concat(argsUtil.toArray(options));
            return new Promise(function(resolve, reject) {
              var electron;
              electron = cp.spawn("electron", args, {
                stdio: "inherit"
              });
              return electron.on("close", function(code, signal) {
                return resolve(code);
              });
            });
          }
        };
      })(this));
    },
    openProject: function(options) {
      return Project(options.project).open();
    },
    runServer: function(options) {
      var args;
      args = {};
      _.defaults(options, {
        autoOpen: true
      });
      if (!options.project) {
        throw new Error("Missing path to project:\n\nPlease pass 'npm run server -- --project path/to/project'\n\n");
      }
      if (options.debug) {
        args.debug = "--debug";
      }
      _.extend(args, {
        script: "index.js",
        watch: ["--watch", "lib"],
        ignore: ["--ignore", "lib/public"],
        verbose: "--verbose",
        exts: ["-e", "coffee,js"],
        args: ["--", "--mode", "openProject", "--project", options.project]
      });
      args = _.chain(args).values().flatten().value();
      cp.spawn("nodemon", args, {
        stdio: "inherit"
      });
      if (options.autoOpen) {
        _.delay(function() {
          return require("opn")("http://localhost:2020/__");
        }, 2000);
      }
      if (options.debug) {
        cp.spawn("node-inspector", [], {
          stdio: "inherit"
        });
        return require("opn")("http://127.0.0.1:8080/debug?ws=127.0.0.1:8080&port=5858");
      }
    },
    start: function(argv) {
      var mode, options;
      if (argv == null) {
        argv = [];
      }
      logger.info("starting desktop app", {
        args: argv
      });
      options = argsUtil.toObject(argv);
      switch (false) {
        case !options.removeIds:
          options.mode = "removeIds";
          break;
        case !options.version:
          options.mode = "version";
          break;
        case !options.smokeTest:
          options.mode = "smokeTest";
          break;
        case !options.returnPkg:
          options.mode = "returnPkg";
          break;
        case !options.logs:
          options.mode = "logs";
          break;
        case !options.clearLogs:
          options.mode = "clearLogs";
          break;
        case !options.getKey:
          options.mode = "getKey";
          break;
        case !options.generateKey:
          options.mode = "generateKey";
          break;
        case !options.ci:
          options.mode = "ci";
          break;
        case !options.runProject:
          options.mode = "headless";
          break;
        default:
          if (options.mode == null) {
            options.mode = "headed";
          }
      }
      mode = options.mode;
      options = _.omit(options, "mode");
      return this.startInMode(mode, options);
    },
    startInMode: function(mode, options) {
      switch (mode) {
        case "removeIds":
          return Project.removeIds(options.projectPath).then(function(stats) {
            if (stats == null) {
              stats = {};
            }
            return console.log("Removed '" + stats.ids + "' ids from '" + stats.files + "' files.");
          }).then(exit0)["catch"](exitErr);
        case "version":
          return returnPkg(options).get("version").then(function(version) {
            return console.log(version);
          }).then(exit0)["catch"](exitErr);
        case "smokeTest":
          return smokeTest(options).then(function(pong) {
            return console.log(pong);
          }).then(exit0)["catch"](exitErr);
        case "returnPkg":
          return returnPkg(options).then(function(pkg) {
            return console.log(JSON.stringify(pkg));
          }).then(exit0)["catch"](exitErr);
        case "logs":
          return logs.print().then(exit0)["catch"](exitErr);
        case "clearLogs":
          return logs.clear().then(exit0)["catch"](exitErr);
        case "getKey":
          return Project.getSecretKeyByPath(options.projectPath).then(function(key) {
            return console.log(key);
          }).then(exit0)["catch"](exitErr);
        case "generateKey":
          return Project.generateSecretKeyByPath(options.projectPath).then(function(key) {
            return console.log(key);
          }).then(exit0)["catch"](exitErr);
        case "headless":
          return this.runElectron(mode, options).then(exit0)["catch"](exitErr);
        case "headed":
          return this.runElectron(mode, options);
        case "ci":
          return this.runElectron(mode, options).then(exit)["catch"](exitErr);
        case "server":
          return this.runServer(options);
        case "openProject":
          return this.openProject(options);
        default:
          throw new Error("Cannot start. Invalid mode: '" + mode + "'");
      }
    }
  };

}).call(this);

});
require.register("./lib/electron/handlers/cookies.js",function (module, exports, require) {(function() {
  var Promise;

  Promise = require("bluebird");

  module.exports = {
    clearGithub: function(cookies) {
      var removeCookie;
      cookies = Promise.promisifyAll(cookies);
      removeCookie = function(cookie) {
        var prefix, url;
        prefix = cookie.secure ? "https://" : "http://";
        if (cookie.domain[0] === ".") {
          prefix += "www";
        }
        url = prefix + cookie.domain + cookie.path;
        return cookies.removeAsync(url, cookie.name);
      };
      return cookies.getAsync({
        domain: "github.com"
      }).map(removeCookie)["return"](null);
    }
  };

}).call(this);

});
require.register("./lib/electron/handlers/dialog.js",function (module, exports, require) {(function() {
  var Renderer, dialog;

  dialog = require("electron").dialog;

  Renderer = require("./renderer");

  module.exports = {
    show: function() {
      var props;
      props = {
        properties: ["openDirectory"]
      };
      return new Promise(function(resolve, reject) {
        return dialog.showOpenDialog(props, function(paths) {
          if (paths == null) {
            paths = [];
          }
          return process.nextTick(function() {
            return resolve(paths[0]);
          });
        });
      });
    }
  };

}).call(this);

});
require.register("./lib/electron/handlers/events.js",function (module, exports, require) {(function() {
  var Project, Renderer, Updater, _, cookies, cyIcons, dialog, errors, handleEvent, ipc, logs, pgk, project, shell, user,
    slice = [].slice;

  _ = require("lodash");

  ipc = require("electron").ipcMain;

  shell = require("electron").shell;

  cyIcons = require("@cypress/core-icons");

  dialog = require("./dialog");

  project = require("./project");

  pgk = require("./package");

  cookies = require("./cookies");

  logs = require("./logs");

  Renderer = require("./renderer");

  user = require("../../user");

  errors = require("../../errors");

  Updater = require("../../updater");

  Project = require("../../project");

  handleEvent = function(options, event, id, type, arg) {
    var callback, echo, send, sendErr, sendResponse, upd, win;
    sendResponse = function(data) {
      if (data == null) {
        data = {};
      }
      try {
        return event.sender.send("response", data);
      } catch (undefined) {}
    };
    sendErr = function(err) {
      callback("onError", err);
      return sendResponse({
        id: id,
        __error: errors.clone(err)
      });
    };
    send = function(data) {
      return sendResponse({
        id: id,
        data: data
      });
    };
    callback = function() {
      var args, fn, key;
      key = arguments[0], args = 2 <= arguments.length ? slice.call(arguments, 1) : [];
      fn = options[key];
      if (_.isFunction(fn)) {
        return fn.apply(null, args);
      }
    };
    switch (type) {
      case "quit":
        return callback("onQuit");
      case "gui:error":
        return logs.error(arg).then(function() {
          return send(null);
        })["catch"](sendErr);
      case "show:directory:dialog":
        return dialog.show().then(send)["catch"](sendErr);
      case "log:in":
        return user.logIn(arg).then(send)["catch"](sendErr);
      case "log:out":
        return user.logOut().then(send)["catch"](sendErr);
      case "get:current:user":
        return user.get().then(send)["catch"](sendErr);
      case "clear:github:cookies":
        return cookies.clearGithub(event.sender.session.cookies).then(send)["catch"](sendErr);
      case "external:open":
        return shell.openExternal(arg);
      case "window:open":
        return Renderer.create(arg).then(send)["catch"](sendErr);
      case "window:close":
        return Renderer.getByWebContents(event.sender).destroy();
      case "get:options":
        return pgk(options).then(send)["catch"](sendErr);
      case "updater:check":
        return Updater.check({
          onNewVersion: function() {
            return send(true);
          },
          onNoNewVersion: function() {
            return send(false);
          }
        });
      case "updater:run":
        echo = function(event, version) {
          return send({
            event: event,
            version: version
          });
        };
        upd = Updater.run({
          onStart: function() {
            return echo("start");
          },
          onApply: function() {
            return echo("apply");
          },
          onError: function() {
            return echo("error");
          },
          onDone: function() {
            return echo("done");
          },
          onNone: function() {
            return echo("none");
          },
          onDownload: function(version) {
            return echo("download", version);
          }
        });
        win = Renderer.getByWebContents(event.sender);
        return win.once("closed", function() {
          return upd.cancel();
        });
      case "get:about:logo:src":
        return send(cyIcons.getPathToIcon("icon_32x32@2x.png"));
      case "get:logs":
        return logs.get().then(send)["catch"](sendErr);
      case "clear:logs":
        return logs.clear().then(function() {
          return send(null);
        })["catch"](sendErr);
      case "on:log":
        return logs.onLog(send);
      case "off:log":
        logs.off();
        return send(null);
      case "get:project:paths":
        return Project.paths().then(send)["catch"](sendErr);
      case "add:project":
        return Project.add(arg).then(function() {
          return send(arg);
        })["catch"](sendErr);
      case "remove:project":
        return Project.remove(arg).then(function() {
          return send(arg);
        })["catch"](sendErr);
      case "open:project":
        return project.open(arg, options, {
          sync: true,
          changeEvents: true
        }).call("getConfig").then(send).then(function() {
          return callback("onOpenProject");
        })["catch"](function(err) {
          return sendErr(err);
        });
      case "close:project":
        return project.close({
          sync: true
        }).then(send).then(function() {
          return callback("onCloseProject");
        })["catch"](sendErr);
      case "on:project:settings:change":
        return project.onSettingsChanged().then(function() {
          return send(null);
        })["catch"](sendErr);
      default:
        throw new Error("No ipc event registered for: '" + type + "'");
    }
  };

  module.exports = {
    handleEvent: handleEvent,
    stop: function() {
      return ipc.removeAllListeners();
    },
    start: function(options) {
      return ipc.on("request", _.partial(this.handleEvent, options));
    }
  };

}).call(this);

});
require.register("./lib/electron/handlers/logs.js",function (module, exports, require) {(function() {
  var chalk, logger;

  chalk = require("chalk");

  logger = require("../../logger");

  module.exports = {
    get: function() {
      return logger.getLogs();
    },
    clear: function() {
      return logger.clearLogs();
    },
    off: function() {
      return logger.off();
    },
    onLog: function(fn) {
      return logger.onLog(fn);
    },
    error: function(err) {
      return logger.createException(err)["catch"](function() {});
    },
    print: function() {
      return this.get().then(function(logs) {
        return logs.forEach(function(log, i) {
          var color, str;
          str = JSON.stringify(log);
          color = i % 2 === 0 ? "cyan" : "yellow";
          return console.log(chalk[color](str));
        });
      });
    }
  };

}).call(this);

});
require.register("./lib/electron/handlers/package.js",function (module, exports, require) {(function() {
  var Promise, _, cwd, fs, path, pathToPkg;

  _ = require("lodash");

  fs = require("fs-extra");

  path = require("path");

  Promise = require("bluebird");

  cwd = require("../../cwd");

  fs = Promise.promisifyAll(fs);

  pathToPkg = cwd("package.json");

  module.exports = function(options) {
    return fs.readJsonAsync(pathToPkg).then(function(json) {
      return _.extend({}, options, _.pick(json, "version"));
    });
  };

}).call(this);

});
require.register("./lib/electron/handlers/project.js",function (module, exports, require) {(function() {
  var Project, Promise, _, cache, config, errors, openProject;

  _ = require("lodash");

  Promise = require("bluebird");

  config = require("../../config");

  errors = require("../../errors");

  cache = require("../../cache");

  Project = require("../../project");

  openProject = null;

  module.exports = {
    open: function(path, args, options) {
      if (args == null) {
        args = {};
      }
      if (options == null) {
        options = {};
      }
      options = _.extend({}, config.whitelist(args), options);
      openProject = Project(path);
      return openProject.open(options);
    },
    opened: function() {
      return openProject;
    },
    onSettingsChanged: function() {
      return Promise["try"]((function(_this) {
        return function() {
          if (!openProject) {
            return errors["throw"]("NO_CURRENTLY_OPEN_PROJECT");
          } else {
            return new Promise(function(resolve, reject) {
              return openProject.on("settings:changed", function() {
                return resolve();
              });
            });
          }
        };
      })(this));
    },
    close: function(options) {
      var nullify;
      if (options == null) {
        options = {};
      }
      nullify = function() {
        openProject = null;
        return Promise.resolve(null);
      };
      if (!openProject) {
        return nullify();
      } else {
        return openProject.close(options).then(nullify);
      }
    }
  };

}).call(this);

});
require.register("./lib/electron/handlers/renderer.js",function (module, exports, require) {(function() {
  var BrowserWindow, _, cwd, cyDesktop, getByType, getUrl, path, recentlyCreatedWindow, uri, user, windows;

  _ = require("lodash");

  path = require("path");

  uri = require("url");

  cyDesktop = require("@cypress/core-desktop-gui");

  BrowserWindow = require("electron").BrowserWindow;

  cwd = require("../../cwd");

  user = require("../../user");

  windows = {};

  recentlyCreatedWindow = false;

  getUrl = function(type) {
    switch (type) {
      case "GITHUB_LOGIN":
        return user.getLoginUrl();
      case "ABOUT":
        return cyDesktop.getPathToAbout();
      case "DEBUG":
        return cyDesktop.getPathToDebug();
      case "UPDATES":
        return cyDesktop.getPathToUpdates();
      case "INDEX":
        return cyDesktop.getPathToIndex();
      default:
        throw new Error("No acceptable window type found for: '" + type + "'");
    }
  };

  getByType = function(type) {
    return windows[type];
  };

  module.exports = {
    reset: function() {
      return windows = {};
    },
    get: function(type) {
      var ref;
      return (function() {
        if ((ref = getByType(type)) != null) {
          return ref;
        } else {
          throw new Error("No window exists for: '" + type + "'");
        }
      })();
    },
    showAll: function() {
      return _.invoke(windows, "showInactive");
    },
    hideAllUnlessAnotherWindowIsFocused: function() {
      if (BrowserWindow.getFocusedWindow() || recentlyCreatedWindow) {
        return;
      }
      return _.invoke(windows, "hide");
    },
    getByWebContents: function(webContents) {
      return _.find(windows, function(win) {
        return win.webContents === webContents;
      });
    },
    create: function(options) {
      var args, err, height, urlChanged, width, win;
      if (options == null) {
        options = {};
      }
      if (win = getByType(options.type)) {
        win.show();
        if (options.type === "GITHUB_LOGIN") {
          err = new Error;
          err.alreadyOpen = true;
          return Promise.reject(err);
        } else {
          return Promise.resolve(win);
        }
      }
      recentlyCreatedWindow = true;
      _.defaults(options, {
        onFocus: function() {},
        onBlur: function() {}
      });
      args = _.defaults({}, options, {
        width: 600,
        height: 500,
        show: true,
        preload: cwd("lib", "ipc", "ipc.js"),
        webPreferences: {
          nodeIntegration: false
        }
      });
      if (args.url == null) {
        args.url = getUrl(options.type);
      }
      urlChanged = function(url, resolve) {
        var code, parsed;
        parsed = uri.parse(url, true);
        if (code = parsed.query.code) {
          _.defer(function() {
            return win.destroy();
          });
          return resolve(code);
        }
      };
      if (args.transparent && args.show) {
        width = args.width, height = args.height;
        args.show = false;
        args.width = 0;
        args.height = 0;
      }
      win = new BrowserWindow(args);
      win.on("blur", function() {
        return options.onBlur.apply(win, arguments);
      });
      win.on("focus", function() {
        return options.onFocus.apply(win, arguments);
      });
      windows[options.type] = win;
      win.webContents.id = _.uniqueId("webContents");
      win.once("closed", function() {
        win.removeAllListeners();
        return delete windows[options.type];
      });
      if (args.devTools) {
        win.webContents.openDevTools({
          detach: true
        });
      }
      return Promise.resolve(args.url).then(function(url) {
        if (width && height) {
          win.webContents.once("dom-ready", function() {
            win.setSize(width, height);
            return win.show();
          });
        }
        win.loadURL(url);
        recentlyCreatedWindow = false;
        if (args.type === "GITHUB_LOGIN") {
          return new Promise(function(resolve, reject) {
            win.webContents.on("will-navigate", function(e, url) {
              return urlChanged(url, resolve);
            });
            return win.webContents.on("did-get-redirect-request", function(e, oldUrl, newUrl) {
              return urlChanged(newUrl, resolve);
            });
          });
        } else {
          return Promise.resolve(win);
        }
      });
    }
  };

}).call(this);

});
require.register("./lib/electron/handlers/tray.js",function (module, exports, require) {(function() {
  var Tray, _, colors, cypressIcons, nativeImage, tray;

  _ = require("lodash");

  cypressIcons = require("@cypress/core-icons");

  nativeImage = require("electron").nativeImage;

  Tray = require("electron").Tray;

  tray = null;

  colors = {
    black: nativeImage.createFromPath(cypressIcons.getPathToTray("mac-normal.png")),
    blue: nativeImage.createFromPath(cypressIcons.getPathToTray("mac-normal-blue.png")),
    red: nativeImage.createFromPath(cypressIcons.getPathToTray("mac-normal-red.png")),
    white: nativeImage.createFromPath(cypressIcons.getPathToTray("mac-normal-inverse.png"))
  };

  module.exports = {
    setImage: function(color, options) {
      var c;
      if (options == null) {
        options = {};
      }
      if (!tray) {
        return;
      }
      if (!(c = colors[color])) {
        throw new Error("Did not receive a valid tray icon color. Got: '" + color + "'");
      }
      if (options.pressed) {
        return tray.setPressedImage(c);
      } else {
        return tray.setImage(c);
      }
    },
    getColors: function() {
      return colors;
    },
    getTray: function() {
      return tray;
    },
    resetTray: function() {
      return tray = null;
    },
    display: function(options) {
      if (options == null) {
        options = {};
      }
      _.defaults(options, {
        onDrop: function() {},
        onClick: function() {},
        onRightClick: function() {},
        onDragEnter: function() {},
        onDragLeave: function() {}
      });
      tray = new Tray(null);
      tray.on("click", options.onClick);
      tray.on("right-click", options.onRightClick);
      tray.on("drop", options.onDrop);
      tray.on("drag-enter", options.onDragEnter);
      tray.on("drag-leave", options.onDragLeave);
      tray.on("double-click", options.onClick);
      this.setImage("black");
      this.setImage("white", {
        pressed: true
      });
      tray.setToolTip("Cypress");
      return tray;
    }
  };

}).call(this);

});
require.register("./lib/electron/handlers/updater.js",function (module, exports, require) {(function() {


}).call(this);

});
require.register("./lib/electron/index.js",function (module, exports, require) {(function() {
  module.exports = function(mode, options) {
    switch (mode) {
      case "ci":
        return require("../modes/ci").run(options);
      case "headless":
        return require("../modes/headless").run(options);
      case "headed":
        return require("../modes/headed").run(options);
    }
  };

}).call(this);

});
require.register("./lib/environment.js",function (module, exports, require) {(function() {
  var cwd, fs, getEnv, pkg;

  require("./util/http_overrides");

  fs = require("fs-extra");

  cwd = require("./cwd");

  Error.stackTraceLimit = Infinity;

  pkg = cwd("package.json");

  getEnv = function() {
    var base, ref;
    return (base = process.env)["CYPRESS_ENV"] || (base["CYPRESS_ENV"] = (ref = fs.readJsonSync(pkg).env) != null ? ref : "development");
  };

  module.exports = getEnv();

}).call(this);

});
require.register("./lib/errors.js",function (module, exports, require) {(function() {
  var API, Promise, _, ansi_up, chalk, exceptions,
    indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; },
    hasProp = {}.hasOwnProperty;

  _ = require("lodash");

  chalk = require("chalk");

  ansi_up = require("ansi_up");

  Promise = require("bluebird");

  exceptions = "CI_CANNOT_COMMUNICATE".split(" ");

  API = {
    getMsgByType: function(type, arg1, arg2) {
      switch (type) {
        case "NOT_LOGGED_IN":
          return "You're not logged in.\n\nRun `cypress open` to open the Desktop App and login.";
        case "TESTS_DID_NOT_START":
          return "Can't start tests, the remote client never connected.";
        case "PROJECT_DOES_NOT_EXIST":
          return "You need to add a project to run tests.";
        case "NOT_CI_ENVIRONMENT":
          return "Can't run CI outside of a CI provider and environment.";
        case "CI_KEY_MISSING":
          return "Can't run in CI without a CI key. You did not provide one.";
        case "CI_KEY_NOT_VALID":
          return "Can't run project in CI. Your project's CI key: " + (chalk.blue(arg1)) + " is invalid.";
        case "CI_PROJECT_NOT_FOUND":
          return "Can't find project. Aborting the CI run.\n\nCheck that your 'projectId' and 'secret CI key' are valid.";
        case "CI_CANNOT_COMMUNICATE":
          return "Can't communicate with remote Cypress servers. This is a temporary problem. Try again later.";
        case "DEV_NO_SERVER":
          return " > The local API server isn't running in development. This may cause problems running the GUI.";
        case "NO_PROJECT_ID":
          return "Can't find 'projectId' in the 'cypress.json' file for this project: " + chalk.blue(arg1);
        case "NO_PROJECT_FOUND_AT_PROJECT_ROOT":
          return "Can't find project at the path: " + chalk.blue(arg1);
        case "CANNOT_FETCH_PROJECT_TOKEN":
          return "Can't find project's secret key.";
        case "CANNOT_CREATE_PROJECT_TOKEN":
          return "Can't create project's secret key.";
        case "PORT_IN_USE_SHORT":
          return "Port '" + arg1 + "' is already in use.";
        case "PORT_IN_USE_LONG":
          return "Can't run project because port is currently in use: " + chalk.blue(arg1) + "\n\n" + chalk.yellow("Assign a different port with the '--port <port>' argument or shut down the other running process.");
        case "ERROR_READING_FILE":
          return "Error reading from: " + chalk.blue(arg1) + "\n\n" + chalk.yellow(arg2);
        case "ERROR_WRITING_FILE":
          return "Error writing to: " + chalk.blue(arg1) + "\n\n" + chalk.yellow(arg2);
        case "SPEC_FILE_NOT_FOUND":
          return "Can't find test spec: " + chalk.blue(arg1);
        case "NO_CURRENTLY_OPEN_PROJECT":
          return "Can't find open project.";
      }
    },
    get: function(type, arg1, arg2) {
      var err, msg;
      msg = this.getMsgByType(type, arg1, arg2);
      err = new Error(msg);
      err.type = type;
      return err;
    },
    isCypressErr: function(err) {
      var ref;
      return err.type && this.getMsgByType(err.type) && (ref = err.type, indexOf.call(exceptions, ref) < 0);
    },
    warning: function(type) {
      var err;
      err = this.get(type);
      return this.log(err, "magenta");
    },
    log: function(err, color) {
      if (color == null) {
        color = "red";
      }
      return Promise["try"]((function(_this) {
        return function() {
          console.log(chalk[color](err.message));
          if (_this.isCypressErr(err)) {
            return;
          }
          switch (process.env["CYPRESS_ENV"]) {
            case "production":
              break;
            default:
              return console.log(err.stack);
          }
        };
      })(this));
    },
    "throw": function(type, arg) {
      throw this.get(type, arg);
    },
    clone: function(err) {
      var obj, prop, val;
      obj = _.pick(err, "type", "name", "stack", "fileName", "lineNumber", "columnNumber");
      obj.message = ansi_up.ansi_to_html(err.message, {
        use_classes: true
      });
      for (prop in err) {
        if (!hasProp.call(err, prop)) continue;
        val = err[prop];
        obj[prop] = val;
      }
      return obj;
    }
  };

  module.exports = _.bindAll(API);

}).call(this);

});
require.register("./lib/exception.js",function (module, exports, require) {(function() {
  var Promise, Settings, api, cache, fs, logger, request, user, winston;

  request = require("request-promise");

  Promise = require("bluebird");

  winston = require("winston");

  fs = require("fs-extra");

  api = require("./api");

  user = require("./user");

  cache = require("./cache");

  logger = require("./logger");

  Settings = require("./util/settings");

  module.exports = {
    getCache: function() {
      return cache.read();
    },
    getLogs: function() {
      return logger.getLogs();
    },
    getErr: function(err) {
      return {
        name: err.name,
        message: err.message,
        stack: err.stack,
        info: winston.exception.getAllInfo(err)
      };
    },
    getVersion: function() {
      return fs.readJsonAsync("./package.json").get("version");
    },
    getBody: function(err, settings) {
      var body;
      body = {
        err: this.getErr(err)
      };
      return Promise.all([this.getCache(), this.getLogs(), this.getVersion()]).spread(function(cache, logs, version) {
        body.cache = cache;
        body.logs = logs;
        body.settings = settings;
        return body.version = version;
      })["return"](body);
    },
    getSession: function() {
      return user.get().then(function(user) {
        return user && user.session_token;
      });
    },
    create: function(err, settings) {
      if (process.env["CYPRESS_ENV"] !== "production") {
        return Promise.resolve();
      }
      return Promise.props({
        body: this.getBody(err, settings),
        session: this.getSession()
      }).then(function(props) {
        return api.createRaygunException(props.body, props.session);
      });
    }
  };

}).call(this);

});
require.register("./lib/fixture.js",function (module, exports, require) {(function() {
  var Promise, _, beautify, check, coffee, cwd, extensions, formatter, fs, jsonlint, lastCharacterIsNewLine, path, pretty, queue;

  _ = require("lodash");

  fs = require("fs-extra");

  path = require("path");

  check = require("syntax-error");

  coffee = require("coffee-script");

  Promise = require("bluebird");

  jsonlint = require("jsonlint");

  beautify = require("js-beautify").html;

  pretty = require("js-object-pretty-print").pretty;

  formatter = require("jsonlint/lib/formatter").formatter;

  cwd = require("./cwd");

  fs = Promise.promisifyAll(fs);

  extensions = ".json .js .coffee .html .txt .png .jpg .jpeg .gif .tif .tiff .zip".split(" ");

  queue = {};

  lastCharacterIsNewLine = function(str) {
    return str[str.length - 1] === "\n";
  };

  module.exports = {
    get: function() {
      var ext, fixture, p, tryParsingFile;
      p = path.join.apply(path, arguments);
      fixture = path.basename(p);
      if (ext = path.extname(p)) {
        return this.parseFile(p, fixture, ext);
      } else {
        tryParsingFile = (function(_this) {
          return function(index) {
            ext = extensions[index];
            if (!ext) {
              throw new Error("No fixture file found with an acceptable extension. Searched in: " + p);
            }
            return _this.fileExists(p + ext)["catch"](function() {
              return tryParsingFile(index + 1);
            }).then(function() {
              return this.parseFile(p + ext, fixture, ext);
            });
          };
        })(this);
        return Promise.resolve(tryParsingFile(0));
      }
    },
    fileExists: function(p) {
      return fs.statAsync(p).bind(this);
    },
    parseFile: function(p, fixture, ext) {
      var cleanup;
      if (queue[p]) {
        return Promise.delay(1).then((function(_this) {
          return function() {
            return _this.parseFile(p, fixture, ext);
          };
        })(this));
      } else {
        queue[p] = true;
        cleanup = function() {
          return delete queue[p];
        };
        return this.fileExists(p)["catch"](function(err) {
          throw new Error("No fixture exists at: " + p);
        }).then(function() {
          return this.parseFileByExtension(p, fixture, ext);
        }).then(function(ret) {
          cleanup();
          return ret;
        })["catch"](function(err) {
          cleanup();
          throw err;
        });
      }
    },
    parseFileByExtension: function(p, fixture, ext) {
      if (ext == null) {
        ext = path.extname(fixture);
      }
      switch (ext) {
        case ".json":
          return this.parseJson(p, fixture);
        case ".js":
          return this.parseJs(p, fixture);
        case ".coffee":
          return this.parseCoffee(p, fixture);
        case ".html":
          return this.parseHtml(p, fixture);
        case ".txt":
          return this.parseText(p, fixture);
        case ".png":
        case ".jpg":
        case ".jpeg":
        case ".gif":
        case ".tif":
        case ".tiff":
        case ".zip":
          return this.parseBase64(p, fixture);
        default:
          throw new Error("Invalid fixture extension: '" + ext + "'. Acceptable file extensions are: " + (extensions.join(", ")));
      }
    },
    parseJson: function(p, fixture) {
      return fs.readFileAsync(p, "utf8").bind(this).then(function(str) {
        var formatted;
        formatted = formatter.formatJson(str, "  ");
        if (formatted === str) {
          return str;
        } else {
          if (lastCharacterIsNewLine(str)) {
            formatted += "\n";
          }
          return fs.writeFileAsync(p, formatted)["return"](formatted);
        }
      }).then(jsonlint.parse)["catch"](function(err) {
        throw new Error("'" + fixture + "' is not valid JSON.\n" + err.message);
      });
    },
    parseJs: function(p, fixture) {
      return fs.readFileAsync(p, "utf8").bind(this).then(function(str) {
        var e, err, error, obj;
        try {
          obj = eval("(" + str + ")");
        } catch (error) {
          e = error;
          err = check(str, fixture);
          if (err) {
            throw err;
          }
          throw e;
        }
        return obj;
      }).then(function(obj) {
        var str;
        str = pretty(obj, 2);
        return fs.writeFileAsync(p, str)["return"](obj);
      })["catch"](function(err) {
        throw new Error("'" + fixture + "' is not a valid JavaScript object." + (err.toString()));
      });
    },
    parseCoffee: function(p, fixture) {
      var dc;
      dc = process.env.NODE_DISABLE_COLORS;
      process.env.NODE_DISABLE_COLORS = "0";
      return fs.readFileAsync(p, "utf8").bind(this).then(function(str) {
        str = coffee.compile(str, {
          bare: true
        });
        return eval(str);
      }).then(function(obj) {
        var str;
        str = pretty(obj, 2);
        return fs.writeFileAsync(p, str)["return"](obj);
      })["catch"](function(err) {
        throw new Error("'" + fixture + " is not a valid CoffeeScript object.\n" + (err.toString()));
      })["finally"](function() {
        return process.env.NODE_DISABLE_COLORS = dc;
      });
    },
    parseHtml: function(p, fixture) {
      return fs.readFileAsync(p, "utf8").bind(this).then(function(str) {
        var html;
        html = beautify(str, {
          indent_size: 2,
          extra_liners: []
        });
        if (lastCharacterIsNewLine(str)) {
          html += "\n";
        }
        return fs.writeFileAsync(p, html)["return"](html);
      });
    },
    parseText: function(p, fixture) {
      return fs.readFileAsync(p, "utf8").bind(this);
    },
    parseBase64: function(p, fixture) {
      return fs.readFileAsync(p, "base64").bind(this);
    }
  };

}).call(this);

});
require.register("./lib/ids.js",function (module, exports, require) {(function() {
  var Promise, fs, glob, idRe, path;

  fs = require("fs");

  path = require("path");

  glob = require("glob");

  Promise = require("bluebird");

  fs = Promise.promisifyAll(fs);

  idRe = /\s*\[.{3}\]/g;

  module.exports = {
    files: function(pathToTestFiles) {
      return new Promise(function(resolve, reject) {
        return glob(path.join(pathToTestFiles, "**", "*+(.js|.coffee)"), {
          nodir: true
        }, function(err, files) {
          if (err) {
            reject(err);
          }
          return resolve(files);
        });
      });
    },
    get: function(pathToTestFiles) {
      var getIds;
      getIds = function(memo, file) {
        return fs.readFileAsync(file, "utf8").then(function(contents) {
          var matches;
          if (matches = contents.match(idRe)) {
            memo = memo.concat(matches);
          }
          return memo;
        });
      };
      return Promise.reduce(this.files(pathToTestFiles), getIds, []);
    },
    remove: function(pathToTestFiles) {
      var removeIds;
      removeIds = function(memo, file) {
        return fs.readFileAsync(file, "utf8").then(function(contents) {
          var matches;
          if (matches = contents.match(idRe)) {
            memo.ids += matches.length;
            memo.files += 1;
            contents = contents.replace(idRe, "");
            fs.writeFileAsync(file, contents);
          }
          return memo;
        });
      };
      return Promise.reduce(this.files(pathToTestFiles), removeIds, {
        ids: 0,
        files: 0
      });
    }
  };

}).call(this);

});
require.register("./lib/konfig.js",function (module, exports, require) {(function() {
  var getConfig, konfig;

  require("./environment");

  konfig = require("konfig");

  getConfig = function() {
    var config, previousNodeEnv;
    previousNodeEnv = process.env["NODE_ENV"];
    process.env["NODE_ENV"] = process.env["CYPRESS_ENV"];
    config = konfig().app;
    process.env["NODE_ENV"] = previousNodeEnv;
    return function(getter) {
      return config[getter];
    };
  };

  module.exports = getConfig();

}).call(this);

});
require.register("./lib/logger.js",function (module, exports, require) {(function() {
  var Promise, _, createFile, fs, getName, getPathToLog, konfig, logger, path, transports, winston,
    indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; },
    slice = [].slice;

  path = require("path");

  _ = require("lodash");

  fs = require("fs-extra");

  Promise = require("bluebird");

  winston = require("winston");

  konfig = require("./konfig");

  fs.ensureDirSync(konfig("log_path"));

  getName = function(name) {
    return name + ".log";
  };

  getPathToLog = function(name) {
    return path.join(konfig("log_path"), getName(name));
  };

  createFile = function(name, level, opts) {
    var obj;
    if (opts == null) {
      opts = {};
    }
    obj = {
      name: name,
      filename: getPathToLog(name),
      colorize: true,
      tailable: true,
      maxsize: 1000000
    };
    if (level) {
      obj.level = level;
    }
    _.extend(obj, opts);
    return new winston.transports.File(obj);
  };

  transports = [
    createFile("all", null, {
      handleExceptions: true
    })
  ];

  if (process.env["CYPRESS_DEBUG"]) {
    transports.push(new winston.transports.Console());
  }

  logger = new winston.Logger({
    transports: transports,
    exitOnError: function(err) {
      return logger.defaultErrorHandler(err);
    }
  });

  logger.createException = function(err) {
    return require("./exception").create(err, logger.getSettings());
  };

  logger.defaultErrorHandler = function(err) {
    var exit, handleErr;
    logger.info("caught error", {
      error: err.message,
      stack: err.stack
    });
    exit = function() {
      return process.exit(1);
    };
    handleErr = function() {
      var e, ret;
      if (e = logger.errorHandler) {
        ret = e(err);
        if (ret === true) {
          return exit();
        }
      } else {
        console.error(err);
        console.error(err.stack);
        return exit();
      }
    };
    logger.createException(err).then(handleErr)["catch"](handleErr);
    return false;
  };

  logger.setSettings = function(obj) {
    return logger._settings = obj;
  };

  logger.getSettings = function() {
    return logger._settings;
  };

  logger.unsetSettings = function() {
    return delete logger._settings;
  };

  logger.setErrorHandler = function(fn) {
    return logger.errorHandler = fn;
  };

  logger.getData = function(obj) {
    var keys;
    keys = ["level", "message", "timestamp", "type"];
    return _.reduce(obj, function(memo, value, key) {
      if (indexOf.call(keys, key) < 0) {
        memo.data[key] = value;
      } else {
        memo[key] = value;
      }
      return memo;
    }, {
      data: {}
    });
  };

  logger.normalize = function(logs) {
    if (logs == null) {
      logs = [];
    }
    return _.map(logs, logger.getData);
  };

  logger.getLogs = function() {
    var transport;
    transport = "all";
    return new Promise(function(resolve, reject) {
      var opts, ref, t;
      opts = {
        limit: 500,
        order: "desc"
      };
      t = (function() {
        if ((ref = logger.transports[transport]) != null) {
          return ref;
        } else {
          throw new Error("Log transport: '" + transport + "' does not exist!");
        }
      })();
      return t.query(opts, function(err, results) {
        if (err) {
          return reject(err);
        }
        return resolve(logger.normalize(results));
      });
    });
  };

  logger.off = function() {
    return logger.removeAllListeners("logging");
  };

  logger.onLog = function(fn) {
    var name;
    name = "all";
    logger.off();
    return logger.on("logging", function(transport, level, msg, data) {
      var obj;
      if (transport.name === name) {
        obj = {
          level: level,
          message: msg
        };
        obj.type = data.type;
        obj.data = _.omit(data, "type");
        obj.timestamp = new Date;
        return fn(obj);
      }
    });
  };

  logger.clearLogs = function() {
    var files;
    files = _.map(logger.transports, function(value, key) {
      return fs.outputFileAsync(getPathToLog(key), "");
    });
    return Promise.all(files);
  };

  logger.log = _.wrap(logger.log, function() {
    var args, last, orig;
    orig = arguments[0], args = 2 <= arguments.length ? slice.call(arguments, 1) : [];
    last = _.last(args);
    if (_.isObject(last)) {
      _.defaults(last, {
        type: "server"
      });
    }
    return orig.apply(this, args);
  });

  process.removeAllListeners("unhandledRejection");

  process.on("unhandledRejection", function(err, promise) {
    logger.defaultErrorHandler(err);
    return false;
  });

  module.exports = logger;

}).call(this);

});
require.register("./lib/modes/ci.js",function (module, exports, require) {(function() {
  var Project, Promise, api, errors, git, headless, os;

  os = require("os");

  git = require("gift");

  Promise = require("bluebird");

  headless = require("./headless");

  api = require("../api");

  errors = require("../errors");

  Project = require("../project");

  module.exports = {
    getBranchFromGit: function(repo) {
      return repo.branchAsync().get("name")["catch"](function() {
        return "";
      });
    },
    getMessage: function(repo) {
      return repo.current_commitAsync().get("message")["catch"](function() {
        return "";
      });
    },
    getAuthor: function(repo) {
      return repo.current_commitAsync().get("author").get("name")["catch"](function() {
        return "";
      });
    },
    getBranch: function(repo) {
      var b, branch, i, len, ref;
      ref = ["CIRCLE_BRANCH", "TRAVIS_BRANCH", "CI_BRANCH"];
      for (i = 0, len = ref.length; i < len; i++) {
        branch = ref[i];
        if (b = process.env[branch]) {
          return Promise.resolve(b);
        }
      }
      return this.getBranchFromGit(repo);
    },
    ensureCi: function() {
      return Promise["try"]((function(_this) {
        return function() {
          if (os.platform() === "linux") {
            return;
          }
          return errors["throw"]("NOT_CI_ENVIRONMENT");
        };
      })(this));
    },
    ensureProjectAPIToken: function(projectId, projectPath, projectName, key) {
      var repo;
      if (!key) {
        return errors["throw"]("CI_KEY_MISSING");
      }
      repo = Promise.promisifyAll(git(projectPath));
      return Promise.props({
        branch: this.getBranch(repo),
        author: this.getAuthor(repo),
        message: this.getMessage(repo)
      }).then(function(git) {
        return api.createCi({
          key: key,
          projectId: projectId,
          projectName: projectName,
          branch: git.branch,
          author: git.author,
          message: git.message
        })["catch"](function(err) {
          switch (err.statusCode) {
            case 401:
              key = key.slice(0, 5) + "..." + key.slice(-5);
              return errors["throw"]("CI_KEY_NOT_VALID", key);
            case 404:
              return errors["throw"]("CI_PROJECT_NOT_FOUND");
            default:
              return errors["throw"]("CI_CANNOT_COMMUNICATE");
          }
        });
      });
    },
    reportStats: function(projectId, ciId, projectName, key, stats) {
      return api.updateCi({
        key: key,
        ciId: ciId,
        stats: stats,
        projectId: projectId,
        projectName: projectName
      })["catch"](function(err) {});
    },
    run: function(options) {
      var projectPath;
      projectPath = options.projectPath;
      return this.ensureCi().then(function() {
        return Project.add(projectPath);
      }).then(function() {
        return Project.id(projectPath);
      }).then((function(_this) {
        return function(id) {
          return Project.config(projectPath).then(function(cfg) {
            var projectName;
            projectName = cfg.projectName;
            return _this.ensureProjectAPIToken(id, projectPath, projectName, options.key).then(function(ciId) {
              options.ensureSession = false;
              return headless.run(options).then(function(stats) {
                if (stats == null) {
                  stats = {};
                }
                return _this.reportStats(id, ciId, projectName, options.key, stats)["return"](stats.failures);
              });
            });
          });
        };
      })(this));
    }
  };

}).call(this);

});
require.register("./lib/modes/headed.js",function (module, exports, require) {(function() {
  var Events, Position, Promise, Renderer, Tray, Updater, _, app, cyIcons, errors, image, logs, notifier, os, user;

  _ = require("lodash");

  os = require("os");

  app = require("electron").app;

  image = require("electron").nativeImage;

  Promise = require("bluebird");

  cyIcons = require("@cypress/core-icons");

  Position = require("electron-positioner");

  notifier = require("node-notifier");

  user = require("../user");

  errors = require("../errors");

  Updater = require("../updater");

  logs = require("../electron/handlers/logs");

  Tray = require("../electron/handlers/tray");

  Events = require("../electron/handlers/events");

  Renderer = require("../electron/handlers/renderer");

  module.exports = {
    isMac: function() {
      return os.platform() === "darwin";
    },
    onDrop: function() {},
    onClick: function(bounds, win) {
      var coords, positioner;
      positioner = new Position(win);
      coords = positioner.calculate("trayCenter", bounds);
      Updater.setCoords(coords);
      win.setPosition(coords.x, coords.y);
      if (win.isVisible()) {
        return win.hide();
      } else {
        return win.show();
      }
    },
    onRightClick: function() {},
    onWindowAllClosed: function(app) {
      Events.stop();
      return app.exit(0);
    },
    getRendererArgs: function(coords) {
      var common;
      common = {
        width: 300,
        height: 400,
        resizable: false,
        type: "INDEX",
        onBlur: function() {
          if (this.webContents.isDevToolsOpened()) {
            return;
          }
          return Renderer.hideAllUnlessAnotherWindowIsFocused();
        },
        onFocus: function() {
          return Renderer.showAll();
        }
      };
      _.extend(common, this.platformArgs());
      if (coords) {
        _.extend(common, coords, {
          show: true
        });
      }
      return common;
    },
    platformArgs: function() {
      return {
        darwin: {
          show: false,
          frame: false,
          transparent: true
        },
        linux: {
          show: true,
          frame: true,
          transparent: false,
          icon: image.createFromPath(cyIcons.getPathToIcon("icon_128x128.png"))
        }
      }[os.platform()];
    },
    notify: function() {
      if (!this.isMac()) {
        return;
      }
      return user.ensureSession()["catch"](function() {
        return notifier.notify({
          title: "Cypress is now running...",
          message: "Click the 'cy' icon in your tray to login.",
          icon: cyIcons.getPathToIcon("icon_32x32@2x.png")
        });
      });
    },
    ready: function(options) {
      var ready;
      if (options == null) {
        options = {};
      }
      _.defaults(options, {
        onQuit: function() {
          logs.off();
          return app.exit(0);
        },
        onOpenProject: function() {
          return Tray.setImage("blue");
        },
        onCloseProject: function() {
          return Tray.setImage("black");
        },
        onError: function(err) {
          return Tray.setImage("red");
        }
      });
      ready = (function(_this) {
        return function() {
          return Renderer.create(_this.getRendererArgs(options.coords)).then(function(win) {
            Events.start(options);
            if (options.updating) {
              Updater.install(options);
            }
            Tray.display({
              onDrop: function() {},
              onClick: function(e, bounds) {
                return _this.onClick(bounds, win);
              },
              onRightClick: function() {}
            });
            return win;
          });
        };
      })(this);
      return Promise.props({
        ready: ready(),
        notify: this.notify()
      }).get("ready");
    },
    run: function(options) {
      return new Promise((function(_this) {
        return function(resolve, reject) {
          app.commandLine.appendSwitch("disable-renderer-backgrounding");
          app.on("window-all-closed", function() {
            return _this.onWindowAllClosed(app);
          });
          return app.on("ready", function() {
            return resolve(_this.ready(options));
          });
        };
      })(this));
    }
  };

}).call(this);

});
require.register("./lib/modes/headless.js",function (module, exports, require) {(function() {
  var Project, Promise, Renderer, chalk, errors, inquirer, project, user;

  chalk = require("chalk");

  Promise = require("bluebird");

  inquirer = require("inquirer");

  user = require("../user");

  errors = require("../errors");

  Project = require("../project");

  project = require("../electron/handlers/project");

  Renderer = require("../electron/handlers/renderer");

  module.exports = {
    getId: function() {
      return Math.random();
    },
    ensureAndOpenProjectByPath: function(id, options) {
      var open, projectPath;
      projectPath = options.projectPath;
      open = (function(_this) {
        return function() {
          return _this.openProject(id, options);
        };
      })(this);
      return Project.exists(projectPath).then((function(_this) {
        return function(bool) {
          if (bool) {
            return open();
          }
          return _this.promptAddProject(projectPath).then(open);
        };
      })(this));
    },
    promptAddProject: function(projectPath) {
      var questions;
      console.log(chalk.yellow("We couldn't find a Cypress project at this path:"), chalk.blue(projectPath), "\n");
      questions = [
        {
          name: "add",
          type: "list",
          message: "Would you like to add this project to Cypress?",
          choices: [
            {
              name: "Yes: add this project and run the tests.",
              value: true
            }, {
              name: "No:  don't add this project.",
              value: false
            }
          ]
        }
      ];
      return new Promise((function(_this) {
        return function(resolve, reject) {
          return inquirer.prompt(questions, function(answers) {
            if (answers.add) {
              return Project.add(projectPath).then(function() {
                console.log(chalk.green("\nOk great, added the project.\n"));
                return resolve();
              })["catch"](reject);
            } else {
              return reject(errors.get("PROJECT_DOES_NOT_EXIST"));
            }
          });
        };
      })(this));
    },
    openProject: function(id, options) {
      return project.open(options.projectPath, options, {
        morgan: false,
        socketId: id,
        report: true,
        isHeadless: true
      })["catch"]({
        portInUse: true
      }, function(err) {
        return errors["throw"]("PORT_IN_USE_LONG", err.port);
      });
    },
    createRenderer: function(url, showGui) {
      if (showGui == null) {
        showGui = false;
      }
      return Renderer.create({
        url: url,
        width: 0,
        height: 0,
        show: showGui,
        frame: false,
        type: "PROJECT"
      }).then(function(win) {
        if (!showGui) {
          win.hide();
        }
        win.setSize(1280, 720);
        return win.center();
      });
    },
    waitForRendererToConnect: function(project, id) {
      return this.waitForSocketConnection(project, id).timeout(10000)["catch"](Promise.TimeoutError, function(err) {
        return errors["throw"]("TESTS_DID_NOT_START");
      });
    },
    waitForSocketConnection: function(project, id) {
      return new Promise(function(resolve, reject) {
        var fn;
        fn = function(socketId) {
          if (socketId === id) {
            project.removeListener("socket:connected", fn);
            return resolve();
          }
        };
        return project.on("socket:connected", fn);
      });
    },
    waitForTestsToFinishRunning: function(project) {
      return new Promise(function(resolve, reject) {
        return project.once("end", resolve);
      });
    },
    runTests: function(project, id, url, gui) {
      return Promise.props({
        connection: this.waitForRendererToConnect(project, id),
        stats: this.waitForTestsToFinishRunning(project),
        renderer: this.createRenderer(url, gui)
      });
    },
    ready: function(options) {
      var ready;
      if (options == null) {
        options = {};
      }
      ready = (function(_this) {
        return function() {
          var id;
          id = _this.getId();
          return _this.ensureAndOpenProjectByPath(id, options).then(function(project) {
            return project.ensureSpecUrl(options.spec).then(function(url) {
              console.log("\nTests should begin momentarily...\n");
              return _this.runTests(project, id, url, options.showHeadlessGui).get("stats");
            });
          });
        };
      })(this);
      if (options.ensureSession !== false) {
        return user.ensureSession().then(ready);
      } else {
        return ready();
      }
    },
    run: function(options) {
      var app, waitForReady;
      app = require("electron").app;
      app.commandLine.appendSwitch("disable-renderer-backgrounding");
      waitForReady = function() {
        return new Promise(function(resolve, reject) {
          return app.on("ready", resolve);
        });
      };
      return Promise.any([waitForReady(), Promise.delay(500)]).then((function(_this) {
        return function() {
          return _this.ready(options);
        };
      })(this));
    }
  };

}).call(this);

});
require.register("./lib/modes/pkg.js",function (module, exports, require) {(function() {
  var Promise, cwd, fs, path;

  fs = require("fs-extra");

  path = require("path");

  Promise = require("bluebird");

  cwd = require("../cwd");

  fs = Promise.promisifyAll(fs);

  module.exports = function() {
    return fs.readJsonAsync(cwd("package.json"));
  };

}).call(this);

});
require.register("./lib/modes/smoke_test.js",function (module, exports, require) {(function() {
  module.exports = function(options) {
    return Promise.resolve(options.pong);
  };

}).call(this);

});
require.register("./lib/project.js",function (module, exports, require) {(function() {
  var EE, Project, Promise, Reporter, Server, Watchers, _, api, cache, config, errors, fs, glob, ids, logger, path, scaffold, settings, user,
    extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
    hasProp = {}.hasOwnProperty,
    slice = [].slice,
    indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

  path = require("path");

  glob = require("glob");

  EE = require("events");

  _ = require("lodash");

  fs = require("fs-extra");

  Promise = require("bluebird");

  ids = require("./ids");

  api = require("./api");

  user = require("./user");

  cache = require("./cache");

  config = require("./config");

  logger = require("./logger");

  errors = require("./errors");

  Server = require("./server");

  scaffold = require("./scaffold");

  Watchers = require("./watchers");

  Reporter = require("./reporter");

  settings = require("./util/settings");

  fs = Promise.promisifyAll(fs);

  glob = Promise.promisify(glob);

  Project = (function(superClass) {
    extend(Project, superClass);

    function Project(projectRoot) {
      if (!(this instanceof Project)) {
        return new Project(projectRoot);
      }
      if (!projectRoot) {
        throw new Error("Instantiating lib/project requires a projectRoot!");
      }
      this.projectRoot = path.resolve(projectRoot);
      this.server = Server();
      this.watchers = Watchers();
    }

    Project.prototype.open = function(options) {
      if (options == null) {
        options = {};
      }
      _.defaults(options, {
        type: "opened",
        sync: false,
        report: false,
        changeEvents: false
      });
      return this.getConfig(options).then((function(_this) {
        return function(cfg) {
          return _this.server.open(_this.projectRoot, cfg).then(function() {
            _this.cfg = cfg;
            _this.sync(options);
            return Promise.join(_this.watchSettingsAndStartWebsockets(options.changeEvents, cfg), _this.scaffold(cfg))["return"](_this);
          });
        };
      })(this));
    };

    Project.prototype.sync = function(options) {
      return this.ensureProjectId().then((function(_this) {
        return function(id) {
          return _this.updateProject(id, options);
        };
      })(this))["catch"](function() {});
    };

    Project.prototype.close = function(options) {
      var ref, ref1;
      if (options == null) {
        options = {};
      }
      _.defaults(options, {
        sync: false,
        type: "closed"
      });
      this.sync(options);
      this.removeAllListeners();
      return Promise.join((ref = this.server) != null ? ref.close() : void 0, (ref1 = this.watchers) != null ? ref1.close() : void 0);
    };

    Project.prototype.updateProject = function(id, options) {
      if (options == null) {
        options = {};
      }
      return Promise["try"]((function(_this) {
        return function() {
          if (!options.sync) {
            return;
          }
          return Promise.all([user.ensureSession(), _this.getConfig()]).spread(function(session, cfg) {
            return api.updateProject(id, options.type, cfg.projectName, session);
          });
        };
      })(this));
    };

    Project.prototype.watchSettings = function(changeEvents) {
      var obj;
      if (!changeEvents) {
        return;
      }
      obj = {
        onChange: (function(_this) {
          return function(filePath, stats) {
            if (_this.generatedProjectIdTimestamp && (new Date - _this.generatedProjectIdTimestamp) < 1000) {
              return;
            }
            return _this.emit("settings:changed");
          };
        })(this)
      };
      return this.watchers.watch(settings.pathToCypressJson(this.projectRoot), obj);
    };

    Project.prototype.watchSettingsAndStartWebsockets = function(changeEvents, config) {
      var reporter;
      if (config == null) {
        config = {};
      }
      this.watchSettings(changeEvents);
      if (config.report) {
        reporter = Reporter.create(config.reporter);
      }
      return this.server.startWebsockets(this.watchers, config, {
        onIsNewProject: (function(_this) {
          return function() {
            return _this.determineIsNewProject(config.integrationFolder);
          };
        })(this),
        onConnect: (function(_this) {
          return function(id) {
            return _this.emit("socket:connected", id);
          };
        })(this),
        onMocha: (function(_this) {
          return function() {
            var args, event, stats;
            event = arguments[0], args = 2 <= arguments.length ? slice.call(arguments, 1) : [];
            if (!reporter) {
              return;
            }
            args = [event].concat(args);
            reporter.emit.apply(reporter, args);
            if (event === "end") {
              stats = reporter.stats();
              _this.server.end();
              return Promise.delay(1000).then(function() {
                return _this.emit("end", stats);
              });
            }
          };
        })(this)
      });
    };

    Project.prototype.determineIsNewProject = function(integrationFolder) {
      var checkIfBothMatch, getCurrentSize, nameIsDefault;
      nameIsDefault = function(file) {
        return path.basename(file) === scaffold.integrationExampleName();
      };
      getCurrentSize = function(file) {
        return fs.statAsync(file).get("size");
      };
      checkIfBothMatch = function(current, scaffold) {
        return current === scaffold;
      };
      return glob("**/*", {
        cwd: integrationFolder,
        realpath: true
      }).then(function(files) {
        var def, exampleSpec;
        if (files.length !== 1) {
          return false;
        }
        exampleSpec = files[0];
        if (!(def = nameIsDefault(exampleSpec))) {
          return false;
        }
        return Promise.join(getCurrentSize(exampleSpec), scaffold.integrationExampleSize(), checkIfBothMatch);
      });
    };

    Project.prototype.getConfig = function(options) {
      var c;
      if (options == null) {
        options = {};
      }
      if (c = this.cfg) {
        return Promise.resolve(c);
      } else {
        return config.get(this.projectRoot, options);
      }
    };

    Project.prototype.ensureSpecUrl = function(spec) {
      return this.getConfig().then((function(_this) {
        return function(cfg) {
          if (spec) {
            return _this.ensureSpecExists(spec).then(function(pathToSpec) {
              var prefixedPath;
              prefixedPath = _this.getPrefixedPathToSpec(cfg.integrationFolder, pathToSpec);
              return _this.getUrlBySpec(cfg.clientUrl, prefixedPath);
            });
          } else {
            return _this.getUrlBySpec(cfg.clientUrl, "/__all");
          }
        };
      })(this));
    };

    Project.prototype.ensureSpecExists = function(spec) {
      var specFile;
      specFile = path.resolve(this.projectRoot, spec);
      return fs.statAsync(specFile)["return"](specFile)["catch"](function() {
        return errors["throw"]("SPEC_FILE_NOT_FOUND", specFile);
      });
    };

    Project.prototype.getPrefixedPathToSpec = function(integrationFolder, pathToSpec) {
      return "/" + path.join("integration", path.relative(integrationFolder, pathToSpec));
    };

    Project.prototype.getUrlBySpec = function(clientUrl, specUrl) {
      return [clientUrl, "#/tests", specUrl, "?__ui=satellite"].join("");
    };

    Project.prototype.scaffold = function(config) {
      return Promise.join(scaffold.integration(config.integrationFolder), scaffold.fixture(config.fixturesFolder, {
        remove: config.fixturesFolderRemove
      }), scaffold.support(config.supportFolder, {
        remove: config.supportFolderRemove
      }));
    };

    Project.prototype.writeProjectId = function(id) {
      var attrs;
      attrs = {
        projectId: id
      };
      logger.info("Writing Project ID", _.clone(attrs));
      this.generatedProjectIdTimestamp = new Date;
      return settings.write(this.projectRoot, attrs)["return"](id);
    };

    Project.prototype.createProjectId = function() {
      var id;
      if (id = process.env.CYPRESS_PROJECT_ID) {
        return this.writeProjectId(id);
      }
      return Promise.all([user.ensureSession(), this.getConfig()]).bind(this).spread(function(session, cfg) {
        return api.createProject(cfg.projectName, session);
      }).then(this.writeProjectId);
    };

    Project.prototype.getProjectId = function() {
      return this.verifyExistance().then((function(_this) {
        return function() {
          var id;
          if (id = process.env.CYPRESS_PROJECT_ID) {
            return {
              projectId: id
            };
          } else {
            return settings.read(_this.projectRoot);
          }
        };
      })(this)).then((function(_this) {
        return function(settings) {
          var id;
          if (settings && (id = settings.projectId)) {
            return id;
          }
          return errors["throw"]("NO_PROJECT_ID", _this.projectRoot);
        };
      })(this));
    };

    Project.prototype.verifyExistance = function() {
      return fs.statAsync(this.projectRoot)["return"](this)["catch"]((function(_this) {
        return function() {
          return errors["throw"]("NO_PROJECT_FOUND_AT_PROJECT_ROOT", _this.projectRoot);
        };
      })(this));
    };

    Project.prototype.ensureProjectId = function() {
      return this.getProjectId().bind(this)["catch"]({
        type: "NO_PROJECT_ID"
      }, this.createProjectId);
    };

    Project.paths = function() {
      return cache.getProjectPaths();
    };

    Project.remove = function(path) {
      return cache.removeProject(path);
    };

    Project.add = function(path) {
      return cache.insertProject(path);
    };

    Project.removeIds = function(p) {
      return Project(p).verifyExistance().call("getConfig").then(function(cfg) {
        return ids.remove(cfg.integrationFolder);
      });
    };

    Project.id = function(path) {
      return Project(path).getProjectId();
    };

    Project.exists = function(path) {
      return this.paths().then(function(paths) {
        return indexOf.call(paths, path) >= 0;
      });
    };

    Project.config = function(path) {
      return Project(path).getConfig();
    };

    Project.getSecretKeyByPath = function(path) {
      return Project.id(path).then(function(id) {
        return user.ensureSession().then(function(session) {
          return api.getProjectToken(id, session)["catch"](function() {
            return errors["throw"]("CANNOT_FETCH_PROJECT_TOKEN");
          });
        });
      });
    };

    Project.generateSecretKeyByPath = function(path) {
      return Project.id(path).then(function(id) {
        return user.ensureSession().then(function(session) {
          return api.updateProjectToken(id, session)["catch"](function() {
            return errors["throw"]("CANNOT_CREATE_PROJECT_TOKEN");
          });
        });
      });
    };

    return Project;

  })(EE);

  module.exports = Project;

}).call(this);

});
require.register("./lib/reporter.js",function (module, exports, require) {(function() {
  var Mocha, Reporter, STATS, _, chalk, createErr, createRunnable, createSuite, events,
    slice = [].slice;

  _ = require("lodash");

  Mocha = require("mocha");

  chalk = require("chalk");

  STATS = "suites tests passes pending failures start end duration".split(" ");

  createSuite = function(obj) {
    var p, suite;
    suite = new Mocha.Suite(obj.title, {});
    if (p = obj.parent) {
      suite.parent = createSuite(p);
    }
    return suite;
  };

  createRunnable = function(obj) {
    var p, runnable;
    runnable = new Mocha.Runnable(obj.title, function() {});
    runnable.timedOut = obj.timedOut;
    runnable.async = obj.async;
    runnable.sync = obj.sync;
    runnable.duration = obj.duration;
    runnable.state = obj.state;
    if (p = obj.parent) {
      runnable.parent = createSuite(p);
    }
    return runnable;
  };

  createErr = function(test, err) {
    return [createRunnable(test), err];
  };

  events = {
    "start": true,
    "end": true,
    "suite": createSuite,
    "suite end": createSuite,
    "test": createRunnable,
    "test end": createRunnable,
    "hook": createRunnable,
    "hook end": createRunnable,
    "pass": createRunnable,
    "pending": createRunnable,
    "fail": createErr
  };

  Reporter = (function() {
    function Reporter(reporterName) {
      var reporter;
      if (reporterName == null) {
        reporterName = "spec";
      }
      if (!(this instanceof Reporter)) {
        return new Reporter(reporterName);
      }
      this.reporterName = reporterName;
      if (reporterName === "teamcity") {
        reporter = require("mocha-teamcity-reporter");
      } else {
        reporter = this.reporterName;
      }
      this.mocha = new Mocha({
        reporter: reporter
      });
      this.runner = new Mocha.Runner(this.mocha.suite);
      this.reporter = new this.mocha._reporter(this.runner, {});
      this.runner.ignoreLeaks = true;
    }

    Reporter.prototype.emit = function() {
      var args, event;
      event = arguments[0], args = 2 <= arguments.length ? slice.call(arguments, 1) : [];
      if (args = this.parseArgs(event, args)) {
        return this.runner.emit.apply(this.runner, args);
      }
    };

    Reporter.prototype.parseArgs = function(event, args) {
      var e;
      if (e = events[event]) {
        if (_.isFunction(e)) {
          args = e.apply(this, args);
        }
        return [event].concat(args);
      }
    };

    Reporter.prototype.stats = function() {
      return _.extend({
        reporter: this.reporterName
      }, _.pick(this.reporter.stats, STATS));
    };

    Reporter.create = function(reporterName) {
      return new Reporter(reporterName);
    };

    return Reporter;

  })();

  module.exports = Reporter;

}).call(this);

});
require.register("./lib/request.js",function (module, exports, require) {(function() {
  var _, request;

  _ = require("lodash");

  request = require("request-promise");

  module.exports = {
    contentTypeIsJson: function(response) {
      var ref, ref1;
      return response != null ? (ref = response.headers) != null ? (ref1 = ref["content-type"]) != null ? ref1.includes("application/json") : void 0 : void 0 : void 0;
    },
    parseJsonBody: function(body) {
      var e, error;
      try {
        return JSON.parse(body);
      } catch (error) {
        e = error;
        return body;
      }
    },
    normalizeResponse: function(response) {
      response = _.pick(response, "statusCode", "body", "headers");
      response.status = response.statusCode;
      delete response.statusCode;
      if (_.isString(response.body) && this.contentTypeIsJson(response)) {
        response.body = this.parseJsonBody(response.body);
      }
      return response;
    },
    reduceCookieToArray: function(c) {
      return _.reduce(c, function(memo, val, key) {
        memo.push([key.trim(), val.trim()].join("="));
        return memo;
      }, []);
    },
    createCookieString: function(c) {
      return this.reduceCookieToArray(c).join("; ");
    },
    send: function(options) {
      var c, ms;
      if (options == null) {
        options = {};
      }
      _.defaults(options, {
        headers: {},
        gzip: true
      });
      _.extend(options, {
        strictSSL: false,
        simple: false,
        resolveWithFullResponse: true
      });
      if (c = options.cookies) {
        options.headers["Cookie"] = this.createCookieString(c);
      }
      ms = Date.now();
      return request(options).then(this.normalizeResponse.bind(this)).then(function(resp) {
        resp.duration = Date.now() - ms;
        return resp;
      });
    }
  };

}).call(this);

});
require.register("./lib/routes.js",function (module, exports, require) {(function() {
  var CacheBuster, builds, cwd, files, logger, path, proxy, spec, xhrs;

  path = require("path");

  CacheBuster = require("./util/cache_buster");

  cwd = require("./cwd");

  logger = require("./logger");

  spec = require("./controllers/spec_processor");

  xhrs = require("./controllers/xhrs");

  files = require("./controllers/files");

  proxy = require("./controllers/proxy");

  builds = require("./controllers/builds");

  module.exports = function(app, config) {
    app.get("/__cypress/tests", function(req, res, next) {
      var test;
      test = CacheBuster.strip(req.query.p);
      return spec.handle(test, req, res, config, next);
    });
    app.get("/__cypress/files", function(req, res) {
      return files.handleFiles(req, res, config);
    });
    app.get("/__cypress/iframes/*", function(req, res) {
      return files.handleIframe(req, res, config);
    });
    app.get("/__cypress/builds", function(req, res, next) {
      return builds.handleBuilds(req, res, config, next);
    });
    app.all("/__cypress/xhrs/*", function(req, res, next) {
      return xhrs.handle(req, res, config, next);
    });
    app.get("/__root/*", function(req, res, next) {
      var file;
      file = path.join(config.projectRoot, req.params[0]);
      return res.sendFile(file, {
        etag: false
      });
    });
    app.get(config.clientRoute, function(req, res) {
      return res.render(cwd("lib", "public", "index.html"), {
        config: JSON.stringify(config),
        projectName: config.projectName
      });
    });
    app.all("*", function(req, res, next) {
      return proxy.handle(req, res, config, app, next);
    });
    return app.use(function(err, req, res, next) {
      console.log(err.stack);
      res.set("x-cypress-error", err.message);
      res.set("x-cypress-stack", err.stack.replace("\n", "\\n"));
      return res.sendStatus(500);
    });
  };

}).call(this);

});
require.register("./lib/scaffold.js",function (module, exports, require) {(function() {
  var INTEGRATION_EXAMPLE_SPEC, Promise, _, cwd, cypressEx, fs, path;

  _ = require("lodash");

  fs = require("fs-extra");

  Promise = require("bluebird");

  path = require("path");

  cypressEx = require("@cypress/core-example");

  cwd = require("./cwd");

  fs = Promise.promisifyAll(fs);

  INTEGRATION_EXAMPLE_SPEC = cypressEx.getPathToExample();

  module.exports = {
    integration: function(folder) {
      return this.verifyScaffolding(folder, (function(_this) {
        return function() {
          return _this.copy(INTEGRATION_EXAMPLE_SPEC, folder);
        };
      })(this));
    },
    fixture: function(folder, options) {
      return this.verifyScaffolding(folder, options, (function(_this) {
        return function() {
          return _this.copy("example.json", folder);
        };
      })(this));
    },
    support: function(folder, options) {
      return this.verifyScaffolding(folder, options, (function(_this) {
        return function() {
          return Promise.join(_this.copy("defaults.js", folder), _this.copy("commands.js", folder));
        };
      })(this));
    },
    copy: function(file, folder) {
      var dest, src;
      src = path.resolve(cwd("lib", "scaffold"), file);
      dest = path.join(folder, path.basename(file));
      return fs.copyAsync(src, dest);
    },
    integrationExampleSize: function() {
      return fs.statAsync(INTEGRATION_EXAMPLE_SPEC).get("size");
    },
    integrationExampleName: function() {
      return path.basename(INTEGRATION_EXAMPLE_SPEC);
    },
    verifyScaffolding: function(folder, options, fn) {
      var remove;
      if (options == null) {
        options = {};
      }
      if (_.isFunction(options)) {
        fn = options;
        options = {};
      }
      _.defaults(options, {
        remove: false
      });
      if (options.remove) {
        remove = function() {
          return fs.removeAsync(folder)["catch"](remove);
        };
        return fs.statAsync(folder).then(remove)["catch"](function() {});
      } else {
        return fs.statAsync(folder)["catch"]((function(_this) {
          return function() {
            return fn.call(_this);
          };
        })(this));
      }
    }
  };

}).call(this);

});
require.register("./lib/server.js",function (module, exports, require) {(function() {
  var Promise, Server, Socket, _, allowDestroy, cookie, cwd, errors, express, hbs, http, httpProxy, logger, url;

  _ = require("underscore");

  hbs = require("hbs");

  url = require("url");

  http = require("http");

  cookie = require("cookie");

  express = require("express");

  Promise = require("bluebird");

  httpProxy = require("http-proxy");

  allowDestroy = require("server-destroy");

  cwd = require("./cwd");

  errors = require("./errors");

  logger = require("./logger");

  Socket = require("./socket");

  Server = (function() {
    function Server() {
      if (!(this instanceof Server)) {
        return new Server;
      }
      this._server = null;
      this._proxy = null;
      this._socket = null;
    }

    Server.prototype.createExpressApp = function(port, morgan) {
      var app;
      app = express();
      app.set("port", port);
      app.set("view engine", "html");
      app.engine("html", hbs.__express);
      app.use(require("cookie-parser")());
      app.use(require("compression")());
      if (morgan) {
        app.use(require("morgan")("dev"));
      }
      app.use("/__cypress/static", express["static"](cwd("lib", "public")));
      app.use(require("errorhandler")());
      app.disable("x-powered-by");
      return app;
    };

    Server.prototype.createRoutes = function(app, config) {
      return require("./routes")(app, config);
    };

    Server.prototype.getHttpServer = function() {
      return this._server;
    };

    Server.prototype.portInUseErr = function(port) {
      var e;
      e = errors.get("PORT_IN_USE_SHORT", port);
      e.port = port;
      e.portInUse = true;
      return e;
    };

    Server.prototype.open = function(projectRoot, config) {
      if (config == null) {
        config = {};
      }
      return Promise["try"]((function(_this) {
        return function() {
          var app;
          app = _this.createExpressApp(config.port, config.morgan);
          logger.setSettings(config);
          _this.createRoutes(app, config);
          return _this.createServer(config.port, config.socketIoRoute, app)["return"](_this);
        };
      })(this));
    };

    Server.prototype.createServer = function(port, socketIoRoute, app) {
      return new Promise((function(_this) {
        return function(resolve, reject) {
          var onError, onUpgrade;
          _this._server = http.createServer(app);
          _this._proxy = httpProxy.createProxyServer();
          allowDestroy(_this._server);
          onError = function(err) {
            if (err.code === "EADDRINUSE") {
              return reject(_this.portInUseErr(port));
            }
          };
          onUpgrade = function(req, socket, head) {
            return _this.proxyWebsockets(_this._proxy, socketIoRoute, req, socket, head);
          };
          _this._server.on("upgrade", onUpgrade);
          _this._server.once("error", onError);
          return _this._server.listen(port, function() {
            _this.isListening = true;
            logger.info("Server listening", {
              port: port
            });
            _this._server.removeListener("error", onError);
            return resolve(_this._server);
          });
        };
      })(this));
    };

    Server.prototype.proxyWebsockets = function(proxy, socketIoRoute, req, socket, head) {
      var cookies, hostname, port, ref, ref1, remoteHost;
      if (req.url.startsWith(socketIoRoute)) {
        return;
      }
      cookies = cookie.parse((ref = req.headers.cookie) != null ? ref : "");
      if (remoteHost = cookies["__cypress.remoteHost"]) {
        ref1 = url.parse(remoteHost), hostname = ref1.hostname, port = ref1.port;
        return proxy.ws(req, socket, head, {
          target: {
            host: hostname,
            port: port
          }
        });
      } else {
        if (socket.writable) {
          return socket.end();
        }
      }
    };

    Server.prototype._close = function() {
      return new Promise((function(_this) {
        return function(resolve) {
          logger.unsetSettings();
          if (!_this._server || !_this.isListening) {
            return resolve();
          }
          logger.info("Server closing");
          return _this._server.destroy(function() {
            _this.isListening = false;
            return resolve();
          });
        };
      })(this));
    };

    Server.prototype.close = function() {
      var ref;
      return Promise.join(this._close(), (ref = this._socket) != null ? ref.close() : void 0);
    };

    Server.prototype.end = function() {
      return this._socket && this._socket.end();
    };

    Server.prototype.startWebsockets = function(watchers, config, options) {
      this._socket = Socket();
      return this._socket.startListening(this._server, watchers, config, options);
    };

    return Server;

  })();

  module.exports = Server;

}).call(this);

});
require.register("./lib/socket.js",function (module, exports, require) {(function() {
  var Promise, Request, Socket, _, cwd, fixture, fs, logger, open, os, path, pathHelpers, socketIo, str, uuid,
    slice = [].slice;

  _ = require("lodash");

  os = require("os");

  fs = require("fs-extra");

  str = require("underscore.string");

  path = require("path");

  uuid = require("node-uuid");

  Promise = require("bluebird");

  socketIo = require("socket.io");

  open = require("./util/open");

  pathHelpers = require("./util/path_helpers");

  cwd = require("./cwd");

  fixture = require("./fixture");

  Request = require("./request");

  logger = require("./logger");

  Socket = (function() {
    function Socket() {
      if (!(this instanceof Socket)) {
        return new Socket;
      }
    }

    Socket.prototype.onTestFileChange = function(integrationFolder, originalFilePath, filePath, stats) {
      logger.info("onTestFileChange", {
        filePath: filePath
      });
      if (!/\.(js|coffee)$/.test(filePath)) {
        return;
      }
      return fs.statAsync(filePath).then((function(_this) {
        return function() {
          return _this.io.emit("test:changed", {
            file: originalFilePath
          });
        };
      })(this))["catch"](function() {});
    };

    Socket.prototype.watchTestFileByPath = function(config, originalFilePath, watchers, cb) {
      var testFilePath;
      if (cb == null) {
        cb = function() {};
      }
      testFilePath = str.ltrim(originalFilePath, "/");
      testFilePath = pathHelpers.getAbsolutePathToSpec(testFilePath, config);
      if ((testFilePath === this.testFilePath) || (config.watchForFileChanges === false)) {
        return cb();
      }
      logger.info("watching test file", {
        path: testFilePath
      });
      watchers.remove(testFilePath);
      this.testFilePath = testFilePath;
      return watchers.watchAsync(testFilePath, {
        onChange: _.bind(this.onTestFileChange, this, config.integrationFolder, originalFilePath)
      }).then(cb);
    };

    Socket.prototype.onRequest = function(options, cb) {
      return Request.send(options).then(cb)["catch"](function(err) {
        return cb({
          __error: err.message
        });
      });
    };

    Socket.prototype.onFixture = function(config, file, cb) {
      return fixture.get(config.fixturesFolder, file).then(cb)["catch"](function(err) {
        return cb({
          __error: err.message
        });
      });
    };

    Socket.prototype.createIo = function(server, path) {
      return socketIo(server, {
        path: path,
        destroyUpgrade: false
      });
    };

    Socket.prototype._startListening = function(server, watchers, config, options) {
      var chromiums, integrationFolder, messages, socketIoRoute;
      _.defaults(options, {
        socketId: null,
        onMocha: function() {},
        onConnect: function() {},
        onChromiumRun: function() {},
        onIsNewProject: function() {},
        checkForAppErrors: function() {}
      });
      options.onIsNewProject = Promise.method(options.onIsNewProject);
      messages = {};
      chromiums = {};
      integrationFolder = config.integrationFolder, socketIoRoute = config.socketIoRoute;
      this.testsDir = integrationFolder;
      this.io = this.createIo(server, socketIoRoute);
      return this.io.on("connection", (function(_this) {
        return function(socket) {
          logger.info("socket connected");
          socket.on("chromium:connected", function() {
            if (socket.inChromiumRoom) {
              return;
            }
            socket.inChromiumRoom = true;
            socket.join("chromium");
            return socket.on("chromium:history:response", function(id, response) {
              var message;
              if (message = chromiums[id]) {
                delete chromiums[id];
                return message(response);
              }
            });
          });
          socket.on("history:entries", function(cb) {
            var id;
            id = uuid.v4();
            chromiums[id] = cb;
            if (_.keys(_this.io.sockets.adapter.rooms.chromium).length > 0) {
              messages[id] = cb;
              return _this.io.to("chromium").emit("chromium:history:request", id);
            } else {
              return cb({
                __error: "Could not process 'history:entries'. No chromium servers connected."
              });
            }
          });
          socket.on("remote:connected", function() {
            logger.info("remote:connected");
            if (socket.inRemoteRoom) {
              return;
            }
            socket.inRemoteRoom = true;
            socket.join("remote");
            return socket.on("remote:response", function(id, response) {
              var message;
              if (message = messages[id]) {
                delete messages[id];
                logger.info("remote:response", {
                  id: id,
                  response: response
                });
                return message(response);
              }
            });
          });
          socket.on("client:request", function(message, data, cb) {
            var id;
            if (!_.isFunction(cb)) {
              cb = data;
              data = null;
            }
            id = uuid.v4();
            logger.info("client:request", {
              id: id,
              msg: message,
              data: data
            });
            if (_.keys(_this.io.sockets.adapter.rooms.remote).length > 0) {
              messages[id] = cb;
              return _this.io.to("remote").emit("remote:request", id, message, data);
            } else {
              return cb({
                __error: "Could not process '" + message + "'. No remote servers connected."
              });
            }
          });
          socket.on("run:tests:in:chromium", function(src) {
            return options.onChromiumRun(src);
          });
          socket.on("watch:test:file", function(filePath, cb) {
            return _this.watchTestFileByPath(config, filePath, watchers, cb);
          });
          socket.on("request", function() {
            return _this.onRequest.apply(_this, arguments);
          });
          socket.on("fixture", function(fixturePath, cb) {
            return _this.onFixture(config, fixturePath, cb);
          });
          _.each("load:spec:iframe url:changed page:loading command:add command:attrs:changed runner:start runner:end before:run before:add after:add suite:add suite:start suite:stop test test:add test:start test:end after:run test:results:ready exclusive:test".split(" "), function(event) {
            return socket.on(event, function() {
              var args, ref;
              args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
              args = _.chain(args).reject(_.isUndefined).reject(_.isFunction).value();
              return (ref = _this.io).emit.apply(ref, [event].concat(slice.call(args)));
            });
          });
          socket.on("app:connect", function(socketId) {
            return options.onConnect(socketId, socket);
          });
          socket.on("mocha", function() {
            return options.onMocha.apply(options, arguments);
          });
          socket.on("open:finder", function(p, cb) {
            var opts;
            if (cb == null) {
              cb = function() {};
            }
            opts = {};
            if (os.platform() === "darwin") {
              opts.args = "-R";
            }
            return open.opn(p, opts).then(function() {
              return cb();
            });
          });
          return socket.on("is:new:project", function(cb) {
            return options.onIsNewProject().then(cb);
          });
        };
      })(this));
    };

    Socket.prototype.end = function() {
      return this.io && this.io.emit("tests:finished");
    };

    Socket.prototype.startListening = function(server, watchers, config, options) {
      if (process.env["CYPRESS_ENV"] === "development") {
        this.listenToCssChanges(watchers);
      }
      return this._startListening(server, watchers, config, options);
    };

    Socket.prototype.listenToCssChanges = function(watchers) {
      return watchers.watch(cwd("lib", "public", "css"), {
        ignored: (function(_this) {
          return function(path, stats) {
            if (fs.statSync(path).isDirectory()) {
              return false;
            }
            return !/\.css$/.test(path);
          };
        })(this),
        onChange: (function(_this) {
          return function(filePath, stats) {
            filePath = path.basename(filePath);
            return _this.io.emit("cypress:css:changed", {
              file: filePath
            });
          };
        })(this)
      });
    };

    Socket.prototype.close = function() {
      var ref;
      return (ref = this.io) != null ? ref.close() : void 0;
    };

    return Socket;

  })();

  module.exports = Socket;

}).call(this);

});
require.register("./lib/updater.js",function (module, exports, require) {(function() {
  var NwUpdater, Promise, Updater, _, argsUtil, chmodr, coords, cwd, fs, glob, konfig, logger, path, tar, trash,
    slice = [].slice;

  fs = require("fs-extra");

  tar = require("tar-fs");

  path = require("path");

  Promise = require("bluebird");

  _ = require("lodash");

  glob = require("glob");

  chmodr = require("chmodr");

  trash = require("trash");

  NwUpdater = require("node-webkit-updater");

  cwd = require("./cwd");

  konfig = require("./konfig");

  logger = require("./logger");

  argsUtil = require("./util/args");

  trash = Promise.promisify(trash);

  chmodr = Promise.promisify(chmodr);

  coords = null;

  Updater = (function() {
    function Updater(callbacks) {
      if (!(this instanceof Updater)) {
        return new Updater(callbacks);
      }
      this.client = new NwUpdater(this.getPackage());
      this.request = null;
      this.cancelled = false;
      this.callbacks = callbacks;
      if (process.env["CYPRESS_ENV"] !== "production") {
        this.patchAppPath();
      }
    }

    Updater.prototype.getCoords = function() {
      var c;
      if (!(c = coords)) {
        return;
      }
      return "--coords=" + c.x + "x" + c.y;
    };

    Updater.prototype.getArgs = function() {
      var c;
      c = this.getClient();
      return _.compact(["--app-path=" + c.getAppPath(), "--exec-path=" + c.getAppExec(), "--updating", this.getCoords()]);
    };

    Updater.prototype.patchAppPath = function() {
      return this.getClient().getAppPath = function() {
        return cwd();
      };
    };

    Updater.prototype.getPackage = function() {
      var pkg;
      pkg = fs.readJsonSync(cwd("package.json"));
      pkg.manifestUrl = konfig("desktop_manifest_url");
      return pkg;
    };

    Updater.prototype.getClient = function() {
      var ref;
      return (function() {
        if ((ref = this.client) != null) {
          return ref;
        } else {
          throw new Error("missing Updater#client");
        }
      }).call(this);
    };

    Updater.prototype.trash = function(appPath) {
      logger.info("trashing current app", {
        appPath: appPath
      });
      return trash([appPath]);
    };

    Updater.prototype.install = function(argsObj) {
      var appPath, args, c, execPath;
      if (argsObj == null) {
        argsObj = {};
      }
      c = this.getClient();
      appPath = argsObj.appPath, execPath = argsObj.execPath;
      argsObj = _.omit(argsObj, "updating", "execPath", "appPath");
      args = argsUtil.toArray(argsObj);
      return this.trash(appPath).then((function(_this) {
        return function() {
          logger.info("installing updated app", {
            appPath: appPath,
            execPath: execPath
          });
          return _this.copyTmpToAppPath(c.getAppPath(), appPath).then(function() {
            c.run(execPath, args);
            return process.exit(0);
          });
        };
      })(this));
    };

    Updater.prototype.copyTmpToAppPath = function(tmp, appPath) {
      return new Promise(function(resolve, reject) {
        var obj;
        obj = {
          fs: require("original-fs")
        };
        return tar.pack(tmp, obj).pipe(tar.extract(appPath, obj)).on("error", reject).on("finish", resolve);
      });
    };

    Updater.prototype.copyCyDataTo = function(newAppPath) {
      var p;
      p = new Promise(function(resolve, reject) {
        return glob("**/app/package.json", {
          cwd: newAppPath,
          ignore: "**/node_modules/**"
        }, function(err, files) {
          var newAppConfigPath;
          if (err) {
            return reject(err);
          }
          newAppConfigPath = path.join(newAppPath, path.dirname(files[0]), konfig("cy_path"));
          return resolve(newAppConfigPath);
        });
      });
      return p.then(function(newAppConfigPath) {
        var cyConfigPath;
        cyConfigPath = cwd(konfig("cy_path"));
        logger.info("copying .cy to tmp destination", {
          src: cyConfigPath,
          destination: newAppConfigPath
        });
        return fs.copyAsync(cyConfigPath, newAppConfigPath).then(function() {
          return chmodr(newAppConfigPath, 0x1ed);
        });
      });
    };

    Updater.prototype.runInstaller = function(newAppPath) {
      return this.copyCyDataTo(newAppPath).bind(this).then(function() {
        var args;
        args = this.getArgs();
        logger.info("running installer from tmp", {
          destination: newAppPath,
          args: args
        });
        this.getClient().runInstaller(newAppPath, args, {});
        return process.exit();
      });
    };

    Updater.prototype.unpack = function(destinationPath, manifest) {
      var fn;
      logger.info("unpacking new version", {
        destination: destinationPath
      });
      this.trigger("apply");
      fn = (function(_this) {
        return function(err, newAppPath) {
          if (err) {
            return _this.trigger("error", err);
          }
          if (_this.cancelled) {
            return;
          }
          return _this.runInstaller(newAppPath);
        };
      })(this);
      return this.getClient().unpack(destinationPath, fn, manifest);
    };

    Updater.prototype.download = function(manifest) {
      var fn;
      logger.info("downloading new version", {
        version: manifest.version
      });
      this.trigger("download", manifest.version);
      fn = (function(_this) {
        return function(err, destinationPath) {
          if (err) {
            return _this.trigger("error", err);
          }
          return setTimeout(function() {
            if (_this.cancelled) {
              return;
            }
            return _this.unpack(destinationPath, manifest);
          }, 1000);
        };
      })(this);
      return this.request = this.getClient().download(fn, manifest);
    };

    Updater.prototype.cancel = function() {
      this.cancelled = true;
      try {
        return this.request.abort();
      } catch (undefined) {}
    };

    Updater.prototype.trigger = function() {
      var args, cb, event;
      event = arguments[0], args = 2 <= arguments.length ? slice.call(arguments, 1) : [];
      event = "on" + event[0].toUpperCase() + event.slice(1);
      if (cb = this.callbacks && this.callbacks[event]) {
        return cb.apply(this, args);
      }
    };

    Updater.prototype.check = function(options) {
      if (options == null) {
        options = {};
      }
      logger.info("checking for new version");
      return this.getClient().checkNewVersion((function(_this) {
        return function(err, newVersionExists, manifest) {
          if (err) {
            return _this.trigger("error", err);
          }
          if (newVersionExists) {
            logger.info("new version exists", {
              version: manifest.version
            });
            return typeof options.onNewVersion === "function" ? options.onNewVersion(manifest) : void 0;
          } else {
            logger.info("new version does not exist");
            return typeof options.onNoNewVersion === "function" ? options.onNoNewVersion() : void 0;
          }
        };
      })(this));
    };

    Updater.prototype.run = function() {
      this.trigger("start");
      this.check({
        onNewVersion: (function(_this) {
          return function(manifest) {
            return _this.download(manifest);
          };
        })(this),
        onNoNewVersion: (function(_this) {
          return function() {
            return _this.trigger("none");
          };
        })(this)
      });
      return this;
    };

    Updater.setCoords = function(c) {
      return coords = c;
    };

    Updater.install = function(options) {
      return Updater().install(options);
    };

    Updater.check = function(options) {
      if (options == null) {
        options = {};
      }
      return Updater().check(options);
    };

    Updater.run = function(callbacks) {
      if (callbacks == null) {
        callbacks = {};
      }
      return Updater(callbacks).run();
    };

    return Updater;

  })();

  module.exports = Updater;

}).call(this);

});
require.register("./lib/user.js",function (module, exports, require) {(function() {
  var api, cache, errors;

  api = require("./api");

  cache = require("./cache");

  errors = require("./errors");

  module.exports = {
    get: function() {
      return cache.getUser();
    },
    set: function(user) {
      return cache.setUser(user);
    },
    getLoginUrl: function() {
      return api.getLoginUrl();
    },
    logIn: function(code) {
      return api.createSignin(code).then((function(_this) {
        return function(user) {
          return _this.set(user)["return"](user);
        };
      })(this));
    },
    logOut: function() {
      var remove;
      remove = function() {
        return cache.removeUser();
      };
      return this.get().then(function(user) {
        var session;
        session = user && user.session_token;
        if (session) {
          return api.createSignout(session).then(remove);
        } else {
          return remove();
        }
      });
    },
    ensureSession: function() {
      return this.get().then(function(user) {
        var st;
        if (user && (st = user.session_token)) {
          return st;
        } else {
          return errors["throw"]("NOT_LOGGED_IN");
        }
      });
    }
  };

}).call(this);

});
require.register("./lib/util/args.js",function (module, exports, require) {(function() {
  var _, anyUnderscoredValuePairs, backup, coerce, config, cwd, minimist, parseCoords, parseNestedValues, path, whitelist,
    slice = [].slice;

  _ = require("lodash");

  path = require("path");

  minimist = require("minimist");

  coerce = require("./coerce");

  config = require("../config");

  cwd = require("../cwd");

  whitelist = "appPath execPath apiKey smokeTest getKey generateKey runProject project spec ci updating ping coords key logs clearLogs returnPkg version mode autoOpen removeIds showHeadlessGui config".split(" ");

  whitelist = whitelist.concat(config.getConfigKeys());

  parseCoords = function(coords) {
    var ref, x, y;
    ref = _.map(coords.split("x"), parseFloat), x = ref[0], y = ref[1];
    return {
      x: x,
      y: y
    };
  };

  parseNestedValues = function(vals) {
    return _(vals.split(",")).map(function(pair) {
      return pair.split("=");
    }).object().mapValues(coerce).value();
  };

  backup = function(key, options) {
    return options["_" + key] = options[key];
  };

  anyUnderscoredValuePairs = function(val, key, obj) {
    var v;
    if (v = obj["_" + key]) {
      return v;
    }
    return val;
  };

  module.exports = {
    toObject: function(argv) {
      var c, envs, options, p, ref, rp;
      options = minimist(argv, {
        alias: {
          "app-path": "appPath",
          "exec-path": "execPath",
          "api-key": "apiKey",
          "smoke-test": "smokeTest",
          "remove-ids": "removeIds",
          "get-key": "getKey",
          "new-key": "generateKey",
          "run-project": "runProject",
          "clear-logs": "clearLogs",
          "return-pkg": "returnPkg",
          "auto-open": "autoOpen",
          "env": "environmentVariables",
          "show-headless-gui": "showHeadlessGui"
        }
      });
      _.extend(options, _.pick.apply(_, [argv].concat(slice.call(whitelist))), {
        env: process.env["CYPRESS_ENV"]
      });
      if (options.updating && !options.appPath) {
        ref = options._.slice(-2), options.appPath = ref[0], options.execPath = ref[1];
      }
      if (options.coords) {
        backup("coords", options);
        options.coords = parseCoords(options.coords);
      }
      if (envs = options.environmentVariables) {
        backup("environmentVariables", options);
        options.environmentVariables = parseNestedValues(envs);
      }
      if (c = options.config) {
        backup("config", options);
        c = parseNestedValues(c);
        options.config = c;
        _.extend(options, config.whitelist(c));
      }
      if (rp = options.runProject || (p = options.project)) {
        options.projectPath = path.resolve(cwd(), rp != null ? rp : p);
      }
      if (options.smokeTest) {
        options.pong = options.ping;
      }
      return options;
    },
    toArray: function(obj) {
      var ref;
      if (obj == null) {
        obj = {};
      }
      return (ref = _.chain(obj).mapValues(anyUnderscoredValuePairs)).pick.apply(ref, whitelist).mapValues(function(val, key) {
        return "--" + key + "=" + val;
      }).values().value();
    }
  };

}).call(this);

});
require.register("./lib/util/cache_buster.js",function (module, exports, require) {(function() {
  var DIGITS, SEPERATOR, _;

  _ = require('lodash');

  DIGITS = 3;

  SEPERATOR = "-";

  module.exports = {
    get: function() {
      return SEPERATOR + Math.random().toFixed(DIGITS).slice(2, 5);
    },
    strip: function(str) {
      if (this._hasCacheBuster(str)) {
        return str.slice(0, -4);
      } else {
        return str;
      }
    },
    _hasCacheBuster: function(str) {
      return str.split("").slice(-4, -3).join("") === SEPERATOR;
    }
  };

}).call(this);

});
require.register("./lib/util/coerce.js",function (module, exports, require) {(function() {
  var str;

  str = require("underscore.string");

  module.exports = function(value) {
    var ref, ref1;
    switch (false) {
      case ((ref = str.toNumber(value)) != null ? ref.toString() : void 0) !== value:
        return str.toNumber(value);
      case ((ref1 = str.toBoolean(value)) != null ? ref1.toString() : void 0) !== value:
        return str.toBoolean(value);
      default:
        return value;
    }
  };

}).call(this);

});
require.register("./lib/util/escape_regexp.js",function (module, exports, require) {(function() {
  var reSymbols;

  reSymbols = /[-\/\\^$*+?.()|[\]{}]/g;

  module.exports = function(str) {
    return str.replace(reSymbols, '\\$&');
  };

}).call(this);

});
require.register("./lib/util/http_overrides.js",function (module, exports, require) {(function() {
  var Promise, addRequest, cache, dns, getCachedFamily, http, net, setCache;

  net = require("net");

  dns = require("dns");

  http = require("http");

  Promise = require("bluebird");

  cache = {};

  addRequest = http.Agent.prototype.addRequest;

  setCache = function(options, family) {
    return cache[options.host + ":" + options.port] = family;
  };

  getCachedFamily = function(options) {
    return cache[options.host + ":" + options.port];
  };

  http.Agent.prototype.addRequest = function(req, options) {
    var agent, family, makeRequest;
    agent = this;
    makeRequest = function() {
      return addRequest.call(agent, req, options);
    };
    if (family = getCachedFamily(options)) {
      options.family = family;
      return makeRequest();
    }
    return dns.lookup(options.host, {
      all: true
    }, function(err, addresses) {
      var connect;
      if (err) {
        return makeRequest();
      }
      connect = function(address) {
        return new Promise(function(resolve, reject) {
          var client;
          client = net.connect(options.port, address.address);
          client.on("connect", function() {
            client.end();
            return resolve(address);
          });
          return client.on("error", reject);
        });
      };
      return Promise["try"](function() {
        return addresses.map(connect);
      }).any().then(function(address) {
        setCache(options, address.family);
        return options.family = address.family;
      }).then(makeRequest)["catch"](makeRequest);
    });
  };

}).call(this);

});
require.register("./lib/util/open.js",function (module, exports, require) {(function() {
  var opn;

  opn = require("opn");

  module.exports = {
    opn: opn
  };

}).call(this);

});
require.register("./lib/util/path_helpers.js",function (module, exports, require) {(function() {
  var isIntegrationTestRe, isUnitTestRe, path;

  path = require("path");

  isIntegrationTestRe = /^integration/;

  isUnitTestRe = /^unit/;

  module.exports = {
    getAbsolutePathToSpec: function(spec, config) {
      switch (false) {
        case !isIntegrationTestRe.test(spec):
          spec = path.relative("integration", spec);
          return spec = path.join(config.integrationFolder, spec);
        default:
          return spec;
      }
    }
  };

}).call(this);

});
require.register("./lib/util/provider.js",function (module, exports, require) {(function() {
  var _, getProviderKey, isCodeship, isGitlab, isWercker, providers;

  _ = require("lodash");

  isCodeship = function() {
    return process.env.CI_NAME && process.env.CI_NAME === "codeship";
  };

  isGitlab = function() {
    return process.env.GITLAB_CI || process.env.CI_SERVER_NAME && process.env.CI_SERVER_NAME === "GitLab CI";
  };

  isWercker = function() {
    return process.env.WERCKER || process.env.WERCKER_MAIN_PIPELINE_STARTED;
  };

  providers = {
    "appveyor": "APPVEYOR",
    "bamboo": "bamboo_planKey",
    "buildkite": "BUILDKITE",
    "circle": "CIRCLECI",
    "codeship": isCodeship,
    "drone": "DRONE",
    "gitlab": isGitlab,
    "hudson": "HUDSON_URL",
    "jenkins": "JENKINS_URL",
    "semaphore": "SEMAPHORE",
    "shippable": "SHIPPABLE",
    "snap": "SNAP_CI",
    "teamcity": "TEAMCITY_VERSION",
    "teamfoundation": "TF_BUILD",
    "travis": "TRAVIS",
    "wercker": isWercker
  };

  getProviderKey = function() {
    return _.findKey(providers, function(value, key) {
      switch (false) {
        case !_.isString(value):
          return process.env[value];
        case !_.isFunction(value):
          return value();
      }
    });
  };

  module.exports = {
    get: function() {
      var ref;
      return (ref = getProviderKey()) != null ? ref : "unknown";
    }
  };

}).call(this);

});
require.register("./lib/util/routes.js",function (module, exports, require) {(function() {
  var Routes, Uri, _, addQueryParams, api_url, konfig, parseArgs, routes,
    slice = [].slice;

  _ = require("lodash");

  Uri = require("jsuri");

  konfig = require("../konfig");

  api_url = konfig("api_url");

  routes = {
    api: "",
    auth: "v1/auth",
    ping: "ping",
    token: "token",
    signin: "signin",
    signout: "signout",
    ci: "ci/:id",
    tests: "tests/:id",
    projects: "projects",
    project: "projects/:id",
    projectCi: "projects/:id/ci",
    projectKeys: "projects/:id/keys",
    projectToken: "projects/:id/token",
    exceptions: "exceptions"
  };

  addQueryParams = function(url, params) {
    return _.reduce(params, function(memo, value, key) {
      memo.addQueryParam(key, value);
      return memo;
    }, url);
  };

  parseArgs = function(url, args) {
    if (args == null) {
      args = [];
    }
    _.each(args, function(value) {
      switch (false) {
        case !_.isObject(value):
          return addQueryParams(url, value);
        case !_.isString(value):
          return url.setPath(url.path().replace(":id", value));
      }
    });
    return url;
  };

  Routes = _.reduce(routes, function(memo, value, key) {
    memo[key] = function() {
      var args, url;
      args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
      url = new Uri(api_url).setPath(value);
      if (args.length) {
        url = parseArgs(url, args);
      }
      return url.toString();
    };
    return memo;
  }, {});

  module.exports = Routes;

}).call(this);

});
require.register("./lib/util/settings.js",function (module, exports, require) {(function() {
  var Promise, _, errors, flattenCypress, fs, path, renameVisitToPageLoad;

  _ = require("lodash");

  Promise = require("bluebird");

  path = require("path");

  fs = require("fs-extra");

  errors = require("../errors");

  fs = Promise.promisifyAll(fs);

  flattenCypress = function(obj) {
    var cypress;
    if (cypress = obj.cypress) {
      return cypress;
    }
  };

  renameVisitToPageLoad = function(obj) {
    var v;
    if (v = obj.visitTimeout) {
      obj = _.omit(obj, "visitTimeout");
      obj.pageLoadTimeout = v;
      return obj;
    }
  };

  module.exports = {
    _pathToFile: function(projectRoot, file) {
      return path.join(projectRoot, file);
    },
    _err: function(type, file, err) {
      var e;
      e = errors.get(type, file, err);
      e.code = err.code;
      e.errno = err.errno;
      throw e;
    },
    _logReadErr: function(file, err) {
      return this._err("ERROR_READING_FILE", file, err);
    },
    _logWriteErr: function(file, err) {
      return this._err("ERROR_WRITING_FILE", file, err);
    },
    _write: function(file, obj) {
      if (obj == null) {
        obj = {};
      }
      return fs.writeJsonAsync(file, obj, {
        spaces: 2
      })["return"](obj)["catch"]((function(_this) {
        return function(err) {
          return _this._logWriteErr(file, err);
        };
      })(this));
    },
    _applyRewriteRules: function(obj) {
      if (obj == null) {
        obj = {};
      }
      return _.reduce([flattenCypress, renameVisitToPageLoad], function(memo, fn) {
        var ret;
        if (ret = fn(memo)) {
          return ret;
        } else {
          return memo;
        }
      }, obj);
    },
    read: function(projectRoot) {
      var file;
      file = this._pathToFile(projectRoot, "cypress.json");
      return fs.readJsonAsync(file)["catch"]({
        code: "ENOENT"
      }, (function(_this) {
        return function() {
          return _this._write(file, {});
        };
      })(this)).then((function(_this) {
        return function(json) {
          var changed;
          if (json == null) {
            json = {};
          }
          changed = _this._applyRewriteRules(json);
          if (_.isEqual(json, changed)) {
            return json;
          } else {
            return _this._write(file, changed);
          }
        };
      })(this))["catch"]((function(_this) {
        return function(err) {
          if (errors.isCypressErr(err)) {
            throw err;
          }
          return _this._logReadErr(file, err);
        };
      })(this));
    },
    readEnv: function(projectRoot) {
      var file;
      file = this._pathToFile(projectRoot, "cypress.env.json");
      return fs.readJsonAsync(file)["catch"]({
        code: "ENOENT"
      }, function() {
        return {};
      })["catch"]((function(_this) {
        return function(err) {
          if (errors.isCypressErr(err)) {
            throw err;
          }
          return _this._logReadErr(file, err);
        };
      })(this));
    },
    write: function(projectRoot, obj) {
      if (obj == null) {
        obj = {};
      }
      return this.read(projectRoot).then((function(_this) {
        return function(settings) {
          var file;
          _.extend(settings, obj);
          file = _this._pathToFile(projectRoot, "cypress.json");
          return _this._write(file, settings);
        };
      })(this));
    },
    remove: function(projectRoot) {
      return fs.unlinkSync(this._pathToFile(projectRoot, "cypress.json"));
    },
    pathToCypressJson: function(projectRoot) {
      return this._pathToFile(projectRoot, "cypress.json");
    }
  };

}).call(this);

});
require.register("./lib/util/url_helpers.js",function (module, exports, require) {(function() {
  var Url, _, fileRe, httpRe, jsUri;

  _ = require('lodash');

  Url = require('url');

  jsUri = require("jsuri");

  httpRe = /:\/\//;

  fileRe = /^file:\/\//;

  module.exports = {
    isFile: function(url) {
      return fileRe.test(url);
    },
    isAbsolute: function(url) {
      return httpRe.test(url) && !this.isFile(url);
    },
    isRelative: function(url) {
      return !this.isAbsolute(url) && !this.isFile(url);
    },
    detectScheme: function(url) {
      if (url == null) {
        url = "";
      }
      switch (false) {
        case !this.isFile(url):
          return "file";
        case !this.isAbsolute(url):
          return "absolute";
        case !this.isRelative(url):
          return "relative";
        default:
          throw new Error("Url: " + url + " did not match 'absolute', 'relative', or 'file' scheme.");
      }
    },
    mergeOrigin: function(origin, redirect) {
      var originUrl, redirectUrl;
      originUrl = Url.parse(origin);
      redirectUrl = Url.parse(redirect);
      _.each(_.pick(redirectUrl, "protocol", "auth", "hostname", "port", "pathname"), function(value, key) {
        if (value == null) {
          return redirectUrl[key] = originUrl[key];
        }
      });
      return redirectUrl.format();
    },
    merge: function(origin, redirect) {
      var originUrl, redirectUrl;
      originUrl = Url.parse(origin, true);
      redirectUrl = Url.parse(redirect, true);
      _.each(redirectUrl, function(value, key) {
        if (value == null) {
          return redirectUrl[key] = originUrl[key];
        }
      });
      return redirectUrl.format();
    },
    replaceHost: function(original, remoteHost) {
      original = new jsUri(original);
      remoteHost = new jsUri(remoteHost);
      original.setProtocol(remoteHost.protocol());
      original.setHost(remoteHost.host());
      original.setPort(remoteHost.port());
      return original.toString();
    },
    getOriginFromFqdnUrl: function(url) {
      url = Url.parse(url.slice(1));
      if (url.protocol && url.host) {
        url.pathname = "";
        url.search = "";
        url.hash = "";
        return url.format();
      }
    }
  };

}).call(this);

});
require.register("./lib/watchers.js",function (module, exports, require) {(function() {
  var Promise, Watchers, _, chokidar;

  _ = require("lodash");

  Promise = require("bluebird");

  chokidar = require("chokidar");

  Watchers = (function() {
    function Watchers() {
      if (!(this instanceof Watchers)) {
        return new Watchers;
      }
      this.watched = {};
    }

    Watchers.prototype.remove = function(key) {
      var watched;
      if (!(watched = this.watched[key])) {
        return;
      }
      watched.close();
      return delete this.watched[key];
    };

    Watchers.prototype._add = function(pathToFile, watched) {
      this.remove(pathToFile);
      return this.watched[pathToFile] = watched;
    };

    Watchers.prototype.close = function() {
      var key, ref, results, val;
      ref = this.watched;
      results = [];
      for (key in ref) {
        val = ref[key];
        results.push(this.remove(key));
      }
      return results;
    };

    Watchers.prototype.watchAsync = function(pathToFile, options) {
      var _this;
      if (options == null) {
        options = {};
      }
      _this = this;
      return new Promise((function(_this) {
        return function(resolve, reject) {
          options.onReady = function() {
            return resolve();
          };
          return _this.watch(pathToFile, options);
        };
      })(this));
    };

    Watchers.prototype.watch = function(pathToFile, options) {
      var w;
      if (options == null) {
        options = {};
      }
      _.defaults(options, {
        interval: 250,
        usePolling: true,
        useFsEvents: false,
        ignored: null,
        onChange: null,
        onReady: null,
        onError: null
      });
      w = chokidar.watch(pathToFile, options);
      this._add(pathToFile, w);
      if (_.isFunction(options.onChange)) {
        w.on("change", options.onChange);
      }
      if (_.isFunction(options.onReady)) {
        w.on("ready", options.onReady);
      }
      if (_.isFunction(options.onError)) {
        w.on("error", options.onError);
      }
      return this;
    };

    return Watchers;

  })();

  module.exports = Watchers;

}).call(this);

});
this_module.exports = require("./index.js");
}(require, module));