var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.getRegisteredEngines=exports.findSuitableTask=exports.executeOrSkipTask=exports.executeTask=exports.initializeTask=exports.getEngineRunner=exports.getEngineSubTasks=exports.hasEngineTask=exports.getEngineTask=exports.executeEngineTask=exports.getPlatformExtensions=exports.getEngineRunnerByPlatform=exports.getEngineConfigByPlatform=exports.generateEnvVars=exports.registerPlatformEngine=exports.loadEngineConfigs=exports.registerMissingPlatformEngines=exports.configureEngines=exports.registerEngine=void 0;var _regenerator=_interopRequireDefault(require("@babel/runtime/regenerator"));
var _path=_interopRequireDefault(require("path"));
var _logger=require("../systemManager/logger");
var _common=require("../common");
var _analytics=_interopRequireDefault(require("../systemManager/analytics"));
var _buildHooks=require("../projectManager/buildHooks");
var _prompt=require("../../cli/prompt");
var _npmUtils=require("../systemManager/npmUtils");
var _exec=require("../systemManager/exec");
var _resolve=require("../resolve");

var _fileutils=require("../systemManager/fileutils");
var _constants=require("../constants");


var REGISTERED_ENGINES=[];
var ENGINES={};
var ENGINE_CORE='engine-core';

var registerEngine=function registerEngine(c,engine,platform){return _regenerator.default.async(function registerEngine$(_context){while(1){switch(_context.prev=_context.next){case 0:
ENGINES[engine.getId()]=engine;
REGISTERED_ENGINES.push(engine);
_registerEnginePlatform(c,platform,engine);case 3:case"end":return _context.stop();}}},null,null,null,Promise);};exports.registerEngine=registerEngine;


var _registerEnginePlatform=function _registerEnginePlatform(c,platform,engine){
if(platform){
c.runtime.enginePlatforms[platform]=engine;
}
};

var configureEngines=function configureEngines(c){var engines,devDependencies,needsPackageUpdate;return _regenerator.default.async(function configureEngines$(_context2){while(1){switch(_context2.prev=_context2.next){case 0:
(0,_logger.logTask)('configureEngines');if(!
c.runtime.isWrapper){_context2.next=3;break;}return _context2.abrupt("return",true);case 3:
engines=c.files.project.config.engines;
devDependencies=c.files.project.package.devDependencies;
needsPackageUpdate=false;
if(engines){
Object.keys(engines).forEach(function(k){var _c$buildConfig$engine,_c$buildConfig$engine2;
var engVer=(_c$buildConfig$engine=c.buildConfig.engineTemplates)==null?void 0:(_c$buildConfig$engine2=_c$buildConfig$engine[k])==null?void 0:_c$buildConfig$engine2.version;
if(engVer){
if(devDependencies[k]){
if(devDependencies[k]!==engVer){
needsPackageUpdate=true;
(0,_logger.logInfo)("Updating missing engine "+k+" "+
(0,_logger.chalk)().red(devDependencies[k])+"=>"+engVer+" to package.json");
devDependencies[k]=engVer;
}
}else{
needsPackageUpdate=true;
(0,_logger.logInfo)("Adding missing engine "+k+"@"+engVer+" to package.json");
devDependencies[k]=engVer;
}
}
});
if(needsPackageUpdate){
(0,_fileutils.writeFileSync)(c.paths.project.package,c.files.project.package);
}
}return _context2.abrupt("return",
true);case 8:case"end":return _context2.stop();}}},null,null,null,Promise);};exports.configureEngines=configureEngines;


var registerMissingPlatformEngines=function registerMissingPlatformEngines(c,taskInstance){var _taskInstance$platfor;var registerEngineList;return _regenerator.default.async(function registerMissingPlatformEngines$(_context3){while(1){switch(_context3.prev=_context3.next){case 0:
(0,_logger.logTask)('registerMissingPlatformEngines');if(!(
!taskInstance.isGlobalScope&&(taskInstance==null?void 0:(_taskInstance$platfor=taskInstance.platforms)==null?void 0:_taskInstance$platfor.length)===0)){_context3.next=7;break;}
registerEngineList=[];
c.buildConfig.defaults.supportedPlatforms.forEach(function(platform){
registerEngineList.push(
registerPlatformEngine(c,platform));

});if(!

registerEngineList.length){_context3.next=7;break;}_context3.next=7;return _regenerator.default.awrap(
Promise.all(registerEngineList));case 7:return _context3.abrupt("return",



true);case 8:case"end":return _context3.stop();}}},null,null,null,Promise);};exports.registerMissingPlatformEngines=registerMissingPlatformEngines;


