UNPKG

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