'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 _hashErrorObject;

function _load_hashErrorObject() {
  return _hashErrorObject = _interopRequireDefault(require('../error/hash-error-object'));
}

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/config/exceptions/invalid-bit-json'));
}

var _invalidPackageJson;

function _load_invalidPackageJson() {
  return _invalidPackageJson = _interopRequireDefault(require('../consumer/config/exceptions/invalid-package-json'));
}

var _invalidVersion;

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

var _noIdMatchWildcard;

function _load_noIdMatchWildcard() {
  return _noIdMatchWildcard = _interopRequireDefault(require('../api/consumer/lib/exceptions/no-id-match-wildcard'));
}

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 _componentIssuesTemplate;

function _load_componentIssuesTemplate() {
  return _componentIssuesTemplate = _interopRequireDefault(require('./templates/component-issues-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 _externalTestErrors;

function _load_externalTestErrors() {
  return _externalTestErrors = _interopRequireDefault(require('../consumer/component/exceptions/external-test-errors'));
}

var _externalBuildErrors;

function _load_externalBuildErrors() {
  return _externalBuildErrors = _interopRequireDefault(require('../consumer/component/exceptions/external-build-errors'));
}

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 _extensionGetDynamicConfigError;

function _load_extensionGetDynamicConfigError() {
  return _extensionGetDynamicConfigError = _interopRequireDefault(require('../extensions/exceptions/extension-get-dynamic-config-error'));
}

var _extensionInitError;

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

var _mainFileRemoved;

function _load_mainFileRemoved() {
  return _mainFileRemoved = _interopRequireDefault(require('../consumer/component/exceptions/main-file-removed'));
}

var _invalidConfigDir;

function _load_invalidConfigDir() {
  return _invalidConfigDir = _interopRequireDefault(require('../consumer/bit-map/exceptions/invalid-config-dir'));
}

var _ejectToWorkspace;

function _load_ejectToWorkspace() {
  return _ejectToWorkspace = _interopRequireDefault(require('../consumer/component/exceptions/eject-to-workspace'));
}

var _ejectBoundToWorkspace;

function _load_ejectBoundToWorkspace() {
  return _ejectBoundToWorkspace = _interopRequireDefault(require('../consumer/component/exceptions/eject-bound-to-workspace'));
}

var _ejectNoDir;

function _load_ejectNoDir() {
  return _ejectNoDir = _interopRequireDefault(require('../consumer/component-ops/exceptions/eject-no-dir'));
}

var _constants;

function _load_constants() {
  return _constants = require('../constants');
}

var _injectNonEjected;

function _load_injectNonEjected() {
  return _injectNonEjected = _interopRequireDefault(require('../consumer/component/exceptions/inject-non-ejected'));
}

var _extensionSchemaError;

function _load_extensionSchemaError() {
  return _extensionSchemaError = _interopRequireDefault(require('../extensions/exceptions/extension-schema-error'));
}

var _gitNotFound;

function _load_gitNotFound() {
  return _gitNotFound = _interopRequireDefault(require('../utils/git/exceptions/git-not-found'));
}

var _objectsWithoutConsumer;

function _load_objectsWithoutConsumer() {
  return _objectsWithoutConsumer = _interopRequireDefault(require('../api/consumer/lib/exceptions/objects-without-consumer'));
}

var _invalidConfigPropPath;

function _load_invalidConfigPropPath() {
  return _invalidConfigPropPath = _interopRequireDefault(require('../consumer/config/exceptions/invalid-config-prop-path'));
}

var _diagnosisNotFound;

function _load_diagnosisNotFound() {
  return _diagnosisNotFound = _interopRequireDefault(require('../api/consumer/lib/exceptions/diagnosis-not-found'));
}

var _missingDiagnosisName;

function _load_missingDiagnosisName() {
  return _missingDiagnosisName = _interopRequireDefault(require('../api/consumer/lib/exceptions/missing-diagnosis-name'));
}

var _remoteResolverError;

function _load_remoteResolverError() {
  return _remoteResolverError = _interopRequireDefault(require('../scope/network/exceptions/remote-resolver-error'));
}

var _exportAnotherOwnerPrivate;

function _load_exportAnotherOwnerPrivate() {
  return _exportAnotherOwnerPrivate = _interopRequireDefault(require('../scope/network/exceptions/export-another-owner-private'));
}

var _componentsPendingImport;

function _load_componentsPendingImport() {
  return _componentsPendingImport = _interopRequireDefault(require('../consumer/component-ops/exceptions/components-pending-import'));
}

var _statusCmd;

function _load_statusCmd() {
  return _statusCmd = require('./commands/public-cmds/status-cmd');
}

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

var reportIssueToGithubMsg = 'This error should have never happened. Please report this issue on Github https://github.com/teambit/bit/issues';

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]/<name>';
}], [(_invalidConfigDir || _load_invalidConfigDir()).default, function (err) {
  return `error: the eject path is already part of "${(_chalk || _load_chalk()).default.bold(err.compId)}" path`;
}], [(_ejectToWorkspace || _load_ejectToWorkspace()).default, function () {
  return 'error: could not eject config to the workspace root please provide a valid path';
}], [(_ejectBoundToWorkspace || _load_ejectBoundToWorkspace()).default, function () {
  return 'error: could not eject config for authored component which are bound to the workspace configuration';
}], [(_injectNonEjected || _load_injectNonEjected()).default, function () {
  return 'error: could not inject config for already injected component';
}], [(_componentsPendingImport || _load_componentsPendingImport()).default, function () {
  return (_statusCmd || _load_statusCmd()).importPendingMsg;
}], [(_ejectNoDir || _load_ejectNoDir()).default, function (err) {
  return `error: could not eject config for ${(_chalk || _load_chalk()).default.bold(err.compId)}, please provide path which doesn't contain {${(_constants || _load_constants()).COMPONENT_DIR}} to eject`;
}], [(_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.\n${reportIssueToGithubMsg}`;
}], [(_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-unresolved-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}\n${reportIssueToGithubMsg}`;
}], [(_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://${(_constants || _load_constants()).BASE_DOCS_DOMAIN}/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()).HashNotFound, function (err) {
  return `hash ${(_chalk || _load_chalk()).default.bold(err.hash)} not found`;
}], [(_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
3) bit checkout ${err.versions.join(' ')} ${err.id}
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
3) bit checkout [version] [id]
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()).OutdatedIndexJson, function (err) {
  return `error: component ${(_chalk || _load_chalk()).default.bold(err.componentId)} found in the index.json file, however, is missing from the scope.
to get the file rebuild, please delete it at "${err.indexJsonPath}".\n${reportIssueToGithubMsg}
`;
}], [(_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}` : ''}`;
}], [(_remoteResolverError || _load_remoteResolverError()).default, function (err) {
  return `error: ${err.message ? `${err.message}` : 'unexpected remote resolver error has occurred'}`;
}], [(_exportAnotherOwnerPrivate || _load_exportAnotherOwnerPrivate()).default, function (err) {
  return `error: unable to export components to ${err.destinationScope} because they have dependencies on components in ${err.sourceScope}.
bit does not allow setting dependencies between components in private collections managed by different owners.

see troubleshooting at https://${(_constants || _load_constants()).BASE_DOCS_DOMAIN}/docs/bitdev-permissions.html`;
}], [(_exceptions3 || _load_exceptions3()).SSHInvalidResponse, function () {
  return `error: received an invalid response from the remote SSH server.
to see the invalid response, have a look at the log, located at ${(_constants || _load_constants()).DEBUG_LOG}`;
}], [(_exceptions4 || _load_exceptions4()).InvalidIndexJson, function (err) {
  return `fatal: your .bit/index.json is not a valid JSON file.
To rebuild the file, please run ${(_chalk || _load_chalk()).default.bold('bit init --reset')}.
Original Error: ${err.message}`;
}], [(_exceptions4 || _load_exceptions4()).ScopeNotFound, function (err) {
  return `error: scope not found at ${(_chalk || _load_chalk()).default.bold(err.scopePath)}`;
}], [(_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`;
}], [(_missingDiagnosisName || _load_missingDiagnosisName()).default, function (err) {
  return 'error: please provide a diagnosis name';
}], [(_diagnosisNotFound || _load_diagnosisNotFound()).default, function (err) {
  return `error: diagnosis ${(_chalk || _load_chalk()).default.bold(err.diagnosisName)} not found`;
}], [(_exceptions2 || _load_exceptions2()).ComponentSpecsFailed, function (err) {
  return `${err.specsResultsAndIdPretty}component tests failed. please make sure all tests pass before tagging a new version or use the "--force" flag to force-tag components.\nto view test failures, please use the "--verbose" flag or use the "bit test" command`;
}], [(_exceptions2 || _load_exceptions2()).ComponentOutOfSync, function (err) {
  return `component ${(_chalk || _load_chalk()).default.bold(err.id)} is not in-sync between the consumer and the scope.
if it is originated from another git branch, go back to that branch to continue working on the component.
if possible, remove the component using "bit remove" and re-import or re-create it.
to re-start Bit from scratch, deleting all objects from the scope, use "bit init --reset-hard"`;
}], [(_exceptions2 || _load_exceptions2()).MissingDependencies, function (err) {
  var missingDepsColored = (0, (_componentIssuesTemplate || _load_componentIssuesTemplate()).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]`');
}], [(_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 ["-", "_", "$", "!"]`;
}], [(_exceptions || _load_exceptions()).InvalidName, function (err) {
  return `error: "${(_chalk || _load_chalk()).default.bold(err.componentName)}" is invalid, component names can only contain alphanumeric, lowercase characters, and the following ["-", "_", "$", "!", "/"]`;
}], [(_exceptions || _load_exceptions()).InvalidScopeName, function (err) {
  return `error: "${(_chalk || _load_chalk()).default.bold(err.scopeName)}" is invalid, component scope names 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`;
}], [(_invalidPackageJson || _load_invalidPackageJson()).default, function (err) {
  return `error: package.json at ${(_chalk || _load_chalk()).default.bold(err.path)} is not a valid JSON file.
please fix the file in order to run bit commands`;
}], [(_invalidConfigPropPath || _load_invalidConfigPropPath()).default, function (err) {
  return `error: the path "${(_chalk || _load_chalk()).default.bold(err.fieldValue)}" of "${(_chalk || _load_chalk()).default.bold(err.fieldName)}" in your bit.json or package.json file is invalid.
please make sure it's not absolute and doesn't contain invalid characters`;
}], [(_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: the component ${(_chalk || _load_chalk()).default.bold(err.componentId)} 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://${(_constants || _load_constants()).BASE_DOCS_DOMAIN}/docs/isolating-and-tracking-components.html#define-a-components-main-file`;
}], [(_exceptions6 || _load_exceptions6()).MissingMainFileMultipleComponents, function (err) {
  return `error: the components ${(_chalk || _load_chalk()).default.bold(err.componentIds.join(', '))} 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://${(_constants || _load_constants()).BASE_DOCS_DOMAIN}/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`;
}], [(_mainFileRemoved || _load_mainFileRemoved()).default, function (err) {
  return `error: main file ${(_chalk || _load_chalk()).default.bold(err.mainFile)} was removed from ${(_chalk || _load_chalk()).default.bold(err.id)}.
please use "bit remove" to delete the component or "bit add" with "--main" and "--id" flags to add a new mainFile`;
}], [(_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.`;
}], [(_exceptions6 || _load_exceptions6()).PathOutsideConsumer, function (err) {
  return `error: file or directory "${(_chalk || _load_chalk()).default.bold(err.path)}" is located outside of the workspace.`;
}], [(_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`;
}], [(_noIdMatchWildcard || _load_noIdMatchWildcard()).default, function (err) {
  return `unable to find component ids that match the following: ${err.idsWithWildcards.join(', ')}`;
}], [(_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');
}], [(_externalTestErrors || _load_externalTestErrors()).default, function (err) {
  return `error: bit failed to test ${err.id} with the following exception:\n${getExternalErrorsMessageAndStack(err.originalErrors)}`;
}], [(_externalBuildErrors || _load_externalBuildErrors()).default, function (err) {
  return `error: bit failed to build ${err.id} with the following exception:\n${getExternalErrorsMessageAndStack(err.originalErrors)}`;
}], [(_extensionLoadError || _load_extensionLoadError()).default, function (err) {
  return `error: bit failed to load ${err.compName} with the following exception:\n${getExternalErrorMessage(err.originalError)}.\n${err.printStack ? err.originalError.stack : ''}`;
}], [(_extensionSchemaError || _load_extensionSchemaError()).default, function (err) {
  return `error: configuration passed to extension ${(_chalk || _load_chalk()).default.bold(err.extensionName)} is invalid:\n${err.errors}`;
}], [(_extensionInitError || _load_extensionInitError()).default, function (err) {
  return `error: bit failed to initialized ${err.compName} with the following exception:\n${getExternalErrorMessage(err.originalError)}.\n${err.originalError.stack}`;
}], [(_extensionGetDynamicPackagesError || _load_extensionGetDynamicPackagesError()).default, function (err) {
  return `error: bit failed to get the dynamic packages from ${err.compName} with the following exception:\n${err.originalError.message}.\n${err.originalError.stack}`;
}], [(_extensionGetDynamicConfigError || _load_extensionGetDynamicConfigError()).default, function (err) {
  return `error: bit failed to get the config from ${err.compName} 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${getExternalErrorMessage(err.originalError)}.\n${err.originalError.stack}`;
}], [(_gitNotFound || _load_gitNotFound()).default, function (err) {
  return "error: unable to run command because git executable not found. please ensure git is installed and/or git_path is configured using the 'bit config set git_path <GIT_PATH>'";
}], [(_exceptions3 || _load_exceptions3()).AuthenticationFailed, function (err) {
  return `authentication failed. see troubleshooting at https://${(_constants || _load_constants()).BASE_DOCS_DOMAIN}/docs/authentication-issues.html\n\n${err.debugInfo}`;
}], [(_objectsWithoutConsumer || _load_objectsWithoutConsumer()).default, function (err) {
  return `error: unable to initialize a bit workspace. bit has found undeleted local objects at ${(_chalk || _load_chalk()).default.bold(err.scopePath)}.
1. use the ${(_chalk || _load_chalk()).default.bold('--reset-hard')} flag to clear all data and initialize an empty workspace.
2. if deleted by mistake, please restore .bitmap and bit.json.
3. force workspace initialization without clearing data use the ${(_chalk || _load_chalk()).default.bold('--force')} flag.`;
}]];

