/
source-map.ts
119 lines (103 loc) 路 2.92 KB
/
source-map.ts
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
import {
GenMapping,
addMapping,
setSourceContent,
allMappings,
encodedMap,
decodedMap,
} from "@jridgewell/gen-mapping";
import type {
EncodedSourceMap,
DecodedSourceMap,
Mapping,
} from "@jridgewell/gen-mapping";
/**
* Build a sourcemap.
*/
export default class SourceMap {
private _map: GenMapping;
private _rawMappings: Mapping[] | undefined;
private _sourceFileName: string | undefined;
// Any real line is > 0, so init to 0 is fine.
private _lastGenLine = 0;
private _lastSourceLine = 0;
// Source columns can be 0, but we ony check in unison with sourceLine, which
// inits to an impossible value. So init to 0 is fine.
private _lastSourceColumn = 0;
constructor(
opts: { sourceFileName?: string; sourceRoot?: string },
code: string | { [sourceFileName: string]: string },
) {
const map = (this._map = new GenMapping({ sourceRoot: opts.sourceRoot }));
this._sourceFileName = opts.sourceFileName?.replace(/\\/g, "/");
this._rawMappings = undefined;
if (typeof code === "string") {
setSourceContent(map, this._sourceFileName, code);
} else if (typeof code === "object") {
Object.keys(code).forEach(sourceFileName => {
setSourceContent(
map,
sourceFileName.replace(/\\/g, "/"),
code[sourceFileName],
);
});
}
}
/**
* Get the sourcemap.
*/
get(): EncodedSourceMap {
return encodedMap(this._map);
}
getDecoded(): DecodedSourceMap {
return decodedMap(this._map);
}
getRawMappings(): Mapping[] {
return (this._rawMappings ||= allMappings(this._map));
}
/**
* Mark the current generated position with a source position. May also be passed null line/column
* values to insert a mapping to nothing.
*/
mark(
generated: { line: number; column: number },
line: number,
column: number,
identifierName?: string | null,
filename?: string | null,
force?: boolean,
) {
const generatedLine = generated.line;
// Adding an empty mapping at the start of a generated line just clutters the map.
if (this._lastGenLine !== generatedLine && line === null) return;
// If this mapping points to the same source location as the last one, we can ignore it since
// the previous one covers it.
if (
!force &&
this._lastGenLine === generatedLine &&
this._lastSourceLine === line &&
this._lastSourceColumn === column
) {
return;
}
this._rawMappings = undefined;
this._lastGenLine = generatedLine;
this._lastSourceLine = line;
this._lastSourceColumn = column;
addMapping(this._map, {
name: identifierName,
generated,
source:
line == null
? undefined
: filename?.replace(/\\/g, "/") || this._sourceFileName,
original:
line == null
? undefined
: {
line: line,
column: column,
},
});
}
}