var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.runAndroidLog=exports.runAndroid=exports.packageAndroid=exports.listAndroidTargets=exports.buildAndroid=exports.launchAndroidSimulator=exports.configureGradleProject=void 0;var _defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));var _slicedToArray2=_interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));var _regenerator=_interopRequireDefault(require("@babel/runtime/regenerator"));

var _path=_interopRequireDefault(require("path"));
var _os=_interopRequireDefault(require("os"));
var _fs=_interopRequireDefault(require("fs"));
var _net=_interopRequireDefault(require("net"));
var _chalk=_interopRequireDefault(require("chalk"));
var _shelljs=_interopRequireDefault(require("shelljs"));
var _child_process=_interopRequireDefault(require("child_process"));
var _inquirer=_interopRequireDefault(require("inquirer"));

var _exec=require("../../systemTools/exec");
var _platform=require("../../cli/platform");
var _common=require("../../common");













var _prompt=require("../../systemTools/prompt");
var _fileutils=require("../../systemTools/fileutils");
var _projectParser=require("../../projectTools/projectParser");
var _constants=require("../../constants");
var _pluginTools=require("../../pluginTools");
var _manifestParser=require("./manifestParser");
var _kotlinParser=require("./kotlinParser");
var _gradleParser=require("./gradleParser");



