"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports.sanitizePluginPath = exports.resolvePluginDependants = exports.parsePlugins = exports.overrideTemplatePlugins = exports.overrideFileContents = exports.loadPluginTemplates = exports.installPackageDependenciesAndPlugins = exports.includesPluginPath = exports.getPluginList = exports.getModuleConfigs = exports.getMergedPlugin = exports.getLocalRenativePlugin = exports.copyTemplatePluginsSync = exports.configurePlugins = void 0;
var _deepmerge = _interopRequireDefault(require("deepmerge"));
var _path = _interopRequireDefault(require("path"));
var _prompt = require("../../cli/prompt");
var _common = require("../common");
var _configManager = require("../configManager");
var _constants = require("../constants");
var _fileutils = require("../systemManager/fileutils");




var _logger = require("../systemManager/logger");




var _npmUtils = require("../systemManager/npmUtils");
var _resolve = require("../systemManager/resolve");function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { "default": obj };}function _toConsumableArray(arr) {return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();}function _nonIterableSpread() {throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");}function _unsupportedIterableToArray(o, minLen) {if (!o) return;if (typeof o === "string") return _arrayLikeToArray(o, minLen);var n = Object.prototype.toString.call(o).slice(8, -1);if (n === "Object" && o.constructor) n = o.constructor.name;if (n === "Map" || n === "Set") return Array.from(o);if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);}function _iterableToArray(iter) {if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);}function _arrayWithoutHoles(arr) {if (Array.isArray(arr)) return _arrayLikeToArray(arr);}function _arrayLikeToArray(arr, len) {if (len == null || len > arr.length) len = arr.length;for (var i = 0, arr2 = new Array(len); i < len; i++) {arr2[i] = arr[i];}return arr2;}function ownKeys(object, enumerableOnly) {var keys = Object.keys(object);if (Object.getOwnPropertySymbols) {var symbols = Object.getOwnPropertySymbols(object);enumerableOnly && (symbols = symbols.filter(function (sym) {return Object.getOwnPropertyDescriptor(object, sym).enumerable;})), keys.push.apply(keys, symbols);}return keys;}function _objectSpread(target) {for (var i = 1; i < arguments.length; i++) {var source = null != arguments[i] ? arguments[i] : {};i % 2 ? ownKeys(Object(source), !0).forEach(function (key) {_defineProperty(target, key, source[key]);}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) {Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));});}return target;}function _defineProperty(obj, key, value) {if (key in obj) {Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true });} else {obj[key] = value;}return obj;}function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {try {var info = gen[key](arg);var value = info.value;} catch (error) {reject(error);return;}if (info.done) {resolve(value);} else {Promise.resolve(value).then(_next, _throw);}}function _asyncToGenerator(fn) {return function () {var self = this,args = arguments;return new Promise(function (resolve, reject) {var gen = fn.apply(self, args);function _next(value) {asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);}function _throw(err) {asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);}_next(undefined);});};}


var getPluginList = function getPluginList(c) {var isUpdate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
  var output = {
    asString: '',
    asArray: [],
    plugins: [],
    allPlugins: {} // this is used by taskRnvPluginAdd
  };

  var i = 1;

  Object.keys(c.files.rnv.pluginTemplates.configs).forEach(function (pk) {
    var plugins = c.files.rnv.pluginTemplates.configs[pk].pluginTemplates;
    Object.keys(plugins).forEach(function (k) {
      var p = plugins[k];

      var platforms = '';
      c.runtime.availablePlatforms.forEach(function (v) {
        if (p[v]) platforms += "".concat(v, ", ");
      });
      if (platforms.length) {
        platforms = platforms.slice(0, platforms.length - 2);
      }
      var installedPlugin = c.buildConfig &&
      c.buildConfig.plugins &&
      c.buildConfig.plugins[k];
      var installedString = installedPlugin ?
      (0, _logger.chalk)().yellow('installed') :
      (0, _logger.chalk)().green('not installed');
      if (isUpdate && installedPlugin) {
        output.plugins.push(k);
        var versionString;
        if (installedPlugin.version !== p.version) {
          versionString = "(".concat((0, _logger.chalk)().yellow(
          installedPlugin.version), ") => (").concat(
          (0, _logger.chalk)().green(p.version), ")");
        } else {
          versionString = "(".concat((0, _logger.chalk)().green(installedPlugin.version), ")");
        }
        output.asString += " [".concat(i, "]> ").concat((0, _logger.chalk)().bold(
        k), " ").concat(
        versionString, "\n");
        output.asArray.push({
          name: "".concat(k, " ").concat(versionString),
          value: k });

        output.allPlugins[k] = p; // this is used by taskRnvPluginAdd
        i++;
      } else if (!isUpdate) {
        output.plugins.push(k);
        output.asString += " [".concat(i, "]> ").concat((0, _logger.chalk)().bold(k), " (").concat((0, _logger.chalk)().grey(
        p.version), ") [").concat(
        platforms, "] - ").concat(installedString, "\n");
        output.asArray.push({
          name: "".concat(k, " (").concat((0, _logger.chalk)().grey(
          p.version), ") [").concat(
          platforms, "] - ").concat(installedString),
          value: k });

        output.allPlugins[k] = p; // this is used by taskRnvPluginAdd

        i++;
      }
      output.asArray.sort(function (a, b) {
        var aStr = a.name.toLowerCase();
        var bStr = b.name.toLowerCase();
        var com = 0;
        if (aStr > bStr) {
          com = 1;
        } else if (aStr < bStr) {
          com = -1;
        }
        return com;
      });
    });
  });

  return output;
};exports.getPluginList = getPluginList;


var _getPluginScope = function _getPluginScope(plugin) {
  if (typeof plugin === 'string' || plugin instanceof String) {
    if (plugin.startsWith('source:')) {
      return { scope: plugin.split(':').pop() };
    }
    return { npmVersion: plugin };
  }if (plugin !== null && plugin !== void 0 && plugin.source) {
    return { scope: plugin === null || plugin === void 0 ? void 0 : plugin.source };
  }
  return { scope: 'rnv' };
};

var getMergedPlugin = function getMergedPlugin(c, key) {var _c$buildConfig$plugin;
  (0, _logger.logDebug)("getMergedPlugin:".concat(key));

  var plugin = (_c$buildConfig$plugin = c.buildConfig.plugins) === null || _c$buildConfig$plugin === void 0 ? void 0 : _c$buildConfig$plugin[key];
  if (!plugin) return null;

  var scopes = [];
  var mergedPlugin = _getMergedPlugin(c, plugin, key, null, scopes);
  scopes.reverse();
  // if (!mergedPlugin.version) {
  //     logWarning(`Plugin ${key} has no version`);
  //     // return null;
  // }
  mergedPlugin._scopes = scopes;
  mergedPlugin._id = key;
  return mergedPlugin;
};exports.getMergedPlugin = getMergedPlugin;

var _getMergedPlugin = function _getMergedPlugin(c, plugin, pluginKey, parentScope, scopes, skipSanitize) {var _c$buildConfig$plugin2, _c$buildConfig$plugin3, _c$buildConfig$plugin4, _c$buildConfig;
  if (!plugin) {
    return {};
  }

  var _getPluginScope2 = _getPluginScope(plugin),scope = _getPluginScope2.scope,npmVersion = _getPluginScope2.npmVersion;
  if (scope === parentScope) return plugin;

  if (npmVersion) {
    return {
      version: npmVersion };

  }
  if (scope !== '' && !!scope && !((_c$buildConfig$plugin2 = c.buildConfig.pluginTemplates) !== null && _c$buildConfig$plugin2 !== void 0 && _c$buildConfig$plugin2[scope]) && !c.runtime._skipPluginScopeWarnings) {
    (0, _logger.logWarning)("Plugin ".concat(
    pluginKey, " is not recognized plugin in ").concat(scope, " scope"));

  } else if (scope) {
    scopes.push(scope);
  }

  var parentPlugin = _getMergedPlugin(c, (_c$buildConfig$plugin3 =
  c.buildConfig.pluginTemplates) === null || _c$buildConfig$plugin3 === void 0 ? void 0 : (_c$buildConfig$plugin4 = _c$buildConfig$plugin3[scope]) === null || _c$buildConfig$plugin4 === void 0 ? void 0 : _c$buildConfig$plugin4[pluginKey], pluginKey, scope, scopes, true);
  var currentPlugin = plugin;
  if (typeof plugin === 'string' || plugin instanceof String) {
    currentPlugin = {};
  }
  _constants.INJECTABLE_CONFIG_PROPS.forEach(function (v) {
    c.configPropsInjects[v] = (0, _common.getConfigProp)(c, c.platform, v);
  });
  if (currentPlugin.pluginDependencies) {
    Object.keys(currentPlugin.pluginDependencies).forEach(function (plugDepKey) {
      if (currentPlugin.pluginDependencies[plugDepKey] === 'source:self') {
        currentPlugin.pluginDependencies[plugDepKey] = "source:".concat(parentScope);
      }
    });
  }
  var mergedObj = (0, _fileutils.mergeObjects)(c, parentPlugin, currentPlugin, true, true);
  // IMPORTANT: only final top level merge should be sanitized
  var obj = skipSanitize ? mergedObj : (0, _fileutils.sanitizeDynamicProps)(mergedObj, {
    files: c.files,
    runtimeProps: c.runtime,
    props: (_c$buildConfig = c.buildConfig) === null || _c$buildConfig === void 0 ? void 0 : _c$buildConfig._refs,
    configProps: c.configPropsInjects });


  // IMPORTANT: only final top level merge should be sanitized
  var mergedPlugin = skipSanitize ? obj : (0, _fileutils.sanitizeDynamicProps)(obj, {
    files: c.files,
    runtimeProps: c.runtime,
    props: obj.props,
    configProps: c.configPropsInjects });


  return mergedPlugin;
};

var configurePlugins = /*#__PURE__*/function () {var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(c) {var _c$buildConfig2;var hasPackageChanged, newDeps, newDevDeps, _c$files$project$pack, dependencies, devDependencies;return regeneratorRuntime.wrap(function _callee$(_context) {while (1) {switch (_context.prev = _context.next) {case 0:
            (0, _logger.logTask)('configurePlugins');if (!

            c.program.skipDependencyCheck) {_context.next = 3;break;}return _context.abrupt("return", true);case 3:

            if (!c.files.project["package"].dependencies) {
              c.files.project["package"].dependencies = {};
            }

            hasPackageChanged = false;if ((_c$buildConfig2 =

            c.buildConfig) !== null && _c$buildConfig2 !== void 0 && _c$buildConfig2.plugins) {_context.next = 7;break;}return _context.abrupt("return");case 7:



            newDeps = {};
            newDevDeps = {};_c$files$project$pack =
            c.files.project["package"], dependencies = _c$files$project$pack.dependencies, devDependencies = _c$files$project$pack.devDependencies;
            Object.keys(c.buildConfig.plugins).forEach(function (k) {
              var plugin = getMergedPlugin(c, k);

              if (!plugin) {
                (0, _logger.logWarning)("Plugin with name ".concat(
                (0, _logger.chalk)().white(
                k), " does not exists in ReNative source:rnv scope. you need to define it manually here: ").concat(
                (0, _logger.chalk)().white(
                c.paths.project.builds.config)));


              } else if (dependencies && dependencies[k]) {
                if (plugin['no-active'] !== true && plugin['no-npm'] !== true) {
                  if (!plugin.version) {
                    if (!c.runtime._skipPluginScopeWarnings) {
                      (0, _logger.logInfo)("Plugin ".concat(k, " not ready yet (waiting for scope ").concat(plugin.scope, "). SKIPPING..."));
                    }
                  } else if (dependencies[k] !== plugin.version) {
                    if (k === 'renative' && c.runtime.isWrapper) {
                      (0, _logger.logWarning)(
                      "You're in ReNative wrapper mode. plugin renative will stay as local dep!");

                    } else {
                      (0, _logger.logWarning)("Version mismatch of dependency ".concat(
                      (0, _logger.chalk)().white(
                      k), " between:\n").concat(

                      (0, _logger.chalk)().white(c.paths.project["package"]), ": v(").concat((0, _logger.chalk)().red(dependencies[k]), ") and\n").concat(
                      (0, _logger.chalk)().white(c.paths.project.builds.config), ": v(").concat((0, _logger.chalk)().green(
                      plugin.version), ").\npackage.json will be overriden"));




                      hasPackageChanged = true;
                      newDeps[k] = plugin.version;
                    }
                  }
                }
              } else if (devDependencies && devDependencies[k]) {
                if (
                plugin['no-active'] !== true &&
                plugin['no-npm'] !== true)

                {
                  if (!plugin.version) {
                    if (!c.runtime._skipPluginScopeWarnings) {
                      (0, _logger.logInfo)("Plugin ".concat(k, " not ready yet (waiting for scope ").concat(plugin.scope, "). SKIPPING..."));
                    }
                  } else if (devDependencies[k] !== plugin.version) {
                    (0, _logger.logWarning)("Version mismatch of devDependency ".concat(
                    (0, _logger.chalk)().white(
                    k), " between package.json: v(").concat(
                    (0, _logger.chalk)().red(
                    devDependencies[k]), ") and plugins.json: v(").concat(
                    (0, _logger.chalk)().red(
                    plugin.version), "). package.json will be overriden"));


                    hasPackageChanged = true;
                    newDevDeps[k] = plugin.version;
                  }
                }
              } else if (
              plugin['no-active'] !== true &&
              plugin['no-npm'] !== true)
              {
                // Dependency does not exists
                if (plugin.version) {
                  (0, _logger.logInfo)("Missing dependency ".concat(
                  (0, _logger.chalk)().white(k), " v(").concat((0, _logger.chalk)().red(
                  plugin.version), ") in package.json. INSTALLING...DONE"));



                  hasPackageChanged = true;
                  newDeps[k] = plugin.version;
                }
              }

              if (plugin && plugin.npm) {
                Object.keys(plugin.npm).forEach(function (npmKey) {
                  var npmDep = plugin.npm[npmKey];
                  // IMPORTANT: Do not override top level override with plugin.npm ones
                  var topLevelPlugin = getMergedPlugin(c, npmKey);
                  if (topLevelPlugin && (topLevelPlugin === null || topLevelPlugin === void 0 ? void 0 : topLevelPlugin.version) !== npmDep) {
                    (0, _logger.logInfo)("RNV Detected plugin dependency conflict. ".concat((0, _logger.chalk)().cyan('RESOLVING...'), "\n- ").concat(
                    npmKey, "@").concat((0, _logger.chalk)().green(topLevelPlugin === null || topLevelPlugin === void 0 ? void 0 : topLevelPlugin.version), " ").concat((0, _logger.chalk)().cyan('<='), "\n- ").concat(
                    k, " .npm sub dependencies:\n   |- ").concat(
                    npmKey, "@").concat((0, _logger.chalk)().red(npmDep)));
                  } else if (!dependencies[npmKey]) {
                    (0, _logger.logInfo)("Plugin ".concat(
                    (0, _logger.chalk)().white(
                    k), " requires npm dependency ").concat(
                    (0, _logger.chalk)().white(
                    npmKey), ". INSTALLING...DONE"));


                    newDeps[npmKey] = npmDep;
                    hasPackageChanged = true;
                  } else if (dependencies[npmKey] !== npmDep) {
                    (0, _logger.logWarning)("Plugin ".concat(
                    (0, _logger.chalk)().white(
                    k), " npm dependency ").concat(
                    (0, _logger.chalk)().white(npmKey), " mismatch (").concat((0, _logger.chalk)().red(
                    dependencies[npmKey]), ") => (").concat(
                    (0, _logger.chalk)().green(
                    npmDep), ") .updating npm dependency in your package.json"));


                    newDeps[npmKey] = npmDep;
                    hasPackageChanged = true;
                  }
                });
              }
            });

            // c.runtime.skipPackageUpdate only reflects rnv version mismatch. should not prevent updating other deps
            if (hasPackageChanged /*! c.runtime.skipPackageUpdate */) {
              _updatePackage(c, { dependencies: newDeps, devDependencies: newDevDeps });
            }return _context.abrupt("return",

            true);case 13:case "end":return _context.stop();}}}, _callee);}));return function configurePlugins(_x) {return _ref.apply(this, arguments);};}();exports.configurePlugins = configurePlugins;


