var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.runTizenSimOrDevice=exports.addDevelopTizenCertificate=exports.createDevelopTizenCertificate=exports.listTizenTargets=exports.launchTizenSimulator=exports.DEFAULT_SECURITY_PROFILE_NAME=exports.DEFAULT_CERTIFICATE_NAME=void 0;var _regenerator=_interopRequireDefault(require("@babel/runtime/regenerator"));var _defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));var _inquirer=_interopRequireDefault(require("inquirer"));
var _net=_interopRequireDefault(require("net"));
var _path=_interopRequireDefault(require("path"));
var _common=require("../../common");
var _constants=require("../../constants");


var _exec=require("../../systemManager/exec");
var _fileutils=require("../../systemManager/fileutils");
var _logger=require("../../systemManager/logger");


var _webpackUtils=require("../webpackUtils");
var _common2=require("./common");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(Object(source),true).forEach(function(key){(0,_defineProperty2.default)(target,key,source[key]);});}else if(Object.getOwnPropertyDescriptors){Object.defineProperties(target,Object.getOwnPropertyDescriptors(source));}else{ownKeys(Object(source)).forEach(function(key){Object.defineProperty(target,key,Object.getOwnPropertyDescriptor(source,key));});}}return target;}


var xml2js=require('xml2js');

var parser=new xml2js.Parser();

var DEFAULT_CERTIFICATE_NAME='tizen_author';exports.DEFAULT_CERTIFICATE_NAME=DEFAULT_CERTIFICATE_NAME;


var formatXMLObject=function formatXMLObject(obj){var _obj$modelConfig,_platArr$;
var platArr=(_obj$modelConfig=obj['model-config'])==null?void 0:_obj$modelConfig.platform;
var platKeyArr=(platArr==null?void 0:(_platArr$=platArr[0])==null?void 0:_platArr$.key)||(platArr==null?void 0:platArr.key);
if(platKeyArr){
return _objectSpread({},
platKeyArr.reduce(function(acc,cur){
acc[cur.name]=cur.$t;
return acc;
},{}));

}
(0,_logger.logWarning)('Invalid object received from shell cat /etc/config/model-config.xml');
return{};
};

var DEFAULT_SECURITY_PROFILE_NAME='RNVanillaCert';exports.DEFAULT_SECURITY_PROFILE_NAME=DEFAULT_SECURITY_PROFILE_NAME;


var launchTizenSimulator=function launchTizenSimulator(c,name){
(0,_logger.logTask)("launchTizenSimulator:"+name);

if(name){
return(0,_exec.execCLI)(c,_constants.CLI_TIZEN_EMULATOR,"launch --name "+name,{
detached:true});

}
return Promise.reject('No simulator -t target name specified!');
};exports.launchTizenSimulator=launchTizenSimulator;

var listTizenTargets=function listTizenTargets(c){var targets,targetArr,targetStr;return _regenerator.default.async(function listTizenTargets$(_context){while(1){switch(_context.prev=_context.next){case 0:_context.next=2;return _regenerator.default.awrap(
(0,_exec.execCLI)(c,_constants.CLI_TIZEN_EMULATOR,'list-vm',{
detached:true}));case 2:targets=_context.sent;

targetArr=targets.split('\n');
targetStr='';
Object.keys(targetArr).forEach(function(i){
targetStr+="["+i+"]> "+targetArr[i]+"\n";
});
(0,_logger.logToSummary)("Tizen Targets:\n"+targetStr);case 7:case"end":return _context.stop();}}},null,null,null,Promise);};exports.listTizenTargets=listTizenTargets;


var createDevelopTizenCertificate=function createDevelopTizenCertificate(c){return new Promise(function(resolve){
(0,_logger.logTask)('createDevelopTizenCertificate');

var certDirPath=c.paths.workspace.dir;
var certFilename=DEFAULT_CERTIFICATE_NAME;
var certPassword='1234';

(0,_exec.execCLI)(
c,
_constants.CLI_TIZEN,"certificate -- "+
certDirPath+" -a rnv -f "+certFilename+" -p "+certPassword).


then(function(){return addDevelopTizenCertificate(c,{
profileName:DEFAULT_SECURITY_PROFILE_NAME,
certPath:_path.default.join(certDirPath,certFilename+".p12"),
certPassword:certPassword});}).

then(function(){return resolve();}).
catch(function(e){
(0,_logger.logError)(e);
resolve();
});
});};exports.createDevelopTizenCertificate=createDevelopTizenCertificate;

