prompt.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. var falafel = require('../');
  2. var vm = require('vm');
  3. var termExps = [
  4. 'Identifier',
  5. 'CallExpression',
  6. 'BinaryExpression',
  7. 'UpdateExpression',
  8. 'UnaryExpression'
  9. ].reduce(function (acc, key) { acc[key] = true; return acc }, {});
  10. function terminated (node) {
  11. for (var p = node; p.parent; p = p.parent) {
  12. if (termExps[p.type]) return true;
  13. }
  14. return false;
  15. }
  16. var src = '{"a":[2,~9,prompt(":d")],"b":4,"c":prompt("beep"),"d":6}';
  17. var offsets = [];
  18. var output = falafel('(' + src + ')', function (node) {
  19. var isLeaf = node.parent
  20. && !terminated(node.parent) && terminated(node)
  21. ;
  22. if (isLeaf) {
  23. var s = node.source();
  24. var prompted = false;
  25. var res = vm.runInNewContext('(' + s + ')', {
  26. prompt : function (x) {
  27. setTimeout(function () {
  28. node.update(x.toUpperCase());
  29. }, Math.random() * 50);
  30. prompted = true;
  31. }
  32. });
  33. if (!prompted) {
  34. var s_ = JSON.stringify(res);
  35. node.update(s_);
  36. }
  37. }
  38. });
  39. setTimeout(function () {
  40. console.log(src);
  41. console.log('---');
  42. console.log(output);
  43. }, 200);