source-map-consumer.js 37 KB

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