var loadEngineConfigs=function loadEngineConfigs(c){var _c$buildConfig;var engines,enginesToInstall;return _regenerator.default.async(function loadEngineConfigs$(_context4){while(1){switch(_context4.prev=_context4.next){case 0:
(0,_logger.logTask)('loadEngineConfigs');
engines=(_c$buildConfig=c.buildConfig)==null?void 0:_c$buildConfig.engines;
c.runtime.engineConfigs={};
enginesToInstall=[];if(!
engines){_context4.next=13;break;}
Object.keys(engines).forEach(function(k){
var engineRootPath=(0,_resolve.doResolve)(k);
var configPath=engineRootPath?_path.default.join(engineRootPath,'renative.engine.json'):null;
if(configPath&&(0,_fileutils.fsExistsSync)(configPath)){
var engineConfig=(0,_fileutils.readObjectSync)(configPath);
c.runtime.engineConfigs[engineConfig.id]=engineConfig;
}else{var _c$buildConfig$engine3,_c$buildConfig$engine4;
var engVer=(_c$buildConfig$engine3=c.buildConfig.engineTemplates)==null?void 0:(_c$buildConfig$engine4=_c$buildConfig$engine3[k])==null?void 0:_c$buildConfig$engine4.version;
if(engVer){
enginesToInstall.push(k+"@"+engVer);
}
}
});if(!
enginesToInstall.length){_context4.next=11;break;}
(0,_logger.logInfo)("Some engines not installed in your project:\n"+
enginesToInstall.map(function(v){return"> "+v;}).join('\n')+"\n INSTALLING...");_context4.next=10;return _regenerator.default.awrap(

Promise.all(enginesToInstall.map(function(v){return(0,_exec.executeAsync)("npm i "+v+" --no-save",{
cwd:c.paths.project.dir});})));case 10:return _context4.abrupt("return",

loadEngineConfigs(c));case 11:_context4.next=18;break;case 13:if(!

c.files.project.config){_context4.next=18;break;}
(0,_logger.logInfo)('Engine configs missing in your renative.json. FIXING...DONE');
c.files.project.config.engines={
'@rnv/engine-rn':'source:rnv',
'@rnv/engine-rn-web':'source:rnv',
'@rnv/engine-rn-next':'source:rnv',
'@rnv/engine-rn-electron':'source:rnv'};

(0,_fileutils.writeFileSync)(c.paths.project.config,c.files.project.config);return _context4.abrupt("return",
false);case 18:return _context4.abrupt("return",

true);case 19:case"end":return _context4.stop();}}},null,null,null,Promise);};exports.loadEngineConfigs=loadEngineConfigs;


var registerPlatformEngine=function registerPlatformEngine(c,platform){

var selectedEngineConfig=getEngineConfigByPlatform(c,platform);
if(selectedEngineConfig){
var existingEngine=ENGINES[selectedEngineConfig.id];
if(!existingEngine){var _require;
registerEngine(c,(_require=require(selectedEngineConfig.packageName))==null?void 0:_require.default,platform);
}else{
_registerEnginePlatform(c,platform,existingEngine);
}
}
};exports.registerPlatformEngine=registerPlatformEngine;

var generateEnvVars=function generateEnvVars(c,moduleConfig,nextConfig){return{
RNV_EXTENSIONS:getPlatformExtensions(c),
RNV_MODULE_PATHS:(moduleConfig==null?void 0:moduleConfig.modulePaths)||[],
RNV_MODULE_ALIASES:(moduleConfig==null?void 0:moduleConfig.moduleAliasesArray)||[],
RNV_NEXT_TRANSPILE_MODULES:nextConfig,
RNV_PROJECT_ROOT:c.paths.project.dir,
RNV_MONO_ROOT:c.runtime.isWrapper?_path.default.join(c.paths.project.dir,'../..'):c.paths.project.dir};};exports.generateEnvVars=generateEnvVars;

