'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.removeComponentsFromWorkspacesAndDependencies = exports.writePackageJsonFromObject = exports.getPackageJsonObject = exports.addWorkspacesToPackageJson = exports.updateAttribute = exports.addComponentsWithVersionToRoot = exports.preparePackageJsonToWrite = exports.write = exports.changeDependenciesToRelativeSyntax = exports.removeComponentsFromNodeModules = exports.addComponentsToRoot = undefined;

var _regenerator;

function _load_regenerator() {
  return _regenerator = _interopRequireDefault(require('babel-runtime/regenerator'));
}

var _bluebird;

function _load_bluebird() {
  return _bluebird = require('bluebird');
}

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

/**
 * Add components as dependencies to root package.json
 */


// the instance comes from bit-javascript PackageJson class
var addComponentsToRoot = function () {
  var _ref = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee(consumer, components) {
    var componentsToAdd;
    return (_regenerator || _load_regenerator()).default.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            componentsToAdd = components.reduce(function (acc, component) {
              var componentMap = consumer.bitMap.getComponent(component.id);
              if (componentMap.origin !== (_constants || _load_constants()).COMPONENT_ORIGINS.IMPORTED) return acc;
              if (!componentMap.rootDir) {
                throw new (_generalError || _load_generalError()).default(`rootDir is missing from an imported component ${component.id.toString()}`);
              }
              var locationAsUnixFormat = convertToValidPathForPackageManager(componentMap.rootDir);
              var packageName = (0, (_componentIdToPackageName || _load_componentIdToPackageName()).default)(component.id, component.bindingPrefix);
              acc[packageName] = locationAsUnixFormat;
              return acc;
            }, {});

            if (!(_ramda || _load_ramda()).default.isEmpty(componentsToAdd)) {
              _context.next = 3;
              break;
            }

            return _context.abrupt('return');

          case 3:
            _context.next = 5;
            return _addDependenciesPackagesIntoPackageJson(consumer.getPath(), componentsToAdd);

          case 5:
          case 'end':
            return _context.stop();
        }
      }
    }, _callee, this);
  }));

  return function addComponentsToRoot(_x, _x2) {
    return _ref.apply(this, arguments);
  };
}();

var _addDependenciesPackagesIntoPackageJson = function () {
  var _ref2 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee2(dir, dependencies) {
    var packageJson;
    return (_regenerator || _load_regenerator()).default.wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            _context2.next = 2;
            return getPackageJsonObject(dir);

          case 2:
            _context2.t0 = _context2.sent;

            if (_context2.t0) {
              _context2.next = 5;
              break;
            }

            _context2.t0 = { dependencies: {} };

          case 5:
            packageJson = _context2.t0;

            packageJson.dependencies = Object.assign({}, packageJson.dependencies, dependencies);
            return _context2.abrupt('return', writePackageJsonFromObject(dir, packageJson));

          case 8:
          case 'end':
            return _context2.stop();
        }
      }
    }, _callee2, this);
  }));

  return function _addDependenciesPackagesIntoPackageJson(_x3, _x4) {
    return _ref2.apply(this, arguments);
  };
}();

/**
 * Add given components with their versions to root package.json
 */


var addComponentsWithVersionToRoot = function () {
  var _ref3 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee3(consumer, componentsIds) {
    var driver, PackageJson, componentsToAdd;
    return (_regenerator || _load_regenerator()).default.wrap(function _callee3$(_context3) {
      while (1) {
        switch (_context3.prev = _context3.next) {
          case 0:
            driver = consumer.driver.getDriver(false);
            PackageJson = driver.PackageJson;
            componentsToAdd = (_ramda || _load_ramda()).default.fromPairs(componentsIds.map(function (id) {
              return [id.toStringWithoutVersion(), id.version];
            }));
            _context3.next = 5;
            return PackageJson.addComponentsIntoExistingPackageJson(consumer.getPath(), componentsToAdd, (0, (_npmRegistryName || _load_npmRegistryName()).default)());

          case 5:
          case 'end':
            return _context3.stop();
        }
      }
    }, _callee3, this);
  }));

  return function addComponentsWithVersionToRoot(_x5, _x6) {
    return _ref3.apply(this, arguments);
  };
}();

