1. /**
  2. * Buffers string input with a timeout for dry-run scenarios.
  3. *
  4. * @param {number} timeoutMs The timeout in milliseconds.
  5. * @returns {Promise<string>} A promise that resolves with the buffered input string
  6. * or rejects with an error if the timeout is exceeded.
  7. */
  8. async function bufferedInput(timeoutMs) {
  9. let buffer = "";
  10. let startTime = Date.now();
  11. return new Promise((resolve, reject) => {
  12. const inputHandler = (e) => {
  13. if (e.length > 0) {
  14. buffer += e;
  15. }
  16. };
  17. // Capture input events
  18. process.stdin.setEncoding('utf8');
  19. process.stdin.on('data', inputHandler);
  20. process.stdin.resume();
  21. process.stdin.on('timeout', () => {
  22. process.stdin.off('data', inputHandler);
  23. process.stdin.off('timeout');
  24. if (buffer.length > 0) {
  25. resolve(buffer);
  26. } else {
  27. reject(new Error("Timeout: No input received"));
  28. }
  29. });
  30. process.stdin.on('close', () => {
  31. process.stdin.off('data', inputHandler);
  32. process.stdin.off('timeout');
  33. resolve(buffer);
  34. });
  35. // Timeout implementation
  36. setTimeout(() => {
  37. process.stdin.off('data', inputHandler);
  38. process.stdin.off('timeout');
  39. resolve(buffer);
  40. }, timeoutMs);
  41. });
  42. }

Add your comment