-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcore.js
1473 lines (1255 loc) · 41.3 KB
/
core.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
/**
* @file
* @summary Useful to prevent a badly behaved prod application from pissing its guts out.
* Otherwise, you really shouldn't have console calls in your code...
*
* @author WebItUp
* @version 0.4.0
*
* @license <a href="http://www.gnu.org/licenses/agpl-3.0.html">AGPL</a>.
* @copyright All rights reserved <a href="http://www.webitup.fr">copyright WebItUp</a>
* @name https://github.com/jsBoot/jsboot.js/blob/master/src/jsboot/core/errorHandler.js#74-70c39446998be95596b03bc170b23bba337ce8b4
*/
/*global console*/
jsBoot.add(console).as('nativeConsole');
jsBoot.pack('jsBoot.core', function(api) {
'use strict';
var fakeConsole = {
debug: function() {},
log: function() {},
info: function() {},
trace: function() {},
warn: console.warn,
error: console.error
};
this.toggleConsole = function(on) {
var mesh = on ? api.nativeConsole : fakeConsole;
Object.getOwnPropertyNames(mesh).forEach(function(i) {
console[i] = mesh[i];
});
};
});
/**
* The overloaded Error object has an additional (array) member "stack".
* If there is a printStackTrace method available in the scope at the moment the Error is built,
* it will evalute that method - [] otherwise.
*
* @file
* @summary An enhanced Error object with stacktrace.
*
* @author WebItUp
* @version 0.4.0
*
* @license <a href="http://www.gnu.org/licenses/agpl-3.0.html">AGPL</a>.
* @copyright All rights reserved <a href="http://www.webitup.fr">copyright WebItUp</a>
* @name https://github.com/jsBoot/jsboot.js/blob/master/src/jsboot/core/error.js#74-70c39446998be95596b03bc170b23bba337ce8b4
* @see http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/
* @see http://stackoverflow.com/questions/332422/how-do-i-get-the-name-of-an-objects-type-in-javascript
*/
/*global Error, window, printStackTrace*/
jsBoot.add(Error).as('NativeError');
jsBoot.pack('jsBoot.core', function(api) {
'use strict';
// Possibly pb related to X-Domain limitation shit
this.Error = function(name, message) {
// Error behavior is strange...
var b = api.NativeError.apply(this, [message]);
// Not too sure this leads anywhere safe though (google code fux...)
if ((this == window) || (this === undefined))
return;
this.message = b.message;
this.stack = b.stack;
this.name = name;
if (!this.stack)
this.stack = (typeof printStackTrace != 'undefined') ? printStackTrace() : [];
};
Object.getOwnPropertyNames(api.NativeError.prototype).forEach(function(i) {
if (i != 'constructor')
this.Error.prototype[i] = api.NativeError.prototype[i];
}, this);
['NOT_IMPLEMENTED', 'UNSPECIFIED', 'NOT_INITIALIZED', 'WRONG_ARGUMENTS',
'UNSUPPORTED', 'NATURAL_BORN_CRASH'].forEach(function(item, idx) {
this.Error[item] = this.Error.prototype[item] = idx;
}, this);
this.Error.prototype.toString = function() {
return this.name + ': ' + this.message + '\nStack: ' +
((typeof this.stack == 'array') ? this.stack.join('\n') : this.stack);
};
});
/**
* @namespace
* @name jsBoot
*/
/**
* @namespace
* @name jsBoot.core
*/
/**
* @class
* @name jsBoot.core.Error
*/
/**
* Just in case you are too lazy to define errors yourself, use this hodge pot here... NOT recommended.
* @property
* @static
* @constant
* @name jsBoot.core.Error.UNSPECIFIED
*/
/**
* Use this in a method that explicitely wants to say implementation is missing (in a virtual for eg.)
* @property
* @static
* @constant
* @name jsBoot.core.Error.NOT_IMPLEMENTED
*/
/**
* Meant to say that something has not been properly inited before being used
* @property
* @static
* @constant
* @name jsBoot.core.Error.NOT_INITIALIZED
*/
/**
* Use this if you do validate arguments, and what's passed doesn't cut it
* @property
* @static
* @constant
* @name jsBoot.core.Error.WRONG_ARGUMENTS
*/
/**
* Use this in factories for example, where the arguments ask for something that's not doable.
* @property
* @static
* @constant
* @name jsBoot.core.Error.UNSUPPORTED
*/
/**
* Interecepted throw that gets respoofed into the list.
* @property
* @static
* @constant
* @name jsBoot.core.Error.NATURAL_BORN_CRASH
*/
/**
* Provides a simple declarative mechanism to get hooked onto exceptions
*
* @file
* @summary Mechanism to catch exceptions.
*
* @author WebItUp
* @version 0.4.0
*
* @license <a href="http://www.gnu.org/licenses/agpl-3.0.html">AGPL</a>.
* @copyright All rights reserved <a href="http://www.webitup.fr">copyright WebItUp</a>
* @name https://github.com/jsBoot/jsboot.js/blob/master/src/jsboot/core/errorHandler.js#74-70c39446998be95596b03bc170b23bba337ce8b4
*/
jsBoot.pack('jsBoot.core', function() {
/*global window, console*/
'use strict';
// Consumer may register an handler instead of the dumb one
/**
* Call this declare a callback for exceptions
* @summary
* @function
* @name jsBoot.core.registerErrorHandler
* @param {Function} hnd Callback to be notified of exceptions.
* @returns undefined
*/
this.registerErrorHandler = function(hnd) {
handlers.push(hnd);
};
var handlers = [];
if (window.onerror)
handlers.push(window.onerror);
var err = function(message, ex) {
console.error(' [jsBoot.core.errorHandler]', message, ex);
};
window.onerror = function(e) {
var args = Array.prototype.slice.call(arguments);
try {
return handlers.some(function(item) {
return item.apply(null, args);
});
}catch (ed) {
err('Some error handler shamefully failed to do anything useful because of', ed);
err('"Lost" error was:', e);
}
};
});
/**
* @namespace Errors spat by eventDispatchers
* @name Roxee.gist.errors.eventDispatcher
*/
/**
* A listener failed during execution.
* @memberof Roxee.gist.errors.eventDispatcher
* @property
* @type {String}
* @constant
* @name LISTENER_FAILURE
*/
jsBoot.add(1).as('delay');
jsBoot.pack('jsBoot.types', function(api) {
/*jshint browser:true*/
'use strict';
// A simple event emitter, supporting coalesce and asynchronous dispatching
this.EventDispatcher = function() {
// Useful while debugging (will CRASH AND STOP dispatching on the first failing listener)
this.crash = false;
this.addEventListener = function(type, listener, context, throwable) {
if (!(type in listeners)) {
listeners[type] = [];
queue[type] = [];
}
// Bind the listener onto the desired execution context
var l = listener.bind(context);
l.throwable = !!throwable;
l.bound = listener;
l.context = context;
listeners[type].push(l);
};
// BEWARE keeping references to inactive objects will prevent needed GC... This is no *weak* ref.
// XXX untested code
this.removeEventListener = function(type, listener, context) {
if (!(type in listeners))
return;
listeners[type].some(function(l, x) {
if ((listener == l.bound) && (context == l.context))
listeners[type].splice(x, 1);
});
// for (var x = 0, l; (x < listeners[type].length) && (l = listeners[type][x]); x++)
// if ((listener == l.bound) && (context == l.context)) {
// listeners[type].splice(x, 1);
// return;
// }
};
this.dispatchEvent = function(type, details, synchronous) {
// Only dispatch if there is something to listen, or if this is a change event and there is a mutation listener
if (!((type in listeners) || (type == this.CHANGE && ((BEFORE_MUTATION in listeners) ||
(AFTER_MUTATION in listeners)))))
return;
// Cancel any previous running coalesce
if (type in tout)
clearTimeout(tout[type]);
// Queue-up the details for the event to dispatch
if (!(type in queue))
queue[type] = [];
queue[type].push(details);
// If it's asynchronous, set timeout delay already
if (!synchronous)
tout[type] = setTimeout(handleQueue, api.delay, type, this);
else
handleQueue(type);
};
// Private var to hold listeners for given types
var listeners = {};
// Private var to hold timeout references for asynchronous dispatching
var tout = {};
// Queue, to hold coalescable events
var queue = {};
this.destroy = function() {
Object.keys(tout).forEach(function(type) {
clearTimeout(tout[type]);
});
// for (var type in tout) {
// if (tout.hasOwnProperty(type))
// clearTimeout(tout[type]);
// }
queue = {};
tout = {};
listeners = {};
};
var handleQueue = (function(type, target) {
// If that was asynchronous, clear-up the timeout now
if (type in tout)
delete tout[type];
// Change event may dispatch additional before and after mutation
if ((type == CHANGE) && (BEFORE_MUTATION in listeners))
listeners[BEFORE_MUTATION] = doHandle(listeners[BEFORE_MUTATION], target, BEFORE_MUTATION, {},
'A before mutation event listener failed', this.crash);
// For each event in the queue to be dispatched
if (type in listeners)
queue[type].forEach(function(details) {
listeners[type] = doHandle(listeners[type], target, type, details, 'An event listener failed', this.crash);
}, this);
// Empty queue now
queue[type].splice(0, queue[type].length);
// Change event may dispatch additional before and after mutation
if ((type == CHANGE) && (AFTER_MUTATION in listeners))
listeners[AFTER_MUTATION] = doHandle(listeners[AFTER_MUTATION], target, AFTER_MUTATION, {},
'An after mutation event listener failed', this.crash);
}.bind(this));
};
// Dispatched when a batch of changes are handled
var BEFORE_MUTATION = this.EventDispatcher.prototype.BEFORE_MUTATION = 'changestart';
// Might be used to notify something changed in the object
var CHANGE = this.EventDispatcher.prototype.CHANGE = 'change';
// Dispatched when a batch of changes ends
var AFTER_MUTATION = this.EventDispatcher.prototype.AFTER_MUTATION = 'changestop';
// Static helper function
var doHandle = function(listeners, target, type, details, mumble, crash) {
// XXX Right now, result is not handled - provisional for cancelling / holding stuff
var result = false;
var eve = {
type: type,
target: target,
details: details
};
var defThrow = [];
var ret = listeners.filter(function(listener) {
if (crash) {
result |= listener(eve);
}else {
try {
result |= listener(eve);
}catch (e) {
defThrow.push(new jsBoot.core.Error('LISTENER_FAILURE', mumble + ':' + e));
}
}
return !listener.throwable;
});
// Throw no matter what - the crash thing is cool to stop the flow at the first error,
// but production code HAS to report failures
if (defThrow.length)
throw defThrow.shift();
return ret;
};
});
jsBoot.use('jsBoot.types.EventDispatcher').as('dispatcher');
// An object that when mutating (eg: via a call to the change method) will dispatch a change event
jsBoot.pack('jsBoot.types', function(api) {
/*global Ember*/
'use strict';
// XXX clarify this shit
// XXX What's wrong with Ember.Object.prototype?
this.Mutable = function() {
if (typeof Ember != 'undefined') {
var em = new Ember.Object();
for (var i in em) {
if (i != 'constructor' && i != 'set')
this[i] = em[i];
}
}
api.dispatcher.apply(this);
};
this.Mutable.prototype = Object.create(api.dispatcher.prototype);
// XXX The persistence of "change" is only here for Roxee backward compat
this.Mutable.prototype.set = this.Mutable.prototype.change = function(key, value) {
var ov = (typeof Ember != 'undefined') ? this.get(key) : this[key];
if (value == ov)
return;
this.dispatchEvent(this.CHANGE, {key: key, oldValue: ov, newValue: value});
if (typeof Ember != 'undefined') {
Ember.set(this, key, value);
}else {
this[key] = value;
}
};
// Should not be constructed before the store is ready
/*
this.StoreMutable = function(storeObject){
this.Mutable.apply(this);
Object.keys(storeObject).forEach(function(key){
// XXX miss typage instanciation
this[key] = storeObject[key];
}, this);
// Should save on user-idle, or on logout / shutdown
this.addEventListener(this.AFTER_MUTATION, function(){
// Reset / repopulate store object
Object.keys(storeObject).forEach(function(key){
// XXX miss typage serialization
if(key in this)
storeObject[key] = this[key];
else
delete storeObject[key];
});
}, this);
};
StoreMutable.prototype = Object.create(Mutable.prototype);
*/
});
/*
var des = function(valuesHolder){
};
return {
toto: {
enumerable: true,
configurable: false,
writable: true,
value: 'whatever'
},
titi: {
enumerable: true,
configurable: false,
value: 'toto',
parse: function(value){
return 'parse: ' + value;
},
serialize: function(value){
return 'serialize: ' + value;
}
}
};
var TypedMutable = function(descriptor){
var proxy = Object.create({}, descriptor);
Object.keys(descriptor).forEach(function(key){
Object.defineProperty(this, key, {
enumerable: descriptor[key].enumerable,
configurable: true,
get: function(){
if(descriptor[key].parse){
return descriptor[key].parse(proxy[key]);
return proxy[key];
},
set: descriptor[key].writable ? function(value){
if(descriptor[key].serialize){
proxy[key] = descriptor[key].serialize(value);
return;
}
switch(typeof descriptor[key].value){
case 'number':
proxy[key] = parseInt(value, 10);
break;
case 'boolean':
proxy[key] = !!value;
break;
case 'string':
proxy[key] = '' + value;
break;
case 'object':
// XXX code injection risk?
proxy[key] = value; // Object.create({}, value);
break;
case 'function':
// Custom filtering method
}
} : undefined
});
}, this);
};
var a1 = new TypedMutable(des);
var a2 = new TypedMutable(des);
// throw "toto"
*/
/*
jsBoot.use('jsBoot.types.Mutable');
jsBoot.pack('jsBoot.types', function(api) {
'use strict';
this.TypedMutable = function(descriptor, initialMesh) {
api.Mutable.apply(this);
this.isTyped = true;
var privatePool = {};
var lastMesh = {};
Object.keys(descriptor).forEach(function(i) {
var item = descriptor[i];
switch (typeof item) {
case 'number':
this[i] = parseInt(item, 10);
break;
case 'boolean':
this[i] = (item == 'true');
break;
case 'string':
this[i] = '' + item;
break;
case 'object':
// May be null, an array, or an object-object
this[i] = item;
break;
case 'function':
Object.defineProperty(this, i, {
enumerable: true,
configurable: true,
get: function() {
// XXX super dirty and dangerous - cause of the bind
// Verify this in IE and other non-bindable browsers
if (item.isDirty || item.constructor != Function)
return item(lastMesh[i]);
else {
if (typeof privatePool[i] == 'undefined') {
privatePool[i] = new item(lastMesh[i] || null);
}
return privatePool[i];
}
},
set: function(value) {
privatePool[i] = value;
// XXX dirty trix to let polymorph descriptors do whatever job need be be done
if (item.isDirty)
privatePool[i] = item(value);
}
});
break;
}
}, this);
this.free = function() {
privatePool = {};
};
this.toObject = function() {
var ret = {};
Object.keys(descriptor).forEach(function(i) {
ret[i] = (!!this[i] && (typeof this[i] == 'object') && ('toObject' in this[i])) ? this[i].toObject() : this[i];
}, this);
return ret;
};
this.fromObject = function(networkMesh) {
if (typeof networkMesh != 'object')
networkMesh = {id: networkMesh};
Object.keys(networkMesh).forEach(function(i) {
if (!(i in descriptor))
return;
var item = networkMesh[i];
switch (typeof descriptor[i]) {
case 'number':
this.set(i, parseInt(item, 10));
break;
case 'boolean':
this.set(i, (item == 'true'));
break;
case 'string':
this.set(i, '' + item);
break;
case 'object':
// May be null, an array, or an object-object
this.set(i, item);
break;
case 'function':
if (typeof privatePool[i] != 'undefined') {
if (descriptor[i].constructor == Function) {
if (!!privatePool[i]) {
privatePool[i].fromObject(networkMesh[i]);
}else {
lastMesh[i] = networkMesh[i];
}
}else
this.set(i, descriptor[i](networkMesh[i]));
}else
// Merge and override lastMesh otherwise, to be used for later construction
lastMesh[i] = networkMesh[i];
// if(typeof privatePool[i] != 'undefined')
// if('fromObject' in privatePool[i])
// privatePool[i].fromObject(networkMesh[i]);
// else
// this.set(i, descriptor[i](networkMesh[i]));
// else
// // Merge and override lastMesh otherwise, to be used for later construction
// lastMesh[i] = networkMesh[i];
break;
default:
this.set(i, item);
throw new Error('UNTYPED_MESH', 'Mesh is not typed properly ' + i + ' ' + descriptor[i] + ' ' + item);
}
}, this);
};
if (initialMesh)
this.fromObject(initialMesh);
};
});
*/
/**
* User activity controller that dispatch changes (blur, idle, active).
*
* @file
* @summary User activity helper.
*
* @author WebItUp
* @version 0.4.0
*
* @license <a href="http://www.gnu.org/licenses/agpl-3.0.html">AGPL</a>.
* @copyright All rights reserved <a href="http://www.webitup.fr">copyright WebItUp</a>
* @name https://github.com/jsBoot/jsboot.js/blob/master/src/jsboot/controllers/idle.js#74-70c39446998be95596b03bc170b23bba337ce8b4
*/
/*jshint browser:true*/
jsBoot.use('jsBoot.types.EventDispatcher');
jsBoot.add(500).as('idleTime');
jsBoot.add(5000).as('staleTime');
jsBoot.pack('jsBoot.controllers', function(api) {
'use strict';
var STATE_CHANGED = 'STATE_CHANGED';
var ACTIVE = 'ACTIVE';
var IDLE = 'IDLE';
var BLURRED = 'BLURRED';
var UserActivityController = function() {
// We are an event dispatcher
api.EventDispatcher.apply(this);
var idleInterval;
var lastActive = Date.now();
var lastState = IDLE;
var staled = false;
Object.defineProperty(this, 'status', {
get: function() {
return lastState;
}
});
Object.defineProperty(this, 'staled', {
get: function() {
return staled;
}
});
var checkState = (function() {
if (lastState == ACTIVE) {
if ((Date.now() - lastActive) > api.idleTime) {
lastState = IDLE;
this.dispatchEvent(STATE_CHANGED);
}
}else if (!staled) {
if ((Date.now() - lastActive) > api.staleTime) {
staled = true;
this.dispatchEvent(STATE_CHANGED);
}
}
}.bind(this));
var isActive = (function(/*e*/) {
if (lastState == BLURRED)
return;
lastActive = Date.now();
if (lastState == IDLE) {
lastState = ACTIVE;
staled = false;
this.dispatchEvent(STATE_CHANGED);
}
}.bind(this));
var isBlur = (function() {
lastState = BLURRED;
this.dispatchEvent(STATE_CHANGED);
}.bind(this));
var isFocus = (function() {
lastActive = Date.now();
lastState = ACTIVE;
staled = false;
this.dispatchEvent(STATE_CHANGED);
}.bind(this));
this.boot = function(time, staleTime) {
// Allow override of the default time
if (time)
api.idleTime = time * 1000;
if (staleTime)
api.staleTime = staleTime * 1000;
// Idling support
document.addEventListener('mousemove', isActive, true);
document.addEventListener('click', isActive, true);
document.addEventListener('dblclick', isActive, true);
window.addEventListener('keypress', isActive, true);
window.addEventListener('blur', isBlur, true);
window.addEventListener('focus', isFocus, true);
idleInterval = setInterval(checkState, api.idleTime / 2);
};
this.shutdown = function() {
// Kill all refs to listeners
this.destroy();
clearInterval(idleInterval);
// Idling support
document.removeEventListener('mousemove', isActive, true);
document.removeEventListener('click', isActive, true);
document.removeEventListener('dblclick', isActive, true);
window.removeEventListener('keypress', isActive, true);
window.removeEventListener('blur', isBlur, true);
window.removeEventListener('focus', isFocus, true);
};
};
UserActivityController.prototype = Object.create(api.EventDispatcher.prototype, {
STATE_CHANGED: {value: STATE_CHANGED, writable: false, enumerable: true},
ACTIVE: {value: ACTIVE, writable: false, enumerable: true},
IDLE: {value: IDLE, writable: false, enumerable: true},
BLURRED: {value: BLURRED, writable: false, enumerable: true}
});
this.userActivity = new UserActivityController();
});
/**
* Single app helper.
*
* @file
* @summary Single app helper.
*
* @author WebItUp
* @version 0.4.0
*
* @license <a href="http://www.gnu.org/licenses/agpl-3.0.html">AGPL</a>.
* @copyright All rights reserved <a href="http://www.webitup.fr">copyright WebItUp</a>
* @name https://github.com/jsBoot/jsboot.js/blob/master/src/jsboot/controllers/singleapp.js#74-70c39446998be95596b03bc170b23bba337ce8b4
*/
/*jshint browser:true*/
jsBoot.add(window.localStorage).as('localStorage');
jsBoot.add(window.sessionStorage).as('sessionStorage');
// Lifetime of a (stale) lock, before aquiring
jsBoot.add(1000).as('lifeLength');
jsBoot.use('jsBoot.types.EventDispatcher');
jsBoot.use('jsBoot.core.Error');
jsBoot.pack('jsBoot.controllers', function(api) {
'use strict';
// Trivial low level helpers
var getId = function(name) {
var id;
// No session storage means we won't persist over reloads
if (api.sessionStorage)
id = api.sessionStorage.getItem('_jsbootsingleapp_' + name + '_instanceId');
if (!id) {
id = Date.now() + '-' + Math.random(1000);
if (api.sessionStorage)
api.sessionStorage.setItem('_jsbootsingleapp_' + name + '_instanceId', id);
}
return id;
};
var read = function(name) {
return (api.localStorage.getItem('_jsbootsingleapp_' + name + '_lockname') || '').split('_');
};
var write = function(name, d) {
api.localStorage.setItem('_jsbootsingleapp_' + name + '_lockname', d);
};
var kill = function(name) {
api.localStorage.removeItem('_jsbootsingleapp_' + name + '_lockname');
};
var lockOwner;
var isOwned = false;
var saidFail = false;
var ticker = function(appKey, instanceId, success, failure) {
// Decide whether to acquire lock or not
var currentOwner = read(appKey);
// The lock is already there. Is it ours? Is it still valid?
if ((currentOwner.pop() != instanceId) && ((Date.now() - currentOwner.shift()) < api.lifeLength)) {
// If we previously owned it, or haven't spoken yet, scream!!!
if (isOwned || !saidFail) {
isOwned = false;
saidFail = true;
failure();
}
return;
}
// Otherwise, confirm / acquire lock
if (!isOwned) {
isOwned = true;
saidFail = false;
success();
}
// We do this after in order to resist porn mode conditions making the setItem call fail
write(appKey, Date.now() + '_' + instanceId);
};
var free = function(appKey, instanceId) {
// Clear timeout
if (lockOwner) {
window.clearInterval(lockOwner);
lockOwner = undefined;
}
// Clean the lock if we own it
if (read(appKey).pop() == instanceId)
kill(appKey);
// Reset
isOwned = false;
saidFail = false;
};
var own = function(key, id, ticktime, success, failure) {
lockOwner = window.setInterval(ticker, ticktime, key, id, success, failure);
};
var ACQUIRED = 'acquired';
var WAITING = 'waiting';
var status;
var success = function() {
status = ACQUIRED;
this.dispatchEvent(this.STATE_CHANGED);
};
var failure = function() {
status = WAITING;
this.dispatchEvent(this.STATE_CHANGED);
throw new api.Error('ALREADY_LOCKED',
'Another instance of the app is already running.', true);
};
var SingleApp = function() {
api.EventDispatcher.apply(this);
Object.defineProperty(this, 'status', {
enumerable: true,
get: function() {
return status;
}
});
var akey;
var iid;
this.boot = function(appKey, length) {
if (length)
api.lifeLength = length * 1000;
status = WAITING;
akey = appKey;
iid = getId(akey);
// Do good measure: cleanup shit if we were there before
free(akey, iid);
own(akey, iid, api.lifeLength / 2, success.bind(this), failure.bind(this));
};
this.shutdown = function() {
this.destroy();
free(akey, iid);
akey = iid = null;
};
};
SingleApp.prototype = Object.create(api.EventDispatcher.prototype);
SingleApp.prototype.ACQUIRED = ACQUIRED;
SingleApp.prototype.WAITING = WAITING;
SingleApp.prototype.STATE_CHANGED = 'state_changed';
this.singleApp = new SingleApp();
});
/**
* Storage backend providing temporary and persistent spaces for both the app and the user.
* Note that it proceeds by loading/saving entirely the objects.
* This is a helper for reasonably sized objects, not an indexedDB for heavy manipulation
* (stressing again: everything is loaded into RAM on boot / login, and saved on shutdown / flush).
* Once booted, you can manipulate them as regular objects.
*
* @file
* @summary Storage helper.
*
* @author WebItUp
* @version 0.4.0
*
* @license <a href="http://www.gnu.org/licenses/agpl-3.0.html">AGPL</a>.
* @copyright All rights reserved <a href="http://www.webitup.fr">copyright WebItUp</a>
* @name https://github.com/jsBoot/jsboot.js/blob/master/src/jsboot/utils/storage.js#74-70c39446998be95596b03bc170b23bba337ce8b4
*/
// - encrypt private datastore?
// http://bitwiseshiftleft.github.com/sjcl/doc/symbols/sjcl.html
// http://www.matasano.com/articles/javascript-cryptography/
// - compress persistent store?
// - http://stackoverflow.com/questions/294297/javascript-implementation-of-gzip
// - http://rosettacode.org/wiki/LZW_compression
// - http://rumkin.com/tools/compression/compress_huff.php
// - https://github.com/olle/lz77-kit/blob/master/src/main/js/lz77.js
// - use something else?
// http://brian.io/lawnchair/adapters/
// http://dev-test.nemikor.com/web-storage/support-test/
// Idb (XXX to be implemented)
/*jshint browser:true, devel:true*/
var IDB = {
indexedDB: window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB,
IDBTransaction: window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction,
IDBKeyRange: window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange
};
jsBoot.add(IDB).as('IDB');
// Optional backends
jsBoot.add(window.openDatabase, true).as('openDatabase');
jsBoot.add(window.localStorage, true).as('localStorage');
// XXX IE8 doesn't support this - "class doesn't support automation" error deep inside gister
// XXX SessionStorage is useful for time limited caching - it's not shared accross tabs
jsBoot.add(window.sessionStorage, true).as('sessionStorage');
jsBoot.add(window.JSON).as('json');
jsBoot.use('jsBoot.core.Error');
jsBoot.pack('jsBoot.utils', function(api) {
'use strict';
// XXX see IE8 error from above
// api.sessionStorage = ('sessionStorage' in window) ? window.sessionStorage : null;
var userKey;
this.storage = new (function() {
/**#@+
* @memberof Roxee.gist.dataStore
*/
/**
* An accessor to the persistent dataStore.
* @property
* @type {String}
* @name persistent
*/
this.persistent = {};
/**
* An accessor to the volatile (caching) dataStore.
* @property
* @type {String}
* @name cache
*/
this.cache = {};
/**
* An accessor to the caching private dataStore.
* @property
* @type {String}
* @name userCache
*/
this.userCache = {};
/**