index.js
  1  'use strict';
  2  
  3  const escapeStringRegexp = require('escape-string-regexp');
  4  
  5  const cwd = typeof process === 'object' && process && typeof process.cwd === 'function'
  6    ? process.cwd()
  7    : '.'
  8  
  9  const natives = [].concat(
 10    require('module').builtinModules,
 11    'bootstrap_node',
 12    'node',
 13  ).map(n => new RegExp(`(?:\\((?:node:)?${n}(?:\\.js)?:\\d+:\\d+\\)$|^\\s*at (?:node:)?${n}(?:\\.js)?:\\d+:\\d+$)`));
 14  
 15  natives.push(
 16    /\((?:node:)?internal\/[^:]+:\d+:\d+\)$/,
 17    /\s*at (?:node:)?internal\/[^:]+:\d+:\d+$/,
 18    /\/\.node-spawn-wrap-\w+-\w+\/node:\d+:\d+\)?$/
 19  );
 20  
 21  class StackUtils {
 22    constructor (opts) {
 23      opts = {
 24        ignoredPackages: [],
 25        ...opts
 26      };
 27  
 28      if ('internals' in opts === false) {
 29        opts.internals = StackUtils.nodeInternals();
 30      }
 31  
 32      if ('cwd' in opts === false) {
 33        opts.cwd = cwd
 34      }
 35  
 36      this._cwd = opts.cwd.replace(/\\/g, '/');
 37      this._internals = [].concat(
 38        opts.internals,
 39        ignoredPackagesRegExp(opts.ignoredPackages)
 40      );
 41  
 42      this._wrapCallSite = opts.wrapCallSite || false;
 43    }
 44  
 45    static nodeInternals () {
 46      return [...natives];
 47    }
 48  
 49    clean (stack, indent = 0) {
 50      indent = ' '.repeat(indent);
 51  
 52      if (!Array.isArray(stack)) {
 53        stack = stack.split('\n');
 54      }
 55  
 56      if (!(/^\s*at /.test(stack[0])) && (/^\s*at /.test(stack[1]))) {
 57        stack = stack.slice(1);
 58      }
 59  
 60      let outdent = false;
 61      let lastNonAtLine = null;
 62      const result = [];
 63  
 64      stack.forEach(st => {
 65        st = st.replace(/\\/g, '/');
 66  
 67        if (this._internals.some(internal => internal.test(st))) {
 68          return;
 69        }
 70  
 71        const isAtLine = /^\s*at /.test(st);
 72  
 73        if (outdent) {
 74          st = st.trimEnd().replace(/^(\s+)at /, '$1');
 75        } else {
 76          st = st.trim();
 77          if (isAtLine) {
 78            st = st.slice(3);
 79          }
 80        }
 81  
 82        st = st.replace(`${this._cwd}/`, '');
 83  
 84        if (st) {
 85          if (isAtLine) {
 86            if (lastNonAtLine) {
 87              result.push(lastNonAtLine);
 88              lastNonAtLine = null;
 89            }
 90  
 91            result.push(st);
 92          } else {
 93            outdent = true;
 94            lastNonAtLine = st;
 95          }
 96        }
 97      });
 98  
 99      return result.map(line => `${indent}${line}\n`).join('');
100    }
101  
102    captureString (limit, fn = this.captureString) {
103      if (typeof limit === 'function') {
104        fn = limit;
105        limit = Infinity;
106      }
107  
108      const {stackTraceLimit} = Error;
109      if (limit) {
110        Error.stackTraceLimit = limit;
111      }
112  
113      const obj = {};
114  
115      Error.captureStackTrace(obj, fn);
116      const {stack} = obj;
117      Error.stackTraceLimit = stackTraceLimit;
118  
119      return this.clean(stack);
120    }
121  
122    capture (limit, fn = this.capture) {
123      if (typeof limit === 'function') {
124        fn = limit;
125        limit = Infinity;
126      }
127  
128      const {prepareStackTrace, stackTraceLimit} = Error;
129      Error.prepareStackTrace = (obj, site) => {
130        if (this._wrapCallSite) {
131          return site.map(this._wrapCallSite);
132        }
133  
134        return site;
135      };
136  
137      if (limit) {
138        Error.stackTraceLimit = limit;
139      }
140  
141      const obj = {};
142      Error.captureStackTrace(obj, fn);
143      const { stack } = obj;
144      Object.assign(Error, {prepareStackTrace, stackTraceLimit});
145  
146      return stack;
147    }
148  
149    at (fn = this.at) {
150      const [site] = this.capture(1, fn);
151  
152      if (!site) {
153        return {};
154      }
155  
156      const res = {
157        line: site.getLineNumber(),
158        column: site.getColumnNumber()
159      };
160  
161      setFile(res, site.getFileName(), this._cwd);
162  
163      if (site.isConstructor()) {
164        res.constructor = true;
165      }
166  
167      if (site.isEval()) {
168        res.evalOrigin = site.getEvalOrigin();
169      }
170  
171      // Node v10 stopped with the isNative() on callsites, apparently
172      /* istanbul ignore next */
173      if (site.isNative()) {
174        res.native = true;
175      }
176  
177      let typename;
178      try {
179        typename = site.getTypeName();
180      } catch (_) {
181      }
182  
183      if (typename && typename !== 'Object' && typename !== '[object Object]') {
184        res.type = typename;
185      }
186  
187      const fname = site.getFunctionName();
188      if (fname) {
189        res.function = fname;
190      }
191  
192      const meth = site.getMethodName();
193      if (meth && fname !== meth) {
194        res.method = meth;
195      }
196  
197      return res;
198    }
199  
200    parseLine (line) {
201      const match = line && line.match(re);
202      if (!match) {
203        return null;
204      }
205  
206      const ctor = match[1] === 'new';
207      let fname = match[2];
208      const evalOrigin = match[3];
209      const evalFile = match[4];
210      const evalLine = Number(match[5]);
211      const evalCol = Number(match[6]);
212      let file = match[7];
213      const lnum = match[8];
214      const col = match[9];
215      const native = match[10] === 'native';
216      const closeParen = match[11] === ')';
217      let method;
218  
219      const res = {};
220  
221      if (lnum) {
222        res.line = Number(lnum);
223      }
224  
225      if (col) {
226        res.column = Number(col);
227      }
228  
229      if (closeParen && file) {
230        // make sure parens are balanced
231        // if we have a file like "asdf) [as foo] (xyz.js", then odds are
232        // that the fname should be += " (asdf) [as foo]" and the file
233        // should be just "xyz.js"
234        // walk backwards from the end to find the last unbalanced (
235        let closes = 0;
236        for (let i = file.length - 1; i > 0; i--) {
237          if (file.charAt(i) === ')') {
238            closes++;
239          } else if (file.charAt(i) === '(' && file.charAt(i - 1) === ' ') {
240            closes--;
241            if (closes === -1 && file.charAt(i - 1) === ' ') {
242              const before = file.slice(0, i - 1);
243              const after = file.slice(i + 1);
244              file = after;
245              fname += ` (${before}`;
246              break;
247            }
248          }
249        }
250      }
251  
252      if (fname) {
253        const methodMatch = fname.match(methodRe);
254        if (methodMatch) {
255          fname = methodMatch[1];
256          method = methodMatch[2];
257        }
258      }
259  
260      setFile(res, file, this._cwd);
261  
262      if (ctor) {
263        res.constructor = true;
264      }
265  
266      if (evalOrigin) {
267        res.evalOrigin = evalOrigin;
268        res.evalLine = evalLine;
269        res.evalColumn = evalCol;
270        res.evalFile = evalFile && evalFile.replace(/\\/g, '/');
271      }
272  
273      if (native) {
274        res.native = true;
275      }
276  
277      if (fname) {
278        res.function = fname;
279      }
280  
281      if (method && fname !== method) {
282        res.method = method;
283      }
284  
285      return res;
286    }
287  }
288  
289  function setFile (result, filename, cwd) {
290    if (filename) {
291      filename = filename.replace(/\\/g, '/');
292      if (filename.startsWith(`${cwd}/`)) {
293        filename = filename.slice(cwd.length + 1);
294      }
295  
296      result.file = filename;
297    }
298  }
299  
300  function ignoredPackagesRegExp(ignoredPackages) {
301    if (ignoredPackages.length === 0) {
302      return [];
303    }
304  
305    const packages = ignoredPackages.map(mod => escapeStringRegexp(mod));
306  
307    return new RegExp(`[\/\\\\]node_modules[\/\\\\](?:${packages.join('|')})[\/\\\\][^:]+:\\d+:\\d+`)
308  }
309  
310  const re = new RegExp(
311    '^' +
312      // Sometimes we strip out the '    at' because it's noisy
313    '(?:\\s*at )?' +
314      // $1 = ctor if 'new'
315    '(?:(new) )?' +
316      // $2 = function name (can be literally anything)
317      // May contain method at the end as [as xyz]
318    '(?:(.*?) \\()?' +
319      // (eval at <anonymous> (file.js:1:1),
320      // $3 = eval origin
321      // $4:$5:$6 are eval file/line/col, but not normally reported
322    '(?:eval at ([^ ]+) \\((.+?):(\\d+):(\\d+)\\), )?' +
323      // file:line:col
324      // $7:$8:$9
325      // $10 = 'native' if native
326    '(?:(.+?):(\\d+):(\\d+)|(native))' +
327      // maybe close the paren, then end
328      // if $11 is ), then we only allow balanced parens in the filename
329      // any imbalance is placed on the fname.  This is a heuristic, and
330      // bound to be incorrect in some edge cases.  The bet is that
331      // having weird characters in method names is more common than
332      // having weird characters in filenames, which seems reasonable.
333    '(\\)?)$'
334  );
335  
336  const methodRe = /^(.*?) \[as (.*?)\]$/;
337  
338  module.exports = StackUtils;