forked from bluesmoon/boomerang
/
errors.js
2381 lines (2101 loc) · 74.8 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
/**
* The `Errors` plugin automatically captures JavaScript and other errors from
* your web application.
*
* This plugin has a corresponding {@tutorial header-snippets} that helps capture errors prior to Boomerang loading.
*
* For information on how to include this plugin, see the {@tutorial building} tutorial.
*
* ## Sources of Errors
*
* When the `Errors` plugin is enabled, the following sources of errors are captured:
*
* * JavaScript runtime errors captured via the
* [`onerror`](https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onerror)
* global event handler
* * [``XMLHttpRequest``](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest)
* responses that were not successful. Note {@link BOOMR.plugins.AutoXHR} is required
* if using this.
* * Any calls to [``window.console.error``](https://developer.mozilla.org/en-US/docs/Web/API/Console/error)
* * JavaScript runtime errors that happen during a callback for
* [``addEventListener``](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener)
* _(disabled by default, enabled via {@link BOOMR.plugins.Errors.init `monitorEvents`})_
* * JavaScript runtime errors that happen during a callback for
* [``setTimeout``](https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout)
* and [``setInterval``](https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval)
* _(disabled by default, enabled via {@link BOOMR.plugins.Errors.init `monitorTimeout`})_
* * Manually sent errors via {@link BOOMR.plugins.Errors.send}
* * Functions that threw an exception that were wrapped via {@link BOOMR.plugins.Errors.wrap}
* * Functions that threw an exception that were run via {@link BOOMR.plugins.Errors.test}
* * JavaScript runtime errors captured via the
* [`unhandledrejection`](https://developer.mozilla.org/en-US/docs/Web/Events/unhandledrejection)
* global event handler _(disabled by default, enabled via {@link BOOMR.plugins.Errors.init `monitorRejections`})_
* * JavaScript runtime warnings captured via the
* [`Reporting API`](https://www.w3.org/TR/reporting/#reporting-observer)
* _(disabled by default, enabled via {@link BOOMR.plugins.Errors.init `monitorReporting`})_
*
* All of the options above can be
* {@link BOOMR.plugins.Errors.init manually turned off}.
*
* ## Supported Browsers
*
* The `Errors` plugin can be enabled for all browsers, though some older browsers
* may not be able to capture the full breadth of sources of errors. Due to the lack
* of error detail on some older browsers, some errors may be reported more than once.
*
* Notable browsers:
*
* * Internet Explorer <= 8: Does not support capturing `XMLHttpRequest` errors.
*
* ## Manually Sending Errors
*
* Besides automatically capturing errors from `onerror`, `XMLHttpRequest`,
* `console.error` or event handlers such as `setTimeout`, you can also manually
* send errors.
*
* There are three ways of doing this as follows:
*
* * {@link BOOMR.plugins.Errors.send}: Immediately sends an error.
* * {@link BOOMR.plugins.Errors.wrap}: Wraps a function with error tracking
* * {@link BOOMR.plugins.Errors.test}: Runs the function and captures any errors.
*
* ## Error callback
*
* You can specify an {@link BOOMR.plugins.Errors.init `onError`} function that
* the Errors plugin will call any time an error is captured on the page.
*
* If your `onError` function returns `true`, the error will be captured.
*
* If your `onError` function does not return `true`, the error will be ignored.
*
* Example:
*
* ```
* BOOMR.init({
* Errors: {
* onError: function(err) {
* if (err.message && err.message.indexOf("internally handled")) {
* return false;
* }
* return true;
* }
* }
* });
* ```
*
* ## When to Send Errors
*
* By default, errors captured during the page load will be sent along with the
* page load beacon.
*
* Errors that happen after the page load will not be captured or sent.
*
* To enable capturing of errors after page load, you need to set
* {@link BOOMR.plugins.Errors.init `sendAfterOnload`} to `true`. If set,
* errors that happen after the page load will be sent at most once every
* {@link BOOMR.plugins.Errors.init `sendInterval`} (which defaults to 1 second)
* on a new beacon.
*
* Example:
*
* ```
* BOOMR.init({
* Errors: {
* sendAfterOnload: true,
* sendInterval: 5000
* }
* });
* ```
*
* ## How Many Errors to Capture
*
* The `Errors` plugin will only capture up to
* {@link BOOMR.plugins.Errors.init `maxErrors`} (defaults to 10) distinct
* errors on the page.
*
* Please note that duplicate errors (those with the same function name, stack,
* and so on) are tracked as single distinct error, with a `count` of how many
* times it was seen.
*
* You can increase (or decrease) `maxErrors`. For example:
* ```
* BOOMR.init({
* Errors: {
* maxErrors: 20
* }
* });
* ```
*
* ## Dealing with Script Error
*
* When looking at JavaScript errors, you will likely come across the generic error
* message: `Script error.`
*
* `Script Error.` is the message that browsers send to the
* [`window.onerror`](https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onerror)
* global exception handler when the error was triggered by a script loaded from a different (cross)
* [origin](https://developer.mozilla.org/en-US/docs/Glossary/Origin). `window.onerror`
* is used by Boomerang so that it gets notified of all unhandled exceptions.
*
* The `Script Error.` string is given _instead_ of the real error message
* and does not contain any useful information about what caused the error. In addition,
* there is no stack associated with the message, so it's impossible to know where
* or why the error occurred.
*
* Browsers mask the real error message for cross-origin scripts due to security and
* privacy concerns - they don't want to leak sensitive information in the message
* or stack. The only thing that `window.onerror` knows for cross-origin scripts
* is that an error occurred, not where or why.
*
* ### Example
*
* For an example of where you'd see `Script Error.`, consider the following code
* that lives on `website.com`:
*
* ```html
* <html>
* <head>
* <title>website.com</title>
* </head>
* <body>
* <script>
* window.onerror = function(message, url, line, column, error) {
* console.log("window.onerror: " + message);
* console.log((error && error.stack) ? error.stack : "(no stack)");
* };
* </script>
* <script src="my-script.js"></script>
* <script src="https://anothersite.com/my-script.js"></script>
* </body>
* </html>
* ```
*
* Assume `my-script.js` is the same file being served from both `website.com` and
* `anothersite.com`:
*
* ```javascript
* function runCode() {
* a = b + 1;
* }
*
* runCode();
* ```
*
* When `my-script.js` is loaded from `website.com`, it will be executed twice:
*
* 1. First on the same-origin, where we'll see the full error message followed by
* the stack:
*
* ```
* window.onerror: Uncaught ReferenceError: b is not defined
*
* ReferenceError: b is not defined
* at runCode (my-script.js:2)
* at my-script.js:5
* ```
*
* 2. Then, it will be loaded from `https://anothersite.com/my-script.js`, which
* will be considered cross-origin and only `Script Error.` will be logged:
*
* ```
* window.onerror: Script error.
*
* (no stack)
* ```
*
* As you can see, browser shares the full details of the exception when it's served
* from the same origin as the website, but if it's served from any other origin,
* it will be considered cross-origin and no details will be shared.
*
* Note that while the browser only shares `Script Error.` to `window.onerror`
* for cross-origin scripts, if _you_ have browser developer tools open,
* the browser will show _you_ the full error message in the Console. This is
* because there aren't any security or privacy concerns for a developer looking at
* their own machine's information.
*
* ### When You'll See Script Error
*
* Unfortunately `Script Error.` will be shown in many legitimate use-cases,
* such as:
*
* 1. When serving your website's JavaScript from a CDN (since it will be coming
* from a different origin)
*
* 2. When loading a library such as jQuery or Angular from their CDN, i.e.
* [Google's Hosted Libraries](https://developers.google.com/speed/libraries/)
* or [cdnjs](https://cdnjs.com/)
*
* 3. When a third-party script loads from another domain
*
* The good news is that in many of these cases, there are changes you can make to
* ensure the full error message and stack are shared with `window.onerror`.
*
* ### Fixing Script Error
*
* To ensure a cross-origin script shares full error details with `window.onerror`,
* you'll need to do **two** things:
*
* 1. Add `crossorigin="anonymous"` to the `<script>` tag
*
* The [`crossorigin="anonymous"` attrib](https://www.w3.org/TR/html5/infrastructure.html#cors-settings-attribute)
* tells the browser that the script should be fetched without sending
* any cookies or HTTP authentication
*
* 2. Add the `Access-Control-Allow-Origin` (ACAO) header to the JavaScript file's response.
*
* The `Access-Control-Allow-Origin` header is part of the
* [Cross Origin Resource Sharing](https://www.w3.org/TR/cors/) (CORS) standard.
*
* The ACAO header **must** be set in the JavaScript's HTTP response headers.
*
* An example header that sets ACAO for all calling origins would be:
*
* `Access-Control-Allow-Origin: *`
*
* If both conditions are true, cross-origin JavaScript files will report errors
* to `window.onerror` with the correct error message and full stack.
*
* The biggest challenge to getting this working is that (1) is within the _site's_
* control while (2) can only be configured by the _owner_ of the JavaScript. If you're
* loading JavaScript from a third-party, you will need to encourage them to add the
* ACAO header if it's not already set. The good news is that many CDNs and
* third-parties set the ACAO header already.
*
* ### Workarounds for Third Parties that aren't sending ACAO
*
* One way to help monitor for errors coming from third-party scripts that aren't
* setting ACAO (and aren't within your control) is by manually wrapping calls
* to any of the third-party script's functions in a `try {} catch {}`.
*
* ```javascript
* try {
* // calls a cross-origin script that doesn't have ACAO
* runThirdPartyCode();
* } catch (e) {
* // report on error with e.message and e.stack
* }
* ```
*
* If `runThirdPartyCode()` causes any errors, the `catch {}` handler will get the full
* details of the exception.
*
* Unfortunately this won't work for functions that are executed in the third-party
* script as a result of browser events or callbacks (since you're not wrapping them).
*
* When using Boomerang to monitor JavaScript errors, Boomerang automatically wraps some
* of the built-in browser APIs such as `setTimeout`, `setInterval`
* (via the {@link BOOMR.plugins.Errors.init `monitorTimeout`} option)
* and `addEventListener` (via the {@link BOOMR.plugins.Errors.init `monitorEvents`} option)
* with a minimal-overhead wrapper. It does this to help ensure as many cross-origin
* exceptions as possible have full stack details. You may also do this manually via
* [`` BOOMR.plugin.Errors.wrap(function)``](#BOOMR_plugin_Errors_wrap).
*
* Note that enabling {@link BOOMR.plugins.Errors.init `monitorTimeout`} or
* {@link BOOMR.plugins.Errors.init `monitorEvents`} can have side-effects and has caused
* compatibility issues with JavaScript code on some sites. Enabling those options is only
* recommended after verifying there are no problems.
*
* ## Why is Boomerang in my Error Stack?
*
* When looking at error reports, you may find errors that have a function in
* `boomerang.js` (or `/boomerang/`) on the stack. Why is that? Is Boomerang
* causing errors on your site?
*
* One of the ways that Boomerang is able to monitor and measure your site's performance
* is by _wrapping_ itself around some of the core browser APIs. Boomerang only does
* this in a few places, if absolutely necessary -- namely, when the browser doesn't
* provide a native "monitoring" interface for something that needs to be tracked.
*
* One example is for `XMLHttpRequests`, as there are no browser APIs to monitor when
* XHRs load. To monitor XHRs, Boomerang swaps in its own `window.XMLHttpRequest`
* object, wrapping around the native methods. When an XHR is created (via `.open()`),
* the lightweight Boomerang wrapper is executed first so it can log a start timestamp.
* When the XHR finishes (via a `readyState` change), Boomerang can log the end
* timestamp and report on the XHR's performance.
*
* Examples of Boomerang wrapping native methods include:
*
* * `XMLHttpRequest` if the XHR instrumentation is turned on
* * `console.error` if error tracking is turned on
* * `setTimeout` and `setInterval`(if error tracking is turned on
* (with {@link BOOMR.plugins.Errors.init `monitorTimeout`})
* * `addEventListener` and `removeEventListener` (if error tracking is turned on
* (with {@link BOOMR.plugins.Errors.init `monitorEvents`})
*
* All of these wrapped functions come into play when you see an error stack with
* a `boomerang.js` function in it.
*
* Often, the `boomerang.js` function will be at the _bottom_ of the stack (the first
* function called). This does not mean Boomerang caused the error, merely that
* the monitoring code was running before the error occurred. The actual
* error happens towards the _top_ of the stack -- the function that ran and threw
* the exception.
*
* Let's look at some examples:
*
* ```
* Cannot read property 'foo' of undefined at thirdPartyTwo (https://thirdparty.com/core.js:1:100)
* at thirdPartyOne (https://thirdparty.com/core.js:1:101)
* at runThirdParty (https://thirdparty.com/core.js:1:102)
* at xhrCallback (http://website.com/site.js:2:200)
* at XMLHttpRequest.send (https://mysite.com/boomerang.js:3:300)
* ```
*
* In the above example, Boomerang is monitoring `XMLHttpRequests`. An XHR was
* loaded on the site, and during the XHR callback, an exception was thrown. Even
* though `/boomerang/` is listed here, the error was caused by code in the XHR
* callback (`xhrCallback` eventually calling `thirdPartyTwo`).
*
* Here's a second example:
*
* ```
* Reference error: a is not defined at setTimeout (http://website.com/site.js:1:200)
* at BOOMR_plugins_errors_wrap (http://mysite.com/boomerang.js:3:300)
* at onclick (http://website.com/site.js:1:100)
* ```
*
* In the above example, JavaScript Error Reporting is enabled and an exception was
* thrown in a `setTimeout()` on the website. You can see the `BOOMR_plugins_errors_wrap`
* function is near the top of the stack, but this is merely the error tracking code.
* All it did was wrap `setTimeout` to help ensure that cross-origin exceptions are
* caught. It was not the actual cause of the site's error.
*
* Here's a third example:
*
* ```
* Error: missing argument 1 at BOOMR.window.console.error (https://mysite.com/boomerang.js:3:300)
* at u/< (https://website.com/site.js:1:100)
* at tp/this.$get</< (https://website.com/site.js:1:200)
* at $digest (https://website.com/site.js:1:300)
* at $apply (https://website.com/site.js:1:400)
* at ut (https://website.com/site.js:1:500)
* at it (https://website.com/site.js:1:600)
* at vp/</k.onload (https://website.com/site.js:1:700)
* ```
*
* In the above example, JavaScript Error Reporting is enabled and has wrapped
* `console.error`. The minified function `u/<` must be logging a `console.error`,
* which executes the Boomerang wrapper code, reporting the error.
*
* In summary, if you see Boomerang functions in error stacks similar to any of the
* ones listed below, it's probable that you're just seeing a side-effect of the
* monitoring code:
*
* * `BOOMR_addError`
* * `BOOMR_plugins_errors_onerror`
* * `BOOMR_plugins_errors_onxhrerror`
* * `BOOMR_plugins_errors_console_error`
* * `BOOMR_plugins_errors_wrap`
* * `BOOMR.window.console.error`
* * `BOOMR_plugins_errors_onrejection`
*
* ## Side Effects
*
* Enabling wrapping through {@link BOOMR.plugins.Errors.init `monitorEvents`} and
* {@link BOOMR.plugins.Errors.init `monitorTimeout`} may trigger some side effects:
*
* * Boomerang's monitoring code will be run first for every callback, which will add minimal (though non-zero)
* overhead.
* * In browser console logs, errors that are triggered by other libraries that have been wrapped
* will now look like they come from Boomerang instead, as Boomerang is now on the bottom of the call stack.
* * Browser developer tools such as Chrome's Performance and Profiler tabs may be confused about
* JavaScript CPU attribution. In other words, they may think Boomerang is the cause of more work than it is.
* * Chrome Lighthouse may be confused about JavaScript CPU attribution, due to the same reasons as above.
* * WebPagetest may be confused about JavaScript CPU attribution, due to the same reasons as above.
* * There are some cases where JavaScript applications may have compatibility issues with the wrapping. Some
* notable cases include:
* * Use of the global `window.event` object, [see issue](https://github.com/whatwg/dom/issues/735).
* * Other libraries that wrap `setTimeout`, `addEventListener`, etc such as `history.js`.
* * Pages that use the `<base href="...">` tag.
*
* For more details, you can read this
* [article](https://nicj.net/side-effects-of-boomerangs-javascript-error-tracking/).
*
* ## Beacon Parameters
*
* * `err`: The compressed error data structure
* * `http.initiator = error` (if not part of a Page Load beacon)
*
* The compressed error data structure is a [JSURL](https://github.com/Sage/jsurl)
* encoded JSON object.
*
* Each element in the array is a compressed representation of a JavaScript error:
*
* * `n`: Count (if the error was seen more than once)
* * `f[]`: An array of frames
* * `f[].l`: Line number
* * `f[].c`: Colum number
* * `f[].f`: Function name
* * `f[].w`: File name (if origin differs from root page)
* * `f[].wo`: File name without origin (if same as root page)
* * `s`: Source:
* * `1`: Error was triggered by the application
* * `2`: Error was triggered by Boomerang
* * `v`: Via
* * `1`: Application ({@link BOOMR.plugins.Errors.send})
* * `2`: Global exception handler (`window.onerror`)
* * `3`: Network (XHR) error
* * `4`: Console (`console.error`)
* * `5`: Event handler (`addEventListener`)
* * `6`: `setTimeout` or `setInterval`
* * `t`: Type (e.g. `SyntaxError` or `ReferenceError`)
* * `c`: Code (for network errors)
* * `m`: Error messag
* * `x`: Extra data
* * `d`: Timestamp (base 36)
*
* @class BOOMR.plugins.Errors
*/
/*eslint-disable*/
//
// 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[]
* @ignore
*/
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]
* @ignore
*/
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 = window.BOOMR || {};
BOOMR.plugins = BOOMR.plugins || {};
if (BOOMR.plugins.Errors) {
return;
}
//
// Constants
//
/**
* Functions to strip from any stack (internal functions)
*/
var STACK_FUNCTIONS_REMOVE = [
"BOOMR_addError",
"createStackForSend",
"BOOMR.window.console.error",
"BOOMR.plugins.Errors.init",
"BOOMR.window.onerror",
// below matches multiple functions:
"BOOMR_plugins_errors_"
];
// functions to strip if they match a STACK_FILENAME_MATCH
var STACK_FUNCTIONS_REMOVE_IF_FILENAME_MATCH = [
"Object.send",
"b.send",
"wrap",
"Anonymous function"
];
// files that will match for STACK_FUNCTIONS_REMOVE_IF_FILENAME_MATCH
var STACK_FILENAME_MATCH = [
"/boomerang"
];
/**
* 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 (BOOMR.utils.isArray(config.frames)) {
this.frames = config.frames;
}
else {
this.frames = [];
}
if (BOOMR.utils.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, k,
now = BOOMR.now(),
skipThis, thisFrame, thisFn;
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) {
// check to see if the filename of frames two and 3 are the same (boomerang),
// if so, remove both
if (frames[1].fileName === frames[2].fileName) {
// remove the top 3 frames
frames = frames.slice(3);
}
else {
// 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++) {
thisFrame = frames[i];
thisFn = thisFrame.functionName;
skipThis = false;
// strip boomerang function names
if (thisFn) {
for (j = 0; j < STACK_FUNCTIONS_REMOVE.length; j++) {
if (thisFn.indexOf(STACK_FUNCTIONS_REMOVE[j]) !== -1) {
frames.splice(i, 1);
forceUpdate = true;
// outloop continues with the next element
i--;
skipThis = true;
break;
}
}
// strip additional functions if they also match a file
if (!skipThis && thisFrame.fileName) {
for (j = 0; j < STACK_FILENAME_MATCH.length; j++) {
if (thisFrame.fileName.indexOf(STACK_FILENAME_MATCH[j]) !== -1) {
// this file name matches, see if any of the matching functions also do
for (k = 0; k < STACK_FUNCTIONS_REMOVE_IF_FILENAME_MATCH.length; k++) {
if (thisFn.indexOf(STACK_FUNCTIONS_REMOVE_IF_FILENAME_MATCH[k]) !== -1) {
frames.splice(i, 1);
forceUpdate = true;
// outloop continues with the next element
i--;
skipThis = true;
break;
}
}
}
}
}
}
}
if (frames.length) {
// 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