var getEngineConfigByPlatform=function getEngineConfigByPlatform(c,platform,ignoreMissingError){
var selectedEngineKey;
if(c.buildConfig&&!!platform&&c.runtime.engineConfigs){
selectedEngineKey=c.program.engine||(0,_common.getConfigProp)(c,platform,'engine');
var selectedEngine=c.runtime.engineConfigs[selectedEngineKey];
if(!selectedEngine&&!ignoreMissingError){
(0,_logger.logDebug)("ERROR: Engine: "+selectedEngineKey+" does not exists or is not registered "+new Error());

}
return selectedEngine;
}
return null;
};exports.getEngineConfigByPlatform=getEngineConfigByPlatform;

var getEngineRunnerByPlatform=function getEngineRunnerByPlatform(c,platform){
var selectedEngine=getEngineConfigByPlatform(c,platform);
return ENGINES[selectedEngine==null?void 0:selectedEngine.id];
};exports.getEngineRunnerByPlatform=getEngineRunnerByPlatform;

var getPlatformExtensions=function getPlatformExtensions(c,excludeServer){
var id=c.runtime.engine.getId();
var output=[id+".jsx",id+".js",id+".tsx",id+".ts"].concat(_constants.EXTENSIONS[c.platform]).filter(function(ext){return!excludeServer||!ext.includes('server.');});
return output;
};exports.getPlatformExtensions=getPlatformExtensions;

var executeEngineTask=function executeEngineTask(c,task,parentTask,originTask,tasks,isFirstTask){var needsHelp,t,inOnlyMode,doPipe;return _regenerator.default.async(function executeEngineTask$(_context5){while(1){switch(_context5.prev=_context5.next){case 0:
needsHelp=Object.prototype.hasOwnProperty.call(c.program,'help');

t=getEngineTask(task,tasks);if(!(

needsHelp&&!parentTask)){_context5.next=10;break;}
(0,_logger.logRaw)("\n=======================================================\nINTERACTIVE HELP FOR TASK: "+

(0,_logger.chalk)().green(t.task)+"\n\nDescription: "+

t.description+"\n\nOptions:\n\n"+



t.params.map(function(v){
var option=v.shortcut?"`-"+v.shortcut+"`, ":'';
return option+"`--"+v.key+"` - "+v.description;
}).join('\n')+"\n\n  ");if(!


t.fnHelp){_context5.next=7;break;}_context5.next=7;return _regenerator.default.awrap(
t.fnHelp(c,parentTask,originTask));case 7:_context5.next=9;return _regenerator.default.awrap(


(0,_prompt.pressAnyKeyToContinue)());case 9:
(0,_logger.logRaw)("\n=======================================================");case 10:if(!(



!t.isGlobalScope&&isFirstTask)){_context5.next=14;break;}if(!
c.files.project.package){_context5.next=14;break;}_context5.next=14;return _regenerator.default.awrap(

(0,_npmUtils.checkIfProjectAndNodeModulesExists)(c));case 14:


inOnlyMode=c.program.only;
doPipe=!t.isGlobalScope&&(!inOnlyMode||inOnlyMode&&isFirstTask);if(!
doPipe){_context5.next=19;break;}_context5.next=19;return _regenerator.default.awrap(_executePipe(c,task,'before'));case 19:_context5.next=21;return _regenerator.default.awrap(
t.fn(c,parentTask,originTask));case 21:if(!
doPipe){_context5.next=24;break;}_context5.next=24;return _regenerator.default.awrap(_executePipe(c,task,'after'));case 24:case"end":return _context5.stop();}}},null,null,null,Promise);};exports.executeEngineTask=executeEngineTask;


var getEngineTask=function getEngineTask(task,tasks){
var tsk;
var taskCleaned=task.split(' ')[0];
tsk=tasks[task];
if(!tsk){
tsk=tasks[taskCleaned];
}
return tsk;
};exports.getEngineTask=getEngineTask;

