source-map-support.js 18 KB

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