source-map-support.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  1. var SourceMapConsumer = require('source-map').SourceMapConsumer;
  2. var path = require('path');
  3. var fs = require('fs');
  4. // Only install once if called multiple times
  5. var alreadyInstalled = false;
  6. // If true, the caches are reset before a stack trace formatting operation
  7. var emptyCacheBetweenOperations = false;
  8. // Supports {browser, node, auto}
  9. var environment = "auto";
  10. // Maps a file path to a string containing the file contents
  11. var fileContentsCache = {};
  12. // Maps a file path to a source map for that file
  13. var sourceMapCache = {};
  14. // Regex for detecting source maps
  15. var reSourceMap = /^data:application\/json[^,]+base64,/;
  16. function isInBrowser() {
  17. if (environment === "browser")
  18. return true;
  19. if (environment === "node")
  20. return false;
  21. return ((typeof window !== 'undefined') && (typeof XMLHttpRequest === 'function'));
  22. }
  23. function hasGlobalProcessEventEmitter() {
  24. return ((typeof process === 'object') && (process !== null) && (typeof process.on === 'function'));
  25. }
  26. function retrieveFile(path) {
  27. // Trim the path to make sure there is no extra whitespace.
  28. path = path.trim();
  29. if (path in fileContentsCache) {
  30. return fileContentsCache[path];
  31. }
  32. try {
  33. // Use SJAX if we are in the browser
  34. if (isInBrowser()) {
  35. var xhr = new XMLHttpRequest();
  36. xhr.open('GET', path, false);
  37. xhr.send(null);
  38. var contents = null
  39. if (xhr.readyState === 4 && xhr.status === 200) {
  40. contents = xhr.responseText
  41. }
  42. }
  43. // Otherwise, use the filesystem
  44. else {
  45. var contents = fs.readFileSync(path, 'utf8');
  46. }
  47. } catch (e) {
  48. var contents = null;
  49. }
  50. return fileContentsCache[path] = contents;
  51. }
  52. // Support URLs relative to a directory, but be careful about a protocol prefix
  53. // in case we are in the browser (i.e. directories may start with "http://")
  54. function supportRelativeURL(file, url) {
  55. if (!file) return url;
  56. var dir = path.dirname(file);
  57. var match = /^\w+:\/\/[^\/]*/.exec(dir);
  58. var protocol = match ? match[0] : '';
  59. return protocol + path.resolve(dir.slice(protocol.length), url);
  60. }
  61. function retrieveSourceMapURL(source) {
  62. var fileData;
  63. if (isInBrowser()) {
  64. var xhr = new XMLHttpRequest();
  65. xhr.open('GET', source, false);
  66. xhr.send(null);
  67. fileData = xhr.readyState === 4 ? xhr.responseText : null;
  68. // Support providing a sourceMappingURL via the SourceMap header
  69. var sourceMapHeader = xhr.getResponseHeader("SourceMap") ||
  70. xhr.getResponseHeader("X-SourceMap");
  71. if (sourceMapHeader) {
  72. return sourceMapHeader;
  73. }
  74. }
  75. // Get the URL of the source map
  76. fileData = retrieveFile(source);
  77. // //# sourceMappingURL=foo.js.map /*# sourceMappingURL=foo.js.map */
  78. var re = /(?:\/\/[@#][ \t]+sourceMappingURL=([^\s'"]+?)[ \t]*$)|(?:\/\*[@#][ \t]+sourceMappingURL=([^\*]+?)[ \t]*(?:\*\/)[ \t]*$)/mg;
  79. // Keep executing the search to find the *last* sourceMappingURL to avoid
  80. // picking up sourceMappingURLs from comments, strings, etc.
  81. var lastMatch, match;
  82. while (match = re.exec(fileData)) lastMatch = match;
  83. if (!lastMatch) return null;
  84. return lastMatch[1];
  85. };
  86. // Can be overridden by the retrieveSourceMap option to install. Takes a
  87. // generated source filename; returns a {map, optional url} object, or null if
  88. // there is no source map. The map field may be either a string or the parsed
  89. // JSON object (ie, it must be a valid argument to the SourceMapConsumer
  90. // constructor).
  91. function retrieveSourceMap(source) {
  92. var sourceMappingURL = retrieveSourceMapURL(source);
  93. if (!sourceMappingURL) return null;
  94. // Read the contents of the source map
  95. var sourceMapData;
  96. if (reSourceMap.test(sourceMappingURL)) {
  97. // Support source map URL as a data url
  98. var rawData = sourceMappingURL.slice(sourceMappingURL.indexOf(',') + 1);
  99. sourceMapData = new Buffer(rawData, "base64").toString();
  100. sourceMappingURL = null;
  101. } else {
  102. // Support source map URLs relative to the source URL
  103. sourceMappingURL = supportRelativeURL(source, sourceMappingURL);
  104. sourceMapData = retrieveFile(sourceMappingURL);
  105. }
  106. if (!sourceMapData) {
  107. return null;
  108. }
  109. return {
  110. url: sourceMappingURL,
  111. map: sourceMapData
  112. };
  113. }
  114. function mapSourcePosition(position) {
  115. var sourceMap = sourceMapCache[position.source];
  116. if (!sourceMap) {
  117. // Call the (overrideable) retrieveSourceMap function to get the source map.
  118. var urlAndMap = retrieveSourceMap(position.source);
  119. if (urlAndMap) {
  120. sourceMap = sourceMapCache[position.source] = {
  121. url: urlAndMap.url,
  122. map: new SourceMapConsumer(urlAndMap.map)
  123. };
  124. // Load all sources stored inline with the source map into the file cache
  125. // to pretend like they are already loaded. They may not exist on disk.
  126. if (sourceMap.map.sourcesContent) {
  127. sourceMap.map.sources.forEach(function(source, i) {
  128. var contents = sourceMap.map.sourcesContent[i];
  129. if (contents) {
  130. var url = supportRelativeURL(sourceMap.url, source);
  131. fileContentsCache[url] = contents;
  132. }
  133. });
  134. }
  135. } else {
  136. sourceMap = sourceMapCache[position.source] = {
  137. url: null,
  138. map: null
  139. };
  140. }
  141. }
  142. // Resolve the source URL relative to the URL of the source map
  143. if (sourceMap && sourceMap.map) {
  144. var originalPosition = sourceMap.map.originalPositionFor(position);
  145. // Only return the original position if a matching line was found. If no
  146. // matching line is found then we return position instead, which will cause
  147. // the stack trace to print the path and line for the compiled file. It is
  148. // better to give a precise location in the compiled file than a vague
  149. // location in the original file.
  150. if (originalPosition.source !== null) {
  151. originalPosition.source = supportRelativeURL(
  152. sourceMap.url, originalPosition.source);
  153. return originalPosition;
  154. }
  155. }
  156. return position;
  157. }
  158. // Parses code generated by FormatEvalOrigin(), a function inside V8:
  159. // https://code.google.com/p/v8/source/browse/trunk/src/messages.js
  160. function mapEvalOrigin(origin) {
  161. // Most eval() calls are in this format
  162. var match = /^eval at ([^(]+) \((.+):(\d+):(\d+)\)$/.exec(origin);
  163. if (match) {
  164. var position = mapSourcePosition({
  165. source: match[2],
  166. line: match[3],
  167. column: match[4] - 1
  168. });
  169. return 'eval at ' + match[1] + ' (' + position.source + ':' +
  170. position.line + ':' + (position.column + 1) + ')';
  171. }
  172. // Parse nested eval() calls using recursion
  173. match = /^eval at ([^(]+) \((.+)\)$/.exec(origin);
  174. if (match) {
  175. return 'eval at ' + match[1] + ' (' + mapEvalOrigin(match[2]) + ')';
  176. }
  177. // Make sure we still return useful information if we didn't find anything
  178. return origin;
  179. }
  180. // This is copied almost verbatim from the V8 source code at
  181. // https://code.google.com/p/v8/source/browse/trunk/src/messages.js. The
  182. // implementation of wrapCallSite() used to just forward to the actual source
  183. // code of CallSite.prototype.toString but unfortunately a new release of V8
  184. // did something to the prototype chain and broke the shim. The only fix I
  185. // could find was copy/paste.
  186. function CallSiteToString() {
  187. var fileName;
  188. var fileLocation = "";
  189. if (this.isNative()) {
  190. fileLocation = "native";
  191. } else {
  192. fileName = this.getScriptNameOrSourceURL();
  193. if (!fileName && this.isEval()) {
  194. fileLocation = this.getEvalOrigin();
  195. fileLocation += ", "; // Expecting source position to follow.
  196. }
  197. if (fileName) {
  198. fileLocation += fileName;
  199. } else {
  200. // Source code does not originate from a file and is not native, but we
  201. // can still get the source position inside the source string, e.g. in
  202. // an eval string.
  203. fileLocation += "<anonymous>";
  204. }
  205. var lineNumber = this.getLineNumber();
  206. if (lineNumber != null) {
  207. fileLocation += ":" + lineNumber;
  208. var columnNumber = this.getColumnNumber();
  209. if (columnNumber) {
  210. fileLocation += ":" + columnNumber;
  211. }
  212. }
  213. }
  214. var line = "";
  215. var functionName = this.getFunctionName();
  216. var addSuffix = true;
  217. var isConstructor = this.isConstructor();
  218. var isMethodCall = !(this.isToplevel() || isConstructor);
  219. if (isMethodCall) {
  220. var typeName = this.getTypeName();
  221. var methodName = this.getMethodName();
  222. if (functionName) {
  223. if (typeName && functionName.indexOf(typeName) != 0) {
  224. line += typeName + ".";
  225. }
  226. line += functionName;
  227. if (methodName && functionName.indexOf("." + methodName) != functionName.length - methodName.length - 1) {
  228. line += " [as " + methodName + "]";
  229. }
  230. } else {
  231. line += typeName + "." + (methodName || "<anonymous>");
  232. }
  233. } else if (isConstructor) {
  234. line += "new " + (functionName || "<anonymous>");
  235. } else if (functionName) {
  236. line += functionName;
  237. } else {
  238. line += fileLocation;
  239. addSuffix = false;
  240. }
  241. if (addSuffix) {
  242. line += " (" + fileLocation + ")";
  243. }
  244. return line;
  245. }
  246. function cloneCallSite(frame) {
  247. var object = {};
  248. Object.getOwnPropertyNames(Object.getPrototypeOf(frame)).forEach(function(name) {
  249. object[name] = /^(?:is|get)/.test(name) ? function() { return frame[name].call(frame); } : frame[name];
  250. });
  251. object.toString = CallSiteToString;
  252. return object;
  253. }
  254. function wrapCallSite(frame) {
  255. // Most call sites will return the source file from getFileName(), but code
  256. // passed to eval() ending in "//# sourceURL=..." will return the source file
  257. // from getScriptNameOrSourceURL() instead
  258. var source = frame.getFileName() || frame.getScriptNameOrSourceURL();
  259. if (source) {
  260. var line = frame.getLineNumber();
  261. var column = frame.getColumnNumber() - 1;
  262. // Fix position in Node where some (internal) code is prepended.
  263. // See https://github.com/evanw/node-source-map-support/issues/36
  264. if (line === 1 && !isInBrowser() && !frame.isEval()) {
  265. column -= 62;
  266. }
  267. var position = mapSourcePosition({
  268. source: source,
  269. line: line,
  270. column: column
  271. });
  272. frame = cloneCallSite(frame);
  273. frame.getFileName = function() { return position.source; };
  274. frame.getLineNumber = function() { return position.line; };
  275. frame.getColumnNumber = function() { return position.column + 1; };
  276. frame.getScriptNameOrSourceURL = function() { return position.source; };
  277. return frame;
  278. }
  279. // Code called using eval() needs special handling
  280. var origin = frame.isEval() && frame.getEvalOrigin();
  281. if (origin) {
  282. origin = mapEvalOrigin(origin);
  283. frame = cloneCallSite(frame);
  284. frame.getEvalOrigin = function() { return origin; };
  285. return frame;
  286. }
  287. // If we get here then we were unable to change the source position
  288. return frame;
  289. }
  290. // This function is part of the V8 stack trace API, for more info see:
  291. // http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi
  292. function prepareStackTrace(error, stack) {
  293. if (emptyCacheBetweenOperations) {
  294. fileContentsCache = {};
  295. sourceMapCache = {};
  296. }
  297. return error + stack.map(function(frame) {
  298. return '\n at ' + wrapCallSite(frame);
  299. }).join('');
  300. }
  301. // Generate position and snippet of original source with pointer
  302. function getErrorSource(error) {
  303. var match = /\n at [^(]+ \((.*):(\d+):(\d+)\)/.exec(error.stack);
  304. if (match) {
  305. var source = match[1];
  306. var line = +match[2];
  307. var column = +match[3];
  308. // Support the inline sourceContents inside the source map
  309. var contents = fileContentsCache[source];
  310. // Support files on disk
  311. if (!contents && fs.existsSync(source)) {
  312. contents = fs.readFileSync(source, 'utf8');
  313. }
  314. // Format the line from the original source code like node does
  315. if (contents) {
  316. var code = contents.split(/(?:\r\n|\r|\n)/)[line - 1];
  317. if (code) {
  318. return source + ':' + line + '\n' + code + '\n' +
  319. new Array(column).join(' ') + '^';
  320. }
  321. }
  322. }
  323. return null;
  324. }
  325. function printErrorAndExit (error) {
  326. var source = getErrorSource(error);
  327. if (source) {
  328. console.error();
  329. console.error(source);
  330. }
  331. console.error(error.stack);
  332. process.exit(1);
  333. }
  334. function shimEmitUncaughtException () {
  335. var origEmit = process.emit;
  336. process.emit = function (type) {
  337. if (type === 'uncaughtException') {
  338. var hasStack = (arguments[1] && arguments[1].stack);
  339. var hasListeners = (this.listeners(type).length > 0);
  340. if (hasStack && !hasListeners) {
  341. return printErrorAndExit(arguments[1]);
  342. }
  343. }
  344. return origEmit.apply(this, arguments);
  345. }
  346. }
  347. exports.wrapCallSite = wrapCallSite;
  348. exports.getErrorSource = getErrorSource;
  349. exports.mapSourcePosition = mapSourcePosition;
  350. exports.retrieveSourceMap = retrieveSourceMap;
  351. exports.install = function(options) {
  352. if (!alreadyInstalled) {
  353. alreadyInstalled = true;
  354. Error.prepareStackTrace = prepareStackTrace;
  355. // Configure options
  356. options = options || {};
  357. var installHandler = 'handleUncaughtExceptions' in options ?
  358. options.handleUncaughtExceptions : true;
  359. emptyCacheBetweenOperations = 'emptyCacheBetweenOperations' in options ?
  360. options.emptyCacheBetweenOperations : false;
  361. if (options.environment) {
  362. environment = options.environment;
  363. if (["node", "browser", "auto"].indexOf(environment) === -1)
  364. throw new Error("environment " + environment + " was unknown. Available options are {auto, browser, node}")
  365. }
  366. // Allow sources to be found by methods other than reading the files
  367. // directly from disk.
  368. if (options.retrieveFile)
  369. retrieveFile = options.retrieveFile;
  370. // Allow source maps to be found by methods other than reading the files
  371. // directly from disk.
  372. if (options.retrieveSourceMap)
  373. retrieveSourceMap = options.retrieveSourceMap;
  374. // Provide the option to not install the uncaught exception handler. This is
  375. // to support other uncaught exception handlers (in test frameworks, for
  376. // example). If this handler is not installed and there are no other uncaught
  377. // exception handlers, uncaught exceptions will be caught by node's built-in
  378. // exception handler and the process will still be terminated. However, the
  379. // generated JavaScript code will be shown above the stack trace instead of
  380. // the original source code.
  381. if (installHandler && hasGlobalProcessEventEmitter()) {
  382. shimEmitUncaughtException();
  383. }
  384. }
  385. };