"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports.listAndSelectNpmVersion = exports.jetifyIfRequired = exports.installPackageDependencies = exports.cleanNodeModules = exports.checkNpxIsInstalled = exports.checkIfProjectAndNodeModulesExists = exports.checkAndCreateProjectPackage = exports.areNodeModulesInstalled = void 0;
var _path = _interopRequireDefault(require("path"));
var _inquirer = _interopRequireDefault(require("inquirer"));
var _exec = require("./exec");
var _fileutils = require("./fileutils");
var _logger = require("./logger");
var _constants = require("../constants");
var _resolve = require("./resolve");

var _prompt = require("../../cli/prompt");function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { "default": obj };}function _slicedToArray(arr, i) {return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();}function _nonIterableRest() {throw new TypeError("Invalid attempt to destructure 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 _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 _iterableToArrayLimit(arr, i) {var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];if (_i == null) return;var _arr = [];var _n = true;var _d = false;var _s, _e;try {for (_i = _i.call(arr); !(_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"] != null) _i["return"]();} finally {if (_d) throw _e;}}return _arr;}function _arrayWithHoles(arr) {if (Array.isArray(arr)) return arr;}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 packageJsonIsValid = function packageJsonIsValid(c) {
  if (!(0, _fileutils.fsExistsSync)(c.paths.project["package"])) return false;
  var pkg = (0, _fileutils.readObjectSync)(c.paths.project["package"]);
  if (!pkg) return false;
  // yarn add creates a package.json with only dependencies, that is not valid
  if (Object.keys(pkg).length === 1 && Object.keys(pkg)[0] === 'dependencies') return false;
  return true;
};

var checkNpxIsInstalled = /*#__PURE__*/function () {var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {var _inquirerPrompt, confirm;return regeneratorRuntime.wrap(function _callee$(_context) {while (1) {switch (_context.prev = _context.next) {case 0:
            (0, _logger.logTask)('checkNpxIsInstalled');if (
            (0, _exec.commandExistsSync)('npx')) {_context.next = 9;break;}
            (0, _logger.logWarning)('npx is not installed, please install it before running this command');_inquirerPrompt =

            (0, _prompt.inquirerPrompt)({
              type: 'confirm',
              message: 'Do you want to install npx it now?' }), confirm = _inquirerPrompt.confirm;if (!


            confirm) {_context.next = 8;break;}_context.next = 7;return (
              (0, _exec.executeAsync)('npm install -g npx'));case 7:return _context.abrupt("return",
            true);case 8:throw (


              new Error('npx is not installed'));case 9:case "end":return _context.stop();}}}, _callee);}));return function checkNpxIsInstalled() {return _ref.apply(this, arguments);};}();exports.checkNpxIsInstalled = checkNpxIsInstalled;



