remapping.mjs 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. import { decodedMappings, traceSegment, TraceMap } from '@jridgewell/trace-mapping';
  2. import { GenMapping, maybeAddSegment, setSourceContent, setIgnore, toDecodedMap, toEncodedMap } from '@jridgewell/gen-mapping';
  3. const SOURCELESS_MAPPING = /* #__PURE__ */ SegmentObject('', -1, -1, '', null, false);
  4. const EMPTY_SOURCES = [];
  5. function SegmentObject(source, line, column, name, content, ignore) {
  6. return { source, line, column, name, content, ignore };
  7. }
  8. function Source(map, sources, source, content, ignore) {
  9. return {
  10. map,
  11. sources,
  12. source,
  13. content,
  14. ignore,
  15. };
  16. }
  17. /**
  18. * MapSource represents a single sourcemap, with the ability to trace mappings into its child nodes
  19. * (which may themselves be SourceMapTrees).
  20. */
  21. function MapSource(map, sources) {
  22. return Source(map, sources, '', null, false);
  23. }
  24. /**
  25. * A "leaf" node in the sourcemap tree, representing an original, unmodified source file. Recursive
  26. * segment tracing ends at the `OriginalSource`.
  27. */
  28. function OriginalSource(source, content, ignore) {
  29. return Source(null, EMPTY_SOURCES, source, content, ignore);
  30. }
  31. /**
  32. * traceMappings is only called on the root level SourceMapTree, and begins the process of
  33. * resolving each mapping in terms of the original source files.
  34. */
  35. function traceMappings(tree) {
  36. // TODO: Eventually support sourceRoot, which has to be removed because the sources are already
  37. // fully resolved. We'll need to make sources relative to the sourceRoot before adding them.
  38. const gen = new GenMapping({ file: tree.map.file });
  39. const { sources: rootSources, map } = tree;
  40. const rootNames = map.names;
  41. const rootMappings = decodedMappings(map);
  42. for (let i = 0; i < rootMappings.length; i++) {
  43. const segments = rootMappings[i];
  44. for (let j = 0; j < segments.length; j++) {
  45. const segment = segments[j];
  46. const genCol = segment[0];
  47. let traced = SOURCELESS_MAPPING;
  48. // 1-length segments only move the current generated column, there's no source information
  49. // to gather from it.
  50. if (segment.length !== 1) {
  51. const source = rootSources[segment[1]];
  52. traced = originalPositionFor(source, segment[2], segment[3], segment.length === 5 ? rootNames[segment[4]] : '');
  53. // If the trace is invalid, then the trace ran into a sourcemap that doesn't contain a
  54. // respective segment into an original source.
  55. if (traced == null)
  56. continue;
  57. }
  58. const { column, line, name, content, source, ignore } = traced;
  59. maybeAddSegment(gen, i, genCol, source, line, column, name);
  60. if (source && content != null)
  61. setSourceContent(gen, source, content);
  62. if (ignore)
  63. setIgnore(gen, source, true);
  64. }
  65. }
  66. return gen;
  67. }
  68. /**
  69. * originalPositionFor is only called on children SourceMapTrees. It recurses down into its own
  70. * child SourceMapTrees, until we find the original source map.
  71. */
  72. function originalPositionFor(source, line, column, name) {
  73. if (!source.map) {
  74. return SegmentObject(source.source, line, column, name, source.content, source.ignore);
  75. }
  76. const segment = traceSegment(source.map, line, column);
  77. // If we couldn't find a segment, then this doesn't exist in the sourcemap.
  78. if (segment == null)
  79. return null;
  80. // 1-length segments only move the current generated column, there's no source information
  81. // to gather from it.
  82. if (segment.length === 1)
  83. return SOURCELESS_MAPPING;
  84. return originalPositionFor(source.sources[segment[1]], segment[2], segment[3], segment.length === 5 ? source.map.names[segment[4]] : name);
  85. }
  86. function asArray(value) {
  87. if (Array.isArray(value))
  88. return value;
  89. return [value];
  90. }
  91. /**
  92. * Recursively builds a tree structure out of sourcemap files, with each node
  93. * being either an `OriginalSource` "leaf" or a `SourceMapTree` composed of
  94. * `OriginalSource`s and `SourceMapTree`s.
  95. *
  96. * Every sourcemap is composed of a collection of source files and mappings
  97. * into locations of those source files. When we generate a `SourceMapTree` for
  98. * the sourcemap, we attempt to load each source file's own sourcemap. If it
  99. * does not have an associated sourcemap, it is considered an original,
  100. * unmodified source file.
  101. */
  102. function buildSourceMapTree(input, loader) {
  103. const maps = asArray(input).map((m) => new TraceMap(m, ''));
  104. const map = maps.pop();
  105. for (let i = 0; i < maps.length; i++) {
  106. if (maps[i].sources.length > 1) {
  107. throw new Error(`Transformation map ${i} must have exactly one source file.\n` +
  108. 'Did you specify these with the most recent transformation maps first?');
  109. }
  110. }
  111. let tree = build(map, loader, '', 0);
  112. for (let i = maps.length - 1; i >= 0; i--) {
  113. tree = MapSource(maps[i], [tree]);
  114. }
  115. return tree;
  116. }
  117. function build(map, loader, importer, importerDepth) {
  118. const { resolvedSources, sourcesContent, ignoreList } = map;
  119. const depth = importerDepth + 1;
  120. const children = resolvedSources.map((sourceFile, i) => {
  121. // The loading context gives the loader more information about why this file is being loaded
  122. // (eg, from which importer). It also allows the loader to override the location of the loaded
  123. // sourcemap/original source, or to override the content in the sourcesContent field if it's
  124. // an unmodified source file.
  125. const ctx = {
  126. importer,
  127. depth,
  128. source: sourceFile || '',
  129. content: undefined,
  130. ignore: undefined,
  131. };
  132. // Use the provided loader callback to retrieve the file's sourcemap.
  133. // TODO: We should eventually support async loading of sourcemap files.
  134. const sourceMap = loader(ctx.source, ctx);
  135. const { source, content, ignore } = ctx;
  136. // If there is a sourcemap, then we need to recurse into it to load its source files.
  137. if (sourceMap)
  138. return build(new TraceMap(sourceMap, source), loader, source, depth);
  139. // Else, it's an unmodified source file.
  140. // The contents of this unmodified source file can be overridden via the loader context,
  141. // allowing it to be explicitly null or a string. If it remains undefined, we fall back to
  142. // the importing sourcemap's `sourcesContent` field.
  143. const sourceContent = content !== undefined ? content : sourcesContent ? sourcesContent[i] : null;
  144. const ignored = ignore !== undefined ? ignore : ignoreList ? ignoreList.includes(i) : false;
  145. return OriginalSource(source, sourceContent, ignored);
  146. });
  147. return MapSource(map, children);
  148. }
  149. /**
  150. * A SourceMap v3 compatible sourcemap, which only includes fields that were
  151. * provided to it.
  152. */
  153. class SourceMap {
  154. constructor(map, options) {
  155. const out = options.decodedMappings ? toDecodedMap(map) : toEncodedMap(map);
  156. this.version = out.version; // SourceMap spec says this should be first.
  157. this.file = out.file;
  158. this.mappings = out.mappings;
  159. this.names = out.names;
  160. this.ignoreList = out.ignoreList;
  161. this.sourceRoot = out.sourceRoot;
  162. this.sources = out.sources;
  163. if (!options.excludeContent) {
  164. this.sourcesContent = out.sourcesContent;
  165. }
  166. }
  167. toString() {
  168. return JSON.stringify(this);
  169. }
  170. }
  171. /**
  172. * Traces through all the mappings in the root sourcemap, through the sources
  173. * (and their sourcemaps), all the way back to the original source location.
  174. *
  175. * `loader` will be called every time we encounter a source file. If it returns
  176. * a sourcemap, we will recurse into that sourcemap to continue the trace. If
  177. * it returns a falsey value, that source file is treated as an original,
  178. * unmodified source file.
  179. *
  180. * Pass `excludeContent` to exclude any self-containing source file content
  181. * from the output sourcemap.
  182. *
  183. * Pass `decodedMappings` to receive a SourceMap with decoded (instead of
  184. * VLQ encoded) mappings.
  185. */
  186. function remapping(input, loader, options) {
  187. const opts = typeof options === 'object' ? options : { excludeContent: !!options, decodedMappings: false };
  188. const tree = buildSourceMapTree(input, loader);
  189. return new SourceMap(traceMappings(tree), opts);
  190. }
  191. export { remapping as default };
  192. //# sourceMappingURL=remapping.mjs.map