'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
// all errors that the command does not handle comes to this switch statement
// if you handle the error, then return true


var _chalk;

function _load_chalk() {
  return _chalk = _interopRequireDefault(require('chalk'));
}

var _exceptions;

function _load_exceptions() {
  return _exceptions = require('../bit-id/exceptions');
}

var _exceptions2;

function _load_exceptions2() {
  return _exceptions2 = require('../consumer/exceptions');
}

var _driver;

function _load_driver() {
  return _driver = require('../driver');
}

var _componentNotFoundInPath;

function _load_componentNotFoundInPath() {
  return _componentNotFoundInPath = _interopRequireDefault(require('../consumer/component/exceptions/component-not-found-in-path'));
}

var _missingFilesFromComponent;

function _load_missingFilesFromComponent() {
  return _missingFilesFromComponent = _interopRequireDefault(require('../consumer/component/exceptions/missing-files-from-component'));
}

var _pluginNotFound;

function _load_pluginNotFound() {
  return _pluginNotFound = _interopRequireDefault(require('../consumer/component/exceptions/plugin-not-found'));
}

var _permissionDenied;

function _load_permissionDenied() {
  return _permissionDenied = _interopRequireDefault(require('../scope/network/exceptions/permission-denied'));
}

var _exceptions3;

function _load_exceptions3() {
  return _exceptions3 = require('../scope/network/exceptions');
}

var _remoteNotFound;

function _load_remoteNotFound() {
  return _remoteNotFound = _interopRequireDefault(require('../remotes/exceptions/remote-not-found'));
}

var _exceptions4;

function _load_exceptions4() {
  return _exceptions4 = require('../scope/exceptions');
}

var _invalidBitJson;

function _load_invalidBitJson() {
  return _invalidBitJson = _interopRequireDefault(require('../consumer/bit-json/exceptions/invalid-bit-json'));
}

var _invalidVersion;

function _load_invalidVersion() {
  return _invalidVersion = _interopRequireDefault(require('../api/consumer/lib/exceptions/invalid-version'));
}

var _nothingToCompareTo;

function _load_nothingToCompareTo() {
  return _nothingToCompareTo = _interopRequireDefault(require('../api/consumer/lib/exceptions/nothing-to-compare-to'));
}

var _promptCanceled;

function _load_promptCanceled() {
  return _promptCanceled = _interopRequireDefault(require('../prompts/exceptions/prompt-canceled'));
}

var _idExportedAlready;

function _load_idExportedAlready() {
  return _idExportedAlready = _interopRequireDefault(require('../api/consumer/lib/exceptions/id-exported-already'));
}

var _fileSourceNotFound;

function _load_fileSourceNotFound() {
  return _fileSourceNotFound = _interopRequireDefault(require('../consumer/component/exceptions/file-source-not-found'));
}

var _exceptions5;

function _load_exceptions5() {
  return _exceptions5 = require('../consumer/bit-map/exceptions');
}

var _logger;

function _load_logger() {
  return _logger = _interopRequireDefault(require('../logger/logger'));
}

var _remoteUndefined;

function _load_remoteUndefined() {
  return _remoteUndefined = _interopRequireDefault(require('./commands/exceptions/remote-undefined'));
}

var _addTestsWithoutId;

function _load_addTestsWithoutId() {
  return _addTestsWithoutId = _interopRequireDefault(require('./commands/exceptions/add-tests-without-id'));
}

var _missingDependenciesTemplate;

function _load_missingDependenciesTemplate() {
  return _missingDependenciesTemplate = _interopRequireDefault(require('./templates/missing-dependencies-template'));
}

var _newerVersionTemplate;

function _load_newerVersionTemplate() {
  return _newerVersionTemplate = _interopRequireDefault(require('./templates/newer-version-template'));
}

var _exceptions6;

function _load_exceptions6() {
  return _exceptions6 = require('../consumer/component-ops/add-components/exceptions');
}

var _analytics;

function _load_analytics() {
  return _analytics = require('../analytics/analytics');
}

var _externalTestError;

function _load_externalTestError() {
  return _externalTestError = _interopRequireDefault(require('../consumer/component/exceptions/external-test-error'));
}

var _externalBuildError;

function _load_externalBuildError() {
  return _externalBuildError = _interopRequireDefault(require('../consumer/component/exceptions/external-build-error'));
}

var _invalidCompilerInterface;

function _load_invalidCompilerInterface() {
  return _invalidCompilerInterface = _interopRequireDefault(require('../consumer/component/exceptions/invalid-compiler-interface'));
}

var _extensionFileNotFound;