var _updatePackage = function _updatePackage(c, override) {
  var newPackage = (0, _deepmerge["default"])(c.files.project["package"], override);
  (0, _configManager.writeRenativeConfigFile)(c, c.paths.project["package"], newPackage);
  c.files.project["package"] = newPackage;
  c._requiresNpmInstall = true;
};

var resolvePluginDependants = /*#__PURE__*/function () {var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(c) {var plugins, pluginKeys, i, key;return regeneratorRuntime.wrap(function _callee2$(_context2) {while (1) {switch (_context2.prev = _context2.next) {case 0:
            (0, _logger.logTask)('resolvePluginDependants');
            plugins = c.buildConfig.plugins;if (!

            plugins) {_context2.next = 12;break;}
            pluginKeys = Object.keys(plugins);
            i = 0;case 5:if (!(i < pluginKeys.length)) {_context2.next = 12;break;}
            key = pluginKeys[i];_context2.next = 9;return (
              _resolvePluginDependencies(c, key, plugins[key], null));case 9:i++;_context2.next = 5;break;case 12:return _context2.abrupt("return",



            true);case 13:case "end":return _context2.stop();}}}, _callee2);}));return function resolvePluginDependants(_x2) {return _ref2.apply(this, arguments);};}();exports.resolvePluginDependants = resolvePluginDependants;