function findErrorDefinition(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.
  });
  return error;
}

function getErrorFunc(errorDefinition) {
  if (!errorDefinition) return null;

  var _errorDefinition = _slicedToArray(errorDefinition, 2),
      func = _errorDefinition[1];

  return func;
}

function getErrorMessage(error, func) {
  if (!error || !func) return '';
  var errorMessage = func(error);
  if (error.showDoctorMessage) {
    errorMessage = `${errorMessage}

run 'bit doctor' to get detailed workspace diagnosis and issue resolution.`;
  }
  return errorMessage;
}

function getExternalErrorMessage(externalError) {
  if (!externalError) return '';

  // In case an error is not a real error
  if (!(externalError instanceof Error)) {
    return externalError;
  }
  // In case it's not a bit error
  if (externalError.message) {
    return externalError.message;
  }
  var errorDefinition = findErrorDefinition(externalError);
  var func = getErrorFunc(errorDefinition);
  var errorMessage = getErrorMessage(externalError, func);
  return errorMessage;
}

function getExternalErrorsMessageAndStack(errors) {
  var result = errors.map(function (e) {
    var msg = getExternalErrorMessage(e);
    var stack = e.stack || '';
    return `${msg}\n${stack}\n`;
  }).join('~~~~~~~~~~~~~\n');
  return result;
}