var getPackageDependency = function () {
  var _ref4 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee4(consumer, dependencyId, parentId) {
    var parentComponentMap, dependencyComponentMap;
    return (_regenerator || _load_regenerator()).default.wrap(function _callee4$(_context4) {
      while (1) {
        switch (_context4.prev = _context4.next) {
          case 0:
            parentComponentMap = consumer.bitMap.getComponent(parentId);
            dependencyComponentMap = consumer.bitMap.getComponentIfExist(dependencyId);
            return _context4.abrupt('return', getPackageDependencyValue(dependencyId, parentComponentMap, dependencyComponentMap));

          case 3:
          case 'end':
            return _context4.stop();
        }
      }
    }, _callee4, this);
  }));

  return function getPackageDependency(_x7, _x8, _x9) {
    return _ref4.apply(this, arguments);
  };
}();

var changeDependenciesToRelativeSyntax = function () {
  var _ref5 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee6(consumer, components, dependencies) {
    var _this = this;

    var dependenciesIds, driver, PackageJson, updateComponentPackageJson, packageJsonFiles;
    return (_regenerator || _load_regenerator()).default.wrap(function _callee6$(_context6) {
      while (1) {
        switch (_context6.prev = _context6.next) {
          case 0:
            dependenciesIds = (_bitId || _load_bitId()).BitIds.fromArray(dependencies.map(function (dependency) {
              return dependency.id;
            }));
            driver = consumer.driver.getDriver(false);
            PackageJson = driver.PackageJson;

            updateComponentPackageJson = function () {
              var _ref6 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee5(component) {
                var componentMap, packageJson, getPackages, devDeps, compilerDeps, testerDeps;
                return (_regenerator || _load_regenerator()).default.wrap(function _callee5$(_context5) {
                  while (1) {
                    switch (_context5.prev = _context5.next) {
                      case 0:
                        componentMap = consumer.bitMap.getComponent(component.id);
                        packageJson = void 0;
                        _context5.prev = 2;
                        _context5.next = 5;
                        return PackageJson.load(componentMap.rootDir);

                      case 5:
                        packageJson = _context5.sent;
                        _context5.next = 11;
                        break;

                      case 8:
                        _context5.prev = 8;
                        _context5.t0 = _context5['catch'](2);
                        return _context5.abrupt('return', Promise.resolve());

                      case 11:
                        getPackages = function getPackages(deps) {
                          var packages = deps.get().map(function (dependency) {
                            var dependencyId = dependency.id.toStringWithoutVersion();
                            if (dependenciesIds.searchWithoutVersion(dependency.id)) {
                              var dependencyComponent = dependencies.find(function (d) {
                                return d.id.isEqualWithoutVersion(dependency.id);
                              });
                              // $FlowFixMe dependencyComponent must be found (two line earlier there is a check for that)
                              var dependencyComponentMap = consumer.bitMap.getComponentIfExist(dependencyComponent.id);
                              var dependencyPackageValue = getPackageDependencyValue(dependencyId, componentMap, dependencyComponentMap);
                              return dependencyPackageValue ? [dependencyId, dependencyPackageValue] : [];
                            }
                            return [];
                          });
                          return (_ramda || _load_ramda()).default.fromPairs(packages);
                        };

                        devDeps = getPackages(component.devDependencies);
                        compilerDeps = getPackages(component.compilerDependencies);
                        testerDeps = getPackages(component.testerDependencies);

                        packageJson.addDependencies(getPackages(component.dependencies), (0, (_npmRegistryName || _load_npmRegistryName()).default)());
                        packageJson.addDevDependencies(_extends({}, devDeps, compilerDeps, testerDeps), (0, (_npmRegistryName || _load_npmRegistryName()).default)());
                        // return packageJson.write({ override: true });
                        return _context5.abrupt('return', (_jsonFile || _load_jsonFile()).default.load({
                          // $FlowFixMe
                          base: componentMap.rootDir, // $FlowFixMe
                          path: (_path || _load_path()).default.join(componentMap.rootDir, (_constants || _load_constants()).PACKAGE_JSON),
                          content: packageJson,
                          override: true
                        }));

                      case 18:
                      case 'end':
                        return _context5.stop();
                    }
                  }
                }, _callee5, _this, [[2, 8]]);
              }));

              return function updateComponentPackageJson(_x13) {
                return _ref6.apply(this, arguments);
              };
            }();
            // $FlowFixMe


            _context6.next = 6;
            return Promise.all(components.map(function (component) {
              return updateComponentPackageJson(component);
            }));

          case 6:
            packageJsonFiles = _context6.sent;
            return _context6.abrupt('return', packageJsonFiles.filter(function (file) {
              return file;
            }));

          case 8:
          case 'end':
            return _context6.stop();
        }
      }
    }, _callee6, this);
  }));

  return function changeDependenciesToRelativeSyntax(_x10, _x11, _x12) {
    return _ref5.apply(this, arguments);
  };
}();

