This repository has been archived by the owner on Dec 10, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gun.js
2214 lines (2119 loc) · 72.9 KB
/
gun.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
;(function(){
/* UNBUILD */
var root;
if(typeof window !== "undefined"){ root = window }
if(typeof global !== "undefined"){ root = global }
root = root || {};
var console = root.console || {log: function(){}};
function USE(arg, req){
return req? require(arg) : arg.slice? USE[R(arg)] : function(mod, path){
arg(mod = {exports: {}});
USE[R(path)] = mod.exports;
}
function R(p){
return p.split('/').slice(-1).toString().replace('.js','');
}
}
if(typeof module !== "undefined"){ var common = module }
/* UNBUILD */
;USE(function(module){
// Generic javascript utilities.
var Type = {};
//Type.fns = Type.fn = {is: function(fn){ return (!!fn && fn instanceof Function) }}
Type.fn = {is: function(fn){ return (!!fn && 'function' == typeof fn) }}
Type.bi = {is: function(b){ return (b instanceof Boolean || typeof b == 'boolean') }}
Type.num = {is: function(n){ return !list_is(n) && ((n - parseFloat(n) + 1) >= 0 || Infinity === n || -Infinity === n) }}
Type.text = {is: function(t){ return (typeof t == 'string') }}
Type.text.ify = function(t){
if(Type.text.is(t)){ return t }
if(typeof JSON !== "undefined"){ return JSON.stringify(t) }
return (t && t.toString)? t.toString() : t;
}
Type.text.random = function(l, c){
var s = '';
l = l || 24; // you are not going to make a 0 length random number, so no need to check type
c = c || '0123456789ABCDEFGHIJKLMNOPQRSTUVWXZabcdefghijklmnopqrstuvwxyz';
while(l > 0){ s += c.charAt(Math.floor(Math.random() * c.length)); l-- }
return s;
}
Type.text.match = function(t, o){ var r = false;
t = t || '';
o = Type.text.is(o)? {'=': o} : o || {}; // {'~', '=', '*', '<', '>', '+', '-', '?', '!'} // ignore case, exactly equal, anything after, lexically larger, lexically lesser, added in, subtacted from, questionable fuzzy match, and ends with.
if(Type.obj.has(o,'~')){ t = t.toLowerCase(); o['='] = (o['='] || o['~']).toLowerCase() }
if(Type.obj.has(o,'=')){ return t === o['='] }
if(Type.obj.has(o,'*')){ if(t.slice(0, o['*'].length) === o['*']){ r = true; t = t.slice(o['*'].length) } else { return false }}
if(Type.obj.has(o,'!')){ if(t.slice(-o['!'].length) === o['!']){ r = true } else { return false }}
if(Type.obj.has(o,'+')){
if(Type.list.map(Type.list.is(o['+'])? o['+'] : [o['+']], function(m){
if(t.indexOf(m) >= 0){ r = true } else { return true }
})){ return false }
}
if(Type.obj.has(o,'-')){
if(Type.list.map(Type.list.is(o['-'])? o['-'] : [o['-']], function(m){
if(t.indexOf(m) < 0){ r = true } else { return true }
})){ return false }
}
if(Type.obj.has(o,'>')){ if(t > o['>']){ r = true } else { return false }}
if(Type.obj.has(o,'<')){ if(t < o['<']){ r = true } else { return false }}
function fuzzy(t,f){ var n = -1, i = 0, c; for(;c = f[i++];){ if(!~(n = t.indexOf(c, n+1))){ return false }} return true } // via http://stackoverflow.com/questions/9206013/javascript-fuzzy-search
if(Type.obj.has(o,'?')){ if(fuzzy(t, o['?'])){ r = true } else { return false }} // change name!
return r;
}
Type.list = {is: function(l){ return (l instanceof Array) }}
Type.list.slit = Array.prototype.slice;
Type.list.sort = function(k){ // creates a new sort function based off some key
return function(A,B){
if(!A || !B){ return 0 } A = A[k]; B = B[k];
if(A < B){ return -1 }else if(A > B){ return 1 }
else { return 0 }
}
}
Type.list.map = function(l, c, _){ return obj_map(l, c, _) }
Type.list.index = 1; // change this to 0 if you want non-logical, non-mathematical, non-matrix, non-convenient array notation
Type.obj = {is: function(o){ return o? (o instanceof Object && o.constructor === Object) || Object.prototype.toString.call(o).match(/^\[object (\w+)\]$/)[1] === 'Object' : false }}
Type.obj.put = function(o, k, v){ return (o||{})[k] = v, o }
Type.obj.has = function(o, k){ return o && Object.prototype.hasOwnProperty.call(o, k) }
Type.obj.del = function(o, k){
if(!o){ return }
o[k] = null;
delete o[k];
return o;
}
Type.obj.as = function(o, k, v, u){ return o[k] = o[k] || (u === v? {} : v) }
Type.obj.ify = function(o){
if(obj_is(o)){ return o }
try{o = JSON.parse(o);
}catch(e){o={}};
return o;
}
;(function(){ var u;
function map(v,k){
if(obj_has(this,k) && u !== this[k]){ return }
this[k] = v;
}
Type.obj.to = function(from, to){
to = to || {};
obj_map(from, map, to);
return to;
}
}());
Type.obj.copy = function(o){ // because http://web.archive.org/web/20140328224025/http://jsperf.com/cloning-an-object/2
return !o? o : JSON.parse(JSON.stringify(o)); // is shockingly faster than anything else, and our data has to be a subset of JSON anyways!
}
;(function(){
function empty(v,i){ var n = this.n;
if(n && (i === n || (obj_is(n) && obj_has(n, i)))){ return }
if(i){ return true }
}
Type.obj.empty = function(o, n){
if(!o){ return true }
return obj_map(o,empty,{n:n})? false : true;
}
}());
;(function(){
function t(k,v){
if(2 === arguments.length){
t.r = t.r || {};
t.r[k] = v;
return;
} t.r = t.r || [];
t.r.push(k);
};
var keys = Object.keys;
Type.obj.map = function(l, c, _){
var u, i = 0, x, r, ll, lle, f = fn_is(c);
t.r = null;
if(keys && obj_is(l)){
ll = keys(l); lle = true;
}
if(list_is(l) || ll){
x = (ll || l).length;
for(;i < x; i++){
var ii = (i + Type.list.index);
if(f){
r = lle? c.call(_ || this, l[ll[i]], ll[i], t) : c.call(_ || this, l[i], ii, t);
if(r !== u){ return r }
} else {
//if(Type.test.is(c,l[i])){ return ii } // should implement deep equality testing!
if(c === l[lle? ll[i] : i]){ return ll? ll[i] : ii } // use this for now
}
}
} else {
for(i in l){
if(f){
if(obj_has(l,i)){
r = _? c.call(_, l[i], i, t) : c(l[i], i, t);
if(r !== u){ return r }
}
} else {
//if(a.test.is(c,l[i])){ return i } // should implement deep equality testing!
if(c === l[i]){ return i } // use this for now
}
}
}
return f? t.r : Type.list.index? 0 : -1;
}
}());
Type.time = {};
Type.time.is = function(t){ return t? t instanceof Date : (+new Date().getTime()) }
var fn_is = Type.fn.is;
var list_is = Type.list.is;
var obj = Type.obj, obj_is = obj.is, obj_has = obj.has, obj_map = obj.map;
module.exports = Type;
})(USE, './type');
;USE(function(module){
// On event emitter generic javascript utility.
module.exports = function onto(tag, arg, as){
if(!tag){ return {to: onto} }
var u, tag = (this.tag || (this.tag = {}))[tag] ||
(this.tag[tag] = {tag: tag, to: onto._ = {
next: function(arg){ var tmp;
if((tmp = this.to)){
tmp.next(arg);
}}
}});
if(arg instanceof Function){
var be = {
off: onto.off ||
(onto.off = function(){
if(this.next === onto._.next){ return !0 }
if(this === this.the.last){
this.the.last = this.back;
}
this.to.back = this.back;
this.next = onto._.next;
this.back.to = this.to;
if(this.the.last === this.the){
delete this.on.tag[this.the.tag];
}
}),
to: onto._,
next: arg,
the: tag,
on: this,
as: as,
};
(be.back = tag.last || tag).to = be;
return tag.last = be;
}
if((tag = tag.to) && u !== arg){ tag.next(arg) }
return tag;
};
})(USE, './onto');
;USE(function(module){
/* Based on the Hypothetical Amnesia Machine thought experiment */
function HAM(machineState, incomingState, currentState, incomingValue, currentValue){
if(machineState < incomingState){
return {defer: true}; // the incoming value is outside the boundary of the machine's state, it must be reprocessed in another state.
}
if(incomingState < currentState){
return {historical: true}; // the incoming value is within the boundary of the machine's state, but not within the range.
}
if(currentState < incomingState){
return {converge: true, incoming: true}; // the incoming value is within both the boundary and the range of the machine's state.
}
if(incomingState === currentState){
incomingValue = Lexical(incomingValue) || "";
currentValue = Lexical(currentValue) || "";
if(incomingValue === currentValue){ // Note: while these are practically the same, the deltas could be technically different
return {state: true};
}
/*
The following is a naive implementation, but will always work.
Never change it unless you have specific needs that absolutely require it.
If changed, your data will diverge unless you guarantee every peer's algorithm has also been changed to be the same.
As a result, it is highly discouraged to modify despite the fact that it is naive,
because convergence (data integrity) is generally more important.
Any difference in this algorithm must be given a new and different name.
*/
if(incomingValue < currentValue){ // Lexical only works on simple value types!
return {converge: true, current: true};
}
if(currentValue < incomingValue){ // Lexical only works on simple value types!
return {converge: true, incoming: true};
}
}
return {err: "Invalid CRDT Data: "+ incomingValue +" to "+ currentValue +" at "+ incomingState +" to "+ currentState +"!"};
}
if(typeof JSON === 'undefined'){
throw new Error(
'JSON is not included in this browser. Please load it first: ' +
'ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js'
);
}
var Lexical = JSON.stringify, undefined;
module.exports = HAM;
})(USE, './HAM');
;USE(function(module){
var Type = USE('./type');
var Val = {};
Val.is = function(v){ // Valid values are a subset of JSON: null, binary, number (!Infinity), text, or a soul relation. Arrays need special algorithms to handle concurrency, so they are not supported directly. Use an extension that supports them if needed but research their problems first.
if(v === u){ return false }
if(v === null){ return true } // "deletes", nulling out keys.
if(v === Infinity){ return false } // we want this to be, but JSON does not support it, sad face.
if(text_is(v) // by "text" we mean strings.
|| bi_is(v) // by "binary" we mean boolean.
|| num_is(v)){ // by "number" we mean integers or decimals.
return true; // simple values are valid.
}
return Val.rel.is(v) || false; // is the value a soul relation? Then it is valid and return it. If not, everything else remaining is an invalid data type. Custom extensions can be built on top of these primitives to support other types.
}
Val.link = Val.rel = {_: '#'};
;(function(){
Val.rel.is = function(v){ // this defines whether an object is a soul relation or not, they look like this: {'#': 'UUID'}
if(v && v[rel_] && !v._ && obj_is(v)){ // must be an object.
var o = {};
obj_map(v, map, o);
if(o.id){ // a valid id was found.
return o.id; // yay! Return it.
}
}
return false; // the value was not a valid soul relation.
}
function map(s, k){ var o = this; // map over the object...
if(o.id){ return o.id = false } // if ID is already defined AND we're still looping through the object, it is considered invalid.
if(k == rel_ && text_is(s)){ // the key should be '#' and have a text value.
o.id = s; // we found the soul!
} else {
return o.id = false; // if there exists anything else on the object that isn't the soul, then it is considered invalid.
}
}
}());
Val.rel.ify = function(t){ return obj_put({}, rel_, t) } // convert a soul into a relation and return it.
Type.obj.has._ = '.';
var rel_ = Val.link._, u;
var bi_is = Type.bi.is;
var num_is = Type.num.is;
var text_is = Type.text.is;
var obj = Type.obj, obj_is = obj.is, obj_put = obj.put, obj_map = obj.map;
module.exports = Val;
})(USE, './val');
;USE(function(module){
var Type = USE('./type');
var Val = USE('./val');
var Node = {_: '_'};
Node.soul = function(n, o){ return (n && n._ && n._[o || soul_]) } // convenience function to check to see if there is a soul on a node and return it.
Node.soul.ify = function(n, o){ // put a soul on an object.
o = (typeof o === 'string')? {soul: o} : o || {};
n = n || {}; // make sure it exists.
n._ = n._ || {}; // make sure meta exists.
n._[soul_] = o.soul || n._[soul_] || text_random(); // put the soul on it.
return n;
}
Node.soul._ = Val.link._;
;(function(){
Node.is = function(n, cb, as){ var s; // checks to see if an object is a valid node.
if(!obj_is(n)){ return false } // must be an object.
if(s = Node.soul(n)){ // must have a soul on it.
return !obj_map(n, map, {as:as,cb:cb,s:s,n:n});
}
return false; // nope! This was not a valid node.
}
function map(v, k){ // we invert this because the way we check for this is via a negation.
if(k === Node._){ return } // skip over the metadata.
if(!Val.is(v)){ return true } // it is true that this is an invalid node.
if(this.cb){ this.cb.call(this.as, v, k, this.n, this.s) } // optionally callback each key/value.
}
}());
;(function(){
Node.ify = function(obj, o, as){ // returns a node from a shallow object.
if(!o){ o = {} }
else if(typeof o === 'string'){ o = {soul: o} }
else if(o instanceof Function){ o = {map: o} }
if(o.map){ o.node = o.map.call(as, obj, u, o.node || {}) }
if(o.node = Node.soul.ify(o.node || {}, o)){
obj_map(obj, map, {o:o,as:as});
}
return o.node; // This will only be a valid node if the object wasn't already deep!
}
function map(v, k){ var o = this.o, tmp, u; // iterate over each key/value.
if(o.map){
tmp = o.map.call(this.as, v, ''+k, o.node);
if(u === tmp){
obj_del(o.node, k);
} else
if(o.node){ o.node[k] = tmp }
return;
}
if(Val.is(v)){
o.node[k] = v;
}
}
}());
var obj = Type.obj, obj_is = obj.is, obj_del = obj.del, obj_map = obj.map;
var text = Type.text, text_random = text.random;
var soul_ = Node.soul._;
var u;
module.exports = Node;
})(USE, './node');
;USE(function(module){
var Type = USE('./type');
var Node = USE('./node');
function State(){
var t;
/*if(perf){
t = start + perf.now(); // Danger: Accuracy decays significantly over time, even if precise.
} else {*/
t = time();
//}
if(last < t){
return N = 0, last = t + State.drift;
}
return last = t + ((N += 1) / D) + State.drift;
}
var time = Type.time.is, last = -Infinity, N = 0, D = 1000; // WARNING! In the future, on machines that are D times faster than 2016AD machines, you will want to increase D by another several orders of magnitude so the processing speed never out paces the decimal resolution (increasing an integer effects the state accuracy).
var perf = (typeof performance !== 'undefined')? (performance.timing && performance) : false, start = (perf && perf.timing && perf.timing.navigationStart) || (perf = false);
State._ = '>';
State.drift = 0;
State.is = function(n, k, o){ // convenience function to get the state on a key on a node and return it.
var tmp = (k && n && n[N_] && n[N_][State._]) || o;
if(!tmp){ return }
return num_is(tmp = tmp[k])? tmp : -Infinity;
}
State.lex = function(){ return State().toString(36).replace('.','') }
State.ify = function(n, k, s, v, soul){ // put a key's state on a node.
if(!n || !n[N_]){ // reject if it is not node-like.
if(!soul){ // unless they passed a soul
return;
}
n = Node.soul.ify(n, soul); // then make it so!
}
var tmp = obj_as(n[N_], State._); // grab the states data.
if(u !== k && k !== N_){
if(num_is(s)){
tmp[k] = s; // add the valid state.
}
if(u !== v){ // Note: Not its job to check for valid values!
n[k] = v;
}
}
return n;
}
State.to = function(from, k, to){
var val = from[k]; // BUGGY!
if(obj_is(val)){
val = obj_copy(val);
}
return State.ify(to, k, State.is(from, k), val, Node.soul(from));
}
;(function(){
State.map = function(cb, s, as){ var u; // for use with Node.ify
var o = obj_is(o = cb || s)? o : null;
cb = fn_is(cb = cb || s)? cb : null;
if(o && !cb){
s = num_is(s)? s : State();
o[N_] = o[N_] || {};
obj_map(o, map, {o:o,s:s});
return o;
}
as = as || obj_is(s)? s : u;
s = num_is(s)? s : State();
return function(v, k, o, opt){
if(!cb){
map.call({o: o, s: s}, v,k);
return v;
}
cb.call(as || this || {}, v, k, o, opt);
if(obj_has(o,k) && u === o[k]){ return }
map.call({o: o, s: s}, v,k);
}
}
function map(v,k){
if(N_ === k){ return }
State.ify(this.o, k, this.s) ;
}
}());
var obj = Type.obj, obj_as = obj.as, obj_has = obj.has, obj_is = obj.is, obj_map = obj.map, obj_copy = obj.copy;
var num = Type.num, num_is = num.is;
var fn = Type.fn, fn_is = fn.is;
var N_ = Node._, u;
module.exports = State;
})(USE, './state');
;USE(function(module){
var Type = USE('./type');
var Val = USE('./val');
var Node = USE('./node');
var Graph = {};
;(function(){
Graph.is = function(g, cb, fn, as){ // checks to see if an object is a valid graph.
if(!g || !obj_is(g) || obj_empty(g)){ return false } // must be an object.
return !obj_map(g, map, {cb:cb,fn:fn,as:as}); // makes sure it wasn't an empty object.
}
function map(n, s){ // we invert this because the way'? we check for this is via a negation.
if(!n || s !== Node.soul(n) || !Node.is(n, this.fn, this.as)){ return true } // it is true that this is an invalid graph.
if(!this.cb){ return }
nf.n = n; nf.as = this.as; // sequential race conditions aren't races.
this.cb.call(nf.as, n, s, nf);
}
function nf(fn){ // optional callback for each node.
if(fn){ Node.is(nf.n, fn, nf.as) } // where we then have an optional callback for each key/value.
}
}());
;(function(){
Graph.ify = function(obj, env, as){
var at = {path: [], obj: obj};
if(!env){
env = {};
} else
if(typeof env === 'string'){
env = {soul: env};
} else
if(env instanceof Function){
env.map = env;
}
if(env.soul){
at.rel = Val.rel.ify(env.soul);
}
env.shell = (as||{}).shell;
env.graph = env.graph || {};
env.seen = env.seen || [];
env.as = env.as || as;
node(env, at);
env.root = at.node;
return env.graph;
}
function node(env, at){ var tmp;
if(tmp = seen(env, at)){ return tmp }
at.env = env;
at.soul = soul;
if(Node.ify(at.obj, map, at)){
at.rel = at.rel || Val.rel.ify(Node.soul(at.node));
if(at.obj !== env.shell){
env.graph[Val.rel.is(at.rel)] = at.node;
}
}
return at;
}
function map(v,k,n){
var at = this, env = at.env, is, tmp;
if(Node._ === k && obj_has(v,Val.rel._)){
return n._; // TODO: Bug?
}
if(!(is = valid(v,k,n, at,env))){ return }
if(!k){
at.node = at.node || n || {};
if(obj_has(v, Node._) && Node.soul(v)){ // ? for safety ?
at.node._ = obj_copy(v._);
}
at.node = Node.soul.ify(at.node, Val.rel.is(at.rel));
at.rel = at.rel || Val.rel.ify(Node.soul(at.node));
}
if(tmp = env.map){
tmp.call(env.as || {}, v,k,n, at);
if(obj_has(n,k)){
v = n[k];
if(u === v){
obj_del(n, k);
return;
}
if(!(is = valid(v,k,n, at,env))){ return }
}
}
if(!k){ return at.node }
if(true === is){
return v;
}
tmp = node(env, {obj: v, path: at.path.concat(k)});
if(!tmp.node){ return }
return tmp.rel; //{'#': Node.soul(tmp.node)};
}
function soul(id){ var at = this;
var prev = Val.link.is(at.rel), graph = at.env.graph;
at.rel = at.rel || Val.rel.ify(id);
at.rel[Val.rel._] = id;
if(at.node && at.node[Node._]){
at.node[Node._][Val.rel._] = id;
}
if(obj_has(graph, prev)){
graph[id] = graph[prev];
obj_del(graph, prev);
}
}
function valid(v,k,n, at,env){ var tmp;
if(Val.is(v)){ return true }
if(obj_is(v)){ return 1 }
if(tmp = env.invalid){
v = tmp.call(env.as || {}, v,k,n);
return valid(v,k,n, at,env);
}
env.err = "Invalid value at '" + at.path.concat(k).join('.') + "'!";
if(Type.list.is(v)){ env.err += " Use `.set(item)` instead of an Array." }
}
function seen(env, at){
var arr = env.seen, i = arr.length, has;
while(i--){ has = arr[i];
if(at.obj === has.obj){ return has }
}
arr.push(at);
}
}());
Graph.node = function(node){
var soul = Node.soul(node);
if(!soul){ return }
return obj_put({}, soul, node);
}
;(function(){
Graph.to = function(graph, root, opt){
if(!graph){ return }
var obj = {};
opt = opt || {seen: {}};
obj_map(graph[root], map, {obj:obj, graph: graph, opt: opt});
return obj;
}
function map(v,k){ var tmp, obj;
if(Node._ === k){
if(obj_empty(v, Val.rel._)){
return;
}
this.obj[k] = obj_copy(v);
return;
}
if(!(tmp = Val.rel.is(v))){
this.obj[k] = v;
return;
}
if(obj = this.opt.seen[tmp]){
this.obj[k] = obj;
return;
}
this.obj[k] = this.opt.seen[tmp] = Graph.to(this.graph, tmp, this.opt);
}
}());
var fn_is = Type.fn.is;
var obj = Type.obj, obj_is = obj.is, obj_del = obj.del, obj_has = obj.has, obj_empty = obj.empty, obj_put = obj.put, obj_map = obj.map, obj_copy = obj.copy;
var u;
module.exports = Graph;
})(USE, './graph');
;USE(function(module){
// request / response module, for asking and acking messages.
USE('./onto'); // depends upon onto!
module.exports = function ask(cb, as){
if(!this.on){ return }
if(!(cb instanceof Function)){
if(!cb || !as){ return }
var id = cb['#'] || cb, tmp = (this.tag||empty)[id];
if(!tmp){ return }
tmp = this.on(id, as);
clearTimeout(tmp.err);
return true;
}
var id = (as && as['#']) || Math.random().toString(36).slice(2);
if(!cb){ return id }
var to = this.on(id, cb, as);
to.err = to.err || setTimeout(function(){
to.next({err: "Error: No ACK received yet.", lack: true});
to.off();
}, (this.opt||{}).lack || 9000);
return id;
}
})(USE, './ask');
;USE(function(module){
var Type = USE('./type');
function Dup(opt){
var dup = {s:{}};
opt = opt || {max: 1000, age: 1000 * 9};//1000 * 60 * 2};
dup.check = function(id){ var tmp;
if(!(tmp = dup.s[id])){ return false }
if(tmp.pass){ return tmp.pass = false }
return dup.track(id);
}
dup.track = function(id, pass){
var it = dup.s[id] || (dup.s[id] = {});
it.was = time_is();
if(pass){ it.pass = true }
if(!dup.to){
dup.to = setTimeout(function(){
var now = time_is();
Type.obj.map(dup.s, function(it, id){
if(it && opt.age > (now - it.was)){ return }
Type.obj.del(dup.s, id);
});
dup.to = null;
}, opt.age + 9);
}
return it;
}
return dup;
}
var time_is = Type.time.is;
module.exports = Dup;
})(USE, './dup');
;USE(function(module){
function Gun(o){
if(o instanceof Gun){ return (this._ = {gun: this, $: this}).$ }
if(!(this instanceof Gun)){ return new Gun(o) }
return Gun.create(this._ = {gun: this, $: this, opt: o});
}
Gun.is = function($){ return ($ instanceof Gun) || ($ && $._ && ($ === $._.$)) || false }
Gun.version = 0.9;
Gun.chain = Gun.prototype;
Gun.chain.toJSON = function(){};
var Type = USE('./type');
Type.obj.to(Type, Gun);
Gun.HAM = USE('./HAM');
Gun.val = USE('./val');
Gun.node = USE('./node');
Gun.state = USE('./state');
Gun.graph = USE('./graph');
Gun.on = USE('./onto');
Gun.ask = USE('./ask');
Gun.dup = USE('./dup');
;(function(){
Gun.create = function(at){
at.root = at.root || at;
at.graph = at.graph || {};
at.on = at.on || Gun.on;
at.ask = at.ask || Gun.ask;
at.dup = at.dup || Gun.dup();
var gun = at.$.opt(at.opt);
if(!at.once){
at.on('in', root, at);
at.on('out', root, {at: at, out: root});
Gun.on('create', at);
at.on('create', at);
}
at.once = 1;
return gun;
}
function root(msg){
//add to.next(at); // TODO: MISSING FEATURE!!!
var ev = this, as = ev.as, at = as.at || as, gun = at.$, dup, tmp;
if(!(tmp = msg['#'])){ tmp = msg['#'] = text_rand(9) }
if((dup = at.dup).check(tmp)){
if(as.out === msg.out){
msg.out = u;
ev.to.next(msg);
}
return;
}
dup.track(tmp);
if(!at.ask(msg['@'], msg)){
if(msg.get){
Gun.on.get(msg, gun); //at.on('get', get(msg));
}
if(msg.put){
Gun.on.put(msg, gun); //at.on('put', put(msg));
}
}
ev.to.next(msg);
if(!as.out){
msg.out = root;
at.on('out', msg);
}
}
}());
;(function(){
Gun.on.put = function(msg, gun){
var at = gun._, ctx = {$: gun, graph: at.graph, put: {}, map: {}, souls: {}, machine: Gun.state(), ack: msg['@'], cat: at, stop: {}};
if(!Gun.graph.is(msg.put, null, verify, ctx)){ ctx.err = "Error: Invalid graph!" }
if(ctx.err){ return at.on('in', {'@': msg['#'], err: Gun.log(ctx.err) }) }
obj_map(ctx.put, merge, ctx);
if(!ctx.async){ obj_map(ctx.map, map, ctx) }
if(u !== ctx.defer){
setTimeout(function(){
Gun.on.put(msg, gun);
}, ctx.defer - ctx.machine);
}
if(!ctx.diff){ return }
at.on('put', obj_to(msg, {put: ctx.diff}));
};
function verify(val, key, node, soul){ var ctx = this;
var state = Gun.state.is(node, key), tmp;
if(!state){ return ctx.err = "Error: No state on '"+key+"' in node '"+soul+"'!" }
var vertex = ctx.graph[soul] || empty, was = Gun.state.is(vertex, key, true), known = vertex[key];
var HAM = Gun.HAM(ctx.machine, state, was, val, known);
if(!HAM.incoming){
if(HAM.defer){ // pick the lowest
ctx.defer = (state < (ctx.defer || Infinity))? state : ctx.defer;
}
return;
}
ctx.put[soul] = Gun.state.to(node, key, ctx.put[soul]);
(ctx.diff || (ctx.diff = {}))[soul] = Gun.state.to(node, key, ctx.diff[soul]);
ctx.souls[soul] = true;
}
function merge(node, soul){
var ctx = this, cat = ctx.$._, at = (cat.next || empty)[soul];
if(!at){
if(!(cat.opt||empty).super){
ctx.souls[soul] = false;
return;
}
at = (ctx.$.get(soul)._);
}
var msg = ctx.map[soul] = {
put: node,
get: soul,
$: at.$
}, as = {ctx: ctx, msg: msg};
ctx.async = !!cat.tag.node;
if(ctx.ack){ msg['@'] = ctx.ack }
obj_map(node, each, as);
if(!ctx.async){ return }
if(!ctx.and){
// If it is async, we only need to setup one listener per context (ctx)
cat.on('node', function(m){
this.to.next(m); // make sure to call other context's listeners.
if(m !== ctx.map[m.get]){ return } // filter out events not from this context!
ctx.souls[m.get] = false; // set our many-async flag
obj_map(m.put, patch, m); // merge into view
if(obj_map(ctx.souls, function(v){ if(v){ return v } })){ return } // if flag still outstanding, keep waiting.
if(ctx.c){ return } ctx.c = 1; // failsafe for only being called once per context.
this.off();
obj_map(ctx.map, map, ctx); // all done, trigger chains.
});
}
ctx.and = true;
cat.on('node', msg); // each node on the current context's graph needs to be emitted though.
}
function each(val, key){
var ctx = this.ctx, graph = ctx.graph, msg = this.msg, soul = msg.get, node = msg.put, at = (msg.$._), tmp;
graph[soul] = Gun.state.to(node, key, graph[soul]);
if(ctx.async){ return }
at.put = Gun.state.to(node, key, at.put);
}
function patch(val, key){
var msg = this, node = msg.put, at = (msg.$._);
at.put = Gun.state.to(node, key, at.put);
}
function map(msg, soul){
if(!msg.$){ return }
this.cat.stop = this.stop; // temporary fix till a better solution?
(msg.$._).on('in', msg);
this.cat.stop = null; // temporary fix till a better solution?
}
Gun.on.get = function(msg, gun){
var root = gun._, get = msg.get, soul = get[_soul], node = root.graph[soul], has = get[_has], tmp;
var next = root.next || (root.next = {}), at = next[soul];
if(obj_has(soul, '*')){ // TEMPORARY HACK FOR MARTTI, TESTING
var graph = {};
Gun.obj.map(root.graph, function(node, s){
if(Gun.text.match(s, soul)){
graph[s] = Gun.obj.copy(node);
}
});
if(!Gun.obj.empty(graph)){
root.on('in', {
'@': msg['#'],
how: '*',
put: graph,
$: gun
});
}
} // TEMPORARY HACK FOR MARTTI, TESTING
if(!node){ return root.on('get', msg) }
if(has){
if(!obj_has(node, has)){ return root.on('get', msg) }
node = Gun.state.to(node, has);
// If we have a key in-memory, do we really need to fetch?
// Maybe... in case the in-memory key we have is a local write
// we still need to trigger a pull/merge from peers.
} else {
node = Gun.obj.copy(node);
}
node = Gun.graph.node(node);
tmp = (at||empty).ack;
root.on('in', {
'@': msg['#'],
how: 'mem',
put: node,
$: gun
});
//if(0 < tmp){ return }
root.on('get', msg);
}
}());
;(function(){
Gun.chain.opt = function(opt){
opt = opt || {};
var gun = this, at = gun._, tmp = opt.peers || opt;
if(!obj_is(opt)){ opt = {} }
if(!obj_is(at.opt)){ at.opt = opt }
if(text_is(tmp)){ tmp = [tmp] }
if(list_is(tmp)){
tmp = obj_map(tmp, function(url, i, map){
map(url, {url: url});
});
if(!obj_is(at.opt.peers)){ at.opt.peers = {}}
at.opt.peers = obj_to(tmp, at.opt.peers);
}
at.opt.peers = at.opt.peers || {};
obj_to(opt, at.opt); // copies options on to `at.opt` only if not already taken.
Gun.on('opt', at);
at.opt.uuid = at.opt.uuid || function(){ return state_lex() + text_rand(12) }
return gun;
}
}());
var list_is = Gun.list.is;
var text = Gun.text, text_is = text.is, text_rand = text.random;
var obj = Gun.obj, obj_is = obj.is, obj_has = obj.has, obj_to = obj.to, obj_map = obj.map, obj_copy = obj.copy;
var state_lex = Gun.state.lex, _soul = Gun.val.rel._, _has = '.', node_ = Gun.node._, rel_is = Gun.val.link.is;
var empty = {}, u;
console.debug = function(i, s){ return (console.debug.i && i === console.debug.i && console.debug.i++) && (console.log.apply(console, arguments) || s) };
Gun.log = function(){ return (!Gun.log.off && console.log.apply(console, arguments)), [].slice.call(arguments).join(' ') }
Gun.log.once = function(w,s,o){ return (o = Gun.log.once)[w] = o[w] || 0, o[w]++ || Gun.log(s) }
;"Please do not remove these messages unless you are paying for a monthly sponsorship, thanks!";
Gun.log.once("welcome", "Hello wonderful person! :) Thanks for using GUN, feel free to ask for help on https://gitter.im/amark/gun and ask StackOverflow questions tagged with 'gun'!");
;"Please do not remove these messages unless you are paying for a monthly sponsorship, thanks!";
if(typeof window !== "undefined"){ (window.GUN = window.Gun = Gun).window = window }
try{ if(typeof common !== "undefined"){ common.exports = Gun } }catch(e){}
module.exports = Gun;
/*Gun.on('opt', function(ctx){ // FOR TESTING PURPOSES
this.to.next(ctx);
if(ctx.once){ return }
ctx.on('node', function(msg){
var to = this.to;
//Gun.node.is(msg.put, function(v,k){ msg.put[k] = v + v });
setTimeout(function(){
to.next(msg);
},1);
});
});*/
})(USE, './root');
;USE(function(module){
var Gun = USE('./root');
Gun.chain.back = function(n, opt){ var tmp;
n = n || 1;
if(-1 === n || Infinity === n){
return this._.root.$;
} else
if(1 === n){
return (this._.back || this._).$;
}
var gun = this, at = gun._;
if(typeof n === 'string'){
n = n.split('.');
}
if(n instanceof Array){
var i = 0, l = n.length, tmp = at;
for(i; i < l; i++){
tmp = (tmp||empty)[n[i]];
}
if(u !== tmp){
return opt? gun : tmp;
} else
if((tmp = at.back)){
return tmp.$.back(n, opt);
}
return;
}
if(n instanceof Function){
var yes, tmp = {back: at};
while((tmp = tmp.back)
&& u === (yes = n(tmp, opt))){}
return yes;
}
if(Gun.num.is(n)){
return (at.back || at).$.back(n - 1);
}
return this;
}
var empty = {}, u;
})(USE, './back');
;USE(function(module){
// WARNING: GUN is very simple, but the JavaScript chaining API around GUN
// is complicated and was extremely hard to build. If you port GUN to another
// language, consider implementing an easier API to build.
var Gun = USE('./root');
Gun.chain.chain = function(sub){
var gun = this, at = gun._, chain = new (sub || gun).constructor(gun), cat = chain._, root;
cat.root = root = at.root;
cat.id = ++root.once;
cat.back = gun._;
cat.on = Gun.on;
cat.on('in', input, cat); // For 'in' if I add my own listeners to each then I MUST do it before in gets called. If I listen globally for all incoming data instead though, regardless of individual listeners, I can transform the data there and then as well.
cat.on('out', output, cat); // However for output, there isn't really the global option. I must listen by adding my own listener individually BEFORE this one is ever called.
return chain;
}
function output(msg){
var put, get, at = this.as, back = at.back, root = at.root, tmp;
if(!msg.I){ msg.I = at.$ }
if(!msg.$){ msg.$ = at.$ }
this.to.next(msg);
if(get = msg.get){
/*if(u !== at.put){
at.on('in', at);
return;
}*/
if(get['#'] || at.soul){
get['#'] = get['#'] || at.soul;
msg['#'] || (msg['#'] = text_rand(9));
back = (root.$.get(get['#'])._);
if(!(get = get['.'])){
tmp = back.ack;
if(!tmp){ back.ack = -1 }
if(obj_has(back, 'put')){
back.on('in', back);
}
if(tmp){ return }
msg.$ = back.$;
} else
if(obj_has(back.put, get)){
put = (back.$.get(get)._);
if(!(tmp = put.ack)){ put.ack = -1 }
back.on('in', {
$: back.$,
put: Gun.state.to(back.put, get),
get: back.get
});
if(tmp){ return }
}
root.ask(ack, msg);
return root.on('in', msg);
}
if(root.now){ root.now[at.id] = root.now[at.id] || true; at.pass = {} }
if(get['.']){
if(at.get){
msg = {get: {'.': at.get}, $: at.$};
//if(back.ask || (back.ask = {})[at.get]){ return }