initial commit

This commit is contained in:
Evan Wallace 2013-01-17 23:56:20 -08:00
commit c50758519f
4 changed files with 341 additions and 0 deletions

74
README.md Normal file
View File

@ -0,0 +1,74 @@
# Source Map Support
This module provides source map support for stack traces in node via the [V8 stack trace API](http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi). It uses the [source-map](https://github.com/mozilla/source-map) module to replace the paths and line numbers of source-mapped files with their original paths and line numbers. The output mimics node's stack trace format with the goal of making every compile-to-JS language more of a first-class citizen. This module takes effect globally and should be initialized by inserting a call to require('source-map-support') at the top of your code.
### CoffeeScript Demo
The following terminal commands show a stack trace in node with CoffeeScript filenames:
$ cat > demo.coffee
require 'source-map-support'
foo = ->
bar = -> throw new Error 'this is a demo'
bar()
foo()
$ npm install source-map-support
$ git clone https://github.com/michaelficarra/CoffeeScriptRedux.git
$ cd CoffeeScriptRedux && npm install && cd ..
$ CoffeeScriptRedux/bin/coffee --js -i demo.coffee > demo.js
$ echo '//@ sourceMappingURL=demo.js.map' >> demo.js
$ CoffeeScriptRedux/bin/coffee --source-map -i demo.coffee > demo.js.map
$ node demo
demo.coffee:4
bar = -> throw new Error 'this is a demo'
^
Error: this is a demo
at bar (demo.coffee:4:19)
at foo (demo.coffee:5:3)
at Object.<anonymous> (demo.coffee:6:3)
at Object.<anonymous> (demo.coffee:6:6)
at Module._compile (module.js:449:26)
at Object.Module._extensions..js (module.js:467:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.runMain (module.js:492:10)
at process.startup.processNextTick.process._tickCallback (node.js:244:9)
### TypeScript Demo
The following terminal commands show a stack trace in node with TypeScript filenames:
$ cat > demo.ts
declare function require(name: string);
require('source-map-support');
class Foo {
constructor() { this.bar(); }
bar() { throw new Error('this is a demo'); }
}
new Foo();
$ npm install source-map-support typescript
$ node_modules/typescript/bin/tsc -sourcemap demo.ts
$ node demo
demo.ts:6
bar() { throw new Error('this is a demo'); }
^
Error: this is a demo
at Foo.bar (demo.ts:6:16)
at new Foo (demo.ts:5:23)
at Object.<anonymous> (demo.ts:8)
at Module._compile (module.js:449:26)
at Object.Module._extensions..js (module.js:467:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.runMain (module.js:492:10)
at process.startup.processNextTick.process._tickCallback (node.js:244:9)
### License
This code is available under the [MIT license](http://opensource.org/licenses/MIT).

14
package.json Normal file
View File

@ -0,0 +1,14 @@
{
"name": "source-map-support",
"version": "0.1.0",
"main": "./source-map-support.js",
"scripts": {
"test": "node_modules/mocha/bin/mocha"
},
"dependencies": {
"source-map": "0.1.8"
},
"devDependencies": {
"mocha": "1.8.1"
}
}

125
source-map-support.js Normal file
View File

@ -0,0 +1,125 @@
var SourceMapConsumer = require('source-map').SourceMapConsumer;
var path = require('path');
var fs = require('fs');
function mapSourcePosition(cache, position) {
var sourceMap = cache[position.source];
if (!sourceMap && fs.existsSync(position.source)) {
// Get the URL of the source map
var fileData = fs.readFileSync(position.source, 'utf8');
var match = /\/\/@\s*sourceMappingURL=(.*)\s*$/.exec(fileData);
if (!match) return position;
var sourceMappingURL = match[1];
// Support source map URLs relative to the source URL
var dir = path.dirname(position.source);
sourceMappingURL = path.resolve(dir, sourceMappingURL);
// Parse the source map
var sourceMap = cache[sourceMappingURL];
if (!sourceMap && fs.existsSync(sourceMappingURL)) {
var sourceMapData = fs.readFileSync(sourceMappingURL, 'utf8');
try {
sourceMap = new SourceMapConsumer(sourceMapData);
cache[position.source] = sourceMap;
} catch (e) {
}
}
}
return sourceMap ? sourceMap.originalPositionFor(position) : position;
}
// Parses code generated by FormatEvalOrigin(), a function inside V8:
// https://code.google.com/p/v8/source/browse/trunk/src/messages.js
function mapEvalOrigin(cache, origin) {
// Most eval() calls are in this format
var match = /^eval at ([^(]+) \((.+):(\d+):(\d+)\)$/.exec(origin);
if (match) {
var position = mapSourcePosition(cache, {
source: match[2],
line: match[3],
column: match[4]
});
return 'eval at ' + match[1] + ' (' + position.source + ':' +
position.line + ':' + position.column + ')';
}
// Parse nested eval() calls using recursion
match = /^eval at ([^(]+) \((.+)\)$/.exec(origin);
if (match) {
return 'eval at ' + match[1] + ' (' + mapEvalOrigin(cache, match[2]) + ')';
}
// Make sure we still return useful information if we didn't find anything
return origin;
}
function wrapCallSite(cache, frame) {
// Most call sites will return the source file from getFileName(), but code
// passed to eval() ending in "//@ sourceURL=..." will return the source file
// from getScriptNameOrSourceURL() instead
var source = frame.getFileName() || frame.getScriptNameOrSourceURL();
if (source) {
var position = mapSourcePosition(cache, {
source: source,
line: frame.getLineNumber(),
column: frame.getColumnNumber()
});
return {
__proto__: frame,
getFileName: function() { return position.source; },
getLineNumber: function() { return position.line; },
getColumnNumber: function() { return position.column; },
getScriptNameOrSourceURL: function() { return position.source; }
};
}
// Code called using eval() needs special handling
var origin = frame.getEvalOrigin();
if (origin) {
origin = mapEvalOrigin(cache, origin);
return {
__proto__: frame,
getEvalOrigin: function() { return origin; }
};
}
// If we get here then we were unable to change the source position
return frame;
}
// This function is part of the V8 stack trace API, for more info see:
// http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi
Error.prepareStackTrace = function(error, stack) {
// Store source maps in a cache so we don't load them more than once when
// formatting a single stack trace (don't cache them forever though in case
// the files change on disk and the user wants to see the updated mapping)
var cache = {};
return error + stack.map(function(frame) {
return '\n at ' + wrapCallSite(cache, frame);
}).join('');
};
// Mimic node's stack trace printing when an exception escapes the process
process.on('uncaughtException', function(error) {
var match = /\n at [^(]+ \((.*):(\d+):(\d+)\)/.exec(error.stack);
if (match) {
var cache = {};
var position = mapSourcePosition(cache, {
source: match[1],
line: match[2],
column: match[3]
});
if (fs.existsSync(position.source)) {
var contents = fs.readFileSync(position.source, 'utf8');
var line = contents.split(/(?:\r\n|\r|\n)/)[position.line - 1];
if (line) {
console.log('\n' + position.source + ':' + position.line);
console.log(line);
console.log(new Array(+position.column).join(' ') + '^');
}
}
}
console.log(error.stack);
process.exit();
});

128
test.js Normal file
View File

@ -0,0 +1,128 @@
require('./source-map-support');
var SourceMapGenerator = require('source-map').SourceMapGenerator;
var assert = require('assert');
var fs = require('fs');
// Create a source map
var sourceMap = new SourceMapGenerator({
file: '.generated.js',
sourceRoot: '.'
});
for (var i = 1; i <= 100; i++) {
sourceMap.addMapping({
generated: { line: i, column: 1 },
original: { line: 1000 + i, column: 100 + i },
source: 'line' + i + '.js'
});
}
function compareStackTrace(source, expected) {
fs.writeFileSync('.generated.js.map', sourceMap);
fs.writeFileSync('.generated.js', 'exports.test = function() {' +
source.join('\n') + '};//@ sourceMappingURL=.generated.js.map');
try {
delete require.cache[require.resolve('./.generated')];
require('./.generated').test();
} catch (e) {
expected = expected.join('\n');
assert.equal(e.stack.slice(0, expected.length), expected);
}
fs.unlinkSync('.generated.js');
fs.unlinkSync('.generated.js.map');
}
it('normal throw', function() {
compareStackTrace([
'throw new Error("test");'
], [
'Error: test',
' at Object.exports.test (./line1.js:1001:101)'
]);
});
it('throw inside function', function() {
compareStackTrace([
'function foo() {',
' throw new Error("test");',
'}',
'foo();'
], [
'Error: test',
' at foo (./line2.js:1002:102)',
' at Object.exports.test (./line4.js:1004:104)'
]);
});
it('throw inside function inside function', function() {
compareStackTrace([
'function foo() {',
' function bar() {',
' throw new Error("test");',
' }',
' bar();',
'}',
'foo();'
], [
'Error: test',
' at bar (./line3.js:1003:103)',
' at foo (./line5.js:1005:105)',
' at Object.exports.test (./line7.js:1007:107)'
]);
});
it('eval', function() {
compareStackTrace([
'eval("throw new Error(\'test\')");'
], [
'Error: test',
' at Object.eval (eval at <anonymous> (./line1.js:1001:101))',
' at Object.exports.test (./line1.js:1001:101)'
]);
});
it('eval inside eval', function() {
compareStackTrace([
'eval("eval(\'throw new Error(\\"test\\")\')");'
], [
'Error: test',
' at Object.eval (eval at <anonymous> (eval at <anonymous> (./line1.js:1001:101)))',
' at Object.eval (eval at <anonymous> (./line1.js:1001:101))',
' at Object.exports.test (./line1.js:1001:101)'
]);
});
it('eval inside function', function() {
compareStackTrace([
'function foo() {',
' eval("throw new Error(\'test\')");',
'}',
'foo();'
], [
'Error: test',
' at eval (eval at foo (./line2.js:1002:102))',
' at foo (./line2.js:1002:102)',
' at Object.exports.test (./line4.js:1004:104)'
]);
});
it('eval with sourceURL', function() {
compareStackTrace([
'eval("throw new Error(\'test\')//@ sourceURL=sourceURL.js");'
], [
'Error: test',
' at Object.eval (sourceURL.js:1:7)',
' at Object.exports.test (./line1.js:1001:101)'
]);
});
it('eval with sourceURL inside eval', function() {
compareStackTrace([
'eval("eval(\'throw new Error(\\"test\\")//@ sourceURL=sourceURL.js\')");'
], [
'Error: test',
' at Object.eval (sourceURL.js:1:7)',
' at Object.eval (eval at <anonymous> (./line1.js:1001:101))',
' at Object.exports.test (./line1.js:1001:101)'
]);
});