1
|
/*
|
2
|
MIT License http://www.opensource.org/licenses/mit-license.php
|
3
|
Author Tobias Koppers @sokra
|
4
|
*/
|
5
|
"use strict";
|
6
|
|
7
|
var Source = require("./Source");
|
8
|
var SourceNode = require("source-map").SourceNode;
|
9
|
|
10
|
var REPLACE_REGEX = /\n(?=.|\s)/g;
|
11
|
|
12
|
function cloneAndPrefix(node, prefix, append) {
|
13
|
if(typeof node === "string") {
|
14
|
var result = node.replace(REPLACE_REGEX, "\n" + prefix);
|
15
|
if(append.length > 0) result = append.pop() + result;
|
16
|
if(/\n$/.test(node)) append.push(prefix);
|
17
|
return result;
|
18
|
} else {
|
19
|
var newNode = new SourceNode(
|
20
|
node.line,
|
21
|
node.column,
|
22
|
node.source,
|
23
|
node.children.map(function(node) {
|
24
|
return cloneAndPrefix(node, prefix, append);
|
25
|
}),
|
26
|
node.name
|
27
|
);
|
28
|
newNode.sourceContents = node.sourceContents;
|
29
|
return newNode;
|
30
|
}
|
31
|
};
|
32
|
|
33
|
class PrefixSource extends Source {
|
34
|
constructor(prefix, source) {
|
35
|
super();
|
36
|
this._source = source;
|
37
|
this._prefix = prefix;
|
38
|
}
|
39
|
|
40
|
source() {
|
41
|
var node = typeof this._source === "string" ? this._source : this._source.source();
|
42
|
var prefix = this._prefix;
|
43
|
return prefix + node.replace(REPLACE_REGEX, "\n" + prefix);
|
44
|
}
|
45
|
|
46
|
node(options) {
|
47
|
var node = this._source.node(options);
|
48
|
var prefix = this._prefix;
|
49
|
var output = [];
|
50
|
var result = new SourceNode();
|
51
|
node.walkSourceContents(function(source, content) {
|
52
|
result.setSourceContent(source, content);
|
53
|
});
|
54
|
var needPrefix = true;
|
55
|
node.walk(function(chunk, mapping) {
|
56
|
var parts = chunk.split(/(\n)/);
|
57
|
for(var i = 0; i < parts.length; i += 2) {
|
58
|
var nl = i + 1 < parts.length;
|
59
|
var part = parts[i] + (nl ? "\n" : "");
|
60
|
if(part) {
|
61
|
if(needPrefix) {
|
62
|
output.push(prefix);
|
63
|
}
|
64
|
output.push(new SourceNode(mapping.line, mapping.column, mapping.source, part, mapping.name));
|
65
|
needPrefix = nl;
|
66
|
}
|
67
|
}
|
68
|
});
|
69
|
result.add(output);
|
70
|
return result;
|
71
|
}
|
72
|
|
73
|
listMap(options) {
|
74
|
var prefix = this._prefix;
|
75
|
var map = this._source.listMap(options);
|
76
|
return map.mapGeneratedCode(function(code) {
|
77
|
return prefix + code.replace(REPLACE_REGEX, "\n" + prefix);
|
78
|
});
|
79
|
}
|
80
|
|
81
|
updateHash(hash) {
|
82
|
if(typeof this._source === "string")
|
83
|
hash.update(this._source);
|
84
|
else
|
85
|
this._source.updateHash(hash);
|
86
|
if(typeof this._prefix === "string")
|
87
|
hash.update(this._prefix);
|
88
|
else
|
89
|
this._prefix.updateHash(hash);
|
90
|
}
|
91
|
}
|
92
|
|
93
|
require("./SourceAndMapMixin")(PrefixSource.prototype);
|
94
|
|
95
|
module.exports = PrefixSource;
|