var _resolvePluginDependencies = /*#__PURE__*/function () {var _ref3 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3(c, key, keyScope, parentKey) {var pluginTemplates, plugin, _getPluginScope3, scope, _pluginTemplates$scop, depPlugin, _yield$inquirerPrompt, confirm, deps, depsKeys, i, depKey, depScope;return regeneratorRuntime.wrap(function _callee3$(_context3) {while (1) {switch (_context3.prev = _context3.next) {case 0:
            // IMPORTANT: Do not cache this valuse as they need to be refreshed every
            // round in case new plugin has been installed and c.buildConfig generated
            pluginTemplates = c.buildConfig.pluginTemplates;
            plugin = getMergedPlugin(c, key);_getPluginScope3 =

            _getPluginScope(keyScope), scope = _getPluginScope3.scope;if (

            plugin) {_context3.next = 16;break;}
            depPlugin = (_pluginTemplates$scop = pluginTemplates[scope]) === null || _pluginTemplates$scop === void 0 ? void 0 : _pluginTemplates$scop[key];if (!

            depPlugin) {_context3.next = 13;break;}_context3.next = 8;return (

              (0, _prompt.inquirerPrompt)({
                type: 'confirm',
                message: "Install ".concat(key, "?"),
                warningMessage: "Plugin ".concat((0, _logger.chalk)().white(key), " source:").concat(
                (0, _logger.chalk)().white(scope), " required by ").concat((0, _logger.chalk)().red(parentKey), " is not installed") }));case 8:_yield$inquirerPrompt = _context3.sent;confirm = _yield$inquirerPrompt.confirm;

            if (confirm) {
              c.files.project.config.plugins[key] = "source:".concat(scope);
              (0, _configManager.writeRenativeConfigFile)(c, c.paths.project.config, c.files.project.config);
              (0, _logger.logSuccess)("Plugin ".concat(key, " sucessfully installed"));
              c._requiresNpmInstall = true;
            }_context3.next = 14;break;case 13:

            (0, _logger.logWarning)("Plugin ".concat((0, _logger.chalk)().white(parentKey), " requires ").concat(
            (0, _logger.chalk)().red(key), " which is not available in your system"));case 14:_context3.next = 16;break;case 16:





            deps = plugin === null || plugin === void 0 ? void 0 : plugin.pluginDependencies;if (!
            deps) {_context3.next = 28;break;}
            depsKeys = Object.keys(deps);
            i = 0;case 20:if (!(i < depsKeys.length)) {_context3.next = 28;break;}
            depKey = depsKeys[i];
            depScope = deps[depKey];_context3.next = 25;return (
              _resolvePluginDependencies(c, depKey, depScope, key));case 25:i++;_context3.next = 20;break;case 28:return _context3.abrupt("return",


            true);case 29:case "end":return _context3.stop();}}}, _callee3);}));return function _resolvePluginDependencies(_x3, _x4, _x5, _x6) {return _ref3.apply(this, arguments);};}();


var parsePlugins = function parsePlugins(c, platform, pluginCallback, ignorePlatformObjectCheck) {
  (0, _logger.logTask)('parsePlugins');
  if (c.buildConfig) {
    var includedPlugins = (0, _common.getConfigProp)(
    c,
    platform,
    'includedPlugins',
    []);

    var excludedPlugins = (0, _common.getConfigProp)(
    c,
    platform,
    'excludedPlugins',
    []);

    if (includedPlugins) {
      var plugins = c.buildConfig.plugins;

      if (plugins) {
        var totalIncludedPlugins = 0;
        Object.keys(plugins).forEach(function (key) {
          if (
          (includedPlugins.includes('*') ||
          includedPlugins.includes(key)) &&
          !excludedPlugins.includes(key))
          {
            var plugin = getMergedPlugin(c, key);
            if (plugin) {
              var pluginPlat = plugin[platform];
              if (ignorePlatformObjectCheck) {
                totalIncludedPlugins++;
                pluginCallback(plugin, pluginPlat, key);
              } else if (pluginPlat) {
                if (
                plugin['no-active'] !== true &&
                plugin.enabled !== false &&
                pluginPlat.enabled !== false)
                {
                  if (plugin.deprecated) {
                    (0, _logger.logWarning)(plugin.deprecated);
                  }
                  if (pluginCallback) {
                    totalIncludedPlugins++;
                    pluginCallback(plugin, pluginPlat, key);
                  }
                } else {
                  (0, _logger.logWarning)("Plugin ".concat(
                  key, " is marked disabled. skipping."));

                }
              }
            }
          }
        });
        if (totalIncludedPlugins === 0) {
          (0, _logger.logWarning)("Found plugins in your app but non are included. are you sure you added ".concat(
          (0, _logger.chalk)().white('includedPlugins'), " in your renative.json config?"));

        }
      } else {
        (0, _logger.logError)("You have no plugins defined in ".concat(
        (0, _logger.chalk)().white(
        c.paths.project.builds.config)));


      }
    } else {
      (0, _logger.logWarning)("You haven't included any ".concat(
      (0, _logger.chalk)().white(
      '{ common: { includedPlugins: [] }}'), " in your ").concat(
      (0, _logger.chalk)().white(
      c.paths.appConfig.config), ". Your app might not work correctly"));


    }
  }
};exports.parsePlugins = parsePlugins;

