-
Notifications
You must be signed in to change notification settings - Fork 34
/
portal.js
1913 lines (1680 loc) · 49.8 KB
/
portal.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
/*
* Portal v1.1.1
* http://flowersinthesand.github.io/portal/
*
* Copyright 2011-2014, Donghwan Kim
* Licensed under the Apache License, Version 2.0
* http://www.apache.org/licenses/LICENSE-2.0
*/
// Implement the Universal Module Definition (UMD) pattern
// see https://github.com/umdjs/umd/blob/master/returnExports.js
(function(root, factory) {
if (typeof define === "function" && define.amd) {
// AMD
define(function() {
return factory(root);
});
} else if (typeof exports === "object") {
// Node
module.exports = factory((function() {
// Prepare the window powered by jsdom
var window = require("jsdom").jsdom().createWindow();
window.WebSocket = require("ws");
window.EventSource = require("eventsource");
return window;
})());
// node-XMLHttpRequest 1.x conforms XMLHttpRequest Level 1 but can perform a cross-domain request
module.exports.support.corsable = true;
} else {
// Browser globals, Window
root.portal = factory(root);
}
}(this, function(window) {
// Enables ECMAScript 5′s strict mode
"use strict";
var // A global identifier
guid,
// Is the unload event being processed?
unloading,
// Portal
portal,
// Convenience utilities
support,
// Default options
defaults,
// Transports
transports,
// Socket instances
sockets = {},
// Callback names for JSONP
jsonpCallbacks = [],
// Core prototypes
toString = Object.prototype.toString,
hasOwn = Object.prototype.hasOwnProperty,
slice = Array.prototype.slice,
// Regard for Node since these are not defined
document = window.document,
location = window.location;
// Callback function
function callbacks(deferred) {
var locked,
memory,
firing,
firingStart,
firingLength,
firingIndex,
list = [],
fire = function(context, args) {
args = args || [];
memory = !deferred || [context, args];
firing = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
for (; firingIndex < firingLength && !locked; firingIndex++) {
list[firingIndex].apply(context, args);
}
firing = false;
},
self = {
add: function(fn) {
var length = list.length;
list.push(fn);
if (firing) {
firingLength = list.length;
} else if (!locked && memory && memory !== true) {
firingStart = length;
fire(memory[0], memory[1]);
}
},
remove: function(fn) {
var i;
for (i = 0; i < list.length; i++) {
if (fn === list[i] || (fn.guid && fn.guid === list[i].guid)) {
if (firing) {
if (i <= firingLength) {
firingLength--;
if (i <= firingIndex) {
firingIndex--;
}
}
}
list.splice(i--, 1);
}
}
},
fire: function(context, args) {
if (!locked && !firing && !(deferred && memory)) {
fire(context, args);
}
},
lock: function() {
locked = true;
},
locked: function() {
return !!locked;
},
unlock: function() {
locked = memory = firing = firingStart = firingLength = firingIndex = undefined;
}
};
return self;
}
// Socket function
function socket(url, options) {
var // Final options
opts,
// Transport
transport,
// The state of the connection
state,
// Reconnection
reconnectTimer,
reconnectDelay,
reconnectTry,
// Event helpers
events = {},
eventId = 0,
// Reply callbacks
replyCallbacks = {},
// Buffer
buffer = [],
// Map of the connection-scoped values
connection = {},
parts = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/.exec(url.toLowerCase()),
// Socket object
self = {
// Finds the value of an option
option: function(key) {
return opts[key];
},
// Gets or sets a connection-scoped value
data: function(key, value) {
if (value === undefined) {
return connection[key];
}
connection[key] = value;
return this;
},
// Returns the state
state: function() {
return state;
},
// Adds event handler
on: function(type, fn) {
var event;
// Handles a map of type and handler
if (typeof type === "object") {
for (event in type) {
self.on(event, type[event]);
}
return this;
}
// For custom event
event = events[type];
if (!event) {
if (events.message.locked()) {
return this;
}
event = events[type] = callbacks();
event.order = events.message.order;
}
event.add(fn);
return this;
},
// Removes event handler
off: function(type, fn) {
var event = events[type];
if (event) {
event.remove(fn);
}
return this;
},
// Adds one time event handler
one: function(type, fn) {
function proxy() {
self.off(type, proxy);
fn.apply(self, arguments);
}
fn.guid = fn.guid || guid++;
proxy.guid = fn.guid;
return self.on(type, proxy);
},
// Fires event handlers
fire: function(type) {
var event = events[type];
if (event) {
event.fire(self, slice.call(arguments, 1));
}
return this;
},
// Establishes a connection
open: function() {
var type,
latch,
connect = function() {
var candidates, type;
if (!latch) {
latch = true;
candidates = connection.candidates = slice.call(opts.transports);
while (!transport && candidates.length) {
type = candidates.shift();
connection.transport = type;
connection.url = self.buildURL("open");
transport = transports[type](self, opts);
}
// Increases the number of reconnection attempts
if (reconnectTry) {
reconnectTry++;
}
// Fires the connecting event and connects
if (transport) {
self.fire("connecting");
transport.open();
} else {
self.fire("close", "notransport");
}
}
},
cancel = function() {
if (!latch) {
latch = true;
self.fire("close", "canceled");
}
};
// Cancels the scheduled connection
if (reconnectTimer) {
clearTimeout(reconnectTimer);
}
// Resets the connection scope and event helpers
connection = {};
for (type in events) {
events[type].unlock();
}
// Chooses transport
transport = undefined;
// From null or waiting state
state = "preparing";
// Check if possible to make use of a shared socket
if (opts.sharing) {
connection.transport = "session";
transport = transports.session(self, opts);
}
// Executes the prepare handler if a physical connection is needed
if (transport) {
connect();
} else {
opts.prepare.call(self, connect, cancel, opts);
}
return this;
},
// Sends an event to the server via the connection
send: function(type, data, doneCallback, failCallback) {
var event;
// Defers sending an event until the state become opened
if (state !== "opened") {
buffer.push(arguments);
return this;
}
// Outbound event
event = {
id: ++eventId,
socket: opts.id,
type: type,
data: data,
reply: !!(doneCallback || failCallback)
};
if (event.reply) {
// Shared socket needs to know the callback event name
// because it fires the callback event directly instead of using reply event
if (connection.transport === "session") {
event.doneCallback = doneCallback;
event.failCallback = failCallback;
} else {
replyCallbacks[eventId] = {done: doneCallback, fail: failCallback};
}
}
// Delegates to the transport
transport.send(support.isBinary(data) ? data : opts.outbound.call(self, event));
return this;
},
// Disconnects the connection
close: function() {
var script, head;
// Prevents reconnection
opts.reconnect = false;
if (reconnectTimer) {
clearTimeout(reconnectTimer);
}
// Fires the close event immediately for transport which doesn't give feedback on disconnection
if (unloading || !transport || !transport.feedback) {
self.fire("close", unloading ? "error" : "aborted");
if (opts.notifyAbort && connection.transport !== "session") {
head = document.head || document.getElementsByTagName("head")[0] || document.documentElement;
script = document.createElement("script");
script.async = false;
script.src = self.buildURL("abort");
script.onload = script.onreadystatechange = function() {
if (!script.readyState || /loaded|complete/.test(script.readyState)) {
script.onload = script.onreadystatechange = null;
if (script.parentNode) {
script.parentNode.removeChild(script);
}
}
};
head.insertBefore(script, head.firstChild);
}
}
// Delegates to the transport
if (transport) {
transport.close();
}
return this;
},
// Broadcasts event to session sockets
broadcast: function(type, data) {
// TODO rename
var broadcastable = connection.broadcastable;
if (broadcastable) {
broadcastable.broadcast({type: "fire", data: {type: type, data: data}});
}
return this;
},
// For internal use only
// fires events from the server
_fire: function(data, isChunk) {
var array;
if (isChunk) {
data = opts.streamParser.call(self, data);
while (data.length) {
self._fire(data.shift());
}
return this;
}
if (support.isBinary(data)) {
array = [{type: "message", data: data}];
} else {
array = opts.inbound.call(self, data);
array = array == null ? [] : !support.isArray(array) ? [array] : array;
}
connection.lastEventIds = [];
support.each(array, function(i, event) {
var latch, args = [event.type, event.data];
opts.lastEventId = event.id;
connection.lastEventIds.push(event.id);
if (event.reply) {
args.push(function(result) {
if (!latch) {
latch = true;
self.send("reply", {id: event.id, data: result});
}
});
}
self.fire.apply(self, args).fire("_message", args);
});
return this;
},
// For internal use only
// builds an effective URL
buildURL: function(when, params) {
var p = when === "open" ?
{
transport: connection.transport,
heartbeat: opts.heartbeat,
lastEventId: opts.lastEventId
} :
when === "poll" ?
{
transport: connection.transport,
lastEventIds: connection.lastEventIds && connection.lastEventIds.join(","),
/* deprecated */lastEventId: opts.lastEventId
} :
{};
support.extend(p, {id: opts.id, _: guid++}, opts.params && opts.params[when], params);
return opts.urlBuilder.call(self, url, p, when);
}
};
// Create the final options
opts = support.extend({}, defaults, options);
if (options) {
// Array should not be deep extended
if (options.transports) {
opts.transports = slice.call(options.transports);
}
}
// Saves original URL
opts.url = url;
// Generates socket id,
opts.id = opts.idGenerator.call(self);
opts.crossDomain = !!(parts &&
// protocol and hostname
(parts[1] != location.protocol || parts[2] != location.hostname ||
// port
(parts[3] || (parts[1] === "http:" ? 80 : 443)) != (location.port || (location.protocol === "http:" ? 80 : 443))));
support.each(["connecting", "open", "message", "close", "waiting"], function(i, type) {
// Creates event helper
events[type] = callbacks(type !== "message");
events[type].order = i;
// Shortcuts for on method
var old = self[type],
on = function(fn) {
return self.on(type, fn);
};
self[type] = !old ? on : function(fn) {
return (support.isFunction(fn) ? on : old).apply(this, arguments);
};
});
// Initializes
self.on({
connecting: function() {
// From preparing state
state = "connecting";
var timeoutTimer;
// Sets timeout timer
function setTimeoutTimer() {
timeoutTimer = setTimeout(function() {
transport.close();
self.fire("close", "timeout");
}, opts.timeout);
}
// Clears timeout timer
function clearTimeoutTimer() {
clearTimeout(timeoutTimer);
}
// Makes the socket sharable
function share() {
var traceTimer,
server,
name = "socket-" + url,
servers = {
// Powered by the storage event and the localStorage
// http://www.w3.org/TR/webstorage/#event-storage
storage: function() {
// The storage event of Internet Explorer works strangely
// TODO test Internet Explorer 11
if (support.browser.msie) {
return;
}
var storage = window.localStorage;
return {
init: function() {
function onstorage(event) {
// When a deletion, newValue initialized to null
if (event.key === name && event.newValue) {
listener(event.newValue);
}
}
// Handles the storage event
support.on(window, "storage", onstorage);
self.one("close", function() {
support.off(window, "storage", onstorage);
// Defers again to clean the storage
self.one("close", function() {
storage.removeItem(name);
storage.removeItem(name + "-opened");
storage.removeItem(name + "-children");
});
});
},
broadcast: function(obj) {
var string = support.stringifyJSON(obj);
storage.setItem(name, string);
setTimeout(function() {
listener(string);
}, 50);
},
get: function(key) {
return support.parseJSON(storage.getItem(name + "-" + key));
},
set: function(key, value) {
storage.setItem(name + "-" + key, support.stringifyJSON(value));
}
};
},
// Powered by the window.open method
// https://developer.mozilla.org/en/DOM/window.open
windowref: function() {
// Internet Explorer raises an invalid argument error
// when calling the window.open method with the name containing non-word characters
var neim = name.replace(/\W/g, ""),
container = document.getElementById(neim),
win;
if (!container) {
container = document.createElement("div");
container.id = neim;
container.style.display = "none";
container.innerHTML = '<iframe name="' + neim + '" />';
document.body.appendChild(container);
}
win = container.firstChild.contentWindow;
return {
init: function() {
// Callbacks from different windows
win.callbacks = [listener];
// In Internet Explorer 8 and less, only string argument can be safely passed to the function in other window
win.fire = function(string) {
var i;
for (i = 0; i < win.callbacks.length; i++) {
win.callbacks[i](string);
}
};
},
broadcast: function(obj) {
if (!win.closed && win.fire) {
win.fire(support.stringifyJSON(obj));
}
},
get: function(key) {
return !win.closed ? win[key] : null;
},
set: function(key, value) {
if (!win.closed) {
win[key] = value;
}
}
};
}
};
// Receives send and close command from the children
function listener(string) {
var command = support.parseJSON(string), data = command.data;
if (!command.target) {
if (command.type === "fire") {
self.fire(data.type, data.data);
}
} else if (command.target === "p") {
switch (command.type) {
case "send":
self.send(data.type, data.data, data.doneCallback, data.failCallback);
break;
case "close":
self.close();
break;
}
}
}
function propagateMessageEvent(args) {
server.broadcast({target: "c", type: "message", data: args});
}
function leaveTrace() {
document.cookie = encodeURIComponent(name) + "=" +
encodeURIComponent(support.stringifyJSON({ts: support.now(), heir: (server.get("children") || [])[0]})) +
"; path=/";
}
// Chooses a server
server = servers.storage() || servers.windowref();
server.init();
// For broadcast method
connection.broadcastable = server;
// List of children sockets
server.set("children", []);
// Flag indicating the parent socket is opened
server.set("opened", false);
// Leaves traces
leaveTrace();
traceTimer = setInterval(leaveTrace, 1000);
self.on("_message", propagateMessageEvent)
.one("open", function() {
server.set("opened", true);
server.broadcast({target: "c", type: "open"});
})
.one("close", function(reason) {
// Clears trace timer
clearInterval(traceTimer);
// Removes the trace
document.cookie = encodeURIComponent(name) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";
// The heir is the parent unless unloading
server.broadcast({target: "c", type: "close", data: {reason: reason, heir: !unloading ? opts.id : (server.get("children") || [])[0]}});
self.off("_message", propagateMessageEvent);
});
}
if (opts.timeout > 0) {
setTimeoutTimer();
self.one("open", clearTimeoutTimer).one("close", clearTimeoutTimer);
}
// Share the socket if possible
if (opts.sharing && connection.transport !== "session") {
share();
}
},
open: function() {
// From connecting state
state = "opened";
var heartbeatTimer;
// Sets heartbeat timer
function setHeartbeatTimer() {
heartbeatTimer = setTimeout(function() {
self.send("heartbeat").one("heartbeat", function() {
clearHeartbeatTimer();
setHeartbeatTimer();
});
heartbeatTimer = setTimeout(function() {
transport.close();
self.fire("close", "error");
}, opts._heartbeat);
}, opts.heartbeat - opts._heartbeat);
}
// Clears heartbeat timer
function clearHeartbeatTimer() {
clearTimeout(heartbeatTimer);
}
if (opts.heartbeat > opts._heartbeat) {
setHeartbeatTimer();
self.one("close", clearHeartbeatTimer);
}
// Locks the connecting event
events.connecting.lock();
// Initializes variables related with reconnection
reconnectTimer = reconnectDelay = reconnectTry = null;
// Flushes buffer
while (buffer.length) {
self.send.apply(self, buffer.shift());
}
},
close: function() {
// From preparing, connecting, or opened state
state = "closed";
var type, event, order = events.close.order;
// Locks event whose order is lower than close event
for (type in events) {
event = events[type];
if (event.order < order) {
event.lock();
}
}
// Schedules reconnection
if (opts.reconnect) {
self.one("close", function() {
reconnectTry = reconnectTry || 1;
reconnectDelay = opts.reconnect.call(self, reconnectDelay, reconnectTry);
if (reconnectDelay !== false) {
reconnectTimer = setTimeout(function() {
self.open();
}, reconnectDelay);
self.fire("waiting", reconnectDelay, reconnectTry);
}
});
}
},
waiting: function() {
// From closed state
state = "waiting";
},
reply: function(reply) {
var fn,
id = reply.id,
data = reply.data,
exception = reply.exception,
callback = replyCallbacks[id];
if (callback) {
fn = exception ? callback.fail : callback.done;
if (fn) {
if (support.isFunction(fn)) {
fn.call(self, data);
} else {
self.fire(fn, data).fire("_message", [fn, data]);
}
delete replyCallbacks[id];
}
}
}
});
return self.open();
}
// Defines the portal
portal = {
// Creates a new socket and connects to the given url
open: function(url, options) {
// Makes url absolute to normalize URL
url = support.getAbsoluteURL(url);
sockets[url] = socket(url, options);
return portal.find(url);
},
// Finds the socket object which is mapped to the given url
find: function(url) {
var i;
// Returns the first socket in the document
if (!arguments.length) {
for (i in sockets) {
if (sockets[i]) {
return sockets[i];
}
}
return null;
}
// The url is a identifier of this socket within the document
return sockets[support.getAbsoluteURL(url)] || null;
},
// Closes all sockets
finalize: function() {
var url, socket;
for (url in sockets) {
socket = sockets[url];
if (socket.state() !== "closed") {
socket.close();
}
// To run the test suite
delete sockets[url];
}
}
};
// Most utility functions are borrowed from jQuery
portal.support = support = {
now: function() {
return new Date().getTime();
},
isArray: function(array) {
return toString.call(array) === "[object Array]";
},
isBinary: function(data) {
// True if data is an instance of Blob, ArrayBuffer or ArrayBufferView
return (/^\[object\s(?:Blob|ArrayBuffer|.+Array)\]$/).test(toString.call(data));
},
isFunction: function(fn) {
return toString.call(fn) === "[object Function]";
},
getAbsoluteURL: function(url) {
var div = document.createElement("div");
// Uses an innerHTML property to obtain an absolute URL
div.innerHTML = '<a href="' + url + '"/>';
// encodeURI and decodeURI are needed to normalize URL between Internet Explorer and non-Internet Explorer,
// since Internet Explorer doesn't encode the href property value and return it - http://jsfiddle.net/Yq9M8/1/
return encodeURI(decodeURI(div.firstChild.href));
},
each: function(array, callback) {
var i;
for (i = 0; i < array.length; i++) {
callback(i, array[i]);
}
},
extend: function(target) {
var i, options, name;
for (i = 1; i < arguments.length; i++) {
if ((options = arguments[i]) != null) {
for (name in options) {
target[name] = options[name];
}
}
}
return target;
},
on: function(elem, type, fn) {
if (elem.addEventListener) {
elem.addEventListener(type, fn, false);
} else if (elem.attachEvent) {
elem.attachEvent("on" + type, fn);
}
},
off: function(elem, type, fn) {
if (elem.removeEventListener) {
elem.removeEventListener(type, fn, false);
} else if (elem.detachEvent) {
elem.detachEvent("on" + type, fn);
}
},
param: function(params) {
var prefix, s = [];
function add(key, value) {
value = support.isFunction(value) ? value() : (value == null ? "" : value);
s.push(encodeURIComponent(key) + "=" + encodeURIComponent(value));
}
function buildParams(prefix, obj) {
var name;
if (support.isArray(obj)) {
support.each(obj, function(i, v) {
if (/\[\]$/.test(prefix)) {
add(prefix, v);
} else {
buildParams(prefix + "[" + (typeof v === "object" ? i : "") + "]", v);
}
});
} else if (obj != null && toString.call(obj) === "[object Object]") {
for (name in obj) {
buildParams(prefix + "[" + name + "]", obj[name]);
}
} else {
add(prefix, obj);
}
}
for (prefix in params) {
buildParams(prefix, params[prefix]);
}
return s.join("&").replace(/%20/g, "+");
},
xhr: function() {
try {
return new window.XMLHttpRequest();
} catch (e1) {
try {
return new window.ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {}
}
},
parseJSON: function(data) {
return !data ?
null :
window.JSON && window.JSON.parse ?
window.JSON.parse(data) :
Function("return " + data)();
},
// http://github.com/flowersinthesand/stringifyJSON
stringifyJSON: function(value) {
var escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
meta = {
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"': '\\"',
'\\': '\\\\'
};
function quote(string) {
return '"' + string.replace(escapable, function(a) {
var c = meta[a];
return typeof c === "string" ? c : "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4);
}) + '"';
}
function f(n) {
return n < 10 ? "0" + n : n;
}
return window.JSON && window.JSON.stringify ?
window.JSON.stringify(value) :
(function str(key, holder) {
var i, v, len, partial, value = holder[key], type = typeof value;
if (value && typeof value === "object" && typeof value.toJSON === "function") {
value = value.toJSON(key);
type = typeof value;
}
switch (type) {
case "string":
return quote(value);
case "number":
return isFinite(value) ? String(value) : "null";
case "boolean":
return String(value);
case "object":
if (!value) {
return "null";
}
switch (toString.call(value)) {
case "[object Date]":
return isFinite(value.valueOf()) ?
'"' + value.getUTCFullYear() + "-" + f(value.getUTCMonth() + 1) + "-" + f(value.getUTCDate()) +
"T" + f(value.getUTCHours()) + ":" + f(value.getUTCMinutes()) + ":" + f(value.getUTCSeconds()) + "Z" + '"' :
"null";
case "[object Array]":
len = value.length;
partial = [];
for (i = 0; i < len; i++) {
partial.push(str(i, value) || "null");
}
return "[" + partial.join(",") + "]";
default:
partial = [];
for (i in value) {
if (hasOwn.call(value, i)) {
v = str(i, value);
if (v) {
partial.push(quote(i) + ":" + v);
}
}
}
return "{" + partial.join(",") + "}";
}
}