source-map-consumer.js 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184
  1. /* -*- Mode: js; js-indent-level: 2; -*- */
  2. /*
  3. * Copyright 2011 Mozilla Foundation and contributors
  4. * Licensed under the New BSD license. See LICENSE or:
  5. * http://opensource.org/licenses/BSD-3-Clause
  6. */
  7. var util = require('./util');
  8. var binarySearch = require('./binary-search');
  9. var ArraySet = require('./array-set').ArraySet;
  10. var base64VLQ = require('./base64-vlq');
  11. var quickSort = require('./quick-sort').quickSort;
  12. function SourceMapConsumer(aSourceMap, aSourceMapURL) {
  13. var sourceMap = aSourceMap;
  14. if (typeof aSourceMap === 'string') {
  15. sourceMap = util.parseSourceMapInput(aSourceMap);
  16. }
  17. return sourceMap.sections != null
  18. ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL)
  19. : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);
  20. }
  21. SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) {
  22. return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);
  23. }
  24. /**
  25. * The version of the source mapping spec that we are consuming.
  26. */
  27. SourceMapConsumer.prototype._version = 3;
  28. // `__generatedMappings` and `__originalMappings` are arrays that hold the
  29. // parsed mapping coordinates from the source map's "mappings" attribute. They
  30. // are lazily instantiated, accessed via the `_generatedMappings` and
  31. // `_originalMappings` getters respectively, and we only parse the mappings
  32. // and create these arrays once queried for a source location. We jump through
  33. // these hoops because there can be many thousands of mappings, and parsing
  34. // them is expensive, so we only want to do it if we must.
  35. //
  36. // Each object in the arrays is of the form:
  37. //
  38. // {
  39. // generatedLine: The line number in the generated code,
  40. // generatedColumn: The column number in the generated code,
  41. // source: The path to the original source file that generated this
  42. // chunk of code,
  43. // originalLine: The line number in the original source that
  44. // corresponds to this chunk of generated code,
  45. // originalColumn: The column number in the original source that
  46. // corresponds to this chunk of generated code,
  47. // name: The name of the original symbol which generated this chunk of
  48. // code.
  49. // }
  50. //
  51. // All properties except for `generatedLine` and `generatedColumn` can be
  52. // `null`.
  53. //
  54. // `_generatedMappings` is ordered by the generated positions.
  55. //
  56. // `_originalMappings` is ordered by the original positions.
  57. SourceMapConsumer.prototype.__generatedMappings = null;
  58. Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {
  59. configurable: true,
  60. enumerable: true,
  61. get: function () {
  62. if (!this.__generatedMappings) {
  63. this._parseMappings(this._mappings, this.sourceRoot);
  64. }
  65. return this.__generatedMappings;
  66. }
  67. });
  68. SourceMapConsumer.prototype.__originalMappings = null;
  69. Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {
  70. configurable: true,
  71. enumerable: true,
  72. get: function () {
  73. if (!this.__originalMappings) {
  74. this._parseMappings(this._mappings, this.sourceRoot);
  75. }
  76. return this.__originalMappings;
  77. }
  78. });
  79. SourceMapConsumer.prototype._charIsMappingSeparator =
  80. function SourceMapConsumer_charIsMappingSeparator(aStr, index) {
  81. var c = aStr.charAt(index);
  82. return c === ";" || c === ",";
  83. };
  84. /**
  85. * Parse the mappings in a string in to a data structure which we can easily
  86. * query (the ordered arrays in the `this.__generatedMappings` and
  87. * `this.__originalMappings` properties).
  88. */
  89. SourceMapConsumer.prototype._parseMappings =
  90. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  91. throw new Error("Subclasses must implement _parseMappings");
  92. };
  93. SourceMapConsumer.GENERATED_ORDER = 1;
  94. SourceMapConsumer.ORIGINAL_ORDER = 2;
  95. SourceMapConsumer.GREATEST_LOWER_BOUND = 1;
  96. SourceMapConsumer.LEAST_UPPER_BOUND = 2;
  97. /**
  98. * Iterate over each mapping between an original source/line/column and a
  99. * generated line/column in this source map.
  100. *
  101. * @param Function aCallback
  102. * The function that is called with each mapping.
  103. * @param Object aContext
  104. * Optional. If specified, this object will be the value of `this` every
  105. * time that `aCallback` is called.
  106. * @param aOrder
  107. * Either `SourceMapConsumer.GENERATED_ORDER` or
  108. * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
  109. * iterate over the mappings sorted by the generated file's line/column
  110. * order or the original's source/line/column order, respectively. Defaults to
  111. * `SourceMapConsumer.GENERATED_ORDER`.
  112. */
  113. SourceMapConsumer.prototype.eachMapping =
  114. function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
  115. var context = aContext || null;
  116. var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
  117. var mappings;
  118. switch (order) {
  119. case SourceMapConsumer.GENERATED_ORDER:
  120. mappings = this._generatedMappings;
  121. break;
  122. case SourceMapConsumer.ORIGINAL_ORDER:
  123. mappings = this._originalMappings;
  124. break;
  125. default:
  126. throw new Error("Unknown order of iteration.");
  127. }
  128. var sourceRoot = this.sourceRoot;
  129. var boundCallback = aCallback.bind(context);
  130. var names = this._names;
  131. var sources = this._sources;
  132. var sourceMapURL = this._sourceMapURL;
  133. for (var i = 0, n = mappings.length; i < n; i++) {
  134. var mapping = mappings[i];
  135. var source = mapping.source === null ? null : sources.at(mapping.source);
  136. source = util.computeSourceURL(sourceRoot, source, sourceMapURL);
  137. boundCallback({
  138. source: source,
  139. generatedLine: mapping.generatedLine,
  140. generatedColumn: mapping.generatedColumn,
  141. originalLine: mapping.originalLine,
  142. originalColumn: mapping.originalColumn,
  143. name: mapping.name === null ? null : names.at(mapping.name)
  144. });
  145. }
  146. };
  147. /**
  148. * Returns all generated line and column information for the original source,
  149. * line, and column provided. If no column is provided, returns all mappings
  150. * corresponding to a either the line we are searching for or the next
  151. * closest line that has any mappings. Otherwise, returns all mappings
  152. * corresponding to the given line and either the column we are searching for
  153. * or the next closest column that has any offsets.
  154. *
  155. * The only argument is an object with the following properties:
  156. *
  157. * - source: The filename of the original source.
  158. * - line: The line number in the original source. The line number is 1-based.
  159. * - column: Optional. the column number in the original source.
  160. * The column number is 0-based.
  161. *
  162. * and an array of objects is returned, each with the following properties:
  163. *
  164. * - line: The line number in the generated source, or null. The
  165. * line number is 1-based.
  166. * - column: The column number in the generated source, or null.
  167. * The column number is 0-based.
  168. */
  169. SourceMapConsumer.prototype.allGeneratedPositionsFor =
  170. function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
  171. var line = util.getArg(aArgs, 'line');
  172. // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping
  173. // returns the index of the closest mapping less than the needle. By
  174. // setting needle.originalColumn to 0, we thus find the last mapping for
  175. // the given line, provided such a mapping exists.
  176. var needle = {
  177. source: util.getArg(aArgs, 'source'),
  178. originalLine: line,
  179. originalColumn: util.getArg(aArgs, 'column', 0)
  180. };
  181. needle.source = this._findSourceIndex(needle.source);
  182. if (needle.source < 0) {
  183. return [];
  184. }
  185. var mappings = [];
  186. var index = this._findMapping(needle,
  187. this._originalMappings,
  188. "originalLine",
  189. "originalColumn",
  190. util.compareByOriginalPositions,
  191. binarySearch.LEAST_UPPER_BOUND);
  192. if (index >= 0) {
  193. var mapping = this._originalMappings[index];
  194. if (aArgs.column === undefined) {
  195. var originalLine = mapping.originalLine;
  196. // Iterate until either we run out of mappings, or we run into
  197. // a mapping for a different line than the one we found. Since
  198. // mappings are sorted, this is guaranteed to find all mappings for
  199. // the line we found.
  200. while (mapping && mapping.originalLine === originalLine) {
  201. mappings.push({
  202. line: util.getArg(mapping, 'generatedLine', null),
  203. column: util.getArg(mapping, 'generatedColumn', null),
  204. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  205. });
  206. mapping = this._originalMappings[++index];
  207. }
  208. } else {
  209. var originalColumn = mapping.originalColumn;
  210. // Iterate until either we run out of mappings, or we run into
  211. // a mapping for a different line than the one we were searching for.
  212. // Since mappings are sorted, this is guaranteed to find all mappings for
  213. // the line we are searching for.
  214. while (mapping &&
  215. mapping.originalLine === line &&
  216. mapping.originalColumn == originalColumn) {
  217. mappings.push({
  218. line: util.getArg(mapping, 'generatedLine', null),
  219. column: util.getArg(mapping, 'generatedColumn', null),
  220. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  221. });
  222. mapping = this._originalMappings[++index];
  223. }
  224. }
  225. }
  226. return mappings;
  227. };
  228. exports.SourceMapConsumer = SourceMapConsumer;
  229. /**
  230. * A BasicSourceMapConsumer instance represents a parsed source map which we can
  231. * query for information about the original file positions by giving it a file
  232. * position in the generated source.
  233. *
  234. * The first parameter is the raw source map (either as a JSON string, or
  235. * already parsed to an object). According to the spec, source maps have the
  236. * following attributes:
  237. *
  238. * - version: Which version of the source map spec this map is following.
  239. * - sources: An array of URLs to the original source files.
  240. * - names: An array of identifiers which can be referrenced by individual mappings.
  241. * - sourceRoot: Optional. The URL root from which all sources are relative.
  242. * - sourcesContent: Optional. An array of contents of the original source files.
  243. * - mappings: A string of base64 VLQs which contain the actual mappings.
  244. * - file: Optional. The generated file this source map is associated with.
  245. *
  246. * Here is an example source map, taken from the source map spec[0]:
  247. *
  248. * {
  249. * version : 3,
  250. * file: "out.js",
  251. * sourceRoot : "",
  252. * sources: ["foo.js", "bar.js"],
  253. * names: ["src", "maps", "are", "fun"],
  254. * mappings: "AA,AB;;ABCDE;"
  255. * }
  256. *
  257. * The second parameter, if given, is a string whose value is the URL
  258. * at which the source map was found. This URL is used to compute the
  259. * sources array.
  260. *
  261. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
  262. */
  263. function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {
  264. var sourceMap = aSourceMap;
  265. if (typeof aSourceMap === 'string') {
  266. sourceMap = util.parseSourceMapInput(aSourceMap);
  267. }
  268. var version = util.getArg(sourceMap, 'version');
  269. var sources = util.getArg(sourceMap, 'sources');
  270. // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
  271. // requires the array) to play nice here.
  272. var names = util.getArg(sourceMap, 'names', []);
  273. var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);
  274. var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);
  275. var mappings = util.getArg(sourceMap, 'mappings');
  276. var file = util.getArg(sourceMap, 'file', null);
  277. // Once again, Sass deviates from the spec and supplies the version as a
  278. // string rather than a number, so we use loose equality checking here.
  279. if (version != this._version) {
  280. throw new Error('Unsupported version: ' + version);
  281. }
  282. if (sourceRoot) {
  283. sourceRoot = util.normalize(sourceRoot);
  284. }
  285. sources = sources
  286. .map(String)
  287. // Some source maps produce relative source paths like "./foo.js" instead of
  288. // "foo.js". Normalize these first so that future comparisons will succeed.
  289. // See bugzil.la/1090768.
  290. .map(util.normalize)
  291. // Always ensure that absolute sources are internally stored relative to
  292. // the source root, if the source root is absolute. Not doing this would
  293. // be particularly problematic when the source root is a prefix of the
  294. // source (valid, but why??). See github issue #199 and bugzil.la/1188982.
  295. .map(function (source) {
  296. return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source)
  297. ? util.relative(sourceRoot, source)
  298. : source;
  299. });
  300. // Pass `true` below to allow duplicate names and sources. While source maps
  301. // are intended to be compressed and deduplicated, the TypeScript compiler
  302. // sometimes generates source maps with duplicates in them. See Github issue
  303. // #72 and bugzil.la/889492.
  304. this._names = ArraySet.fromArray(names.map(String), true);
  305. this._sources = ArraySet.fromArray(sources, true);
  306. this._absoluteSources = this._sources.toArray().map(function (s) {
  307. return util.computeSourceURL(sourceRoot, s, aSourceMapURL);
  308. });
  309. this.sourceRoot = sourceRoot;
  310. this.sourcesContent = sourcesContent;
  311. this._mappings = mappings;
  312. this._sourceMapURL = aSourceMapURL;
  313. this.file = file;
  314. }
  315. BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
  316. BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;
  317. /**
  318. * Utility function to find the index of a source. Returns -1 if not
  319. * found.
  320. */
  321. BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {
  322. var relativeSource = aSource;
  323. if (this.sourceRoot != null) {
  324. relativeSource = util.relative(this.sourceRoot, relativeSource);
  325. }
  326. if (this._sources.has(relativeSource)) {
  327. return this._sources.indexOf(relativeSource);
  328. }
  329. // Maybe aSource is an absolute URL as returned by |sources|. In
  330. // this case we can't simply undo the transform.
  331. var i;
  332. for (i = 0; i < this._absoluteSources.length; ++i) {
  333. if (this._absoluteSources[i] == aSource) {
  334. return i;
  335. }
  336. }
  337. return -1;
  338. };
  339. /**
  340. * Create a BasicSourceMapConsumer from a SourceMapGenerator.
  341. *
  342. * @param SourceMapGenerator aSourceMap
  343. * The source map that will be consumed.
  344. * @param String aSourceMapURL
  345. * The URL at which the source map can be found (optional)
  346. * @returns BasicSourceMapConsumer
  347. */
  348. BasicSourceMapConsumer.fromSourceMap =
  349. function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {
  350. var smc = Object.create(BasicSourceMapConsumer.prototype);
  351. var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
  352. var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
  353. smc.sourceRoot = aSourceMap._sourceRoot;
  354. smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
  355. smc.sourceRoot);
  356. smc.file = aSourceMap._file;
  357. smc._sourceMapURL = aSourceMapURL;
  358. smc._absoluteSources = smc._sources.toArray().map(function (s) {
  359. return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);
  360. });
  361. // Because we are modifying the entries (by converting string sources and
  362. // names to indices into the sources and names ArraySets), we have to make
  363. // a copy of the entry or else bad things happen. Shared mutable state
  364. // strikes again! See github issue #191.
  365. var generatedMappings = aSourceMap._mappings.toArray().slice();
  366. var destGeneratedMappings = smc.__generatedMappings = [];
  367. var destOriginalMappings = smc.__originalMappings = [];
  368. for (var i = 0, length = generatedMappings.length; i < length; i++) {
  369. var srcMapping = generatedMappings[i];
  370. var destMapping = new Mapping;
  371. destMapping.generatedLine = srcMapping.generatedLine;
  372. destMapping.generatedColumn = srcMapping.generatedColumn;
  373. if (srcMapping.source) {
  374. destMapping.source = sources.indexOf(srcMapping.source);
  375. destMapping.originalLine = srcMapping.originalLine;
  376. destMapping.originalColumn = srcMapping.originalColumn;
  377. if (srcMapping.name) {
  378. destMapping.name = names.indexOf(srcMapping.name);
  379. }
  380. destOriginalMappings.push(destMapping);
  381. }
  382. destGeneratedMappings.push(destMapping);
  383. }
  384. quickSort(smc.__originalMappings, util.compareByOriginalPositions);
  385. return smc;
  386. };
  387. /**
  388. * The version of the source mapping spec that we are consuming.
  389. */
  390. BasicSourceMapConsumer.prototype._version = 3;
  391. /**
  392. * The list of original sources.
  393. */
  394. Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {
  395. get: function () {
  396. return this._absoluteSources.slice();
  397. }
  398. });
  399. /**
  400. * Provide the JIT with a nice shape / hidden class.
  401. */
  402. function Mapping() {
  403. this.generatedLine = 0;
  404. this.generatedColumn = 0;
  405. this.source = null;
  406. this.originalLine = null;
  407. this.originalColumn = null;
  408. this.name = null;
  409. }
  410. /**
  411. * Parse the mappings in a string in to a data structure which we can easily
  412. * query (the ordered arrays in the `this.__generatedMappings` and
  413. * `this.__originalMappings` properties).
  414. */
  415. const compareGenerated = util.compareByGeneratedPositionsDeflatedNoLine;
  416. function sortGenerated(array, start) {
  417. let l = array.length;
  418. let n = array.length - start;
  419. if (n <= 1) {
  420. return;
  421. } else if (n == 2) {
  422. let a = array[start];
  423. let b = array[start + 1];
  424. if (compareGenerated(a, b) > 0) {
  425. array[start] = b;
  426. array[start + 1] = a;
  427. }
  428. } else if (n < 20) {
  429. for (let i = start; i < l; i++) {
  430. for (let j = i; j > start; j--) {
  431. let a = array[j - 1];
  432. let b = array[j];
  433. if (compareGenerated(a, b) <= 0) {
  434. break;
  435. }
  436. array[j - 1] = b;
  437. array[j] = a;
  438. }
  439. }
  440. } else {
  441. quickSort(array, compareGenerated, start);
  442. }
  443. }
  444. BasicSourceMapConsumer.prototype._parseMappings =
  445. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  446. var generatedLine = 1;
  447. var previousGeneratedColumn = 0;
  448. var previousOriginalLine = 0;
  449. var previousOriginalColumn = 0;
  450. var previousSource = 0;
  451. var previousName = 0;
  452. var length = aStr.length;
  453. var index = 0;
  454. var cachedSegments = {};
  455. var temp = {};
  456. var originalMappings = [];
  457. var generatedMappings = [];
  458. var mapping, str, segment, end, value;
  459. let subarrayStart = 0;
  460. while (index < length) {
  461. if (aStr.charAt(index) === ';') {
  462. generatedLine++;
  463. index++;
  464. previousGeneratedColumn = 0;
  465. sortGenerated(generatedMappings, subarrayStart);
  466. subarrayStart = generatedMappings.length;
  467. }
  468. else if (aStr.charAt(index) === ',') {
  469. index++;
  470. }
  471. else {
  472. mapping = new Mapping();
  473. mapping.generatedLine = generatedLine;
  474. for (end = index; end < length; end++) {
  475. if (this._charIsMappingSeparator(aStr, end)) {
  476. break;
  477. }
  478. }
  479. str = aStr.slice(index, end);
  480. segment = [];
  481. while (index < end) {
  482. base64VLQ.decode(aStr, index, temp);
  483. value = temp.value;
  484. index = temp.rest;
  485. segment.push(value);
  486. }
  487. if (segment.length === 2) {
  488. throw new Error('Found a source, but no line and column');
  489. }
  490. if (segment.length === 3) {
  491. throw new Error('Found a source and line, but no column');
  492. }
  493. // Generated column.
  494. mapping.generatedColumn = previousGeneratedColumn + segment[0];
  495. previousGeneratedColumn = mapping.generatedColumn;
  496. if (segment.length > 1) {
  497. // Original source.
  498. mapping.source = previousSource + segment[1];
  499. previousSource += segment[1];
  500. // Original line.
  501. mapping.originalLine = previousOriginalLine + segment[2];
  502. previousOriginalLine = mapping.originalLine;
  503. // Lines are stored 0-based
  504. mapping.originalLine += 1;
  505. // Original column.
  506. mapping.originalColumn = previousOriginalColumn + segment[3];
  507. previousOriginalColumn = mapping.originalColumn;
  508. if (segment.length > 4) {
  509. // Original name.
  510. mapping.name = previousName + segment[4];
  511. previousName += segment[4];
  512. }
  513. }
  514. generatedMappings.push(mapping);
  515. if (typeof mapping.originalLine === 'number') {
  516. let currentSource = mapping.source;
  517. while (originalMappings.length <= currentSource) {
  518. originalMappings.push(null);
  519. }
  520. if (originalMappings[currentSource] === null) {
  521. originalMappings[currentSource] = [];
  522. }
  523. originalMappings[currentSource].push(mapping);
  524. }
  525. }
  526. }
  527. sortGenerated(generatedMappings, subarrayStart);
  528. this.__generatedMappings = generatedMappings;
  529. for (var i = 0; i < originalMappings.length; i++) {
  530. if (originalMappings[i] != null) {
  531. quickSort(originalMappings[i], util.compareByOriginalPositionsNoSource);
  532. }
  533. }
  534. this.__originalMappings = [].concat(...originalMappings);
  535. };
  536. /**
  537. * Find the mapping that best matches the hypothetical "needle" mapping that
  538. * we are searching for in the given "haystack" of mappings.
  539. */
  540. BasicSourceMapConsumer.prototype._findMapping =
  541. function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
  542. aColumnName, aComparator, aBias) {
  543. // To return the position we are searching for, we must first find the
  544. // mapping for the given position and then return the opposite position it
  545. // points to. Because the mappings are sorted, we can use binary search to
  546. // find the best mapping.
  547. if (aNeedle[aLineName] <= 0) {
  548. throw new TypeError('Line must be greater than or equal to 1, got '
  549. + aNeedle[aLineName]);
  550. }
  551. if (aNeedle[aColumnName] < 0) {
  552. throw new TypeError('Column must be greater than or equal to 0, got '
  553. + aNeedle[aColumnName]);
  554. }
  555. return binarySearch.search(aNeedle, aMappings, aComparator, aBias);
  556. };
  557. /**
  558. * Compute the last column for each generated mapping. The last column is
  559. * inclusive.
  560. */
  561. BasicSourceMapConsumer.prototype.computeColumnSpans =
  562. function SourceMapConsumer_computeColumnSpans() {
  563. for (var index = 0; index < this._generatedMappings.length; ++index) {
  564. var mapping = this._generatedMappings[index];
  565. // Mappings do not contain a field for the last generated columnt. We
  566. // can come up with an optimistic estimate, however, by assuming that
  567. // mappings are contiguous (i.e. given two consecutive mappings, the
  568. // first mapping ends where the second one starts).
  569. if (index + 1 < this._generatedMappings.length) {
  570. var nextMapping = this._generatedMappings[index + 1];
  571. if (mapping.generatedLine === nextMapping.generatedLine) {
  572. mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
  573. continue;
  574. }
  575. }
  576. // The last mapping for each line spans the entire line.
  577. mapping.lastGeneratedColumn = Infinity;
  578. }
  579. };
  580. /**
  581. * Returns the original source, line, and column information for the generated
  582. * source's line and column positions provided. The only argument is an object
  583. * with the following properties:
  584. *
  585. * - line: The line number in the generated source. The line number
  586. * is 1-based.
  587. * - column: The column number in the generated source. The column
  588. * number is 0-based.
  589. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  590. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  591. * closest element that is smaller than or greater than the one we are
  592. * searching for, respectively, if the exact element cannot be found.
  593. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  594. *
  595. * and an object is returned with the following properties:
  596. *
  597. * - source: The original source file, or null.
  598. * - line: The line number in the original source, or null. The
  599. * line number is 1-based.
  600. * - column: The column number in the original source, or null. The
  601. * column number is 0-based.
  602. * - name: The original identifier, or null.
  603. */
  604. BasicSourceMapConsumer.prototype.originalPositionFor =
  605. function SourceMapConsumer_originalPositionFor(aArgs) {
  606. var needle = {
  607. generatedLine: util.getArg(aArgs, 'line'),
  608. generatedColumn: util.getArg(aArgs, 'column')
  609. };
  610. var index = this._findMapping(
  611. needle,
  612. this._generatedMappings,
  613. "generatedLine",
  614. "generatedColumn",
  615. util.compareByGeneratedPositionsDeflated,
  616. util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
  617. );
  618. if (index >= 0) {
  619. var mapping = this._generatedMappings[index];
  620. if (mapping.generatedLine === needle.generatedLine) {
  621. var source = util.getArg(mapping, 'source', null);
  622. if (source !== null) {
  623. source = this._sources.at(source);
  624. source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);
  625. }
  626. var name = util.getArg(mapping, 'name', null);
  627. if (name !== null) {
  628. name = this._names.at(name);
  629. }
  630. return {
  631. source: source,
  632. line: util.getArg(mapping, 'originalLine', null),
  633. column: util.getArg(mapping, 'originalColumn', null),
  634. name: name
  635. };
  636. }
  637. }
  638. return {
  639. source: null,
  640. line: null,
  641. column: null,
  642. name: null
  643. };
  644. };
  645. /**
  646. * Return true if we have the source content for every source in the source
  647. * map, false otherwise.
  648. */
  649. BasicSourceMapConsumer.prototype.hasContentsOfAllSources =
  650. function BasicSourceMapConsumer_hasContentsOfAllSources() {
  651. if (!this.sourcesContent) {
  652. return false;
  653. }
  654. return this.sourcesContent.length >= this._sources.size() &&
  655. !this.sourcesContent.some(function (sc) { return sc == null; });
  656. };
  657. /**
  658. * Returns the original source content. The only argument is the url of the
  659. * original source file. Returns null if no original source content is
  660. * available.
  661. */
  662. BasicSourceMapConsumer.prototype.sourceContentFor =
  663. function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  664. if (!this.sourcesContent) {
  665. return null;
  666. }
  667. var index = this._findSourceIndex(aSource);
  668. if (index >= 0) {
  669. return this.sourcesContent[index];
  670. }
  671. var relativeSource = aSource;
  672. if (this.sourceRoot != null) {
  673. relativeSource = util.relative(this.sourceRoot, relativeSource);
  674. }
  675. var url;
  676. if (this.sourceRoot != null
  677. && (url = util.urlParse(this.sourceRoot))) {
  678. // XXX: file:// URIs and absolute paths lead to unexpected behavior for
  679. // many users. We can help them out when they expect file:// URIs to
  680. // behave like it would if they were running a local HTTP server. See
  681. // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
  682. var fileUriAbsPath = relativeSource.replace(/^file:\/\//, "");
  683. if (url.scheme == "file"
  684. && this._sources.has(fileUriAbsPath)) {
  685. return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
  686. }
  687. if ((!url.path || url.path == "/")
  688. && this._sources.has("/" + relativeSource)) {
  689. return this.sourcesContent[this._sources.indexOf("/" + relativeSource)];
  690. }
  691. }
  692. // This function is used recursively from
  693. // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we
  694. // don't want to throw if we can't find the source - we just want to
  695. // return null, so we provide a flag to exit gracefully.
  696. if (nullOnMissing) {
  697. return null;
  698. }
  699. else {
  700. throw new Error('"' + relativeSource + '" is not in the SourceMap.');
  701. }
  702. };
  703. /**
  704. * Returns the generated line and column information for the original source,
  705. * line, and column positions provided. The only argument is an object with
  706. * the following properties:
  707. *
  708. * - source: The filename of the original source.
  709. * - line: The line number in the original source. The line number
  710. * is 1-based.
  711. * - column: The column number in the original source. The column
  712. * number is 0-based.
  713. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  714. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  715. * closest element that is smaller than or greater than the one we are
  716. * searching for, respectively, if the exact element cannot be found.
  717. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  718. *
  719. * and an object is returned with the following properties:
  720. *
  721. * - line: The line number in the generated source, or null. The
  722. * line number is 1-based.
  723. * - column: The column number in the generated source, or null.
  724. * The column number is 0-based.
  725. */
  726. BasicSourceMapConsumer.prototype.generatedPositionFor =
  727. function SourceMapConsumer_generatedPositionFor(aArgs) {
  728. var source = util.getArg(aArgs, 'source');
  729. source = this._findSourceIndex(source);
  730. if (source < 0) {
  731. return {
  732. line: null,
  733. column: null,
  734. lastColumn: null
  735. };
  736. }
  737. var needle = {
  738. source: source,
  739. originalLine: util.getArg(aArgs, 'line'),
  740. originalColumn: util.getArg(aArgs, 'column')
  741. };
  742. var index = this._findMapping(
  743. needle,
  744. this._originalMappings,
  745. "originalLine",
  746. "originalColumn",
  747. util.compareByOriginalPositions,
  748. util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
  749. );
  750. if (index >= 0) {
  751. var mapping = this._originalMappings[index];
  752. if (mapping.source === needle.source) {
  753. return {
  754. line: util.getArg(mapping, 'generatedLine', null),
  755. column: util.getArg(mapping, 'generatedColumn', null),
  756. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  757. };
  758. }
  759. }
  760. return {
  761. line: null,
  762. column: null,
  763. lastColumn: null
  764. };
  765. };
  766. exports.BasicSourceMapConsumer = BasicSourceMapConsumer;
  767. /**
  768. * An IndexedSourceMapConsumer instance represents a parsed source map which
  769. * we can query for information. It differs from BasicSourceMapConsumer in
  770. * that it takes "indexed" source maps (i.e. ones with a "sections" field) as
  771. * input.
  772. *
  773. * The first parameter is a raw source map (either as a JSON string, or already
  774. * parsed to an object). According to the spec for indexed source maps, they
  775. * have the following attributes:
  776. *
  777. * - version: Which version of the source map spec this map is following.
  778. * - file: Optional. The generated file this source map is associated with.
  779. * - sections: A list of section definitions.
  780. *
  781. * Each value under the "sections" field has two fields:
  782. * - offset: The offset into the original specified at which this section
  783. * begins to apply, defined as an object with a "line" and "column"
  784. * field.
  785. * - map: A source map definition. This source map could also be indexed,
  786. * but doesn't have to be.
  787. *
  788. * Instead of the "map" field, it's also possible to have a "url" field
  789. * specifying a URL to retrieve a source map from, but that's currently
  790. * unsupported.
  791. *
  792. * Here's an example source map, taken from the source map spec[0], but
  793. * modified to omit a section which uses the "url" field.
  794. *
  795. * {
  796. * version : 3,
  797. * file: "app.js",
  798. * sections: [{
  799. * offset: {line:100, column:10},
  800. * map: {
  801. * version : 3,
  802. * file: "section.js",
  803. * sources: ["foo.js", "bar.js"],
  804. * names: ["src", "maps", "are", "fun"],
  805. * mappings: "AAAA,E;;ABCDE;"
  806. * }
  807. * }],
  808. * }
  809. *
  810. * The second parameter, if given, is a string whose value is the URL
  811. * at which the source map was found. This URL is used to compute the
  812. * sources array.
  813. *
  814. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt
  815. */
  816. function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {
  817. var sourceMap = aSourceMap;
  818. if (typeof aSourceMap === 'string') {
  819. sourceMap = util.parseSourceMapInput(aSourceMap);
  820. }
  821. var version = util.getArg(sourceMap, 'version');
  822. var sections = util.getArg(sourceMap, 'sections');
  823. if (version != this._version) {
  824. throw new Error('Unsupported version: ' + version);
  825. }
  826. this._sources = new ArraySet();
  827. this._names = new ArraySet();
  828. var lastOffset = {
  829. line: -1,
  830. column: 0
  831. };
  832. this._sections = sections.map(function (s) {
  833. if (s.url) {
  834. // The url field will require support for asynchronicity.
  835. // See https://github.com/mozilla/source-map/issues/16
  836. throw new Error('Support for url field in sections not implemented.');
  837. }
  838. var offset = util.getArg(s, 'offset');
  839. var offsetLine = util.getArg(offset, 'line');
  840. var offsetColumn = util.getArg(offset, 'column');
  841. if (offsetLine < lastOffset.line ||
  842. (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {
  843. throw new Error('Section offsets must be ordered and non-overlapping.');
  844. }
  845. lastOffset = offset;
  846. return {
  847. generatedOffset: {
  848. // The offset fields are 0-based, but we use 1-based indices when
  849. // encoding/decoding from VLQ.
  850. generatedLine: offsetLine + 1,
  851. generatedColumn: offsetColumn + 1
  852. },
  853. consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL)
  854. }
  855. });
  856. }
  857. IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
  858. IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;
  859. /**
  860. * The version of the source mapping spec that we are consuming.
  861. */
  862. IndexedSourceMapConsumer.prototype._version = 3;
  863. /**
  864. * The list of original sources.
  865. */
  866. Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {
  867. get: function () {
  868. var sources = [];
  869. for (var i = 0; i < this._sections.length; i++) {
  870. for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {
  871. sources.push(this._sections[i].consumer.sources[j]);
  872. }
  873. }
  874. return sources;
  875. }
  876. });
  877. /**
  878. * Returns the original source, line, and column information for the generated
  879. * source's line and column positions provided. The only argument is an object
  880. * with the following properties:
  881. *
  882. * - line: The line number in the generated source. The line number
  883. * is 1-based.
  884. * - column: The column number in the generated source. The column
  885. * number is 0-based.
  886. *
  887. * and an object is returned with the following properties:
  888. *
  889. * - source: The original source file, or null.
  890. * - line: The line number in the original source, or null. The
  891. * line number is 1-based.
  892. * - column: The column number in the original source, or null. The
  893. * column number is 0-based.
  894. * - name: The original identifier, or null.
  895. */
  896. IndexedSourceMapConsumer.prototype.originalPositionFor =
  897. function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
  898. var needle = {
  899. generatedLine: util.getArg(aArgs, 'line'),
  900. generatedColumn: util.getArg(aArgs, 'column')
  901. };
  902. // Find the section containing the generated position we're trying to map
  903. // to an original position.
  904. var sectionIndex = binarySearch.search(needle, this._sections,
  905. function(needle, section) {
  906. var cmp = needle.generatedLine - section.generatedOffset.generatedLine;
  907. if (cmp) {
  908. return cmp;
  909. }
  910. return (needle.generatedColumn -
  911. section.generatedOffset.generatedColumn);
  912. });
  913. var section = this._sections[sectionIndex];
  914. if (!section) {
  915. return {
  916. source: null,
  917. line: null,
  918. column: null,
  919. name: null
  920. };
  921. }
  922. return section.consumer.originalPositionFor({
  923. line: needle.generatedLine -
  924. (section.generatedOffset.generatedLine - 1),
  925. column: needle.generatedColumn -
  926. (section.generatedOffset.generatedLine === needle.generatedLine
  927. ? section.generatedOffset.generatedColumn - 1
  928. : 0),
  929. bias: aArgs.bias
  930. });
  931. };
  932. /**
  933. * Return true if we have the source content for every source in the source
  934. * map, false otherwise.
  935. */
  936. IndexedSourceMapConsumer.prototype.hasContentsOfAllSources =
  937. function IndexedSourceMapConsumer_hasContentsOfAllSources() {
  938. return this._sections.every(function (s) {
  939. return s.consumer.hasContentsOfAllSources();
  940. });
  941. };
  942. /**
  943. * Returns the original source content. The only argument is the url of the
  944. * original source file. Returns null if no original source content is
  945. * available.
  946. */
  947. IndexedSourceMapConsumer.prototype.sourceContentFor =
  948. function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  949. for (var i = 0; i < this._sections.length; i++) {
  950. var section = this._sections[i];
  951. var content = section.consumer.sourceContentFor(aSource, true);
  952. if (content) {
  953. return content;
  954. }
  955. }
  956. if (nullOnMissing) {
  957. return null;
  958. }
  959. else {
  960. throw new Error('"' + aSource + '" is not in the SourceMap.');
  961. }
  962. };
  963. /**
  964. * Returns the generated line and column information for the original source,
  965. * line, and column positions provided. The only argument is an object with
  966. * the following properties:
  967. *
  968. * - source: The filename of the original source.
  969. * - line: The line number in the original source. The line number
  970. * is 1-based.
  971. * - column: The column number in the original source. The column
  972. * number is 0-based.
  973. *
  974. * and an object is returned with the following properties:
  975. *
  976. * - line: The line number in the generated source, or null. The
  977. * line number is 1-based.
  978. * - column: The column number in the generated source, or null.
  979. * The column number is 0-based.
  980. */
  981. IndexedSourceMapConsumer.prototype.generatedPositionFor =
  982. function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
  983. for (var i = 0; i < this._sections.length; i++) {
  984. var section = this._sections[i];
  985. // Only consider this section if the requested source is in the list of
  986. // sources of the consumer.
  987. if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) {
  988. continue;
  989. }
  990. var generatedPosition = section.consumer.generatedPositionFor(aArgs);
  991. if (generatedPosition) {
  992. var ret = {
  993. line: generatedPosition.line +
  994. (section.generatedOffset.generatedLine - 1),
  995. column: generatedPosition.column +
  996. (section.generatedOffset.generatedLine === generatedPosition.line
  997. ? section.generatedOffset.generatedColumn - 1
  998. : 0)
  999. };
  1000. return ret;
  1001. }
  1002. }
  1003. return {
  1004. line: null,
  1005. column: null
  1006. };
  1007. };
  1008. /**
  1009. * Parse the mappings in a string in to a data structure which we can easily
  1010. * query (the ordered arrays in the `this.__generatedMappings` and
  1011. * `this.__originalMappings` properties).
  1012. */
  1013. IndexedSourceMapConsumer.prototype._parseMappings =
  1014. function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  1015. this.__generatedMappings = [];
  1016. this.__originalMappings = [];
  1017. for (var i = 0; i < this._sections.length; i++) {
  1018. var section = this._sections[i];
  1019. var sectionMappings = section.consumer._generatedMappings;
  1020. for (var j = 0; j < sectionMappings.length; j++) {
  1021. var mapping = sectionMappings[j];
  1022. var source = section.consumer._sources.at(mapping.source);
  1023. source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);
  1024. this._sources.add(source);
  1025. source = this._sources.indexOf(source);
  1026. var name = null;
  1027. if (mapping.name) {
  1028. name = section.consumer._names.at(mapping.name);
  1029. this._names.add(name);
  1030. name = this._names.indexOf(name);
  1031. }
  1032. // The mappings coming from the consumer for the section have
  1033. // generated positions relative to the start of the section, so we
  1034. // need to offset them to be relative to the start of the concatenated
  1035. // generated file.
  1036. var adjustedMapping = {
  1037. source: source,
  1038. generatedLine: mapping.generatedLine +
  1039. (section.generatedOffset.generatedLine - 1),
  1040. generatedColumn: mapping.generatedColumn +
  1041. (section.generatedOffset.generatedLine === mapping.generatedLine
  1042. ? section.generatedOffset.generatedColumn - 1
  1043. : 0),
  1044. originalLine: mapping.originalLine,
  1045. originalColumn: mapping.originalColumn,
  1046. name: name
  1047. };
  1048. this.__generatedMappings.push(adjustedMapping);
  1049. if (typeof adjustedMapping.originalLine === 'number') {
  1050. this.__originalMappings.push(adjustedMapping);
  1051. }
  1052. }
  1053. }
  1054. quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);
  1055. quickSort(this.__originalMappings, util.compareByOriginalPositions);
  1056. };
  1057. exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer;