index.js 7.8 KB

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