function _load_extensionFileNotFound() {
  return _extensionFileNotFound = _interopRequireDefault(require('../extensions/exceptions/extension-file-not-found'));
}

var _extensionNameNotValid;

function _load_extensionNameNotValid() {
  return _extensionNameNotValid = _interopRequireDefault(require('../extensions/exceptions/extension-name-not-valid'));
}

var _generalError;

function _load_generalError() {
  return _generalError = _interopRequireDefault(require('../error/general-error'));
}

var _validationError;

function _load_validationError() {
  return _validationError = _interopRequireDefault(require('../error/validation-error'));
}

var _abstractError;

function _load_abstractError() {
  return _abstractError = _interopRequireDefault(require('../error/abstract-error'));
}

var _exceptions7;

function _load_exceptions7() {
  return _exceptions7 = require('../consumer/login/exceptions');
}

var _extensionLoadError;

function _load_extensionLoadError() {
  return _extensionLoadError = _interopRequireDefault(require('../extensions/exceptions/extension-load-error'));
}

var _extensionGetDynamicPackagesError;

function _load_extensionGetDynamicPackagesError() {
  return _extensionGetDynamicPackagesError = _interopRequireDefault(require('../extensions/exceptions/extension-get-dynamic-packages-error'));
}

var _extensionInitError;