var write = function () {
  var _ref7 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee7(consumer, component, bitDir) {
    var override = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
    var writeBitDependencies = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;
    var excludeRegistryPrefix = arguments[5];
    var packageJson;
    return (_regenerator || _load_regenerator()).default.wrap(function _callee7$(_context7) {
      while (1) {
        switch (_context7.prev = _context7.next) {
          case 0:
            _context7.next = 2;
            return preparePackageJsonToWrite(consumer, component, bitDir, override, writeBitDependencies, excludeRegistryPrefix);

          case 2:
            packageJson = _context7.sent;
            _context7.next = 5;
            return packageJson.write({ override });

          case 5:
            return _context7.abrupt('return', packageJson);

          case 6:
          case 'end':
            return _context7.stop();
        }
      }
    }, _callee7, this);
  }));

  return function write(_x14, _x15, _x16) {
    return _ref7.apply(this, arguments);
  };
}();

var preparePackageJsonToWrite = function () {
  var _ref8 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee10(consumer, component, bitDir) {
    var override = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;

    var _this2 = this;

    var writeBitDependencies = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;
    var excludeRegistryPrefix = arguments[5];
    var PackageJson, getBitDependencies, bitDependencies, bitDevDependencies, bitCompilerDependencies, bitTesterDependencies, registryPrefix, name, getPackageJsonInstance, packageJson, distRootDir, distPackageJson;
    return (_regenerator || _load_regenerator()).default.wrap(function _callee10$(_context10) {
      while (1) {
        switch (_context10.prev = _context10.next) {
          case 0:
            (_logger || _load_logger()).default.debug(`package-json.write. bitDir ${bitDir}. override ${override.toString()}`);
            PackageJson = consumer.driver.getDriver(false).PackageJson;

            getBitDependencies = function () {
              var _ref9 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee9(dependencies) {
                var dependenciesPackages;
                return (_regenerator || _load_regenerator()).default.wrap(function _callee9$(_context9) {
                  while (1) {
                    switch (_context9.prev = _context9.next) {
                      case 0:
                        if (writeBitDependencies) {
                          _context9.next = 2;
                          break;
                        }

                        return _context9.abrupt('return', {});

                      case 2:
                        dependenciesPackages = dependencies.get().map(function () {
                          var _ref10 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee8(dep) {
                            var packageDependency;
                            return (_regenerator || _load_regenerator()).default.wrap(function _callee8$(_context8) {
                              while (1) {
                                switch (_context8.prev = _context8.next) {
                                  case 0:
                                    _context8.next = 2;
                                    return getPackageDependency(consumer, dep.id, component.id);

                                  case 2:
                                    packageDependency = _context8.sent;
                                    return _context8.abrupt('return', [dep.id.toStringWithoutVersion(), packageDependency]);

                                  case 4:
                                  case 'end':
                                    return _context8.stop();
                                }
                              }
                            }, _callee8, _this2);
                          }));

                          return function (_x25) {
                            return _ref10.apply(this, arguments);
                          };
                        }());
                        _context9.t0 = (_ramda || _load_ramda()).default;
                        _context9.next = 6;
                        return Promise.all(dependenciesPackages);

                      case 6:
                        _context9.t1 = _context9.sent;
                        return _context9.abrupt('return', _context9.t0.fromPairs.call(_context9.t0, _context9.t1));

                      case 8:
                      case 'end':
                        return _context9.stop();
                    }
                  }
                }, _callee9, _this2);
              }));

              return function getBitDependencies(_x24) {
                return _ref9.apply(this, arguments);
              };
            }();

            _context10.next = 5;
            return getBitDependencies(component.dependencies);

          case 5:
            bitDependencies = _context10.sent;
            _context10.next = 8;
            return getBitDependencies(component.devDependencies);

          case 8:
            bitDevDependencies = _context10.sent;
            _context10.next = 11;
            return getBitDependencies(component.compilerDependencies);

          case 11:
            bitCompilerDependencies = _context10.sent;
            _context10.next = 14;
            return getBitDependencies(component.testerDependencies);

          case 14:
            bitTesterDependencies = _context10.sent;
            registryPrefix = component.bindingPrefix || (0, (_npmRegistryName || _load_npmRegistryName()).default)();
            name = excludeRegistryPrefix ? (0, (_componentIdToPackageName || _load_componentIdToPackageName()).default)(component.id, component.bindingPrefix, false) : (0, (_componentIdToPackageName || _load_componentIdToPackageName()).default)(component.id, component.bindingPrefix);

            getPackageJsonInstance = function getPackageJsonInstance(dir) {
              var packageJson = new PackageJson(dir, {
                name,
                version: component.version,
                homepage: component._getHomepage(),
                main: (0, (_path2 || _load_path2()).pathNormalizeToLinux)(component.dists.calculateMainDistFile(component.mainFile)),
                dependencies: component.packageDependencies,
                // Add environments PackageDependencies to the devDependencies in the package.json
                devDependencies: _extends({}, component.devPackageDependencies, component.compilerPackageDependencies, component.testerPackageDependencies),
                peerDependencies: component.peerPackageDependencies,
                componentRootFolder: dir,
                license: `SEE LICENSE IN ${!(_ramda || _load_ramda()).default.isEmpty(component.license) ? 'LICENSE' : 'UNLICENSED'}`
              });
              packageJson.addDependencies(bitDependencies, registryPrefix);
              packageJson.addDevDependencies(_extends({}, bitDevDependencies, bitCompilerDependencies, bitTesterDependencies), registryPrefix);
              return packageJson;
            };

            packageJson = getPackageJsonInstance(bitDir);

            if (!(!component.dists.isEmpty() && !component.dists.areDistsInsideComponentDir)) {
              _context10.next = 26;
              break;
            }

            distRootDir = component.dists.distsRootDir;

            if (distRootDir) {
              _context10.next = 23;
              break;
            }

            throw new (_generalError || _load_generalError()).default('component.dists.distsRootDir is not defined yet');

          case 23:
            distPackageJson = getPackageJsonInstance(distRootDir);
            _context10.next = 26;
            return distPackageJson.write({ override });

          case 26:
            return _context10.abrupt('return', packageJson);

          case 27:
          case 'end':
            return _context10.stop();
        }
      }
    }, _callee10, this);
  }));

  return function preparePackageJsonToWrite(_x19, _x20, _x21) {
    return _ref8.apply(this, arguments);
  };
}();

