source-map-generator.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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 base64VLQ = require('./base64-vlq');
  8. var util = require('./util');
  9. var ArraySet = require('./array-set').ArraySet;
  10. var MappingList = require('./mapping-list').MappingList;
  11. /**
  12. * An instance of the SourceMapGenerator represents a source map which is
  13. * being built incrementally. You may pass an object with the following
  14. * properties:
  15. *
  16. * - file: The filename of the generated source.
  17. * - sourceRoot: A root for all relative URLs in this source map.
  18. */
  19. function SourceMapGenerator(aArgs) {
  20. if (!aArgs) {
  21. aArgs = {};
  22. }
  23. this._file = util.getArg(aArgs, 'file', null);
  24. this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
  25. this._skipValidation = util.getArg(aArgs, 'skipValidation', false);
  26. this._sources = new ArraySet();
  27. this._names = new ArraySet();
  28. this._mappings = new MappingList();
  29. this._sourcesContents = null;
  30. }
  31. SourceMapGenerator.prototype._version = 3;
  32. /**
  33. * Creates a new SourceMapGenerator based on a SourceMapConsumer
  34. *
  35. * @param aSourceMapConsumer The SourceMap.
  36. */
  37. SourceMapGenerator.fromSourceMap =
  38. function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
  39. var sourceRoot = aSourceMapConsumer.sourceRoot;
  40. var generator = new SourceMapGenerator({
  41. file: aSourceMapConsumer.file,
  42. sourceRoot: sourceRoot
  43. });
  44. aSourceMapConsumer.eachMapping(function (mapping) {
  45. var newMapping = {
  46. generated: {
  47. line: mapping.generatedLine,
  48. column: mapping.generatedColumn
  49. }
  50. };
  51. if (mapping.source != null) {
  52. newMapping.source = mapping.source;
  53. if (sourceRoot != null) {
  54. newMapping.source = util.relative(sourceRoot, newMapping.source);
  55. }
  56. newMapping.original = {
  57. line: mapping.originalLine,
  58. column: mapping.originalColumn
  59. };
  60. if (mapping.name != null) {
  61. newMapping.name = mapping.name;
  62. }
  63. }
  64. generator.addMapping(newMapping);
  65. });
  66. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  67. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  68. if (content != null) {
  69. generator.setSourceContent(sourceFile, content);
  70. }
  71. });
  72. return generator;
  73. };
  74. /**
  75. * Add a single mapping from original source line and column to the generated
  76. * source's line and column for this source map being created. The mapping
  77. * object should have the following properties:
  78. *
  79. * - generated: An object with the generated line and column positions.
  80. * - original: An object with the original line and column positions.
  81. * - source: The original source file (relative to the sourceRoot).
  82. * - name: An optional original token name for this mapping.
  83. */
  84. SourceMapGenerator.prototype.addMapping =
  85. function SourceMapGenerator_addMapping(aArgs) {
  86. var generated = util.getArg(aArgs, 'generated');
  87. var original = util.getArg(aArgs, 'original', null);
  88. var source = util.getArg(aArgs, 'source', null);
  89. var name = util.getArg(aArgs, 'name', null);
  90. if (!this._skipValidation) {
  91. this._validateMapping(generated, original, source, name);
  92. }
  93. if (source != null) {
  94. source = String(source);
  95. if (!this._sources.has(source)) {
  96. this._sources.add(source);
  97. }
  98. }
  99. if (name != null) {
  100. name = String(name);
  101. if (!this._names.has(name)) {
  102. this._names.add(name);
  103. }
  104. }
  105. this._mappings.add({
  106. generatedLine: generated.line,
  107. generatedColumn: generated.column,
  108. originalLine: original != null && original.line,
  109. originalColumn: original != null && original.column,
  110. source: source,
  111. name: name
  112. });
  113. };
  114. /**
  115. * Set the source content for a source file.
  116. */
  117. SourceMapGenerator.prototype.setSourceContent =
  118. function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
  119. var source = aSourceFile;
  120. if (this._sourceRoot != null) {
  121. source = util.relative(this._sourceRoot, source);
  122. }
  123. if (aSourceContent != null) {
  124. // Add the source content to the _sourcesContents map.
  125. // Create a new _sourcesContents map if the property is null.
  126. if (!this._sourcesContents) {
  127. this._sourcesContents = Object.create(null);
  128. }
  129. this._sourcesContents[util.toSetString(source)] = aSourceContent;
  130. } else if (this._sourcesContents) {
  131. // Remove the source file from the _sourcesContents map.
  132. // If the _sourcesContents map is empty, set the property to null.
  133. delete this._sourcesContents[util.toSetString(source)];
  134. if (Object.keys(this._sourcesContents).length === 0) {
  135. this._sourcesContents = null;
  136. }
  137. }
  138. };
  139. /**
  140. * Applies the mappings of a sub-source-map for a specific source file to the
  141. * source map being generated. Each mapping to the supplied source file is
  142. * rewritten using the supplied source map. Note: The resolution for the
  143. * resulting mappings is the minimium of this map and the supplied map.
  144. *
  145. * @param aSourceMapConsumer The source map to be applied.
  146. * @param aSourceFile Optional. The filename of the source file.
  147. * If omitted, SourceMapConsumer's file property will be used.
  148. * @param aSourceMapPath Optional. The dirname of the path to the source map
  149. * to be applied. If relative, it is relative to the SourceMapConsumer.
  150. * This parameter is needed when the two source maps aren't in the same
  151. * directory, and the source map to be applied contains relative source
  152. * paths. If so, those relative source paths need to be rewritten
  153. * relative to the SourceMapGenerator.
  154. */
  155. SourceMapGenerator.prototype.applySourceMap =
  156. function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
  157. var sourceFile = aSourceFile;
  158. // If aSourceFile is omitted, we will use the file property of the SourceMap
  159. if (aSourceFile == null) {
  160. if (aSourceMapConsumer.file == null) {
  161. throw new Error(
  162. 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +
  163. 'or the source map\'s "file" property. Both were omitted.'
  164. );
  165. }
  166. sourceFile = aSourceMapConsumer.file;
  167. }
  168. var sourceRoot = this._sourceRoot;
  169. // Make "sourceFile" relative if an absolute Url is passed.
  170. if (sourceRoot != null) {
  171. sourceFile = util.relative(sourceRoot, sourceFile);
  172. }
  173. // Applying the SourceMap can add and remove items from the sources and
  174. // the names array.
  175. var newSources = new ArraySet();
  176. var newNames = new ArraySet();
  177. // Find mappings for the "sourceFile"
  178. this._mappings.unsortedForEach(function (mapping) {
  179. if (mapping.source === sourceFile && mapping.originalLine != null) {
  180. // Check if it can be mapped by the source map, then update the mapping.
  181. var original = aSourceMapConsumer.originalPositionFor({
  182. line: mapping.originalLine,
  183. column: mapping.originalColumn
  184. });
  185. if (original.source != null) {
  186. // Copy mapping
  187. mapping.source = original.source;
  188. if (aSourceMapPath != null) {
  189. mapping.source = util.join(aSourceMapPath, mapping.source)
  190. }
  191. if (sourceRoot != null) {
  192. mapping.source = util.relative(sourceRoot, mapping.source);
  193. }
  194. mapping.originalLine = original.line;
  195. mapping.originalColumn = original.column;
  196. if (original.name != null) {
  197. mapping.name = original.name;
  198. }
  199. }
  200. }
  201. var source = mapping.source;
  202. if (source != null && !newSources.has(source)) {
  203. newSources.add(source);
  204. }
  205. var name = mapping.name;
  206. if (name != null && !newNames.has(name)) {
  207. newNames.add(name);
  208. }
  209. }, this);
  210. this._sources = newSources;
  211. this._names = newNames;
  212. // Copy sourcesContents of applied map.
  213. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  214. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  215. if (content != null) {
  216. if (aSourceMapPath != null) {
  217. sourceFile = util.join(aSourceMapPath, sourceFile);
  218. }
  219. if (sourceRoot != null) {
  220. sourceFile = util.relative(sourceRoot, sourceFile);
  221. }
  222. this.setSourceContent(sourceFile, content);
  223. }
  224. }, this);
  225. };
  226. /**
  227. * A mapping can have one of the three levels of data:
  228. *
  229. * 1. Just the generated position.
  230. * 2. The Generated position, original position, and original source.
  231. * 3. Generated and original position, original source, as well as a name
  232. * token.
  233. *
  234. * To maintain consistency, we validate that any new mapping being added falls
  235. * in to one of these categories.
  236. */
  237. SourceMapGenerator.prototype._validateMapping =
  238. function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
  239. aName) {
  240. // When aOriginal is truthy but has empty values for .line and .column,
  241. // it is most likely a programmer error. In this case we throw a very
  242. // specific error message to try to guide them the right way.
  243. // For example: https://github.com/Polymer/polymer-bundler/pull/519
  244. if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {
  245. throw new Error(
  246. 'original.line and original.column are not numbers -- you probably meant to omit ' +
  247. 'the original mapping entirely and only map the generated position. If so, pass ' +
  248. 'null for the original mapping instead of an object with empty or null values.'
  249. );
  250. }
  251. if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  252. && aGenerated.line > 0 && aGenerated.column >= 0
  253. && !aOriginal && !aSource && !aName) {
  254. // Case 1.
  255. return;
  256. }
  257. else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  258. && aOriginal && 'line' in aOriginal && 'column' in aOriginal
  259. && aGenerated.line > 0 && aGenerated.column >= 0
  260. && aOriginal.line > 0 && aOriginal.column >= 0
  261. && aSource) {
  262. // Cases 2 and 3.
  263. return;
  264. }
  265. else {
  266. throw new Error('Invalid mapping: ' + JSON.stringify({
  267. generated: aGenerated,
  268. source: aSource,
  269. original: aOriginal,
  270. name: aName
  271. }));
  272. }
  273. };
  274. /**
  275. * Serialize the accumulated mappings in to the stream of base 64 VLQs
  276. * specified by the source map format.
  277. */
  278. SourceMapGenerator.prototype._serializeMappings =
  279. function SourceMapGenerator_serializeMappings() {
  280. var previousGeneratedColumn = 0;
  281. var previousGeneratedLine = 1;
  282. var previousOriginalColumn = 0;
  283. var previousOriginalLine = 0;
  284. var previousName = 0;
  285. var previousSource = 0;
  286. var result = '';
  287. var next;
  288. var mapping;
  289. var nameIdx;
  290. var sourceIdx;
  291. var mappings = this._mappings.toArray();
  292. for (var i = 0, len = mappings.length; i < len; i++) {
  293. mapping = mappings[i];
  294. next = ''
  295. if (mapping.generatedLine !== previousGeneratedLine) {
  296. previousGeneratedColumn = 0;
  297. while (mapping.generatedLine !== previousGeneratedLine) {
  298. next += ';';
  299. previousGeneratedLine++;
  300. }
  301. }
  302. else {
  303. if (i > 0) {
  304. if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
  305. continue;
  306. }
  307. next += ',';
  308. }
  309. }
  310. next += base64VLQ.encode(mapping.generatedColumn
  311. - previousGeneratedColumn);
  312. previousGeneratedColumn = mapping.generatedColumn;
  313. if (mapping.source != null) {
  314. sourceIdx = this._sources.indexOf(mapping.source);
  315. next += base64VLQ.encode(sourceIdx - previousSource);
  316. previousSource = sourceIdx;
  317. // lines are stored 0-based in SourceMap spec version 3
  318. next += base64VLQ.encode(mapping.originalLine - 1
  319. - previousOriginalLine);
  320. previousOriginalLine = mapping.originalLine - 1;
  321. next += base64VLQ.encode(mapping.originalColumn
  322. - previousOriginalColumn);
  323. previousOriginalColumn = mapping.originalColumn;
  324. if (mapping.name != null) {
  325. nameIdx = this._names.indexOf(mapping.name);
  326. next += base64VLQ.encode(nameIdx - previousName);
  327. previousName = nameIdx;
  328. }
  329. }
  330. result += next;
  331. }
  332. return result;
  333. };
  334. SourceMapGenerator.prototype._generateSourcesContent =
  335. function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
  336. return aSources.map(function (source) {
  337. if (!this._sourcesContents) {
  338. return null;
  339. }
  340. if (aSourceRoot != null) {
  341. source = util.relative(aSourceRoot, source);
  342. }
  343. var key = util.toSetString(source);
  344. return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)
  345. ? this._sourcesContents[key]
  346. : null;
  347. }, this);
  348. };
  349. /**
  350. * Externalize the source map.
  351. */
  352. SourceMapGenerator.prototype.toJSON =
  353. function SourceMapGenerator_toJSON() {
  354. var map = {
  355. version: this._version,
  356. sources: this._sources.toArray(),
  357. names: this._names.toArray(),
  358. mappings: this._serializeMappings()
  359. };
  360. if (this._file != null) {
  361. map.file = this._file;
  362. }
  363. if (this._sourceRoot != null) {
  364. map.sourceRoot = this._sourceRoot;
  365. }
  366. if (this._sourcesContents) {
  367. map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
  368. }
  369. return map;
  370. };
  371. /**
  372. * Render the source map being generated to a string.
  373. */
  374. SourceMapGenerator.prototype.toString =
  375. function SourceMapGenerator_toString() {
  376. return JSON.stringify(this.toJSON());
  377. };
  378. exports.SourceMapGenerator = SourceMapGenerator;