-
Notifications
You must be signed in to change notification settings - Fork 1
/
better-stack-traces.js
309 lines (282 loc) · 8.89 KB
/
better-stack-traces.js
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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
;(function () {
var LINES_BEFORE = 2;
var LINES_AFTER = 3;
var MAX_COLUMNS = 80;
var DEFAULT_INDENT = 4;
var GUTTER_CONTENT = " » ";
var DOT_CHAR = "•";
var ELLIPSIS_CHAR = "…";
var EMDASH_CHAR = "─";
var ERR_FILE_NOT_EXIST = "ENOENT";
var NOOP = function() {};
var DEFAULT_LIBRARY_REGEX = /node_modules/;
// Helper for generating a repeated string.
function repeatString(repeat, length) {
return new Array(length).join(repeat) + repeat;
}
// Helper for getting a default value only when the given value is undefined.
function fallback(value, fallbackValue) {
return typeof value === "undefined" ? fallbackValue : value;
}
/*
/path/to/your/code.js
─────────────────────
189 »
190 » function bar(x) {
191 » throw new Error("x: " + x)
•••••••••••••••
192 » }
193 »
194 » foo(bar)
*/
function BetterStackTrace(error, frames, opt) {
this.error = error;
this.frames = frames;
// Initialize caches.
this._outCache = null;
this._fileCache = {};
// Parse flags.
opt = opt || {};
this._collapseLibraries = fallback(opt.collapseLibraries, DEFAULT_LIBRARY_REGEX);
this._linesBefore = fallback(opt.before, LINES_BEFORE);
this._linesAfter = fallback(opt.after, LINES_AFTER);
this._maxColumns = opt.maxColumns || MAX_COLUMNS;
this._outputPrefix = repeatString(" ", fallback(opt.indent, DEFAULT_INDENT));
this._gutterContent = opt.gutter || GUTTER_CONTENT;
// Get external dependencies.
var req = opt.require || (typeof require === "undefined" ? NOOP : require);
var win = opt.window || (typeof window === "undefined" ? {} : window);
this._fs = opt.fs || req("fs") || win.fs;
try {
this._coffee = opt.coffee || req("coffee-script") || win.CoffeeScript;
} catch(err) {
this._coffee = null;
}
}
BetterStackTrace.prototype = {
// Final traces are output as strings.
toString: function toString() {
this._outCache = this._outCache || this._format(this.error, this.frames);
return this._outCache;
},
_shouldCollapse: function _shouldCollapse(fileName) {
if (this._collapseLibraries) {
if (this._collapseLibraries.test) {
return this._collapseLibraries.test(fileName);
} else {
return DEFAULT_LIBRARY_REGEX.test(fileName);
}
} else {
return false;
}
},
_readCode: function _readCode(fileName) {
var code = this._fileCache[fileName];
if (!code) {
code = this._fs.readFileSync(fileName).toString();
if (/\.coffee$/.test(fileName)) {
if (this._coffee) {
code = this._compileCoffeeScript(code);
} else {
throw new Error("CoffeeScript compiler unavailable, did you include it in your dependencies?");
}
}
this._fileCache[fileName] = code;
}
return code;
},
_compileCoffeeScript: function _compileCoffeeScript(code) {
if (this._coffee) {
return this._coffee.compile(code);
} else {
return "CoffeeScript compiler unavailable";
}
},
_formatCodeLine: function _formatCodeLine(lineNumber, line, maxLineNumber) {
var pad = maxLineNumber.toString().length - lineNumber.toString().length;
var padding = "";
while (pad-- > 0) {
padding += " ";
}
if (line.length > this._maxColumns) {
line = line.slice(0, this._maxColumns - 1) + ELLIPSIS_CHAR;
}
return padding + lineNumber + this._gutterContent + line;
},
_formatCodeArrow: function _formatCodeArrow(lineNumber, columnNumber, maxLineNumber) {
var length = (this._gutterContent + maxLineNumber).length + columnNumber;
return repeatString(DOT_CHAR, length);
},
_formatContext: function _formatContext(fileName, lineNumber, columnNumber) {
// Attempt to read the file, compiling to CoffeeScript if needed.
// Show errors if there is a problem reading the code.
try {
var code = this._readCode(fileName);
} catch(err) {
if (err.code === ERR_FILE_NOT_EXIST) {
throw err;
}
return this._outputPrefix + err.toString();
}
// Figure out the lines of context before and after.
var lines = code.split("\n");
var preLines = lines.slice(lineNumber - this._linesBefore - 1, lineNumber);
var postLines = lines.slice(lineNumber, lineNumber + this._linesAfter);
// Collect formatted versions of all the lines. Render
var formattedLines = [];
var maxLineNumber = lineNumber + this._linesAfter;
var currentLineNumber = lineNumber - this._linesBefore;
function renderLines(lines) {
while (lines.length) {
formattedLines.push(this._formatCodeLine(
currentLineNumber++,
lines.shift(),
maxLineNumber
));
}
}
renderLines.call(this, preLines);
formattedLines.push(this._formatCodeArrow(
currentLineNumber - 1,
columnNumber,
maxLineNumber
));
renderLines.call(this, postLines);
return this._outputPrefix + formattedLines.join("\n" + this._outputPrefix);
},
// Based on V8 FormatStackTrace.
// http://code.google.com/p/v8/source/browse/trunk/src/messages.js
_format: function _format(error, frames) {
var lines = [];
try {
lines.push(error.toString());
} catch (e) {
try {
lines.push("<error: " + e + ">");
} catch (ee) {
lines.push("<error>");
}
}
for (var i = 0; i < frames.length; i++) {
var frame = frames[i];
var line;
try {
line = this._formatFrame(frame);
} catch (e) {
try {
line = "<error: " + e + ">";
} catch (ee) {
// Any code that reaches this point is seriously nasty!
line = "<error>";
}
}
lines.push(line);
}
return lines.join("\n");
},
// Based on V8 FormatSourcePosition.
// http://code.google.com/p/v8/source/browse/trunk/src/messages.js
_formatFrame: function _formatFrame(frame) {
var fileLocation = "";
var context = null;
if (frame.isNative()) {
fileLocation = "native";
} else if (frame.isEval()) {
fileLocation = "eval at " + frame.getEvalOrigin();
} else {
var fileName = frame.getFileName();
if (fileName) {
fileLocation += fileName;
var lineNumber = frame.getLineNumber();
if (lineNumber != null) {
fileLocation += ":" + lineNumber;
var columnNumber = frame.getColumnNumber();
if (columnNumber) {
fileLocation += ":" + columnNumber;
}
try {
if (this._shouldCollapse(fileName)) {
context = null;
} else {
context = this._formatContext(fileName, lineNumber, columnNumber);
}
} catch(err) {
if (err.code === ERR_FILE_NOT_EXIST) {
context = null;
} else {
context = err;
}
}
}
}
}
if (!fileLocation) {
fileLocation = "unknown source";
}
var line = "";
var functionName = frame.getFunction().name;
var methodName = frame.getMethodName();
var addPrefix = true;
var isConstructor = frame.isConstructor();
var isMethodCall = !(frame.isToplevel() || isConstructor);
if (isMethodCall) {
line += frame.getTypeName() + ".";
if (functionName) {
line += functionName;
if (methodName && (methodName != functionName)) {
line += " [as " + methodName + "]";
}
} else {
line += methodName || "<anonymous>";
}
} else if (isConstructor) {
line += "new " + (functionName || "<anonymous>");
} else if (functionName) {
line += functionName;
} else {
line += fileLocation;
addPrefix = false;
}
if (addPrefix) {
line += " (" + fileLocation + ")";
}
line = "at " + line;
if (context) {
var underline = this._outputPrefix + line.replace(/./g, EMDASH_CHAR);
var betterLine = [line, underline, context].join("\n");
return this._outputPrefix + betterLine + "\n";
} else {
return this._outputPrefix + line;
}
}
};
// Helpers for installing and uninstalling stack trace handlers.
var installations = [];
function register(callback) {
if (typeof callback !== "function") {
var options = callback;
callback = function(error, frames) {
return new BetterStackTrace(error, frames, options).toString();
};
}
if (Error.prepareStackTrace) {
installations.push(Error.prepareStackTrace)
}
Error.prepareStackTrace = callback;
}
function unregister() {
if (Error.prepareStackTrace) {
delete Error.prepareStackTrace;
}
if (installations.length) {
Error.prepareStackTrace = installations.pop();
}
}
// Export for browser and node.
var exp = typeof exports === "undefined" ? (this.BetterStackTraces = {}) : exports;
exp.register = register;
exp.unregister = unregister;
exp.install = register; // deprecated
exp.uninstall = unregister; // deprecated
exp.BetterStackTrace = BetterStackTrace;
}).call(this);