forked from demerzel3/karma-sourcemap-loader
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
94 lines (77 loc) · 2.62 KB
/
index.js
File metadata and controls
94 lines (77 loc) · 2.62 KB
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
var fs = require('graceful-fs');
var path = require('path');
var sourcemapUrlRegeExp = /^\/\/#\s*sourceMappingURL=/;
var createSourceMapLocatorPreprocessor = function(args, logger, config) {
var log = logger.create('preprocessor.sourcemap');
var charsetRegex = /^;charset=([^;]+);/;
return function(content, file, done) {
function resolveLocalPath(path) {
return path
.replace(/webpack:\/\//, process.cwd())
.replace(/\?[^:]*/, '');
}
function sourceMapData(data){
file.sourceMap = JSON.parse(data);
if (config && config.useLocalPaths) {
file.sourceMap.sources = file.sourceMap.sources.map(function (path) {
return resolveLocalPath(path);
});
}
done(content);
}
function inlineMap(inlineData){
var charset = 'utf-8';
if (charsetRegex.test(inlineData)) {
var matches = inlineData.match(charsetRegex);
if (matches.length === 2) {
charset = matches[1];
inlineData = inlineData.slice(matches[0].length -1);
}
}
if (/^;base64,/.test(inlineData)) {
// base64-encoded JSON string
log.debug('base64-encoded source map for', file.originalPath);
var buffer = new Buffer(inlineData.slice(';base64,'.length), 'base64');
sourceMapData(buffer.toString(charset));
} else {
// straight-up URL-encoded JSON string
log.debug('raw inline source map for', file.originalPath);
sourceMapData(decodeURIComponent(inlineData));
}
}
function fileMap(mapPath){
fs.exists(mapPath, function(exists) {
if (!exists) {
done(content);
return;
}
fs.readFile(mapPath, function(err, data) {
if (err){ throw err; }
log.debug('external source map exists for', file.originalPath);
sourceMapData(data);
});
});
}
var lines = content.split(/\n/);
var lastLine = lines.pop();
while (/^\s*$/.test(lastLine)) {
lastLine = lines.pop();
}
var mapUrl;
if (sourcemapUrlRegeExp.test(lastLine)) {
mapUrl = lastLine.replace(sourcemapUrlRegeExp, '');
}
if (!mapUrl) {
fileMap(file.path + ".map");
} else if (/^data:application\/json/.test(mapUrl)) {
inlineMap(mapUrl.slice('data:application/json'.length));
} else {
fileMap(path.resolve(path.dirname(file.path), mapUrl));
}
};
};
createSourceMapLocatorPreprocessor.$inject = ['args', 'logger', 'config.sourcemap'];
// PUBLISH DI MODULE
module.exports = {
'preprocessor:sourcemap': ['factory', createSourceMapLocatorPreprocessor]
};