var loadPluginTemplates = /*#__PURE__*/function () {var _ref4 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee4(c) {var _c$files$project$conf, _c$files$project$conf2;var customPluginTemplates, missingDeps, dependencies, hasPackageChanged;return regeneratorRuntime.wrap(function _callee4$(_context4) {while (1) {switch (_context4.prev = _context4.next) {case 0:
            (0, _logger.logTask)('loadPluginTemplates');
            c.files.rnv.pluginTemplates.config = (0, _fileutils.readObjectSync)(
            c.paths.rnv.pluginTemplates.config);


            c.files.rnv.pluginTemplates.configs = {
              rnv: c.files.rnv.pluginTemplates.config };


            c.paths.rnv.pluginTemplates.dirs = { rnv: c.paths.rnv.pluginTemplates.dir };

            customPluginTemplates = (_c$files$project$conf = c.files.project.config) === null || _c$files$project$conf === void 0 ? void 0 : (_c$files$project$conf2 = _c$files$project$conf.paths) === null || _c$files$project$conf2 === void 0 ? void 0 : _c$files$project$conf2.pluginTemplates;
            missingDeps = _parsePluginTemplateDependencies(c, customPluginTemplates);if (!
            missingDeps.length) {_context4.next = 20;break;}
            dependencies = c.files.project["package"].dependencies;
            hasPackageChanged = false;
            missingDeps.forEach(function (dep) {
              var plugin = getMergedPlugin(c, dep);
              if (plugin) {
                hasPackageChanged = true;
                dependencies[dep] = plugin.version;
              } else {
                // Unresolved Plugin
              }
            });
            // CHECK IF paths.pluginTemplates SCOPES are INSTALLED
            // This must be installed to avoid scoped plugins errors
            if (!hasPackageChanged) {_context4.next = 19;break;}
            _updatePackage(c, { dependencies: dependencies });
            (0, _logger.logInfo)('Found missing dependency scopes. INSTALLING...');_context4.next = 15;return (
              (0, _npmUtils.installPackageDependencies)(c));case 15:_context4.next = 17;return (
              loadPluginTemplates(c));case 17:_context4.next = 20;break;case 19:

            missingDeps.forEach(function (npmDep) {
              (0, _logger.logWarning)("Plugin scope ".concat(npmDep, " does not exists in package.json."));
            });case 20:return _context4.abrupt("return",


            true);case 21:case "end":return _context4.stop();}}}, _callee4);}));return function loadPluginTemplates(_x7) {return _ref4.apply(this, arguments);};}();exports.loadPluginTemplates = loadPluginTemplates;


var _parsePluginTemplateDependencies = function _parsePluginTemplateDependencies(c, customPluginTemplates) {var scope = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'root';
  (0, _logger.logTask)('_parsePluginTemplateDependencies', "scope:".concat(scope));
  var missingDeps = [];
  if (customPluginTemplates) {
    Object.keys(customPluginTemplates).forEach(function (k) {
      var val = customPluginTemplates[k];
      if (val.npm) {var _c$files$project$pack2, _c$files$project$pack3;
        var npmDep = ((_c$files$project$pack2 = c.files.project["package"]) === null || _c$files$project$pack2 === void 0 ? void 0 : _c$files$project$pack2.dependencies[val.npm]) || ((_c$files$project$pack3 =
        c.files.project["package"]) === null || _c$files$project$pack3 === void 0 ? void 0 : _c$files$project$pack3.devDependencies[val.npm]);

        if (npmDep) {
          var ptPath;
          if (npmDep.startsWith('file:')) {
            ptPath = _path["default"].join(
            c.paths.project.dir,
            npmDep.replace('file:', ''),
            val.path || '');

          } else {
            // ptPath = path.join(c.paths.project.nodeModulesDir, val.npm, val.path || '');
            ptPath = "".concat((0, _resolve.doResolve)(val.npm), "/").concat(val.path);
          }

          var ptConfig = _path["default"].join(
          ptPath,
          _constants.RENATIVE_CONFIG_PLUGINS_NAME);

          c.paths.rnv.pluginTemplates.dirs[k] = ptPath;
          if ((0, _fileutils.fsExistsSync)(ptConfig)) {
            c.files.rnv.pluginTemplates.configs[k] = (0, _fileutils.readObjectSync)(
            ptConfig);

            _parsePluginTemplateDependencies(c,
            c.files.rnv.pluginTemplates.configs[k].pluginTemplateDependencies,
            k);
          } else {
            (0, _logger.logWarning)("Plugin scope ".concat(val.npm, " is not installed yet."));
          }
        } else {
          // logWarning(`Plugin scope ${val.npm} does not exists in package.json.`);
          missingDeps.push(val.npm);
        }
      }
    });
  }
  return missingDeps;
};

var getCleanRegExString = function getCleanRegExString(str) {return str.
  replace(/\(/g, '\\(').
  replace(/\)/g, '\\)').
  replace(/\^/g, '\\^').
  replace(/\?/g, '\\?').
  replace(/\|/g, '\\|').
  replace(/\*/g, '\\*').
  replace(/\|/g, '\\|').
  replace(/\[/g, '\\[').
  replace(/\]/g, '\\]').
  replace(/\{/g, '\\{').
  replace(/\}/g, '\\}').
  replace(/\+/g, '\\+').
  replace(/ /g, ' {1,}');};

