trace-mapping.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. import { encode, decode } from '@jridgewell/sourcemap-codec';
  2. import resolver from './resolve';
  3. import maybeSort from './sort';
  4. import buildBySources from './by-source';
  5. import {
  6. memoizedState,
  7. memoizedBinarySearch,
  8. upperBound,
  9. lowerBound,
  10. found as bsFound,
  11. } from './binary-search';
  12. import {
  13. COLUMN,
  14. SOURCES_INDEX,
  15. SOURCE_LINE,
  16. SOURCE_COLUMN,
  17. NAMES_INDEX,
  18. REV_GENERATED_LINE,
  19. REV_GENERATED_COLUMN,
  20. } from './sourcemap-segment';
  21. import { parse } from './types';
  22. import type { SourceMapSegment, ReverseSegment } from './sourcemap-segment';
  23. import type {
  24. SourceMapV3,
  25. DecodedSourceMap,
  26. EncodedSourceMap,
  27. InvalidOriginalMapping,
  28. OriginalMapping,
  29. InvalidGeneratedMapping,
  30. GeneratedMapping,
  31. SourceMapInput,
  32. Needle,
  33. SourceNeedle,
  34. SourceMap,
  35. EachMapping,
  36. Bias,
  37. XInput,
  38. SectionedSourceMap,
  39. Ro,
  40. } from './types';
  41. import type { Source } from './by-source';
  42. import type { MemoState } from './binary-search';
  43. export type { SourceMapSegment } from './sourcemap-segment';
  44. export type {
  45. SourceMap,
  46. DecodedSourceMap,
  47. EncodedSourceMap,
  48. Section,
  49. SectionedSourceMap,
  50. SourceMapV3,
  51. Bias,
  52. EachMapping,
  53. GeneratedMapping,
  54. InvalidGeneratedMapping,
  55. InvalidOriginalMapping,
  56. Needle,
  57. OriginalMapping,
  58. OriginalMapping as Mapping,
  59. SectionedSourceMapInput,
  60. SourceMapInput,
  61. SourceNeedle,
  62. XInput,
  63. EncodedSourceMapXInput,
  64. DecodedSourceMapXInput,
  65. SectionedSourceMapXInput,
  66. SectionXInput,
  67. } from './types';
  68. interface PublicMap {
  69. _encoded: TraceMap['_encoded'];
  70. _decoded: TraceMap['_decoded'];
  71. _decodedMemo: TraceMap['_decodedMemo'];
  72. _bySources: TraceMap['_bySources'];
  73. _bySourceMemos: TraceMap['_bySourceMemos'];
  74. }
  75. const LINE_GTR_ZERO = '`line` must be greater than 0 (lines start at line 1)';
  76. const COL_GTR_EQ_ZERO = '`column` must be greater than or equal to 0 (columns start at column 0)';
  77. export const LEAST_UPPER_BOUND = -1;
  78. export const GREATEST_LOWER_BOUND = 1;
  79. export { FlattenMap, FlattenMap as AnyMap } from './flatten-map';
  80. export class TraceMap implements SourceMap {
  81. declare version: SourceMapV3['version'];
  82. declare file: SourceMapV3['file'];
  83. declare names: SourceMapV3['names'];
  84. declare sourceRoot: SourceMapV3['sourceRoot'];
  85. declare sources: SourceMapV3['sources'];
  86. declare sourcesContent: SourceMapV3['sourcesContent'];
  87. declare ignoreList: SourceMapV3['ignoreList'];
  88. declare resolvedSources: string[];
  89. declare private _encoded: string | undefined;
  90. declare private _decoded: SourceMapSegment[][] | undefined;
  91. declare private _decodedMemo: MemoState;
  92. declare private _bySources: Source[] | undefined;
  93. declare private _bySourceMemos: MemoState[] | undefined;
  94. constructor(map: Ro<SourceMapInput>, mapUrl?: string | null) {
  95. const isString = typeof map === 'string';
  96. if (!isString && (map as unknown as { _decodedMemo: any })._decodedMemo) return map as TraceMap;
  97. const parsed = parse(map as Exclude<SourceMapInput, TraceMap>);
  98. const { version, file, names, sourceRoot, sources, sourcesContent } = parsed;
  99. this.version = version;
  100. this.file = file;
  101. this.names = names || [];
  102. this.sourceRoot = sourceRoot;
  103. this.sources = sources;
  104. this.sourcesContent = sourcesContent;
  105. this.ignoreList = parsed.ignoreList || (parsed as XInput).x_google_ignoreList || undefined;
  106. const resolve = resolver(mapUrl, sourceRoot);
  107. this.resolvedSources = sources.map(resolve);
  108. const { mappings } = parsed;
  109. if (typeof mappings === 'string') {
  110. this._encoded = mappings;
  111. this._decoded = undefined;
  112. } else if (Array.isArray(mappings)) {
  113. this._encoded = undefined;
  114. this._decoded = maybeSort(mappings, isString);
  115. } else if ((parsed as unknown as SectionedSourceMap).sections) {
  116. throw new Error(`TraceMap passed sectioned source map, please use FlattenMap export instead`);
  117. } else {
  118. throw new Error(`invalid source map: ${JSON.stringify(parsed)}`);
  119. }
  120. this._decodedMemo = memoizedState();
  121. this._bySources = undefined;
  122. this._bySourceMemos = undefined;
  123. }
  124. }
  125. /**
  126. * Typescript doesn't allow friend access to private fields, so this just casts the map into a type
  127. * with public access modifiers.
  128. */
  129. function cast(map: unknown): PublicMap {
  130. return map as any;
  131. }
  132. /**
  133. * Returns the encoded (VLQ string) form of the SourceMap's mappings field.
  134. */
  135. export function encodedMappings(map: TraceMap): EncodedSourceMap['mappings'] {
  136. return (cast(map)._encoded ??= encode(cast(map)._decoded!));
  137. }
  138. /**
  139. * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field.
  140. */
  141. export function decodedMappings(map: TraceMap): Readonly<DecodedSourceMap['mappings']> {
  142. return (cast(map)._decoded ||= decode(cast(map)._encoded!));
  143. }
  144. /**
  145. * A low-level API to find the segment associated with a generated line/column (think, from a
  146. * stack trace). Line and column here are 0-based, unlike `originalPositionFor`.
  147. */
  148. export function traceSegment(
  149. map: TraceMap,
  150. line: number,
  151. column: number,
  152. ): Readonly<SourceMapSegment> | null {
  153. const decoded = decodedMappings(map);
  154. // It's common for parent source maps to have pointers to lines that have no
  155. // mapping (like a "//# sourceMappingURL=") at the end of the child file.
  156. if (line >= decoded.length) return null;
  157. const segments = decoded[line];
  158. const index = traceSegmentInternal(
  159. segments,
  160. cast(map)._decodedMemo,
  161. line,
  162. column,
  163. GREATEST_LOWER_BOUND,
  164. );
  165. return index === -1 ? null : segments[index];
  166. }
  167. /**
  168. * A higher-level API to find the source/line/column associated with a generated line/column
  169. * (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in
  170. * `source-map` library.
  171. */
  172. export function originalPositionFor(
  173. map: TraceMap,
  174. needle: Needle,
  175. ): OriginalMapping | InvalidOriginalMapping {
  176. let { line, column, bias } = needle;
  177. line--;
  178. if (line < 0) throw new Error(LINE_GTR_ZERO);
  179. if (column < 0) throw new Error(COL_GTR_EQ_ZERO);
  180. const decoded = decodedMappings(map);
  181. // It's common for parent source maps to have pointers to lines that have no
  182. // mapping (like a "//# sourceMappingURL=") at the end of the child file.
  183. if (line >= decoded.length) return OMapping(null, null, null, null);
  184. const segments = decoded[line];
  185. const index = traceSegmentInternal(
  186. segments,
  187. cast(map)._decodedMemo,
  188. line,
  189. column,
  190. bias || GREATEST_LOWER_BOUND,
  191. );
  192. if (index === -1) return OMapping(null, null, null, null);
  193. const segment = segments[index];
  194. if (segment.length === 1) return OMapping(null, null, null, null);
  195. const { names, resolvedSources } = map;
  196. return OMapping(
  197. resolvedSources[segment[SOURCES_INDEX]],
  198. segment[SOURCE_LINE] + 1,
  199. segment[SOURCE_COLUMN],
  200. segment.length === 5 ? names[segment[NAMES_INDEX]] : null,
  201. );
  202. }
  203. /**
  204. * Finds the generated line/column position of the provided source/line/column source position.
  205. */
  206. export function generatedPositionFor(
  207. map: TraceMap,
  208. needle: SourceNeedle,
  209. ): GeneratedMapping | InvalidGeneratedMapping {
  210. const { source, line, column, bias } = needle;
  211. return generatedPosition(map, source, line, column, bias || GREATEST_LOWER_BOUND, false);
  212. }
  213. /**
  214. * Finds all generated line/column positions of the provided source/line/column source position.
  215. */
  216. export function allGeneratedPositionsFor(map: TraceMap, needle: SourceNeedle): GeneratedMapping[] {
  217. const { source, line, column, bias } = needle;
  218. // SourceMapConsumer uses LEAST_UPPER_BOUND for some reason, so we follow suit.
  219. return generatedPosition(map, source, line, column, bias || LEAST_UPPER_BOUND, true);
  220. }
  221. /**
  222. * Iterates each mapping in generated position order.
  223. */
  224. export function eachMapping(map: TraceMap, cb: (mapping: EachMapping) => void): void {
  225. const decoded = decodedMappings(map);
  226. const { names, resolvedSources } = map;
  227. for (let i = 0; i < decoded.length; i++) {
  228. const line = decoded[i];
  229. for (let j = 0; j < line.length; j++) {
  230. const seg = line[j];
  231. const generatedLine = i + 1;
  232. const generatedColumn = seg[0];
  233. let source = null;
  234. let originalLine = null;
  235. let originalColumn = null;
  236. let name = null;
  237. if (seg.length !== 1) {
  238. source = resolvedSources[seg[1]];
  239. originalLine = seg[2] + 1;
  240. originalColumn = seg[3];
  241. }
  242. if (seg.length === 5) name = names[seg[4]];
  243. cb({
  244. generatedLine,
  245. generatedColumn,
  246. source,
  247. originalLine,
  248. originalColumn,
  249. name,
  250. } as EachMapping);
  251. }
  252. }
  253. }
  254. function sourceIndex(map: TraceMap, source: string): number {
  255. const { sources, resolvedSources } = map;
  256. let index = sources.indexOf(source);
  257. if (index === -1) index = resolvedSources.indexOf(source);
  258. return index;
  259. }
  260. /**
  261. * Retrieves the source content for a particular source, if its found. Returns null if not.
  262. */
  263. export function sourceContentFor(map: TraceMap, source: string): string | null {
  264. const { sourcesContent } = map;
  265. if (sourcesContent == null) return null;
  266. const index = sourceIndex(map, source);
  267. return index === -1 ? null : sourcesContent[index];
  268. }
  269. /**
  270. * Determines if the source is marked to ignore by the source map.
  271. */
  272. export function isIgnored(map: TraceMap, source: string): boolean {
  273. const { ignoreList } = map;
  274. if (ignoreList == null) return false;
  275. const index = sourceIndex(map, source);
  276. return index === -1 ? false : ignoreList.includes(index);
  277. }
  278. /**
  279. * A helper that skips sorting of the input map's mappings array, which can be expensive for larger
  280. * maps.
  281. */
  282. export function presortedDecodedMap(map: DecodedSourceMap, mapUrl?: string): TraceMap {
  283. const tracer = new TraceMap(clone(map, []), mapUrl);
  284. cast(tracer)._decoded = map.mappings;
  285. return tracer;
  286. }
  287. /**
  288. * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects
  289. * a sourcemap, or to JSON.stringify.
  290. */
  291. export function decodedMap(
  292. map: TraceMap,
  293. ): Omit<DecodedSourceMap, 'mappings'> & { mappings: readonly SourceMapSegment[][] } {
  294. return clone(map, decodedMappings(map));
  295. }
  296. /**
  297. * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects
  298. * a sourcemap, or to JSON.stringify.
  299. */
  300. export function encodedMap(map: TraceMap): EncodedSourceMap {
  301. return clone(map, encodedMappings(map));
  302. }
  303. function clone<T extends string | readonly SourceMapSegment[][]>(
  304. map: TraceMap | DecodedSourceMap,
  305. mappings: T,
  306. ): T extends string ? EncodedSourceMap : DecodedSourceMap {
  307. return {
  308. version: map.version,
  309. file: map.file,
  310. names: map.names,
  311. sourceRoot: map.sourceRoot,
  312. sources: map.sources,
  313. sourcesContent: map.sourcesContent,
  314. mappings,
  315. ignoreList: map.ignoreList || (map as XInput).x_google_ignoreList,
  316. } as any;
  317. }
  318. function OMapping(source: null, line: null, column: null, name: null): InvalidOriginalMapping;
  319. function OMapping(
  320. source: string,
  321. line: number,
  322. column: number,
  323. name: string | null,
  324. ): OriginalMapping;
  325. function OMapping(
  326. source: string | null,
  327. line: number | null,
  328. column: number | null,
  329. name: string | null,
  330. ): OriginalMapping | InvalidOriginalMapping {
  331. return { source, line, column, name } as any;
  332. }
  333. function GMapping(line: null, column: null): InvalidGeneratedMapping;
  334. function GMapping(line: number, column: number): GeneratedMapping;
  335. function GMapping(
  336. line: number | null,
  337. column: number | null,
  338. ): GeneratedMapping | InvalidGeneratedMapping {
  339. return { line, column } as any;
  340. }
  341. function traceSegmentInternal(
  342. segments: SourceMapSegment[],
  343. memo: MemoState,
  344. line: number,
  345. column: number,
  346. bias: Bias,
  347. ): number;
  348. function traceSegmentInternal(
  349. segments: ReverseSegment[],
  350. memo: MemoState,
  351. line: number,
  352. column: number,
  353. bias: Bias,
  354. ): number;
  355. function traceSegmentInternal(
  356. segments: SourceMapSegment[] | ReverseSegment[],
  357. memo: MemoState,
  358. line: number,
  359. column: number,
  360. bias: Bias,
  361. ): number {
  362. let index = memoizedBinarySearch(segments, column, memo, line);
  363. if (bsFound) {
  364. index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index);
  365. } else if (bias === LEAST_UPPER_BOUND) index++;
  366. if (index === -1 || index === segments.length) return -1;
  367. return index;
  368. }
  369. function sliceGeneratedPositions(
  370. segments: ReverseSegment[],
  371. memo: MemoState,
  372. line: number,
  373. column: number,
  374. bias: Bias,
  375. ): GeneratedMapping[] {
  376. let min = traceSegmentInternal(segments, memo, line, column, GREATEST_LOWER_BOUND);
  377. // We ignored the bias when tracing the segment so that we're guarnateed to find the first (in
  378. // insertion order) segment that matched. Even if we did respect the bias when tracing, we would
  379. // still need to call `lowerBound()` to find the first segment, which is slower than just looking
  380. // for the GREATEST_LOWER_BOUND to begin with. The only difference that matters for us is when the
  381. // binary search didn't match, in which case GREATEST_LOWER_BOUND just needs to increment to
  382. // match LEAST_UPPER_BOUND.
  383. if (!bsFound && bias === LEAST_UPPER_BOUND) min++;
  384. if (min === -1 || min === segments.length) return [];
  385. // We may have found the segment that started at an earlier column. If this is the case, then we
  386. // need to slice all generated segments that match _that_ column, because all such segments span
  387. // to our desired column.
  388. const matchedColumn = bsFound ? column : segments[min][COLUMN];
  389. // The binary search is not guaranteed to find the lower bound when a match wasn't found.
  390. if (!bsFound) min = lowerBound(segments, matchedColumn, min);
  391. const max = upperBound(segments, matchedColumn, min);
  392. const result = [];
  393. for (; min <= max; min++) {
  394. const segment = segments[min];
  395. result.push(GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN]));
  396. }
  397. return result;
  398. }
  399. function generatedPosition(
  400. map: TraceMap,
  401. source: string,
  402. line: number,
  403. column: number,
  404. bias: Bias,
  405. all: false,
  406. ): GeneratedMapping | InvalidGeneratedMapping;
  407. function generatedPosition(
  408. map: TraceMap,
  409. source: string,
  410. line: number,
  411. column: number,
  412. bias: Bias,
  413. all: true,
  414. ): GeneratedMapping[];
  415. function generatedPosition(
  416. map: TraceMap,
  417. source: string,
  418. line: number,
  419. column: number,
  420. bias: Bias,
  421. all: boolean,
  422. ): GeneratedMapping | InvalidGeneratedMapping | GeneratedMapping[] {
  423. line--;
  424. if (line < 0) throw new Error(LINE_GTR_ZERO);
  425. if (column < 0) throw new Error(COL_GTR_EQ_ZERO);
  426. const { sources, resolvedSources } = map;
  427. let sourceIndex = sources.indexOf(source);
  428. if (sourceIndex === -1) sourceIndex = resolvedSources.indexOf(source);
  429. if (sourceIndex === -1) return all ? [] : GMapping(null, null);
  430. const bySourceMemos = (cast(map)._bySourceMemos ||= sources.map(memoizedState));
  431. const generated = (cast(map)._bySources ||= buildBySources(decodedMappings(map), bySourceMemos));
  432. const segments = generated[sourceIndex][line];
  433. if (segments == null) return all ? [] : GMapping(null, null);
  434. const memo = bySourceMemos[sourceIndex];
  435. if (all) return sliceGeneratedPositions(segments, memo, line, column, bias);
  436. const index = traceSegmentInternal(segments, memo, line, column, bias);
  437. if (index === -1) return GMapping(null, null);
  438. const segment = segments[index];
  439. return GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN]);
  440. }