var hasEngineTask=function hasEngineTask(task,tasks,isProjectScope){var _getEngineTask;return(
isProjectScope?!!getEngineTask(task,tasks):(_getEngineTask=getEngineTask(task,tasks))==null?void 0:_getEngineTask.isGlobalScope);};exports.hasEngineTask=hasEngineTask;

var getEngineSubTasks=function getEngineSubTasks(task,tasks,exactMatch){return Object.values(tasks).filter(function(v){return exactMatch?v.task.split(' ')[0]===task:v.task.startsWith(task);});};exports.getEngineSubTasks=getEngineSubTasks;

var getEngineRunner=function getEngineRunner(c,task){
var selectedEngine=getEngineConfigByPlatform(c,c.platform);var
configExists=c.paths.project.configExists;
if(!selectedEngine){
if(ENGINES[ENGINE_CORE].hasTask(task,configExists))return ENGINES[ENGINE_CORE];

throw new Error("Cound not find suitable executor for task "+(0,_logger.chalk)().white(task));
}
c.runtime.engineConfig=selectedEngine;
var engine=ENGINES[selectedEngine==null?void 0:selectedEngine.id];
if(!engine){
if(ENGINES[ENGINE_CORE].hasTask(task,configExists))return ENGINES[ENGINE_CORE];
throw new Error("Cound not find active engine with id "+(selectedEngine==null?void 0:selectedEngine.id)+". Available engines:\n        "+
Object.keys(ENGINES).join(', '));
}
if(engine.hasTask(task,configExists))return engine;
if(ENGINES[ENGINE_CORE].hasTask(task,configExists))return ENGINES[ENGINE_CORE];

throw new Error("Cound not find suitable executor for task "+(0,_logger.chalk)().white(task));
};exports.getEngineRunner=getEngineRunner;

var executedTasks={};

var initializeTask=function initializeTask(c,task){return _regenerator.default.async(function initializeTask$(_context6){while(1){switch(_context6.prev=_context6.next){case 0:
(0,_logger.logTask)('initializeTask',task);
c.runtime.task=task;
executedTasks={};

_analytics.default.captureEvent({
type:task+"Project",
platform:c.platform});_context6.next=6;return _regenerator.default.awrap(


executeTask(c,task,null,task,true));case 6:return _context6.abrupt("return",
true);case 7:case"end":return _context6.stop();}}},null,null,null,Promise);};exports.initializeTask=initializeTask;


var _executePipe=function _executePipe(c,task,phase){return _regenerator.default.async(function _executePipe$(_context7){while(1){switch(_context7.prev=_context7.next){case 0:return _context7.abrupt("return",(0,_buildHooks.executePipe)(c,task.split(' ').join(':')+":"+phase));case 1:case"end":return _context7.stop();}}},null,null,null,Promise);};

var TASK_LIMIT=20;

var executeTask=function executeTask(c,task,parentTask,originTask,isFirstTask){var pt,prt;return _regenerator.default.async(function executeTask$(_context8){while(1){switch(_context8.prev=_context8.next){case 0:
pt=parentTask?"=> ["+parentTask+"] ":'';
c._currentTask=task;
(0,_logger.logInitTask)(pt+"=> ["+(0,_logger.chalk)().bold.rgb(170,106,170)(task)+"]");

if(!executedTasks[task])executedTasks[task]=0;if(!(
executedTasks[task]>TASK_LIMIT)){_context8.next=6;break;}return _context8.abrupt("return",
Promise.reject("You reached maximum amount of executions per one task ("+TASK_LIMIT+") task: "+task+".\nThis is to warn you ended up in task loop.\n("+

task+" calls same or another task which calls "+task+" again)\nbut issue migh not be necessarily with this task\n\nTo avoid that test your task code against parentTask and avoid executing same task X from within task X"));case 6:_context8.next=8;return _regenerator.default.awrap(




getEngineRunner(c,task).executeTask(c,task,parentTask,originTask,isFirstTask));case 8:
executedTasks[task]++;

c._currentTask=parentTask;
prt=parentTask?"<= ["+(0,_logger.chalk)().rgb(170,106,170)(parentTask)+"] ":'';
(0,_logger.logExitTask)(prt+"<= "+task);case 12:case"end":return _context8.stop();}}},null,null,null,Promise);};exports.executeTask=executeTask;