var updateAttribute = function () {
  var _ref11 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee11(consumer, componentDir, attributeName, attributeValue) {
    var writeFile = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;
    var PackageJson, packageJson;
    return (_regenerator || _load_regenerator()).default.wrap(function _callee11$(_context11) {
      while (1) {
        switch (_context11.prev = _context11.next) {
          case 0:
            PackageJson = consumer.driver.getDriver(false).PackageJson;
            _context11.prev = 1;
            _context11.next = 4;
            return PackageJson.load(componentDir);

          case 4:
            packageJson = _context11.sent;

            packageJson[attributeName] = attributeValue;
            return _context11.abrupt('return', writeFile ? packageJson.write({ override: true }) : packageJson);

          case 9:
            _context11.prev = 9;
            _context11.t0 = _context11['catch'](1);
            return _context11.abrupt('return', Promise.resolve());

          case 12:
          case 'end':
            return _context11.stop();
        }
      }
    }, _callee11, this, [[1, 9]]);
  }));

  return function updateAttribute(_x26, _x27, _x28, _x29) {
    return _ref11.apply(this, arguments);
  };
}();

/**
 * Adds workspace array to package.json - only if user wants to work with yarn workspaces
 */


var addWorkspacesToPackageJson = function () {
  var _ref12 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee12(consumer, customImportPath) {
    var rootDir, dependenciesDirectory, componentsDefaultDirectory, driver, PackageJson;
    return (_regenerator || _load_regenerator()).default.wrap(function _callee12$(_context12) {
      while (1) {
        switch (_context12.prev = _context12.next) {
          case 0:
            if (!(consumer.bitJson.manageWorkspaces && consumer.bitJson.packageManager === 'yarn' && consumer.bitJson.useWorkspaces)) {
              _context12.next = 8;
              break;
            }

            rootDir = consumer.getPath();
            dependenciesDirectory = consumer.bitJson.dependenciesDirectory;
            componentsDefaultDirectory = consumer.dirStructure.componentsDefaultDirectory;
            driver = consumer.driver.getDriver(false);
            PackageJson = driver.PackageJson;
            _context12.next = 8;
            return PackageJson.addWorkspacesToPackageJson(rootDir, componentsDefaultDirectory + (_constants || _load_constants()).SUB_DIRECTORIES_GLOB_PATTERN, dependenciesDirectory + (_constants || _load_constants()).SUB_DIRECTORIES_GLOB_PATTERN, customImportPath ? consumer.getPathRelativeToConsumer(customImportPath) : customImportPath);

          case 8:
          case 'end':
            return _context12.stop();
        }
      }
    }, _callee12, this);
  }));

  return function addWorkspacesToPackageJson(_x31, _x32) {
    return _ref12.apply(this, arguments);
  };
}();