var checkAndCreateProjectPackage = /*#__PURE__*/function () {var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(c) {var _c$files$project$conf, _c$files$project$conf2, _c$files$project$conf3, _c$files$project$conf4, _c$files$project$conf5, packageName, version, templateName, rnvVersion, pkgJson, pkgJsonStringClean;return regeneratorRuntime.wrap(function _callee2$(_context2) {while (1) {switch (_context2.prev = _context2.next) {case 0:
            (0, _logger.logTask)('checkAndCreateProjectPackage');

            if (!packageJsonIsValid(c)) {
              (0, _logger.logInfo)("Your ".concat(
              c.paths.project["package"], " is missing. CREATING...DONE"));


              packageName = c.files.project.config.projectName ||
              c.paths.project.dir.split('/').pop();
              version = ((_c$files$project$conf = c.files.project.config.defaults) === null || _c$files$project$conf === void 0 ? void 0 : (_c$files$project$conf2 = _c$files$project$conf["package"]) === null || _c$files$project$conf2 === void 0 ? void 0 : _c$files$project$conf2.version) || '0.1.0';
              templateName = (_c$files$project$conf3 = c.files.project.config) === null || _c$files$project$conf3 === void 0 ? void 0 : _c$files$project$conf3.currentTemplate;
              if (!templateName) {
                (0, _logger.logWarning)('You are missing currentTemplate in your renative.json');
              }
              rnvVersion = c.files.rnv["package"].version;

              pkgJson = {};
              pkgJson.name = packageName;
              pkgJson.version = version;
              pkgJson.dependencies = {
                renative: rnvVersion };

              pkgJson.devDependencies = {
                rnv: rnvVersion };

              pkgJson.devDependencies[templateName] = (_c$files$project$conf4 = c.files.project.config) === null || _c$files$project$conf4 === void 0 ? void 0 : (_c$files$project$conf5 = _c$files$project$conf4.templates[templateName]) === null || _c$files$project$conf5 === void 0 ? void 0 : _c$files$project$conf5.version;
              pkgJsonStringClean = JSON.stringify(pkgJson, null, 2);
              (0, _fileutils.fsWriteFileSync)(c.paths.project["package"], pkgJsonStringClean);
            }

            (0, _fileutils.loadFile)(c.files.project, c.paths.project, 'package');return _context2.abrupt("return",

            true);case 4:case "end":return _context2.stop();}}}, _callee2);}));return function checkAndCreateProjectPackage(_x) {return _ref2.apply(this, arguments);};}();exports.checkAndCreateProjectPackage = checkAndCreateProjectPackage;


var areNodeModulesInstalled = function areNodeModulesInstalled() {return !!(0, _resolve.doResolve)('resolve', false);};exports.areNodeModulesInstalled = areNodeModulesInstalled;

var listAndSelectNpmVersion = /*#__PURE__*/function () {var _ref3 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3(c, npmPackage, rnvTemplates) {var templateVersionsStr, versionArr, templateTagsStr, tagArr, rnvVersion, validVersions, recommendedVersion, _yield$inquirer$promp, inputTemplateVersion;return regeneratorRuntime.wrap(function _callee3$(_context3) {while (1) {switch (_context3.prev = _context3.next) {case 0:_context3.next = 2;return (
              (0, _exec.executeAsync)(
              c, "npm view ".concat(
              npmPackage, " versions")));case 2:templateVersionsStr = _context3.sent;

            versionArr = templateVersionsStr.
            replace(/\r?\n|\r|\s|'|\[|\]/g, '').
            split(',');_context3.next = 6;return (

              (0, _exec.executeAsync)(
              c, "npm dist-tag ls ".concat(
              npmPackage)));case 6:templateTagsStr = _context3.sent;

            tagArr = [];
            templateTagsStr.split('\n').forEach(function (tString) {
              var tArr = tString.split(': ');
              tagArr.push({
                name: tArr[0],
                version: tArr[1] });

            });

            rnvVersion = c.rnvVersion;
            validVersions = versionArr.map(function (v) {return { name: v, value: v };});


            validVersions.forEach(function (item) {
              var matchStr = '';
              var matchArr = [];
              tagArr.forEach(function (tag) {
                if (tag.version === item.value) {
                  matchArr.push(tag.name);
                }
              });
              if (matchArr.length) {
                matchStr = " (HEAD: ".concat(matchArr.join(', '), ")");
                item.name = "".concat(item.value).concat(matchStr);
              }
              if (rnvTemplates !== null && rnvTemplates !== void 0 && rnvTemplates.includes && rnvTemplates.includes(npmPackage)) {
                if (item.value === rnvVersion) {
                  item.name = "".concat(item.name, " <= RECOMMENDED");
                  recommendedVersion = item;
                }
              }
            });
            if (!recommendedVersion) recommendedVersion = validVersions[0];


            validVersions.sort(function (a, b) {
              if (a.name > b.name) return 1;

              return b.name > a.name ? -1 : 0;
            }).reverse();

            validVersions.unshift(validVersions.splice(validVersions.indexOf(recommendedVersion), 1)[0]);_context3.next = 17;return (


              _inquirer["default"].prompt({
                name: 'inputTemplateVersion',
                type: 'list',
                message: "What ".concat(npmPackage, " version to use?"),
                "default": recommendedVersion.name,
                choices: validVersions }));case 17:_yield$inquirer$promp = _context3.sent;inputTemplateVersion = _yield$inquirer$promp.inputTemplateVersion;return _context3.abrupt("return",


            inputTemplateVersion);case 20:case "end":return _context3.stop();}}}, _callee3);}));return function listAndSelectNpmVersion(_x2, _x3, _x4) {return _ref3.apply(this, arguments);};}();exports.listAndSelectNpmVersion = listAndSelectNpmVersion;


