"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports.waitForHost = exports.sanitizeColor = exports.isMonorepo = exports.getTimestampPathsConfig = exports.getTemplateProjectDir = exports.getTemplateDir = exports.getPlatformServerDir = exports.getPlatformProjectDir = exports.getPlatformOutputDir = exports.getPlatformBuildDir = exports.getMonorepoRoot = exports.getIP = exports.getGetJsBundleFile = exports.getFlavouredProp = exports.getEntryFile = exports.getDevServerHost = exports.getConfigPropArray = exports.getConfigProp = exports.getCliArguments = exports.getBuildsFolder = exports.getBuildFilePath = exports.getAppVersionCode = exports.getAppVersion = exports.getAppTitle = exports.getAppTemplateFolder = exports.getAppLicense = exports.getAppId = exports.getAppFolder = exports.getAppDescription = exports.getAppAuthor = exports.existBuildsOverrideForTargetPathSync = exports["default"] = exports.confirmActiveBundler = exports.checkPortInUse = exports.addSystemInjects = exports._getConfigProp = void 0;var _colorString = _interopRequireDefault(require("color-string"));
var _detectPort = _interopRequireDefault(require("detect-port"));
var _ip = _interopRequireDefault(require("ip"));
var _killPort = _interopRequireDefault(require("kill-port"));
var _axios = _interopRequireDefault(require("axios"));
var _lodash = _interopRequireDefault(require("lodash.get"));
var _path = _interopRequireDefault(require("path"));
var _prompt = require("../cli/prompt");
var _constants = require("./constants");
var _fileutils = require("./systemManager/fileutils");
var _logger = require("./systemManager/logger");



var _utils = require("./systemManager/utils");function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { "default": obj };}function _typeof(obj) {"@babel/helpers - typeof";return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {return typeof obj;} : function (obj) {return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;}, _typeof(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);});};}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;}

var getTimestampPathsConfig = function getTimestampPathsConfig(c, platform) {var _timestampBuildFiles;
  var timestampBuildFiles;
  var pPath = _path["default"].join(
  c.paths.project.builds.dir, "".concat(
  c.runtime.appId, "_").concat(platform));

  if (platform === 'web') {
    timestampBuildFiles = getConfigProp(c, platform, 'timestampBuildFiles', []).map(function (v) {return _path["default"].join(pPath, v);});
  }
  if ((_timestampBuildFiles = timestampBuildFiles) !== null && _timestampBuildFiles !== void 0 && _timestampBuildFiles.length) {
    return { paths: timestampBuildFiles, timestamp: c.runtime.timestamp };
  }
  return null;
};exports.getTimestampPathsConfig = getTimestampPathsConfig;

var getCliArguments = function getCliArguments(c) {var _missingArg;
  var _c$program = c.program,args = _c$program.args,rawArgs = _c$program.rawArgs;
  var argsCopy = _toConsumableArray(args);
  var missingArg = rawArgs[rawArgs.indexOf(argsCopy[1]) + 1];
  if (((_missingArg = missingArg) === null || _missingArg === void 0 ? void 0 : _missingArg[0]) === '-') {
    if (rawArgs[rawArgs.indexOf(argsCopy[1]) + 2]) {
      missingArg = rawArgs[rawArgs.indexOf(argsCopy[1]) + 2];
    } else {
      missingArg = undefined;
    }
  }
  if (rawArgs.length === 3) missingArg = undefined;
  argsCopy[2] = missingArg;
  return argsCopy.filter(function (arg) {return !!arg;});
};exports.getCliArguments = getCliArguments;

var addSystemInjects = function addSystemInjects(c, injects) {
  if (!c.systemPropsInjects) c.systemPropsInjects = [];
  if (injects) {
    injects.forEach(function (item) {
      c.systemPropsInjects.push(item);
    });
  }
};exports.addSystemInjects = addSystemInjects;

var sanitizeColor = function sanitizeColor(val, key) {
  if (!val) {
    (0, _logger.logWarning)("You are missing ".concat(
    (0, _logger.chalk)().white(key), " in your renative config. will use default #FFFFFF instead"));

    return {
      rgb: [255, 255, 255, 1],
      rgbDecimal: [1, 1, 1, 1],
      hex: '#FFFFFF' };

  }

  var rgb = _colorString["default"].get.rgb(val);
  var hex = _colorString["default"].to.hex(rgb);

  return {
    rgb: rgb,
    rgbDecimal: rgb.map(function (v) {return v > 1 ? Math.round(v / 255 * 10) / 10 : v;}),
    hex: hex };

};exports.sanitizeColor = sanitizeColor;

