-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
77 lines (63 loc) · 2.2 KB
/
index.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
'use strict'
var fs = require('fs')
var path = require('path')
var SourceMapConsumer = require('source-map').SourceMapConsumer
var INLINE_SOURCEMAP_REGEX = /^data:application\/json[^,]+base64,/
var SOURCEMAP_REGEX = /(?:\/\/[@#][ \t]+sourceMappingURL=([^\s'"]+?)[ \t]*$)|(?:\/\*[@#][ \t]+sourceMappingURL=([^*]+?)[ \t]*(?:\*\/)[ \t]*$)/
var READ_FILE_OPTS = { encoding: 'utf8' }
module.exports = function readSourceMap (filename, cb) {
fs.readFile(filename, READ_FILE_OPTS, function (err, sourceFile) {
if (err) {
return cb(err)
}
// Look for a sourcemap URL
var sourceMapUrl = resolveSourceMapUrl(sourceFile, path.dirname(filename))
if (!sourceMapUrl) {
return cb()
}
// If it's an inline map, decode it and pass it through the same consumer factory
if (isInlineMap(sourceMapUrl)) {
return onMapRead(null, decodeInlineMap(sourceMapUrl))
}
// Load actual source map from given path
fs.readFile(sourceMapUrl, READ_FILE_OPTS, onMapRead)
function onMapRead (readErr, sourceMap) {
if (readErr) {
readErr.message = 'Error reading sourcemap for file "' + filename + '":\n' + readErr.message
return cb(readErr)
}
try {
(new SourceMapConsumer(sourceMap))
.then(function onConsumerReady (consumer) {
return cb(null, consumer)
}, onConsumerError)
} catch (parseErr) {
onConsumerError(parseErr)
}
}
function onConsumerError (parseErr) {
parseErr.message = 'Error parsing sourcemap for file "' + filename + '":\n' + parseErr.message
return cb(parseErr)
}
})
}
function resolveSourceMapUrl (sourceFile, sourcePath) {
var lines = sourceFile.split(/\r?\n/)
var sourceMapUrl = null
for (var i = lines.length - 1; i >= 0 && !sourceMapUrl; i--) {
sourceMapUrl = lines[i].match(SOURCEMAP_REGEX)
}
if (!sourceMapUrl) {
return null
}
return isInlineMap(sourceMapUrl[1])
? sourceMapUrl[1]
: path.resolve(sourcePath, sourceMapUrl[1])
}
function isInlineMap (url) {
return INLINE_SOURCEMAP_REGEX.test(url)
}
function decodeInlineMap (data) {
var rawData = data.slice(data.indexOf(',') + 1)
return Buffer.from(rawData, 'base64').toString()
}