/
inject.js
4272 lines (3786 loc) · 134 KB
/
inject.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
/*
Inject
Copyright 2013 LinkedIn
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an "AS
IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
express or implied. See the License for the specific language
governing permissions and limitations under the License.
*/
(function(context, undefined) {
// --------------------------------------------------
// ENVIRONMENT
// --------------------------------------------------
var InjectContext;
function init(version) {
var ic = InjectContext.createContext();
context.require = ic.require;
context.define = ic.define;
context.Inject = ic.Inject;
context.Inject.version = version;
}
// --------------------------------------------------
// INCLUDES/
// --------------------------------------------------
/*jshint unused:false */
/*
Inject
Copyright 2011 LinkedIn
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an "AS
IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
express or implied. See the License for the specific language
governing permissions and limitations under the License.
*/
/**
* Below are the "sandboxing" wrappers for our commonJS implementation
* we reach in to the inject namespace (default "Inject"), into the
* _ object, which contains methods reachable during the eval.
* Markers in the file for dynamic content are identified with
* __DOUBLE_UNDERSCORES__
* @file This file contains the commonJS header and footers
**/
/**
CommonJS header with placeholders for Inject namespace, module ID,
module URI, function ID and pointcut before advice.
@type {string}
@global
*/
var commonJSHeader = (['',
'__REACHABLE_PATH__.fn = function() {',
' with (window) {',
' __REACHABLE_PATH__.innerFn = function() {',
' // id: __MODULE_ID__ uri: __MODULE_URI__',
' var module = __REACHABLE_PATH__.module,',
' require = __REACHABLE_PATH__.require,',
' define = __REACHABLE_PATH__.define,',
' exports = module.exports;',
' try{module.undefined_function();}catch(e){module.__error_line = e;}' // NOTE: Must be on one line for clean error reporting
]).join('\n');
/**
CommonJS footer with placeholders for Inject namespace, exception, and
pointcut after advice.
@type {string}
@global
*/
var commonJSFooter = (['',
' __REACHABLE_PATH__.module = module;',
' };',
' __REACHABLE_PATH__.defineExecutingModuleAs("__MODULE_ID__", "__MODULE_URI__");',
' try {',
' __REACHABLE_PATH__.innerFn.call(__REACHABLE_PATH__.module);',
' }',
' catch (__EXCEPTION__) {',
' __REACHABLE_PATH__.module.__error = __EXCEPTION__;',
' }',
' __REACHABLE_PATH__.undefineExecutingModule();',
' }',
'};',
'']).join('\n');
/*jshint unused:false, evil:true */
/*global navigator:true, Object:true, localStorage:true */
/*
Inject
Copyright 2011 LinkedIn
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an "AS
IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
express or implied. See the License for the specific language
governing permissions and limitations under the License.
*/
// sniffs and assigns UA tests
var IS_IE = eval('/*@cc_on!@*/false');
var IS_GK = false;
(function () {
var ua = navigator.userAgent.toLowerCase();
if (ua.indexOf('gecko') !== -1) {
IS_GK = true;
}
})();
/**
* a storagetoken identifier we use for the bucket (lscache)
* @constant
*/
var FILE_STORAGE_TOKEN = 'INJECT';
/**
* the version of data storage schema for lscache
* @constant
*/
var LSCACHE_SCHEMA_VERSION = 1;
/**
* the schema version string for validation of lscache schema
* @constant
*/
var LSCACHE_SCHEMA_VERSION_STRING = '!version';
/**
* the cache version string for validation of developer lscache code
* @constant
*/
var LSCACHE_APP_KEY_STRING = '!appCacheKey';
/**
* Regex for identifying things that end in *.js or *.txt
* @constant
*/
var FILE_SUFFIX_REGEX = /.*?\.(js|txt)(\?.*)?$/;
/**
* This is the basic suffix for JS files. When there is no
* extension, we add this if enabled
* @constant
*/
var BASIC_FILE_SUFFIX = '.js';
/** prefixes for URLs that begin with http/https
* @constant
*/
var HOST_PREFIX_REGEX = /^https?:\/\//;
/**
* suffix for URLs used to capture everything up to / or the
* end of the string
* @constant
*/
var HOST_SUFFIX_REGEX = /^(.*?)(\/.*|$)/;
/**
* a regular expression for slicing a response from iframe communication into its parts
* (1) Anything up to a space (status code)
* (2) Anything up to a space (moduleid)
* (3) Any text up until the end of the string (file)
* @constant
**/
var RESPONSE_SLICER_REGEX = /^(.+?)[\s]+([\w\W]+?)[\s]+([\w\W]+)$/m;
/**
* a regex to locate the function () opener
* @constant
*/
var FUNCTION_REGEX = /^[\s\(]*function[^\(]*\(([^)]*)\)/;
/**
* a regex to locate newlines within a function body
* @constant
*/
var FUNCTION_NEWLINES_REGEX = /\/\/.*?[\r\n]|\/\*(?:.|[\r\n])*?\*\//g;
/**
* captures the body of a JS function
* @constant
*/
var FUNCTION_BODY_REGEX = /[\w\W]*?\{([\w\W]*)\}/m;
/**
* locate whitespace within a function body
* @constant
*/
var WHITESPACE_REGEX = /\s+/g;
/**
* Extract require() statements from within a larger string.
* Used by analyzer to parse files.
* @constant
*/
var REQUIRE_REGEX = new RegExp(
'(?:^|[\\s;,=\\?:\\}\\)\\(])' + // begins with start of string, and any symbol a function call() can follow
'require[\\s]*\\('+ // the keyword "require", whitespace, and then an opening paren
'[\'"]'+ // a quoted stirng (require takes a single or double quoted string)
'([^\'"]+?)'+ // the valid characters for a "module identifier"... includes AMD characters. You cannot match a quote
'[\'"]' + // the closing quote character
'\\)', // end of paren for "require"
'gim' // flags: global, case-insensitive, multiline
);
/**
* Extract define() statements from within a larger string.
* Used by analyzer to parse files.
* @constant
*/
var DEFINE_REGEX = new RegExp(
'(?:^|[\\s;,\\?\\}\\)\\(])' + // begins with start of string, and any symbol a function call() can follow
'define[\\s]*\\(' + // the "define" keyword, followed by optional whitespace and its opening paren
'[\\w\\W]*?\\[' + // anything (don't care) until we hit the first [
'([\\w\\W]*?)' + // our match (contents of the array)
'\\]', // the closing bracket
'gim' // flags: global, case-insensitive, multiline
);
/**
* Extract terms from define statements.
* Used by analyzer to parse files in conjunction with DEFINE_REGEX.
* @constant
*/
var DEFINE_TERM_REGEX = new RegExp(
'[\'"]' + // a quote
'([\\w\\W]*?)' + // the term inside of quotes
'[\'"]', // the closing quotes
'gim' // flags: global, case-insensitive, multiline
);
/**
* extract define() statements from within a larger string
* note: this was changed to resolve #177, we used the
* don't-be-greedy modifiers on the \S and \w\W sections
* @constant
*/
var IS_AMD_REGEX = /(?:^|[\s]+)define[\s]*\(/g;
/**
* index of all commonJS builtins in a function arg collection
* @constant
*/
var BUILTINS = {require: true, exports: true, module: true};
/**
* a regex for replacing builtins and quotes
* @constant
*/
var BUILTINS_REPLACE_REGEX = /[\s]|"|'|(require)|(exports)|(module)/g;
/**
* capture anything that involves require*, aggressive to cut
* down the number of lines we analyze
* @constant
*/
var GREEDY_REQUIRE_REXEX = /require.*/;
/**
* match comments in our file (so we can strip during a static analysis)
* @constant
*/
var JS_COMMENTS_REGEX = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg;
/**
* identifies a path as relative
* @constant
*/
var RELATIVE_PATH_REGEX = /^(\.{1,2}\/).+/;
/**
* identifies a path as absolute fully-qualified URL
* @constant
*/
var ABSOLUTE_PATH_REGEX = /^([A-Za-z]+:)?\/\//;
/**
* The :// part of the protocol (to remove when splitting on / for URLs)
* @constant
*/
var PROTOCOL_REGEX = /:\/\//;
/**
* A string equivalent of the protocol regex
* @constant
*/
var PROTOCOL_STRING = '://';
/**
* A replacement for :// that doesn't contain slashes
* @constant
*/
var PROTOCOL_EXPANDED_REGEX = /__INJECT_PROTOCOL_COLON_SLASH_SLASH__/;
/**
* A string version of the expanded protocol regex
* @constant
*/
var PROTOCOL_EXPANDED_STRING = '__INJECT_PROTOCOL_COLON_SLASH_SLASH__';
/**
* the default hasOwnProperty method
*/
var HAS_OWN_PROPERTY = Object.prototype.hasOwnProperty;
/**
* run a test to determine if localstorage is available
* @constant
*/
var HAS_LOCAL_STORAGE = (function () {
try {
localStorage.setItem('injectLStest', 'ok');
localStorage.removeItem('injectLStest');
return true;
}
catch (err) {
return false;
}
})();
/**
* this regex is used to strip leading slashes
* @constant
*/
var LEADING_SLASHES_REGEX = /^\/+/g;
/*jshint unused:false */
/*global window:true, XMLHttpRequest:true, ActiveXObject:true, console:true */
/*
Inject
Copyright 2011 LinkedIn
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an "AS
IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
express or implied. See the License for the specific language
governing permissions and limitations under the License.
*/
/**
User configuration options
@property {string} moduleRoot Base path for all module includes
@see InjectCore.setModuleRoot
@property {number} fileExpires Time (in seconds) for how long to preserve
items in cache @see InjectCore.setExpires
@property {boolean} useSuffix Specify true to append file suffix when
resolving an identifier to a URL. @see RulesEngine.resolveFile
@property {object} xd Contains properties related to cross-domain requests
@property {string|null} xd.relayFile URL to easyXDM provider document
@property {object} debug
@property {boolean} debug.sourceMap Specify true to enable source
mapping @see Executor
@property {boolean} debug.logging Specify true to enable logging
@see debugLog
@type {object}
@global
*/
var userConfig = {
moduleRoot: null,
fileExpires: 0,
useSuffix: true,
xd: {
relayFile: null
},
debug: {
sourceMap: false,
logging: false
}
};
/**
The local scope
@global
*/
var context = this;
/**
Mappings for module => handling defined by the user.
@global
*/
var userModules = {};
/**
Returns whether or not 'property' exists in 'object' as a Function
or Object.
@param {object} object The object to inspect.
@param {*} property The property to assert exists in 'object'
@return {Boolean} true if 'property' exists in 'object', and false
otherwise.
@function
@global
*/
var isHostMethod = function (object, property) {
// Return if typeof is 'function', 'object' or 'unknown' (can occur for IE)
// See http://stackoverflow.com/questions/10982739/typeof-returning-unknown-in-ie
var t = typeof object[property];
return t === 'function' || (!!(t === 'object' && object[property])) || t === 'unknown';
};
/**
Calls the specified function in the specified scope.
@param {Function} fn The function to call.
@param {object} scope The scope to execute the function in.
@return {*} The result of calling fn.
@function
@global
*/
function proxy(fn, scope) {
if (!scope) {
throw new Error('proxying requires a scope');
}
if (!fn) {
throw new Error('proxying requires a function');
}
return function () {
return fn.apply(scope, arguments);
};
}
/**
Apples fn to each item in given collection.
@param {*[]} collection An array of arbitrary elements.
@param {Function} fn A function that takes one argument.
Each element from 'collection' will be passed to 'fn'.
@function
@global
*/
function each(collection, fn) {
for (var i = 0, len = collection.length; i < len; i++) {
fn(collection[i]);
}
}
function guid() {
return ('INJECT_xxxxxxxx_xxxx_4xxx_yxxx_xxxxxxxxxxxx').replace(/[xy]/g, function(c) {
var r = Math.random() * 16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
}
/**
Function for logging debug output.
@type {Function}
@global
*/
var debugLog = function () {};
// TODO: more robust logging solution
(function () {
var logs = [];
var canLog = (typeof(console) !== 'undefined' && console.log && typeof(console.log) === 'function');
var doLog = function (origin, message) {
if (userConfig.debug && userConfig.debug.logging) {
console.log('## ' + origin + ' ##' + '\n' + message);
}
};
if (canLog) {
debugLog = doLog;
}
})();
var normalizeStack;
(function() {
var type = null;
normalizeStack = function(stack) {
if (!type) {
type = stacknorm.mode(stack);
}
return stacknorm[type](stack);
};
// stack normalizer from https://github.com/eriwen/javascript-stacktrace/blob/master/stacktrace.js
var stacknorm = {
/**
* Mode could differ for different exception, e.g.
* exceptions in Chrome may or may not have arguments or stack.
*
* @return {String} mode of operation for the exception
*/
mode: function(e) {
if (e['arguments'] && e.stack) {
return 'chrome';
} else if (e.stack && e.sourceURL) {
return 'safari';
} else if (e.stack && e.number) {
return 'ie';
} else if (e.stack && e.fileName) {
return 'firefox';
} else if (e.message && e['opera#sourceloc']) {
// e.message.indexOf("Backtrace:") > -1 -> opera9
// 'opera#sourceloc' in e -> opera9, opera10a
// !e.stacktrace -> opera9
if (!e.stacktrace) {
return 'opera9'; // use e.message
}
if (e.message.indexOf('\n') > -1 && e.message.split('\n').length > e.stacktrace.split('\n').length) {
// e.message may have more stack entries than e.stacktrace
return 'opera9'; // use e.message
}
return 'opera10a'; // use e.stacktrace
} else if (e.message && e.stack && e.stacktrace) {
// e.stacktrace && e.stack -> opera10b
if (e.stacktrace.indexOf("called from line") < 0) {
return 'opera10b'; // use e.stacktrace, format differs from 'opera10a'
}
// e.stacktrace && e.stack -> opera11
return 'opera11'; // use e.stacktrace, format differs from 'opera10a', 'opera10b'
} else if (e.stack && !e.fileName) {
// phantomJS looks like chrome, but only returns line numbers
// We can look for [\d]+:[\d]+)?\n|$
// Chrome 27 does not have e.arguments as earlier versions,
// but still does not have e.fileName as Firefox
var hasColumns = /:[\d]+:[\d]+\)?(\n|$)/;
return (hasColumns.test(e.stack)) ? 'chrome' : 'phantom';
}
return 'other';
},
/**
* Given an Error object, return a formatted Array based on Chrome's stack string.
*
* @param e - Error object to inspect
* @return Array<String> of function calls, files and line numbers
*/
chrome: function(e) {
return (e.stack + '\n')
.replace(/^\s+(at eval )?at\s+/gm, '') // remove 'at' and indentation
.replace(/^([^\(]+?)([\n$])/gm, '{anonymous}() ($1)$2')
.replace(/^Object.<anonymous>\s*\(([^\)]+)\)/gm, '{anonymous}() ($1)')
.replace(/^(.+) \((.+)\)$/gm, '$1@$2')
.split('\n')
.slice(1, -1);
},
/**
* Given an Error object, return a formatted Array based on PhantomJS's stack string.
*
* @param e - Error object to inspect
* @return Array<String> of function calls, files and line numbers
*/
phantom: function(e) {
return (e.stack + '\n')
.replace(/^\s+(at eval )?at\s+/gm, '') // remove 'at' and indentation
.replace(/^([^\(]+?)([\n$])/gm, '{anonymous}() ($1)$2')
.replace(/^Object.<anonymous>\s*\(([^\)]+)\)/gm, '{anonymous}() ($1)')
.replace(/^(.+) \((.+)\)$/gm, '$1@$2')
.replace(/(.+):([0-9]+)(\)?)/g, '$1:$2:0$3')
.split('\n')
.slice(1, -1);
},
/**
* Given an Error object, return a formatted Array based on Safari's stack string.
*
* @param e - Error object to inspect
* @return Array<String> of function calls, files and line numbers
*/
safari: function(e) {
return e.stack.replace(/\[native code\]\n/m, '')
.replace(/^(?=\w+Error\:).*$\n/m, '')
.replace(/^@/gm, '{anonymous}()@')
.split('\n');
},
/**
* Given an Error object, return a formatted Array based on IE's stack string.
*
* @param e - Error object to inspect
* @return Array<String> of function calls, files and line numbers
*/
ie: function(e) {
return e.stack
.replace(/^\s*at\s+(.*)$/gm, '$1')
.replace(/^Anonymous function\s+/gm, '{anonymous}() ')
.replace(/^(.+)\s+\((.+)\)$/gm, '$1@$2')
.split('\n')
.slice(1);
},
/**
* Given an Error object, return a formatted Array based on Firefox's stack string.
*
* @param e - Error object to inspect
* @return Array<String> of function calls, files and line numbers
*/
firefox: function(e) {
return e.stack.replace(/(?:\n@:0)?\s+$/m, '')
.replace(/^(?:\((\S*)\))?@/gm, '{anonymous}($1)@')
.split('\n');
},
opera11: function(e) {
var ANON = '{anonymous}', lineRE = /^.*line (\d+), column (\d+)(?: in (.+))? in (\S+):$/;
var lines = e.stacktrace.split('\n'), result = [];
for (var i = 0, len = lines.length; i < len; i += 2) {
var match = lineRE.exec(lines[i]);
if (match) {
var location = match[4] + ':' + match[1] + ':' + match[2];
var fnName = match[3] || "global code";
fnName = fnName.replace(/<anonymous function: (\S+)>/, "$1").replace(/<anonymous function>/, ANON);
result.push(fnName + '@' + location + ' -- ' + lines[i + 1].replace(/^\s+/, ''));
}
}
return result;
},
opera10b: function(e) {
// "<anonymous function: run>([arguments not available])@file://localhost/G:/js/stacktrace.js:27\n" +
// "printStackTrace([arguments not available])@file://localhost/G:/js/stacktrace.js:18\n" +
// "@file://localhost/G:/js/test/functional/testcase1.html:15"
var lineRE = /^(.*)@(.+):(\d+)$/;
var lines = e.stacktrace.split('\n'), result = [];
for (var i = 0, len = lines.length; i < len; i++) {
var match = lineRE.exec(lines[i]);
if (match) {
var fnName = match[1] ? (match[1] + '()') : "global code";
result.push(fnName + '@' + match[2] + ':' + match[3]);
}
}
return result;
},
/**
* Given an Error object, return a formatted Array based on Opera 10's stacktrace string.
*
* @param e - Error object to inspect
* @return Array<String> of function calls, files and line numbers
*/
opera10a: function(e) {
// " Line 27 of linked script file://localhost/G:/js/stacktrace.js\n"
// " Line 11 of inline#1 script in file://localhost/G:/js/test/functional/testcase1.html: In function foo\n"
var ANON = '{anonymous}', lineRE = /Line (\d+).*script (?:in )?(\S+)(?:: In function (\S+))?$/i;
var lines = e.stacktrace.split('\n'), result = [];
for (var i = 0, len = lines.length; i < len; i += 2) {
var match = lineRE.exec(lines[i]);
if (match) {
var fnName = match[3] || ANON;
result.push(fnName + '()@' + match[2] + ':' + match[1] + ' -- ' + lines[i + 1].replace(/^\s+/, ''));
}
}
return result;
},
// Opera 7.x-9.2x only!
opera9: function(e) {
// " Line 43 of linked script file://localhost/G:/js/stacktrace.js\n"
// " Line 7 of inline#1 script in file://localhost/G:/js/test/functional/testcase1.html\n"
var ANON = '{anonymous}', lineRE = /Line (\d+).*script (?:in )?(\S+)/i;
var lines = e.message.split('\n'), result = [];
for (var i = 2, len = lines.length; i < len; i += 2) {
var match = lineRE.exec(lines[i]);
if (match) {
result.push(ANON + '()@' + match[2] + ':' + match[1] + ' -- ' + lines[i + 1].replace(/^\s+/, ''));
}
}
return result;
},
// Safari 5-, IE 9-, and others
other: function(curr) {
var ANON = '{anonymous}', fnRE = /function\s*([\w\-$]+)?\s*\(/i, stack = [], fn, args, maxStackSize = 10;
while (curr && curr['arguments'] && stack.length < maxStackSize) {
fn = fnRE.test(curr.toString()) ? RegExp.$1 || ANON : ANON;
args = Array.prototype.slice.call(curr['arguments'] || []);
stack[stack.length] = fn + '(' + this.stringifyArguments(args) + ')';
curr = curr.caller;
}
return stack;
}
};
}());
/**
Methods to add and remove events based on browser capabilities.
@param {Object} obj A target object to add or remove a listener.
@param {String} evt The event type.
@param {Function} fn The target function to add or remove.
@param {Boolean} capture Use capturing if supported.
@function
@global
*/
var addListener, removeListener;
(function(win) {
if (win.addEventListener) {
addListener = function(el, evt, fn, capture) {
el.addEventListener(evt, fn, capture || false);
};
removeListener = function(el, evt, fn, capture) {
el.removeEventListener(evt, fn, capture || false);
};
}
else {
addListener = function(el, evt, fn) {
el.attachEvent('on' + evt, fn);
};
removeListener = function(el, evt, fn) {
el.detachEvent('on' + evt, fn);
};
}
}(window));
// --------------------------------------------------
// XD COLLECTION
// --------------------------------------------------
/*
Inject
Copyright 2011 LinkedIn
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an "AS
IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
express or implied. See the License for the specific language
governing permissions and limitations under the License.
*/
var reURI = /^((http.?:)\/\/([^:\/\s]+)(:\d+)*)/; // returns groups for protocol (2), domain (3) and port (4)
function addListener(el, evt, fn) {
if (window.addEventListener) {
el.addEventListener(evt, fn, false);
}
else {
el.attachEvent('on' + evt, fn);
}
}
function getDomainName(url) {
return url.match(reURI)[3];
}
function sendMessage(target, targetsUrl, command, params) {
if (!params) {
params = {};
}
params = JSON.stringify(params);
target.postMessage([command, params].join(':'), targetsUrl);
}
var getXHR = (function() {
var XMLHttpFactories = [
function () { return new XMLHttpRequest(); },
function () { return new ActiveXObject("Msxml2.XMLHTTP"); },
function () { return new ActiveXObject("Msxml3.XMLHTTP"); },
function () { return new ActiveXObject("Microsoft.XMLHTTP"); }
];
var xmlhttp = false;
for (var i=0;i<XMLHttpFactories.length;i++) {
try {
XMLHttpFactories[i]();
xmlhttp = XMLHttpFactories[i];
}
catch (e) {
continue;
}
break;
}
return xmlhttp;
}());
// --------------------------------------------------
// FIBER
// --------------------------------------------------
/*
Inject
Copyright 2011 LinkedIn
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an "AS
IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
express or implied. See the License for the specific language
governing permissions and limitations under the License.
*/
var module = {
exports: {}
};
// Fiber.js 1.0.4
// @Author: Kirollos Risk
//
// Copyright (c) 2012 LinkedIn.
// All Rights Reserved. Apache Software License 2.0
// http://www.apache.org/licenses/LICENSE-2.0
( function( global ) {
// Baseline setup
// --------------
// Stores whether the object is being initialized. i.e., whether
// to run the `init` function, or not.
var initializing = false,
// Keep a few prototype references around - for speed access,
// and saving bytes in the minified version.
ArrayProto = Array.prototype,
// Save the previous value of `Fiber`.
previousFiber = global.Fiber;
// Helper function to copy properties from one object to the other.
function copy( from, to ) {
var name;
for( name in from ) {
if( from.hasOwnProperty( name ) ) {
to[name] = from[name];
}
}
}
// The base `Fiber` implementation.
function Fiber(){};
// ###Extend
//
// Returns a subclass.
Fiber.extend = function( fn ) {
// Keep a reference to the current prototye.
var parent = this.prototype,
// Invoke the function which will return an object literal used to define
// the prototype. Additionally, pass in the parent prototype, which will
// allow instances to use it.
properties = fn( parent ),
// Stores the constructor's prototype.
proto;
// The constructor function for a subclass.
function child(){
if( !initializing ){
// Custom initialization is done in the `init` method.
this.init.apply( this, arguments );
// Prevent susbsequent calls to `init`.
// Note: although a `delete this.init` would remove the `init` function from the instance,
// it would still exist in its super class' prototype. Therefore, explicitly set
// `init` to `void 0` to obtain the `undefined` primitive value (in case the global's `undefined`
// property has been re-assigned).
this.init = void 0;
}
}
// Instantiate a base class (but only create the instance, without running `init`).
// and make every `constructor` instance an instance of `this` and of `constructor`.
initializing = true;
proto = child.prototype = new this;
initializing = false;
// Add default `init` function, which a class may override; it should call the
// super class' `init` function (if it exists);
proto.init = function(){
if ( typeof parent.init === 'function' ) {
parent.init.apply( this, arguments );
}
};
// Copy the properties over onto the new prototype.
copy( properties, proto );
// Enforce the constructor to be what we expect.
proto.constructor = child;
// Keep a reference to the parent prototype.
// (Note: currently used by decorators and mixins, so that the parent can be inferred).
child.__base__ = parent;
// Make this class extendable.
child.extend = Fiber.extend;
return child;
};
// Utilities
// ---------
// ###Proxy
//
// Returns a proxy object for accessing base methods with a given context.
//
// - `base`: the instance' parent class prototype.
// - `instance`: a Fiber class instance.
//
// Overloads:
//
// - `Fiber.proxy( instance )`
// - `Fiber.proxy( base, instance )`
//
Fiber.proxy = function( base, instance ) {
var name,
iface = {},
wrap;
// If there's only 1 argument specified, then it is the instance,
// thus infer `base` from its constructor.
if ( arguments.length === 1 ) {
instance = base;
base = instance.constructor.__base__;
}
// Returns a function which calls another function with `instance` as
// the context.
wrap = function( fn ) {
return function() {
return base[fn].apply( instance, arguments );
};
};
// For each function in `base`, create a wrapped version.
for( name in base ){
if( base.hasOwnProperty( name ) && typeof base[name] === 'function' ){
iface[name] = wrap( name );
}
}
return iface;
};
// ###Decorate
//
// Decorate an instance with given decorator(s).
//
// - `instance`: a Fiber class instance.
// - `decorator[s]`: the argument list of decorator functions.
//
// Note: when a decorator is executed, the argument passed in is the super class' prototype,
// and the context (i.e. the `this` binding) is the instance.
//
// *Example usage:*
//
// function Decorator( base ) {
// // this === obj
// return {
// greet: function() {
// console.log('hi!');
// }
// };
// }
//
// var obj = new Bar(); // Some instance of a Fiber class
// Fiber.decorate(obj, Decorator);
// obj.greet(); // hi!
//
Fiber.decorate = function( instance /*, decorator[s] */) {
var i,
// Get the base prototype.
base = instance.constructor.__base__,
// Get all the decorators in the arguments.
decorators = ArrayProto.slice.call( arguments, 1 ),
len = decorators.length;
for( i = 0; i < len; i++ ){
copy( decorators[i].call( instance, base ), instance );
}
};
// ###Mixin