Completed
Push — master ( d71171...8b8f67 )
by Vitaly
24s
created

stacktracey.js (3 issues)

1
"use strict";
2
3
/*  ------------------------------------------------------------------------ */
4
5
const O            = Object,
0 ignored issues
show
Comprehensibility Best Practice introduced by
You seem to be aliasing the built-in name Object as O. This makes your code very difficult to follow, consider using the built-in name directly.
Loading history...
6
      isBrowser    = (typeof window !== 'undefined') && (window.window === window) && window.navigator,
7
      lastOf       = x => x[x.length - 1],
8
      getSource    = require ('get-source'),
9
      partition    = require ('./impl/partition'),
10
      asTable      = require ('as-table'),
11
      nixSlashes   = x => x.replace (/\\/g, '/'),
12
      pathRoot     = isBrowser ? window.location.href : (nixSlashes (process.cwd ()) + '/')
13
14
/*  ------------------------------------------------------------------------ */
15
16
class StackTracey extends Array {
17
18
    constructor (input, offset) {
19
        
20
        const originalInput          = input
21
            , isParseableSyntaxError = input && (input instanceof SyntaxError && !isBrowser)
22
        
23
        super ()
24
25
    /*  Fixes for Safari    */
26
27
        this.constructor = StackTracey
28
        this.__proto__   = StackTracey.prototype
29
30
    /*  new StackTracey ()            */
31
32
        if (!input) {
33
             input = new Error ()
34
             offset = (offset === undefined) ? 1 : offset
35
        }
36
37
    /*  new StackTracey (Error)      */
38
39
        if (input instanceof Error) {
40
            input = input[StackTracey.stack] || input.stack || ''
41
        }
42
43
    /*  new StackTracey (string)     */
44
45
        if (typeof input === 'string') {
46
            input = StackTracey.rawParse (input).slice (offset).map (StackTracey.extractEntryMetadata)
47
        }
48
49
    /*  new StackTracey (array)      */
50
51
        if (Array.isArray (input)) {
52
53
            if (isParseableSyntaxError) {
54
                
55
                const rawLines = module.require ('util').inspect (originalInput).split ('\n')
56
                    , fileLine = rawLines[0].match (/^([^:]+):(.+)/)
57
58
                if (fileLine) {
59
                    input.unshift ({
60
                        file: nixSlashes (fileLine[1]),
61
                        line: fileLine[2],
62
                        column: (rawLines[2] || '').indexOf ('^') + 1,
63
                        sourceLine: rawLines[1],
64
                        callee: '(syntax error)',
65
                        syntaxError: true
66
                    })
67
                }
68
            }
69
70
            this.length = input.length
71
            input.forEach ((x, i) => this[i] = x)
72
        }
73
    }
74
75
    static extractEntryMetadata (e) {
76
        
77
        const fileRelative = StackTracey.relativePath (e.file || '')
78
79
        return O.assign (e, {
80
81
            calleeShort:  e.calleeShort || lastOf ((e.callee || '').split ('.')),
82
            fileRelative: fileRelative,
83
            fileShort:    StackTracey.shortenPath (fileRelative),
84
            fileName:     lastOf ((e.file || '').split ('/')),
85
            thirdParty:   StackTracey.isThirdParty (fileRelative) && !e.index
86
        })
87
    }
88
89
    static shortenPath (relativePath) {
90
        return relativePath.replace (/^node_modules\//, '')
91
                           .replace (/^webpack\/bootstrap\//, '')
92
    }
93
94
    static relativePath (fullPath) {
95
        return fullPath.replace (pathRoot, '')
96
                       .replace (/^.*\:\/\/?\/?/, '')
97
    }
98
99
    static isThirdParty (relativePath) {
100
        return (relativePath[0] === '~')                          || // webpack-specific heuristic
101
               (relativePath[0] === '/')                          || // external source
102
               (relativePath.indexOf ('node_modules')      === 0) ||
103
               (relativePath.indexOf ('webpack/bootstrap') === 0)
104
    }
105
106
    static rawParse (str) {
107
108
        const lines = (str || '').split ('\n')
109
110
        const entries = lines.map (line => { line = line.trim ()
111
112
            var callee, fileLineColumn = [], native, planA, planB
0 ignored issues
show
The assignment to variable fileLineColumn seems to be never used. Consider removing it.
Loading history...
113
114
            if ((planA = line.match (/at (.+) \((.+)\)/)) ||
115
                (planA = line.match (/(.*)@(.*)/))) {
116
117
                callee         =  planA[1]
118
                native         = (planA[2] === 'native')
119
                fileLineColumn = (planA[2].match (/(.*):(.+):(.+)/) || []).slice (1) }
120
121
            else if ((planB = line.match (/^(at\s+)*(.+):([0-9]+):([0-9]+)/) )) {
122
                fileLineColumn = (planB).slice (2) }
123
124
            else {
125
                return undefined }
126
127
        /*  Detect things like Array.reduce
128
            TODO: detect more built-in types            */
129
            
130
            if (callee && !fileLineColumn[0]) {
131
                const type = callee.split ('.')[0]
132
                if (type === 'Array') {
133
                    native = true
134
                }
135
            }
136
137
            return {
138
                beforeParse: line,
139
                callee:      callee || '',
140
                index:       isBrowser && (fileLineColumn[0] === window.location.href),
141
                native:      native || false,
142
                file:        nixSlashes (fileLineColumn[0] || ''),
143
                line:        parseInt (fileLineColumn[1] || '', 10) || undefined,
144
                column:      parseInt (fileLineColumn[2] || '', 10) || undefined } })
145
146
        return entries.filter (x => (x !== undefined))
147
    }
148
149
    withSource (i) {
150
        return this[i] && StackTracey.withSource (this[i])
151
    }
152
153
    static withSource (loc) {
154
155
        if (loc.sourceFile || (loc.file && loc.file.indexOf ('<') >= 0)) { // skip things like <anonymous> and stuff that was already fetched
156
            return loc
157
            
158
        } else {
159
            let resolved = getSource (loc.file || '').resolve (loc)
160
161
            if (resolved.sourceFile) {
162
                resolved.file = resolved.sourceFile.path
163
                resolved = StackTracey.extractEntryMetadata (resolved)
164
            }
165
166
            if (resolved.sourceLine && resolved.sourceLine.includes ('// @hide')) {
167
                resolved.sourceLine  = resolved.sourceLine.replace  ('// @hide', '')
168
                resolved.hide = true
169
            }
170
171
            return O.assign ({ sourceLine: '' }, loc, resolved)
172
        }
173
    }
174
175
    get withSources () {
176
        return new StackTracey (this.map (StackTracey.withSource))
177
    }
178
179
    get mergeRepeatedLines () {
180
        return new StackTracey (
181
            partition (this, e => e.file + e.line).map (
182
                group => {
183
                    return group.items.slice (1).reduce ((memo, entry) => {
184
                        memo.callee      = (memo.callee      || '<anonymous>') + ' → ' + (entry.callee      || '<anonymous>')
185
                        memo.calleeShort = (memo.calleeShort || '<anonymous>') + ' → ' + (entry.calleeShort || '<anonymous>')
186
                        return memo }, O.assign ({}, group.items[0])) }))
187
    }
188
189
    get clean () {
190
        return this.withSources.mergeRepeatedLines.filter ((e, i) => (i === 0) || !(e.thirdParty || e.hide || e.native))
191
    }
192
193
    at (i) {
194
        return O.assign ({
195
196
            beforeParse: '',
197
            callee:      '<???>',
198
            index:       false,
199
            native:      false,
200
            file:        '<???>',
201
            line:        0,
202
            column:      0
203
204
        }, this[i])
205
    }
206
207
    static locationsEqual (a, b) {
208
        return (a.file   === b.file) &&
209
               (a.line   === b.line) &&
210
               (a.column === b.column)
211
    }
212
213
    get pretty () {
214
215
        const trimEnd   = (s, n) => (s.length > n) ? (s.slice (0, n-1) + '…') : s        
216
        const trimStart = (s, n) => (s.length > n) ? ('…' + s.slice (-(n-1))) : s
217
218
        return asTable (this.withSources.map (
219
                            e => [
220
                                ('at ' + trimEnd (e.calleeShort, 30)),
221
                                trimStart ((e.fileShort && (e.fileShort + ':' + e.line)) || '', 40),
222
                                trimEnd (((e.sourceLine || '').trim () || ''), 80)
223
                            ]))
224
    }
225
226
    static resetCache () {
227
228
        getSource.resetCache ()
229
    }
230
}
231
232
/*  Chaining helper for .isThirdParty
233
    ------------------------------------------------------------------------ */
234
235
(() => {
236
237
    const methods = {
238
239
        include (pred) {
240
241
            const f = StackTracey.isThirdParty
242
            O.assign (StackTracey.isThirdParty = (path => f (path) ||  pred (path)), methods)
243
        },
244
245
        except (pred) {
246
247
            const f = StackTracey.isThirdParty
248
            O.assign (StackTracey.isThirdParty = (path => f (path) && !pred (path)), methods)
249
        },
250
    }
251
252
    O.assign (StackTracey.isThirdParty, methods)
253
254
}) ()
255
256
/*  Array methods
257
    ------------------------------------------------------------------------ */
258
259
;['map', 'filter', 'slice', 'concat', 'reverse'].forEach (name => {
260
261
    StackTracey.prototype[name] = function (/*...args */) { // no support for ...args in Node v4 :(
262
        
263
        const arr = Array.from (this)
264
        return new StackTracey (arr[name].apply (arr, arguments))
265
    }
266
})
267
268
/*  A private field that an Error instance can expose
269
    ------------------------------------------------------------------------ */
270
271
StackTracey.stack = /* istanbul ignore next */ (typeof Symbol !== 'undefined') ? Symbol.for ('StackTracey') : '__StackTracey'
0 ignored issues
show
The variable Symbol seems to be never declared. If this is a global, consider adding a /** global: Symbol */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
272
273
/*  ------------------------------------------------------------------------ */
274
275
module.exports = StackTracey
276
277
/*  ------------------------------------------------------------------------ */
278
279