var checkIfProjectAndNodeModulesExists = /*#__PURE__*/function () {var _ref4 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee4(c) {return regeneratorRuntime.wrap(function _callee4$(_context4) {while (1) {switch (_context4.prev = _context4.next) {case 0:
            (0, _logger.logTask)('checkIfProjectAndNodeModulesExists');if (!(

            c.paths.project.configExists && !(0, _fileutils.fsExistsSync)(c.paths.project.nodeModulesDir))) {_context4.next = 6;break;}
            c._requiresNpmInstall = false;
            (0, _logger.logInfo)(
            'node_modules folder is missing. INSTALLING...');_context4.next = 6;return (

              installPackageDependencies(c));case 6:case "end":return _context4.stop();}}}, _callee4);}));return function checkIfProjectAndNodeModulesExists(_x5) {return _ref4.apply(this, arguments);};}();exports.checkIfProjectAndNodeModulesExists = checkIfProjectAndNodeModulesExists;



var _getInstallScript = function _getInstallScript(c) {var _c$buildConfig;
  var tasks = (_c$buildConfig = c.buildConfig) === null || _c$buildConfig === void 0 ? void 0 : _c$buildConfig.tasks;
  if (!tasks) return null;
  if (Array.isArray(tasks)) {
    for (var i = 0; i < tasks.length; i++) {
      if (tasks[i].name === 'install') {
        return tasks[i].script;
      }
    }
  } else {var _tasks$install;
    return (_tasks$install = tasks.install) === null || _tasks$install === void 0 ? void 0 : _tasks$install.script;
  }
};

