/
trace-mapping.ts
376 lines (324 loc) · 11 KB
/
trace-mapping.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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
import { encode, decode } from '@jridgewell/sourcemap-codec';
import resolve from './resolve';
import stripFilename from './strip-filename';
import maybeSort from './sort';
import buildBySources from './by-source';
import {
memoizedState,
memoizedBinarySearch,
upperBound,
lowerBound,
found as bsFound,
} from './binary-search';
import {
SOURCES_INDEX,
SOURCE_LINE,
SOURCE_COLUMN,
NAMES_INDEX,
REV_GENERATED_LINE,
REV_GENERATED_COLUMN,
} from './sourcemap-segment';
import type { SourceMapSegment, ReverseSegment } from './sourcemap-segment';
import type {
SourceMapV3,
DecodedSourceMap,
EncodedSourceMap,
InvalidOriginalMapping,
OriginalMapping,
InvalidGeneratedMapping,
GeneratedMapping,
SourceMapInput,
Needle,
SourceNeedle,
SourceMap,
EachMapping,
} from './types';
import type { Source } from './by-source';
import type { MemoState } from './binary-search';
export type { SourceMapSegment } from './sourcemap-segment';
export type {
SourceMapInput,
SectionedSourceMapInput,
DecodedSourceMap,
EncodedSourceMap,
SectionedSourceMap,
InvalidOriginalMapping,
OriginalMapping as Mapping,
OriginalMapping,
InvalidGeneratedMapping,
GeneratedMapping,
EachMapping,
} from './types';
const INVALID_ORIGINAL_MAPPING: InvalidOriginalMapping = Object.freeze({
source: null,
line: null,
column: null,
name: null,
});
const INVALID_GENERATED_MAPPING: InvalidGeneratedMapping = Object.freeze({
line: null,
column: null,
});
const LINE_GTR_ZERO = '`line` must be greater than 0 (lines start at line 1)';
const COL_GTR_EQ_ZERO = '`column` must be greater than or equal to 0 (columns start at column 0)';
export const LEAST_UPPER_BOUND = -1;
export const GREATEST_LOWER_BOUND = 1;
/**
* Returns the encoded (VLQ string) form of the SourceMap's mappings field.
*/
export let encodedMappings: (map: TraceMap) => EncodedSourceMap['mappings'];
/**
* Returns the decoded (array of lines of segments) form of the SourceMap's mappings field.
*/
export let decodedMappings: (map: TraceMap) => Readonly<DecodedSourceMap['mappings']>;
/**
* A low-level API to find the segment associated with a generated line/column (think, from a
* stack trace). Line and column here are 0-based, unlike `originalPositionFor`.
*/
export let traceSegment: (
map: TraceMap,
line: number,
column: number,
) => Readonly<SourceMapSegment> | null;
/**
* A higher-level API to find the source/line/column associated with a generated line/column
* (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in
* `source-map` library.
*/
export let originalPositionFor: (
map: TraceMap,
needle: Needle,
) => OriginalMapping | InvalidOriginalMapping;
/**
* Finds the source/line/column directly after the mapping returned by originalPositionFor, provided
* the found mapping is from the same source and line as the originalPositionFor mapping.
*
* Eg, in the code `let id = 1`, `originalPositionAfter` could find the mapping associated with `1`
* using the same needle that would return `id` when calling `originalPositionFor`.
*/
export let generatedPositionFor: (
map: TraceMap,
needle: SourceNeedle,
) => GeneratedMapping | InvalidGeneratedMapping;
/**
* Iterates each mapping in generated position order.
*/
export let eachMapping: (map: TraceMap, cb: (mapping: EachMapping) => void) => void;
/**
* A helper that skips sorting of the input map's mappings array, which can be expensive for larger
* maps.
*/
export let presortedDecodedMap: (map: DecodedSourceMap, mapUrl?: string) => TraceMap;
/**
* Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects
* a sourcemap, or to JSON.stringify.
*/
export let decodedMap: (
map: TraceMap,
) => Omit<DecodedSourceMap, 'mappings'> & { mappings: readonly SourceMapSegment[][] };
/**
* Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects
* a sourcemap, or to JSON.stringify.
*/
export let encodedMap: (map: TraceMap) => EncodedSourceMap;
export { AnyMap } from './any-map';
export class TraceMap implements SourceMap {
declare version: SourceMapV3['version'];
declare file: SourceMapV3['file'];
declare names: SourceMapV3['names'];
declare sourceRoot: SourceMapV3['sourceRoot'];
declare sources: SourceMapV3['sources'];
declare sourcesContent: SourceMapV3['sourcesContent'];
declare resolvedSources: string[];
private declare _encoded: string | undefined;
private declare _decoded: SourceMapSegment[][] | undefined;
private _decodedMemo = memoizedState();
private _bySources: Source[] | undefined = undefined;
private _bySourceMemos: MemoState[] | undefined = undefined;
constructor(map: SourceMapInput, mapUrl?: string | null) {
const isString = typeof map === 'string';
const parsed = isString ? (JSON.parse(map) as Exclude<SourceMapInput, string>) : map;
const { version, file, names, sourceRoot, sources, sourcesContent } = parsed;
this.version = version;
this.file = file;
this.names = names;
this.sourceRoot = sourceRoot;
this.sources = sources;
this.sourcesContent = sourcesContent;
if (sourceRoot || mapUrl) {
const from = resolve(sourceRoot || '', stripFilename(mapUrl));
this.resolvedSources = sources.map((s) => resolve(s || '', from));
} else {
this.resolvedSources = sources.map((s) => s || '');
}
const { mappings } = parsed;
if (typeof mappings === 'string') {
this._encoded = mappings;
this._decoded = undefined;
} else {
this._encoded = undefined;
this._decoded = maybeSort(mappings, isString);
}
}
static {
encodedMappings = (map) => {
return (map._encoded ??= encode(map._decoded!));
};
decodedMappings = (map) => {
return (map._decoded ||= decode(map._encoded!));
};
traceSegment = (map, line, column) => {
const decoded = decodedMappings(map);
// It's common for parent source maps to have pointers to lines that have no
// mapping (like a "//# sourceMappingURL=") at the end of the child file.
if (line >= decoded.length) return null;
return traceSegmentInternal(
decoded[line],
map._decodedMemo,
line,
column,
GREATEST_LOWER_BOUND,
);
};
originalPositionFor = (map, { line, column, bias }) => {
line--;
if (line < 0) throw new Error(LINE_GTR_ZERO);
if (column < 0) throw new Error(COL_GTR_EQ_ZERO);
const decoded = decodedMappings(map);
// It's common for parent source maps to have pointers to lines that have no
// mapping (like a "//# sourceMappingURL=") at the end of the child file.
if (line >= decoded.length) return INVALID_ORIGINAL_MAPPING;
const segment = traceSegmentInternal(
decoded[line],
map._decodedMemo,
line,
column,
bias || GREATEST_LOWER_BOUND,
);
if (segment == null) return INVALID_ORIGINAL_MAPPING;
if (segment.length == 1) return INVALID_ORIGINAL_MAPPING;
const { names, resolvedSources } = map;
return {
source: resolvedSources[segment[SOURCES_INDEX]],
line: segment[SOURCE_LINE] + 1,
column: segment[SOURCE_COLUMN],
name: segment.length === 5 ? names[segment[NAMES_INDEX]] : null,
};
};
generatedPositionFor = (map, { source, line, column, bias }) => {
line--;
if (line < 0) throw new Error(LINE_GTR_ZERO);
if (column < 0) throw new Error(COL_GTR_EQ_ZERO);
const { sources, resolvedSources } = map;
let sourceIndex = sources.indexOf(source);
if (sourceIndex === -1) sourceIndex = resolvedSources.indexOf(source);
if (sourceIndex === -1) return INVALID_GENERATED_MAPPING;
const generated = (map._bySources ||= buildBySources(
decodedMappings(map),
(map._bySourceMemos = sources.map(memoizedState)),
));
const memos = map._bySourceMemos!;
const segments = generated[sourceIndex][line];
if (segments == null) return INVALID_GENERATED_MAPPING;
const segment = traceSegmentInternal(
segments,
memos[sourceIndex],
line,
column,
bias || GREATEST_LOWER_BOUND,
);
if (segment == null) return INVALID_GENERATED_MAPPING;
return {
line: segment[REV_GENERATED_LINE] + 1,
column: segment[REV_GENERATED_COLUMN],
};
};
eachMapping = (map, cb) => {
const decoded = decodedMappings(map);
const { names, resolvedSources } = map;
for (let i = 0; i < decoded.length; i++) {
const line = decoded[i];
for (let j = 0; j < line.length; j++) {
const seg = line[j];
const generatedLine = i + 1;
const generatedColumn = seg[0];
let source = null;
let originalLine = null;
let originalColumn = null;
let name = null;
if (seg.length !== 1) {
source = resolvedSources[seg[1]];
originalLine = seg[2] + 1;
originalColumn = seg[3];
}
if (seg.length === 5) name = names[seg[4]];
cb({
generatedLine,
generatedColumn,
source,
originalLine,
originalColumn,
name,
} as EachMapping);
}
}
};
presortedDecodedMap = (map, mapUrl) => {
const clone = Object.assign({}, map);
clone.mappings = [];
const tracer = new TraceMap(clone, mapUrl);
tracer._decoded = map.mappings;
return tracer;
};
decodedMap = (map) => {
return {
version: 3,
file: map.file,
names: map.names,
sourceRoot: map.sourceRoot,
sources: map.sources,
sourcesContent: map.sourcesContent,
mappings: decodedMappings(map),
};
};
encodedMap = (map) => {
return {
version: 3,
file: map.file,
names: map.names,
sourceRoot: map.sourceRoot,
sources: map.sources,
sourcesContent: map.sourcesContent,
mappings: encodedMappings(map),
};
};
}
}
function traceSegmentInternal(
segments: SourceMapSegment[],
memo: MemoState,
line: number,
column: number,
bias: typeof LEAST_UPPER_BOUND | typeof GREATEST_LOWER_BOUND,
): Readonly<SourceMapSegment> | null;
function traceSegmentInternal(
segments: ReverseSegment[],
memo: MemoState,
line: number,
column: number,
bias: typeof LEAST_UPPER_BOUND | typeof GREATEST_LOWER_BOUND,
): Readonly<ReverseSegment> | null;
function traceSegmentInternal(
segments: SourceMapSegment[] | ReverseSegment[],
memo: MemoState,
line: number,
column: number,
bias: typeof LEAST_UPPER_BOUND | typeof GREATEST_LOWER_BOUND,
): Readonly<SourceMapSegment | ReverseSegment> | null {
let index = memoizedBinarySearch(segments, column, memo, line);
if (bsFound) {
index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index);
} else if (bias === LEAST_UPPER_BOUND) index++;
if (index === -1 || index === segments.length) return null;
return segments[index];
}