var _overridePlugin = function _overridePlugin(c, pluginsPath, dir) {
  var source = _path["default"].resolve(pluginsPath, dir, 'overrides');
  var dest = (0, _resolve.doResolve)(dir, false);
  if (!dest) return;

  var plugin = getMergedPlugin(c, dir);
  var flavourSource;
  if (plugin) {
    flavourSource = _path["default"].resolve(
    pluginsPath,
    dir, "overrides@".concat(
    plugin.version));

  }

  if (flavourSource && (0, _fileutils.fsExistsSync)(flavourSource)) {
    (0, _fileutils.copyFolderContentsRecursiveSync)(flavourSource, dest, false);
  } else if ((0, _fileutils.fsExistsSync)(source)) {
    (0, _fileutils.copyFolderContentsRecursiveSync)(source, dest, false);
    // fsReaddirSync(pp).forEach((dir) => {
    //     copyFileSync(path.resolve(pp, file), path.resolve(c.paths.project.dir, 'node_modules', dir));
    // });
  } else {
    (0, _logger.logDebug)("Your plugin configuration has no override path ".concat(
    (0, _logger.chalk)().white(
    source), ". skipping folder override action"));


  }

  var overridePath;
  if (plugin.version) {
    var pluginVerArr = plugin.version.split('.');
    var pluginVersions = [];
    var prevVersion;
    pluginVerArr.forEach(function (v) {
      if (prevVersion) {
        prevVersion = "".concat(prevVersion, ".").concat(v);
      } else {
        prevVersion = "".concat(v);
      }
      pluginVersions.push(prevVersion);
    });
    pluginVersions.reverse();


    for (var i = 0; i < pluginVersions.length; i++) {
      overridePath = _path["default"].resolve(pluginsPath, dir, "overrides@".concat(pluginVersions[i], ".json"));
      if ((0, _fileutils.fsExistsSync)(overridePath)) {
        break;
      }
    }
  }

  if (!(0, _fileutils.fsExistsSync)(overridePath)) {
    overridePath = _path["default"].resolve(pluginsPath, dir, 'overrides.json');
  }
  var overrideConfig = (0, _fileutils.readObjectSync)(overridePath);
  var overrides = overrideConfig === null || overrideConfig === void 0 ? void 0 : overrideConfig.overrides;
  if (overrides) {
    Object.keys(overrides).forEach(function (k) {
      var ovDir = _path["default"].join(dest, k);
      var override = overrides[k];
      if ((0, _fileutils.fsExistsSync)(ovDir)) {
        if ((0, _fileutils.fsLstatSync)(ovDir).isDirectory()) {
          (0, _logger.logWarning)(
          'overrides.json: Directories not supported yet. specify path to actual file');

        } else {
          overrideFileContents(ovDir, override, overridePath);
        }
      }
    });
  }
};

var overrideFileContents = function overrideFileContents(dest, override) {var overridePath = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';
  if ((0, _fileutils.fsExistsSync)(dest)) {
    var fileToFix = (0, _fileutils.fsReadFileSync)(dest).toString();
    var foundRegEx = false;
    var failTerms = [];
    Object.keys(override).forEach(function (fk) {
      var regEx = new RegExp("".concat(getCleanRegExString(fk)), 'g');
      var count = (fileToFix.match(regEx) || []).length;

      var overrided = override[fk];
      var regEx2 = new RegExp(getCleanRegExString(overrided), 'g');
      var count2 = (fileToFix.match(regEx2) || []).length;
      if (!count) {
        if (!count2) {
          failTerms.push(fk);
        } else {
          foundRegEx = true;
        }
      } else {
        foundRegEx = true;
        fileToFix = fileToFix.replace(regEx, override[fk]);
      }
    });
    if (!foundRegEx) {
      failTerms.forEach(function (term) {
        if (!fileToFix.includes(override[term])) {
          (0, _logger.logWarning)("No Match found in ".concat((0, _logger.chalk)().red(
          dest), " for expression: ").concat(
          (0, _logger.chalk)().red(term), ".\nConsider update or removal of ").concat(
          (0, _logger.chalk)().white(overridePath)));
        }
      });
    }
    (0, _fileutils.fsWriteFileSync)(dest, fileToFix);
  } else {
    (0, _logger.logDebug)("overrideFileContents Warning: path does not exists ".concat(dest));
  }
};exports.overrideFileContents = overrideFileContents;

var installPackageDependenciesAndPlugins = /*#__PURE__*/function () {var _ref5 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee5(c) {return regeneratorRuntime.wrap(function _callee5$(_context5) {while (1) {switch (_context5.prev = _context5.next) {case 0:
            (0, _logger.logTask)('installPackageDependenciesAndPlugins');_context5.next = 3;return (

              (0, _npmUtils.installPackageDependencies)(c));case 3:_context5.next = 5;return (
              overrideTemplatePlugins(c));case 5:_context5.next = 7;return (
              _checkForPluginDependencies(c));case 7:case "end":return _context5.stop();}}}, _callee5);}));return function installPackageDependenciesAndPlugins(_x8) {return _ref5.apply(this, arguments);};}();exports.installPackageDependenciesAndPlugins = installPackageDependenciesAndPlugins;


var _getPluginConfiguration = function _getPluginConfiguration(c, pluginName) {
  var renativePluginPath;
  try {
    renativePluginPath = require.resolve("".concat(pluginName, "/renative.plugin.json"), { paths: [c.paths.project.dir] });
  } catch (_unused) {
    //
  }

  if (renativePluginPath) {
    return (0, _fileutils.readObjectSync)(renativePluginPath);
  }
  return null;
};