var removeComponentsFromNodeModules = function () {
  var _ref13 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee13(consumer, componentIds) {
    var registryPrefix, pathsToRemove;
    return (_regenerator || _load_regenerator()).default.wrap(function _callee13$(_context13) {
      while (1) {
        switch (_context13.prev = _context13.next) {
          case 0:
            (_logger || _load_logger()).default.debug(`removeComponentsFromNodeModules: ${componentIds.map(function (c) {
              return c.toString();
            }).join(', ')}`);
            registryPrefix = (0, (_npmRegistryName || _load_npmRegistryName()).default)();
            // paths without scope name, don't have a symlink in node-modules

            pathsToRemove = componentIds.map(function (id) {
              return id.scope ? (0, (_componentNodeModulesPath || _load_componentNodeModulesPath()).default)(registryPrefix, id) : null;
            }).filter(function (a) {
              return a;
            }); // remove null

            (_logger || _load_logger()).default.debug(`deleting the following paths: ${pathsToRemove.join('\n')}`);
            // $FlowFixMe nulls were removed in the previous filter function
            return _context13.abrupt('return', Promise.all(pathsToRemove.map(function (componentPath) {
              return (_fsExtra || _load_fsExtra()).default.remove(consumer.toAbsolutePath(componentPath));
            })));

          case 5:
          case 'end':
            return _context13.stop();
        }
      }
    }, _callee13, this);
  }));

  return function removeComponentsFromNodeModules(_x33, _x34) {
    return _ref13.apply(this, arguments);
  };
}();