var getDevServerHost = function getDevServerHost(c) {
  var devServerHostOrig = getConfigProp(c, c.platform, 'devServerHost');
  if (!devServerHostOrig) {
    devServerHostOrig = getConfigProp(c, c.platform, 'webpack', {}).devServerHost;
    if (devServerHostOrig) {
      (0, _logger.logWarning)('DEPRECATED: webpack.devServerHost. use devServerHost directly instead');
    }
  }
  if (!devServerHostOrig) {
    if (!devServerHostOrig) {
      devServerHostOrig = getConfigProp(c, c.platform, 'webpackConfig', {}).devServerHost;
      if (devServerHostOrig) {
        (0, _logger.logWarning)('DEPRECATED: webpackConfig.devServerHost. use devServerHost directly instead');
      }
    }
  }
  var devServerHostFixed = (0, _utils.getValidLocalhost)(devServerHostOrig, c.runtime.localhost);

  return devServerHostFixed;
};exports.getDevServerHost = getDevServerHost;

var waitForHost = /*#__PURE__*/function () {var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(c) {var suffix,attempts,maxAttempts,CHECK_INTEVAL,devServerHost,url,_args = arguments;return regeneratorRuntime.wrap(function _callee$(_context) {while (1) {switch (_context.prev = _context.next) {case 0:suffix = _args.length > 1 && _args[1] !== undefined ? _args[1] : 'assets/bundle.js';
            (0, _logger.logTask)('waitForHost', "port:".concat(c.runtime.port));
            attempts = 0;
            maxAttempts = 10;
            CHECK_INTEVAL = 2000;
            // const spinner = ora('Waiting for webpack to finish...').start();

            devServerHost = getDevServerHost(c);
            url = "http://".concat(devServerHost, ":").concat(c.runtime.port, "/").concat(suffix);return _context.abrupt("return",

            new Promise(function (resolve, reject) {
              var interval = setInterval(function () {
                _axios["default"].
                get(url).
                then(function (res) {
                  if (res.status === 200) {
                    clearInterval(interval);
                    // spinner.succeed();
                    // spinner.succeed();
                    return resolve(true);}
                  attempts++;
                  if (attempts === maxAttempts) {
                    clearInterval(interval);
                    // spinner.fail('Can\'t connect to webpack. Try restarting it.');
                    // spinner.fail('Can\'t connect to webpack. Try restarting it.');
                    return reject("Can't connect to host. Try restarting it.");

                  }
                })["catch"](
                function () {
                  attempts++;
                  if (attempts > maxAttempts) {
                    clearInterval(interval);
                    // spinner.fail('Can\'t connect to webpack. Try restarting it.');
                    // spinner.fail('Can\'t connect to webpack. Try restarting it.');
                    return reject("Can't connect to host. Try restarting it.");

                  }
                });
              }, CHECK_INTEVAL);
            }));case 8:case "end":return _context.stop();}}}, _callee);}));return function waitForHost(_x) {return _ref.apply(this, arguments);};}();exports.waitForHost = waitForHost;


var existBuildsOverrideForTargetPathSync = function existBuildsOverrideForTargetPathSync(c, destPath) {
  var appFolder = getAppFolder(c);
  var relativePath = _path["default"].relative(appFolder, destPath);
  var result = false;

  var pathsToCheck = [];

  if (c.paths.appConfig.dirs) {
    c.paths.appConfig.dirs.forEach(function (v) {
      pathsToCheck.push(getBuildsFolder(c, c.platform, v));
    });
  }

  for (var i = 0; i < pathsToCheck.length; i++) {
    if ((0, _fileutils.fsExistsSync)(_path["default"].join(pathsToCheck[i], relativePath))) {
      result = true;
      break;
    }
  }
  return result;
};exports.existBuildsOverrideForTargetPathSync = existBuildsOverrideForTargetPathSync;

