trace-mapping.mjs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  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; i++, index++) {
  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; i--, index--) {
  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. const { sections } = parsed;
  193. let i = 0;
  194. for (; i < sections.length - 1; i++) {
  195. const no = sections[i + 1].offset;
  196. addSection(sections[i], mapUrl, mappings, sources, sourcesContent, names, no.line, no.column);
  197. }
  198. if (sections.length > 0) {
  199. addSection(sections[i], mapUrl, mappings, sources, sourcesContent, names, Infinity, Infinity);
  200. }
  201. const joined = {
  202. version: 3,
  203. file: parsed.file,
  204. names,
  205. sources,
  206. sourcesContent,
  207. mappings,
  208. };
  209. return presortedDecodedMap(joined);
  210. };
  211. function addSection(section, mapUrl, mappings, sources, sourcesContent, names, stopLine, stopColumn) {
  212. const map = AnyMap(section.map, mapUrl);
  213. const { line: lineOffset, column: columnOffset } = section.offset;
  214. const sourcesOffset = sources.length;
  215. const namesOffset = names.length;
  216. const decoded = decodedMappings(map);
  217. const { resolvedSources } = map;
  218. append(sources, resolvedSources);
  219. append(sourcesContent, map.sourcesContent || fillSourcesContent(resolvedSources.length));
  220. append(names, map.names);
  221. // If this section jumps forwards several lines, we need to add lines to the output mappings catch up.
  222. for (let i = mappings.length; i <= lineOffset; i++)
  223. mappings.push([]);
  224. // We can only add so many lines before we step into the range that the next section's map
  225. // controls. When we get to the last line, then we'll start checking the segments to see if
  226. // they've crossed into the column range.
  227. const stopI = stopLine - lineOffset;
  228. const len = Math.min(decoded.length, stopI + 1);
  229. for (let i = 0; i < len; i++) {
  230. const line = decoded[i];
  231. // On the 0th loop, the line will already exist due to a previous section, or the line catch up
  232. // loop above.
  233. const out = i === 0 ? mappings[lineOffset] : (mappings[lineOffset + i] = []);
  234. // On the 0th loop, the section's column offset shifts us forward. On all other lines (since the
  235. // map can be multiple lines), it doesn't.
  236. const cOffset = i === 0 ? columnOffset : 0;
  237. for (let j = 0; j < line.length; j++) {
  238. const seg = line[j];
  239. const column = cOffset + seg[COLUMN];
  240. // If this segment steps into the column range that the next section's map controls, we need
  241. // to stop early.
  242. if (i === stopI && column >= stopColumn)
  243. break;
  244. if (seg.length === 1) {
  245. out.push([column]);
  246. continue;
  247. }
  248. const sourcesIndex = sourcesOffset + seg[SOURCES_INDEX];
  249. const sourceLine = seg[SOURCE_LINE];
  250. const sourceColumn = seg[SOURCE_COLUMN];
  251. if (seg.length === 4) {
  252. out.push([column, sourcesIndex, sourceLine, sourceColumn]);
  253. continue;
  254. }
  255. out.push([column, sourcesIndex, sourceLine, sourceColumn, namesOffset + seg[NAMES_INDEX]]);
  256. }
  257. }
  258. }
  259. function append(arr, other) {
  260. for (let i = 0; i < other.length; i++)
  261. arr.push(other[i]);
  262. }
  263. // Sourcemaps don't need to have sourcesContent, and if they don't, we need to create an array of
  264. // equal length to the sources. This is because the sources and sourcesContent are paired arrays,
  265. // where `sourcesContent[i]` is the content of the `sources[i]` file. If we didn't, then joined
  266. // sourcemap would desynchronize the sources/contents.
  267. function fillSourcesContent(len) {
  268. const sourcesContent = [];
  269. for (let i = 0; i < len; i++)
  270. sourcesContent[i] = null;
  271. return sourcesContent;
  272. }
  273. const INVALID_ORIGINAL_MAPPING = Object.freeze({
  274. source: null,
  275. line: null,
  276. column: null,
  277. name: null,
  278. });
  279. const INVALID_GENERATED_MAPPING = Object.freeze({
  280. line: null,
  281. column: null,
  282. });
  283. const LINE_GTR_ZERO = '`line` must be greater than 0 (lines start at line 1)';
  284. const COL_GTR_EQ_ZERO = '`column` must be greater than or equal to 0 (columns start at column 0)';
  285. const LEAST_UPPER_BOUND = -1;
  286. const GREATEST_LOWER_BOUND = 1;
  287. /**
  288. * Returns the encoded (VLQ string) form of the SourceMap's mappings field.
  289. */
  290. let encodedMappings;
  291. /**
  292. * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field.
  293. */
  294. let decodedMappings;
  295. /**
  296. * A low-level API to find the segment associated with a generated line/column (think, from a
  297. * stack trace). Line and column here are 0-based, unlike `originalPositionFor`.
  298. */
  299. let traceSegment;
  300. /**
  301. * A higher-level API to find the source/line/column associated with a generated line/column
  302. * (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in
  303. * `source-map` library.
  304. */
  305. let originalPositionFor;
  306. /**
  307. * Finds the source/line/column directly after the mapping returned by originalPositionFor, provided
  308. * the found mapping is from the same source and line as the originalPositionFor mapping.
  309. *
  310. * Eg, in the code `let id = 1`, `originalPositionAfter` could find the mapping associated with `1`
  311. * using the same needle that would return `id` when calling `originalPositionFor`.
  312. */
  313. let generatedPositionFor;
  314. /**
  315. * Iterates each mapping in generated position order.
  316. */
  317. let eachMapping;
  318. /**
  319. * A helper that skips sorting of the input map's mappings array, which can be expensive for larger
  320. * maps.
  321. */
  322. let presortedDecodedMap;
  323. /**
  324. * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects
  325. * a sourcemap, or to JSON.stringify.
  326. */
  327. let decodedMap;
  328. /**
  329. * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects
  330. * a sourcemap, or to JSON.stringify.
  331. */
  332. let encodedMap;
  333. class TraceMap {
  334. constructor(map, mapUrl) {
  335. this._decodedMemo = memoizedState();
  336. this._bySources = undefined;
  337. this._bySourceMemos = undefined;
  338. const isString = typeof map === 'string';
  339. if (!isString && map.constructor === TraceMap)
  340. return map;
  341. const parsed = (isString ? JSON.parse(map) : map);
  342. const { version, file, names, sourceRoot, sources, sourcesContent } = parsed;
  343. this.version = version;
  344. this.file = file;
  345. this.names = names;
  346. this.sourceRoot = sourceRoot;
  347. this.sources = sources;
  348. this.sourcesContent = sourcesContent;
  349. if (sourceRoot || mapUrl) {
  350. const from = resolve(sourceRoot || '', stripFilename(mapUrl));
  351. this.resolvedSources = sources.map((s) => resolve(s || '', from));
  352. }
  353. else {
  354. this.resolvedSources = sources.map((s) => s || '');
  355. }
  356. const { mappings } = parsed;
  357. if (typeof mappings === 'string') {
  358. this._encoded = mappings;
  359. this._decoded = undefined;
  360. }
  361. else {
  362. this._encoded = undefined;
  363. this._decoded = maybeSort(mappings, isString);
  364. }
  365. }
  366. }
  367. (() => {
  368. encodedMappings = (map) => {
  369. var _a;
  370. return ((_a = map._encoded) !== null && _a !== void 0 ? _a : (map._encoded = encode(map._decoded)));
  371. };
  372. decodedMappings = (map) => {
  373. return (map._decoded || (map._decoded = decode(map._encoded)));
  374. };
  375. traceSegment = (map, line, column) => {
  376. const decoded = decodedMappings(map);
  377. // It's common for parent source maps to have pointers to lines that have no
  378. // mapping (like a "//# sourceMappingURL=") at the end of the child file.
  379. if (line >= decoded.length)
  380. return null;
  381. return traceSegmentInternal(decoded[line], map._decodedMemo, line, column, GREATEST_LOWER_BOUND);
  382. };
  383. originalPositionFor = (map, { line, column, bias }) => {
  384. line--;
  385. if (line < 0)
  386. throw new Error(LINE_GTR_ZERO);
  387. if (column < 0)
  388. throw new Error(COL_GTR_EQ_ZERO);
  389. const decoded = decodedMappings(map);
  390. // It's common for parent source maps to have pointers to lines that have no
  391. // mapping (like a "//# sourceMappingURL=") at the end of the child file.
  392. if (line >= decoded.length)
  393. return INVALID_ORIGINAL_MAPPING;
  394. const segment = traceSegmentInternal(decoded[line], map._decodedMemo, line, column, bias || GREATEST_LOWER_BOUND);
  395. if (segment == null)
  396. return INVALID_ORIGINAL_MAPPING;
  397. if (segment.length == 1)
  398. return INVALID_ORIGINAL_MAPPING;
  399. const { names, resolvedSources } = map;
  400. return {
  401. source: resolvedSources[segment[SOURCES_INDEX]],
  402. line: segment[SOURCE_LINE] + 1,
  403. column: segment[SOURCE_COLUMN],
  404. name: segment.length === 5 ? names[segment[NAMES_INDEX]] : null,
  405. };
  406. };
  407. generatedPositionFor = (map, { source, line, column, bias }) => {
  408. line--;
  409. if (line < 0)
  410. throw new Error(LINE_GTR_ZERO);
  411. if (column < 0)
  412. throw new Error(COL_GTR_EQ_ZERO);
  413. const { sources, resolvedSources } = map;
  414. let sourceIndex = sources.indexOf(source);
  415. if (sourceIndex === -1)
  416. sourceIndex = resolvedSources.indexOf(source);
  417. if (sourceIndex === -1)
  418. return INVALID_GENERATED_MAPPING;
  419. const generated = (map._bySources || (map._bySources = buildBySources(decodedMappings(map), (map._bySourceMemos = sources.map(memoizedState)))));
  420. const memos = map._bySourceMemos;
  421. const segments = generated[sourceIndex][line];
  422. if (segments == null)
  423. return INVALID_GENERATED_MAPPING;
  424. const segment = traceSegmentInternal(segments, memos[sourceIndex], line, column, bias || GREATEST_LOWER_BOUND);
  425. if (segment == null)
  426. return INVALID_GENERATED_MAPPING;
  427. return {
  428. line: segment[REV_GENERATED_LINE] + 1,
  429. column: segment[REV_GENERATED_COLUMN],
  430. };
  431. };
  432. eachMapping = (map, cb) => {
  433. const decoded = decodedMappings(map);
  434. const { names, resolvedSources } = map;
  435. for (let i = 0; i < decoded.length; i++) {
  436. const line = decoded[i];
  437. for (let j = 0; j < line.length; j++) {
  438. const seg = line[j];
  439. const generatedLine = i + 1;
  440. const generatedColumn = seg[0];
  441. let source = null;
  442. let originalLine = null;
  443. let originalColumn = null;
  444. let name = null;
  445. if (seg.length !== 1) {
  446. source = resolvedSources[seg[1]];
  447. originalLine = seg[2] + 1;
  448. originalColumn = seg[3];
  449. }
  450. if (seg.length === 5)
  451. name = names[seg[4]];
  452. cb({
  453. generatedLine,
  454. generatedColumn,
  455. source,
  456. originalLine,
  457. originalColumn,
  458. name,
  459. });
  460. }
  461. }
  462. };
  463. presortedDecodedMap = (map, mapUrl) => {
  464. const clone = Object.assign({}, map);
  465. clone.mappings = [];
  466. const tracer = new TraceMap(clone, mapUrl);
  467. tracer._decoded = map.mappings;
  468. return tracer;
  469. };
  470. decodedMap = (map) => {
  471. return {
  472. version: 3,
  473. file: map.file,
  474. names: map.names,
  475. sourceRoot: map.sourceRoot,
  476. sources: map.sources,
  477. sourcesContent: map.sourcesContent,
  478. mappings: decodedMappings(map),
  479. };
  480. };
  481. encodedMap = (map) => {
  482. return {
  483. version: 3,
  484. file: map.file,
  485. names: map.names,
  486. sourceRoot: map.sourceRoot,
  487. sources: map.sources,
  488. sourcesContent: map.sourcesContent,
  489. mappings: encodedMappings(map),
  490. };
  491. };
  492. })();
  493. function traceSegmentInternal(segments, memo, line, column, bias) {
  494. let index = memoizedBinarySearch(segments, column, memo, line);
  495. if (found) {
  496. index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index);
  497. }
  498. else if (bias === LEAST_UPPER_BOUND)
  499. index++;
  500. if (index === -1 || index === segments.length)
  501. return null;
  502. return segments[index];
  503. }
  504. export { AnyMap, GREATEST_LOWER_BOUND, LEAST_UPPER_BOUND, TraceMap, decodedMap, decodedMappings, eachMapping, encodedMap, encodedMappings, generatedPositionFor, originalPositionFor, presortedDecodedMap, traceSegment };
  505. //# sourceMappingURL=trace-mapping.mjs.map