var removeComponentsFromWorkspacesAndDependencies = function () {
  var _ref14 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee14(consumer, componentIds) {
    var rootDir, driver, PackageJson, dirsToRemove;
    return (_regenerator || _load_regenerator()).default.wrap(function _callee14$(_context14) {
      while (1) {
        switch (_context14.prev = _context14.next) {
          case 0:
            rootDir = consumer.getPath();
            driver = consumer.driver.getDriver(false);
            PackageJson = driver.PackageJson;

            if (!(consumer.bitJson.manageWorkspaces && consumer.bitJson.packageManager === 'yarn' && consumer.bitJson.useWorkspaces)) {
              _context14.next = 7;
              break;
            }

            dirsToRemove = componentIds.map(function (id) {
              return consumer.bitMap.getComponent(id, { ignoreVersion: true }).rootDir;
            });
            _context14.next = 7;
            return PackageJson.removeComponentsFromWorkspaces(rootDir, dirsToRemove);

          case 7:
            _context14.next = 9;
            return PackageJson.removeComponentsFromDependencies(rootDir, (0, (_npmRegistryName || _load_npmRegistryName()).default)(), componentIds.map(function (id) {
              return id.toStringWithoutVersion();
            }));

          case 9:
            _context14.next = 11;
            return removeComponentsFromNodeModules(consumer, componentIds);

          case 11:
          case 'end':
            return _context14.stop();
        }
      }
    }, _callee14, this);
  }));

  return function removeComponentsFromWorkspacesAndDependencies(_x35, _x36) {
    return _ref14.apply(this, arguments);
  };
}();

/**
 * get the package.json object of the given dir, if not found, return null
 */


var getPackageJsonObject = function () {
  var _ref15 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee15(dir) {
    var packageJsonObject;
    return (_regenerator || _load_regenerator()).default.wrap(function _callee15$(_context15) {
      while (1) {
        switch (_context15.prev = _context15.next) {
          case 0:
            _context15.prev = 0;
            _context15.next = 3;
            return (_fsExtra || _load_fsExtra()).default.readJson(composePath(dir));

          case 3:
            packageJsonObject = _context15.sent;
            return _context15.abrupt('return', packageJsonObject);

          case 7:
            _context15.prev = 7;
            _context15.t0 = _context15['catch'](0);

            if (!(_context15.t0.code === 'ENOENT')) {
              _context15.next = 11;
              break;
            }

            return _context15.abrupt('return', null);

          case 11:
            throw _context15.t0;

          case 12:
          case 'end':
            return _context15.stop();
        }
      }
    }, _callee15, this, [[0, 7]]);
  }));

  return function getPackageJsonObject(_x37) {
    return _ref15.apply(this, arguments);
  };
}();

var writePackageJsonFromObject = function () {
  var _ref16 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee16(dir, data) {
    return (_regenerator || _load_regenerator()).default.wrap(function _callee16$(_context16) {
      while (1) {
        switch (_context16.prev = _context16.next) {
          case 0:
            return _context16.abrupt('return', (_fsExtra || _load_fsExtra()).default.outputJSON(composePath(dir), data, { spaces: 2 }));

          case 1:
          case 'end':
            return _context16.stop();
        }
      }
    }, _callee16, this);
  }));

  return function writePackageJsonFromObject(_x38, _x39) {
    return _ref16.apply(this, arguments);
  };
}();

var _ramda;

