This repository has been archived by the owner on Aug 14, 2023. It is now read-only.
forked from JohannesHoppe/bower-datajs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
datajs.js
10577 lines (8938 loc) · 489 KB
/
datajs.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
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy,
// modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// datajs.js
(function (window, undefined) {
var datajs = window.datajs || {};
var odata = window.OData || {};
// AMD support
if (typeof define === 'function' && define.amd) {
define('datajs', datajs);
define('OData', odata);
} else {
window.datajs = datajs;
window.OData = odata;
}
datajs.version = {
major: 1,
minor: 1,
build: 1
};
var activeXObject = function (progId) {
/// <summary>Creates a new ActiveXObject from the given progId.</summary>
/// <param name="progId" type="String" mayBeNull="false" optional="false">
/// ProgId string of the desired ActiveXObject.
/// </param>
/// <remarks>
/// This function throws whatever exception might occur during the creation
/// of the ActiveXObject.
/// </remarks>
/// <returns type="Object">
/// The ActiveXObject instance. Null if ActiveX is not supported by the
/// browser.
/// </returns>
if (window.ActiveXObject) {
return new window.ActiveXObject(progId);
}
return null;
};
var assigned = function (value) {
/// <summary>Checks whether the specified value is different from null and undefined.</summary>
/// <param name="value" mayBeNull="true" optional="true">Value to check.</param>
/// <returns type="Boolean">true if the value is assigned; false otherwise.</returns>
return value !== null && value !== undefined;
};
var contains = function (arr, item) {
/// <summary>Checks whether the specified item is in the array.</summary>
/// <param name="arr" type="Array" optional="false" mayBeNull="false">Array to check in.</param>
/// <param name="item">Item to look for.</param>
/// <returns type="Boolean">true if the item is contained, false otherwise.</returns>
var i, len;
for (i = 0, len = arr.length; i < len; i++) {
if (arr[i] === item) {
return true;
}
}
return false;
};
var defined = function (a, b) {
/// <summary>Given two values, picks the first one that is not undefined.</summary>
/// <param name="a">First value.</param>
/// <param name="b">Second value.</param>
/// <returns>a if it's a defined value; else b.</returns>
return (a !== undefined) ? a : b;
};
var delay = function (callback) {
/// <summary>Delays the invocation of the specified function until execution unwinds.</summary>
/// <param name="callback" type="Function">Callback function.</param>
if (arguments.length === 1) {
window.setTimeout(callback, 0);
return;
}
var args = Array.prototype.slice.call(arguments, 1);
window.setTimeout(function () {
callback.apply(this, args);
}, 0);
};
var extend = function (target, values) {
/// <summary>Extends the target with the specified values.</summary>
/// <param name="target" type="Object">Object to add properties to.</param>
/// <param name="values" type="Object">Object with properties to add into target.</param>
/// <returns type="Object">The target object.</returns>
for (var name in values) {
target[name] = values[name];
}
return target;
};
var find = function (arr, callback) {
/// <summary>Returns the first item in the array that makes the callback function true.</summary>
/// <param name="arr" type="Array" optional="false" mayBeNull="true">Array to check in.</param>
/// <param name="callback" type="Function">Callback function to invoke once per item in the array.</param>
/// <returns>The first item that makes the callback return true; null otherwise or if the array is null.</returns>
if (arr) {
var i, len;
for (i = 0, len = arr.length; i < len; i++) {
if (callback(arr[i])) {
return arr[i];
}
}
}
return null;
};
var isArray = function (value) {
/// <summary>Checks whether the specified value is an array object.</summary>
/// <param name="value">Value to check.</param>
/// <returns type="Boolean">true if the value is an array object; false otherwise.</returns>
return Object.prototype.toString.call(value) === "[object Array]";
};
var isDate = function (value) {
/// <summary>Checks whether the specified value is a Date object.</summary>
/// <param name="value">Value to check.</param>
/// <returns type="Boolean">true if the value is a Date object; false otherwise.</returns>
return Object.prototype.toString.call(value) === "[object Date]";
};
var isObject = function (value) {
/// <summary>Tests whether a value is an object.</summary>
/// <param name="value">Value to test.</param>
/// <remarks>
/// Per javascript rules, null and array values are objects and will cause this function to return true.
/// </remarks>
/// <returns type="Boolean">True is the value is an object; false otherwise.</returns>
return typeof value === "object";
};
var parseInt10 = function (value) {
/// <summary>Parses a value in base 10.</summary>
/// <param name="value" type="String">String value to parse.</param>
/// <returns type="Number">The parsed value, NaN if not a valid value.</returns>
return parseInt(value, 10);
};
var renameProperty = function (obj, oldName, newName) {
/// <summary>Renames a property in an object.</summary>
/// <param name="obj" type="Object">Object in which the property will be renamed.</param>
/// <param name="oldName" type="String">Name of the property that will be renamed.</param>
/// <param name="newName" type="String">New name of the property.</param>
/// <remarks>
/// This function will not do anything if the object doesn't own a property with the specified old name.
/// </remarks>
if (obj.hasOwnProperty(oldName)) {
obj[newName] = obj[oldName];
delete obj[oldName];
}
};
var throwErrorCallback = function (error) {
/// <summary>Default error handler.</summary>
/// <param name="error" type="Object">Error to handle.</param>
throw error;
};
var trimString = function (str) {
/// <summary>Removes leading and trailing whitespaces from a string.</summary>
/// <param name="str" type="String" optional="false" mayBeNull="false">String to trim</param>
/// <returns type="String">The string with no leading or trailing whitespace.</returns>
if (str.trim) {
return str.trim();
}
return str.replace(/^\s+|\s+$/g, '');
};
var undefinedDefault = function (value, defaultValue) {
/// <summary>Returns a default value in place of undefined.</summary>
/// <param name="value" mayBeNull="true" optional="true">Value to check.</param>
/// <param name="defaultValue">Value to return if value is undefined.</param>
/// <returns>value if it's defined; defaultValue otherwise.</returns>
/// <remarks>
/// This should only be used for cases where falsy values are valid;
/// otherwise the pattern should be 'x = (value) ? value : defaultValue;'.
/// </remarks>
return (value !== undefined) ? value : defaultValue;
};
// Regular expression that splits a uri into its components:
// 0 - is the matched string.
// 1 - is the scheme.
// 2 - is the authority.
// 3 - is the path.
// 4 - is the query.
// 5 - is the fragment.
var uriRegEx = /^([^:\/?#]+:)?(\/\/[^\/?#]*)?([^?#:]+)?(\?[^#]*)?(#.*)?/;
var uriPartNames = ["scheme", "authority", "path", "query", "fragment"];
var getURIInfo = function (uri) {
/// <summary>Gets information about the components of the specified URI.</summary>
/// <param name="uri" type="String">URI to get information from.</param>
/// <returns type="Object">
/// An object with an isAbsolute flag and part names (scheme, authority, etc.) if available.
/// </returns>
var result = { isAbsolute: false };
if (uri) {
var matches = uriRegEx.exec(uri);
if (matches) {
var i, len;
for (i = 0, len = uriPartNames.length; i < len; i++) {
if (matches[i + 1]) {
result[uriPartNames[i]] = matches[i + 1];
}
}
}
if (result.scheme) {
result.isAbsolute = true;
}
}
return result;
};
var getURIFromInfo = function (uriInfo) {
/// <summary>Builds a URI string from its components.</summary>
/// <param name="uriInfo" type="Object"> An object with uri parts (scheme, authority, etc.).</param>
/// <returns type="String">URI string.</returns>
return "".concat(
uriInfo.scheme || "",
uriInfo.authority || "",
uriInfo.path || "",
uriInfo.query || "",
uriInfo.fragment || "");
};
// Regular expression that splits a uri authority into its subcomponents:
// 0 - is the matched string.
// 1 - is the userinfo subcomponent.
// 2 - is the host subcomponent.
// 3 - is the port component.
var uriAuthorityRegEx = /^\/{0,2}(?:([^@]*)@)?([^:]+)(?::{1}(\d+))?/;
// Regular expression that matches percentage enconded octects (i.e %20 or %3A);
var pctEncodingRegEx = /%[0-9A-F]{2}/ig;
var normalizeURICase = function (uri) {
/// <summary>Normalizes the casing of a URI.</summary>
/// <param name="uri" type="String">URI to normalize, absolute or relative.</param>
/// <returns type="String">The URI normalized to lower case.</returns>
var uriInfo = getURIInfo(uri);
var scheme = uriInfo.scheme;
var authority = uriInfo.authority;
if (scheme) {
uriInfo.scheme = scheme.toLowerCase();
if (authority) {
var matches = uriAuthorityRegEx.exec(authority);
if (matches) {
uriInfo.authority = "//" +
(matches[1] ? matches[1] + "@" : "") +
(matches[2].toLowerCase()) +
(matches[3] ? ":" + matches[3] : "");
}
}
}
uri = getURIFromInfo(uriInfo);
return uri.replace(pctEncodingRegEx, function (str) {
return str.toLowerCase();
});
};
var normalizeURI = function (uri, base) {
/// <summary>Normalizes a possibly relative URI with a base URI.</summary>
/// <param name="uri" type="String">URI to normalize, absolute or relative.</param>
/// <param name="base" type="String" mayBeNull="true">Base URI to compose with.</param>
/// <returns type="String">The composed URI if relative; the original one if absolute.</returns>
if (!base) {
return uri;
}
var uriInfo = getURIInfo(uri);
if (uriInfo.isAbsolute) {
return uri;
}
var baseInfo = getURIInfo(base);
var normInfo = {};
var path;
if (uriInfo.authority) {
normInfo.authority = uriInfo.authority;
path = uriInfo.path;
normInfo.query = uriInfo.query;
} else {
if (!uriInfo.path) {
path = baseInfo.path;
normInfo.query = uriInfo.query || baseInfo.query;
} else {
if (uriInfo.path.charAt(0) === '/') {
path = uriInfo.path;
} else {
path = mergeUriPathWithBase(uriInfo.path, baseInfo.path);
}
normInfo.query = uriInfo.query;
}
normInfo.authority = baseInfo.authority;
}
normInfo.path = removeDotsFromPath(path);
normInfo.scheme = baseInfo.scheme;
normInfo.fragment = uriInfo.fragment;
return getURIFromInfo(normInfo);
};
var mergeUriPathWithBase = function (uriPath, basePath) {
/// <summary>Merges the path of a relative URI and a base URI.</summary>
/// <param name="uriPath" type="String>Relative URI path.</param>
/// <param name="basePath" type="String">Base URI path.</param>
/// <returns type="String">A string with the merged path.</returns>
var path = "/";
var end;
if (basePath) {
end = basePath.lastIndexOf("/");
path = basePath.substring(0, end);
if (path.charAt(path.length - 1) !== "/") {
path = path + "/";
}
}
return path + uriPath;
};
var removeDotsFromPath = function (path) {
/// <summary>Removes the special folders . and .. from a URI's path.</summary>
/// <param name="path" type="string">URI path component.</param>
/// <returns type="String">Path without any . and .. folders.</returns>
var result = "";
var segment = "";
var end;
while (path) {
if (path.indexOf("..") === 0 || path.indexOf(".") === 0) {
path = path.replace(/^\.\.?\/?/g, "");
} else if (path.indexOf("/..") === 0) {
path = path.replace(/^\/\..\/?/g, "/");
end = result.lastIndexOf("/");
if (end === -1) {
result = "";
} else {
result = result.substring(0, end);
}
} else if (path.indexOf("/.") === 0) {
path = path.replace(/^\/\.\/?/g, "/");
} else {
segment = path;
end = path.indexOf("/", 1);
if (end !== -1) {
segment = path.substring(0, end);
}
result = result + segment;
path = path.replace(segment, "");
}
}
return result;
};
var convertByteArrayToHexString = function (str) {
var arr = [];
if (window.atob === undefined) {
arr = decodeBase64(str);
} else {
var binaryStr = window.atob(str);
for (var i = 0; i < binaryStr.length; i++) {
arr.push(binaryStr.charCodeAt(i));
}
}
var hexValue = "";
var hexValues = "0123456789ABCDEF";
for (var j = 0; j < arr.length; j++) {
var t = arr[j];
hexValue += hexValues[t >> 4];
hexValue += hexValues[t & 0x0F];
}
return hexValue;
};
var decodeBase64 = function (str) {
var binaryString = "";
for (var i = 0; i < str.length; i++) {
var base65IndexValue = getBase64IndexValue(str[i]);
var binaryValue = "";
if (base65IndexValue !== null) {
binaryValue = base65IndexValue.toString(2);
binaryString += addBase64Padding(binaryValue);
}
}
var byteArray = [];
var numberOfBytes = parseInt(binaryString.length / 8, 10);
for (i = 0; i < numberOfBytes; i++) {
var intValue = parseInt(binaryString.substring(i * 8, (i + 1) * 8), 2);
byteArray.push(intValue);
}
return byteArray;
};
var getBase64IndexValue = function (character) {
var asciiCode = character.charCodeAt(0);
var asciiOfA = 65;
var differenceBetweenZanda = 6;
if (asciiCode >= 65 && asciiCode <= 90) { // between "A" and "Z" inclusive
return asciiCode - asciiOfA;
} else if (asciiCode >= 97 && asciiCode <= 122) { // between 'a' and 'z' inclusive
return asciiCode - asciiOfA - differenceBetweenZanda;
} else if (asciiCode >= 48 && asciiCode <= 57) { // between '0' and '9' inclusive
return asciiCode + 4;
} else if (character == "+") {
return 62;
} else if (character == "/") {
return 63;
} else {
return null;
}
};
var addBase64Padding = function (binaryString) {
while (binaryString.length < 6) {
binaryString = "0" + binaryString;
}
return binaryString;
};
// URI prefixes to generate smaller code.
var http = "http://";
var w3org = http + "www.w3.org/"; // http://www.w3.org/
var xhtmlNS = w3org + "1999/xhtml"; // http://www.w3.org/1999/xhtml
var xmlnsNS = w3org + "2000/xmlns/"; // http://www.w3.org/2000/xmlns/
var xmlNS = w3org + "XML/1998/namespace"; // http://www.w3.org/XML/1998/namespace
var mozillaParserErroNS = http + "www.mozilla.org/newlayout/xml/parsererror.xml";
var hasLeadingOrTrailingWhitespace = function (text) {
/// <summary>Checks whether the specified string has leading or trailing spaces.</summary>
/// <param name="text" type="String">String to check.</param>
/// <returns type="Boolean">true if text has any leading or trailing whitespace; false otherwise.</returns>
var re = /(^\s)|(\s$)/;
return re.test(text);
};
var isWhitespace = function (text) {
/// <summary>Determines whether the specified text is empty or whitespace.</summary>
/// <param name="text" type="String">Value to inspect.</param>
/// <returns type="Boolean">true if the text value is empty or all whitespace; false otherwise.</returns>
var ws = /^\s*$/;
return text === null || ws.test(text);
};
var isWhitespacePreserveContext = function (domElement) {
/// <summary>Determines whether the specified element has xml:space='preserve' applied.</summary>
/// <param name="domElement">Element to inspect.</param>
/// <returns type="Boolean">Whether xml:space='preserve' is in effect.</returns>
while (domElement !== null && domElement.nodeType === 1) {
var val = xmlAttributeValue(domElement, "space", xmlNS);
if (val === "preserve") {
return true;
} else if (val === "default") {
break;
} else {
domElement = domElement.parentNode;
}
}
return false;
};
var isXmlNSDeclaration = function (domAttribute) {
/// <summary>Determines whether the attribute is a XML namespace declaration.</summary>
/// <param name="domAttribute">Element to inspect.</param>
/// <returns type="Boolean">
/// True if the attribute is a namespace declaration (its name is 'xmlns' or starts with 'xmlns:'; false otherwise.
/// </returns>
var nodeName = domAttribute.nodeName;
return nodeName == "xmlns" || nodeName.indexOf("xmlns:") === 0;
};
var safeSetProperty = function (obj, name, value) {
/// <summary>Safely set as property in an object by invoking obj.setProperty.</summary>
/// <param name="obj">Object that exposes a setProperty method.</param>
/// <param name="name" type="String" mayBeNull="false">Property name.</param>
/// <param name="value">Property value.</param>
try {
obj.setProperty(name, value);
} catch (_) { }
};
var msXmlDom3 = function () {
/// <summary>Creates an configures new MSXML 3.0 ActiveX object.</summary>
/// <remakrs>
/// This function throws any exception that occurs during the creation
/// of the MSXML 3.0 ActiveX object.
/// <returns type="Object">New MSXML 3.0 ActiveX object.</returns>
var msxml3 = activeXObject("Msxml2.DOMDocument.3.0");
if (msxml3) {
safeSetProperty(msxml3, "ProhibitDTD", true);
safeSetProperty(msxml3, "MaxElementDepth", 256);
safeSetProperty(msxml3, "AllowDocumentFunction", false);
safeSetProperty(msxml3, "AllowXsltScript", false);
}
return msxml3;
};
var msXmlDom = function () {
/// <summary>Creates an configures new MSXML 6.0 or MSXML 3.0 ActiveX object.</summary>
/// <remakrs>
/// This function will try to create a new MSXML 6.0 ActiveX object. If it fails then
/// it will fallback to create a new MSXML 3.0 ActiveX object. Any exception that
/// happens during the creation of the MSXML 6.0 will be handled by the function while
/// the ones that happend during the creation of the MSXML 3.0 will be thrown.
/// <returns type="Object">New MSXML 3.0 ActiveX object.</returns>
try {
var msxml = activeXObject("Msxml2.DOMDocument.6.0");
if (msxml) {
msxml.async = true;
}
return msxml;
} catch (_) {
return msXmlDom3();
}
};
var msXmlParse = function (text) {
/// <summary>Parses an XML string using the MSXML DOM.</summary>
/// <remakrs>
/// This function throws any exception that occurs during the creation
/// of the MSXML ActiveX object. It also will throw an exception
/// in case of a parsing error.
/// <returns type="Object">New MSXML DOMDocument node representing the parsed XML string.</returns>
var dom = msXmlDom();
if (!dom) {
return null;
}
dom.loadXML(text);
var parseError = dom.parseError;
if (parseError.errorCode !== 0) {
xmlThrowParserError(parseError.reason, parseError.srcText, text);
}
return dom;
};
var xmlThrowParserError = function (exceptionOrReason, srcText, errorXmlText) {
/// <summary>Throws a new exception containing XML parsing error information.</summary>
/// <param name="exceptionOrReason">
/// String indicatin the reason of the parsing failure or
/// Object detailing the parsing error.
/// </param>
/// <param name="srcText" type="String">
/// String indicating the part of the XML string that caused the parsing error.
/// </param>
/// <param name="errorXmlText" type="String">XML string for wich the parsing failed.</param>
if (typeof exceptionOrReason === "string") {
exceptionOrReason = { message: exceptionOrReason };
}
throw extend(exceptionOrReason, { srcText: srcText || "", errorXmlText: errorXmlText || "" });
};
var xmlParse = function (text) {
/// <summary>Returns an XML DOM document from the specified text.</summary>
/// <param name="text" type="String">Document text.</param>
/// <returns>XML DOM document.</returns>
/// <remarks>This function will throw an exception in case of a parse error.</remarks>
var domParser = window.DOMParser && new window.DOMParser();
var dom;
if (!domParser) {
dom = msXmlParse(text);
if (!dom) {
xmlThrowParserError("XML DOM parser not supported");
}
return dom;
}
try {
dom = domParser.parseFromString(text, "text/xml");
} catch (e) {
xmlThrowParserError(e, "", text);
}
var element = dom.documentElement;
var nsURI = element.namespaceURI;
var localName = xmlLocalName(element);
// Firefox reports errors by returing the DOM for an xml document describing the problem.
if (localName === "parsererror" && nsURI === mozillaParserErroNS) {
var srcTextElement = xmlFirstChildElement(element, mozillaParserErroNS, "sourcetext");
var srcText = srcTextElement ? xmlNodeValue(srcTextElement) : "";
xmlThrowParserError(xmlInnerText(element) || "", srcText, text);
}
// Chrome (and maybe other webkit based browsers) report errors by injecting a header with an error message.
// The error may be localized, so instead we simply check for a header as the
// top element or descendant child of the document.
if (localName === "h3" && nsURI === xhtmlNS || xmlFirstDescendantElement(element, xhtmlNS, "h3")) {
var reason = "";
var siblings = [];
var cursor = element.firstChild;
while (cursor) {
if (cursor.nodeType === 1) {
reason += xmlInnerText(cursor) || "";
}
siblings.push(cursor.nextSibling);
cursor = cursor.firstChild || siblings.shift();
}
reason += xmlInnerText(element) || "";
xmlThrowParserError(reason, "", text);
}
return dom;
};
var xmlQualifiedName = function (prefix, name) {
/// <summary>Builds a XML qualified name string in the form of "prefix:name".</summary>
/// <param name="prefix" type="String" maybeNull="true">Prefix string.</param>
/// <param name="name" type="String">Name string to qualify with the prefix.</param>
/// <returns type="String">Qualified name.</returns>
return prefix ? prefix + ":" + name : name;
};
var xmlAppendText = function (domNode, textNode) {
/// <summary>Appends a text node into the specified DOM element node.</summary>
/// <param name="domNode">DOM node for the element.</param>
/// <param name="text" type="String" mayBeNull="false">Text to append as a child of element.</param>
if (hasLeadingOrTrailingWhitespace(textNode.data)) {
var attr = xmlAttributeNode(domNode, xmlNS, "space");
if (!attr) {
attr = xmlNewAttribute(domNode.ownerDocument, xmlNS, xmlQualifiedName("xml", "space"));
xmlAppendChild(domNode, attr);
}
attr.value = "preserve";
}
domNode.appendChild(textNode);
return domNode;
};
var xmlAttributes = function (element, onAttributeCallback) {
/// <summary>Iterates through the XML element's attributes and invokes the callback function for each one.</summary>
/// <param name="element">Wrapped element to iterate over.</param>
/// <param name="onAttributeCallback" type="Function">Callback function to invoke with wrapped attribute nodes.</param>
var attributes = element.attributes;
var i, len;
for (i = 0, len = attributes.length; i < len; i++) {
onAttributeCallback(attributes.item(i));
}
};
var xmlAttributeValue = function (domNode, localName, nsURI) {
/// <summary>Returns the value of a DOM element's attribute.</summary>
/// <param name="domNode">DOM node for the owning element.</param>
/// <param name="localName" type="String">Local name of the attribute.</param>
/// <param name="nsURI" type="String">Namespace URI of the attribute.</param>
/// <returns type="String" maybeNull="true">The attribute value, null if not found.</returns>
var attribute = xmlAttributeNode(domNode, localName, nsURI);
return attribute ? xmlNodeValue(attribute) : null;
};
var xmlAttributeNode = function (domNode, localName, nsURI) {
/// <summary>Gets an attribute node from a DOM element.</summary>
/// <param name="domNode">DOM node for the owning element.</param>
/// <param name="localName" type="String">Local name of the attribute.</param>
/// <param name="nsURI" type="String">Namespace URI of the attribute.</param>
/// <returns>The attribute node, null if not found.</returns>
var attributes = domNode.attributes;
if (attributes.getNamedItemNS) {
return attributes.getNamedItemNS(nsURI || null, localName);
}
return attributes.getQualifiedItem(localName, nsURI) || null;
};
var xmlBaseURI = function (domNode, baseURI) {
/// <summary>Gets the value of the xml:base attribute on the specified element.</summary>
/// <param name="domNode">Element to get xml:base attribute value from.</param>
/// <param name="baseURI" mayBeNull="true" optional="true">Base URI used to normalize the value of the xml:base attribute.</param>
/// <returns type="String">Value of the xml:base attribute if found; the baseURI or null otherwise.</returns>
var base = xmlAttributeNode(domNode, "base", xmlNS);
return (base ? normalizeURI(base.value, baseURI) : baseURI) || null;
};
var xmlChildElements = function (domNode, onElementCallback) {
/// <summary>Iterates through the XML element's child DOM elements and invokes the callback function for each one.</summary>
/// <param name="element">DOM Node containing the DOM elements to iterate over.</param>
/// <param name="onElementCallback" type="Function">Callback function to invoke for each child DOM element.</param>
xmlTraverse(domNode, /*recursive*/false, function (child) {
if (child.nodeType === 1) {
onElementCallback(child);
}
// continue traversing.
return true;
});
};
var xmlFindElementByPath = function (root, namespaceURI, path) {
/// <summary>Gets the descendant element under root that corresponds to the specified path and namespace URI.</summary>
/// <param name="root">DOM element node from which to get the descendant element.</param>
/// <param name="namespaceURI" type="String">The namespace URI of the element to match.</param>
/// <param name="path" type="String">Path to the desired descendant element.</param>
/// <returns>The element specified by path and namespace URI.</returns>
/// <remarks>
/// All the elements in the path are matched against namespaceURI.
/// The function will stop searching on the first element that doesn't match the namespace and the path.
/// </remarks>
var parts = path.split("/");
var i, len;
for (i = 0, len = parts.length; i < len; i++) {
root = root && xmlFirstChildElement(root, namespaceURI, parts[i]);
}
return root || null;
};
var xmlFindNodeByPath = function (root, namespaceURI, path) {
/// <summary>Gets the DOM element or DOM attribute node under root that corresponds to the specified path and namespace URI.</summary>
/// <param name="root">DOM element node from which to get the descendant node.</param>
/// <param name="namespaceURI" type="String">The namespace URI of the node to match.</param>
/// <param name="path" type="String">Path to the desired descendant node.</param>
/// <returns>The node specified by path and namespace URI.</returns>
/// <remarks>
/// This function will traverse the path and match each node associated to a path segement against the namespace URI.
/// The traversal stops when the whole path has been exahusted or a node that doesn't belogong the specified namespace is encountered.
///
/// The last segment of the path may be decorated with a starting @ character to indicate that the desired node is a DOM attribute.
/// </remarks>
var lastSegmentStart = path.lastIndexOf("/");
var nodePath = path.substring(lastSegmentStart + 1);
var parentPath = path.substring(0, lastSegmentStart);
var node = parentPath ? xmlFindElementByPath(root, namespaceURI, parentPath) : root;
if (node) {
if (nodePath.charAt(0) === "@") {
return xmlAttributeNode(node, nodePath.substring(1), namespaceURI);
}
return xmlFirstChildElement(node, namespaceURI, nodePath);
}
return null;
};
var xmlFirstChildElement = function (domNode, namespaceURI, localName) {
/// <summary>Returns the first child DOM element under the specified DOM node that matches the specified namespace URI and local name.</summary>
/// <param name="domNode">DOM node from which the child DOM element is going to be retrieved.</param>
/// <param name="namespaceURI" type="String" optional="true">The namespace URI of the element to match.</param>
/// <param name="localName" type="String" optional="true">Name of the element to match.</param>
/// <returns>The node's first child DOM element that matches the specified namespace URI and local name; null otherwise.</returns>
return xmlFirstElementMaybeRecursive(domNode, namespaceURI, localName, /*recursive*/false);
};
var xmlFirstDescendantElement = function (domNode, namespaceURI, localName) {
/// <summary>Returns the first descendant DOM element under the specified DOM node that matches the specified namespace URI and local name.</summary>
/// <param name="domNode">DOM node from which the descendant DOM element is going to be retrieved.</param>
/// <param name="namespaceURI" type="String" optional="true">The namespace URI of the element to match.</param>
/// <param name="localName" type="String" optional="true">Name of the element to match.</param>
/// <returns>The node's first descendant DOM element that matches the specified namespace URI and local name; null otherwise.</returns>
if (domNode.getElementsByTagNameNS) {
var result = domNode.getElementsByTagNameNS(namespaceURI, localName);
return result.length > 0 ? result[0] : null;
}
return xmlFirstElementMaybeRecursive(domNode, namespaceURI, localName, /*recursive*/true);
};
var xmlFirstElementMaybeRecursive = function (domNode, namespaceURI, localName, recursive) {
/// <summary>Returns the first descendant DOM element under the specified DOM node that matches the specified namespace URI and local name.</summary>
/// <param name="domNode">DOM node from which the descendant DOM element is going to be retrieved.</param>
/// <param name="namespaceURI" type="String" optional="true">The namespace URI of the element to match.</param>
/// <param name="localName" type="String" optional="true">Name of the element to match.</param>
/// <param name="recursive" type="Boolean">
/// True if the search should include all the descendants of the DOM node.
/// False if the search should be scoped only to the direct children of the DOM node.
/// </param>
/// <returns>The node's first descendant DOM element that matches the specified namespace URI and local name; null otherwise.</returns>
var firstElement = null;
xmlTraverse(domNode, recursive, function (child) {
if (child.nodeType === 1) {
var isExpectedNamespace = !namespaceURI || xmlNamespaceURI(child) === namespaceURI;
var isExpectedNodeName = !localName || xmlLocalName(child) === localName;
if (isExpectedNamespace && isExpectedNodeName) {
firstElement = child;
}
}
return firstElement === null;
});
return firstElement;
};
var xmlInnerText = function (xmlElement) {
/// <summary>Gets the concatenated value of all immediate child text and CDATA nodes for the specified element.</summary>
/// <param name="domElement">Element to get values for.</param>
/// <returns type="String">Text for all direct children.</returns>
var result = null;
var root = (xmlElement.nodeType === 9 && xmlElement.documentElement) ? xmlElement.documentElement : xmlElement;
var whitespaceAlreadyRemoved = root.ownerDocument.preserveWhiteSpace === false;
var whitespacePreserveContext;
xmlTraverse(root, false, function (child) {
if (child.nodeType === 3 || child.nodeType === 4) {
// isElementContentWhitespace indicates that this is 'ignorable whitespace',
// but it's not defined by all browsers, and does not honor xml:space='preserve'
// in some implementations.
//
// If we can't tell either way, we walk up the tree to figure out whether
// xml:space is set to preserve; otherwise we discard pure-whitespace.
//
// For example <a> <b>1</b></a>. The space between <a> and <b> is usually 'ignorable'.
var text = xmlNodeValue(child);
var shouldInclude = whitespaceAlreadyRemoved || !isWhitespace(text);
if (!shouldInclude) {
// Walk up the tree to figure out whether we are in xml:space='preserve' context
// for the cursor (needs to happen only once).
if (whitespacePreserveContext === undefined) {
whitespacePreserveContext = isWhitespacePreserveContext(root);
}
shouldInclude = whitespacePreserveContext;
}
if (shouldInclude) {
if (!result) {
result = text;
} else {
result += text;
}
}
}
// Continue traversing?
return true;
});
return result;
};
var xmlLocalName = function (domNode) {
/// <summary>Returns the localName of a XML node.</summary>
/// <param name="domNode">DOM node to get the value from.</param>
/// <returns type="String">localName of domNode.</returns>
return domNode.localName || domNode.baseName;
};
var xmlNamespaceURI = function (domNode) {
/// <summary>Returns the namespace URI of a XML node.</summary>
/// <param name="node">DOM node to get the value from.</param>
/// <returns type="String">Namespace URI of domNode.</returns>
return domNode.namespaceURI || null;
};
var xmlNodeValue = function (domNode) {
/// <summary>Returns the value or the inner text of a XML node.</summary>
/// <param name="node">DOM node to get the value from.</param>
/// <returns>Value of the domNode or the inner text if domNode represents a DOM element node.</returns>
if (domNode.nodeType === 1) {
return xmlInnerText(domNode);
}
return domNode.nodeValue;
};
var xmlTraverse = function (domNode, recursive, onChildCallback) {
/// <summary>Walks through the descendants of the domNode and invokes a callback for each node.</summary>
/// <param name="domNode">DOM node whose descendants are going to be traversed.</param>
/// <param name="recursive" type="Boolean">
/// True if the traversal should include all the descenants of the DOM node.
/// False if the traversal should be scoped only to the direct children of the DOM node.
/// </param>
/// <returns type="String">Namespace URI of node.</returns>
var subtrees = [];
var child = domNode.firstChild;
var proceed = true;
while (child && proceed) {
proceed = onChildCallback(child);
if (proceed) {
if (recursive && child.firstChild) {
subtrees.push(child.firstChild);
}
child = child.nextSibling || subtrees.shift();
}
}
};
var xmlSiblingElement = function (domNode, namespaceURI, localName) {
/// <summary>Returns the next sibling DOM element of the specified DOM node.</summary>
/// <param name="domNode">DOM node from which the next sibling is going to be retrieved.</param>
/// <param name="namespaceURI" type="String" optional="true">The namespace URI of the element to match.</param>
/// <param name="localName" type="String" optional="true">Name of the element to match.</param>
/// <returns>The node's next sibling DOM element, null if there is none.</returns>
var sibling = domNode.nextSibling;
while (sibling) {
if (sibling.nodeType === 1) {
var isExpectedNamespace = !namespaceURI || xmlNamespaceURI(sibling) === namespaceURI;
var isExpectedNodeName = !localName || xmlLocalName(sibling) === localName;
if (isExpectedNamespace && isExpectedNodeName) {
return sibling;
}
}
sibling = sibling.nextSibling;
}
return null;
};
var xmlDom = function () {
/// <summary>Creates a new empty DOM document node.</summary>
/// <returns>New DOM document node.</returns>
/// <remarks>
/// This function will first try to create a native DOM document using
/// the browsers createDocument function. If the browser doesn't
/// support this but supports ActiveXObject, then an attempt to create
/// an MSXML 6.0 DOM will be made. If this attempt fails too, then an attempt
/// for creating an MXSML 3.0 DOM will be made. If this last attemp fails or
/// the browser doesn't support ActiveXObject then an exception will be thrown.
/// </remarks>
var implementation = window.document.implementation;
return (implementation && implementation.createDocument) ?
implementation.createDocument(null, null, null) :
msXmlDom();
};
var xmlAppendChildren = function (parent, children) {
/// <summary>Appends a collection of child nodes or string values to a parent DOM node.</summary>
/// <param name="parent">DOM node to which the children will be appended.</param>
/// <param name="children" type="Array">Array containing DOM nodes or string values that will be appended to the parent.</param>
/// <returns>The parent with the appended children or string values.</returns>
/// <remarks>
/// If a value in the children collection is a string, then a new DOM text node is going to be created
/// for it and then appended to the parent.
/// </remarks>
if (!isArray(children)) {
return xmlAppendChild(parent, children);
}