1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 | const sourceMap = require('source-map')
|
7 | const splitRE = /\r?\n/g
|
8 | const emptyRE = /^(?:\/\/)?\s*$/
|
9 |
|
10 |
|
11 | module.exports = {
|
12 |
|
13 |
|
14 |
|
15 | async merge (map, inputMap) {
|
16 | let inputMapConsumer = await new sourceMap.SourceMapConsumer(inputMap)
|
17 | let outputMapConsumer = await new sourceMap.SourceMapConsumer(map)
|
18 |
|
19 | let mergedGenerator = new sourceMap.SourceMapGenerator({
|
20 | file: inputMapConsumer.file,
|
21 | sourceRoot: inputMapConsumer.sourceRoot
|
22 | })
|
23 |
|
24 | var source = outputMapConsumer.sources[0]
|
25 |
|
26 | inputMapConsumer.eachMapping(function (mapping) {
|
27 | let generatedPosition = outputMapConsumer.generatedPositionFor({
|
28 | line: mapping.generatedLine,
|
29 | column: mapping.generatedColumn,
|
30 | source: source
|
31 | })
|
32 |
|
33 | if (generatedPosition.column != null && mapping.originalLine != null && mapping.originalColumn != null) {
|
34 | mergedGenerator.addMapping({
|
35 | source: mapping.source,
|
36 |
|
37 | original: mapping.source == null ? null : {
|
38 | line: mapping.originalLine,
|
39 | column: mapping.originalColumn
|
40 | },
|
41 |
|
42 | generated: generatedPosition
|
43 | })
|
44 | }
|
45 | })
|
46 |
|
47 | var mergedMap = mergedGenerator.toJSON()
|
48 | inputMap.mappings = mergedMap.mappings
|
49 | return inputMap
|
50 | },
|
51 |
|
52 | async prepend (prefix, source, {map, file, sourceRoot}) {
|
53 | if (map) {
|
54 | let consumer = await new sourceMap.SourceMapConsumer(map)
|
55 | let node = sourceMap.SourceNode.fromStringWithSourceMap(source, consumer)
|
56 | node.prepend(prefix)
|
57 | let result = node.toStringWithSourceMap()
|
58 | return {
|
59 | code: result.code,
|
60 | map: result.map.toJSON()
|
61 | }
|
62 | }
|
63 |
|
64 | let generator = new sourceMap.SourceMapGenerator({
|
65 | file,
|
66 | sourceRoot
|
67 | })
|
68 |
|
69 | generator.setSourceContent(file, source)
|
70 | let output = prefix + '\n' + source
|
71 |
|
72 | let prefixLen = prefix.split(splitRE).length
|
73 | output.split(splitRE).forEach((line, index) => {
|
74 | if (emptyRE.test(line)) {
|
75 | return
|
76 | }
|
77 |
|
78 | if (index < prefixLen) {
|
79 | generator.addMapping({
|
80 | source: file,
|
81 | original: {
|
82 | line: 1,
|
83 | column: 0
|
84 | },
|
85 | generated: {
|
86 | line: 1,
|
87 | column: index + 1
|
88 | }
|
89 | })
|
90 | } else {
|
91 | generator.addMapping({
|
92 | source: file,
|
93 | original: {
|
94 | line: index + 1 - prefixLen,
|
95 | column: 0
|
96 | },
|
97 | generated: {
|
98 | line: index + 1,
|
99 | column: 0
|
100 | }
|
101 | })
|
102 | }
|
103 | })
|
104 |
|
105 | return {
|
106 | code: output,
|
107 | map: generator.toJSON()
|
108 | }
|
109 | }
|
110 | }
|