var addDevelopTizenCertificate=function addDevelopTizenCertificate(c,secureProfileConfig){return new Promise(function(resolve){
(0,_logger.logTask)('addDevelopTizenCertificate');

var _ref=secureProfileConfig||{},profileName=_ref.profileName,certPath=_ref.certPath,certPassword=_ref.certPassword;
(0,_exec.execCLI)(
c,
_constants.CLI_TIZEN,"security-profiles add -n "+
profileName+" -a "+certPath+" -p "+certPassword,
{privateParams:[certPassword]}).

then(function(){return resolve();}).
catch(function(e){
(0,_logger.logError)(e);
resolve();
});
});};exports.addDevelopTizenCertificate=addDevelopTizenCertificate;

var _getDeviceID=function _getDeviceID(c,target){var device,connectResponse,devicesList,lines,devices,deviceID;return _regenerator.default.async(function _getDeviceID$(_context2){while(1){switch(_context2.prev=_context2.next){case 0:
device=c.program.device;if(!

device){_context2.next=17;break;}_context2.prev=2;_context2.next=5;return _regenerator.default.awrap(


(0,_exec.execCLI)(
c,
_constants.CLI_SDB_TIZEN,"connect "+
target));case 5:connectResponse=_context2.sent;_context2.next=11;break;case 8:_context2.prev=8;_context2.t0=_context2["catch"](2);


connectResponse=_context2.t0;case 11:if(!

connectResponse.includes('EPERM')){_context2.next=13;break;}throw(
new Error(
"We can't connect to this device even though it is reachable. Please make sure you have enabled Developer Mode and you have added your IP in the Host PC IP section. For more information consult https://developer.samsung.com/tv/develop/getting-started/using-sdk/tv-device"));case 13:if(!


connectResponse.includes('failed to connect to remote target')){_context2.next=15;break;}throw(
new Error("Failed to connect to "+
target+". Make sure the IP is correct and you are connected on the same network."));case 15:if(!


connectResponse.includes('error')){_context2.next=17;break;}throw new Error(connectResponse);case 17:_context2.next=19;return _regenerator.default.awrap(


(0,_exec.execCLI)(c,_constants.CLI_SDB_TIZEN,'devices'));case 19:devicesList=_context2.sent;if(!
devicesList.includes(target)){_context2.next=26;break;}
lines=devicesList.trim().split(/\r?\n/);
devices=lines.filter(function(line){return line.includes(target);});

if(devices.length>1){

}

deviceID=devices[0].split('device')[1].trim();return _context2.abrupt("return",
deviceID);case 26:return _context2.abrupt("return",

Promise.reject("No device matching "+target+" could be found."));case 27:case"end":return _context2.stop();}}},null,null,[[2,8]],Promise);};