/**
 * if err.userError is set, it inherits from AbstractError, which are user errors not Bit errors
 * and should not be reported to Sentry.
 * reason why we don't check (err instanceof AbstractError) is that it could be thrown from a fork,
 * in which case, it loses its class and has only the fields.
 */
function sendToAnalyticsAndSentry(err) {
  var possiblyHashedError = (0, (_hashErrorObject || _load_hashErrorObject()).default)(err);
  // only level FATAL are reported to Sentry.
  // $FlowFixMe
  var level = err.isUserError ? (_analytics || _load_analytics()).LEVEL.INFO : (_analytics || _load_analytics()).LEVEL.FATAL;
  (_analytics || _load_analytics()).Analytics.setError(level, possiblyHashedError);
}

exports.default = function (err) {
  var errorDefinition = findErrorDefinition(err);
  sendToAnalyticsAndSentry(err);
  if (!errorDefinition) {
    return (_chalk || _load_chalk()).default.red(err.message || err);
  }
  var func = getErrorFunc(errorDefinition);
  var errorMessage = getErrorMessage(err, func) || 'unknown error';
  err.message = errorMessage;
  (_logger || _load_logger()).default.error(`User gets the following error: ${errorMessage}`);
  return (_chalk || _load_chalk()).default.red(errorMessage);
};