trace-mapping.mjs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  1. import { encode, decode } from '@jridgewell/sourcemap-codec';
  2. import resolveUri from '@jridgewell/resolve-uri';
  3. function resolve(input, base) {
  4. // The base is always treated as a directory, if it's not empty.
  5. // https://github.com/mozilla/source-map/blob/8cb3ee57/lib/util.js#L327
  6. // https://github.com/chromium/chromium/blob/da4adbb3/third_party/blink/renderer/devtools/front_end/sdk/SourceMap.js#L400-L401
  7. if (base && !base.endsWith('/'))
  8. base += '/';
  9. return resolveUri(input, base);
  10. }
  11. /**
  12. * Removes everything after the last "/", but leaves the slash.
  13. */
  14. function stripFilename(path) {
  15. if (!path)
  16. return '';
  17. const index = path.lastIndexOf('/');
  18. return path.slice(0, index + 1);
  19. }
  20. const COLUMN = 0;
  21. const SOURCES_INDEX = 1;
  22. const SOURCE_LINE = 2;
  23. const SOURCE_COLUMN = 3;
  24. const NAMES_INDEX = 4;
  25. const REV_GENERATED_LINE = 1;
  26. const REV_GENERATED_COLUMN = 2;
  27. function maybeSort(mappings, owned) {
  28. const unsortedIndex = nextUnsortedSegmentLine(mappings, 0);
  29. if (unsortedIndex === mappings.length)
  30. return mappings;
  31. // If we own the array (meaning we parsed it from JSON), then we're free to directly mutate it. If
  32. // not, we do not want to modify the consumer's input array.
  33. if (!owned)
  34. mappings = mappings.slice();
  35. for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) {
  36. mappings[i] = sortSegments(mappings[i], owned);
  37. }
  38. return mappings;
  39. }
  40. function nextUnsortedSegmentLine(mappings, start) {
  41. for (let i = start; i < mappings.length; i++) {
  42. if (!isSorted(mappings[i]))
  43. return i;
  44. }
  45. return mappings.length;
  46. }
  47. function isSorted(line) {
  48. for (let j = 1; j < line.length; j++) {
  49. if (line[j][COLUMN] < line[j - 1][COLUMN]) {
  50. return false;
  51. }
  52. }
  53. return true;
  54. }
  55. function sortSegments(line, owned) {
  56. if (!owned)
  57. line = line.slice();
  58. return line.sort(sortComparator);
  59. }
  60. function sortComparator(a, b) {
  61. return a[COLUMN] - b[COLUMN];
  62. }
  63. let found = false;
  64. /**
  65. * A binary search implementation that returns the index if a match is found.
  66. * If no match is found, then the left-index (the index associated with the item that comes just
  67. * before the desired index) is returned. To maintain proper sort order, a splice would happen at
  68. * the next index:
  69. *
  70. * ```js
  71. * const array = [1, 3];
  72. * const needle = 2;
  73. * const index = binarySearch(array, needle, (item, needle) => item - needle);
  74. *
  75. * assert.equal(index, 0);
  76. * array.splice(index + 1, 0, needle);
  77. * assert.deepEqual(array, [1, 2, 3]);
  78. * ```
  79. */
  80. function binarySearch(haystack, needle, low, high) {
  81. while (low <= high) {
  82. const mid = low + ((high - low) >> 1);
  83. const cmp = haystack[mid][COLUMN] - needle;
  84. if (cmp === 0) {
  85. found = true;
  86. return mid;
  87. }
  88. if (cmp < 0) {
  89. low = mid + 1;
  90. }
  91. else {
  92. high = mid - 1;
  93. }
  94. }
  95. found = false;
  96. return low - 1;
  97. }
  98. function upperBound(haystack, needle, index) {
  99. for (let i = index + 1; i < haystack.length; index = i++) {
  100. if (haystack[i][COLUMN] !== needle)
  101. break;
  102. }
  103. return index;
  104. }
  105. function lowerBound(haystack, needle, index) {
  106. for (let i = index - 1; i >= 0; index = i--) {
  107. if (haystack[i][COLUMN] !== needle)
  108. break;
  109. }
  110. return index;
  111. }
  112. function memoizedState() {
  113. return {
  114. lastKey: -1,
  115. lastNeedle: -1,
  116. lastIndex: -1,
  117. };
  118. }
  119. /**
  120. * This overly complicated beast is just to record the last tested line/column and the resulting
  121. * index, allowing us to skip a few tests if mappings are monotonically increasing.
  122. */
  123. function memoizedBinarySearch(haystack, needle, state, key) {
  124. const { lastKey, lastNeedle, lastIndex } = state;
  125. let low = 0;
  126. let high = haystack.length - 1;
  127. if (key === lastKey) {
  128. if (needle === lastNeedle) {
  129. found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle;
  130. return lastIndex;
  131. }
  132. if (needle >= lastNeedle) {
  133. // lastIndex may be -1 if the previous needle was not found.
  134. low = lastIndex === -1 ? 0 : lastIndex;
  135. }
  136. else {
  137. high = lastIndex;
  138. }
  139. }
  140. state.lastKey = key;
  141. state.lastNeedle = needle;
  142. return (state.lastIndex = binarySearch(haystack, needle, low, high));
  143. }
  144. // Rebuilds the original source files, with mappings that are ordered by source line/column instead
  145. // of generated line/column.
  146. function buildBySources(decoded, memos) {
  147. const sources = memos.map(buildNullArray);
  148. for (let i = 0; i < decoded.length; i++) {
  149. const line = decoded[i];
  150. for (let j = 0; j < line.length; j++) {
  151. const seg = line[j];
  152. if (seg.length === 1)
  153. continue;
  154. const sourceIndex = seg[SOURCES_INDEX];
  155. const sourceLine = seg[SOURCE_LINE];
  156. const sourceColumn = seg[SOURCE_COLUMN];
  157. const originalSource = sources[sourceIndex];
  158. const originalLine = (originalSource[sourceLine] || (originalSource[sourceLine] = []));
  159. const memo = memos[sourceIndex];
  160. // The binary search either found a match, or it found the left-index just before where the
  161. // segment should go. Either way, we want to insert after that. And there may be multiple
  162. // generated segments associated with an original location, so there may need to move several
  163. // indexes before we find where we need to insert.
  164. const index = upperBound(originalLine, sourceColumn, memoizedBinarySearch(originalLine, sourceColumn, memo, sourceLine));
  165. insert(originalLine, (memo.lastIndex = index + 1), [sourceColumn, i, seg[COLUMN]]);
  166. }
  167. }
  168. return sources;
  169. }
  170. function insert(array, index, value) {
  171. for (let i = array.length; i > index; i--) {
  172. array[i] = array[i - 1];
  173. }
  174. array[index] = value;
  175. }
  176. // Null arrays allow us to use ordered index keys without actually allocating contiguous memory like
  177. // a real array. We use a null-prototype object to avoid prototype pollution and deoptimizations.
  178. // Numeric properties on objects are magically sorted in ascending order by the engine regardless of
  179. // the insertion order. So, by setting any numeric keys, even out of order, we'll get ascending
  180. // order when iterating with for-in.
  181. function buildNullArray() {
  182. return { __proto__: null };
  183. }
  184. const AnyMap = function (map, mapUrl) {
  185. const parsed = typeof map === 'string' ? JSON.parse(map) : map;
  186. if (!('sections' in parsed))
  187. return new TraceMap(parsed, mapUrl);
  188. const mappings = [];
  189. const sources = [];
  190. const sourcesContent = [];
  191. const names = [];
  192. recurse(parsed, mapUrl, mappings, sources, sourcesContent, names, 0, 0, Infinity, Infinity);
  193. const joined = {
  194. version: 3,
  195. file: parsed.file,
  196. names,
  197. sources,
  198. sourcesContent,
  199. mappings,
  200. };
  201. return presortedDecodedMap(joined);
  202. };
  203. function recurse(input, mapUrl, mappings, sources, sourcesContent, names, lineOffset, columnOffset, stopLine, stopColumn) {
  204. const { sections } = input;
  205. for (let i = 0; i < sections.length; i++) {
  206. const { map, offset } = sections[i];
  207. let sl = stopLine;
  208. let sc = stopColumn;
  209. if (i + 1 < sections.length) {
  210. const nextOffset = sections[i + 1].offset;
  211. sl = Math.min(stopLine, lineOffset + nextOffset.line);
  212. if (sl === stopLine) {
  213. sc = Math.min(stopColumn, columnOffset + nextOffset.column);
  214. }
  215. else if (sl < stopLine) {
  216. sc = columnOffset + nextOffset.column;
  217. }
  218. }
  219. addSection(map, mapUrl, mappings, sources, sourcesContent, names, lineOffset + offset.line, columnOffset + offset.column, sl, sc);
  220. }
  221. }
  222. function addSection(input, mapUrl, mappings, sources, sourcesContent, names, lineOffset, columnOffset, stopLine, stopColumn) {
  223. if ('sections' in input)
  224. return recurse(...arguments);
  225. const map = new TraceMap(input, mapUrl);
  226. const sourcesOffset = sources.length;
  227. const namesOffset = names.length;
  228. const decoded = decodedMappings(map);
  229. const { resolvedSources, sourcesContent: contents } = map;
  230. append(sources, resolvedSources);
  231. append(names, map.names);
  232. if (contents)
  233. append(sourcesContent, contents);
  234. else
  235. for (let i = 0; i < resolvedSources.length; i++)
  236. sourcesContent.push(null);
  237. for (let i = 0; i < decoded.length; i++) {
  238. const lineI = lineOffset + i;
  239. // We can only add so many lines before we step into the range that the next section's map
  240. // controls. When we get to the last line, then we'll start checking the segments to see if
  241. // they've crossed into the column range. But it may not have any columns that overstep, so we
  242. // still need to check that we don't overstep lines, too.
  243. if (lineI > stopLine)
  244. return;
  245. // The out line may already exist in mappings (if we're continuing the line started by a
  246. // previous section). Or, we may have jumped ahead several lines to start this section.
  247. const out = getLine(mappings, lineI);
  248. // On the 0th loop, the section's column offset shifts us forward. On all other lines (since the
  249. // map can be multiple lines), it doesn't.
  250. const cOffset = i === 0 ? columnOffset : 0;
  251. const line = decoded[i];
  252. for (let j = 0; j < line.length; j++) {
  253. const seg = line[j];
  254. const column = cOffset + seg[COLUMN];
  255. // If this segment steps into the column range that the next section's map controls, we need
  256. // to stop early.
  257. if (lineI === stopLine && column >= stopColumn)
  258. return;
  259. if (seg.length === 1) {
  260. out.push([column]);
  261. continue;
  262. }
  263. const sourcesIndex = sourcesOffset + seg[SOURCES_INDEX];
  264. const sourceLine = seg[SOURCE_LINE];
  265. const sourceColumn = seg[SOURCE_COLUMN];
  266. out.push(seg.length === 4
  267. ? [column, sourcesIndex, sourceLine, sourceColumn]
  268. : [column, sourcesIndex, sourceLine, sourceColumn, namesOffset + seg[NAMES_INDEX]]);
  269. }
  270. }
  271. }
  272. function append(arr, other) {
  273. for (let i = 0; i < other.length; i++)
  274. arr.push(other[i]);
  275. }
  276. function getLine(arr, index) {
  277. for (let i = arr.length; i <= index; i++)
  278. arr[i] = [];
  279. return arr[index];
  280. }
  281. const LINE_GTR_ZERO = '`line` must be greater than 0 (lines start at line 1)';
  282. const COL_GTR_EQ_ZERO = '`column` must be greater than or equal to 0 (columns start at column 0)';
  283. const LEAST_UPPER_BOUND = -1;
  284. const GREATEST_LOWER_BOUND = 1;
  285. /**
  286. * Returns the encoded (VLQ string) form of the SourceMap's mappings field.
  287. */
  288. let encodedMappings;
  289. /**
  290. * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field.
  291. */
  292. let decodedMappings;
  293. /**
  294. * A low-level API to find the segment associated with a generated line/column (think, from a
  295. * stack trace). Line and column here are 0-based, unlike `originalPositionFor`.
  296. */
  297. let traceSegment;
  298. /**
  299. * A higher-level API to find the source/line/column associated with a generated line/column
  300. * (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in
  301. * `source-map` library.
  302. */
  303. let originalPositionFor;
  304. /**
  305. * Finds the source/line/column directly after the mapping returned by originalPositionFor, provided
  306. * the found mapping is from the same source and line as the originalPositionFor mapping.
  307. *
  308. * Eg, in the code `let id = 1`, `originalPositionAfter` could find the mapping associated with `1`
  309. * using the same needle that would return `id` when calling `originalPositionFor`.
  310. */
  311. let generatedPositionFor;
  312. /**
  313. * Iterates each mapping in generated position order.
  314. */
  315. let eachMapping;
  316. /**
  317. * Retrieves the source content for a particular source, if its found. Returns null if not.
  318. */
  319. let sourceContentFor;
  320. /**
  321. * A helper that skips sorting of the input map's mappings array, which can be expensive for larger
  322. * maps.
  323. */
  324. let presortedDecodedMap;
  325. /**
  326. * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects
  327. * a sourcemap, or to JSON.stringify.
  328. */
  329. let decodedMap;
  330. /**
  331. * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects
  332. * a sourcemap, or to JSON.stringify.
  333. */
  334. let encodedMap;
  335. class TraceMap {
  336. constructor(map, mapUrl) {
  337. this._decodedMemo = memoizedState();
  338. this._bySources = undefined;
  339. this._bySourceMemos = undefined;
  340. const isString = typeof map === 'string';
  341. if (!isString && map._decodedMemo)
  342. return map;
  343. const parsed = (isString ? JSON.parse(map) : map);
  344. const { version, file, names, sourceRoot, sources, sourcesContent } = parsed;
  345. this.version = version;
  346. this.file = file;
  347. this.names = names;
  348. this.sourceRoot = sourceRoot;
  349. this.sources = sources;
  350. this.sourcesContent = sourcesContent;
  351. const from = resolve(sourceRoot || '', stripFilename(mapUrl));
  352. this.resolvedSources = sources.map((s) => resolve(s || '', from));
  353. const { mappings } = parsed;
  354. if (typeof mappings === 'string') {
  355. this._encoded = mappings;
  356. this._decoded = undefined;
  357. }
  358. else {
  359. this._encoded = undefined;
  360. this._decoded = maybeSort(mappings, isString);
  361. }
  362. }
  363. }
  364. (() => {
  365. encodedMappings = (map) => {
  366. var _a;
  367. return ((_a = map._encoded) !== null && _a !== void 0 ? _a : (map._encoded = encode(map._decoded)));
  368. };
  369. decodedMappings = (map) => {
  370. return (map._decoded || (map._decoded = decode(map._encoded)));
  371. };
  372. traceSegment = (map, line, column) => {
  373. const decoded = decodedMappings(map);
  374. // It's common for parent source maps to have pointers to lines that have no
  375. // mapping (like a "//# sourceMappingURL=") at the end of the child file.
  376. if (line >= decoded.length)
  377. return null;
  378. return traceSegmentInternal(decoded[line], map._decodedMemo, line, column, GREATEST_LOWER_BOUND);
  379. };
  380. originalPositionFor = (map, { line, column, bias }) => {
  381. line--;
  382. if (line < 0)
  383. throw new Error(LINE_GTR_ZERO);
  384. if (column < 0)
  385. throw new Error(COL_GTR_EQ_ZERO);
  386. const decoded = decodedMappings(map);
  387. // It's common for parent source maps to have pointers to lines that have no
  388. // mapping (like a "//# sourceMappingURL=") at the end of the child file.
  389. if (line >= decoded.length)
  390. return OMapping(null, null, null, null);
  391. const segment = traceSegmentInternal(decoded[line], map._decodedMemo, line, column, bias || GREATEST_LOWER_BOUND);
  392. if (segment == null)
  393. return OMapping(null, null, null, null);
  394. if (segment.length == 1)
  395. return OMapping(null, null, null, null);
  396. const { names, resolvedSources } = map;
  397. return OMapping(resolvedSources[segment[SOURCES_INDEX]], segment[SOURCE_LINE] + 1, segment[SOURCE_COLUMN], segment.length === 5 ? names[segment[NAMES_INDEX]] : null);
  398. };
  399. generatedPositionFor = (map, { source, line, column, bias }) => {
  400. line--;
  401. if (line < 0)
  402. throw new Error(LINE_GTR_ZERO);
  403. if (column < 0)
  404. throw new Error(COL_GTR_EQ_ZERO);
  405. const { sources, resolvedSources } = map;
  406. let sourceIndex = sources.indexOf(source);
  407. if (sourceIndex === -1)
  408. sourceIndex = resolvedSources.indexOf(source);
  409. if (sourceIndex === -1)
  410. return GMapping(null, null);
  411. const generated = (map._bySources || (map._bySources = buildBySources(decodedMappings(map), (map._bySourceMemos = sources.map(memoizedState)))));
  412. const memos = map._bySourceMemos;
  413. const segments = generated[sourceIndex][line];
  414. if (segments == null)
  415. return GMapping(null, null);
  416. const segment = traceSegmentInternal(segments, memos[sourceIndex], line, column, bias || GREATEST_LOWER_BOUND);
  417. if (segment == null)
  418. return GMapping(null, null);
  419. return GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN]);
  420. };
  421. eachMapping = (map, cb) => {
  422. const decoded = decodedMappings(map);
  423. const { names, resolvedSources } = map;
  424. for (let i = 0; i < decoded.length; i++) {
  425. const line = decoded[i];
  426. for (let j = 0; j < line.length; j++) {
  427. const seg = line[j];
  428. const generatedLine = i + 1;
  429. const generatedColumn = seg[0];
  430. let source = null;
  431. let originalLine = null;
  432. let originalColumn = null;
  433. let name = null;
  434. if (seg.length !== 1) {
  435. source = resolvedSources[seg[1]];
  436. originalLine = seg[2] + 1;
  437. originalColumn = seg[3];
  438. }
  439. if (seg.length === 5)
  440. name = names[seg[4]];
  441. cb({
  442. generatedLine,
  443. generatedColumn,
  444. source,
  445. originalLine,
  446. originalColumn,
  447. name,
  448. });
  449. }
  450. }
  451. };
  452. sourceContentFor = (map, source) => {
  453. const { sources, resolvedSources, sourcesContent } = map;
  454. if (sourcesContent == null)
  455. return null;
  456. let index = sources.indexOf(source);
  457. if (index === -1)
  458. index = resolvedSources.indexOf(source);
  459. return index === -1 ? null : sourcesContent[index];
  460. };
  461. presortedDecodedMap = (map, mapUrl) => {
  462. const clone = Object.assign({}, map);
  463. clone.mappings = [];
  464. const tracer = new TraceMap(clone, mapUrl);
  465. tracer._decoded = map.mappings;
  466. return tracer;
  467. };
  468. decodedMap = (map) => {
  469. return {
  470. version: 3,
  471. file: map.file,
  472. names: map.names,
  473. sourceRoot: map.sourceRoot,
  474. sources: map.sources,
  475. sourcesContent: map.sourcesContent,
  476. mappings: decodedMappings(map),
  477. };
  478. };
  479. encodedMap = (map) => {
  480. return {
  481. version: 3,
  482. file: map.file,
  483. names: map.names,
  484. sourceRoot: map.sourceRoot,
  485. sources: map.sources,
  486. sourcesContent: map.sourcesContent,
  487. mappings: encodedMappings(map),
  488. };
  489. };
  490. })();
  491. function OMapping(source, line, column, name) {
  492. return { source, line, column, name };
  493. }
  494. function GMapping(line, column) {
  495. return { line, column };
  496. }
  497. function traceSegmentInternal(segments, memo, line, column, bias) {
  498. let index = memoizedBinarySearch(segments, column, memo, line);
  499. if (found) {
  500. index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index);
  501. }
  502. else if (bias === LEAST_UPPER_BOUND)
  503. index++;
  504. if (index === -1 || index === segments.length)
  505. return null;
  506. return segments[index];
  507. }
  508. export { AnyMap, GREATEST_LOWER_BOUND, LEAST_UPPER_BOUND, TraceMap, decodedMap, decodedMappings, eachMapping, encodedMap, encodedMappings, generatedPositionFor, originalPositionFor, presortedDecodedMap, sourceContentFor, traceSegment };
  509. //# sourceMappingURL=trace-mapping.mjs.map