var installPackageDependencies = /*#__PURE__*/function () {var _ref5 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee5(c) {var failOnError,customScript,isYarnInstalled,yarnLockPath,npmLockPath,command,yarnLockExists,packageLockExists,_yield$inquirerPrompt,packageManager,_c$files$project$conf6,_c$files$project$conf7,plats,_c$files$project$conf8,_args5 = arguments;return regeneratorRuntime.wrap(function _callee5$(_context5) {while (1) {switch (_context5.prev = _context5.next) {case 0:failOnError = _args5.length > 1 && _args5[1] !== undefined ? _args5[1] : false;
            c.runtime.forceBuildHookRebuild = true;
            customScript = _getInstallScript(c);if (!

            customScript) {_context5.next = 10;break;}
            (0, _logger.logTask)('installPackageDependencies');
            (0, _logger.logInfo)("Found custom task for install: ".concat(customScript, "."));_context5.next = 8;return (
              (0, _exec.executeAsync)(customScript));case 8:
            c._requiresNpmInstall = false;return _context5.abrupt("return",
            true);case 10:


            isYarnInstalled = (0, _exec.commandExistsSync)('yarn') || (0, _resolve.doResolve)('yarn', false);
            yarnLockPath = _path["default"].join(c.paths.project.dir, 'yarn.lock');
            npmLockPath = _path["default"].join(c.paths.project.dir, 'package-lock.json');
            command = 'npm install';


            yarnLockExists = (0, _fileutils.fsExistsSync)(yarnLockPath);
            packageLockExists = (0, _fileutils.fsExistsSync)(npmLockPath);if (!(

            yarnLockExists || packageLockExists)) {_context5.next = 22;break;}if (!(

            yarnLockExists && !isYarnInstalled)) {_context5.next = 19;break;}throw new Error('You have a yarn.lock file but you don\'t have yarn installed. Install it or delete yarn.lock');case 19:
            command = yarnLockExists ? 'yarn' : 'npm install';_context5.next = 37;break;case 22:if (!
            c.program.packageManager) {_context5.next = 32;break;}if (!

            ['yarn', 'npm'].includes(c.program.packageManager)) {_context5.next = 29;break;}
            command = c.program.packageManager === 'yarn' ? 'yarn' : 'npm install';if (!(
            command === 'yarn' && !isYarnInstalled)) {_context5.next = 27;break;}throw new Error('You specified yarn as packageManager but it\'s not installed');case 27:_context5.next = 30;break;case 29:throw (

              new Error("Unsupported package manager ".concat(
              c.program.packageManager, ". Only yarn and npm are supported at the moment.")));case 30:_context5.next = 37;break;case 32:_context5.next = 34;return (



              (0, _prompt.inquirerPrompt)({
                type: 'list',
                name: 'packageManager',
                message: 'What package manager would you like to use?',
                choices: ['yarn', 'npm'],
                "default": 'npm' }));case 34:_yield$inquirerPrompt = _context5.sent;packageManager = _yield$inquirerPrompt.packageManager;

            if (packageManager === 'yarn') command = 'yarn';case 37:


            (0, _logger.logTask)('installPackageDependencies', "packageManager:(".concat(command, ")"));_context5.prev = 38;_context5.next = 41;return (


              (0, _exec.executeAsync)(command));case 41:_context5.next = 43;return (
              (0, _fileutils.invalidatePodsChecksum)(c));case 43:_context5.next = 62;break;case 45:_context5.prev = 45;_context5.t0 = _context5["catch"](38);if (!

            failOnError) {_context5.next = 50;break;}
            (0, _logger.logError)(_context5.t0);return _context5.abrupt("return",
            false);case 50:

            (0, _logger.logWarning)("".concat(_context5.t0, "\n Seems like your node_modules is corrupted by other libs. ReNative will try to fix it for you"));_context5.prev = 51;_context5.next = 54;return (



              cleanNodeModules(c));case 54:_context5.next = 56;return (
              installPackageDependencies(c, true));case 56:_context5.next = 62;break;case 58:_context5.prev = 58;_context5.t1 = _context5["catch"](51);

            (0, _logger.logError)(_context5.t1);return _context5.abrupt("return",
            false);case 62:_context5.prev = 62;



            plats = (_c$files$project$conf6 = c.files.project.config) === null || _c$files$project$conf6 === void 0 ? void 0 : (_c$files$project$conf7 = _c$files$project$conf6.defaults) === null || _c$files$project$conf7 === void 0 ? void 0 : _c$files$project$conf7.supportedPlatforms;
            if (
            Array.isArray(plats) && (plats.includes(_constants.ANDROID) ||
            plats.includes(_constants.ANDROID_TV) ||
            plats.includes(_constants.FIRE_TV) ||
            plats.includes(_constants.ANDROID_WEAR)))
            {
              if (!c.files.project.configLocal) {
                c.files.project.configLocal = {};
              }
              if (!((_c$files$project$conf8 = c.files.project.configLocal) !== null && _c$files$project$conf8 !== void 0 && _c$files$project$conf8._meta)) {
                c.files.project.configLocal._meta = {};
              }
              c.files.project.configLocal._meta.requiresJetify = true;
              (0, _fileutils.writeFileSync)(c.paths.project.configLocal, c.files.project.configLocal);
            }
            c._requiresNpmInstall = false;return _context5.abrupt("return",
            true);case 69:_context5.prev = 69;_context5.t2 = _context5["catch"](62);

            (0, _logger.logError)(_context5.t2);return _context5.abrupt("return",
            false);case 73:case "end":return _context5.stop();}}}, _callee5, null, [[38, 45], [51, 58], [62, 69]]);}));return function installPackageDependencies(_x6) {return _ref5.apply(this, arguments);};}();exports.installPackageDependencies = installPackageDependencies;



