No Description

sourcemap.js 7.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. /*
  2. * grunt-contrib-concat
  3. * http://gruntjs.com/
  4. *
  5. * Copyright (c) 2015 "Cowboy" Ben Alman, contributors
  6. * Licensed under the MIT license.
  7. */
  8. 'use strict';
  9. exports.init = function(grunt) {
  10. var exports = {};
  11. // Node first party libs
  12. var path = require('path');
  13. // Third party libs
  14. var chalk = require('chalk');
  15. var SourceMapConsumer = require('source-map').SourceMapConsumer;
  16. var SourceMapGenerator = require('source-map').SourceMapGenerator;
  17. var SourceNode = require('source-map').SourceNode;
  18. // Return an object that is used to track sourcemap data between calls.
  19. exports.helper = function(files, options) {
  20. // Figure out the source map destination.
  21. var dest = files.dest;
  22. if (options.sourceMapStyle === 'inline') {
  23. // Leave dest as is. It will be used to compute relative sources.
  24. } else if (typeof options.sourceMapName === 'string') {
  25. dest = options.sourceMapName;
  26. } else if (typeof options.sourceMapName === 'function') {
  27. dest = options.sourceMapName(dest);
  28. } else {
  29. dest = dest + '.map';
  30. }
  31. // Inline style and sourceMapName together doesn't work
  32. if (options.sourceMapStyle === 'inline' && options.sourceMapName) {
  33. grunt.log.warn(
  34. 'Source map will be inlined, sourceMapName option ignored.'
  35. );
  36. }
  37. return new SourceMapConcatHelper({
  38. files: files,
  39. dest: dest,
  40. options: options
  41. });
  42. };
  43. function SourceMapConcatHelper(options) {
  44. this.files = options.files;
  45. this.dest = options.dest;
  46. this.options = options.options;
  47. // Create the source map node we'll add concat files into.
  48. this.node = new SourceNode();
  49. // Create an array to store source maps that are referenced from files
  50. // being concatenated.
  51. this.maps = [];
  52. }
  53. // Construct a node split by a zero-length regex.
  54. SourceMapConcatHelper.prototype._dummyNode = function(src, name) {
  55. var node = new SourceNode();
  56. var lineIndex = 1;
  57. var charIndex = 0;
  58. // Tokenize on words, new lines, and white space.
  59. var tokens = src.split(/(\n|[^\S\n]+|\b)/g);
  60. // Filter out empty strings.
  61. tokens = tokens.filter(function(t) { return !!t; });
  62. tokens.forEach(function(token) {
  63. node.add(new SourceNode(lineIndex, charIndex, name, token));
  64. if (token === '\n') {
  65. lineIndex++;
  66. charIndex = 0;
  67. } else {
  68. charIndex += token.length;
  69. }
  70. });
  71. return node;
  72. };
  73. // Add some arbitraty text to the sourcemap.
  74. SourceMapConcatHelper.prototype.add = function(src) {
  75. // Use the dummy node to track new lines and character offset in the unnamed
  76. // concat pieces (banner, footer, separator).
  77. this.node.add(this._dummyNode(src));
  78. };
  79. // Add the lines of a given file to the sourcemap. If in the file, store a
  80. // prior sourcemap and return src with sourceMappingURL removed.
  81. SourceMapConcatHelper.prototype.addlines = function(src, filename) {
  82. var relativeFilename = path.relative(path.dirname(this.dest), filename);
  83. // sourceMap path references are URLs, so ensure forward slashes are used for paths passed to sourcemap library
  84. relativeFilename = relativeFilename.replace(/\\/g, '/');
  85. var node;
  86. if (
  87. /\/\/[@#]\s+sourceMappingURL=(.+)/.test(src) ||
  88. /\/\*#\s+sourceMappingURL=(\S+)\s+\*\//.test(src)
  89. ) {
  90. var sourceMapFile = RegExp.$1;
  91. var sourceMapPath;
  92. var sourceContent;
  93. // Browserify, as an example, stores a datauri at sourceMappingURL.
  94. if (/data:application\/json;base64,([^\s]+)/.test(sourceMapFile)) {
  95. // Set sourceMapPath to the file that the map is inlined.
  96. sourceMapPath = filename;
  97. sourceContent = new Buffer(RegExp.$1, 'base64').toString();
  98. } else {
  99. // If sourceMapPath is relative, expand relative to the file
  100. // refering to it.
  101. sourceMapPath = path.resolve(path.dirname(filename), sourceMapFile);
  102. sourceContent = grunt.file.read(sourceMapPath);
  103. }
  104. var sourceMap = JSON.parse(sourceContent);
  105. var sourceMapConsumer = new SourceMapConsumer(sourceMap);
  106. // Consider the relative path from source files to new sourcemap.
  107. var sourcePathToSourceMapPath =
  108. path.relative(path.dirname(this.dest), path.dirname(sourceMapPath));
  109. // sourceMap path references are URLs, so ensure forward slashes are used for paths passed to sourcemap library
  110. sourcePathToSourceMapPath = sourcePathToSourceMapPath.replace(/\\/g, '/');
  111. // Store the sourceMap so that it may later be consumed.
  112. this.maps.push([
  113. sourceMapConsumer, relativeFilename, sourcePathToSourceMapPath
  114. ]);
  115. // Remove the old sourceMappingURL.
  116. src = src.replace(/[@#]\s+sourceMappingURL=[^\s]+/, '');
  117. // Create a node from the source map for the file.
  118. node = SourceNode.fromStringWithSourceMap(
  119. src, sourceMapConsumer, sourcePathToSourceMapPath
  120. );
  121. } else {
  122. // Use a dummy node. Performs a rudimentary tokenization of the source.
  123. node = this._dummyNode(src, relativeFilename);
  124. }
  125. this.node.add(node);
  126. if (this.options.sourceMapStyle !== 'link') {
  127. this.node.setSourceContent(relativeFilename, src);
  128. }
  129. return src;
  130. };
  131. // Return the comment sourceMappingURL that must be appended to the
  132. // concatenated file.
  133. SourceMapConcatHelper.prototype.url = function() {
  134. // Create the map filepath. Either datauri or destination path.
  135. var mapfilepath;
  136. if (this.options.sourceMapStyle === 'inline') {
  137. var inlineMap = new Buffer(this._write()).toString('base64');
  138. mapfilepath = 'data:application/json;base64,' + inlineMap;
  139. } else {
  140. // Compute relative path to source map destination.
  141. mapfilepath = path.relative(path.dirname(this.files.dest), this.dest);
  142. }
  143. // Create the sourceMappingURL.
  144. var url;
  145. if (/\.css$/.test(this.files.dest)) {
  146. url = '\n/*# sourceMappingURL=' + mapfilepath + ' */';
  147. } else {
  148. url = '\n//# sourceMappingURL=' + mapfilepath;
  149. }
  150. return url;
  151. };
  152. // Return a string for inline use or write the source map to disk.
  153. SourceMapConcatHelper.prototype._write = function() {
  154. // ensure we're using forward slashes, because these are URLs
  155. var file = path.relative(path.dirname(this.dest), this.files.dest);
  156. file = file.replace(/\\/g, '/');
  157. var code_map = this.node.toStringWithSourceMap({
  158. file: file
  159. });
  160. // Consume the new sourcemap.
  161. var generator = SourceMapGenerator.fromSourceMap(
  162. new SourceMapConsumer(code_map.map.toJSON())
  163. );
  164. // Consume sourcemaps for source files.
  165. this.maps.forEach(Function.apply.bind(generator.applySourceMap, generator));
  166. // New sourcemap.
  167. var newSourceMap = generator.toJSON();
  168. // Return a string for inline use or write the map.
  169. if (this.options.sourceMapStyle === 'inline') {
  170. grunt.log.writeln(
  171. 'Source map for ' + chalk.cyan(this.files.dest) + ' inlined.'
  172. );
  173. return JSON.stringify(newSourceMap, null, '');
  174. } else {
  175. grunt.file.write(
  176. this.dest,
  177. JSON.stringify(newSourceMap, null, '')
  178. );
  179. grunt.log.writeln('Source map ' + chalk.cyan(this.dest) + ' created.');
  180. }
  181. };
  182. // Non-private function to write the sourcemap. Shortcuts if writing a inline
  183. // style map.
  184. SourceMapConcatHelper.prototype.write = function() {
  185. if (this.options.sourceMapStyle !== 'inline') {
  186. this._write();
  187. }
  188. };
  189. return exports;
  190. };