Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TraceKit can now be used on frames #68

Open
wants to merge 17 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions _config.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
theme: jekyll-theme-tactile
117 changes: 69 additions & 48 deletions tracekit.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ var UNKNOWN_FUNCTION = '?';

// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Error_types
var ERROR_TYPES_RE = /^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/;

/**
* A better form of hasOwnProperty<br/>
* Example: `_has(MainHostObject, property) === true/false`
Expand Down Expand Up @@ -121,66 +120,86 @@ TraceKit.report = (function reportModuleWrapper() {
lastException = null,
lastExceptionStack = null;


/**
* Can the window be used
* @param {type} win
* @returns {boolean}
* @memberof TraceKit.report
*/
function isWindowAccessible(win) {
try {
return (win.location.href);
} catch (e) { return false; }
}
/**
* Add a crash handler.
* @param {Function} handler
* @param {window} win default is current window. Need if you want to subcribe tracekit to another window/frame
* @memberof TraceKit.report
*/
function subscribe(handler) {
installGlobalHandler();
installGlobalUnhandledRejectionHandler();
handlers.push(handler);

function subscribe(handler, win) {
win = (win || window);
if (isWindowAccessible(win)) {
TraceKit.windowPointer = win;
installGlobalHandler(handler, win);
}
}

/**
* Remove a crash handler.
* @param {Function} handler
* @param {window} win default is current window. Need if you want to unsubcribe tracekit to another window/frame
* @memberof TraceKit.report
*/
function unsubscribe(handler) {
function unsubscribe(handler, win) {
win = (win || window);
if (isWindowAccessible(win)) {
for (var i = handlers.length - 1; i >= 0; --i) {
if (handlers[i] === handler) {
if (handlers[i][0] === handler && win === handlers[i][1]) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What's all stored on handler now in this array?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We weren't doing this before, but since you are calling unsubscribe and you have an array with the previous error handler. Do you think we should be setting it back?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point, i will insert the code

// put back the old event handler
// win.onerror = handlers[i][2];
// remove handler from handlers
handlers.splice(i, 1);
}
}

if (handlers.length === 0) {
uninstallGlobalHandler();
uninstallGlobalUnhandledRejectionHandler();
}
}
}

/**
* Dispatch stack information to all handlers.
* @param {TraceKit.StackTrace} stack
* @param {boolean} isWindowError Is this a top-level window error?
* @param {Error=} error The error that's being handled (if available, null otherwise)
* @param {array} args all the arguments from onerror event. Array of [Message, url, lineNo, columnNo, errorObj]
* @memberof TraceKit.report
* @throws An exception if an error occurs while calling an handler.
*/
function notifyHandlers(stack, isWindowError, error) {
function notifyHandlers(stack, isWindowError, args) {
var exception = null;
if (isWindowError && !TraceKit.collectWindowErrors) {
return;
}
for (var i in handlers) {
if (_has(handlers, i)) {
if (_has(handlers, i) && handlers[i][1] === TraceKit.windowPointer) {
try {
handlers[i](stack, isWindowError, error);
var errorObj=(args.length > 4) ? args[4] : null;
handlers[i][0](stack, isWindowError, errorObj);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is kind of confusing, so we call a method with stack, isWindowErorr and an array with 4 items? We seem to only be using the error object, so it might be better to revert this signature to just be error object. Previous thought: Maybe we need to add a comment stating that these arguments are actually: message, url, lineNo, columnNo, errorObj (if we were on es6, restructuring would make this so much more readable but we can't use that :(`,

} catch (inner) {
exception = inner;
}
// Call old onerror events
if (handlers[i][2]) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We weren't doing this before were we? It's just really hard to follow this and make sense of what's going on.. We call all the other handlers in a try catch.

return handlers[i][2].apply(handlers[i][1], args);
}
}
}

if (exception) {
throw exception;
}
}

var _oldOnerrorHandler, _onErrorHandlerInstalled;
var _oldOnunhandledrejectionHandler, _onUnhandledRejectionHandlerInstalled;

/**
* Ensures all global unhandled exceptions are recorded.
* Supported by Gecko and IE.
Expand All @@ -193,11 +212,11 @@ TraceKit.report = (function reportModuleWrapper() {
*/
function traceKitWindowOnError(message, url, lineNo, columnNo, errorObj) {
var stack = null;

TraceKit.windowPointer = this;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So this modifies the pointer which might of been set earlier when you subscribed. I'm not sure this should be updated as it would change the subscription handler? Thoughts?

if (lastExceptionStack) {
TraceKit.computeStackTrace.augmentStackTraceWithInitialElement(lastExceptionStack, url, lineNo, message);
processLastException();
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

any reason for not passing through the arguments?

} else if (errorObj) {
} else if (errorObj) {
stack = TraceKit.computeStackTrace(errorObj);
notifyHandlers(stack, true, errorObj);
} else {
Expand All @@ -206,7 +225,6 @@ TraceKit.report = (function reportModuleWrapper() {
'line': lineNo,
'column': columnNo
};

var name;
var msg = message; // must be new var or will modify original `arguments`
if ({}.toString.call(message) === '[object String]') {
Expand All @@ -216,22 +234,19 @@ TraceKit.report = (function reportModuleWrapper() {
msg = groups[2];
}
}

location.func = TraceKit.computeStackTrace.guessFunctionName(location.url, location.line);
location.context = TraceKit.computeStackTrace.gatherContext(location.url, location.line);
stack = {
'name': name,
'message': msg,
'mode': 'onerror',
'stack': [location]
'mode': 'onerror',
'stack': [location]
};

notifyHandlers(stack, true, null);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

any reason for not passing through the arguments?

}

if (_oldOnerrorHandler) {
return _oldOnerrorHandler.apply(this, arguments);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we were calling old handlers to preserve existing work flows.

}


return false;
}
Expand All @@ -250,16 +265,18 @@ TraceKit.report = (function reportModuleWrapper() {

/**
* Install a global onerror handler
* @param {Function} handler
* @param {window} win tracekit will be attached to this window
* @memberof TraceKit.report
*/
function installGlobalHandler() {
if (_onErrorHandlerInstalled === true) {
function installGlobalHandler(handler, win) {
if (win._onErrorHandlerInstalled === true) {
return;
}

_oldOnerrorHandler = window.onerror;
window.onerror = traceKitWindowOnError;
_onErrorHandlerInstalled = true;
var oldOnerrorHandler = win.onerror;
win.onerror = traceKitWindowOnError;
win._onErrorHandlerInstalled = true;
handlers.push([handler, win, oldOnerrorHandler]);
}

/**
Expand Down Expand Up @@ -333,8 +350,8 @@ TraceKit.report = (function reportModuleWrapper() {
// slow slow IE to see if onerror occurs or not before reporting
// this exception; otherwise, we will end up with an incomplete
// stack trace
setTimeout(function () {
if (lastException === ex) {
window.setTimeout(function () {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Any specific reason to putting this to window? It might block users from using this in node?

if (lastException == ex) {
processLastException();
}
}, (stack.incomplete ? 2000 : 0));
Expand Down Expand Up @@ -434,7 +451,8 @@ TraceKit.report = (function reportModuleWrapper() {
*/
TraceKit.computeStackTrace = (function computeStackTraceWrapper() {
var debug = false,
sourceCache = {};
sourceCache = {},
curWin = TraceKit.windowPointer;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we rename this to win


/**
* Attempts to retrieve source code via XMLHttpRequest, which is used
Expand Down Expand Up @@ -490,7 +508,9 @@ TraceKit.computeStackTrace = (function computeStackTraceWrapper() {
*/
var source = '';
var domain = '';
try { domain = window.document.domain; } catch (e) { }
try {
domain = curWin.document.domain;
} catch (e) {}
var match = /(.*)\:\/\/([^:\/]+)([:\d]*)\/{0,1}([\s\S]*)/.exec(url);
if (match && match[2] === domain) {
source = loadSource(url);
Expand Down Expand Up @@ -621,6 +641,7 @@ TraceKit.computeStackTrace = (function computeStackTraceWrapper() {
}
}


return null;
}

Expand Down Expand Up @@ -656,12 +677,12 @@ TraceKit.computeStackTrace = (function computeStackTraceWrapper() {
* @memberof TraceKit.computeStackTrace
*/
function findSourceByFunctionBody(func) {
if (_isUndefined(window && window.document)) {
if (_isUndefined(curWin && curWin.document)) {
return;
}

var urls = [window.location.href],
scripts = window.document.getElementsByTagName('script'),
var urls = [curWin.location.href],
scripts = curWin.document.getElementsByTagName('script'),
body,
code = '' + func,
codeRE = /^function(?:\s+([\w$]+))?\s*\(([\w\s,]*)\)\s*\{\s*(\S[\s\S]*\S)\s*\}\s*$/,
Expand Down Expand Up @@ -771,12 +792,10 @@ TraceKit.computeStackTrace = (function computeStackTraceWrapper() {
var chrome = /^\s*at (.*?) ?\(((?:file|https?|blob|chrome-extension|native|eval|webpack|<anonymous>|\/).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,
gecko = /^\s*(.*?)(?:\((.*?)\))?(?:^|@)((?:file|https?|blob|chrome|webpack|resource|\[native).*?|[^@]*bundle)(?::(\d+))?(?::(\d+))?\s*$/i,
winjs = /^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i,

// Used to additionally parse URL/line/column from eval frames
isEval,
geckoEval = /(\S+) line (\d+)(?: > eval line \d+)* > eval/i,
chromeEval = /\((\S*)(?::(\d+))(?::(\d+))\)/,

lines = ex.stack.split('\n'),
stack = [],
submatch,
Expand Down Expand Up @@ -839,6 +858,7 @@ TraceKit.computeStackTrace = (function computeStackTraceWrapper() {
}

element.context = element.line ? gatherContext(element.url, element.line) : null;

stack.push(element);
}

Expand Down Expand Up @@ -965,7 +985,7 @@ TraceKit.computeStackTrace = (function computeStackTraceWrapper() {
lineRE2 = /^\s*Line (\d+) of inline#(\d+) script in ((?:file|https?|blob)\S+)(?:: in function (\S+))?\s*$/i,
lineRE3 = /^\s*Line (\d+) of function script\s*$/i,
stack = [],
scripts = (window && window.document && window.document.getElementsByTagName('script')),
scripts = (curWin && curWin.document && curWin.document.getElementsByTagName('script')),
inlineScriptBlocks = [],
parts;

Expand Down Expand Up @@ -1006,7 +1026,7 @@ TraceKit.computeStackTrace = (function computeStackTraceWrapper() {
}
}
} else if ((parts = lineRE3.exec(lines[line]))) {
var url = window.location.href.replace(/#.*$/, '');
var url = curWin.location.href.replace(/#.*$/, '');
var re = new RegExp(escapeCodeAsRegExpForMatchingInsideHTML(lines[line + 1]));
var src = findSourceInUrls(re, [url]);
item = {
Expand Down Expand Up @@ -1191,6 +1211,7 @@ TraceKit.computeStackTrace = (function computeStackTraceWrapper() {
* @memberof TraceKit.computeStackTrace
*/
function computeStackTrace(ex, depth) {
curWin = TraceKit.windowPointer;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This doesn't seem to be used

var stack = null;
depth = (depth == null ? 0 : +depth);

Expand Down Expand Up @@ -1280,8 +1301,8 @@ TraceKit.computeStackTrace = (function computeStackTraceWrapper() {
*/
TraceKit.extendToAsynchronousCallbacks = function () {
var _helper = function _helper(fnName) {
var originalFn = window[fnName];
window[fnName] = function traceKitAsyncExtension() {
var originalFn = TraceKit.windowPointer[fnName];
TraceKit.windowPointer[fnName] = function traceKitAsyncExtension() {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Might want to store this in a variable

// Make a copy of the arguments
var args = _slice.call(arguments);
var originalCallback = args[0];
Expand Down Expand Up @@ -1324,4 +1345,4 @@ if (typeof define === 'function' && define.amd) {
window.TraceKit = TraceKit;
}

}(typeof window !== 'undefined' ? window : global));
}(typeof window !== 'undefined' ? window : global));