var jetifyIfRequired = /*#__PURE__*/function () {var _ref6 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee6(c) {var _c$files$project$conf9, _c$files$project$conf10;return regeneratorRuntime.wrap(function _callee6$(_context6) {while (1) {switch (_context6.prev = _context6.next) {case 0:
            (0, _logger.logTask)('jetifyIfRequired');if (!((_c$files$project$conf9 =
            c.files.project.configLocal) !== null && _c$files$project$conf9 !== void 0 && (_c$files$project$conf10 = _c$files$project$conf9._meta) !== null && _c$files$project$conf10 !== void 0 && _c$files$project$conf10.requiresJetify)) {_context6.next = 7;break;}if (!
            (0, _resolve.doResolve)('jetifier')) {_context6.next = 7;break;}_context6.next = 5;return (
              (0, _exec.executeAsync)('npx jetify'));case 5:
            c.files.project.configLocal._meta.requiresJetify = false;
            (0, _fileutils.writeFileSync)(c.paths.project.configLocal, c.files.project.configLocal);case 7:return _context6.abrupt("return",


            true);case 8:case "end":return _context6.stop();}}}, _callee6);}));return function jetifyIfRequired(_x7) {return _ref6.apply(this, arguments);};}();exports.jetifyIfRequired = jetifyIfRequired;


var cleanNodeModules = function cleanNodeModules() {return new Promise(function (resolve, reject) {
    (0, _logger.logTask)('cleanNodeModules');
    var dirs = [
    'react-native-safe-area-view/.git',
    '@react-navigation/native/node_modules/react-native-safe-area-view/.git',
    'react-navigation/node_modules/react-native-safe-area-view/.git',
    'react-native-safe-area-view/.git',
    '@react-navigation/native/node_modules/react-native-safe-area-view/.git',
    'react-navigation/node_modules/react-native-safe-area-view/.git'].
    reduce(function (acc, dir) {
      var _dir$match = dir.match(/([^/]+)\/(.*)/),_dir$match2 = _slicedToArray(_dir$match, 3),_all = _dir$match2[0],aPackage = _dir$match2[1],aPath = _dir$match2[2];
      (0, _logger.logDebug)("Cleaning: ".concat(_all));
      var resolved = (0, _resolve.doResolve)(aPackage, false);
      if (resolved) {
        acc.push("".concat(resolved, "/").concat(aPath));
      }
      return acc;
    }, []);
    (0, _fileutils.removeDirs)(dirs).
    then(function () {return resolve();})["catch"](
    function (e) {return reject(e);});
    // removeDirs([
    //     path.join(c.paths.project.nodeModulesDir, 'react-native-safe-area-view/.git'),
    //     path.join(c.paths.project.nodeModulesDir, '@react-navigation/native/node_modules/react-native-safe-area-view/.git'),
    //     path.join(c.paths.project.nodeModulesDir, 'react-navigation/node_modules/react-native-safe-area-view/.git'),
    //     path.join(c.paths.rnv.nodeModulesDir, 'react-native-safe-area-view/.git'),
    //     path.join(c.paths.rnv.nodeModulesDir, '@react-navigation/native/node_modules/react-native-safe-area-view/.git'),
    //     path.join(c.paths.rnv.nodeModulesDir, 'react-navigation/node_modules/react-native-safe-area-view/.git')
    // ]).then(() => resolve()).catch(e => reject(e));
  });};exports.cleanNodeModules = cleanNodeModules;
//# sourceMappingURL=npmUtils.js.map