function _load_extensionInitError() {
  return _extensionInitError = _interopRequireDefault(require('../extensions/exceptions/extension-init-error'));
}

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var errorsMap = [[(_remoteUndefined || _load_remoteUndefined()).default, function () {
  return (_chalk || _load_chalk()).default.red('error: remote url must be defined. please use: `ssh://`, `file://` or `bit://` protocols to define remote access');
}], [(_addTestsWithoutId || _load_addTestsWithoutId()).default, function () {
  return (_chalk || _load_chalk()).default.yellow(`please specify a component ID to add test files to an existing component. \n${(_chalk || _load_chalk()).default.bold('example: bit add --tests [test_file_path] --id [component_id]')}`);
}], [(_exceptions2 || _load_exceptions2()).ConsumerAlreadyExists, function () {
  return 'workspace already exists';
}], [(_generalError || _load_generalError()).default, function (err) {
  return `${err.msg}`;
}], [(_exceptions4 || _load_exceptions4()).VersionAlreadyExists, function (err) {
  return `error: version ${err.version} already exists for ${err.componentId}`;
}], [(_exceptions2 || _load_exceptions2()).ConsumerNotFound, function () {
  return 'workspace not found. to initiate a new workspace, please use `bit init`';
}], [(_exceptions2 || _load_exceptions2()).LoginFailed, function () {
  return 'error: there was a problem with web authentication';
}],

// [
//   PluginNotFound,
//   err => `error: The compiler "${err.plugin}" is not installed, please use "bit install ${err.plugin}" to install it.`
// ],
[(_fileSourceNotFound || _load_fileSourceNotFound()).default, function (err) {
  return `file or directory "${err.path}" was not found`;
}], [(_extensionFileNotFound || _load_extensionFileNotFound()).default, function (err) {
  return `file "${err.path}" was not found`;
}], [(_extensionNameNotValid || _load_extensionNameNotValid()).default, function (err) {
  return `error: the extension name "${err.name}" is not a valid component id (it must contain a scope name) fix it on your bit.json file`;
}], [(_exceptions3 || _load_exceptions3()).ProtocolNotSupported, function () {
  return 'error: remote scope protocol is not supported, please use: `ssh://`, `file://` or `bit://`';
}], [(_exceptions3 || _load_exceptions3()).RemoteScopeNotFound, function (err) {
  return `error: remote scope "${(_chalk || _load_chalk()).default.bold(err.name)}" was not found.`;
}], [(_exceptions || _load_exceptions()).InvalidBitId, function () {
  return 'error: component ID is invalid, please use the following format: [scope]/[namespace]/<name>';
}], [(_exceptions4 || _load_exceptions4()).ComponentNotFound, function (err) {
  var msg = err.dependentId ? `error: the component dependency "${(_chalk || _load_chalk()).default.bold(err.id)}" required by "${(_chalk || _load_chalk()).default.bold(err.dependentId)}" was not found` : `error: component "${(_chalk || _load_chalk()).default.bold(err.id)}" was not found`;
  return msg;
}], [(_exceptions4 || _load_exceptions4()).CorruptedComponent, function (err) {
  return `error: the model representation of "${(_chalk || _load_chalk()).default.bold(err.id)}" is corrupted, the object of version ${err.version} is missing. please report this issue on Github https://github.com/teambit/bit/issues`;
}], [(_exceptions4 || _load_exceptions4()).DependencyNotFound, function (err) {
  return `error: dependency "${(_chalk || _load_chalk()).default.bold(err.id)}" was not found. please track this component or use --ignore-missing-dependencies flag (not recommended)`;
}], [(_exceptions6 || _load_exceptions6()).EmptyDirectory, function () {
  return (_chalk || _load_chalk()).default.yellow('directory is empty, no files to add');
}], [(_validationError || _load_validationError()).default, function (err) {
  return `${err.message}\nThis error should have never happened. Please open a new Github issue with the bug details`;
}], [(_componentNotFoundInPath || _load_componentNotFoundInPath()).default, function (err) {
  return `error: component in path "${(_chalk || _load_chalk()).default.bold(err.path)}" was not found`;
}], [(_permissionDenied || _load_permissionDenied()).default, function (err) {
  return `error: permission to scope ${err.scope} was denied\nsee troubleshooting at https://docs.bitsrc.io/docs/authentication-issues.html`;
}], [(_remoteNotFound || _load_remoteNotFound()).default, function (err) {
  return `error: remote "${(_chalk || _load_chalk()).default.bold(err.name)}" was not found`;
}], [(_exceptions3 || _load_exceptions3()).NetworkError, function (err) {
  return `error: remote failed with error the following error:\n "${(_chalk || _load_chalk()).default.bold(err.remoteErr)}"`;
}], [(_exceptions4 || _load_exceptions4()).HashMismatch, function (err) {
  return `found hash mismatch of ${(_chalk || _load_chalk()).default.bold(err.id)}, version ${(_chalk || _load_chalk()).default.bold(err.version)}.
  originalHash: ${(_chalk || _load_chalk()).default.bold(err.originalHash)}.
  currentHash: ${(_chalk || _load_chalk()).default.bold(err.currentHash)}
  this usually happens when a component is old and the migration script was not running or interrupted`;
}], [(_exceptions4 || _load_exceptions4()).MergeConflict, function (err) {
  return `error: merge conflict occurred while importing the component ${err.id}. conflict version(s): ${err.versions.join(', ')}
to resolve it and merge your local and remote changes, please do the following:
1) bit untag ${err.id} ${err.versions.join(' ')}
2) bit import ${err.id} --merge
once your changes are merged with the new remote version, you can tag and export a new version of the component to the remote scope.`;
}], [(_exceptions4 || _load_exceptions4()).MergeConflictOnRemote, function (err) {
  return `error: merge conflict occurred when exporting the component(s) ${err.idsAndVersions.map(function (i) {
    return `${(_chalk || _load_chalk()).default.bold(i.id)} (version(s): ${i.versions.join(', ')})`;
  }).join(', ')} to the remote scope.
to resolve this conflict and merge your remote and local changes, please do the following:
1) bit untag [id] [version]
2) bit import --merge
once your changes are merged with the new remote version, please tag and export a new version of the component to the remote scope.`;
}], [(_exceptions4 || _load_exceptions4()).CyclicDependencies, function (err) {
  return `${err.msg.toString().toLocaleLowerCase()}`;
}], [(_exceptions3 || _load_exceptions3()).UnexpectedNetworkError, function (err) {
  return `error: unexpected network error has occurred. ${err.message ? ` original message: ${err.message}` : ''}`;
}], [(_exceptions3 || _load_exceptions3()).SSHInvalidResponse, function () {
  return 'error: received an invalid response from the remote SSH server';
}], [(_exceptions4 || _load_exceptions4()).ScopeNotFound, function () {
  return 'error: workspace not found. to create a new workspace, please use `bit init`';
}], [(_exceptions4 || _load_exceptions4()).ScopeJsonNotFound, function (err) {
  return `error: scope.json file was not found at ${(_chalk || _load_chalk()).default.bold(err.path)}, please use ${(_chalk || _load_chalk()).default.bold('bit init')} to recreate the file`;
}], [(_exceptions2 || _load_exceptions2()).ComponentSpecsFailed, function (err) {
  return `${err.specsResultsAndIdPretty}component's tests has failed, please fix them before tagging`;
}], [(_exceptions2 || _load_exceptions2()).MissingDependencies, function (err) {
  var missingDepsColored = (0, (_missingDependenciesTemplate || _load_missingDependenciesTemplate()).default)(err.components);
  return `error: issues found with the following component dependencies\n${missingDepsColored}`;
}], [(_exceptions2 || _load_exceptions2()).NothingToImport, function () {
  return (_chalk || _load_chalk()).default.yellow('nothing to import. please use `bit import [component_id]` or configure your dependencies in bit.json');
}], [(_exceptions || _load_exceptions()).InvalidIdChunk, function (err) {
  return `error: "${(_chalk || _load_chalk()).default.bold(err.id)}" is invalid, component IDs can only contain alphanumeric, lowercase characters, and the following ["-", "_", "$", "!"]`;
}], [(_invalidBitJson || _load_invalidBitJson()).default, function (err) {
  return `error: invalid bit.json: ${(_chalk || _load_chalk()).default.bold(err.path)} is not a valid JSON file.
    consider running ${(_chalk || _load_chalk()).default.bold('bit init --reset')} to recreate the file`;
}], [(_driver || _load_driver()).DriverNotFound, function (err) {
  return `error: a client-driver ${(_chalk || _load_chalk()).default.bold(err.driver)} is missing for the language ${(_chalk || _load_chalk()).default.bold(err.lang)} set in your bit.json file.`;
}], [(_exceptions5 || _load_exceptions5()).MissingMainFile, function (err) {
  return 'error: one or more of the added components does not contain a main file.\nplease either use --id to group all added files as one component or use our DSL to define the main file dynamically.\nsee troubleshooting at https://docs.bitsrc.io/docs/isolating-and-tracking-components.html#define-a-components-main-file';
}], [(_exceptions5 || _load_exceptions5()).InvalidBitMap, function (err) {
  return `error: unable to parse your bitMap file at ${(_chalk || _load_chalk()).default.bold(err.path)}, due to an error ${(_chalk || _load_chalk()).default.bold(err.errorMessage)}.
      consider running ${(_chalk || _load_chalk()).default.bold('bit init --reset')} to recreate the file`;
}], [(_exceptions6 || _load_exceptions6()).ExcludedMainFile, function (err) {
  return `error: main file ${(_chalk || _load_chalk()).default.bold(err.mainFile)} was excluded from file list`;
}], [(_exceptions6 || _load_exceptions6()).VersionShouldBeRemoved, function (err) {
  return `please remove the version part from the specified id ${(_chalk || _load_chalk()).default.bold(err.id)} and try again`;
}], [(_exceptions6 || _load_exceptions6()).TestIsDirectory, function (err) {
  return `error: the specified test path ${(_chalk || _load_chalk()).default.bold(err.path)} is a directory, please specify a file or a pattern DSL`;
}], [(_exceptions6 || _load_exceptions6()).MainFileIsDir, function (err) {
  return `error: the specified main path ${(_chalk || _load_chalk()).default.bold(err.mainFile)} is a directory, please specify a file or a pattern DSL`;
}], [(_missingFilesFromComponent || _load_missingFilesFromComponent()).default, function (err) {
  return `component ${err.id} is invalid as part or all of the component files were deleted. please use \'bit remove\' to resolve the issue`;
}], [(_exceptions5 || _load_exceptions5()).MissingBitMapComponent, function (err) {
  return `error: component "${(_chalk || _load_chalk()).default.bold(err.id)}" was not found on your local workspace.\nplease specify a valid component ID or track the component using 'bit add' (see 'bit add --help' for more information)`;
}], [(_exceptions6 || _load_exceptions6()).PathsNotExist, function (err) {
  return `error: file or directory "${(_chalk || _load_chalk()).default.bold(err.paths.join(', '))}" was not found.`;
}], [(_exceptions7 || _load_exceptions7()).WriteToNpmrcError, function (err) {
  return `unable to add @bit as a scoped registry at "${(_chalk || _load_chalk()).default.bold(err.path)}"`;
}], [(_exceptions7 || _load_exceptions7()).PathToNpmrcNotExist, function (err) {
  return `error: file or directory "${(_chalk || _load_chalk()).default.bold(err.path)}" was not found.`;
}], [(_exceptions4 || _load_exceptions4()).VersionNotFound, function (err) {
  return `error: version "${(_chalk || _load_chalk()).default.bold(err.version)}" was not found.`;
}], [(_exceptions6 || _load_exceptions6()).MissingComponentIdForImportedComponent, function (err) {
  return `error: unable to add new files to the component "${(_chalk || _load_chalk()).default.bold(err.id)}" without specifying a component ID. please define the component ID using the --id flag.`;
}], [(_exceptions6 || _load_exceptions6()).IncorrectIdForImportedComponent, function (err) {
  return `error: trying to add a file ${(_chalk || _load_chalk()).default.bold(err.filePath)} to a component-id "${(_chalk || _load_chalk()).default.bold(err.newId)}", however, this file already belong to "${(_chalk || _load_chalk()).default.bold(err.importedId)}"`;
}], [(_exceptions6 || _load_exceptions6()).NoFiles, function (err) {
  return (_chalk || _load_chalk()).default.yellow('warning: no files to add') + (_chalk || _load_chalk()).default.yellow(err.ignoredFiles ? `, the following files were ignored: ${(_chalk || _load_chalk()).default.bold(err.ignoredFiles)}` : '');
}], [(_exceptions6 || _load_exceptions6()).DuplicateIds, function (err) {
  return Object.keys(err.componentObject).map(function (key) {
    return `unable to add ${Object.keys(err.componentObject[key]).length} components with the same ID: ${(_chalk || _load_chalk()).default.bold(key)} : ${err.componentObject[key]}\n`;
  }).join(' ');
}], [(_idExportedAlready || _load_idExportedAlready()).default, function (err) {
  return `component ${(_chalk || _load_chalk()).default.bold(err.id)} has been already exported to ${(_chalk || _load_chalk()).default.bold(err.remote)}`;
}], [(_invalidVersion || _load_invalidVersion()).default, function (err) {
  return `error: version ${(_chalk || _load_chalk()).default.bold(err.version)} is not a valid semantic version. learn more: https://semver.org`;
}], [(_nothingToCompareTo || _load_nothingToCompareTo()).default, function (err) {
  return 'no previous versions to compare';
}], [(_exceptions2 || _load_exceptions2()).NewerVersionFound,
// err => JSON.stringify(err.newerVersions)
function (err) {
  return (0, (_newerVersionTemplate || _load_newerVersionTemplate()).default)(err.newerVersions);
}], [(_promptCanceled || _load_promptCanceled()).default, function (err) {
  return (_chalk || _load_chalk()).default.yellow('operation aborted');
}], [(_externalTestError || _load_externalTestError()).default, function (err) {
  return `error: bit failed to test ${err.id} with the following exception:\n${err.originalError.message}.\n${err.originalError.stack}`;
}], [(_externalBuildError || _load_externalBuildError()).default, function (err) {
  return `error: bit failed to build ${err.id} with the following exception:\n${err.originalError.message}.\n${err.originalError.stack}`;
}], [(_extensionLoadError || _load_extensionLoadError()).default, function (err) {
  return `error: bit failed to load ${err.name} with the following exception:\n${err.originalError.message}.\n${err.originalError.stack}`;
}], [(_extensionInitError || _load_extensionInitError()).default, function (err) {
  return `error: bit failed to initialized ${err.name} with the following exception:\n${err.originalError.message}.\n${err.originalError.stack}`;
}], [(_extensionGetDynamicPackagesError || _load_extensionGetDynamicPackagesError()).default, function (err) {
  return `error: bit failed to get the dynamic packages from ${err.name} with the following exception:\n${err.originalError.message}.\n${err.originalError.stack}`;
}], [(_invalidCompilerInterface || _load_invalidCompilerInterface()).default, function (err) {
  return `"${err.compilerName}" does not have a valid compiler interface, it has to expose a compile method`;
}], [(_exceptions4 || _load_exceptions4()).ResolutionException, function (err) {
  return `error: bit failed to require ${err.filePath} due to the following exception:\n${err.originalError.message}.\n${err.originalError.stack}`;
}], [(_exceptions3 || _load_exceptions3()).AuthenticationFailed, function (err) {
  return 'authentication failed. see troubleshooting at https://docs.bitsrc.io/docs/authentication-issues.html';
}]];