var executeOrSkipTask=function executeOrSkipTask(c,task,parentTask,originTask){return _regenerator.default.async(function executeOrSkipTask$(_context9){while(1){switch(_context9.prev=_context9.next){case 0:if(
c.program.only){_context9.next=2;break;}return _context9.abrupt("return",
executeTask(c,task,parentTask,originTask));case 2:return _context9.abrupt("return",


executeTask(c,_constants.TASK_CONFIGURE_SOFT,parentTask,originTask));case 3:case"end":return _context9.stop();}}},null,null,null,Promise);};exports.executeOrSkipTask=executeOrSkipTask;


var _getTaskOption=function _getTaskOption(_ref){var taskInstance=_ref.taskInstance,hasMultipleSubTasks=_ref.hasMultipleSubTasks;
if(hasMultipleSubTasks){
return taskInstance.task.split(' ')[0]+"...";
}
if(taskInstance.description&&taskInstance.description!==''){
return taskInstance.task.split(' ')[0]+" "+(0,_logger.chalk)().grey("("+taskInstance.description+")");
}
return""+taskInstance.task.split(' ')[0];
};

var findSuitableTask=function findSuitableTask(c){var suitableTaskInstances,taskInstances,tasks,defaultCmd,tasksCommands,filteredTasks,addendum,_await$inquirerPrompt,command,task,suitableEngines,autocompleteEngines,isAutoComplete,message,supportedSubtasksArr,supportedSubtasks,supportedSubtasksFilter,subTasks,_await$inquirerPrompt2,subCommand,supportedPlatforms,platforms,_await$inquirerPrompt3,platform;return _regenerator.default.async(function findSuitableTask$(_context10){while(1){switch(_context10.prev=_context10.next){case 0:if(
c.command){_context10.next=12;break;}
suitableTaskInstances={};
REGISTERED_ENGINES.forEach(function(engine){
engine.getTasks().forEach(function(taskInstance){
var key=taskInstance.task.split(' ')[0];
var hasMultipleSubTasks=false;
if(taskInstance.task.includes(' '))hasMultipleSubTasks=true;
suitableTaskInstances[key]={
taskInstance:taskInstance,
hasMultipleSubTasks:hasMultipleSubTasks};

});
});

taskInstances=Object.values(suitableTaskInstances);

defaultCmd='new';


addendum='';
if(!c.paths.project.configExists){
filteredTasks=taskInstances.filter(function(v){return v.taskInstance.isGlobalScope;});
tasks=filteredTasks.map(function(v){return _getTaskOption(v);}).sort();
tasksCommands=filteredTasks.map(function(v){return v.taskInstance.task.split(' ')[0];}).sort();
addendum=' (Not a ReNative project. options will be limited)';
}else{
tasks=taskInstances.map(function(v){return _getTaskOption(v);}).sort();
tasksCommands=taskInstances.map(function(v){return v.taskInstance.task.split(' ')[0];}).sort();
defaultCmd=tasks.find(function(v){return v.startsWith('run');});
}_context10.next=9;return _regenerator.default.awrap(

(0,_prompt.inquirerPrompt)({
type:'list',
default:defaultCmd,
name:'command',
message:"Pick a command"+addendum,
choices:tasks,
pageSize:15,
logMessage:'Welcome to the brave new world...'}));case 9:_await$inquirerPrompt=_context10.sent;command=_await$inquirerPrompt.command;

c.command=tasksCommands[tasks.indexOf(command)];case 12:

task=c.command;
if(c.subCommand)task+=" "+c.subCommand;

suitableEngines=REGISTERED_ENGINES.filter(function(engine){return engine.hasTask(task,c.paths.project.configExists);});
autocompleteEngines=REGISTERED_ENGINES.filter(function(engine){return engine.getSubTasks(task,true).length;});

isAutoComplete=!suitableEngines.length&&!!c.command&&!autocompleteEngines.length;
message=isAutoComplete?"Autocomplete action for \""+c.command+"\"":"Pick a subCommand for "+c.command;if(

suitableEngines.length){_context10.next=33;break;}

supportedSubtasksArr=[];
REGISTERED_ENGINES.forEach(function(engine){
engine.getSubTasks(task).forEach(function(taskInstance){
var isNotViable=!c.paths.project.configExists&&!taskInstance.isGlobalScope;
if(!isNotViable){var _taskInstance$descrip;
var taskKey=isAutoComplete?taskInstance.task:taskInstance.task.split(' ')[1];

supportedSubtasksArr.push({
desc:(_taskInstance$descrip=taskInstance.description)==null?void 0:_taskInstance$descrip.toLowerCase==null?void 0:_taskInstance$descrip.toLowerCase(),
taskKey:taskKey});

}
});
});
supportedSubtasks={};

supportedSubtasksFilter={};
supportedSubtasksArr.forEach(function(tsk){
var mergedTask=supportedSubtasksFilter[tsk.taskKey];
if(!mergedTask){
supportedSubtasksFilter[tsk.taskKey]=tsk;
}else if(!mergedTask.desc.includes(tsk.desc)){
mergedTask.desc+=", "+tsk.desc;
}
});

Object.values(supportedSubtasksFilter).forEach(function(v){
var desc=v.desc?"("+v.desc+")":'';
var key=v.taskKey+" "+(0,_logger.chalk)().grey(desc);
supportedSubtasks[key]={
taskKey:v.taskKey};

});

subTasks=Object.keys(supportedSubtasks);if(!
subTasks.length){_context10.next=33;break;}_context10.next=29;return _regenerator.default.awrap(
(0,_prompt.inquirerPrompt)({
type:'list',
name:'subCommand',
message:message,
choices:subTasks}));case 29:_await$inquirerPrompt2=_context10.sent;subCommand=_await$inquirerPrompt2.subCommand;

if(isAutoComplete){
task=supportedSubtasks[subCommand].taskKey;
c.command=task.split(' ')[0];
c.subCommand=task.split(' ')[1];
if(c.subCommand){
task=c.command+" "+c.subCommand;
}else{
task=""+c.command;
}
}else{
c.subCommand=supportedSubtasks[subCommand].taskKey;
task=c.command+" "+c.subCommand;
}


suitableEngines=REGISTERED_ENGINES.filter(function(engine){return engine.hasTask(task,c.paths.project.configExists);});case 33:if(



suitableEngines.length){_context10.next=38;break;}
(0,_logger.logError)("could not find suitable task for "+(0,_logger.chalk)().white(c.command));
c.command=null;
c.subCommand=null;return _context10.abrupt("return",
findSuitableTask(c));case 38:if(!(


!c.platform||c.platform===true)){_context10.next=48;break;}
supportedPlatforms={};
suitableEngines.forEach(function(engine){
engine.getTask(task).platforms.forEach(function(plat){
supportedPlatforms[plat]=true;
});
});
platforms=Object.keys(supportedPlatforms);if(!

platforms.length){_context10.next=48;break;}_context10.next=45;return _regenerator.default.awrap(
(0,_prompt.inquirerPrompt)({
type:'list',
name:'platform',
message:"Pick a platform for "+task,
choices:platforms}));case 45:_await$inquirerPrompt3=_context10.sent;platform=_await$inquirerPrompt3.platform;

c.platform=platform;case 48:


c.runtime.engine=getEngineRunner(c,task);
(0,_logger.logInfo)("Current Engine: "+(0,_logger.chalk)().bold.white(
c.runtime.engine.getId()));return _context10.abrupt("return",

c.runtime.engine.getTask(task));case 51:case"end":return _context10.stop();}}},null,null,null,Promise);};exports.findSuitableTask=findSuitableTask;


var getRegisteredEngines=function getRegisteredEngines(){return REGISTERED_ENGINES;};exports.getRegisteredEngines=getRegisteredEngines;
//# sourceMappingURL=index.js.map