forked from xpl/stacktracey
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stacktracey.js
309 lines (225 loc) · 10.1 KB
/
stacktracey.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
"use strict";
/* ------------------------------------------------------------------------ */
const O = Object,
isBrowser = (typeof window !== 'undefined') && (window.window === window) && window.navigator,
lastOf = x => x[x.length - 1],
getSource = require ('get-source'),
partition = require ('./impl/partition'),
asTable = require ('as-table'),
nixSlashes = x => x.replace (/\\/g, '/'),
pathRoot = isBrowser ? window.location.href : (nixSlashes (process.cwd ()) + '/'),
pathToRelative = isBrowser ? ((root, full) => full.replace (root, '')) : module.require ('path').relative
/* ------------------------------------------------------------------------ */
class StackTracey extends Array {
constructor (input, offset) {
const originalInput = input
, isParseableSyntaxError = input && (input instanceof SyntaxError && !isBrowser)
super ()
/* Fixes for Safari */
this.constructor = StackTracey
this.__proto__ = StackTracey.prototype
/* new StackTracey () */
if (!input) {
input = new Error ()
offset = (offset === undefined) ? 1 : offset
}
/* new StackTracey (Error) */
if (input instanceof Error) {
input = input[StackTracey.stack] || input.stack || ''
}
/* new StackTracey (string) */
if (typeof input === 'string') {
input = StackTracey.rawParse (input).slice (offset).map (StackTracey.extractEntryMetadata)
}
/* new StackTracey (array) */
if (Array.isArray (input)) {
if (isParseableSyntaxError) {
const rawLines = module.require ('util').inspect (originalInput).split ('\n')
, fileLine = rawLines[0].split (':')
, line = fileLine.pop ()
, file = fileLine.join (':')
if (file) {
input.unshift ({
file: nixSlashes (file),
line: line,
column: (rawLines[2] || '').indexOf ('^') + 1,
sourceLine: rawLines[1],
callee: '(syntax error)',
syntaxError: true
})
}
}
this.length = input.length
input.forEach ((x, i) => this[i] = x)
}
}
static extractEntryMetadata (e) {
const fileRelative = StackTracey.relativePath (e.file || '')
return O.assign (e, {
calleeShort: e.calleeShort || lastOf ((e.callee || '').split ('.')),
fileRelative: fileRelative,
fileShort: StackTracey.shortenPath (fileRelative),
fileName: lastOf ((e.file || '').split ('/')),
thirdParty: StackTracey.isThirdParty (fileRelative) && !e.index
})
}
static shortenPath (relativePath) {
return relativePath.replace (/^node_modules\//, '')
.replace (/^webpack\/bootstrap\//, '')
}
static relativePath (fullPath) {
return nixSlashes (pathToRelative (pathRoot, fullPath)).replace (/^.*\:\/\/?\/?/, '')
}
static isThirdParty (relativePath) {
return (relativePath[0] === '~') || // webpack-specific heuristic
(relativePath[0] === '/') || // external source
(relativePath.indexOf ('node_modules') === 0) ||
(relativePath.indexOf ('webpack/bootstrap') === 0)
}
static rawParse (str) {
const lines = (str || '').split ('\n')
const entries = lines.map (line => {
line = line.trim ()
let callee, fileLineColumn = [], native, planA, planB
if ((planA = line.match (/at (.+) \((.+)\)/)) ||
((line.slice (0, 3) !== 'at ') && (planA = line.match (/(.*)@(.*)/)))) {
callee = planA[1]
native = (planA[2] === 'native')
fileLineColumn = (planA[2].match (/(.*):(.+):(.+)/) || []).slice (1)
} else if ((planB = line.match (/^(at\s+)*(.+):([0-9]+):([0-9]+)/) )) {
fileLineColumn = (planB).slice (2)
} else {
return undefined
}
/* Detect things like Array.reduce
TODO: detect more built-in types */
if (callee && !fileLineColumn[0]) {
const type = callee.split ('.')[0]
if (type === 'Array') {
native = true
}
}
return {
beforeParse: line,
callee: callee || '',
index: isBrowser && (fileLineColumn[0] === window.location.href),
native: native || false,
file: nixSlashes (fileLineColumn[0] || ''),
line: parseInt (fileLineColumn[1] || '', 10) || undefined,
column: parseInt (fileLineColumn[2] || '', 10) || undefined
}
})
return entries.filter (x => (x !== undefined))
}
withSource (i) {
return this[i] && StackTracey.withSource (this[i])
}
static withSource (loc) {
if (loc.sourceFile || (loc.file && loc.file.indexOf ('<') >= 0)) { // skip things like <anonymous> and stuff that was already fetched
return loc
} else {
let resolved = getSource (loc.file || '').resolve (loc)
if (!resolved.sourceFile) {
return loc
}
if (!resolved.sourceFile.error) {
resolved.file = nixSlashes (resolved.sourceFile.path)
resolved = StackTracey.extractEntryMetadata (resolved)
}
if (!resolved.sourceLine.error) {
if (resolved.sourceLine.includes ('// @hide')) {
resolved.sourceLine = resolved.sourceLine.replace ('// @hide', '')
resolved.hide = true
}
if (resolved.sourceLine.includes ('__webpack_require__') || // webpack-specific heuristics
resolved.sourceLine.includes ('/******/ ({')) {
resolved.thirdParty = true
}
}
return O.assign ({ sourceLine: '' }, loc, resolved)
}
}
get withSources () {
return new StackTracey (this.map (StackTracey.withSource))
}
get mergeRepeatedLines () {
return new StackTracey (
partition (this, e => e.file + e.line).map (
group => {
return group.items.slice (1).reduce ((memo, entry) => {
memo.callee = (memo.callee || '<anonymous>') + ' → ' + (entry.callee || '<anonymous>')
memo.calleeShort = (memo.calleeShort || '<anonymous>') + ' → ' + (entry.calleeShort || '<anonymous>')
return memo }, O.assign ({}, group.items[0]))
}
)
)
}
get clean () {
return this.withSources.mergeRepeatedLines.filter ((e, i) => (i === 0) || !(e.thirdParty || e.hide || e.native))
}
at (i) {
return O.assign ({
beforeParse: '',
callee: '<???>',
index: false,
native: false,
file: '<???>',
line: 0,
column: 0
}, this[i])
}
static locationsEqual (a, b) {
return (a.file === b.file) &&
(a.line === b.line) &&
(a.column === b.column)
}
get pretty () {
const trimEnd = (s, n) => s && ((s.length > n) ? (s.slice (0, n-1) + '…') : s)
const trimStart = (s, n) => s && ((s.length > n) ? ('…' + s.slice (-(n-1))) : s)
return asTable (this.withSources.map (
e => [
('at ' + trimEnd (e.calleeShort, StackTracey.maxColumnWidths.callee)),
trimStart ((e.fileShort && (e.fileShort + ':' + e.line)) || '', StackTracey.maxColumnWidths.file),
trimEnd (((e.sourceLine || '').trim () || ''), StackTracey.maxColumnWidths.sourceLine)
]))
}
static resetCache () {
getSource.resetCache ()
}
}
/* Some default configuration options
------------------------------------------------------------------------ */
StackTracey.maxColumnWidths = {
callee: 30,
file: 60,
sourceLine: 80
}
/* Chaining helper for .isThirdParty
------------------------------------------------------------------------ */
;(() => {
const methods = {
include (pred) {
const f = StackTracey.isThirdParty
O.assign (StackTracey.isThirdParty = (path => f (path) || pred (path)), methods)
},
except (pred) {
const f = StackTracey.isThirdParty
O.assign (StackTracey.isThirdParty = (path => f (path) && !pred (path)), methods)
},
}
O.assign (StackTracey.isThirdParty, methods)
}) ()
/* Array methods
------------------------------------------------------------------------ */
;['map', 'filter', 'slice', 'concat', 'reverse'].forEach (name => {
StackTracey.prototype[name] = function (/*...args */) { // no support for ...args in Node v4 :(
const arr = Array.from (this)
return new StackTracey (arr[name].apply (arr, arguments))
}
})
/* A private field that an Error instance can expose
------------------------------------------------------------------------ */
StackTracey.stack = /* istanbul ignore next */ (typeof Symbol !== 'undefined') ? Symbol.for ('StackTracey') : '__StackTracey'
/* ------------------------------------------------------------------------ */
module.exports = StackTracey
/* ------------------------------------------------------------------------ */