function formatUnhandled(err) {
  (_analytics || _load_analytics()).Analytics.setError((_analytics || _load_analytics()).LEVEL.FATAL, err);
  return (_chalk || _load_chalk()).default.red(err.message || err);
}

exports.default = function (err) {
  var error = errorsMap.find(function (_ref) {
    var _ref2 = _slicedToArray(_ref, 1),
        ErrorType = _ref2[0];

    return err instanceof ErrorType || err.name === ErrorType.name; // in some cases, such as forked process, the received err is serialized.
  });

  if (!error) return formatUnhandled(err);
  /* this is an error that bit knows how to handle dont send to sentry */

  if (err instanceof (_abstractError || _load_abstractError()).default) {
    (_analytics || _load_analytics()).Analytics.setError((_analytics || _load_analytics()).LEVEL.INFO, err.makeAnonymous());
  } else {
    (_analytics || _load_analytics()).Analytics.setError((_analytics || _load_analytics()).LEVEL.FATAL, err);
  }

  var _error = _slicedToArray(error, 2),
      func = _error[1];

  var errorMessage = func(err);
  err.message = errorMessage;
  (_logger || _load_logger()).default.error(`User gets the following error: ${errorMessage}`);
  return (_chalk || _load_chalk()).default.red(errorMessage);
};