UNPKG

2.83 kBJavaScriptView Raw
1/**
2 * @file source-map.js
3 * @author clark-t (clarktanglei@163.com)
4 */
5
6const sourceMap = require('source-map')
7const splitRE = /\r?\n/g
8const emptyRE = /^(?:\/\/)?\s*$/
9// const MagicString = require('magic-string')
10
11module.exports = {
12 // copy from [uglify-loader](https://github.com/bestander/uglify-loader/blob/master/index.js)
13 // and modify to async function
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}