source-map-consumer.js 40 KB

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