var _checkForPluginDependencies = /*#__PURE__*/function () {var _ref6 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee6(c) {var toAdd, install, answer;return regeneratorRuntime.wrap(function _callee6$(_context6) {while (1) {switch (_context6.prev = _context6.next) {case 0:
            toAdd = {};
            Object.keys(c.buildConfig.plugins).forEach(function (pluginName) {
              var renativePluginConfig = _getPluginConfiguration(c, pluginName);

              if (renativePluginConfig !== null && renativePluginConfig !== void 0 && renativePluginConfig.plugins) {
                // we have dependencies for this plugin
                Object.keys(renativePluginConfig.plugins).forEach(function (p) {var _c$buildConfig$plugin5;
                  if (!c.buildConfig.plugins[p] && ((_c$buildConfig$plugin5 = c.buildConfig.plugins[pluginName].plugins) === null || _c$buildConfig$plugin5 === void 0 ? void 0 : _c$buildConfig$plugin5[p]) !== null) {
                    (0, _logger.logWarning)("Plugin ".concat(p, " is not installed yet."));
                    toAdd[p] = renativePluginConfig.plugins[p];
                    c.buildConfig.plugins[p] = renativePluginConfig.plugins[p];
                  }
                });
              }
            });if (!

            Object.keys(toAdd).length) {_context6.next = 20;break;}
            // ask the user
            install = false;if (
            c.program.ci) {_context6.next = 11;break;}_context6.next = 7;return (
              (0, _prompt.inquirerPrompt)({
                type: 'confirm',
                message: "Install ".concat(Object.keys(toAdd).join(', '), "?"),
                warningMessage: "One or more dependencies are not installed: ".concat((0, _logger.chalk)().white(Object.keys(toAdd).join(', '))) }));case 7:answer = _context6.sent;

            install = answer.confirm;_context6.next = 13;break;case 11:

            (0, _logger.logWarning)('CI detected. Automatically installing dependencies');
            install = true;case 13:if (!


            install) {_context6.next = 20;break;}
            c.files.project.config.plugins = _objectSpread(_objectSpread({},
            c.files.project.config.plugins),
            toAdd);

            (0, _configManager.writeRenativeConfigFile)(c, c.paths.project.config, c.files.project.config);_context6.next = 18;return (
              configurePlugins(c));case 18:_context6.next = 20;return (
              installPackageDependenciesAndPlugins(c));case 20:case "end":return _context6.stop();}}}, _callee6);}));return function _checkForPluginDependencies(_x9) {return _ref6.apply(this, arguments);};}();




var overrideTemplatePlugins = /*#__PURE__*/function () {var _ref7 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee7(c) {var rnvPluginsDirs, appPluginDirs, appBasePluginDir;return regeneratorRuntime.wrap(function _callee7$(_context7) {while (1) {switch (_context7.prev = _context7.next) {case 0:
            (0, _logger.logTask)('overrideTemplatePlugins');

            rnvPluginsDirs = c.paths.rnv.pluginTemplates.dirs;
            appPluginDirs = c.paths.appConfig.pluginDirs;
            appBasePluginDir = c.paths.project.appConfigBase.pluginsDir;
            parsePlugins(c, c.platform, function (plugin, pluginPlat, key) {var _plugin$_scopes;
              if (plugin !== null && plugin !== void 0 && (_plugin$_scopes = plugin._scopes) !== null && _plugin$_scopes !== void 0 && _plugin$_scopes.length) {
                plugin._scopes.forEach(function (pluginScope) {
                  var pluginOverridePath = rnvPluginsDirs[pluginScope];
                  if (pluginOverridePath) {
                    _overridePlugin(c, pluginOverridePath, key);
                  }
                });
              }

              if (appBasePluginDir) {
                _overridePlugin(c, appBasePluginDir, key);
              }
              if (appPluginDirs) {
                for (var k = 0; k < appPluginDirs.length; k++) {
                  _overridePlugin(c, appPluginDirs[k], key);
                }
              }
            }, true);return _context7.abrupt("return",
            true);case 6:case "end":return _context7.stop();}}}, _callee7);}));return function overrideTemplatePlugins(_x10) {return _ref7.apply(this, arguments);};}();exports.overrideTemplatePlugins = overrideTemplatePlugins;


var copyTemplatePluginsSync = function copyTemplatePluginsSync(c) {
  var platform = c.platform;
  var destPath = _path["default"].join((0, _common.getAppFolder)(c));

  (0, _logger.logTask)('copyTemplatePluginsSync', "(".concat(destPath, ")"));


  parsePlugins(c, platform, function (plugin, pluginPlat, key) {
    var objectInject = _toConsumableArray(c.configPropsInjects);
    if (plugin.props) {
      Object.keys(plugin.props).forEach(function (v) {
        objectInject.push({
          pattern: "{{props.".concat(v, "}}"),
          override: plugin.props[v] });

      });
    }
    // FOLDER MERGES FROM PROJECT CONFIG PLUGIN
    var sourcePathRnvPlugin = (0, _common.getBuildsFolder)(
    c,
    platform,
    _path["default"].join(c.paths.rnv.pluginTemplates.dir, key));

    (0, _fileutils.copyFolderContentsRecursiveSync)(sourcePathRnvPlugin, destPath, true, false, false, objectInject);

    // FOLDER MERGES FROM PROJECT CONFIG PLUGIN
    var sourcePath3 = (0, _common.getBuildsFolder)(
    c,
    platform,
    _path["default"].join(c.paths.project.appConfigBase.dir, "plugins/".concat(key)));

    (0, _fileutils.copyFolderContentsRecursiveSync)(sourcePath3, destPath, true, false, false, objectInject);

    // FOLDER MERGERS FROM PROJECT CONFIG (PRIVATE)
    var sourcePath3secLegacy = (0, _common.getBuildsFolder)(
    c,
    platform,
    _path["default"].join(
    c.paths.workspace.project.appConfigBase.dir_LEGACY, "plugins/".concat(
    key)));


    (0, _fileutils.copyFolderContentsRecursiveSync)(sourcePath3secLegacy, destPath, true, false, false, objectInject);

    // FOLDER MERGES FROM PROJECT CONFIG PLUGIN (PRIVATE)
    var sourcePath3sec = (0, _common.getBuildsFolder)(
    c,
    platform,
    _path["default"].join(
    c.paths.workspace.project.appConfigBase.dir, "plugins/".concat(
    key)));


    (0, _fileutils.copyFolderContentsRecursiveSync)(sourcePath3sec, destPath, true, false, false, objectInject);

    if ((0, _fileutils.fsExistsSync)(sourcePath3secLegacy)) {
      (0, _logger.logWarning)("Path: ".concat((0, _logger.chalk)().red(sourcePath3secLegacy), " is DEPRECATED.\n    Move your files to: ").concat(
      (0, _logger.chalk)().white(sourcePath3sec), " instead"));
    }

    // FOLDER MERGES FROM APP CONFIG PLUGIN
    var sourcePath2 = (0, _common.getBuildsFolder)(
    c,
    platform,
    _path["default"].join(c.paths.appConfig.dir, "plugins/".concat(key)));

    (0, _fileutils.copyFolderContentsRecursiveSync)(sourcePath2, destPath, true, false, false, objectInject);

    // FOLDER MERGES FROM APP CONFIG PLUGIN (PRIVATE)
    var sourcePath2sec = (0, _common.getBuildsFolder)(
    c,
    platform,
    _path["default"].join(c.paths.workspace.appConfig.dir, "plugins/".concat(key)));

    (0, _fileutils.copyFolderContentsRecursiveSync)(sourcePath2sec, destPath, true, false, false, objectInject);

    // FOLDER MERGES FROM SCOPED PLUGIN TEMPLATES
    Object.keys(c.paths.rnv.pluginTemplates.dirs).forEach(function (pathKey) {
      if (pathKey !== 'rnv') {
        var pluginTemplatePath = c.paths.rnv.pluginTemplates.dirs[pathKey];

        var sourcePath4sec = (0, _common.getBuildsFolder)(
        c,
        platform,
        _path["default"].join(pluginTemplatePath, key));

        (0, _fileutils.copyFolderContentsRecursiveSync)(sourcePath4sec, destPath, true, false, false, objectInject);
      }
    });
  });
};exports.copyTemplatePluginsSync = copyTemplatePluginsSync;