var _getRunningDevices=function _getRunningDevices(c){var platform,devicesList,lines,devices;return _regenerator.default.async(function _getRunningDevices$(_context4){while(1){switch(_context4.prev=_context4.next){case 0:
platform=c.program.platform;_context4.next=3;return _regenerator.default.awrap(
(0,_exec.execCLI)(c,_constants.CLI_SDB_TIZEN,'devices'));case 3:devicesList=_context4.sent;
lines=devicesList.
trim().
split(/\r?\n/).
filter(function(line){return!line.includes('List of devices');});
devices=[];_context4.next=8;return _regenerator.default.awrap(

Promise.all(
lines.map(function _callee(line){var words,name,deviceInfoXML,deviceInfo,deviceType,parseObj;return _regenerator.default.async(function _callee$(_context3){while(1){switch(_context3.prev=_context3.next){case 0:
words=line.replace(/\t/g,'').split('    ');if(!(
words.length>=3)){_context3.next=13;break;}
name=words[0].trim();_context3.next=5;return _regenerator.default.awrap(
(0,_exec.execCLI)(
c,
_constants.CLI_SDB_TIZEN,"-s "+
name+" shell cat /etc/config/model-config.xml",
{ignoreErrors:true}));case 5:deviceInfoXML=_context3.sent;if(!(





deviceInfoXML!==true&&deviceInfoXML!=='')){_context3.next=12;break;}_context3.next=9;return _regenerator.default.awrap(


parser.parseStringPromise(deviceInfoXML));case 9:parseObj=_context3.sent;

deviceInfo=formatXMLObject(parseObj);
deviceType=deviceInfo['tizen.org/feature/profile'];case 12:


if(
platform==='tizenmobile'&&deviceType==='mobile'||
platform==='tizenwatch'&&deviceType==='wearable'||
platform==='tizen'&&!deviceType)
{
devices.push({
name:name,
type:words[1].trim(),
id:words[2].trim(),
deviceType:deviceType});

}case 13:case"end":return _context3.stop();}}},null,null,null,Promise);})));case 8:return _context4.abrupt("return",




devices);case 9:case"end":return _context4.stop();}}},null,null,null,Promise);};


var _waitForEmulatorToBeReady=function _waitForEmulatorToBeReady(c,target){return(0,_common2.waitForEmulator)(c,_constants.CLI_SDB_TIZEN,'devices',function(res){
var lines=res.trim().split(/\r?\n/);
var devices=lines.filter(
function(line){return line.includes(target)&&line.includes('device');});

return devices.length>0;
});};

var _composeDevicesString=function _composeDevicesString(devices){return devices.map(function(device){return{
key:device.id,
name:device.name,
value:device.id};});};








