-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
68 lines (62 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
var
SourceMapConsumer = require( "source-map" ).SourceMapConsumer,
SourceMapGenerator = require( "source-map" ).SourceMapGenerator,
fs = require( "fs" ),
writeFileSync = fs.writeFileSync,
readFileSync = fs.readFileSync,
path = require('path');
function replace(inMap, outFile, searchString, replaceString)
{
var mapping = JSON.parse( readFileSync(inMap) );
var generator = new SourceMapGenerator({
file: outFile
});
var map = new SourceMapConsumer( mapping );
var pos;
var replacements = [];
var src = readFileSync(map.file, 'utf-8');
var lineNum = 0;
var filePos = 0;
src.split('\n').forEach(function(line) {
lineNum++;
var searchPos = 0;
while ((pos = line.indexOf(searchString, searchPos)) != -1) {
src = src.substring(0, filePos+pos) + replaceString + src.substring(filePos+pos+searchString.length);
line = line.substring(0, pos) + replaceString + line.substring(pos+searchString.length);
replacements.push({
line: lineNum,
column: pos
});
searchPos = pos + replaceString.length;
}
filePos += line.length + 1;
});
console.log(replacements);
map.eachMapping(function(mapping) {
replacements.reverse().forEach(function(r) {
if (r.line == mapping.generatedLine && mapping.generatedColumn > r.column) {
var offs = searchString.length - replaceString.length;
mapping.generatedColumn -= offs;
}
});
if (mapping.source) {
var newMapping = {
generated: {
line: mapping.generatedLine,
column: mapping.generatedColumn
},
original: {
line: mapping.originalLine,
column: mapping.originalColumn
},
source: mapping.source
};
return generator.addMapping(newMapping);
} else {
return mapping;
}
});
writeFileSync(outFile, src, 'utf-8');
return writeFileSync(outFile+".map", generator.toString(), 'utf-8');
}
module.exports = replace;