forked from bluesmoon/boomerang
/
errors.js
1544 lines (1316 loc) · 36.9 KB
/
errors.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*eslint-disable*/
//
// Via https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
//
// polyfill for Array.isArray
if (!Array.isArray) {
Array.isArray = function(arg) {
return Object.prototype.toString.call(arg) === '[object Array]';
};
}
//
// Via https://github.com/stacktracejs/error-stack-parser
// Modifications:
// * Removed UMD
// * Return anonymous objects, not StackFrames
//
(function (root, factory) {
'use strict';
root.ErrorStackParser = factory();
}(this, function ErrorStackParser() {
'use strict';
var FIREFOX_SAFARI_STACK_REGEXP = /(^|@)\S+\:\d+/;
var CHROME_IE_STACK_REGEXP = /^\s*at .*(\S+\:\d+|\(native\))/m;
var SAFARI_NATIVE_CODE_REGEXP = /^(eval@)?(\[native code\])?$/;
function _map(array, fn, thisArg) {
if (typeof Array.prototype.map === 'function') {
return array.map(fn, thisArg);
} else {
var output = new Array(array.length);
for (var i = 0; i < array.length; i++) {
output[i] = fn.call(thisArg, array[i]);
}
return output;
}
}
function _filter(array, fn, thisArg) {
if (typeof Array.prototype.filter === 'function') {
return array.filter(fn, thisArg);
} else {
var output = [];
for (var i = 0; i < array.length; i++) {
if (fn.call(thisArg, array[i])) {
output.push(array[i]);
}
}
return output;
}
}
return {
/**
* Given an Error object, extract the most information from it.
* @param error {Error}
* @return Array[]
*/
parse: function ErrorStackParser$$parse(error) {
if (typeof error.stacktrace !== 'undefined' || typeof error['opera#sourceloc'] !== 'undefined') {
return this.parseOpera(error);
} else if (error.stack && error.stack.match(CHROME_IE_STACK_REGEXP)) {
return this.parseV8OrIE(error);
} else if (error.stack) {
return this.parseFFOrSafari(error);
} else {
throw new Error('Cannot parse given Error object');
}
},
/**
* Separate line and column numbers from a URL-like string.
* @param urlLike String
* @return Array[String]
*/
extractLocation: function ErrorStackParser$$extractLocation(urlLike) {
// Fail-fast but return locations like "(native)"
if (urlLike.indexOf(':') === -1) {
return [urlLike];
}
var locationParts = urlLike.replace(/[\(\)\s]/g, '').split(':');
var lastNumber = locationParts.pop();
var possibleNumber = locationParts[locationParts.length - 1];
if (!isNaN(parseFloat(possibleNumber)) && isFinite(possibleNumber)) {
var lineNumber = locationParts.pop();
return [locationParts.join(':'), lineNumber, lastNumber];
} else {
return [locationParts.join(':'), lastNumber, undefined];
}
},
parseV8OrIE: function ErrorStackParser$$parseV8OrIE(error) {
var filtered = _filter(error.stack.split('\n'), function (line) {
return !!line.match(CHROME_IE_STACK_REGEXP);
}, this);
return _map(filtered, function (line) {
if (line.indexOf('(eval ') > -1) {
// Throw away eval information until we implement stacktrace.js/stackframe#8
line = line.replace(/eval code/g, 'eval').replace(/(\(eval at [^\()]*)|(\)\,.*$)/g, '');
}
var tokens = line.replace(/^\s+/, '').replace(/\(eval code/g, '(').split(/\s+/).slice(1);
var locationParts = this.extractLocation(tokens.pop());
var functionName = tokens.join(' ') || undefined;
var fileName = locationParts[0] === 'eval' ? undefined : locationParts[0];
return {
functionName: functionName,
fileName: fileName,
lineNumber: locationParts[1],
columnNumber: locationParts[2],
source: line
};
}, this);
},
parseFFOrSafari: function ErrorStackParser$$parseFFOrSafari(error) {
var filtered = _filter(error.stack.split('\n'), function (line) {
return !line.match(SAFARI_NATIVE_CODE_REGEXP);
}, this);
return _map(filtered, function (line) {
// Throw away eval information until we implement stacktrace.js/stackframe#8
if (line.indexOf(' > eval') > -1) {
line = line.replace(/ line (\d+)(?: > eval line \d+)* > eval\:\d+\:\d+/g, ':$1');
}
if (line.indexOf('@') === -1 && line.indexOf(':') === -1) {
// Safari eval frames only have function names and nothing else
return { functionName: line };
} else {
var tokens = line.split('@');
var locationParts = this.extractLocation(tokens.pop());
var functionName = tokens.join('@') || undefined;
return {
functionName: functionName,
fileName: locationParts[0],
lineNumber: locationParts[1],
columnNumber: locationParts[2],
source: line
};
}
}, this);
},
parseOpera: function ErrorStackParser$$parseOpera(e) {
if (!e.stacktrace || (e.message.indexOf('\n') > -1 &&
e.message.split('\n').length > e.stacktrace.split('\n').length)) {
return this.parseOpera9(e);
} else if (!e.stack) {
return this.parseOpera10(e);
} else {
return this.parseOpera11(e);
}
},
parseOpera9: function ErrorStackParser$$parseOpera9(e) {
var lineRE = /Line (\d+).*script (?:in )?(\S+)/i;
var lines = e.message.split('\n');
var result = [];
for (var i = 2, len = lines.length; i < len; i += 2) {
var match = lineRE.exec(lines[i]);
if (match) {
result.push({
fileName: match[2],
lineNumber: match[1],
source: lines[i]
});
}
}
return result;
},
parseOpera10: function ErrorStackParser$$parseOpera10(e) {
var lineRE = /Line (\d+).*script (?:in )?(\S+)(?:: In function (\S+))?$/i;
var lines = e.stacktrace.split('\n');
var result = [];
for (var i = 0, len = lines.length; i < len; i += 2) {
var match = lineRE.exec(lines[i]);
if (match) {
result.push({
functionName: match[3] || undefined,
fileName: match[2],
lineNumber: match[1],
source: lines[i]
});
}
}
return result;
},
// Opera 10.65+ Error.stack very similar to FF/Safari
parseOpera11: function ErrorStackParser$$parseOpera11(error) {
var filtered = _filter(error.stack.split('\n'), function (line) {
return !!line.match(FIREFOX_SAFARI_STACK_REGEXP) &&
!line.match(/^Error created at/);
}, this);
return _map(filtered, function (line) {
var tokens = line.split('@');
var locationParts = this.extractLocation(tokens.pop());
var functionCall = (tokens.shift() || '');
var functionName = functionCall
.replace(/<anonymous function(: (\w+))?>/, '$2')
.replace(/\([^\)]*\)/g, '') || undefined;
var argsRaw;
if (functionCall.match(/\(([^\)]*)\)/)) {
argsRaw = functionCall.replace(/^[^\(]+\(([^\)]*)\)$/, '$1');
}
var args = (argsRaw === undefined || argsRaw === '[arguments not available]') ? undefined : argsRaw.split(',');
return {
functionName: functionName,
args: args,
fileName: locationParts[0],
lineNumber: locationParts[1],
columnNumber: locationParts[2],
source: line
};
}, this);
}
};
}));
/*eslint-enable*/
/**
* Boomerang Error plugin
*/
(function() {
var impl;
BOOMR = BOOMR || {};
BOOMR.plugins = BOOMR.plugins || {};
if (BOOMR.plugins.Errors) {
return;
}
//
// Constants
//
// functions to strip
var STACK_FUNCTIONS_REMOVE = [
"BOOMR_addError",
"BOOMR_plugins_errors_wrap"
];
/**
* Maximum size, in characters, of stack to capture
*/
var MAX_STACK_SIZE = 5000;
/**
* BoomerangError object
*
* @param {object} config Configuration
*/
function BoomerangError(config) {
config = config || {};
// how many times we've seen this error
if (typeof config.count === "number" || typeof config.count === "string") {
this.count = parseInt(config.count, 10);
}
else {
this.count = 1;
}
if (typeof config.timestamp === "number") {
this.timestamp = config.timestamp;
}
else {
this.timestamp = BOOMR.now();
}
// merge in properties from config
if (typeof config.code === "number" || typeof config.code === "string") {
this.code = parseInt(config.code, 10);
}
if (typeof config.message === "string") {
this.message = config.message;
}
if (typeof config.functionName === "string") {
this.functionName = config.functionName;
}
if (typeof config.fileName === "string") {
this.fileName = config.fileName;
}
if (typeof config.lineNumber === "number" || typeof config.lineNumber === "string") {
this.lineNumber = parseInt(config.lineNumber, 10);
}
if (typeof config.columnNumber === "number" || typeof config.columnNumber === "string") {
this.columnNumber = parseInt(config.columnNumber, 10);
}
if (typeof config.stack === "string") {
this.stack = config.stack;
}
if (typeof config.type === "string") {
this.type = config.type;
}
if (typeof config.extra !== "undefined") {
this.extra = config.extra;
}
this.source = (typeof config.source === "number" || typeof config.source === "string") ?
parseInt(config.source, 10) :
BOOMR.plugins.Errors.SOURCE_APP;
if (typeof config.via === "number" || typeof config.via === "string") {
this.via = parseInt(config.via, 10);
}
if (Array.isArray(config.frames)) {
this.frames = config.frames;
}
else {
this.frames = [];
}
if (Array.isArray(config.events)) {
this.events = config.events;
}
else {
this.events = [];
}
}
/**
* Determines if one BoomerangError object is equal to another
*
* @param {object} other Object to compare to
*
* @returns {boolean} True if the two objects are logically equal errors
*/
BoomerangError.prototype.equals = function(other) {
if (typeof other !== "object") {
return false;
}
else if (this.code !== other.code) {
return false;
}
else if (this.message !== other.message) {
return false;
}
else if (this.functionName !== other.functionName) {
return false;
}
else if (this.fileName !== other.fileName) {
return false;
}
else if (this.lineNumber !== other.lineNumber) {
return false;
}
else if (this.columnNumber !== other.columnNumber) {
return false;
}
else if (this.stack !== other.stack) {
return false;
}
else if (this.type !== other.type) {
return false;
}
else if (this.source !== other.source) {
return false;
}
else {
// same!
return true;
}
};
/**
* Creates a BoomerangError from an Error
*
* @param {Error} error Error object
* @param {number} via How the Error was found (VIA_* enum)
* @param {number} source Source of the error (SOURCE_* enum)
*
* @returns {BoomerangError} Error
*/
BoomerangError.fromError = function(error, via, source) {
var frame, frames, lastFrame, forceUpdate = false, i, j,
now = BOOMR.now();
if (!error) {
return null;
}
// parse the stack
if (error.stack) {
if (error.stack.length > MAX_STACK_SIZE) {
error.stack = error.stack.substr(0, MAX_STACK_SIZE);
}
frames = ErrorStackParser.parse(error);
if (frames && frames.length) {
if (error.generatedStack) {
// if we generated the stack (we were only given a message),
// we should remove our stack-generation function from it
// fix-up stack generation on Chrome
if (frames.length >= 4 &&
frames[1].functionName &&
frames[1].functionName.indexOf("createStackForSend") !== -1) {
// remove the top 3 frames
frames = frames.slice(3);
forceUpdate = true;
}
// fix-up stack generation on Firefox
if (frames.length >= 3 &&
frames[0].functionName &&
frames[0].functionName.indexOf("createStackForSend") !== -1) {
// remove the top 2 frames
frames = frames.slice(2);
forceUpdate = true;
}
// strip other stack generators
if (frames.length >= 1 &&
frames[0].functionName &&
frames[0].functionName.indexOf("BOOMR_plugins_errors") !== -1) {
frames = frames.slice(1);
forceUpdate = true;
}
}
// remove our error wrappers from the stack
for (i = 0; i < frames.length; i++) {
if (frames[i].functionName) {
for (j = 0; j < STACK_FUNCTIONS_REMOVE.length; j++) {
if (frames[i].functionName.indexOf(STACK_FUNCTIONS_REMOVE[j]) !== -1) {
frames.splice(i, 1);
forceUpdate = true;
// outloop continues with the next element
i--;
break;
}
}
}
}
// get the top frame
frame = frames[0];
// fill in our error with the top frame, if not already specified
if (forceUpdate || typeof error.lineNumber === "undefined") {
error.lineNumber = frame.lineNumber;
}
if (forceUpdate || typeof error.columnNumber === "undefined") {
error.columnNumber = frame.columnNumber;
}
if (forceUpdate || typeof error.functionName === "undefined") {
error.functionName = frame.functionName;
}
if (forceUpdate || typeof error.fileName === "undefined") {
error.fileName = frame.fileName;
}
// trim stack down
if (error.stack) {
// remove double-spaces
error.stack = error.stack.replace(/\s\s+/g, " ");
}
}
}
else if (error.functionName ||
error.fileName ||
error.lineNumber ||
error.columnNumber) {
// reconstruct a single frame if given fileName, etc
frames = [{
lineNumber: error.lineNumber,
columnNumber: error.columnNumber,
fileName: error.fileName,
functionName: error.functionName
}];
}
// fixup some old browser types
if (error.message.indexOf("ReferenceError:") !== -1
&& error.name === "Error") {
error.name = "ReferenceError";
}
// create our final object
var err = new BoomerangError({
code: error.code ? error.code : undefined,
message: error.message ? error.message : undefined,
functionName: error.functionName ? error.functionName : undefined,
fileName: error.fileName ? error.fileName : undefined,
lineNumber: error.lineNumber ? error.lineNumber : undefined,
columnNumber: error.columnNumber ? error.columnNumber : undefined,
stack: error.stack ? error.stack : undefined,
type: error.name ? error.name : undefined,
source: source,
via: via,
frames: frames,
extra: error.extra ? error.extra : undefined,
timestamp: error.timestamp ? error.timestamp : now
});
return err;
};
//
// Internal config
//
impl = {
//
// Configuration
//
// overridable
onError: undefined,
monitorGlobal: true,
monitorNetwork: true,
monitorConsole: true,
monitorEvents: true,
monitorTimeout: true,
sendAfterOnload: false,
isDuringLoad: true,
maxErrors: 10,
sendInterval: 1000,
sendIntervalId: -1,
maxEvents: 10,
// state
initialized: false,
supported: false,
/**
* All errors
*/
errors: [],
/**
* Errors queued up for the next batch
*/
q: [],
/**
* Circular event buffer
*/
events: [],
//
// Public Functions
//
/**
* Sends an error
*
* @param {Error|String} error Error object or message
*/
send: function(error, via, source) {
var now = BOOMR.now();
if (!error) {
return;
}
// defaults, if not specified
via = via || BOOMR.plugins.Errors.VIA_APP;
source = source || BOOMR.plugins.Errors.SOURCE_APP;
// if we weren't given a stack, try to create one
if (!error.stack && !error.noStack) {
// run this in a function so we can detect it easier by the name,
// and remove it from any stack frames we send
function createStackForSend() {
try {
throw Error(error);
}
catch (ex) {
error = ex;
// note we generated this stack for later
error.generatedStack = true;
// set the time when it was created
error.timestamp = now;
impl.addError(error, via, source);
}
}
createStackForSend();
}
else {
// add the timestamp
error.timestamp = now;
// send (or queue) the error
impl.addError(error, via, source);
}
},
//
// Private Functions
//
/**
* Sends (or queues) errors
*
* @param {Error} error Error
* @param {number} via VIA_* constant
* @param {number} source SOURCE_* constant
*/
addError: function(error, via, source) {
var onErrorResult, err, dup = false;
// only track post-load errors if configured
if (!impl.isDuringLoad && !impl.sendAfterOnload) {
return;
}
// allow the user to filter out the error
if (impl.onError) {
try {
onErrorResult = impl.onError(error);
}
catch (exc) {
onErrorResult = false;
}
if (!onErrorResult) {
return;
}
}
// obey the errors limit
if (impl.errors.length >= impl.maxErrors) {
return;
}
// convert into our object
err = BoomerangError.fromError(error, via, source);
// add to our list of errors seen for all time
dup = impl.mergeDuplicateErrors(impl.errors, err, false);
// fire an error event with the duped or new error
BOOMR.fireEvent("onerror", dup || err);
// add to our current queue
impl.mergeDuplicateErrors(impl.q, err, true);
if (!impl.isDuringLoad && impl.sendIntervalId === -1) {
if (dup) {
// If this is not during a load, and it's a duplicate of
// a previous error, don't send a beacon just for itself
return;
}
// errors outside of a load will be sent at the next interval
impl.sendIntervalId = setTimeout(function() {
impl.sendIntervalId = -1;
// change this to an 'error' beacon
BOOMR.addVar("http.initiator", "error");
// set it as an API beacon, which means it won't have any timing data
BOOMR.addVar("api", 1);
// add our errors to the beacon
impl.addErrorsToBeacon();
// send it!
BOOMR.sendBeacon();
}, impl.sendInterval);
}
},
/**
* Finds a duplicate BoomerangErrors in the specified array
*
* @param {Array[]} errors Array of BoomerangErrors
* @param {BoomerangError} err BoomerangError to check
*
* @returns {BoomerangError} BoomerangErrors that was duped against, if any
*/
findDuplicateError: function(errors, err) {
if (!Array.isArray(errors) || typeof err === "undefined") {
return undefined;
}
for (var i = 0; i < errors.length; i++) {
if (errors[i].equals(err)) {
return errors[i];
}
}
return undefined;
},
/**
* Merges duplicate BoomerangErrors
*
* @param {Array[]} errors Array of BoomerangErrors
* @param {BoomerangError} err BoomerangError to check
* @param {boolean} bumpCount Increment the count of any found duplicates
*
* @returns {BoomerangError} BoomerangErrors that was duped against, if any
*/
mergeDuplicateErrors: function(errors, err, bumpCount) {
if (!Array.isArray(errors) || typeof err === "undefined") {
return undefined;
}
var dup = impl.findDuplicateError(errors, err);
if (dup) {
if (bumpCount) {
dup.count += err.count;
}
return dup;
}
else {
errors.push(err);
return undefined;
}
},
/**
* Fired 'onbeacon'
*/
onBeacon: function() {
// remove our err vars
BOOMR.removeVar("err");
BOOMR.removeVar("api");
BOOMR.removeVar("http.initiator");
},
/**
* Fired on 'page_ready'
*/
pageReady: function() {
impl.isDuringLoad = false;
},
/**
* Retrieves the current errors
*
* @returns {BoomerangError[]}
*/
getErrors: function() {
if (impl.errors.length === 0) {
return false;
}
return impl.errors;
},
/**
* Gets errors suitable for transmission in a URL
*
* @param {BoomerangError[]} errors BoomerangErrors array
*
* @returns {string} String for URL
*/
getErrorsForUrl: function(errors) {
errors = impl.compressErrors(errors);
if (BOOMR.utils.Compression.jsUrl) {
return BOOMR.utils.Compression.jsUrl(errors);
}
else if (window.JSON) {
url += JSON.stringify(errors);
}
else {
// not supported
BOOMR.debug("JSON is not supported", "Errors");
return "";
}
},
/**
* Adds any queue'd errors to the beacon
*/
addErrorsToBeacon: function() {
if (impl.q.length) {
var err = this.getErrorsForUrl(impl.q);
if (err) {
BOOMR.addVar("err", err);
}
impl.q = [];
}
},
/**
* Fired 'before_beacon'
*/
beforeBeacon: function() {
impl.addErrorsToBeacon();
},
/**
* Wraps calls to functionName in an exception handler that will
* automatically report exceptions.
*
* @param {string} functionName Function name
* @param {object} that Target object
* @param {boolean} useCallingObject Whether or not to use the calling object for 'this'
* @param {number} callbackIndex Which argument is the callback
* @param {number} via Via
*/
wrapFn: function(functionName, that, useCallingObject, callbackIndex, via) {
var origFn = that[functionName];
if (typeof origFn !== "function") {
return;
}
that[functionName] = function() {
try {
var args = Array.prototype.slice.call(arguments);
var callbackFn = args[callbackIndex];
var targetObj = useCallingObject ? this : that;
var wrappedFn = impl.wrap(callbackFn, targetObj, via);
args[callbackIndex] = wrappedFn;
if (functionName === "addEventListener") {
// for removeEventListener we need to keep track of this
// unique tuple of target object, event name (arg0), original function
// and capture (arg2)
impl.trackFn(targetObj, args[0], callbackFn, args[2], wrappedFn);
}
return origFn.apply(targetObj, args);
}
catch (e) {
// error during original callback setup
impl.send(e, via);
}
};
},
/**
* Tracks the specified function for removeEventListener.
*
* @param {object} target Target element (window, element, etc)
* @param {string} type Event type (name)
* @param {function} listener Original listener
* @param {boolean} useCapture Use capture
* @param {function} wrapped Wrapped function
*/
trackFn: function(target, type, listener, useCapture, wrapped) {
if (!target) {
return;
}
if (impl.trackedFnIdx(target, type, listener, useCapture) !== -1) {
// already tracked
return;
}
if (!target._bmrEvents) {
target._bmrEvents = [];
}
target._bmrEvents.push([type, listener, !!useCapture, wrapped]);
},
/**
* Gets the index of the tracked function.
*
* @param {object} target Target element (window, element, etc)
* @param {string} type Event type (name)
* @param {function} listener Original listener
* @param {boolean} useCapture Use capture
*
* @returns {number} Index of already tracked function, or -1 if it doesn't exist
*/
trackedFnIdx: function(target, type, listener, useCapture) {
var i, f;
if (!target) {
return;
}
if (!target._bmrEvents) {
target._bmrEvents = [];
}
for (i = 0; i < target._bmrEvents.length; i++) {
f = target._bmrEvents[i];
if (f[0] === type &&
f[1] === listener &&
f[2] === !!useCapture) {
return i;
}
}
return -1;
},
/**
* Wraps removeEventListener to work with our wrapFn
*
* @param {object} that Target object
*/
wrapRemoveEventListener: function(that) {
var fn = "removeEventListener", origFn = that[fn], idx, wrappedFn;
if (typeof origFn !== "function") {
return;
}
that[fn] = function(type, listener, useCapture) {
idx = impl.trackedFnIdx(this, type, listener, useCapture);
if (idx !== -1) {
wrappedFn = this._bmrEvents[idx][3];
// remove our wrapped function instead
origFn.call(this, type, wrappedFn, useCapture);
// remove bookkeeping
this._bmrEvents.splice(idx, 1);
}
else {
// unknown, pass original args
origFn.call(this, type, listener, useCapture);
}
};
},
/**
* Wraps the function in an exception handler that will
* automatically report exceptions.
*
* @param {function} fn Function
* @param {object} that Target object
* @param {number} via Via (optional)
*
* @returns {function} Wrapped function
*/
wrap: function(fn, that, via) {
if (typeof fn !== "function") {
// Return the input argument as-is. This might happen if the argument
// to setTimeout/setInterval is a string, which is deprecated but supported
// by all browsers, however it isn't something we can wrap (we don't want to have
// eval statements in the code).
return fn;
}
via = via || BOOMR.plugins.Errors.VIA_APP;
return function BOOMR_plugins_errors_wrap() {
try {
return fn.apply(that, arguments);
}
catch (e) {
// error during callback
impl.send(e, via);
}
};
},
/**
* Runs the function, watching for exceptions
*
* @param {function} fn Function
* @param {object} that Target object
* @param {object[]} args Arguments
*/
test: function() {
var fn, that, args;
if (arguments.length === 0) {
return undefined;
}
// the function to run is the first argument
fn = arguments[0];
if (typeof fn !== "function") {
return undefined;
}
// the object is the second
that = arguments.length > 1 ? arguments[1] : BOOMR.window;