var _xmlValuesParser=require("./xmlValuesParser");function ownKeys(object,enumerableOnly){var keys=Object.keys(object);if(Object.getOwnPropertySymbols){var symbols=Object.getOwnPropertySymbols(object);if(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=arguments[i]!=null?arguments[i]:{};if(i%2){ownKeys(source,true).forEach(function(key){(0,_defineProperty2.default)(target,key,source[key]);});}else if(Object.getOwnPropertyDescriptors){Object.defineProperties(target,Object.getOwnPropertyDescriptors(source));}else{ownKeys(source).forEach(function(key){Object.defineProperty(target,key,Object.getOwnPropertyDescriptor(source,key));});}}return target;}

var readline=require('readline');

var CHECK_INTEVAL=5000;

var isRunningOnWindows=process.platform==='win32';

var currentDeviceProps={};

var composeDevicesString=function composeDevicesString(devices,returnArray){
(0,_common.logTask)("composeDevicesString:"+(devices?devices.length:null));
var devicesArray=[];
devices.forEach(function(v,i){return devicesArray.push(_getDeviceString(v,!returnArray?i:null));});
if(returnArray)return devicesArray;
return"\n"+devicesArray.join('');
};

var launchAndroidSimulator=function launchAndroidSimulator(c,platform,target){var isIndependentThread=arguments.length>3&&arguments[3]!==undefined?arguments[3]:false;
(0,_common.logTask)("launchAndroidSimulator:"+platform+":"+target+":"+isIndependentThread);var
maxErrorLength=c.program.maxErrorLength;

if(target==='?'||target===undefined||target===''){
return _listAndroidTargets(c,true,false,false).
then(function(devicesArr){
var devicesString=composeDevicesString(devicesArr);
var readlineInterface=readline.createInterface({
input:process.stdin,
output:process.stdout});

readlineInterface.question((0,_prompt.getQuestion)(devicesString+"\nType number of the emulator you want to launch"),function(v){
var selectedDevice=devicesArr[parseInt(v,10)-1];
if(selectedDevice){
return(0,_exec.execCLI)(c,_constants.CLI_ANDROID_EMULATOR,"-avd \""+selectedDevice.name+"\"",{detached:isIndependentThread});
}
(0,_common.logError)("Wrong choice "+v+"! Ingoring");
});
});
}

if(target){
var actualTarget=target.name||target;
if(isIndependentThread){
(0,_exec.execCLI)(c,_constants.CLI_ANDROID_EMULATOR,"-avd \""+actualTarget+"\"",{detached:isIndependentThread}).catch(function(err){
if(err.includes&&err.includes('WHPX')){
(0,_common.logWarning)(err);
return(0,_common.logError)('It seems you do not have the Windows Hypervisor Platform virtualization enabled. Enter windows features in the Windows search box and select Turn Windows features on or off in the search results. In the Windows Features dialog, enable both Hyper-V and Windows Hypervisor Platform.',true);
}
(0,_common.logError)(err);
});
return Promise.resolve();
}
return(0,_exec.execCLI)(c,_constants.CLI_ANDROID_EMULATOR,"-avd \""+actualTarget+"\"",{detached:isIndependentThread});
}
return Promise.reject('No simulator -t target name specified!');
};exports.launchAndroidSimulator=launchAndroidSimulator;

var listAndroidTargets=function listAndroidTargets(c){var device,list,devices;return _regenerator.default.async(function listAndroidTargets$(_context){while(1){switch(_context.prev=_context.next){case 0:
(0,_common.logTask)('listAndroidTargets');
device=c.program.device;_context.next=4;return _regenerator.default.awrap(

resetAdb(c));case 4:_context.next=6;return _regenerator.default.awrap(
_listAndroidTargets(c,false,device,device));case 6:list=_context.sent;_context.next=9;return _regenerator.default.awrap(
composeDevicesString(list));case 9:devices=_context.sent;
console.log(devices);
if(devices.trim()==='')console.log('No devices found');return _context.abrupt("return",
devices);case 13:case"end":return _context.stop();}}});};exports.listAndroidTargets=listAndroidTargets;


var _getDeviceString=function _getDeviceString(device,i){var

isTV=
device.isTV,isTablet=device.isTablet,name=device.name,udid=device.udid,isDevice=device.isDevice,isActive=device.isActive,avdConfig=device.avdConfig,isWear=device.isWear,arch=device.arch;
var deviceIcon='';
if(isTablet)deviceIcon='Tablet 💊 ';
if(isTV)deviceIcon='TV 📺 ';
if(isWear)deviceIcon='Wear ⌚ ';
if(!deviceIcon&&(udid!=='unknown'||avdConfig))deviceIcon='Phone 📱 ';

var deviceString=_chalk.default.white(name)+" | "+deviceIcon+" | arch: "+arch+" | udid: "+_chalk.default.blue(udid)+(isDevice?_chalk.default.red(' (device)'):'')+" "+(
isActive?_chalk.default.magenta(' (active)'):'');

if(i===null)return{key:name,name:deviceString,value:name};

return"-["+(i+1)+"] "+deviceString+"\n";
};

var resetAdb=function resetAdb(c){var maxErrorLength;return _regenerator.default.async(function resetAdb$(_context2){while(1){switch(_context2.prev=_context2.next){case 0:
maxErrorLength=c.program.maxErrorLength;_context2.next=3;return _regenerator.default.awrap(
(0,_exec.execCLI)(c,_constants.CLI_ANDROID_ADB,'kill-server'));case 3:_context2.next=5;return _regenerator.default.awrap(
(0,_exec.execCLI)(c,_constants.CLI_ANDROID_ADB,'start-server'));case 5:case"end":return _context2.stop();}}});};


var _listAndroidTargets=function _listAndroidTargets(c,skipDevices,skipAvds){var deviceOnly,maxErrorLength,devicesResult,avdResult,_args3=arguments;return _regenerator.default.async(function _listAndroidTargets$(_context3){while(1){switch(_context3.prev=_context3.next){case 0:deviceOnly=_args3.length>3&&_args3[3]!==undefined?_args3[3]:false;
(0,_common.logTask)("_listAndroidTargets:"+c.platform+":"+skipDevices+":"+skipAvds+":"+deviceOnly);
maxErrorLength=c.program.maxErrorLength;_context3.prev=3;if(





skipDevices){_context3.next=8;break;}_context3.next=7;return _regenerator.default.awrap(
(0,_exec.execCLI)(c,_constants.CLI_ANDROID_ADB,'devices -l'));case 7:devicesResult=_context3.sent;case 8:if(

skipAvds){_context3.next=12;break;}_context3.next=11;return _regenerator.default.awrap(
(0,_exec.execCLI)(c,_constants.CLI_ANDROID_EMULATOR,'-list-avds'));case 11:avdResult=_context3.sent;case 12:return _context3.abrupt("return",

_parseDevicesResult(devicesResult,avdResult,deviceOnly,c));case 15:_context3.prev=15;_context3.t0=_context3["catch"](3);return _context3.abrupt("return",

Promise.reject(_context3.t0));case 18:case"end":return _context3.stop();}}},null,null,[[3,15]]);};



var calculateDeviceDiagonal=function calculateDeviceDiagonal(width,height,density){

var widthInches=width/density;
var heightInches=height/density;
return Math.sqrt(widthInches*widthInches+heightInches*heightInches);
};

var isSquareishDevice=function isSquareishDevice(width,height){
var ratio=width/height;
if(ratio>0.8&&ratio<1.2)return true;
return false;
};

var getRunningDeviceProp=function getRunningDeviceProp(c,udid,prop){var maxErrorLength,rawProps,reg,lines;return _regenerator.default.async(function getRunningDeviceProp$(_context4){while(1){switch(_context4.prev=_context4.next){case 0:
maxErrorLength=c.program.maxErrorLength;if(!

currentDeviceProps[udid]){_context4.next=5;break;}if(
prop){_context4.next=4;break;}return _context4.abrupt("return",currentDeviceProps[udid]);case 4:return _context4.abrupt("return",
currentDeviceProps[udid][prop]);case 5:_context4.next=7;return _regenerator.default.awrap(

(0,_exec.execCLI)(c,_constants.CLI_ANDROID_ADB,"-s "+udid+" shell getprop"));case 7:rawProps=_context4.sent;
reg=/\[.+\]: \[.*\n?[^\[]*\]/gm;
lines=rawProps.match(reg);

lines.forEach(function(line){
var words=line.split(']: [');
var key=words[0].slice(1);
var value=words[1].slice(0,words[1].length-1);

if(!currentDeviceProps[udid])currentDeviceProps[udid]={};
currentDeviceProps[udid][key]=value;
});return _context4.abrupt("return",

getRunningDeviceProp(c,udid,prop));case 12:case"end":return _context4.stop();}}});};


var decideIfTVRunning=function decideIfTVRunning(c,device){var udid,model,product,mod,name,flavor,description,hdmi,modelGroup,configuration,cecEnabled,isTV;return _regenerator.default.async(function decideIfTVRunning$(_context5){while(1){switch(_context5.prev=_context5.next){case 0:
udid=device.udid,model=device.model,product=device.product;_context5.next=3;return _regenerator.default.awrap(
getRunningDeviceProp(c,udid,'ro.product.model'));case 3:mod=_context5.sent;_context5.next=6;return _regenerator.default.awrap(
getRunningDeviceProp(c,udid,'ro.product.name'));case 6:name=_context5.sent;_context5.next=9;return _regenerator.default.awrap(
getRunningDeviceProp(c,udid,'ro.build.flavor'));case 9:flavor=_context5.sent;_context5.next=12;return _regenerator.default.awrap(
getRunningDeviceProp(c,udid,'ro.build.description'));case 12:description=_context5.sent;_context5.next=15;return _regenerator.default.awrap(
getRunningDeviceProp(c,udid,'init.svc.hdmi'));case 15:hdmi=_context5.sent;_context5.next=18;return _regenerator.default.awrap(
getRunningDeviceProp(c,udid,'ro.nrdp.modelgroup'));case 18:modelGroup=_context5.sent;_context5.next=21;return _regenerator.default.awrap(
getRunningDeviceProp(c,udid,'ro.build.configuration'));case 21:configuration=_context5.sent;_context5.next=24;return _regenerator.default.awrap(
getRunningDeviceProp(c,udid,'persist.sys.cec.enabled'));case 24:cecEnabled=_context5.sent;

isTV=false;
[mod,name,flavor,description,model,product].forEach(function(string){
if(string&&string.toLowerCase().includes('tv'))isTV=true;
});

if(model.includes('SHIELD'))isTV=true;
if(hdmi)isTV=true;
if(modelGroup&&modelGroup.toLowerCase().includes('firetv'))isTV=true;
if(configuration==='tv')isTV=true;
if(cecEnabled)isTV=true;return _context5.abrupt("return",

isTV);case 33:case"end":return _context5.stop();}}});};


var decideIfWearRunning=function decideIfWearRunning(c,device){var udid,model,product,fingerprint,name,mod,flavor,description,isWear;return _regenerator.default.async(function decideIfWearRunning$(_context6){while(1){switch(_context6.prev=_context6.next){case 0:
udid=device.udid,model=device.model,product=device.product;_context6.next=3;return _regenerator.default.awrap(
getRunningDeviceProp(c,udid,'ro.vendor.build.fingerprint'));case 3:fingerprint=_context6.sent;_context6.next=6;return _regenerator.default.awrap(
getRunningDeviceProp(c,udid,'ro.product.vendor.name'));case 6:name=_context6.sent;_context6.next=9;return _regenerator.default.awrap(
getRunningDeviceProp(c,udid,'ro.product.vendor.model'));case 9:mod=_context6.sent;_context6.next=12;return _regenerator.default.awrap(
getRunningDeviceProp(c,udid,'ro.build.flavor'));case 12:flavor=_context6.sent;_context6.next=15;return _regenerator.default.awrap(
getRunningDeviceProp(c,udid,'ro.build.description'));case 15:description=_context6.sent;

isWear=false;
[fingerprint,name,mod,flavor,description,model,product].forEach(function(string){
if(string&&string.toLowerCase().includes('wear'))isWear=true;
});return _context6.abrupt("return",
isWear);case 19:case"end":return _context6.stop();}}});};


var getDeviceType=function getDeviceType(device,c){var maxErrorLength,screenSizeResult,screenDensityResult,arch,screenProps,_screenSizeResult$spl,_screenSizeResult$spl2,width,height,density,_screenProps,_width,_height,_density,diagonalInches,_density2,_width2,_height2,_arch,sysdir,tagId,tagDisplay,deviceName,avdId,name,skin,image,_diagonalInches;return _regenerator.default.async(function getDeviceType$(_context7){while(1){switch(_context7.prev=_context7.next){case 0:
(0,_common.logDebug)('getDeviceType - in',{device:device});
maxErrorLength=c.program.maxErrorLength;if(!(

device.udid!=='unknown')){_context7.next=31;break;}_context7.next=5;return _regenerator.default.awrap(
(0,_exec.execCLI)(c,_constants.CLI_ANDROID_ADB,"-s "+device.udid+" shell wm size"));case 5:screenSizeResult=_context7.sent;_context7.next=8;return _regenerator.default.awrap(
(0,_exec.execCLI)(c,_constants.CLI_ANDROID_ADB,"-s "+device.udid+" shell wm density"));case 8:screenDensityResult=_context7.sent;_context7.next=11;return _regenerator.default.awrap(
getRunningDeviceProp(c,device.udid,'ro.product.cpu.abi'));case 11:arch=_context7.sent;


if(screenSizeResult){_screenSizeResult$spl=
screenSizeResult.split('Physical size: ')[1].split('x'),_screenSizeResult$spl2=(0,_slicedToArray2.default)(_screenSizeResult$spl,2),width=_screenSizeResult$spl2[0],height=_screenSizeResult$spl2[1];
screenProps={width:parseInt(width,10),height:parseInt(height,10)};
}

if(screenDensityResult){
density=screenDensityResult.split('Physical density: ')[1];
screenProps=_objectSpread({},screenProps,{density:parseInt(density,10)});
}_context7.next=16;return _regenerator.default.awrap(

decideIfTVRunning(c,device));case 16:device.isTV=_context7.sent;if(!(

screenSizeResult&&screenDensityResult)){_context7.next=25;break;}_screenProps=
screenProps,_width=_screenProps.width,_height=_screenProps.height,_density=_screenProps.density;

diagonalInches=calculateDeviceDiagonal(_width,_height,_density);
screenProps=_objectSpread({},screenProps,{diagonalInches:diagonalInches});
device.isTablet=!device.isTV&&diagonalInches>_constants.IS_TABLET_ABOVE_INCH&&diagonalInches<=15;_context7.next=24;return _regenerator.default.awrap(
decideIfWearRunning(c,device));case 24:device.isWear=_context7.sent;case 25:


device.isPhone=!device.isTablet&&!device.isWear&&!device.isTV;
device.isMobile=!device.isWear&&!device.isTV;
device.screenProps=screenProps;
device.arch=arch;
(0,_common.logDebug)('getDeviceType - out',{device:device});return _context7.abrupt("return",
device);case 31:if(!


device.avdConfig){_context7.next=55;break;}
_density2=parseInt(device.avdConfig['hw.lcd.density'],10);
_width2=parseInt(device.avdConfig['hw.lcd.width'],10);
_height2=parseInt(device.avdConfig['hw.lcd.height'],10);
_arch=device.avdConfig['abi.type'];


sysdir=device.avdConfig['image.sysdir.1'];
tagId=device.avdConfig['tag.id'];
tagDisplay=device.avdConfig['tag.display'];
deviceName=device.avdConfig['hw.device.name'];

device.isWear=false;
[sysdir,tagId,tagDisplay,deviceName].forEach(function(string){
if(string&&string.includes('wear'))device.isWear=true;
});

avdId=device.avdConfig.AvdId;
name=device.avdConfig['hw.device.name'];
skin=device.avdConfig['skin.name'];
image=device.avdConfig['image.sysdir.1'];

device.isTV=false;
[avdId,name,skin,image].forEach(function(string){
if(string&&string.toLowerCase().includes('tv'))device.isTV=true;
});

_diagonalInches=calculateDeviceDiagonal(_width2,_height2,_density2);
device.isTablet=!device.isTV&&_diagonalInches>_constants.IS_TABLET_ABOVE_INCH;
device.isPhone=!device.isTablet&&!device.isWear&&!device.isTV;
device.isMobile=!device.isWear&&!device.isTV;
device.arch=_arch;
(0,_common.logDebug)('getDeviceType - out',{device:device});return _context7.abrupt("return",
device);case 55:return _context7.abrupt("return",

device);case 56:case"end":return _context7.stop();}}});};


var getAvdDetails=function getAvdDetails(c,deviceName){var _process$env=
process.env,ANDROID_SDK_HOME=_process$env.ANDROID_SDK_HOME,ANDROID_AVD_HOME=_process$env.ANDROID_AVD_HOME;


var avdConfigPaths=[""+
ANDROID_AVD_HOME,
ANDROID_SDK_HOME+"/.android/avd",
_os.default.homedir()+"/.android/avd"];


var results={};

avdConfigPaths.forEach(function(cPath){
if(_fs.default.existsSync(cPath)){
var filesPath=_fs.default.readdirSync(cPath);


filesPath.forEach(function(fName){
var fPath=_path.default.join(cPath,fName);
var dirent=_fs.default.lstatSync(fPath);
if(!dirent.isDirectory()&&fName===deviceName+".ini"){
var avdData=_fs.default.readFileSync(fPath).toString();
var lines=avdData.trim().split(/\r?\n/);
lines.forEach(function(line){var _line$split=
line.split('='),_line$split2=(0,_slicedToArray2.default)(_line$split,2),key=_line$split2[0],value=_line$split2[1];
if(key==='path'){
var initData=_fs.default.readFileSync(value+"/config.ini").toString();
var initLines=initData.trim().split(/\r?\n/);
var avdConfig={};
initLines.forEach(function(initLine){var _initLine$split=
initLine.split('='),_initLine$split2=(0,_slicedToArray2.default)(_initLine$split,2),iniKey=_initLine$split2[0],iniValue=_initLine$split2[1];

avdConfig[iniKey.trim()]=iniValue.trim();
});
results.avdConfig=avdConfig;
}
});
}
});
}
});
return results;
};

var getEmulatorName=function getEmulatorName(words){var emulator,port,emulatorReply,emulatorReplyArray,emulatorName;return _regenerator.default.async(function getEmulatorName$(_context8){while(1){switch(_context8.prev=_context8.next){case 0:
emulator=words[0];
port=emulator.split('-')[1];_context8.next=4;return _regenerator.default.awrap(

(0,_exec.executeTelnet)(port,'avd name'));case 4:emulatorReply=_context8.sent;
emulatorReplyArray=emulatorReply.split('OK');
emulatorName=emulatorReplyArray[emulatorReplyArray.length-2].trim();return _context8.abrupt("return",
emulatorName);case 8:case"end":return _context8.stop();}}});};


var connectToWifiDevice=function connectToWifiDevice(c,ip){var maxErrorLength,deviceResponse;return _regenerator.default.async(function connectToWifiDevice$(_context9){while(1){switch(_context9.prev=_context9.next){case 0:
maxErrorLength=c.program.maxErrorLength;_context9.next=3;return _regenerator.default.awrap(

(0,_exec.execCLI)(c,_constants.CLI_ANDROID_ADB,"connect "+ip+":5555"));case 3:deviceResponse=_context9.sent;if(!
deviceResponse.includes('connected')){_context9.next=6;break;}return _context9.abrupt("return",true);case 6:
(0,_common.logError)("Failed to connect to "+ip+":5555");return _context9.abrupt("return",
false);case 8:case"end":return _context9.stop();}}});};


var _parseDevicesResult=function _parseDevicesResult(devicesString,avdsString,deviceOnly,c){var devices,skipTargetCheck,lines,avdLines;return _regenerator.default.async(function _parseDevicesResult$(_context12){while(1){switch(_context12.prev=_context12.next){case 0:
(0,_common.logDebug)("_parseDevicesResult:"+devicesString+":"+avdsString+":"+deviceOnly);
devices=[];
skipTargetCheck=c.program.skipTargetCheck;if(!

devicesString){_context12.next=9;break;}
lines=devicesString.trim().split(/\r?\n/);
(0,_common.logDebug)('_parseDevicesResult 2',{lines:lines});if(!(
lines.length!==0)){_context12.next=9;break;}_context12.next=9;return _regenerator.default.awrap(
Promise.all(lines.map(function _callee(line){var words,isDevice,name,model,product;return _regenerator.default.async(function _callee$(_context10){while(1){switch(_context10.prev=_context10.next){case 0:
words=line.split(/[ ,\t]+/).filter(function(w){return w!=='';});if(!(
words.length===0)){_context10.next=3;break;}return _context10.abrupt("return");case 3:
(0,_common.logDebug)('_parseDevicesResult 3',{words:words});if(!(

words[1]==='device')){_context10.next=20;break;}
isDevice=!words[0].includes('emulator');
name=_getDeviceProp(words,'model:');
model=name;
product=_getDeviceProp(words,'product:');
(0,_common.logDebug)('_parseDevicesResult 4',{name:name});if(
isDevice){_context10.next=17;break;}_context10.next=13;return _regenerator.default.awrap(
waitForEmulatorToBeReady(c,words[0]));case 13:_context10.next=15;return _regenerator.default.awrap(
getEmulatorName(words));case 15:name=_context10.sent;
(0,_common.logDebug)('_parseDevicesResult 5',{name:name});case 17:

(0,_common.logDebug)('_parseDevicesResult 6',{deviceOnly:deviceOnly,isDevice:isDevice});
if(deviceOnly&&isDevice||!deviceOnly){
devices.push({
udid:words[0],
isDevice:isDevice,
isActive:true,
name:name,
model:model,
product:product});

}return _context10.abrupt("return",
true);case 20:case"end":return _context10.stop();}}});})));case 9:if(!





avdsString){_context12.next=14;break;}
avdLines=avdsString.trim().split(/\r?\n/);
(0,_common.logDebug)('_parseDevicesResult 7',{avdLines:avdLines});_context12.next=14;return _regenerator.default.awrap(

Promise.all(avdLines.map(function _callee2(line){var avdDetails,findProcess;return _regenerator.default.async(function _callee2$(_context11){while(1){switch(_context11.prev=_context11.next){case 0:


try{
avdDetails=getAvdDetails(c,line);
}catch(e){
(0,_common.logError)(e);
}

try{
(0,_common.logDebug)('_parseDevicesResult 8',{avdDetails:avdDetails});



findProcess=isRunningOnWindows?"tasklist | find \"avd "+line+"\"":"ps x | grep \"avd "+line+"\" | grep -v grep";
_child_process.default.execSync(findProcess);
(0,_common.logDebug)('_parseDevicesResult 9 - excluding running emulator');
}catch(e){
if(avdDetails){
devices.push(_objectSpread({
udid:'unknown',
isDevice:false,
isActive:false,
name:line},
avdDetails));

}
}case 2:case"end":return _context11.stop();}}});})));case 14:



(0,_common.logDebug)('_parseDevicesResult 10',{devices:devices});return _context12.abrupt("return",

Promise.all(devices.map(function(device){return getDeviceType(device,c);})).
then(function(devicesArray){return devicesArray.filter(function(device){var

platform=c.platform;
if(skipTargetCheck)return true;
var matches=platform===_constants.ANDROID&&device.isTablet||platform===_constants.ANDROID_WEAR&&device.isWear||platform===_constants.ANDROID_TV&&device.isTV||platform===_constants.ANDROID&&device.isMobile;
(0,_common.logDebug)('getDeviceType - filter',{device:device,matches:matches,platform:platform});
return matches;
});}));case 16:case"end":return _context12.stop();}}});};


var _getDeviceProp=function _getDeviceProp(arr,prop){
for(var i=0;i<arr.length;i++){
var v=arr[i];
if(v&&v.includes(prop))return v.replace(prop,'');
}
return'';
};

var _askForNewEmulator=function _askForNewEmulator(c,platform){return new Promise(function(resolve,reject){
(0,_common.logTask)('_askForNewEmulator');
var emuName=c.files.private.config.defaultTargets[platform];
var readlineInterface=readline.createInterface({
input:process.stdin,
output:process.stdout});

readlineInterface.question(
(0,_prompt.getQuestion)("Do you want ReNative to create new Emulator ("+_chalk.default.white(emuName)+") for you? (y) to confirm"),
function(v){
if(v.toLowerCase()==='y'){
switch(platform){
case'android':
return _createEmulator(c,'28','google_apis',emuName).
then(function(){return launchAndroidSimulator(c,platform,emuName,true);}).
then(resolve);
case'androidtv':
return _createEmulator(c,'28','android-tv',emuName).
then(function(){return launchAndroidSimulator(c,platform,emuName,true);}).
then(resolve);
case'androidwear':
return _createEmulator(c,'28','android-wear',emuName).
then(function(){return launchAndroidSimulator(c,platform,emuName,true);}).
then(resolve);
default:
return reject('Cannot find any active or created emulators');}

}else{
reject('Cannot find any active or created emulators');
}
});

});};

var _createEmulator=function _createEmulator(c,apiVersion,emuPlatform,emuName){
(0,_common.logTask)('_createEmulator');var
maxErrorLength=c.program.maxErrorLength;

return(0,_exec.execCLI)(c,_constants.CLI_ANDROID_SDKMANAGER,"\"system-images;android-"+apiVersion+";"+emuPlatform+";x86\"").
then(function(){return(0,_exec.execCLI)(c,_constants.CLI_ANDROID_AVDMANAGER,"create avd -n "+emuName+" -k system-images;android-"+apiVersion+";"+emuPlatform+";x86");}).
catch(function(e){return(0,_common.logError)(e,true);});
};

var packageAndroid=function packageAndroid(c,platform){return new Promise(function(resolve,reject){
(0,_common.logTask)("packageAndroid:"+platform);var


entryFile=c.buildConfig.platforms[platform].entryFile;

var outputFile;
if(platform===_constants.ANDROID_WEAR){
outputFile=entryFile;
}else{
outputFile='index.android';
}


var appFolder=(0,_common.getAppFolder)(c,platform);
var reactNative='react-native';

if(isRunningOnWindows){
reactNative=_path.default.normalize(process.cwd()+"/node_modules/.bin/react-native.cmd");
}

console.log('ANDROID PACKAGE STARTING...');
(0,_exec.executeAsync)(c,reactNative+" bundle --platform android --dev false --assets-dest "+appFolder+"/app/src/main/res --entry-file "+entryFile+".js --bundle-output "+appFolder+"/app/src/main/assets/"+outputFile+".bundle").
then(function(){
console.log('ANDROID PACKAGE FINISHED');
return resolve();
}).
catch(function(e){
console.log('ANDROID PACKAGE FAILED');
return reject(e);
});
});};exports.packageAndroid=packageAndroid;

var waitForEmulatorToBeReady=function waitForEmulatorToBeReady(c,emulator){return(0,_common.waitForEmulator)(c,_constants.CLI_ANDROID_ADB,"-s "+emulator+" shell getprop init.svc.bootanim",function(res){return res.includes('stopped');});};

var runAndroid=function runAndroid(c,platform,target){return new Promise(function(resolve,reject){
(0,_common.logTask)("runAndroid:"+platform+":"+target);

var bundleAssets=(0,_common.getConfigProp)(c,platform,'bundleAssets',false)===true;
var bundleIsDev=(0,_common.getConfigProp)(c,platform,'bundleIsDev',false)===true;

if(bundleAssets){
packageAndroid(c,platform,bundleIsDev).
then(function(){return _runGradle(c,platform);}).
then(function(){return resolve();}).
catch(function(e){return reject(e);});
}else{
_runGradle(c,platform).
then(function(){return resolve();}).
catch(function(e){return reject(e);});
}
});};exports.runAndroid=runAndroid;

var _runGradle=function _runGradle(c,platform){var outputAab,target,devicesAndEmulators,activeDevices,inactiveDevices,askWhereToRun,foundDevice,device,dv;return _regenerator.default.async(function _runGradle$(_context14){while(1){switch(_context14.prev=_context14.next){case 0:
(0,_common.logTask)("_runGradle:"+platform);
outputAab=(0,_common.getConfigProp)(c,platform,'aab',false);if(!

outputAab){_context14.next=4;break;}return _context14.abrupt("return",_runGradleApp(c,platform,{}));case 4:

target=c.program.target;_context14.next=7;return _regenerator.default.awrap(

resetAdb(c));case 7:if(!(

target&&_net.default.isIP(target))){_context14.next=10;break;}_context14.next=10;return _regenerator.default.awrap(
connectToWifiDevice(c,target));case 10:_context14.prev=10;_context14.next=13;return _regenerator.default.awrap(




_listAndroidTargets(c,false,false,c.program.device!==undefined));case 13:devicesAndEmulators=_context14.sent;_context14.next=19;break;case 16:_context14.prev=16;_context14.t0=_context14["catch"](10);return _context14.abrupt("return",

Promise.reject(_context14.t0));case 19:

activeDevices=devicesAndEmulators.filter(function(d){return d.isActive;});
inactiveDevices=devicesAndEmulators.filter(function(d){return!d.isActive;});

askWhereToRun=function askWhereToRun(){var devicesString,choices,response,devices,_devicesString,_choices,_response,dev,_devices;return _regenerator.default.async(function askWhereToRun$(_context13){while(1){switch(_context13.prev=_context13.next){case 0:if(!(
activeDevices.length===0&&inactiveDevices.length>0)){_context13.next=16;break;}

devicesString=composeDevicesString(inactiveDevices,true);
choices=devicesString;_context13.next=5;return _regenerator.default.awrap(
_inquirer.default.prompt([{
name:'chosenEmulator',
type:'list',
message:'What emulator would you like to start?',
choices:choices}]));case 5:response=_context13.sent;if(!

response.chosenEmulator){_context13.next=14;break;}_context13.next=9;return _regenerator.default.awrap(
launchAndroidSimulator(c,platform,response.chosenEmulator,true));case 9:_context13.next=11;return _regenerator.default.awrap(
_checkForActiveEmulator(c,platform));case 11:devices=_context13.sent;_context13.next=14;return _regenerator.default.awrap(
_runGradleApp(c,platform,devices));case 14:_context13.next=35;break;case 16:if(!(

activeDevices.length>1)){_context13.next=28;break;}
_devicesString=composeDevicesString(activeDevices,true);
_choices=_devicesString;_context13.next=21;return _regenerator.default.awrap(
_inquirer.default.prompt([{
name:'chosenEmulator',
type:'list',
message:'Where would you like to run your app?',
choices:_choices}]));case 21:_response=_context13.sent;if(!

_response.chosenEmulator){_context13.next=26;break;}
dev=activeDevices.find(function(d){return d.name===_response.chosenEmulator;});_context13.next=26;return _regenerator.default.awrap(
_runGradleApp(c,platform,dev));case 26:_context13.next=35;break;case 28:_context13.next=30;return _regenerator.default.awrap(


_askForNewEmulator(c,platform));case 30:_context13.next=32;return _regenerator.default.awrap(
_checkForActiveEmulator(c,platform));case 32:_devices=_context13.sent;_context13.next=35;return _regenerator.default.awrap(
_runGradleApp(c,platform,_devices));case 35:case"end":return _context13.stop();}}});};if(!



target){_context14.next=44;break;}
(0,_common.logDebug)('Target provided',target);
foundDevice=devicesAndEmulators.find(function(d){return d.udid.includes(target)||d.name.includes(target);});if(!
foundDevice){_context14.next=40;break;}if(!
foundDevice.isActive){_context14.next=31;break;}_context14.next=29;return _regenerator.default.awrap(
_runGradleApp(c,platform,foundDevice));case 29:_context14.next=38;break;case 31:_context14.next=33;return _regenerator.default.awrap(

launchAndroidSimulator(c,platform,foundDevice,true));case 33:_context14.next=35;return _regenerator.default.awrap(
_checkForActiveEmulator(c,platform));case 35:device=_context14.sent;_context14.next=38;return _regenerator.default.awrap(
_runGradleApp(c,platform,device));case 38:_context14.next=42;break;case 40:_context14.next=42;return _regenerator.default.awrap(


askWhereToRun());case 42:_context14.next=54;break;case 44:if(!(

activeDevices.length===1)){_context14.next=51;break;}

dv=activeDevices[0];
(0,_common.logInfo)("Found device "+dv.name+":"+dv.udid+"!");_context14.next=49;return _regenerator.default.awrap(
_runGradleApp(c,platform,dv));case 49:_context14.next=54;break;case 51:

(0,_common.logDebug)('Target not provided, asking where to run');_context14.next=54;return _regenerator.default.awrap(
askWhereToRun());case 54:case"end":return _context14.stop();}}},null,null,[[10,16]]);};



var _checkForActiveEmulator=function _checkForActiveEmulator(c,platform){return new Promise(function(resolve,reject){
(0,_common.logTask)("_checkForActiveEmulator:"+platform);
var attempts=1;
var maxAttempts=isRunningOnWindows?20:10;
var running=false;
var poll=setInterval(function(){

if(!running){
running=true;
_listAndroidTargets(c,false,true,false).
then(function(v){
if(v.length>0){
(0,_common.logSuccess)("Found active emulator! "+_chalk.default.white(v[0].udid)+". Will use it");
clearInterval(poll);
resolve(v[0]);
}else{
running=false;
console.log("looking for active emulators: attempt "+attempts+"/"+maxAttempts);
attempts++;
if(attempts>maxAttempts){
clearInterval(poll);
reject('Could not find any active emulatros');



}
}
}).
catch(function(e){
clearInterval(poll);
(0,_common.logError)(e);
});
}
},CHECK_INTEVAL);
});};

var _checkSigningCerts=function _checkSigningCerts(c){return new Promise(function(resolve,reject){
(0,_common.logTask)('_checkSigningCerts');
var signingConfig=(0,_common.getConfigProp)(c,c.platform,'signingConfig','Debug');

if(signingConfig==='Release'&&!c.files.private.appConfig.configPrivate){
(0,_common.logError)("You're attempting to "+c.command+" app in release mode but you have't configured your "+_chalk.default.white(c.paths.private.appConfig.dir)+" yet.");
(0,_prompt.askQuestion)('Do you want to configure it now? (y)').
then(function(v){
var sc={};
if(v==='y'){
(0,_prompt.askQuestion)("Paste asolute or relative path to "+_chalk.default.white(c.paths.private.appConfig.dir)+" of your existing "+_chalk.default.white('release.keystore')+" file.",sc,'storeFile').
then(function(){return(0,_prompt.askQuestion)('storePassword',sc,'storePassword');}).
then(function(){return(0,_prompt.askQuestion)('keyAlias',sc,'keyAlias');}).
then(function(){return(0,_prompt.askQuestion)('keyPassword',sc,'keyPassword');}).
then(function(){
(0,_prompt.finishQuestion)();
if(c.paths.private.appConfig.dir){
(0,_fileutils.mkdirSync)(c.paths.private.appConfig.dir);
c.files.private.appConfig.configPrivate={
android:sc};

}
_fs.default.writeFileSync(c.paths.private.appConfig.configPrivate,JSON.stringify(c.files.private.appConfig.configPrivate,null,2));
(0,_common.logSuccess)("Successfully created private config file at "+_chalk.default.white(c.paths.private.appConfig.dir)+".");
resolve();
});
}else{
reject("You selected "+v+". Can't proceed");
}
}).catch(function(e){return reject(e);});
}else{
resolve();
}
});};

var _runGradleApp=function _runGradleApp(c,platform,device){return new Promise(function(resolve,reject){
(0,_common.logTask)("_runGradleApp:"+platform);

var signingConfig=(0,_common.getConfigProp)(c,platform,'signingConfig','Debug');
var appFolder=(0,_common.getAppFolder)(c,platform);
var bundleId=(0,_common.getAppId)(c,platform);
var outputAab=(0,_common.getConfigProp)(c,platform,'aab',false);
var outputFolder=signingConfig==='Debug'?'debug':'release';var
arch=device.arch,name=device.name;

_shelljs.default.cd(""+appFolder);

_checkSigningCerts(c).
then(function(){return(0,_exec.executeAsync)(c,(isRunningOnWindows?'gradlew.bat':'./gradlew')+" "+(outputAab?'bundle':'assemble')+signingConfig+" -x bundleReleaseJsAndAssets");}).
then(function(){
if(outputAab){
var aabPath=_path.default.join(appFolder,"app/build/outputs/bundle/"+outputFolder+"/app.aab");
(0,_common.logInfo)("App built. Path "+aabPath);
return Promise.resolve();
}
var apkPath=_path.default.join(appFolder,"app/build/outputs/apk/"+outputFolder+"/app-"+outputFolder+".apk");
if(!_fs.default.existsSync(apkPath)){
apkPath=_path.default.join(appFolder,"app/build/outputs/apk/"+outputFolder+"/app-"+outputFolder+"-unsigned.apk");
}if(!_fs.default.existsSync(apkPath)){
apkPath=_path.default.join(appFolder,"app/build/outputs/apk/"+outputFolder+"/app-"+arch+"-"+outputFolder+".apk");
}
(0,_common.logInfo)("Installing "+apkPath+" on "+name);
return(0,_exec.execCLI)(c,_constants.CLI_ANDROID_ADB,"-s "+device.udid+" install -r -d -f "+apkPath);
}).
then(function(){return!outputAab&&device.isDevice&&platform!==_constants.ANDROID_WEAR?
(0,_exec.execCLI)(c,_constants.CLI_ANDROID_ADB,"-s "+device.udid+" reverse tcp:8081 tcp:8081"):
Promise.resolve();}).
then(function(){return!outputAab&&(0,_exec.execCLI)(c,_constants.CLI_ANDROID_ADB,"-s "+device.udid+" shell am start -n "+bundleId+"/.MainActivity");}).
then(function(){return resolve();}).
catch(function(e){return reject(e);});
});};

var buildAndroid=function buildAndroid(c,platform){return new Promise(function(resolve,reject){
(0,_common.logTask)("buildAndroid:"+platform);

var appFolder=(0,_common.getAppFolder)(c,platform);
var signingConfig=(0,_common.getConfigProp)(c,platform,'signingConfig','Debug');

_shelljs.default.cd(""+appFolder);

_checkSigningCerts(c).
then(function(){return(0,_exec.executeAsync)(c,(isRunningOnWindows?'gradlew.bat':'./gradlew')+" assemble"+signingConfig+" -x bundleReleaseJsAndAssets");}).
then(function(){
(0,_common.logSuccess)("Your APK is located in "+_chalk.default.white(_path.default.join(appFolder,"app/build/outputs/apk/"+signingConfig.toLowerCase()))+" .");
resolve();
}).catch(function(e){return reject(e);});
});};exports.buildAndroid=buildAndroid;

var configureAndroidProperties=function configureAndroidProperties(c,platform){return new Promise(function(resolve){
(0,_common.logTask)("configureAndroidProperties:"+platform);

var appFolder=(0,_common.getAppFolder)(c,platform);

var addNDK=c.files.private.config.sdks.ANDROID_NDK&&!c.files.private.config.sdks.ANDROID_NDK.includes('<USER>');
var ndkString="ndk.dir="+c.files.private.config.sdks.ANDROID_NDK;
var sdkDir=c.files.private.config.sdks.ANDROID_SDK;

if(isRunningOnWindows){
sdkDir=sdkDir.replace(/\\/g,'/');
}

_fs.default.writeFileSync(
_path.default.join(appFolder,'local.properties'),"#Generated by ReNative (https://renative.org)\n"+(

addNDK?ndkString:'')+"\nsdk.dir="+
sdkDir);


resolve();
});};

var configureGradleProject=function configureGradleProject(c,platform){return new Promise(function(resolve,reject){
(0,_common.logTask)("configureGradleProject:"+platform);

if(!(0,_common.isPlatformActive)(c,platform,resolve))return;


(0,_projectParser.copyAssetsFolder)(c,platform).
then(function(){return(0,_projectParser.copyBuildsFolder)(c,platform);}).
then(function(){return configureAndroidProperties(c,platform);}).
then(function(){return configureProject(c,platform);}).
then(function(){return resolve();}).
catch(function(e){return reject(e);});
});};exports.configureGradleProject=configureGradleProject;

var configureProject=function configureProject(c,platform){return new Promise(function(resolve,reject){
(0,_common.logTask)("configureProject:"+platform);

var appFolder=(0,_common.getAppFolder)(c,platform);
var appTemplateFolder=(0,_common.getAppTemplateFolder)(c,platform);

var gradlew=_path.default.join(appFolder,'gradlew');

if(!_fs.default.existsSync(gradlew)){
(0,_common.logWarning)("Looks like your "+_chalk.default.white(platform)+" platformBuild is misconfigured!. let's repair it.");
(0,_platform.createPlatformBuild)(c,platform).
then(function(){return configureGradleProject(c,platform);}).
then(function(){return resolve(c);}).
catch(function(e){return reject(e);});
return;
}

(0,_fileutils.mkdirSync)(_path.default.join(appFolder,'app/src/main/assets'));
_fs.default.writeFileSync(_path.default.join(appFolder,'app/src/main/assets/index.android.bundle'),'{}');
_fs.default.chmodSync(gradlew,'755');


c.pluginConfigAndroid={
pluginIncludes:"include ':app'",
pluginPaths:'',
pluginImports:'',
pluginPackages:'MainReactPackage(),\n',
pluginActivityImports:'',
pluginActivityMethods:'',
mainApplicationMethods:'',
applyPlugin:'',
pluginActivityCreateMethods:'',
pluginActivityResultMethods:'',
pluginSplashActivityImports:'',
manifestApplication:'',
buildGradleAllProjectsRepositories:'',
buildGradleBuildScriptRepositories:'',
buildGradleBuildScriptDependencies:'',
buildGradleBuildScriptDexOptions:'',
appBuildGradleSigningConfigs:'',
appBuildGradleImplementations:'',
appBuildGradleAfterEvaluate:''};



(0,_pluginTools.parsePlugins)(c,platform,function(plugin,pluginPlat,key){
(0,_gradleParser.injectPluginGradleSync)(c,pluginPlat,key,pluginPlat.package);
(0,_kotlinParser.injectPluginKotlinSync)(c,pluginPlat,key,pluginPlat.package);
(0,_manifestParser.injectPluginManifestSync)(c,pluginPlat,key,pluginPlat.package);
(0,_xmlValuesParser.injectPluginXmlValuesSync)(c,pluginPlat,key,pluginPlat.package);
});

c.pluginConfigAndroid.pluginPackages=c.pluginConfigAndroid.pluginPackages.substring(0,c.pluginConfigAndroid.pluginPackages.length-2);


if(c.buildConfig){
if(_fs.default.existsSync(c.paths.project.projectConfig.fontsDir)){
_fs.default.readdirSync(c.paths.project.projectConfig.fontsDir).forEach(function(font){
if(font.includes('.ttf')||font.includes('.otf')){
var key=font.split('.')[0];var
includedFonts=c.buildConfig.common.includedFonts;
if(includedFonts){
if(includedFonts.includes('*')||includedFonts.includes(key)){
if(font){
var fontSource=_path.default.join(c.paths.project.projectConfig.dir,'fonts',font);
if(_fs.default.existsSync(fontSource)){
var fontFolder=_path.default.join(appFolder,'app/src/main/assets/fonts');
(0,_fileutils.mkdirSync)(fontFolder);
var fontDest=_path.default.join(fontFolder,font);
(0,_fileutils.copyFileSync)(fontSource,fontDest);
}else{
(0,_common.logWarning)("Font "+_chalk.default.white(fontSource)+" doesn't exist! Skipping.");
}
}
}
}
}
});
}
}

(0,_gradleParser.parseSettingsGradleSync)(c,platform);
(0,_gradleParser.parseAppBuildGradleSync)(c,platform);
(0,_gradleParser.parseBuildGradleSync)(c,platform);
(0,_kotlinParser.parseMainActivitySync)(c,platform);
(0,_kotlinParser.parseMainApplicationSync)(c,platform);
(0,_kotlinParser.parseSplashActivitySync)(c,platform);
(0,_xmlValuesParser.parseValuesStringsSync)(c,platform);
(0,_manifestParser.parseAndroidManifestSync)(c,platform);
(0,_gradleParser.parseGradlePropertiesSync)(c,platform);

resolve();
});};


var runAndroidLog=function runAndroidLog(c){return new Promise(function(){
var filter=c.program.filter||'';
var child=_child_process.default.spawn(c.cli[_constants.CLI_ANDROID_ADB],['logcat']);

child.stdout.on('data',function(data){
var d=data.toString().split('\n');
d.forEach(function(v){
if(v.includes(' E ')&&v.includes(filter)){
console.log(_chalk.default.red(v));
}else if(v.includes(' W ')&&v.includes(filter)){
console.log(_chalk.default.yellow(v));
}else if(v.includes(filter)){
console.log(v);
}
});
});
});};exports.runAndroidLog=runAndroidLog;