summaryrefslogtreecommitdiff
path: root/deps/node-inspect/test/cli/start-cli.js
blob: e2fa5fe47c9ebe8088129575513757b8fa619a36 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
'use strict';
const spawn = require('child_process').spawn;

// This allows us to keep the helper inside of `test/` without tap warning
// about "pending" test files.
const tap = require('tap');
tap.test('startCLI', (t) => t.end());

const CLI =
  process.env.USE_EMBEDDED_NODE_INSPECT === '1' ?
  'inspect' :
  require.resolve('../../cli.js');

const BREAK_MESSAGE = new RegExp('(?:' + [
  'assert', 'break', 'break on start', 'debugCommand',
  'exception', 'other', 'promiseRejection',
].join('|') + ') in', 'i');

function isPreBreak(output) {
  return /Break on start/.test(output) && /1 \(function \(exports/.test(output);
}

function startCLI(args, flags = []) {
  const child = spawn(process.execPath, [...flags, CLI, ...args]);
  let isFirstStdoutChunk = true;

  const outputBuffer = [];
  function bufferOutput(chunk) {
    if (isFirstStdoutChunk) {
      isFirstStdoutChunk = false;
      outputBuffer.push(chunk.replace(/^debug>\s*/, ''));
    } else {
      outputBuffer.push(chunk);
    }
  }

  function getOutput() {
    return outputBuffer.join('').toString()
      .replace(/^[^\n]*?[\b]/mg, '');
  }

  child.stdout.setEncoding('utf8');
  child.stdout.on('data', bufferOutput);
  child.stderr.setEncoding('utf8');
  child.stderr.on('data', bufferOutput);

  if (process.env.VERBOSE === '1') {
    child.stdout.pipe(process.stderr);
    child.stderr.pipe(process.stderr);
  }

  return {
    flushOutput() {
      const output = this.output;
      outputBuffer.length = 0;
      return output;
    },

    waitFor(pattern, timeout = 2000) {
      function checkPattern(str) {
        if (Array.isArray(pattern)) {
          return pattern.every((p) => p.test(str));
        }
        return pattern.test(str);
      }

      return new Promise((resolve, reject) => {
        function checkOutput() {
          if (checkPattern(getOutput())) {
            tearDown(); // eslint-disable-line no-use-before-define
            resolve();
          }
        }

        function onChildExit() {
          tearDown(); // eslint-disable-line no-use-before-define
          reject(new Error(
            `Child quit while waiting for ${pattern}; found: ${this.output}`));
        }

        const timer = setTimeout(() => {
          tearDown(); // eslint-disable-line no-use-before-define
          reject(new Error([
            `Timeout (${timeout}) while waiting for ${pattern}`,
            `found: ${this.output}`,
          ].join('; ')));
        }, timeout);

        function tearDown() {
          clearTimeout(timer);
          child.stdout.removeListener('data', checkOutput);
          child.removeListener('exit', onChildExit);
        }

        child.on('exit', onChildExit);
        child.stdout.on('data', checkOutput);
        checkOutput();
      });
    },

    waitForPrompt(timeout = 2000) {
      return this.waitFor(/>\s+$/, timeout);
    },

    waitForInitialBreak(timeout = 2000) {
      return this.waitFor(/break (?:on start )?in/i, timeout)
        .then(() => {
          if (isPreBreak(this.output)) {
            return this.command('next', false)
              .then(() => this.waitFor(/break in/, timeout));
          }
        });
    },

    get breakInfo() {
      const output = this.output;
      const breakMatch =
        output.match(/break (?:on start )?in ([^\n]+):(\d+)\n/i);

      if (breakMatch === null) {
        throw new Error(
          `Could not find breakpoint info in ${JSON.stringify(output)}`);
      }
      return { filename: breakMatch[1], line: +breakMatch[2] };
    },

    ctrlC() {
      return this.command('.interrupt');
    },

    get output() {
      return getOutput();
    },

    get rawOutput() {
      return outputBuffer.join('').toString();
    },

    parseSourceLines() {
      return getOutput().split('\n')
        .map((line) => line.match(/(?:\*|>)?\s*(\d+)/))
        .filter((match) => match !== null)
        .map((match) => +match[1]);
    },

    writeLine(input, flush = true) {
      if (flush) {
        this.flushOutput();
      }
      if (process.env.VERBOSE === '1') {
        process.stderr.write(`< ${input}\n`);
      }
      child.stdin.write(input);
      child.stdin.write('\n');
    },

    command(input, flush = true) {
      this.writeLine(input, flush);
      return this.waitForPrompt();
    },

    stepCommand(input) {
      this.writeLine(input, true);
      return this
        .waitFor(BREAK_MESSAGE)
        .then(() => this.waitForPrompt());
    },

    quit() {
      return new Promise((resolve) => {
        child.stdin.end();
        child.on('exit', resolve);
      });
    },
  };
}
module.exports = startCLI;