Debian Codegraph @

packages/babel-generator/src/source-map.ts

raw symbols SCIP
1 import {
2 GenMapping,
3 maybeAddMapping,
4 setSourceContent,
5 allMappings,
6 toEncodedMap,
7 toDecodedMap,
8 } from "@jridgewell/gen-mapping";
9
10 import type {
11 EncodedSourceMap,
12 DecodedSourceMap,
13 Mapping,
14 } from "@jridgewell/gen-mapping";
15
16 /**
17 * Build a sourcemap.
18 */
19
20 export default class SourceMap {
21 private _map: GenMapping;
22 private _rawMappings: Mapping[] | undefined;
23 private _sourceFileName: string | undefined;
24
25 // Any real line is > 0, so init to 0 is fine.
26 private _lastGenLine = 0;
27 private _lastSourceLine = 0;
28
29 // Source columns can be 0, but we ony check in unison with sourceLine, which
30 // inits to an impossible value. So init to 0 is fine.
31 private _lastSourceColumn = 0;
32
33 constructor(
34 opts: { sourceFileName?: string; sourceRoot?: string },
35 code: string | { [sourceFileName: string]: string },
36 ) {
37 const map = (this._map = new GenMapping({ sourceRoot: opts.sourceRoot }));
38 this._sourceFileName = opts.sourceFileName?.replace(/\\/g, "/");
39 this._rawMappings = undefined;
40
41 if (typeof code === "string") {
42 setSourceContent(map, this._sourceFileName, code);
43 } else if (typeof code === "object") {
44 Object.keys(code).forEach(sourceFileName => {
45 setSourceContent(
46 map,
47 sourceFileName.replace(/\\/g, "/"),
48 code[sourceFileName],
49 );
50 });
51 }
52 }
53
54 /**
55 * Get the sourcemap.
56 */
57 get(): EncodedSourceMap {
58 return toEncodedMap(this._map);
59 }
60
61 getDecoded(): DecodedSourceMap {
62 return toDecodedMap(this._map);
63 }
64
65 getRawMappings(): Mapping[] {
66 return (this._rawMappings ||= allMappings(this._map));
67 }
68
69 /**
70 * Mark the current generated position with a source position. May also be passed null line/column
71 * values to insert a mapping to nothing.
72 */
73
74 mark(
75 generated: { line: number; column: number },
76 line: number,
77 column: number,
78 identifierName?: string | null,
79 filename?: string | null,
80 ) {
81 this._rawMappings = undefined;
82
83 maybeAddMapping(this._map, {
84 name: identifierName,
85 generated,
86 source:
87 line == null
88 ? undefined
89 : filename?.replace(/\\/g, "/") || this._sourceFileName,
90 original:
91 line == null
92 ? undefined
93 : {
94 line: line,
95 column: column,
96 },
97 });
98 }
99 }