var sanitizePluginPath = function sanitizePluginPath(str, name, mandatory, options) {
  var newStr = str;
  try {
    if (str !== null && str !== void 0 && str.replace) {
      newStr = str.replace('{{PLUGIN_ROOT}}', (0, _resolve.doResolve)(name, mandatory, options));
    }
  } catch (e) {
    // Ignore
  }
  return newStr;
};exports.sanitizePluginPath = sanitizePluginPath;

var includesPluginPath = function includesPluginPath(str) {
  if (str !== null && str !== void 0 && str.includes) {
    return str.includes('{{PLUGIN_ROOT}}');
  }
  return false;
};exports.includesPluginPath = includesPluginPath;

var getLocalRenativePlugin = function getLocalRenativePlugin() {return {
    version: 'file:../packages/renative',
    webpack: {
      modulePaths: [],
      moduleAliases: {
        renative: {
          projectPath: 'packages/renative' } } } };};exports.getLocalRenativePlugin = getLocalRenativePlugin;






var getModuleConfigs = function getModuleConfigs(c, primaryKey) {
  var modulePaths = [];
  var moduleAliases = {};

  var doNotResolveModulePaths = [];

  // PLUGINS
  parsePlugins(c, c.platform, function (plugin, pluginPlat, key) {
    var webpackConfig = plugin[primaryKey] || plugin.webpack || plugin.webpackConfig;

    if (webpackConfig) {
      if (webpackConfig.modulePaths) {
        if (webpackConfig.modulePaths === false) {
          // ignore
        } else if (webpackConfig.modulePaths === true) {
          modulePaths.push("node_modules/".concat(key));
        } else {
          webpackConfig.modulePaths.forEach(function (v) {
            if (typeof v === 'string') {
              modulePaths.push(v);
            } else if (includesPluginPath(v.projectPath)) {
              doNotResolveModulePaths.push(sanitizePluginPath(v.projectPath, key));
            } else if (v !== null && v !== void 0 && v.projectPath) {
              doNotResolveModulePaths.push(_path["default"].join(c.paths.project.dir, v.projectPath));
            }
          });
        }
      }
      if (webpackConfig.moduleAliases) {
        if (webpackConfig.moduleAliases === true) {
          moduleAliases[key] = (0, _resolve.doResolvePath)(key, true, {}, c.paths.project.nodeModulesDir);
        } else {
          Object.keys(webpackConfig.moduleAliases).forEach(function (aKey) {
            var mAlias = webpackConfig.moduleAliases[aKey];
            if (typeof mAlias === 'string') {
              moduleAliases[key] = (0, _resolve.doResolvePath)(mAlias, true, {}, c.paths.project.nodeModulesDir);
            } else if (mAlias.path) {
              moduleAliases[key] = _path["default"].join(c.paths.project.dir, mAlias.path);
            } else if (includesPluginPath(mAlias.projectPath)) {
              moduleAliases[key] = sanitizePluginPath(mAlias.projectPath, key);
            } else if (mAlias.projectPath) {
              moduleAliases[key] = _path["default"].join(c.paths.project.dir, mAlias.projectPath);
            }
          });
        }
      }
    }
  }, true);

  var moduleAliasesArray = [];
  Object.keys(moduleAliases).forEach(function (key) {
    moduleAliasesArray.push("".concat(key, ":").concat(moduleAliases[key]));
  });

  modulePaths = modulePaths.
  map(function (v) {return (0, _resolve.doResolvePath)(v, true, {}, c.paths.project.dir);}).
  concat(doNotResolveModulePaths).
  concat([c.paths.project.assets.dir]).
  filter(Boolean);


  return { modulePaths: modulePaths, moduleAliases: moduleAliases, moduleAliasesArray: moduleAliasesArray };
};exports.getModuleConfigs = getModuleConfigs;
//# sourceMappingURL=index.js.map