You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
hace 3 años
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189
  1. var scripthostName = 'node'
  2. var __Promise = {};
  3. var promises = [];
  4. function startPromises(){
  5. promises.forEach(function(p){
  6. // console.log(p.chain)
  7. p ? p() : null;
  8. // promises.splice(0,1)
  9. })
  10. }
  11. function isWin(){ return /^win/.test(process.platform) }
  12. var stampedFilePfx = function(date) {
  13. return date.getFullYear() +
  14. ('0' + (date.getMonth() + 1)).slice(-2) +
  15. ('0' + date.getDate()).slice(-2) +
  16. ('0' + date.getHours()).slice(-2) +
  17. ('0' + date.getMinutes()).slice(-2) +
  18. ('0' + date.getSeconds()).slice(-2);
  19. }
  20. var runtimestamp = (new Date()).getTime();
  21. try {
  22. console.log("detected node")
  23. // var WScript = console || WScript // Dummy
  24. // console.Echo = console.log
  25. __Promise = Promise
  26. var __require = require
  27. var map = Array.map
  28. function startPromises(){
  29. promises.forEach(function(p){
  30. // console.log(p.chain)
  31. p ? Promise.resolve(p) === p ? p : p() : null;
  32. // promises.splice(0,1)
  33. })
  34. }
  35. // --------------------------------------------
  36. // Node Exists. Lets launch ourselves in Node itself
  37. var wait = function(ms, cb) {any
  38. return new __Promise(function(resolve){ setTimeout(resolve, ms) } ).then(function(){ cb() });
  39. }
  40. var fs = require('fs')
  41. var existsSync = require('fs').existsSync;
  42. var existsSyncFolder = existsSync
  43. var path = require('path');
  44. var cli = require('./cliverse')
  45. var nodeShellExec = cli.nodeShellExec;
  46. var utils = require('bbhverse');
  47. var any = utils.any;
  48. var wait = setTimeout
  49. // --------------------------------------------
  50. var selectedinstance = { root : path.resolve(".") }
  51. __main(selectedinstance)
  52. }
  53. catch(e) {
  54. WScript.Echo('detected wsh')
  55. scripthostName = 'wsh'
  56. WScript.Echo(WScript.FullName)
  57. console = {
  58. log : function(m) { WScript.Echo(m)}
  59. , error : function(m) {WScript.Echo(m) }
  60. , dir : function(o) {
  61. for(var i in o){ console.log(i + ' : ' + o[i])}
  62. }
  63. }
  64. // if(!String.prototype.trim) String.prototype.trim = function(){
  65. // return this.replace(/^\s+|\s+$/g, '');
  66. // };
  67. // var ovrrides = {
  68. // resolve : function(v){
  69. // if(v && v.then) return v;
  70. // var p = new Promise(function(resolve, reject){ resolve(v) });
  71. // return p;
  72. // }
  73. // };
  74. // // --------------------------------------------
  75. // // Cscript
  76. var wsh = true;
  77. function isWin(){ return true; }
  78. // If UCase( Right( WScript.FullName, 12 ) ) = "\CSCRIPT.EXE" Then
  79. var clii = {
  80. question : function(q, answercb){
  81. WScript.Echo(q)
  82. // console.log('WScript.StdIn : ' + WScript.StdIn.ReadLine() + ' ==== ')
  83. var answer = WScript.StdIn.ReadLine()
  84. answercb(answer)
  85. }
  86. }
  87. var prompter = {
  88. ask : function(q){
  89. // Needs to be serialized. Parallel asks are not possible.
  90. // const clii = readline.createInterface({ input: process.stdin, output: process.stdout });
  91. return new Promise(function(resolve, reject){
  92. clii.question(q, function(answer){
  93. // clii.close();
  94. // console.log("resolve is being called");
  95. resolve(answer)
  96. })
  97. })
  98. }
  99. }
  100. var cli = {
  101. prompt : function(choices, label, defaultchoice){
  102. var options = [];
  103. choices.forEach = forEach
  104. choices.forEach(function(choice){ options.push( ((+choice) + 1) + ' ' + choices[choice] )})
  105. return prompter.ask( label + ' \\n ' + options.join('\n') + '\n default ( <= ' + (defaultchoice || choices[0]) + ' ) : '
  106. ).then( function(choice){
  107. if(!choice) return defaultchoice || choices[0];
  108. if(choice && isNaN(+choice)) return choice;
  109. return choices[(+choice) - 1];
  110. })
  111. }
  112. }
  113. var any = function(iterable, continueOnFailure) {
  114. // var cancelsignal = Symbol()
  115. if(!iterable.reduce) iterable.reduce = reduce
  116. // console.log('iterable.reduce ' + iterable.reduce)
  117. var cancelsignal = "cancelme{mangledrunid}"
  118. return iterable.reduce(
  119. function(p, tasq, i ,a) {
  120. // console.dir(a)
  121. // console.log('Entered')
  122. var handleError = function(err, pVal){
  123. if(err !== cancelsignal) {
  124. // Cancel only once on first failure.
  125. console.warn('Possible failure for task with result : ' )
  126. console.log('Failed : ' + err.message + ' ')
  127. console.dir(pVal)
  128. console.dir(p)
  129. if(i>0 && a[i-1].info) console.dir(a[i-1].info)
  130. console.error('Error : ' + err.stack)
  131. console.error(a[i-1])
  132. a[i-1] ? console.log("tasq : " + a[i-1].toString()) : null;
  133. if(!continueOnFailure) {console.log("Cancelling remaining on any one failure ..."); throw cancelsignal}
  134. else return pVal;
  135. // tasq ? console.log("tasq : " + tasq.toString()) : null; // Previous task is what failed not the one we are going to run.
  136. }
  137. }
  138. if(Promise.resolve(p) === p ) {
  139. if(i>0 && a[i-1].info) p.info = a[i-1].info;
  140. console.dir(' p.then is ' + p.then)
  141. return p.then( function(pVal){
  142. // Falsy values are no longer treated as task failure exceptions. Specially for Promises.
  143. // Even tasq function wrappers are required to return promises that eventually either resolve or reject..
  144. // Failures are known for promises on reject.
  145. // In future if we support direct sync function execution with a result examination for failure
  146. // we could examine the result of the function as falsy's... or a result evaluator handler needs to be passed in...
  147. // if(!pVal) handleError({ error : true, message : 'Failed without result' }, pVal)
  148. // Truthy values are failures if obj has error=true.
  149. if(pVal && pVal.error) handleError(pVal, pVal)
  150. var trycall = function(tasq){
  151. try {
  152. var result = tasq() // PB : TODO -- Handle scope for call
  153. if(tasq.resultHandler) return tasq.resultHandler(result)
  154. // else (Promise.resolve(result) === result ) ? result.start() : null
  155. return result
  156. } catch (error) {
  157. console.error(error);
  158. console.error('Error : ' + error ? error.stack : 'No stack')
  159. if(!continueOnFailure) throw error; // PB : TODO -- Support array of results for any with or without continueonfailure.
  160. }
  161. }
  162. var handleNext = function(){
  163. // console.log('Task finished with result : ')
  164. // console.dir(pVal)
  165. if(i>0 && a[i-1].info) console.dir(a[i-1].info)
  166. if(!tasq && !continueOnFailure) { console.log('Error : No task specified.'); throw false;}
  167. else if(!tasq) { console.log('Error : No task specified.'); return false;}
  168. return (Promise.resolve(tasq) === tasq ) ? tasq /*.start()*/ : trycall(tasq) ;
  169. }
  170. if(Promise.resolve(pVal) === pVal) {
  171. // Passed in function retured a promise. We still need to wait for it.
  172. pVal.then(function(pVal){ return handleNext(); })
  173. }
  174. else return handleNext()
  175. })['catch'](function(error) {
  176. if(error !== cancelsignal) {
  177. console.log('E3 : i = ' + i);
  178. if(error.result) console.error(error.result)
  179. console.error('Error : ' + (error.message || error.messages))
  180. console.error('Error : ' + error.stack)
  181. tasq ? console.log("tasq : " + tasq.toString()) : null;
  182. console.log('debugData 3-------------------------');
  183. // handleError()
  184. throw error
  185. }
  186. else throw cancelsignal;
  187. })
  188. }
  189. else if(!p) {
  190. handleError({ error : true, message : 'Failed without result' }, pVal)
  191. console.log("Bypass remaining on prior failure");
  192. return false; // All remaining tasks will return false in the any results even if they are promisies still running or functions not initiated.
  193. }
  194. else return p; // A truthy value
  195. }
  196. , Promise.resolve(true)
  197. );
  198. }
  199. // __Promise = ovrrides
  200. function forEach(eachFn){
  201. for(var i=0; i<this.length; i++) eachFn(this[i])
  202. }
  203. function reduce(reducnFn, iv){
  204. var acc = iv
  205. for(var i=0; i<this.length; i++) {acc = reducnFn(acc, this[i], i, this) }
  206. return acc;
  207. }
  208. function map(eachFn){
  209. var mapped = []
  210. for(var i=0; i<this.length; i++) mapped.push(eachFn(this[i]))
  211. return mapped
  212. }
  213. var wait = function(cb, ms) { WScript.Sleep(ms); cb() }
  214. var fso = new ActiveXObject('Scripting.FileSystemObject');
  215. var existsSync = function(filepath){ return fso.FileExists(filepath) }
  216. var fs = {
  217. writeFileSync : function(filepath, text) {
  218. // console.log(filepath)
  219. var fh = fso.CreateTextFile(filepath, true);
  220. fh.WriteLine(text);
  221. fh.Close();
  222. }
  223. , mkdirSync : function(path) {
  224. fso.CreateFolder(path)
  225. }
  226. , readFileSync : function(filepath){
  227. var objFileToRead = fso.OpenTextFile(filepath,1)
  228. var strFileText = objFileToRead.ReadAll()
  229. objFileToRead.Close()
  230. return strFileText
  231. }
  232. , unlinkSync : function(filepath){ fso.DeleteFile(filepath) }
  233. }
  234. var path = {
  235. resolve : function(path){ return fso.GetAbsolutePathName(path) }
  236. , dirname : function(filepath) {
  237. var normalized = this.normalize(filepath)
  238. var li = normalized.lastIndexOf("\\")
  239. if( li > -1) {
  240. return normalized.substring(0, li)
  241. }
  242. }
  243. , normalize : function(path){
  244. return path.replace(/\//g,'\\');
  245. }
  246. }
  247. // Detect or specify install directory.
  248. var selectedinstance = { root : path.resolve(".") }
  249. var existsSyncFolder = function(path){
  250. return fso.FolderExists(path)
  251. }
  252. var shell = new ActiveXObject('shell.application');
  253. promises.forEach = forEach
  254. function startPromises(){
  255. promises.forEach(function(p){
  256. // console.log(p.chain)
  257. p.start();
  258. // promises.splice(0,1)
  259. })
  260. }
  261. function nodeShellExec(command, cargs, options){
  262. var elevatedshellexecute = function(cmd, argstr){
  263. shell.ShellExecute(cmd, argstr , "", "", 1);
  264. }
  265. var shellExec = function(cmd, argstr){
  266. var objShell = WScript.createobject("wscript.shell")
  267. // console.log(argstr.join( ' '))
  268. var oExec = objShell.Exec(cmd + ' ' + argstr.join(' '))
  269. var result = {}
  270. var shellresult = { shell : objShell, result : result }
  271. var WshRunning = 0
  272. var WshFinished = 1
  273. var WshFailed = 2
  274. while(oExec.Status === WshRunning){
  275. WScript.StdOut.write('s.')
  276. WScript.Sleep(500)
  277. }
  278. var strOutput = '\n'
  279. switch(oExec.Status) {
  280. case WshFinished :
  281. strOutput = oExec.StdOut.ReadAll()
  282. result.success = true;
  283. result.code = 0
  284. break;
  285. case WshFailed :
  286. strOutput = oExec.StdErr.ReadAll()
  287. result.success = false;
  288. result.code = WshFailed
  289. break;
  290. default : strOutput = 'failed'
  291. break;
  292. }
  293. result.result = command + ' ' + cargs + ' exited with code ' + result.code
  294. result.messages = [strOutput]
  295. // console.log(strOutput)
  296. // WScript.Echo(oExec.Status)
  297. // WScript.Echo(oExec.ProcessID)
  298. // WScript.Echo(oExec.ExitCode)
  299. // console.log(objShell.StdOut.ReadAll)
  300. // console.log(objShell.StdErr.ReadAll)
  301. // objShell = WScript.createobject("wscript.shell")
  302. objShell = null;
  303. return shellresult;
  304. }
  305. var p = null;
  306. var pworker = function(resolve, reject){
  307. // console.dir(p)
  308. var pfx = selectedinstance.root + '\\.elxr\\run-' + runtimestamp + '\\' + stampedFilePfx(new Date())
  309. // console.log('p.chain.length ================ ' + p.chain.length)
  310. options = options || {
  311. runFile : path.normalize( pfx + "out.txt")
  312. // runFile : null
  313. }
  314. var runFile = null;
  315. var runFile = options.runFile || pfx + command + cargs + "out.txt";
  316. // console.log(runFile)
  317. var args = cargs.concat()
  318. // runFile ? (args.push(">"), args.push(runFile)) : cargs
  319. // console.log(command + ' ' + args.join(' '))
  320. // command = 'cmd'
  321. // args = ['/c', 'start',
  322. // '/WAIT', selectedinstance.root + '/Downloads' + '/' + 'Git-2.33.0.2-64-bit.exe'
  323. // , '/VERYSILENT'
  324. // // , '/MERGETASKS=!runcode' // This is required only for vscode...
  325. // ]
  326. var runbat = path.normalize(pfx + "run.bat")
  327. // console.log('runbat : ' + runbat)
  328. fs.writeFileSync(runbat,
  329. '@echo off \r\n' +
  330. (options.cwd ? 'cd ' + options.cwd + ' \r\n' : '') +
  331. // ' cmd /k notepad.exe \r\n' +
  332. command + ' ' + args.join(' ') + ' \r\n' +
  333. 'cmd /c echo done >> ' + runFile + ' \r\n' +
  334. 'echo done'
  335. )
  336. // fs.writeFileSync(runFile, 'started')
  337. // WScript.Quit()
  338. // elevatedshellexecute(runFile)
  339. // while(!existsSync(runbat)) { wait(function(){
  340. // console.log('awiting batch : ' + runbat)
  341. // // shellExec( 'start', ['/W', '/b', runbat])
  342. // // shellExec( 'cmd', ['/k', '/b', runbat])
  343. // shellExec( command, args)
  344. // // cmd /b /c
  345. // }, 500) }
  346. console.log(options.waitmsg || ('awaiting ' + command + ' ' + args.join(' ')))
  347. var shellresult = shellExec( 'cmd', [ '/c', runbat])
  348. // var shellresult = shellExec( 'cmd', ['/c', runbat])
  349. // var shellresult = shellExec( command, args)
  350. var wrapup = function(result) {
  351. // console.log('Wrapping up')
  352. try {
  353. // console.log('resolving.....................');
  354. // console.log('--------------P' + result.messages.join(' ').trim() +'P--------------')
  355. // if(result.messages.join().trim()) resolve(result)
  356. // else reject(result)
  357. resolve(result)
  358. }
  359. catch(e){
  360. // console.dir(e)
  361. if(e.message === 'Input past end of file') {
  362. // console.log('---------------------------------------')
  363. // console.dir(result)
  364. resolve(result)
  365. }
  366. else {
  367. // console.dir(e)
  368. reject(e)
  369. }
  370. }
  371. }
  372. // if(runFile){
  373. // var waitr = function(){
  374. // WScript.StdOut.write('w.')
  375. // if(existsSync(runFile)) {
  376. // var strOutput = fs.readFileSync(runFile)
  377. // shellresult.result.messages = [strOutput]
  378. // wrapup(shellresult.result)
  379. // fs.unlinkSync(runFile)
  380. // }
  381. // // console.dir(shellresult.result)
  382. // wait( waitr, 500)
  383. // }
  384. // // console.log(wait)
  385. // wait( waitr, 500)
  386. // }
  387. // else {
  388. // console.log('There is no runfile.')
  389. // console.log(shellresult.strOutput)
  390. wrapup(shellresult.result)
  391. // }
  392. }
  393. p = new Promise(pworker)
  394. // promises.push(p)
  395. // // Promise tThens don't get hooked up... we need to postpone promise starting until all the thens are registered...
  396. // wait(function(){
  397. // console.log('p.chain.length' + p.chain.length)
  398. // p.start() } , 5000) // Bind and setTImeout is not supported by JScript
  399. return p;
  400. }
  401. createPromiseClass(/*ovrrides*/)
  402. __main( selectedinstance )
  403. function createPromiseClass(overrides) {
  404. function reject(e){
  405. var p = this;
  406. console.log('Promise Rejection : ' + p.fn)
  407. console.dir(e)
  408. // throw e;f
  409. if(p.state !== PromiseClass.PENDING) { console.error ('Error : Promise Rejection can only be called once')}
  410. var __i = 0;
  411. var __e = e;
  412. do {
  413. for(var i = __i; i < p.chain.length; i++, __i = i) if(p.chain[i].isCatch) break;
  414. try {
  415. for(var i = __i; i < p.chain.length; i++, __i = i) if(p.chain[i].isCatch) { p.chain[i](__e); break; }
  416. __i++;
  417. __e = null;
  418. }
  419. catch(e){ __i++; __e = e}
  420. } while(__e)
  421. do {
  422. try { for(var i = __i; i < p.chain.length; i++, __i = i) if(!p.chain[i].isCatch) { p.result = p.chain[i](p.result); } }
  423. catch(e){
  424. __i ++;
  425. do {
  426. try {
  427. for(var i = __i; i < p.chain.length; i++, __i = i) if(p.chain[i].isCatch) { p.chain[i](__e); break; }
  428. __i ++;
  429. __e = null;
  430. }
  431. catch(e){ __i++; __e = e}
  432. } while(__e)
  433. }
  434. } while ( __i < p.chain.length )
  435. p.state = PromiseClass.REJECTED;
  436. }
  437. function resolve(result){
  438. var p = this;
  439. // console.log(result + ' resolve was called with chain length ' + p.chain.length )
  440. if(p.state !== PromiseClass.PENDING) { console.error ('Error : Promise Resolve can only be called once')}
  441. p.result = result;
  442. if(PromiseClass.resolve(p.result) === p.result) {
  443. // console.log( 'result is still a promise waiting for result and promisechain' )
  444. waitForResult(p.result, function(r){ p.processchain(r) })
  445. }
  446. else {
  447. // console.log( 'result is value waiting for promisechain' )
  448. // console.dir(result)
  449. return p.processchain(result)
  450. }
  451. };
  452. function processchain(r){
  453. var __i = 0;
  454. var i = __i;
  455. var __e = null;
  456. p = this;
  457. // console.log('processchain chain.length : ' + p.chain.length)
  458. function __processchain(r){
  459. function waitForThen(p){
  460. if(i < p.chain.length) {
  461. if(!p.chain[i].isCatch) {
  462. // console.log('chain idx : ' + i + ' Executing : then ' + p.result + ' ' + p.chain[i])
  463. try {
  464. p.result = p.chain[i](p.result)
  465. if(PromiseClass.resolve(p.result) === p.result) {
  466. // console.log('chain idx : ' + i + ' result is still a promise starting it ')
  467. // console.dir(p.result.chain)
  468. // console.log('p.result.start : ' + p.result.start + ' ------------------ ')
  469. p.result.start()
  470. // console.log(p.result.fn + ' ------------------ ')
  471. waitForResult(p.result, function(r){
  472. // console.log('we waited')
  473. // WScript.write('.')
  474. p.result = r; i++; __i = i;
  475. waitForThen(p)
  476. })
  477. }
  478. else {
  479. i++; __i = i;
  480. waitForThen(p)
  481. }
  482. }
  483. catch(e) {
  484. i++; __i = i;
  485. __e = e;
  486. console.log('failed on index ' + __i + p.chain[__i-1] )
  487. console.dir(e)
  488. waitForCatch(p);
  489. }
  490. }
  491. else {
  492. // console.log(i + ' Skipping catch : ' + p.result + ' ' + p.chain[i])
  493. i++; __i = i;
  494. waitForThen(p)
  495. }
  496. }
  497. else return p.state = PromiseClass.FULFILLED;
  498. }
  499. function waitForCatch(p) {
  500. if(i < p.chain.length) {
  501. if(p.chain[i].isCatch) {
  502. console.log('chain idx : ' + i + ' Executing : catch : ' + p.result + ' ' + p.chain[i])
  503. try {
  504. p.result = p.chain[i](__e);
  505. if(PromiseClass.resolve(p.result) === p.result) {
  506. p.result.start()
  507. waitForResult(p.result, function(r){
  508. p.result = r; i++; __i = i;
  509. })
  510. waitForThen(p)
  511. }
  512. else {
  513. p.result = r; i++; __i = i;
  514. waitForThen(p)
  515. }
  516. }
  517. catch(e){ i++; __i = i;; __e = e; waitForCatch(p) }
  518. }
  519. else {
  520. i++; __i = i;
  521. waitForCatch(p)
  522. }
  523. }
  524. else return p.state = PromiseClass.REJECTED
  525. }
  526. waitForThen(p);
  527. }
  528. __processchain(r)
  529. }
  530. var create = function(fn){
  531. var p = {
  532. then : function(thenfn){
  533. // console.log('Adding then')
  534. thenfn.isThen = true
  535. // if(Object.prototype.toString.call(p.chain) !== '[object Array]') console.dir(p.chain)
  536. p.chain.push(thenfn)
  537. return p;
  538. }
  539. , 'catch' : function(catchfn) {
  540. catchfn.isCatch = true
  541. p.chain.push(catchfn)
  542. return p;
  543. }
  544. , start : function(){
  545. if(this.started) {
  546. console.error('Cannot start more than once...')
  547. return p
  548. };
  549. this.started = true;
  550. this.fn = fn;
  551. try { fn( function(r){
  552. // console.log('calling presolve in starter ')
  553. p.resolve(r) } , function(r){ p.reject(r) } ) }
  554. catch(e){
  555. // console.log('start catch : ' + e)
  556. // console.log('p.chain.length : ' + p.chain.length)
  557. // // console.dir(p)
  558. // console.dir(e)
  559. // console.log(fn)
  560. p.reject(e)
  561. }
  562. return p
  563. }
  564. , state : PromiseClass.PENDING
  565. , chain : []
  566. , reject : reject
  567. , resolve : resolve
  568. , processchain : processchain
  569. }
  570. p.chain.forEach = forEach;
  571. return p;
  572. }
  573. var PromiseClass = function(fn /*, donotstart */){
  574. var p = create(fn)
  575. // if(!donotstart) {
  576. // wait(function(){
  577. // console.log('p.chain.length' + p.chain.length)
  578. // p.start() } , 500) // Bind and setTImeout is not supported by JScript
  579. // }
  580. return p
  581. }
  582. PromiseClass.PENDING = 1
  583. PromiseClass.FULFILLED = 2
  584. PromiseClass.REJECTED = 3
  585. // PromiseClass.STARTED = 4
  586. PromiseClass.isSETTLED = function(p){ p.state === PromiseClass.FULFILLED || p.state === PromiseClass.REJECTED }
  587. PromiseClass.resolve = function(v){
  588. if(v && v.then) return v;
  589. var p = create(function(resolve, reject){
  590. resolve(v)
  591. });
  592. // console.log('p.chain in resolve. length ' + p.chain.length)
  593. // p.result = v;
  594. // wait(function(){ p.processchain(v) }, 0)
  595. return p;
  596. }
  597. function waitForResult(p, cb){
  598. if(!p) return cb(p)
  599. if(p.state !== PromiseClass.PENDING) cb(p.result)
  600. // console.log(p.state + ' Waiting for ..... ' + p.runFile)
  601. if(p.runFile && false) {
  602. while(!existsSync(p.runFile) && p.state === PromiseClass.PENDING) {
  603. console.log('Waiting for ResultFle'); wait(cb, 500)
  604. }
  605. cb(p.result)
  606. }
  607. else {
  608. // while(p.state === PromiseClass.PENDING) {
  609. // console.log('Waiting for Result')
  610. function waiter(){
  611. // console.log(p.result)
  612. if(p.state === PromiseClass.PENDING) wait(waiter, 500);
  613. else return cb(p.result)
  614. }
  615. wait(waiter, 500)
  616. // }
  617. }
  618. }
  619. PromiseClass.all = any; // Serialized...
  620. PromiseClass.__all = function(arr){
  621. arr.forEach = forEach;
  622. var resultPs = [];
  623. var results = [];
  624. console.log('All : ' + arr.length)
  625. var pAll = new PromiseClass(function(resolve, reject){
  626. console.log('All started : ' + pAll)
  627. // console.dir(pAll)
  628. arr.forEach(function(p){
  629. if(!p.then) { var pfn = p;
  630. p = new PromiseClass(function(resolve, reject){
  631. try{
  632. resolve(pfn())
  633. }
  634. catch(e){
  635. reject(e)
  636. }
  637. })
  638. p.start()
  639. }
  640. else {
  641. // !p.start ? p.start = function(){return p} : null
  642. // p.start()
  643. // .then( function(){ waitForResult(p, function(r){ results.push(r) }) })
  644. }
  645. resultPs.push(p)
  646. // waitForResult(p, function(r){ results.push(r) })
  647. })
  648. // PB : TODO -- This is the same as processchain!!!
  649. var allwaitr = function(){
  650. var allResolved = true
  651. console.log('resultPs : ' + resultPs.length)
  652. for(var rIdx =0; rIdx < resultPs.length; rIdx++ ){
  653. if(resultPs[rIdx]) {
  654. allResolved = false
  655. waitForResult(resultPs[rIdx], function(r){
  656. if(Promise.resolve(r) !== r) results[rIdx] = r; resultPs[rIdx] = null;
  657. })
  658. break;
  659. }
  660. }
  661. if(allResolved) {
  662. // console.log('All Reseloved')
  663. // console.dir(results)
  664. resolve(results)
  665. }
  666. else wait(allwaitr, 500)
  667. }
  668. wait(allwaitr, 500)
  669. })
  670. // pAll.chain = arr;
  671. return pAll
  672. }
  673. // PromiseClass.resolve = overrides.resolve;
  674. Promise = PromiseClass;
  675. return PromiseClass;
  676. }
  677. }
  678. function __main( selectedinstance ){
  679. var downloadsdir = selectedinstance.root + '/Downloads';
  680. var callsheltask = function(args) { return function() { return nodeShellExec.apply(null, args) } }
  681. var gitUser = 'guest';
  682. var gitEmail = 'guest@bbh.org.in';
  683. var BUILD_VERSION = '[VI]Version: {version} - built on {date}[/VI]';
  684. function getVersion() { return BUILD_VERSION; }
  685. console.log(getVersion())
  686. function ensureDirectoryExistence(filePath) {
  687. var dirname = path.dirname(filePath);
  688. if (existsSyncFolder(dirname)) {
  689. return filePath;
  690. }
  691. ensureDirectoryExistence(dirname);
  692. fs.mkdirSync(dirname);
  693. return filePath;
  694. }
  695. var getTaskCheckExists = function(command, options) {
  696. options = options || {}
  697. return function() {
  698. var runFile = path.normalize(selectedinstance.root + '/.elxr/run-' + runtimestamp + '/' + stampedFilePfx(new Date()) + 'where' + command + "out.txt");
  699. var p = nodeShellExec.apply(null, ['cmd', ['/c', 'where', command], { runFile : runFile } ])
  700. p.runFile = runFile;
  701. if (options.ignorefailures) {
  702. return p.then(function(v) {
  703. // WScript.Echo('firstThen ' + v);
  704. return v })['catch']( function(e) {
  705. console.error(e);
  706. // Ignore. Not a major error if where command fails !!!
  707. throw e;
  708. })
  709. }
  710. else return p.then(function() {
  711. // WScript.Echo('firstThen ddd');
  712. return v });
  713. }
  714. }
  715. function verifyAndInstallPrerequisites() {
  716. fs.writeFileSync(ensureDirectoryExistence(downloadsdir + '/readme.txt'), getVersion() + ' Your local downloads for this instance');
  717. var downloadbatch =
  718. "::************************************************************************** \r\n \
  719. :Download_ <url> <File> \r\n \
  720. Powershell.exe ^\r\n \
  721. $AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'; ^\r\n \
  722. [System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols; ^\r\n \
  723. (New-Object System.Net.WebClient).DownloadFile('%1','%2') \r\n \
  724. exit /b \r\n \
  725. ::**************************************************************************";
  726. ensureDirectoryExistence(path.normalize(selectedinstance.root + '/.elxr/run-' + runtimestamp + '/readme.txt'))
  727. fs.writeFileSync(path.normalize(selectedinstance.root + '/.elxr/run-' + runtimestamp + '/download.bat'), downloadbatch);
  728. var downloadtasks = [];
  729. var installtasks = [];
  730. prerequisites.forEach(function(preq) {
  731. var p = preq.exists().then(function(exists) {
  732. if (exists) console.log( preq.shellcmd + ' exists');
  733. else {
  734. console.log(exists)
  735. console.log(preq.shellcmd + ' is not installed');
  736. return preq.preinstallsteps().then(function(){
  737. // console.log(' task.install : ' + preq.install)
  738. installtasks.push( function(){ return preq.install() } );
  739. })
  740. }
  741. })
  742. // .then(function(res){ console.log( 'preinstallsteps ' + res)});
  743. downloadtasks.push( p )
  744. });
  745. // console.log('downloadtasks')
  746. // console.dir(downloadtasks[0])
  747. var p = Promise.all(downloadtasks).then(function(){
  748. // console.log('calling install tasks : ' + installtasks.length)
  749. return any(installtasks) })
  750. // console.log('Promise.all.chain : ' + p.chain)
  751. return p
  752. }
  753. // var choiceHandler = function(choices, choice) {
  754. // console.log('chosen : ' + choice)
  755. // var decision = choices['d'];
  756. // if (choice && choice === 'd' || !choice) {
  757. // decision = choices['d']
  758. // }
  759. // else if (isNaN((+choice))) {
  760. // decision = choice
  761. // }
  762. // else decision = choices[choice-1]
  763. // if(!decision) throw 'Invalid selection : ' + decision
  764. // return decision
  765. // }
  766. // prereq definition helpers. We can't do proper inheritance in cscript. So fallback to global functions.
  767. function exists(next){
  768. var self = this;
  769. console.log('checking existence of ' + self.shellcmd)
  770. return getTaskCheckExists(self.shellcmd, { ignorefailures: true })().then(function(exists) {
  771. // console.log('-------------exists=======================')
  772. // console.dir(exists)
  773. // console.log(exists + ' ' + self.shellcmd + ' exists')
  774. if(exists && exists.messages.join(' ').indexOf(self.shellcmd) > -1 ) {
  775. return true;
  776. }
  777. else return false
  778. })['catch'](function(e){
  779. // console.log('-------------exists catch=======================')
  780. console.dir(e)
  781. return false;
  782. })
  783. }
  784. function unique(arr) {
  785. var hash = {}, result = [];
  786. for ( var i = 0, l = arr.length; i < l; ++i ) {
  787. if ( !hash.hasOwnProperty(arr[i]) ) { //it works with objects! in FF, at least
  788. hash[ arr[i] ] = true;
  789. result.push(arr[i]);
  790. }
  791. }
  792. return result;
  793. }
  794. // var ENV = Object.assign({}, process.env); // Shallow clone it.
  795. var WshShell = WScript.CreateObject("WScript.Shell")
  796. var ENV = WshShell.Environment("Process")
  797. WScript.echo( ENV("Path") )
  798. function sysAddPathVar(path){
  799. // Object.assign({
  800. // inherit: true, shell: true, env: ENV, title: `${command} ${args}`
  801. // }, options)
  802. // var newpath = ENV("Path").split(';');
  803. // newpath = Array.from(new Set(newpath.push(path))).join(';')
  804. var newpath = [];
  805. newpath.push(path)
  806. newpath = unique(newpath).join(';')
  807. // path.split(';').forEach(pel => { var kv = pel.split('='); kv[0] === key ? null : newpath.push(pel); } )
  808. return any([nodeShellExec('setx', [/*'/m',*/ 'PATH', '"%PATH%;' + newpath + '"' ])
  809. // , nodeShellExec('set', [/*'/m',*/ 'PATH', '"%PATH%;' + newpath + '"' ])
  810. ] );
  811. }
  812. var prerequisites = [
  813. {
  814. shellcmd: 'git',
  815. url: 'https://github.com/git-for-windows/git/releases/download/v2.33.0.windows.2/Git-2.33.0.2-64-bit.exe'
  816. , installer: 'Git-2.33.0.2-64-bit.exe'
  817. , installcmd: ['cmd', ['/c', 'start',
  818. '/WAIT', downloadsdir + '/' + 'Git-2.33.0.2-64-bit.exe'
  819. , '/VERYSILENT'
  820. // , '/MERGETASKS=!runcode' // This is required only for vscode...
  821. ]]
  822. , preinstallsteps: function() {
  823. var self = this;
  824. console.log('Git preinstall steps')
  825. var steps = [];
  826. steps.push(
  827. function(){
  828. // console.log('cli prompt steps')
  829. var choices = { 0 : 'guest', 1 : 'chessdemo' }
  830. return cli.prompt(choices, 'git user name', gitUser).then(function(choice){ gitUser = choice } )
  831. }
  832. )
  833. steps.push(
  834. function(){
  835. var choices = { 0 : 'guest@bbh.org.in', 1 : 'chessdemo@bbh.org.in' }
  836. return cli.prompt(choices, 'git user email', gitEmail).then(function(choice){ gitEmail = choice })
  837. }
  838. )
  839. steps.push(
  840. function(){
  841. if (!existsSync(downloadsdir + '/' + self.installer)) {
  842. return nodeShellExec(selectedinstance.root + '/.elxr/run-' + runtimestamp + '/download.bat', [self.url, downloadsdir + '/' + self.installer])
  843. }
  844. else {
  845. console.log(self.installer + ' Already exits Download skipped.')
  846. return Promise.resolve(true)
  847. }
  848. }
  849. )
  850. return any(steps)
  851. // return any([any(steps), any(prompts)])
  852. }
  853. , installsteps: function () {
  854. var self = this;
  855. console.log('Git Installsteps called')
  856. var ifns = [self.installcmd]
  857. if(!ifns.map) ifns.map = map;
  858. return any(ifns.map(callsheltask))['catch'](function(e){
  859. if(e.code === 1602) {
  860. console.warn("Installation was probably cancelled.")
  861. }
  862. else throw e
  863. })
  864. }
  865. , postinstallsteps: function(){
  866. // PB : TODO -- Detect failure or cancellation before attenpting postinstall steps...
  867. var steps = [];
  868. steps.push(
  869. function(){
  870. var choices = { 0 : 'guest', 1 : 'chessdemo' }
  871. return cli.prompt(choices, 'git user name', gitUser).then(function(choice){ gitUser = choice } )
  872. }
  873. )
  874. steps.push(
  875. function(){
  876. var choices = { 0 : 'guest@bbh.org.in', 1 : 'chessdemo@bbh.org.in' }
  877. return cli.prompt(choices, 'git user email', gitEmail).then(function(choice){ gitEmail = choice })
  878. }
  879. )
  880. return any(steps).then(function(){
  881. var steps = [
  882. ['git', ['config', '--global', '--add', 'user.name', gitUser]]
  883. , ['git', ['config', '--global', '--add', 'user.email', gitEmail]]
  884. ]
  885. if(!steps.map) steps.map = map;
  886. return any(steps.map(callsheltask)).then(function(){
  887. })
  888. });
  889. }
  890. , install: function () {
  891. var self = this;
  892. console.log('Git Install called')
  893. return any([ /*self.preinstallsteps,*/ function(){ return self.installsteps() }, function(){ return self.postinstallsteps() } ])
  894. }
  895. , verifyAndInstall : function(){
  896. var self = this;
  897. return self.exists().then( function(exits) {
  898. if(exists) return self.getUser(null, function(){ return self.postinstallsteps() } )
  899. else return self.install();
  900. })
  901. }
  902. , exists : exists
  903. , getUser : function(repo, onNoResult){
  904. onNoResult = onNoResult || function(){return false}
  905. var globalOrLocal = '--global';
  906. if(!repo) globalOrLocal = '--global';
  907. else globalOrLocal = '--local'
  908. var fns = [['git', ['config', globalOrLocal, '--get-all', 'user.name']]]
  909. if(!ifns.map) ifns.map = map;
  910. return any(fns.map(callsheltask)).then(function(result){
  911. // not yet configured.
  912. if(!result.success) return onNoResult()
  913. else {
  914. var users = result.messages[0].trim().split('\n');
  915. if(users.length === 0 ||
  916. users.length === 1 && users[0] === 'guest') {
  917. return onNoResult()
  918. }
  919. else return users[0]; // PB : TODO == We should probably prompt with all the users available for selection !
  920. }
  921. })
  922. ['catch'](function(e){
  923. console.log(e)
  924. return onNoResult()
  925. })
  926. }
  927. }
  928. ,
  929. {
  930. shellcmd: 'node',
  931. url: 'https://nodejs.org/dist/v14.17.6/node-v14.17.6-x64.msi'
  932. , installer: 'node-v14.17.3-x64.msi'
  933. , installcmd: ['MSIEXEC.exe', ['/i'
  934. , path.normalize(downloadsdir + '/' + 'node-v14.17.3-x64.msi')
  935. , 'ACCEPT=YES', '/passive']]
  936. , install : function() {
  937. var self = this;
  938. var ifns = [self.installcmd]
  939. if(!ifns.map) ifns.map = map;
  940. return any(ifns.map(callsheltask))['catch'](function(e){
  941. if(e.code === 1602) {
  942. console.warn("Installation was probably cancelled.")
  943. }
  944. else throw e
  945. })
  946. }
  947. , exists : exists
  948. , preinstallsteps: function() {
  949. var self = this;
  950. console.log('Node preinstall steps')
  951. var steps = [];
  952. steps.push(
  953. function(){
  954. if (!existsSync(downloadsdir + '/' + self.installer)) {
  955. return nodeShellExec(selectedinstance.root + '/.elxr/run-' + runtimestamp + '/download.bat', [self.url, downloadsdir + '/' + self.installer]
  956. , { waitmsg : 'downloading node please wait' })
  957. }
  958. else {
  959. console.log(self.installer + ' Already exits Download skipped.')
  960. return Promise.resolve(true)
  961. }
  962. }
  963. )
  964. return any(steps)
  965. // return any([any(steps), any(prompts)])
  966. }
  967. }
  968. , {
  969. shellcmd: 'python2'
  970. , url: 'https://www.python.org/ftp/python/2.7.18/python-2.7.18.amd64.msi'
  971. , installer: 'python-2.7.18.amd64.msi'
  972. , installcmd: ['MSIEXEC.exe', ['/i'
  973. , path.normalize(downloadsdir + '/' + 'python-2.7.18.amd64.msi')
  974. , 'ACCEPT=YES', '/passive']]
  975. , preinstallsteps : function() { return Promise.resolve(true) }
  976. , install : function() {
  977. var self = this;
  978. var ifns = [self.installcmd]
  979. if(!ifns.map) ifns.map = map;
  980. console.log('Installing')
  981. return any(ifns.map(callsheltask))['catch'](function(e){
  982. if(e.code === 1602) {
  983. console.warn("Installation was probably cancelled.")
  984. }
  985. else throw e
  986. }).then(function(){
  987. return self.postinstallsteps()
  988. })
  989. }
  990. , postinstallsteps : function() { return sysAddPathVar('%USERPROFILE%\\AppData/Local\\Microsoft\\WindowsApps') }
  991. , exists : exists
  992. }
  993. ,
  994. {
  995. shellcmd: 'elxr'
  996. , installcmd: [ isWin() ? 'npm.cmd' : 'npm' , ['link'], { cwd : selectedinstance.root + '\\elxr' /* cwd should be the cloned dir*/}]
  997. , preinstallsteps: function() {
  998. var self = this;
  999. console.log('Elxr preinstall steps')
  1000. var steps = [];
  1001. steps.push(
  1002. function(){
  1003. console.log('Elxr PreInstallsteps called')
  1004. var ifns = [ ['git', ['clone', 'http://git.bbh/chess\\elxr'] ] ]
  1005. if(existsSyncFolder( selectedinstance.root + '\\elxr')) {
  1006. if(existsSyncFolder( selectedinstance.root + '\\elxr\\.git')) {
  1007. // PB : TODO -- use a elxr guid signature to detect more reliably folders named the same that is not us.
  1008. ifns = [ ['git', ['pull'], { cwd : selectedinstance.root + '\\elxr' } ] ]
  1009. }
  1010. else {
  1011. throw 'elxr subfolder not recognized as a git repository. Please cleanup and continue.'
  1012. }
  1013. }
  1014. else console.log(selectedinstance.root + '\\elxr' + ' NOT FOUND ')
  1015. if(!ifns.map) ifns.map = map;
  1016. return any(ifns.map(callsheltask))['catch'](function(e){
  1017. if(e.code === 1602) {
  1018. console.warn("Installation was probably cancelled.")
  1019. }
  1020. else throw e
  1021. })
  1022. }
  1023. )
  1024. return any([any(steps)])
  1025. }
  1026. , installsteps: function () {
  1027. var self = this;
  1028. console.log('Elxr Installsteps called')
  1029. var ifns = [self.installcmd]
  1030. if(!ifns.map) ifns.map = map;
  1031. return any(ifns.map(callsheltask))['catch'](function(e){
  1032. if(e.code === 1602) {
  1033. console.warn("Installation was probably cancelled.")
  1034. }
  1035. else throw e
  1036. })
  1037. }
  1038. , install: function () {
  1039. var self = this;
  1040. console.log('Elxr Install called')
  1041. return any([ /*self.preinstallsteps,*/ function(){ return self.installsteps() } ])
  1042. }
  1043. // , exists : function(){
  1044. // console.log('Elxr PreInstallsteps called')
  1045. // var ifns = [ ['git', ['clone', 'http://git.bbh/chess\\elxr'] ] ]
  1046. // if(existsSyncFolder( selectedinstance.root + '\\elxr')) {
  1047. // if(existsSyncFolder( selectedinstance.root + '\\elxr\\.git')) {
  1048. // // PB : TODO -- use a elxr guid signature to detect more reliably folders named the same that is not us.
  1049. // ifns = [ ['git', ['pull'], { cwd : selectedinstance.root + '\\elxr' } ] ]
  1050. // }
  1051. // else {
  1052. // throw 'elxr subfolder not recognized as a git repository. Please cleanup and continue.'
  1053. // }
  1054. // }
  1055. // else console.log(selectedinstance.root + '\\elxr' + ' NOT FOUND ')
  1056. // if(!ifns.map) ifns.map = map;
  1057. // return any(ifns.map(callsheltask))['catch'](function(e){
  1058. // if(e.code === 1602) {
  1059. // console.warn("Installation was probably cancelled.")
  1060. // }
  1061. // else throw e
  1062. // })
  1063. // }
  1064. , exists : exists
  1065. }
  1066. ]
  1067. if(!prerequisites.forEach) prerequisites.forEach = forEach;
  1068. // nodeShellExec(selectedinstance.root + '/.elxr/run-' + '1629889572461' + '/download.bat'
  1069. // , ['https://github.com/git-for-windows/git/releases/download/v2.31.0.windows.1/Git-2.32.0.2-64-bit.exe'
  1070. // , downloadsdir + '/' + 'Git-2.32.0.2-64-bit.exe']).start()
  1071. promises.push(verifyAndInstallPrerequisites())
  1072. startPromises();
  1073. }