var confirmActiveBundler = /*#__PURE__*/function () {var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(c) {var choices, _yield$inquirerPrompt, selectedOption;return regeneratorRuntime.wrap(function _callee2$(_context2) {while (1) {switch (_context2.prev = _context2.next) {case 0:if (!
            c.runtime.skipActiveServerCheck) {_context2.next = 2;break;}return _context2.abrupt("return", true);case 2:if (!

            c.program.ci) {_context2.next = 4;break;}return _context2.abrupt("return",
            (0, _killPort["default"])(c.runtime.port));case 4:


            choices = ['Restart the server (recommended)', 'Use existing session'];_context2.next = 7;return (

              (0, _prompt.inquirerPrompt)({
                name: 'selectedOption',
                type: 'list',
                choices: choices,
                warningMessage: "Another ".concat(c.platform, " server at port ").concat(
                (0, _logger.chalk)().white(c.runtime.port), " already running") }));case 7:_yield$inquirerPrompt = _context2.sent;selectedOption = _yield$inquirerPrompt.selectedOption;if (!(



            choices[0] === selectedOption)) {_context2.next = 14;break;}_context2.next = 12;return (
              (0, _killPort["default"])(c.runtime.port));case 12:_context2.next = 15;break;case 14:return _context2.abrupt("return",

            false);case 15:return _context2.abrupt("return",

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


var getPlatformBuildDir = function getPlatformBuildDir(c, isRelativePath) {
  if (!c.runtime.engine) {
    (0, _logger.logError)('getPlatformBuildDir not available without specific engine');
    return null;
  }
  return getAppFolder(c, isRelativePath);
};exports.getPlatformBuildDir = getPlatformBuildDir;

var getPlatformOutputDir = function getPlatformOutputDir(c) {
  if (!c.runtime.engine) {
    (0, _logger.logError)('getPlatformOutputDir not available without specific engine');
    return null;
  }
  return _path["default"].join(getAppFolder(c), c.runtime.engine.outputDirName || '');
};exports.getPlatformOutputDir = getPlatformOutputDir;

var getPlatformProjectDir = function getPlatformProjectDir(c) {
  if (!c.runtime.engine) {
    (0, _logger.logError)('getPlatformProjectDir not available without specific engine');
    return null;
  }
  return _path["default"].join(getAppFolder(c), c.runtime.engine.projectDirName || '');
};exports.getPlatformProjectDir = getPlatformProjectDir;

var getPlatformServerDir = function getPlatformServerDir(c) {
  if (!c.runtime.engine) {
    (0, _logger.logError)('getPlatformProjectDir not available without specific engine');
    return null;
  }
  return _path["default"].join(getAppFolder(c), c.runtime.engine.serverDirName || '');
};exports.getPlatformServerDir = getPlatformServerDir;

var getTemplateDir = function getTemplateDir(c) {return _path["default"].join(
  c.paths.project.platformTemplatesDirs[c.platform], "".concat(c.platform));};exports.getTemplateDir = getTemplateDir;


var getTemplateProjectDir = function getTemplateProjectDir(c) {
  if (!c.runtime.engine) {
    (0, _logger.logError)('getTemplateProjectDir not available without specific engine');
    return null;
  }
  return _path["default"].join(getTemplateDir(c), c.runtime.engine.projectDirName);
};

// DEPRECATED
exports.getTemplateProjectDir = getTemplateProjectDir;var getAppFolder = function getAppFolder(c, isRelativePath) {
  if (isRelativePath) {
    return "platformBuilds/".concat(c.runtime.appId, "_").concat(c.platform);
  }
  return _path["default"].join(c.paths.project.builds.dir, "".concat(c.runtime.appId, "_").concat(c.platform));
};

// DEPRECATED
exports.getAppFolder = getAppFolder;var getAppTemplateFolder = function getAppTemplateFolder(c, platform) {return _path["default"].join(
  c.paths.project.platformTemplatesDirs[platform], "".concat(platform));};exports.getAppTemplateFolder = getAppTemplateFolder;


var _getValueOrMergedObject = function _getValueOrMergedObject(
resultCli,
resultScheme,
resultPlatforms,
resultCommon)
{
  if (resultCli !== undefined) {
    return resultCli;
  }
  if (resultScheme !== undefined) {
    if (Array.isArray(resultScheme) || _typeof(resultScheme) !== 'object') {return resultScheme;}
    var val = Object.assign(
    resultCommon || {},
    resultPlatforms || {},
    resultScheme);

    return val;
  }
  if (resultPlatforms !== undefined) {
    if (
    Array.isArray(resultPlatforms) ||
    _typeof(resultPlatforms) !== 'object')
    {return resultPlatforms;}
    return Object.assign(resultCommon || {}, resultPlatforms);
  }
  if (resultPlatforms === null) return null;
  return resultCommon;
};

var getConfigProp = function getConfigProp(c, platform, key, defaultVal) {
  if (!c.buildConfig) {
    (0, _logger.logError)('getConfigProp: c.buildConfig is undefined!');
    return null;
  }
  return _getConfigProp(c, platform, key, defaultVal, c.buildConfig);
};exports.getConfigProp = getConfigProp;

var _getConfigProp = function _getConfigProp(c, platform, key, defaultVal, sourceObj) {var _sourceObj$platforms;
  if (!sourceObj) return null;

  if (!key || !key.split) {
    (0, _logger.logError)('getConfigProp: invalid key!');
    return null;
  }
  var p = (_sourceObj$platforms = sourceObj.platforms) === null || _sourceObj$platforms === void 0 ? void 0 : _sourceObj$platforms[platform];
  var ps = c.runtime.scheme;
  var keyArr = key.split('.');
  var baseKey = keyArr.shift();
  var subKey = keyArr.join('.');

  var resultPlatforms;
  var scheme;
  if (p) {
    scheme = p.buildSchemes ? p.buildSchemes[ps] : undefined;
    resultPlatforms = getFlavouredProp(
    c,
    sourceObj.platforms[platform],
    baseKey);

  }

  scheme = scheme || {};
  var resultCli = _constants.CLI_PROPS.includes(baseKey) ? c.program[baseKey] : undefined;
  var resultScheme = scheme[baseKey];
  var resultCommon = getFlavouredProp(c, sourceObj.common, baseKey);

  var result = _getValueOrMergedObject(
  resultCli,
  resultScheme,
  resultPlatforms,
  resultCommon);

  if (result === undefined || result === null) {
    result = getFlavouredProp(c, sourceObj, baseKey);
  }

  if (result === undefined || result === null) result = defaultVal; // default the value only if it's not specified in any of the files. i.e. undefined
  if (_typeof(result) === 'object' && subKey.length) {
    return (0, _lodash["default"])(result, subKey);
  }
  return result;
};exports._getConfigProp = _getConfigProp;


var getConfigPropArray = function getConfigPropArray(c, platform, key) {
  var result = [];
  var configArr = [
  c.files.defaultWorkspace.config,
  c.files.rnv.projectTemplates.config,
  // { plugins: extraPlugins },
  // { pluginTemplates },
  c.files.workspace.config,
  c.files.workspace.configPrivate,
  c.files.workspace.configLocal,
  c.files.workspace.project.config,
  c.files.workspace.project.configPrivate,
  c.files.workspace.project.configLocal].concat(_toConsumableArray(
  c.files.workspace.appConfig.configs), _toConsumableArray(
  c.files.workspace.appConfig.configsPrivate), _toConsumableArray(
  c.files.workspace.appConfig.configsLocal), [
  c.files.project.config,
  c.files.project.configPrivate,
  c.files.project.configLocal], _toConsumableArray(
  c.files.appConfig.configs), _toConsumableArray(
  c.files.appConfig.configsPrivate), _toConsumableArray(
  c.files.appConfig.configsLocal));

  configArr.forEach(function (config) {
    var val = _getConfigProp(c, platform, key, null, config);
    if (val) {
      result.push(val);
    }
  });


  return result;
};exports.getConfigPropArray = getConfigPropArray;


var getAppId = function getAppId(c, platform) {
  var id = getConfigProp(c, platform, 'id');
  var idSuffix = getConfigProp(c, platform, 'idSuffix');
  return idSuffix ? "".concat(id).concat(idSuffix) : id;
};exports.getAppId = getAppId;

var getAppTitle = function getAppTitle(c, platform) {return getConfigProp(c, platform, 'title');};exports.getAppTitle = getAppTitle;

var getAppAuthor = function getAppAuthor(c, platform) {var _c$files$project$pack;return getConfigProp(c, platform, 'author') || ((_c$files$project$pack = c.files.project["package"]) === null || _c$files$project$pack === void 0 ? void 0 : _c$files$project$pack.author);};exports.getAppAuthor = getAppAuthor;

var getAppLicense = function getAppLicense(c, platform) {var _c$files$project$pack2;return getConfigProp(c, platform, 'license') || ((_c$files$project$pack2 = c.files.project["package"]) === null || _c$files$project$pack2 === void 0 ? void 0 : _c$files$project$pack2.license);};exports.getAppLicense = getAppLicense;

var getEntryFile = function getEntryFile(c, platform) {var _c$buildConfig$platfo, _c$buildConfig$platfo2;return (_c$buildConfig$platfo = c.buildConfig.platforms) === null || _c$buildConfig$platfo === void 0 ? void 0 : (_c$buildConfig$platfo2 = _c$buildConfig$platfo[platform]) === null || _c$buildConfig$platfo2 === void 0 ? void 0 : _c$buildConfig$platfo2.entryFile;};exports.getEntryFile = getEntryFile;

var getGetJsBundleFile = function getGetJsBundleFile(c, platform) {return getConfigProp(c, platform, 'getJsBundleFile');};exports.getGetJsBundleFile = getGetJsBundleFile;

var getAppDescription = function getAppDescription(c, platform) {var _c$files$project$pack3;return getConfigProp(c, platform, 'description') || ((_c$files$project$pack3 =
  c.files.project["package"]) === null || _c$files$project$pack3 === void 0 ? void 0 : _c$files$project$pack3.description);};exports.getAppDescription = getAppDescription;

var getAppVersion = function getAppVersion(c, platform) {var _c$files$project$pack4;
  var version = getConfigProp(c, platform, 'version') || ((_c$files$project$pack4 = c.files.project["package"]) === null || _c$files$project$pack4 === void 0 ? void 0 : _c$files$project$pack4.version);
  if (!version) {
    (0, _logger.logWarning)('You are missing version prop in your config. will default to 0');
    return '0';
  }
  var versionFormat = getConfigProp(c, platform, 'versionFormat');
  if (!versionFormat) return version;
  var versionCodeArr = versionFormat.split('.');
  var dotLength = versionCodeArr.length;
  var isNumArr = versionCodeArr.map(function (v) {return !Number.isNaN(Number(v));});

  var verArr = [];
  var i = 0;
  version.split('.').map(function (v) {return v.split('-').map(function (v2) {return v2.split('+').forEach(function (v3) {
        var isNum = !Number.isNaN(Number(v3));
        if (isNumArr[i] && isNum) {
          verArr.push(v3);
        } else if (!isNumArr[i]) {
          verArr.push(v3);
        }

        i++;
      });});});
  if (verArr.length > dotLength) {
    verArr.length = dotLength;
  }

  var output = verArr.join('.');
  // console.log(`IN: ${version}\nOUT: ${output}`);
  return output;
};exports.getAppVersion = getAppVersion;

var getAppVersionCode = function getAppVersionCode(c, platform) {var _c$files$project$pack5;
  var versionCode = getConfigProp(c, platform, 'versionCode');
  if (versionCode) return versionCode;
  var version = getConfigProp(c, platform, 'version') || ((_c$files$project$pack5 = c.files.project["package"]) === null || _c$files$project$pack5 === void 0 ? void 0 : _c$files$project$pack5.version);
  if (!version || typeof version !== 'string') {
    (0, _logger.logWarning)('You are missing version prop in your config. will default to 0');
    return '0';
  }
  var versionCodeFormat = getConfigProp(c, platform, 'versionCodeFormat', '00.00.00');
  var vFormatArr = versionCodeFormat.split('.').map(function (v) {return v.length;});
  var versionCodeMaxCount = vFormatArr.length;
  var verArr = [];


  version.split('.').map(function (v) {return v.split('-').map(function (v2) {return v2.split('+').forEach(function (v3) {
        var asNumber = Number(v3);
        if (!Number.isNaN(asNumber)) {
          var val = v3;
          var maxDigits = vFormatArr[verArr.length] || 2;

          if (v3.length > maxDigits) {
            val = v3.substr(0, maxDigits);
          } else if (v3.length < maxDigits) {
            var toAdd = maxDigits - v3.length;
            val = v3;
            while (toAdd > 0) {
              val = "0".concat(val);
              toAdd--;
            }
          }
          verArr.push(val);
        }
      });});});
  var verCountDiff = verArr.length - versionCodeMaxCount;
  if (verCountDiff < 0) {
    while (verCountDiff < 0) {
      var extraVersionLen = vFormatArr[versionCodeMaxCount + verCountDiff];
      var num = '';
      while (extraVersionLen) {
        num += '0';
        extraVersionLen--;
      }
      verArr.push(num);
      verCountDiff++;
    }
  }

  var output = Number(verArr.join('')).toString();
  // console.log(`IN: ${version}\nOUT: ${output}`);
  return output;
};exports.getAppVersionCode = getAppVersionCode;

var isMonorepo = function isMonorepo() {
  try {
    (0, _fileutils.fsExistsSync)(_path["default"].resolve(__dirname, '../../../../lerna.json'));
    return true;
  } catch (_err) {
    return false;
  }
};exports.isMonorepo = isMonorepo;

var getMonorepoRoot = function getMonorepoRoot() {
  if (isMonorepo()) {
    return _path["default"].resolve(__dirname, '../../../..');
  }
};exports.getMonorepoRoot = getMonorepoRoot;

var getBuildsFolder = function getBuildsFolder(c, platform, customPath) {
  var pp = customPath || c.paths.appConfig.dir;
  // if (!fsExistsSync(pp)) {
  //     logWarning(`Path ${chalk().white(pp)} does not exist! creating one for you..`);
  // }
  if (!pp) {
    (0, _logger.logWarning)("getBuildsFolder: Path ".concat((0, _logger.chalk)().white('c.paths.appConfig.dir'), " not defined! can't return path. You might not be in renative project"));
    return null;
  }
  var p = _path["default"].join(pp, "builds/".concat(platform, "@").concat(c.runtime.scheme));
  if ((0, _fileutils.fsExistsSync)(p)) return p;
  return _path["default"].join(pp, "builds/".concat(platform));
};exports.getBuildsFolder = getBuildsFolder;

var getIP = function getIP() {return _ip["default"].address();};exports.getIP = getIP;

var checkPortInUse = function checkPortInUse(c, platform, port) {return new Promise(function (resolve, reject) {
    if (port === undefined || port === null) {
      resolve(false);
      return;
    }
    (0, _detectPort["default"])(port, function (err, availablePort) {
      if (err) {
        reject(err);
        return;
      }
      var result = parseInt(port, 10) !== parseInt(availablePort, 10);
      resolve(result);
    });
  });};exports.checkPortInUse = checkPortInUse;

var getFlavouredProp = function getFlavouredProp(c, obj, key) {
  if (!key || !obj) return null;
  var val1 = obj["".concat(key, "@").concat(c.runtime.scheme)];
  if (val1) return val1;
  return obj[key];
};exports.getFlavouredProp = getFlavouredProp;

var getBuildFilePath = function getBuildFilePath(c, platform, filePath) {
  // P1 => platformTemplates
  var sp = _path["default"].join(getAppTemplateFolder(c, platform), filePath);
  // P2 => appConfigs/base + @buildSchemes
  var sp2 = _path["default"].join(
  getBuildsFolder(c, platform, c.paths.project.appConfigBase.dir),
  filePath);

  if ((0, _fileutils.fsExistsSync)(sp2)) sp = sp2;
  // P3 => appConfigs + @buildSchemes
  var sp3 = _path["default"].join(getBuildsFolder(c, platform), filePath);
  if ((0, _fileutils.fsExistsSync)(sp3)) sp = sp3;
  return sp;
};exports.getBuildFilePath = getBuildFilePath;var _default =

{
  getBuildFilePath: getBuildFilePath,
  getBuildsFolder: getBuildsFolder,
  getAppFolder: getAppFolder,
  getAppTemplateFolder: getAppTemplateFolder,
  getAppId: getAppId,
  getAppTitle: getAppTitle,
  getAppVersion: getAppVersion,
  getAppVersionCode: getAppVersionCode,
  writeCleanFile: _fileutils.writeCleanFile,
  getEntryFile: getEntryFile,
  getGetJsBundleFile: getGetJsBundleFile,
  getAppDescription: getAppDescription,
  getAppAuthor: getAppAuthor,
  getAppLicense: getAppLicense,
  getConfigProp: getConfigProp,
  getIP: getIP,
  checkPortInUse: checkPortInUse,
  logTask: function logTask(val) {
    (0, _logger.logError)(
    'DEPRECATED: Common.logTask() has been removed. use Logger.logTask() instead');

    (0, _logger.logTask)(val);
  },
  logWarning: function logWarning(val) {
    (0, _logger.logError)(
    'DEPRECATED: Common.logWarning() has been removed. use Logger.logWarning() instead');

    (0, _logger.logWarning)(val);
  },
  logError: function logError(val) {
    (0, _logger.logError)(
    'DEPRECATED: Common.logError() has been removed. use Logger.logError() instead');

    (0, _logger.logError)(val);
  },
  logSuccess: function logSuccess(val) {
    (0, _logger.logError)(
    'DEPRECATED: Common.logError() has been removed. use Logger.logError() instead');

    (0, _logger.logSuccess)(val);
  },
  logDebug: function logDebug(val) {
    (0, _logger.logError)(
    'DEPRECATED: Common.logDebug() has been removed. use Logger.logDebug() instead');

    (0, _logger.logDebug)(val);
  } };exports["default"] = _default;
//# sourceMappingURL=common.js.map