source-map-consumer.js 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178
  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. const compareGenerated = util.compareByGeneratedPositionsDeflatedNoLine;
  411. function sortGenerated(array, start) {
  412. let l = array.length;
  413. let n = array.length - start;
  414. if (n <= 1) {
  415. return;
  416. } else if (n == 2) {
  417. let a = array[start];
  418. let b = array[start + 1];
  419. if (compareGenerated(a, b) > 0) {
  420. array[start] = b;
  421. array[start + 1] = a;
  422. }
  423. } else if (n < 20) {
  424. for (let i = start; i < l; i++) {
  425. for (let j = i; j > start; j--) {
  426. let a = array[j - 1];
  427. let b = array[j];
  428. if (compareGenerated(a, b) <= 0) {
  429. break;
  430. }
  431. array[j - 1] = b;
  432. array[j] = a;
  433. }
  434. }
  435. } else {
  436. quickSort(array, compareGenerated, start);
  437. }
  438. }
  439. BasicSourceMapConsumer.prototype._parseMappings =
  440. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  441. var generatedLine = 1;
  442. var previousGeneratedColumn = 0;
  443. var previousOriginalLine = 0;
  444. var previousOriginalColumn = 0;
  445. var previousSource = 0;
  446. var previousName = 0;
  447. var length = aStr.length;
  448. var index = 0;
  449. var cachedSegments = {};
  450. var temp = {};
  451. var originalMappings = [];
  452. var generatedMappings = [];
  453. var mapping, str, segment, end, value;
  454. let subarrayStart = 0;
  455. while (index < length) {
  456. if (aStr.charAt(index) === ';') {
  457. generatedLine++;
  458. index++;
  459. previousGeneratedColumn = 0;
  460. sortGenerated(generatedMappings, subarrayStart);
  461. subarrayStart = generatedMappings.length;
  462. }
  463. else if (aStr.charAt(index) === ',') {
  464. index++;
  465. }
  466. else {
  467. mapping = new Mapping();
  468. mapping.generatedLine = generatedLine;
  469. for (end = index; end < length; end++) {
  470. if (this._charIsMappingSeparator(aStr, end)) {
  471. break;
  472. }
  473. }
  474. str = aStr.slice(index, end);
  475. segment = [];
  476. while (index < end) {
  477. base64VLQ.decode(aStr, index, temp);
  478. value = temp.value;
  479. index = temp.rest;
  480. segment.push(value);
  481. }
  482. if (segment.length === 2) {
  483. throw new Error('Found a source, but no line and column');
  484. }
  485. if (segment.length === 3) {
  486. throw new Error('Found a source and line, but no column');
  487. }
  488. // Generated column.
  489. mapping.generatedColumn = previousGeneratedColumn + segment[0];
  490. previousGeneratedColumn = mapping.generatedColumn;
  491. if (segment.length > 1) {
  492. // Original source.
  493. mapping.source = previousSource + segment[1];
  494. previousSource += segment[1];
  495. // Original line.
  496. mapping.originalLine = previousOriginalLine + segment[2];
  497. previousOriginalLine = mapping.originalLine;
  498. // Lines are stored 0-based
  499. mapping.originalLine += 1;
  500. // Original column.
  501. mapping.originalColumn = previousOriginalColumn + segment[3];
  502. previousOriginalColumn = mapping.originalColumn;
  503. if (segment.length > 4) {
  504. // Original name.
  505. mapping.name = previousName + segment[4];
  506. previousName += segment[4];
  507. }
  508. }
  509. generatedMappings.push(mapping);
  510. if (typeof mapping.originalLine === 'number') {
  511. let currentSource = mapping.source;
  512. while (originalMappings.length <= currentSource) {
  513. originalMappings.push(null);
  514. }
  515. if (originalMappings[currentSource] === null) {
  516. originalMappings[currentSource] = [];
  517. }
  518. originalMappings[currentSource].push(mapping);
  519. }
  520. }
  521. }
  522. sortGenerated(generatedMappings, subarrayStart);
  523. this.__generatedMappings = generatedMappings;
  524. for (var i = 0; i < originalMappings.length; i++) {
  525. if (originalMappings[i] != null) {
  526. quickSort(originalMappings[i], util.compareByOriginalPositionsNoSource);
  527. }
  528. }
  529. this.__originalMappings = [].concat(...originalMappings);
  530. };
  531. /**
  532. * Find the mapping that best matches the hypothetical "needle" mapping that
  533. * we are searching for in the given "haystack" of mappings.
  534. */
  535. BasicSourceMapConsumer.prototype._findMapping =
  536. function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
  537. aColumnName, aComparator, aBias) {
  538. // To return the position we are searching for, we must first find the
  539. // mapping for the given position and then return the opposite position it
  540. // points to. Because the mappings are sorted, we can use binary search to
  541. // find the best mapping.
  542. if (aNeedle[aLineName] <= 0) {
  543. throw new TypeError('Line must be greater than or equal to 1, got '
  544. + aNeedle[aLineName]);
  545. }
  546. if (aNeedle[aColumnName] < 0) {
  547. throw new TypeError('Column must be greater than or equal to 0, got '
  548. + aNeedle[aColumnName]);
  549. }
  550. return binarySearch.search(aNeedle, aMappings, aComparator, aBias);
  551. };
  552. /**
  553. * Compute the last column for each generated mapping. The last column is
  554. * inclusive.
  555. */
  556. BasicSourceMapConsumer.prototype.computeColumnSpans =
  557. function SourceMapConsumer_computeColumnSpans() {
  558. for (var index = 0; index < this._generatedMappings.length; ++index) {
  559. var mapping = this._generatedMappings[index];
  560. // Mappings do not contain a field for the last generated columnt. We
  561. // can come up with an optimistic estimate, however, by assuming that
  562. // mappings are contiguous (i.e. given two consecutive mappings, the
  563. // first mapping ends where the second one starts).
  564. if (index + 1 < this._generatedMappings.length) {
  565. var nextMapping = this._generatedMappings[index + 1];
  566. if (mapping.generatedLine === nextMapping.generatedLine) {
  567. mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
  568. continue;
  569. }
  570. }
  571. // The last mapping for each line spans the entire line.
  572. mapping.lastGeneratedColumn = Infinity;
  573. }
  574. };
  575. /**
  576. * Returns the original source, line, and column information for the generated
  577. * source's line and column positions provided. The only argument is an object
  578. * with the following properties:
  579. *
  580. * - line: The line number in the generated source. The line number
  581. * is 1-based.
  582. * - column: The column number in the generated source. The column
  583. * number is 0-based.
  584. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  585. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  586. * closest element that is smaller than or greater than the one we are
  587. * searching for, respectively, if the exact element cannot be found.
  588. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  589. *
  590. * and an object is returned with the following properties:
  591. *
  592. * - source: The original source file, or null.
  593. * - line: The line number in the original source, or null. The
  594. * line number is 1-based.
  595. * - column: The column number in the original source, or null. The
  596. * column number is 0-based.
  597. * - name: The original identifier, or null.
  598. */
  599. BasicSourceMapConsumer.prototype.originalPositionFor =
  600. function SourceMapConsumer_originalPositionFor(aArgs) {
  601. var needle = {
  602. generatedLine: util.getArg(aArgs, 'line'),
  603. generatedColumn: util.getArg(aArgs, 'column')
  604. };
  605. var index = this._findMapping(
  606. needle,
  607. this._generatedMappings,
  608. "generatedLine",
  609. "generatedColumn",
  610. util.compareByGeneratedPositionsDeflated,
  611. util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
  612. );
  613. if (index >= 0) {
  614. var mapping = this._generatedMappings[index];
  615. if (mapping.generatedLine === needle.generatedLine) {
  616. var source = util.getArg(mapping, 'source', null);
  617. if (source !== null) {
  618. source = this._sources.at(source);
  619. source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);
  620. }
  621. var name = util.getArg(mapping, 'name', null);
  622. if (name !== null) {
  623. name = this._names.at(name);
  624. }
  625. return {
  626. source: source,
  627. line: util.getArg(mapping, 'originalLine', null),
  628. column: util.getArg(mapping, 'originalColumn', null),
  629. name: name
  630. };
  631. }
  632. }
  633. return {
  634. source: null,
  635. line: null,
  636. column: null,
  637. name: null
  638. };
  639. };
  640. /**
  641. * Return true if we have the source content for every source in the source
  642. * map, false otherwise.
  643. */
  644. BasicSourceMapConsumer.prototype.hasContentsOfAllSources =
  645. function BasicSourceMapConsumer_hasContentsOfAllSources() {
  646. if (!this.sourcesContent) {
  647. return false;
  648. }
  649. return this.sourcesContent.length >= this._sources.size() &&
  650. !this.sourcesContent.some(function (sc) { return sc == null; });
  651. };
  652. /**
  653. * Returns the original source content. The only argument is the url of the
  654. * original source file. Returns null if no original source content is
  655. * available.
  656. */
  657. BasicSourceMapConsumer.prototype.sourceContentFor =
  658. function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  659. if (!this.sourcesContent) {
  660. return null;
  661. }
  662. var index = this._findSourceIndex(aSource);
  663. if (index >= 0) {
  664. return this.sourcesContent[index];
  665. }
  666. var relativeSource = aSource;
  667. if (this.sourceRoot != null) {
  668. relativeSource = util.relative(this.sourceRoot, relativeSource);
  669. }
  670. var url;
  671. if (this.sourceRoot != null
  672. && (url = util.urlParse(this.sourceRoot))) {
  673. // XXX: file:// URIs and absolute paths lead to unexpected behavior for
  674. // many users. We can help them out when they expect file:// URIs to
  675. // behave like it would if they were running a local HTTP server. See
  676. // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
  677. var fileUriAbsPath = relativeSource.replace(/^file:\/\//, "");
  678. if (url.scheme == "file"
  679. && this._sources.has(fileUriAbsPath)) {
  680. return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
  681. }
  682. if ((!url.path || url.path == "/")
  683. && this._sources.has("/" + relativeSource)) {
  684. return this.sourcesContent[this._sources.indexOf("/" + relativeSource)];
  685. }
  686. }
  687. // This function is used recursively from
  688. // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we
  689. // don't want to throw if we can't find the source - we just want to
  690. // return null, so we provide a flag to exit gracefully.
  691. if (nullOnMissing) {
  692. return null;
  693. }
  694. else {
  695. throw new Error('"' + relativeSource + '" is not in the SourceMap.');
  696. }
  697. };
  698. /**
  699. * Returns the generated line and column information for the original source,
  700. * line, and column positions provided. The only argument is an object with
  701. * the following properties:
  702. *
  703. * - source: The filename of the original source.
  704. * - line: The line number in the original source. The line number
  705. * is 1-based.
  706. * - column: The column number in the original source. The column
  707. * number is 0-based.
  708. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  709. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  710. * closest element that is smaller than or greater than the one we are
  711. * searching for, respectively, if the exact element cannot be found.
  712. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  713. *
  714. * and an object is returned with the following properties:
  715. *
  716. * - line: The line number in the generated source, or null. The
  717. * line number is 1-based.
  718. * - column: The column number in the generated source, or null.
  719. * The column number is 0-based.
  720. */
  721. BasicSourceMapConsumer.prototype.generatedPositionFor =
  722. function SourceMapConsumer_generatedPositionFor(aArgs) {
  723. var source = util.getArg(aArgs, 'source');
  724. source = this._findSourceIndex(source);
  725. if (source < 0) {
  726. return {
  727. line: null,
  728. column: null,
  729. lastColumn: null
  730. };
  731. }
  732. var needle = {
  733. source: source,
  734. originalLine: util.getArg(aArgs, 'line'),
  735. originalColumn: util.getArg(aArgs, 'column')
  736. };
  737. var index = this._findMapping(
  738. needle,
  739. this._originalMappings,
  740. "originalLine",
  741. "originalColumn",
  742. util.compareByOriginalPositions,
  743. util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
  744. );
  745. if (index >= 0) {
  746. var mapping = this._originalMappings[index];
  747. if (mapping.source === needle.source) {
  748. return {
  749. line: util.getArg(mapping, 'generatedLine', null),
  750. column: util.getArg(mapping, 'generatedColumn', null),
  751. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  752. };
  753. }
  754. }
  755. return {
  756. line: null,
  757. column: null,
  758. lastColumn: null
  759. };
  760. };
  761. exports.BasicSourceMapConsumer = BasicSourceMapConsumer;
  762. /**
  763. * An IndexedSourceMapConsumer instance represents a parsed source map which
  764. * we can query for information. It differs from BasicSourceMapConsumer in
  765. * that it takes "indexed" source maps (i.e. ones with a "sections" field) as
  766. * input.
  767. *
  768. * The first parameter is a raw source map (either as a JSON string, or already
  769. * parsed to an object). According to the spec for indexed source maps, they
  770. * have the following attributes:
  771. *
  772. * - version: Which version of the source map spec this map is following.
  773. * - file: Optional. The generated file this source map is associated with.
  774. * - sections: A list of section definitions.
  775. *
  776. * Each value under the "sections" field has two fields:
  777. * - offset: The offset into the original specified at which this section
  778. * begins to apply, defined as an object with a "line" and "column"
  779. * field.
  780. * - map: A source map definition. This source map could also be indexed,
  781. * but doesn't have to be.
  782. *
  783. * Instead of the "map" field, it's also possible to have a "url" field
  784. * specifying a URL to retrieve a source map from, but that's currently
  785. * unsupported.
  786. *
  787. * Here's an example source map, taken from the source map spec[0], but
  788. * modified to omit a section which uses the "url" field.
  789. *
  790. * {
  791. * version : 3,
  792. * file: "app.js",
  793. * sections: [{
  794. * offset: {line:100, column:10},
  795. * map: {
  796. * version : 3,
  797. * file: "section.js",
  798. * sources: ["foo.js", "bar.js"],
  799. * names: ["src", "maps", "are", "fun"],
  800. * mappings: "AAAA,E;;ABCDE;"
  801. * }
  802. * }],
  803. * }
  804. *
  805. * The second parameter, if given, is a string whose value is the URL
  806. * at which the source map was found. This URL is used to compute the
  807. * sources array.
  808. *
  809. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt
  810. */
  811. function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {
  812. var sourceMap = aSourceMap;
  813. if (typeof aSourceMap === 'string') {
  814. sourceMap = util.parseSourceMapInput(aSourceMap);
  815. }
  816. var version = util.getArg(sourceMap, 'version');
  817. var sections = util.getArg(sourceMap, 'sections');
  818. if (version != this._version) {
  819. throw new Error('Unsupported version: ' + version);
  820. }
  821. this._sources = new ArraySet();
  822. this._names = new ArraySet();
  823. var lastOffset = {
  824. line: -1,
  825. column: 0
  826. };
  827. this._sections = sections.map(function (s) {
  828. if (s.url) {
  829. // The url field will require support for asynchronicity.
  830. // See https://github.com/mozilla/source-map/issues/16
  831. throw new Error('Support for url field in sections not implemented.');
  832. }
  833. var offset = util.getArg(s, 'offset');
  834. var offsetLine = util.getArg(offset, 'line');
  835. var offsetColumn = util.getArg(offset, 'column');
  836. if (offsetLine < lastOffset.line ||
  837. (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {
  838. throw new Error('Section offsets must be ordered and non-overlapping.');
  839. }
  840. lastOffset = offset;
  841. return {
  842. generatedOffset: {
  843. // The offset fields are 0-based, but we use 1-based indices when
  844. // encoding/decoding from VLQ.
  845. generatedLine: offsetLine + 1,
  846. generatedColumn: offsetColumn + 1
  847. },
  848. consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL)
  849. }
  850. });
  851. }
  852. IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
  853. IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;
  854. /**
  855. * The version of the source mapping spec that we are consuming.
  856. */
  857. IndexedSourceMapConsumer.prototype._version = 3;
  858. /**
  859. * The list of original sources.
  860. */
  861. Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {
  862. get: function () {
  863. var sources = [];
  864. for (var i = 0; i < this._sections.length; i++) {
  865. for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {
  866. sources.push(this._sections[i].consumer.sources[j]);
  867. }
  868. }
  869. return sources;
  870. }
  871. });
  872. /**
  873. * Returns the original source, line, and column information for the generated
  874. * source's line and column positions provided. The only argument is an object
  875. * with the following properties:
  876. *
  877. * - line: The line number in the generated source. The line number
  878. * is 1-based.
  879. * - column: The column number in the generated source. The column
  880. * number is 0-based.
  881. *
  882. * and an object is returned with the following properties:
  883. *
  884. * - source: The original source file, or null.
  885. * - line: The line number in the original source, or null. The
  886. * line number is 1-based.
  887. * - column: The column number in the original source, or null. The
  888. * column number is 0-based.
  889. * - name: The original identifier, or null.
  890. */
  891. IndexedSourceMapConsumer.prototype.originalPositionFor =
  892. function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
  893. var needle = {
  894. generatedLine: util.getArg(aArgs, 'line'),
  895. generatedColumn: util.getArg(aArgs, 'column')
  896. };
  897. // Find the section containing the generated position we're trying to map
  898. // to an original position.
  899. var sectionIndex = binarySearch.search(needle, this._sections,
  900. function(needle, section) {
  901. var cmp = needle.generatedLine - section.generatedOffset.generatedLine;
  902. if (cmp) {
  903. return cmp;
  904. }
  905. return (needle.generatedColumn -
  906. section.generatedOffset.generatedColumn);
  907. });
  908. var section = this._sections[sectionIndex];
  909. if (!section) {
  910. return {
  911. source: null,
  912. line: null,
  913. column: null,
  914. name: null
  915. };
  916. }
  917. return section.consumer.originalPositionFor({
  918. line: needle.generatedLine -
  919. (section.generatedOffset.generatedLine - 1),
  920. column: needle.generatedColumn -
  921. (section.generatedOffset.generatedLine === needle.generatedLine
  922. ? section.generatedOffset.generatedColumn - 1
  923. : 0),
  924. bias: aArgs.bias
  925. });
  926. };
  927. /**
  928. * Return true if we have the source content for every source in the source
  929. * map, false otherwise.
  930. */
  931. IndexedSourceMapConsumer.prototype.hasContentsOfAllSources =
  932. function IndexedSourceMapConsumer_hasContentsOfAllSources() {
  933. return this._sections.every(function (s) {
  934. return s.consumer.hasContentsOfAllSources();
  935. });
  936. };
  937. /**
  938. * Returns the original source content. The only argument is the url of the
  939. * original source file. Returns null if no original source content is
  940. * available.
  941. */
  942. IndexedSourceMapConsumer.prototype.sourceContentFor =
  943. function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  944. for (var i = 0; i < this._sections.length; i++) {
  945. var section = this._sections[i];
  946. var content = section.consumer.sourceContentFor(aSource, true);
  947. if (content) {
  948. return content;
  949. }
  950. }
  951. if (nullOnMissing) {
  952. return null;
  953. }
  954. else {
  955. throw new Error('"' + aSource + '" is not in the SourceMap.');
  956. }
  957. };
  958. /**
  959. * Returns the generated line and column information for the original source,
  960. * line, and column positions provided. The only argument is an object with
  961. * the following properties:
  962. *
  963. * - source: The filename of the original source.
  964. * - line: The line number in the original source. The line number
  965. * is 1-based.
  966. * - column: The column number in the original source. The column
  967. * number is 0-based.
  968. *
  969. * and an object is returned with the following properties:
  970. *
  971. * - line: The line number in the generated source, or null. The
  972. * line number is 1-based.
  973. * - column: The column number in the generated source, or null.
  974. * The column number is 0-based.
  975. */
  976. IndexedSourceMapConsumer.prototype.generatedPositionFor =
  977. function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
  978. for (var i = 0; i < this._sections.length; i++) {
  979. var section = this._sections[i];
  980. // Only consider this section if the requested source is in the list of
  981. // sources of the consumer.
  982. if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) {
  983. continue;
  984. }
  985. var generatedPosition = section.consumer.generatedPositionFor(aArgs);
  986. if (generatedPosition) {
  987. var ret = {
  988. line: generatedPosition.line +
  989. (section.generatedOffset.generatedLine - 1),
  990. column: generatedPosition.column +
  991. (section.generatedOffset.generatedLine === generatedPosition.line
  992. ? section.generatedOffset.generatedColumn - 1
  993. : 0)
  994. };
  995. return ret;
  996. }
  997. }
  998. return {
  999. line: null,
  1000. column: null
  1001. };
  1002. };
  1003. /**
  1004. * Parse the mappings in a string in to a data structure which we can easily
  1005. * query (the ordered arrays in the `this.__generatedMappings` and
  1006. * `this.__originalMappings` properties).
  1007. */
  1008. IndexedSourceMapConsumer.prototype._parseMappings =
  1009. function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  1010. this.__generatedMappings = [];
  1011. this.__originalMappings = [];
  1012. for (var i = 0; i < this._sections.length; i++) {
  1013. var section = this._sections[i];
  1014. var sectionMappings = section.consumer._generatedMappings;
  1015. for (var j = 0; j < sectionMappings.length; j++) {
  1016. var mapping = sectionMappings[j];
  1017. var source = section.consumer._sources.at(mapping.source);
  1018. source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);
  1019. this._sources.add(source);
  1020. source = this._sources.indexOf(source);
  1021. var name = null;
  1022. if (mapping.name) {
  1023. name = section.consumer._names.at(mapping.name);
  1024. this._names.add(name);
  1025. name = this._names.indexOf(name);
  1026. }
  1027. // The mappings coming from the consumer for the section have
  1028. // generated positions relative to the start of the section, so we
  1029. // need to offset them to be relative to the start of the concatenated
  1030. // generated file.
  1031. var adjustedMapping = {
  1032. source: source,
  1033. generatedLine: mapping.generatedLine +
  1034. (section.generatedOffset.generatedLine - 1),
  1035. generatedColumn: mapping.generatedColumn +
  1036. (section.generatedOffset.generatedLine === mapping.generatedLine
  1037. ? section.generatedOffset.generatedColumn - 1
  1038. : 0),
  1039. originalLine: mapping.originalLine,
  1040. originalColumn: mapping.originalColumn,
  1041. name: name
  1042. };
  1043. this.__generatedMappings.push(adjustedMapping);
  1044. if (typeof adjustedMapping.originalLine === 'number') {
  1045. this.__originalMappings.push(adjustedMapping);
  1046. }
  1047. }
  1048. }
  1049. quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);
  1050. quickSort(this.__originalMappings, util.compareByOriginalPositions);
  1051. };
  1052. exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer;