trace-mapping.mjs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  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 generated line/column position of the provided source/line/column source position.
  306. */
  307. let generatedPositionFor;
  308. /**
  309. * Finds all generated line/column positions of the provided source/line/column source position.
  310. */
  311. let allGeneratedPositionsFor;
  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. const isString = typeof map === 'string';
  338. if (!isString && map._decodedMemo)
  339. return map;
  340. const parsed = (isString ? JSON.parse(map) : map);
  341. const { version, file, names, sourceRoot, sources, sourcesContent } = parsed;
  342. this.version = version;
  343. this.file = file;
  344. this.names = names;
  345. this.sourceRoot = sourceRoot;
  346. this.sources = sources;
  347. this.sourcesContent = sourcesContent;
  348. const from = resolve(sourceRoot || '', stripFilename(mapUrl));
  349. this.resolvedSources = sources.map((s) => resolve(s || '', from));
  350. const { mappings } = parsed;
  351. if (typeof mappings === 'string') {
  352. this._encoded = mappings;
  353. this._decoded = undefined;
  354. }
  355. else {
  356. this._encoded = undefined;
  357. this._decoded = maybeSort(mappings, isString);
  358. }
  359. this._decodedMemo = memoizedState();
  360. this._bySources = undefined;
  361. this._bySourceMemos = undefined;
  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. const segments = decoded[line];
  379. const index = traceSegmentInternal(segments, map._decodedMemo, line, column, GREATEST_LOWER_BOUND);
  380. return index === -1 ? null : segments[index];
  381. };
  382. originalPositionFor = (map, { line, column, bias }) => {
  383. line--;
  384. if (line < 0)
  385. throw new Error(LINE_GTR_ZERO);
  386. if (column < 0)
  387. throw new Error(COL_GTR_EQ_ZERO);
  388. const decoded = decodedMappings(map);
  389. // It's common for parent source maps to have pointers to lines that have no
  390. // mapping (like a "//# sourceMappingURL=") at the end of the child file.
  391. if (line >= decoded.length)
  392. return OMapping(null, null, null, null);
  393. const segments = decoded[line];
  394. const index = traceSegmentInternal(segments, map._decodedMemo, line, column, bias || GREATEST_LOWER_BOUND);
  395. if (index === -1)
  396. return OMapping(null, null, null, null);
  397. const segment = segments[index];
  398. if (segment.length === 1)
  399. return OMapping(null, null, null, null);
  400. const { names, resolvedSources } = map;
  401. return OMapping(resolvedSources[segment[SOURCES_INDEX]], segment[SOURCE_LINE] + 1, segment[SOURCE_COLUMN], segment.length === 5 ? names[segment[NAMES_INDEX]] : null);
  402. };
  403. allGeneratedPositionsFor = (map, { source, line, column, bias }) => {
  404. // SourceMapConsumer uses LEAST_UPPER_BOUND for some reason, so we follow suit.
  405. return generatedPosition(map, source, line, column, bias || LEAST_UPPER_BOUND, true);
  406. };
  407. generatedPositionFor = (map, { source, line, column, bias }) => {
  408. return generatedPosition(map, source, line, column, bias || GREATEST_LOWER_BOUND, false);
  409. };
  410. eachMapping = (map, cb) => {
  411. const decoded = decodedMappings(map);
  412. const { names, resolvedSources } = map;
  413. for (let i = 0; i < decoded.length; i++) {
  414. const line = decoded[i];
  415. for (let j = 0; j < line.length; j++) {
  416. const seg = line[j];
  417. const generatedLine = i + 1;
  418. const generatedColumn = seg[0];
  419. let source = null;
  420. let originalLine = null;
  421. let originalColumn = null;
  422. let name = null;
  423. if (seg.length !== 1) {
  424. source = resolvedSources[seg[1]];
  425. originalLine = seg[2] + 1;
  426. originalColumn = seg[3];
  427. }
  428. if (seg.length === 5)
  429. name = names[seg[4]];
  430. cb({
  431. generatedLine,
  432. generatedColumn,
  433. source,
  434. originalLine,
  435. originalColumn,
  436. name,
  437. });
  438. }
  439. }
  440. };
  441. sourceContentFor = (map, source) => {
  442. const { sources, resolvedSources, sourcesContent } = map;
  443. if (sourcesContent == null)
  444. return null;
  445. let index = sources.indexOf(source);
  446. if (index === -1)
  447. index = resolvedSources.indexOf(source);
  448. return index === -1 ? null : sourcesContent[index];
  449. };
  450. presortedDecodedMap = (map, mapUrl) => {
  451. const tracer = new TraceMap(clone(map, []), mapUrl);
  452. tracer._decoded = map.mappings;
  453. return tracer;
  454. };
  455. decodedMap = (map) => {
  456. return clone(map, decodedMappings(map));
  457. };
  458. encodedMap = (map) => {
  459. return clone(map, encodedMappings(map));
  460. };
  461. function generatedPosition(map, source, line, column, bias, all) {
  462. line--;
  463. if (line < 0)
  464. throw new Error(LINE_GTR_ZERO);
  465. if (column < 0)
  466. throw new Error(COL_GTR_EQ_ZERO);
  467. const { sources, resolvedSources } = map;
  468. let sourceIndex = sources.indexOf(source);
  469. if (sourceIndex === -1)
  470. sourceIndex = resolvedSources.indexOf(source);
  471. if (sourceIndex === -1)
  472. return all ? [] : GMapping(null, null);
  473. const generated = (map._bySources || (map._bySources = buildBySources(decodedMappings(map), (map._bySourceMemos = sources.map(memoizedState)))));
  474. const segments = generated[sourceIndex][line];
  475. if (segments == null)
  476. return all ? [] : GMapping(null, null);
  477. const memo = map._bySourceMemos[sourceIndex];
  478. if (all)
  479. return sliceGeneratedPositions(segments, memo, line, column, bias);
  480. const index = traceSegmentInternal(segments, memo, line, column, bias);
  481. if (index === -1)
  482. return GMapping(null, null);
  483. const segment = segments[index];
  484. return GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN]);
  485. }
  486. })();
  487. function clone(map, mappings) {
  488. return {
  489. version: map.version,
  490. file: map.file,
  491. names: map.names,
  492. sourceRoot: map.sourceRoot,
  493. sources: map.sources,
  494. sourcesContent: map.sourcesContent,
  495. mappings,
  496. };
  497. }
  498. function OMapping(source, line, column, name) {
  499. return { source, line, column, name };
  500. }
  501. function GMapping(line, column) {
  502. return { line, column };
  503. }
  504. function traceSegmentInternal(segments, memo, line, column, bias) {
  505. let index = memoizedBinarySearch(segments, column, memo, line);
  506. if (found) {
  507. index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index);
  508. }
  509. else if (bias === LEAST_UPPER_BOUND)
  510. index++;
  511. if (index === -1 || index === segments.length)
  512. return -1;
  513. return index;
  514. }
  515. function sliceGeneratedPositions(segments, memo, line, column, bias) {
  516. let min = traceSegmentInternal(segments, memo, line, column, GREATEST_LOWER_BOUND);
  517. // We ignored the bias when tracing the segment so that we're guarnateed to find the first (in
  518. // insertion order) segment that matched. Even if we did respect the bias when tracing, we would
  519. // still need to call `lowerBound()` to find the first segment, which is slower than just looking
  520. // for the GREATEST_LOWER_BOUND to begin with. The only difference that matters for us is when the
  521. // binary search didn't match, in which case GREATEST_LOWER_BOUND just needs to increment to
  522. // match LEAST_UPPER_BOUND.
  523. if (!found && bias === LEAST_UPPER_BOUND)
  524. min++;
  525. if (min === -1 || min === segments.length)
  526. return [];
  527. // We may have found the segment that started at an earlier column. If this is the case, then we
  528. // need to slice all generated segments that match _that_ column, because all such segments span
  529. // to our desired column.
  530. const matchedColumn = found ? column : segments[min][COLUMN];
  531. // The binary search is not guaranteed to find the lower bound when a match wasn't found.
  532. if (!found)
  533. min = lowerBound(segments, matchedColumn, min);
  534. const max = upperBound(segments, matchedColumn, min);
  535. const result = [];
  536. for (; min <= max; min++) {
  537. const segment = segments[min];
  538. result.push(GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN]));
  539. }
  540. return result;
  541. }
  542. export { AnyMap, GREATEST_LOWER_BOUND, LEAST_UPPER_BOUND, TraceMap, allGeneratedPositionsFor, decodedMap, decodedMappings, eachMapping, encodedMap, encodedMappings, generatedPositionFor, originalPositionFor, presortedDecodedMap, sourceContentFor, traceSegment };
  543. //# sourceMappingURL=trace-mapping.mjs.map