var runTizenSimOrDevice=function runTizenSimOrDevice(c){var _platformConfig$certi;var hosted,_c$runtime,target,engine,platform,platformConfig,bundleAssets,isHosted,isLightningEngine,tDir,tBuild,tOut,tId,wgt,wgtClean,certProfile,deviceID,askForEmulator,continueLaunching,isTargetSpecified,devices,targetDevice,choices,_await$inquirer$promp2,chosenEmulator;return _regenerator.default.async(function runTizenSimOrDevice$(_context7){while(1){switch(_context7.prev=_context7.next){case 0:
hosted=c.program.hosted;_c$runtime=
c.runtime,target=_c$runtime.target,engine=_c$runtime.engine;
platform=c.platform;

platformConfig=c.buildConfig.platforms[platform];
bundleAssets=(0,_common.getConfigProp)(c,platform,'bundleAssets');
isHosted=hosted!=null?hosted:!bundleAssets;
isLightningEngine=engine.config.id==='engine-lightning';
if(!bundleAssets&&!hosted){

}if(

platformConfig){_context7.next=10;break;}throw(
new Error("runTizen: "+
(0,_logger.chalk)().grey(
platform)+" not defined in your "+
(0,_logger.chalk)().white(c.paths.appConfig.config)));case 10:if(


platformConfig.appName){_context7.next=12;break;}throw(
new Error("runTizen: "+
(0,_logger.chalk)().grey(
platform)+".appName not defined in your "+
(0,_logger.chalk)().white(
c.paths.appConfig.config)));case 12:




tDir=(0,_common.getPlatformProjectDir)(c);
tBuild=_path.default.join(tDir,'build');
tOut=_path.default.join(tDir,'output');
tId=platformConfig.id;
wgt=platformConfig.appName+".wgt";

wgtClean=platformConfig.appName.replace(/[^a-z0-9]/gi,'_')+".wgt";
certProfile=(_platformConfig$certi=platformConfig.certificateProfile)!=null?_platformConfig$certi:DEFAULT_SECURITY_PROFILE_NAME;



askForEmulator=function askForEmulator(){var _await$inquirer$promp,startEmulator,defaultTarget;return _regenerator.default.async(function askForEmulator$(_context5){while(1){switch(_context5.prev=_context5.next){case 0:_context5.next=2;return _regenerator.default.awrap(
_inquirer.default.prompt([
{
name:'startEmulator',
type:'confirm',
message:"Could not find or connect to the specified target ("+
target+"). Would you like to start an emulator?"}]));case 2:_await$inquirer$promp=_context5.sent;startEmulator=_await$inquirer$promp.startEmulator;if(!




startEmulator){_context5.next=33;break;}
defaultTarget=c.files.workspace.config.defaultTargets[platform];_context5.prev=6;_context5.next=9;return _regenerator.default.awrap(

launchTizenSimulator(c,defaultTarget));case 9:
deviceID=defaultTarget;_context5.next=12;return _regenerator.default.awrap(
_waitForEmulatorToBeReady(c,defaultTarget));case 12:return _context5.abrupt("return",
continueLaunching());case 15:_context5.prev=15;_context5.t0=_context5["catch"](6);

(0,_logger.logDebug)("askForEmulator:ERRROR: "+_context5.t0);_context5.prev=18;_context5.next=21;return _regenerator.default.awrap(

(0,_exec.execCLI)(
c,
_constants.CLI_TIZEN_EMULATOR,"create -n "+
defaultTarget+" -p tv-samsung-5.0-x86"));case 21:_context5.next=23;return _regenerator.default.awrap(

launchTizenSimulator(c,defaultTarget));case 23:
deviceID=defaultTarget;_context5.next=26;return _regenerator.default.awrap(
_waitForEmulatorToBeReady(c,defaultTarget));case 26:return _context5.abrupt("return",
continueLaunching());case 29:_context5.prev=29;_context5.t1=_context5["catch"](18);

(0,_logger.logDebug)(_context5.t1);
(0,_logger.logError)("Could not find the specified target and could not create the emulator automatically.\nPlease create one and then edit the default target from "+

c.paths.workspace.dir+"/"+_constants.RENATIVE_CONFIG_NAME);case 33:case"end":return _context5.stop();}}},null,null,[[6,15],[18,29]],Promise);};






continueLaunching=function continueLaunching(){var hasDevice,packageID,toReturn,_packageID;return _regenerator.default.async(function continueLaunching$(_context6){while(1){switch(_context6.prev=_context6.next){case 0:
hasDevice=false;if(

isLightningEngine){_context6.next=10;break;}_context6.t0=
!isHosted;if(!_context6.t0){_context6.next=6;break;}_context6.next=6;return _regenerator.default.awrap((0,_webpackUtils.buildCoreWebpackProject)(c));case 6:_context6.next=8;return _regenerator.default.awrap(
(0,_exec.execCLI)(c,_constants.CLI_TIZEN,"build-web -- "+tDir+" -out "+tBuild));case 8:_context6.next=10;return _regenerator.default.awrap(
(0,_exec.execCLI)(
c,
_constants.CLI_TIZEN,"package -- "+
tBuild+" -s "+certProfile+" -t wgt -o "+tOut));case 10:_context6.prev=10;




packageID=platform==='tizenwatch'||platform==='tizenmobile'?
tId.split('.')[0]:
tId;_context6.next=14;return _regenerator.default.awrap(
(0,_exec.execCLI)(
c,
_constants.CLI_TIZEN,"uninstall -p "+
packageID+" -t "+deviceID,
{ignoreErrors:true}));case 14:

hasDevice=true;_context6.next=25;break;case 17:_context6.prev=17;_context6.t1=_context6["catch"](10);if(!(

_context6.t1&&_context6.t1.includes&&_context6.t1.includes('No device matching'))){_context6.next=25;break;}_context6.next=22;return _regenerator.default.awrap(
launchTizenSimulator(c,target));case 22:_context6.next=24;return _regenerator.default.awrap(
_waitForEmulatorToBeReady(c,target));case 24:hasDevice=_context6.sent;case 25:


try{
if(wgtClean!==wgt){
(0,_logger.logInfo)("Your app name contains characters like spaces, changing output from \""+
wgt+"\" to \""+wgtClean+"\"");
(0,_fileutils.fsRenameSync)(_path.default.join(tOut,wgt),_path.default.join(tOut,wgtClean));
}
}catch(err){
(0,_logger.logError)(err);
}_context6.prev=26;_context6.next=29;return _regenerator.default.awrap(

(0,_exec.execCLI)(
c,
_constants.CLI_TIZEN,"install -- "+
tOut+" -n "+wgtClean+" -t "+deviceID));case 29:

hasDevice=true;_context6.next=41;break;case 32:_context6.prev=32;_context6.t2=_context6["catch"](26);

(0,_logger.logError)(_context6.t2);
(0,_logger.logWarning)("There is no emulator or device connected! Let's try to launch it. \""+
(0,_logger.chalk)().white.bold("rnv target launch -p "+
platform+" -t "+target)+"\"");_context6.next=38;return _regenerator.default.awrap(



launchTizenSimulator(c,target));case 38:_context6.next=40;return _regenerator.default.awrap(
_waitForEmulatorToBeReady(c,target));case 40:hasDevice=_context6.sent;case 41:


toReturn=true;if(!(







platform!=='tizenwatch'&&
platform!=='tizenmobile'&&
hasDevice)){_context6.next=47;break;}_context6.next=45;return _regenerator.default.awrap(

(0,_exec.execCLI)(c,_constants.CLI_TIZEN,"run -p "+tId+" -t "+deviceID));case 45:_context6.next=51;break;case 47:if(!(

(platform==='tizenwatch'||platform==='tizenmobile')&&
hasDevice)){_context6.next=51;break;}

_packageID=tId.split('.');_context6.next=51;return _regenerator.default.awrap(
(0,_exec.execCLI)(
c,
_constants.CLI_TIZEN,"run -p "+
_packageID[0]+" -t "+deviceID));case 51:return _context6.abrupt("return",


toReturn);case 52:case"end":return _context6.stop();}}},null,null,[[10,17],[26,32]],Promise);};



isTargetSpecified=c.program.target;_context7.next=24;return _regenerator.default.awrap(


_getRunningDevices(c));case 24:devices=_context7.sent;if(!

isTargetSpecified){_context7.next=50;break;}if(!

_net.default.isIP(target)){_context7.next=31;break;}_context7.next=29;return _regenerator.default.awrap(
_getDeviceID(c,target));case 29:deviceID=_context7.sent;return _context7.abrupt("return",
continueLaunching());case 31:if(!(


devices.length>0)){_context7.next=36;break;}
targetDevice=devices.find(
function(device){return device.id===target||device.name===target;});if(!

targetDevice){_context7.next=36;break;}
deviceID=targetDevice.id;return _context7.abrupt("return",
continueLaunching());case 36:_context7.prev=36;_context7.next=39;return _regenerator.default.awrap(




launchTizenSimulator(c,target));case 39:_context7.next=41;return _regenerator.default.awrap(
_waitForEmulatorToBeReady(c,target));case 41:
deviceID=target;return _context7.abrupt("return",
continueLaunching());case 45:_context7.prev=45;_context7.t0=_context7["catch"](36);return _context7.abrupt("return",

askForEmulator());case 48:_context7.next=62;break;case 50:if(!(


devices.length===1)){_context7.next=53;break;}
deviceID=devices[0].id;return _context7.abrupt("return",
continueLaunching());case 53:if(!(

devices.length>1)){_context7.next=61;break;}
choices=_composeDevicesString(devices);_context7.next=57;return _regenerator.default.awrap(
_inquirer.default.prompt([
{
name:'chosenEmulator',
type:'list',
message:'On what emulator would you like to run the app?',
choices:choices}]));case 57:_await$inquirer$promp2=_context7.sent;chosenEmulator=_await$inquirer$promp2.chosenEmulator;


deviceID=chosenEmulator;return _context7.abrupt("return",
continueLaunching());case 61:return _context7.abrupt("return",

askForEmulator());case 62:case"end":return _context7.stop();}}},null,null,[[36,45]],Promise);};exports.runTizenSimOrDevice=runTizenSimOrDevice;
//# sourceMappingURL=tizen.js.map