index.js 7.5 KB

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