function _load_ramda() {
  return _ramda = _interopRequireDefault(require('ramda'));
}

var _path;

function _load_path() {
  return _path = _interopRequireDefault(require('path'));
}

var _fsExtra;

function _load_fsExtra() {
  return _fsExtra = _interopRequireDefault(require('fs-extra'));
}

var _bitId;

function _load_bitId() {
  return _bitId = require('../../bit-id');
}

var _constants;

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

var _componentMap;

function _load_componentMap() {
  return _componentMap = _interopRequireDefault(require('../bit-map/component-map'));
}

var _utils;

function _load_utils() {
  return _utils = require('../../utils');
}

var _path2;

function _load_path2() {
  return _path2 = require('../../utils/path');
}

var _componentNodeModulesPath;

function _load_componentNodeModulesPath() {
  return _componentNodeModulesPath = _interopRequireDefault(require('../../utils/bit/component-node-modules-path'));
}

var _logger;

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

var _generalError;

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

var _jsonFile;

function _load_jsonFile() {
  return _jsonFile = _interopRequireDefault(require('./sources/json-file'));
}

var _npmRegistryName;

function _load_npmRegistryName() {
  return _npmRegistryName = _interopRequireDefault(require('../../utils/bit/npm-registry-name'));
}

var _componentIdToPackageName;

function _load_componentIdToPackageName() {
  return _componentIdToPackageName = _interopRequireDefault(require('../../utils/bit/component-id-to-package-name'));
}

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

function convertToValidPathForPackageManager(pathStr) {
  var prefix = 'file:'; // it works for both, Yarn and NPM
  return prefix + (pathStr.startsWith('.') ? pathStr : `./${pathStr}`);
}

/**
 * Only imported components should be saved with relative path in package.json
 * If a component is nested or imported as a package dependency, it should be saved with the version
 * If a component is authored, no need to save it as a dependency of the imported component because
 * the root package.json takes care of it already.
 */
function getPackageDependencyValue(dependencyId, parentComponentMap, dependencyComponentMap) {
  if (!dependencyComponentMap || dependencyComponentMap.origin === (_constants || _load_constants()).COMPONENT_ORIGINS.NESTED) {
    return dependencyId.version;
  }
  if (dependencyComponentMap.origin === (_constants || _load_constants()).COMPONENT_ORIGINS.AUTHORED) {
    return null;
  }
  var dependencyRootDir = dependencyComponentMap.rootDir;
  if (!dependencyRootDir) {
    throw new (_generalError || _load_generalError()).default(`rootDir is missing from an imported component ${dependencyId.toString()}`);
  }
  if (!parentComponentMap.rootDir) throw new (_generalError || _load_generalError()).default('rootDir is missing from an imported component');
  var rootDirRelative = (0, (_utils || _load_utils()).pathRelativeLinux)(parentComponentMap.rootDir, dependencyRootDir);
  return convertToValidPathForPackageManager(rootDirRelative);
}

function composePath(componentRootFolder) {
  return (_path || _load_path()).default.join(componentRootFolder, (_constants || _load_constants()).PACKAGE_JSON);
}

exports.addComponentsToRoot = addComponentsToRoot;
exports.removeComponentsFromNodeModules = removeComponentsFromNodeModules;
exports.changeDependenciesToRelativeSyntax = changeDependenciesToRelativeSyntax;
exports.write = write;
exports.preparePackageJsonToWrite = preparePackageJsonToWrite;
exports.addComponentsWithVersionToRoot = addComponentsWithVersionToRoot;
exports.updateAttribute = updateAttribute;
exports.addWorkspacesToPackageJson = addWorkspacesToPackageJson;
exports.getPackageJsonObject = getPackageJsonObject;
exports.writePackageJsonFromObject = writePackageJsonFromObject;
exports.removeComponentsFromWorkspacesAndDependencies = removeComponentsFromWorkspacesAndDependencies;