forked from Wizcorp/node-tomes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
1861 lines (1412 loc) · 45.1 KB
/
index.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) 2012 Wizcorp, Inc. <info@wizcorp.jp>
//
// 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.
var EventEmitter = require('events').EventEmitter;
function inherits(Child, Parent) {
Child.prototype = Object.create(Parent.prototype, {
constructor: { value: Child, enumerable: false, writable: true, configurable: true }
});
}
// ________
// | \
// \$$$$$$$$______ ______ ____ ______ _______
// | $$ / \ | \ \ / \ / \
// | $$ | $$$$$$\| $$$$$$\$$$$\| $$$$$$\| $$$$$$$
// | $$ | $$ | $$| $$ | $$ | $$| $$ $$ \$$ \
// | $$ | $$__/ $$| $$ | $$ | $$| $$$$$$$$ _\$$$$$$\
// | $$ \$$ $$| $$ | $$ | $$ \$$ \| $$
// \$$ \$$$$$$ \$$ \$$ \$$ \$$$$$$$ \$$$$$$$
function Tome(parent, key) {
// The Tome type holds references and methods that all 'real' types
// inherit. We should never get an object that is just a Tome, it should
// always be at least one other type. We call this function in the
// constructor of each Tome type.
// __root__ holds a reference to the Tome at the top of the chain. We use
// it to identify where our change operations are being held. It exists on
// all Tomes.
// __diff__ is our buffer that holds all of the change operations that have
// been generated. It only exists on the root Tome.
// __version__ is a number that increments whenever a Tome or any of its
// child Tomes changes. It only exists on the root Tome.
// __parent__ holds a reference to the Tome's parent object so we can
// signal up the Tome chain. It only exists on Tomes with parents.
// __key__ is the key that our Tome is referred to by its parent. It only
// exists on Tomes with parents.
// If you're using the node.js event emitter, we need to make the _events
// non-enumerable. Ideally, node.js would make this the default behavior.
var hasParentTome = Tome.isTome(parent);
var properties = {
__dirty__: { writable: true, value: 1 },
__root__: { writable: true, value: hasParentTome ? parent.__root__ : this },
__untomed__: { writable: true, value: { version: 0, cached: undefined } },
_events: { configurable: true, writable: true },
_eventsCount: { configurable: true, writable: true },
_callbacks: { configurable: true, writable: true }
};
if (hasParentTome) {
properties.__parent__ = { writable: true, value: parent };
properties.__key__ = { writable: true, value: key };
} else {
properties.__diff__ = { writable: true, value: [] };
properties.__version__ = { writable: true, value: 1 };
}
Object.defineProperties(this, properties);
}
function emitAdd(tome, key) {
tome.emit('add', key);
}
function emitDel(tome, key) {
tome.emit('del', key);
}
function emitDestroy(tome) {
tome.emit('destroy');
}
function destroy(tome) {
// When a Tome is deleted we emit a destroy event on it and all of its child
// Tomes since they will no longer exist. We go down the Tome chain first and
// then emit our way up.
var keys = Object.keys(tome);
for (var i = 0, len = keys.length; i < len; i += 1) {
var k = keys[i];
if (Tome.isTome(tome[k])) {
destroy(tome[k]);
}
}
emitDestroy(tome);
tome.removeAllListeners();
}
function reset(tome) {
// The reset method deletes all properties on a Tome and turns it back into
// a base Tome with no real type. We should immediately assign it a new type
// based on the value.
delete tome._arr;
delete tome.length;
delete tome._val;
var keys = Object.keys(tome);
var len = keys.length;
var key, i;
// Here we delete all of the properties and emit destroy on all of their
// child Tomes. For destroy we don't really care about the order of events.
// All that matters is that a Tome got destroyed.
for (i = 0; i < len; i += 1) {
key = keys[i];
var o = tome[key];
delete tome[key];
if (Tome.isTome(o)) {
destroy(o);
}
}
// Once we have deleted all of the properties we emit del for each of the
// deleted properties. We use this order so that when we emit del the
// properties have already been deleted.
for (i = 0; i < len; i += 1) {
emitDel(tome, keys[i]);
}
}
Tome.resolveChain = function (tome, chain) {
var len = chain.length;
var target = tome.__root__;
for (var i = 0; i < len; i += 1) {
var link = chain[i];
if (!target.hasOwnProperty(link)) {
throw new ReferenceError('resolveChain - Error resolving chain: ' + chain);
}
target = target[link];
}
return target;
};
Tome.buildChain = function (tome) {
var chain = [];
while (tome.hasOwnProperty('__key__')) {
chain.push(tome.__key__);
tome = tome.__parent__;
}
return chain.reverse();
};
Tome.unTome = function (o) {
var seen = [ o ];
function unTome(tome) {
var out, keys;
var tomeType = Tome.typeOf(tome);
switch (tomeType) {
case 'object':
out = {};
keys = Object.keys(tome);
break;
case 'array':
out = new Array(tome.length);
keys = Object.keys(tome);
break;
case 'undefined':
out = undefined;
break;
case 'null':
out = null;
break;
default:
out = tome.valueOf();
break;
}
if (!keys) {
return out;
}
for (var i = 0; i < keys.length; i += 1) {
var key = keys[i];
if (Tome.typeOf(tome[key]) === 'object' || Tome.typeOf(tome[key]) === 'array') {
if (seen.indexOf(tome[key]) !== -1) {
throw new TypeError('Converting circular structure to Tome');
}
seen.push(tome[key]);
}
out[key] = unTome(tome[key]);
}
return out;
}
return unTome(o);
};
function markDirty(tome, dirtyAt, was) {
if (tome.__dirty__ === dirtyAt) {
return;
}
tome.__dirty__ = dirtyAt;
tome.emit('readable', was);
if (tome.hasOwnProperty('__parent__')) {
markDirty(tome.__parent__, dirtyAt);
}
}
function diff(tome, op, val, chain, pair, was) {
var root = tome.__root__;
tome.__root__.__version__ += 1;
if (!chain) {
chain = Tome.buildChain(tome);
}
var newOp = { chain: chain, op: op };
if (val !== undefined) {
newOp.val = val;
}
root.__diff__.push(newOp);
markDirty(tome, root.__version__, was);
if (pair) {
markDirty(pair, root.__version__, pair);
}
}
function arrayInit(tome, val, seen) {
// An ArrayTome has two non-enumerable properties:
// - _arr: Holds the actual array that we reference.
// - length: Holds the length of the array in _arr.
if (!tome.hasOwnProperty('_arr')) {
Object.defineProperty(tome, '_arr', { configurable: true, writable: true });
}
if (!tome.hasOwnProperty('length')) {
Object.defineProperty(tome, 'length', { configurable: true, writable: true });
}
// val is an array so we take its length and instantiate a new array of
// the appropriate size in _arr. We already know the length so we
// assign that as well.
var len = val.length;
tome._arr = new Array(len);
tome.length = len;
// We go through each element in val and conjure a new Tome based on that
// value with a reference to this tome as its parent. We also assign
// properties with references to those new array elements. We need this
// so we can do things like myTome[3].on('readable', function () {});
// One additional special case that bears mentioning here is when an
// array element has undefined as its value. When that element goes
// through JSON.stringify it turns into null. We handle that by having
// an UndefinedTome type and making its toJSON method return null. Also,
// that element does not show up in hasOwnProperty, so we do not assign
// a property for that element.
for (var i = 0; i < len; i += 1) {
if (Tome.typeOf(val[i]) === 'object' || Tome.typeOf(val[i]) === 'array') {
if (!seen) {
seen = [];
}
if (seen.indexOf(val[i]) !== -1) {
throw new TypeError('Converting circular structure to Tome');
}
seen.push(val[i]);
}
tome._arr[i] = conjure(val[i], tome, i, seen);
// We use hasOwnProperty here because arrays instantiated with new
// have elements, but no keys ie. new Array(1) is different from
// [undefined].
if (val.hasOwnProperty(i)) {
tome[i] = tome._arr[i];
}
}
for (i = 0; i < len; i += 1) {
// We want to emit add after the values have all been assigned.
// Otherwise, we would have unassigned values in the array.
// Additionally, we always emit the value from _arr since the key may
// not exist.
emitAdd(tome, i);
}
}
function emptyInit() {
}
function objectInit(tome, val, seen) {
// An ObjectTome is a Tome that holds other Tomes. It has no
// non-enumerable properties. Every property of an ObjectTome is an
// instance of another Tome.
// There is one special case we need to handle with the ObjectTome type
// and that is when the value of a property is undefined. To match
// javascript's behavior we assign undefined directly to the property
// instead of creating an UndefinedTome since when you JSON.stringify an
// object with a property that has undefined as its value, it will
// leave that property out. This is different behavior from arrays
// which will stringify undefined elements to null.
var keys = Object.keys(val);
var len = keys.length;
var key;
for (var i = 0; i < len; i += 1) {
key = keys[i];
var kv = val[key];
// Here we are detecting circular references, they can only exist
// within objects & arrays so we check that first.
var kvType = Tome.typeOf(kv);
if (kvType === 'object' || kvType === 'array') {
// there are multiple entry points to objectInit, primarily through
// Tome.conjure, but also inside of assign. If we come in via
// assign, seen will be empty so we can initialize it here since
// this is the starting point for any objects that get conjured
// that way.
if (!seen) {
seen = [];
}
if (seen.indexOf(kv) !== -1) {
throw new TypeError('Converting circular structure to Tome');
}
seen.push(kv);
}
tome[key] = kv === undefined ? undefined : conjure(kv, tome, key, seen);
}
// Just like with arrays, we only want to emit add after we are done
// assigning values. We used Object.keys to get an array of all the
// properties we assigned so we can use it again to do the emission of
// adds. We also need to pay special attention when emitting add on
// undefined keys.
for (i = 0; i < len; i += 1) {
key = keys[i];
emitAdd(tome, key);
}
}
function primitiveInit(tome, val) {
if (!tome.hasOwnProperty('_val')) {
Object.defineProperty(tome, '_val', { configurable: true, writable: true });
}
// Some browsers have a hard time with valueOf. We ran into an issue on IOS
// 6 where val.valueOf was throwing a TypeError even though we know for
// sure it has a valueOf method. Esoteric browser issues are not fun.
tome._val = val.constructor.prototype.valueOf.call(val);
}
var initMap = {
"array": arrayInit,
"boolean": primitiveInit,
"null": emptyInit,
"number": primitiveInit,
"object": objectInit,
"string": primitiveInit,
"undefined": emptyInit
};
function ArrayTome(parent, key) {
Tome.call(this, parent, key);
}
function BooleanTome(parent, key) {
Tome.call(this, parent, key);
}
function NullTome(parent, key) {
Tome.call(this, parent, key);
}
function NumberTome(parent, key) {
Tome.call(this, parent, key);
}
function ObjectTome(parent, key) {
Tome.call(this, parent, key);
}
function StringTome(parent, key) {
Tome.call(this, parent, key);
}
function UndefinedTome(parent, key) {
Tome.call(this, parent, key);
}
var tomeMap = {
"array": ArrayTome,
"boolean": BooleanTome,
"null": NullTome,
"number": NumberTome,
"object": ObjectTome,
"string": StringTome,
"undefined": UndefinedTome
};
var types = Object.keys(tomeMap);
inherits(Tome, EventEmitter);
types.forEach(function (type) {
var typedTome = tomeMap[type];
inherits(typedTome, Tome);
Tome[typedTome.name] = typedTome;
});
// Every Tome is an EventEmitter, we can listen for four different events:
//
// - add: Emitted when a Tome receives a new property. Emits the key and
// the value of the property added. This event is only emitted on
// the Tome that received a new property and does not traverse up
// the Tome chain. An add event is always accompanied by a signal
// that does traverse up the Tome chain.
//
// - del: Emitted when deleting a property from a Tome. Emits the key of
// the property that was deleted. This event is only emitted on the
// Tome whose property was deleted and does not traverse up the
// Tome chain. A del event is always accompanied by a signal event
// that does traverse up the Tome chain. Additionally, the Tome
// that was deleted and all of it's children will also emit a
// destroy event.
//
// - destroy: Emitted when a Tome has been deleted. We use this to tell all
// interested parties that the Tome no longer exists and will not
// emit any more events.
//
// - readable: Emitted when a Tome or any of its child Tomes are altered.
//
module.exports = exports = Tome;
Tome.isTome = function (o) {
// If it's literally undefined or null, it's not a Tome.
if (o === undefined || o === null || typeof o !== 'object') {
return false;
}
// If it's inherit from the local Tome then it's obviously a Tome
if (o instanceof Tome) {
return true;
}
var proto;
// Getting the prototype's prototype's of the object
// Recent browsers use the folowing method instead of the getter `__proto__`
if (Object.hasOwnProperty('getPrototypeOf')) {
proto = Object.getPrototypeOf(Object.getPrototypeOf(o));
} else {
proto = o.__proto__ && o.__proto__.__proto__;
}
if (!proto || !proto.constructor) {
return false;
}
// It's only a tome if the constructor is called 'Tome'
var name = proto.constructor.name || proto.constructor.toString().match(/function (\w*)/)[1];
return name === 'Tome';
};
var isArray = Array.isArray;
Tome.typeOf = function (v) {
// We use this function to identify a value's data type. We pay special
// attention to array and null as JavaScript currently considers these
// objects. This also works on Tomes.
if (isArray(v)) {
return 'array';
}
if (v === null) {
return 'null';
}
if (Tome.isTome(v)) {
return v.typeOf();
}
return typeof v;
};
function conjure(val, parent, key, seen) {
// We instantiate a new Tome object by using the Tome.conjure method.
// It will return a new Tome of the appropriate type for our value with Tome
// inherited. This is also how we pass parent into our Tome so we can signal
// a parent that its child has been modified.
var vType = Tome.typeOf(val);
var ClassRef = tomeMap[vType];
var vInit = initMap[vType];
if (vType === 'undefined' && Tome.typeOf(parent) !== 'array') {
throw new TypeError('Tome.conjure - You can only set array elements to undefined.');
}
if (ClassRef === undefined) {
throw new TypeError('Tome.conjure - Invalid value type: ' + vType);
}
var newTome = new ClassRef(parent, key);
vInit(newTome, val, seen);
return newTome;
}
Tome.conjure = function (val, parent, key) {
var seen = [ val ];
return conjure(val, parent, key, seen);
};
Tome.destroy = function (tome) {
if (!Tome.isTome(tome)) {
throw new TypeError('Tome.destroy - You can only destroy Tomes.');
}
destroy(tome);
};
Tome.prototype.is = function (val) {
if (!arguments.length) {
return !!this.valueOf();
}
var x = this.valueOf();
var y = Tome.isTome(val) ? val.valueOf() : val;
if (x === y) {
// 0 === -0, but they are not identical
return x !== 0 || 1 / x === 1 / y;
}
// NaN !== NaN, but they are identical.
// NaNs are the only non-reflexive value, i.e., if x !== x,
// then x is a NaN.
// isNaN is broken: it converts its argument to number, so
// isNaN("foo") => true
return x !== x && y !== y;
};
Tome.prototype.isDirty = function () {
// When we mark a Tome as dirty, we set dirty to the new version from the
// root tome. This way, we can know when the diff for that operation has
// been read by comparing the root Tome's version minus the the number of
// unread diffs against this tome's version.
return this.__dirty__ > this.__root__.__version__ - this.__root__.__diff__.length;
};
Tome.prototype.getVersion = function () {
return this.__root__.__version__;
};
Tome.prototype.getKey = function () {
return this.__key__;
};
Tome.prototype.getParent = function () {
return this.__parent__;
};
Tome.prototype.unTome = function () {
if (this.__dirty__ === this.__untomed__.version) {
return this.__untomed__.cached;
}
var cached = Tome.unTome(this);
this.__untomed__.version = this.__dirty__;
this.__untomed__.cached = cached;
return cached;
};
Tome.prototype.destroy = function () {
return Tome.destroy(this);
};
Tome.prototype.set = function (key, val) {
// We use this to set a property on a Tome to the specified value. This can
// either be a new property in which case we'd emit add and signal, or we
// assign a new value to an existing value, destroying the old value.
// If we try to assign an undefined value to a property, it will only have
// an effect on ObjectTomes, otherwise it will do nothing. This mimics
// JavaScript's behavior.
var tomeType = this.typeOf();
var valType = Tome.typeOf(val);
if (valType === 'undefined') {
if (tomeType === 'object') {
this[key] = undefined;
diff(this, 'del', key);
}
return undefined;
}
if (tomeType !== 'object') {
// Only ObjectTomes can have properties, therefore we reset the Tome to
// the Tome type and then turn it into an ObjectTome. ArrayTome has its
// own set method which falls through to this one if the key is not a
// number.
this.__root__.emit('typeChange', this, tomeType, 'object');
reset(this);
this.__proto__ = ObjectTome.prototype;
}
if (!this.hasOwnProperty(key)) {
// This is a new property, we conjure a new Tome with a type based on
// the type of the value and assign it to the property. Then we emit an
// add event followed by a signal which goes up the Tome chain.
this[key] = Tome.conjure(val, this, key);
emitAdd(this, key);
diff(this, 'set', { key: key, val: val });
// We've already assigned the value to the property so we return this.
return this;
}
var p = this[key];
if (p === undefined) {
// This property exists, but has undefined as its value. We need to
// conjure a Tome to assign a value to it.
this[key] = Tome.conjure(val, this, key);
diff(this, 'set', { key: key, val: val });
// We've already assigned the value to the property so we return this.
return this;
}
if (!Tome.isTome(p)) {
// If this key is not a Tome, complain loudly.
throw new TypeError('Tome.set - Key is not a Tome: ' + key);
}
// And finally, assign the value to the property. This will make sure the
// property is the correct type for the value and emit the signal event.
p.assign(val);
return this;
};
Tome.prototype.assign = function (val) {
val = Tome.unTome(val);
// First we need to get the type of the value and the type of the Tome to
// ensure we match the Tome type to the value type.
var vType = Tome.typeOf(val);
var vClass = tomeMap[vType];
var vInit = initMap[vType];
var pType = this.typeOf();
if (vClass === undefined) {
throw new TypeError('Tome.assign - Invalid value type: ' + vType);
}
if (vType === 'undefined' && (!this.hasOwnProperty('__parent__') || this.__parent__.typeOf() !== 'array')) {
throw new TypeError('Tome.assign - You can only assign undefined to ArrayTome elements');
}
// The simplest cases are boolean, number, and string. If we already have
// the correct Tome type we assign the value, signal, and return our new
// value.
if (vType === pType) {
if (pType === 'boolean' || pType === 'number' || pType === 'string') {
// If we already have the value then just return the value.
if (this._val === val.valueOf()) {
return this;
}
var oldVal = this._val;
this._val = val.valueOf();
diff(this, 'assign', val.valueOf(), null, null, oldVal);
return this;
}
if (vType === 'null') {
return this;
}
if (vType === 'undefined') {
return;
}
}
this.__root__.emit('typeChange', this, pType, vType);
// If we're dealing with an array or object we need to reset the Tome.
if (vType === 'array' || vType === 'object' || pType === 'array' || pType === 'object') {
reset(this);
}
// Now we need to apply a new Tome type based on the value type.
this.__proto__ = vClass.prototype;
vInit(this, val ? val.valueOf() : val);
diff(this, 'assign', val);
return this;
};
Tome.prototype.del = function (key) {
// The del method is used to delete a property from a Tome. The key must
// exist and be a Tome. The Tome will emit a del event with the name of the
// property that was deleted and destory will be emitted by the property
// that was deleted as well as all of its child Tomes. Finally, the Tome will
// also signal that it was changed which also signals all the way up the
// Tome chain.
if (!this.hasOwnProperty(key)) {
throw new ReferenceError('Tome.del - Key is not defined: ' + key);
}
if (!Tome.isTome(this[key])) {
throw new TypeError('Tome.del - Key is not a Tome: ' + key);
}
var o = this[key];
delete this[key];
destroy(o);
emitDel(this, key);
diff(this, 'del', key);
return this;
};
Tome.prototype.move = function (key, newParent, onewKey) {
if (!this.hasOwnProperty(key)) {
throw new ReferenceError('Tome.move - Key is not defined: ' + key);
}
if (onewKey !== undefined && !Tome.isTome(newParent)) {
throw new TypeError('Tome.move - new parent must be a Tome');
} else if (onewKey === undefined && !Tome.isTome(newParent)) {
onewKey = newParent;
newParent = this;
}
if (newParent === this) {
var rO = {};
rO[key] = onewKey;
return this.rename(rO);
}
if (onewKey === undefined) {
onewKey = key;
}
var newKey = parseInt(onewKey, 10);
var newParentType = newParent.typeOf();
if (newKey < 0 && newParentType === 'array') {
return this;
}
// Make a copy of the chains before we move them. For use in the diff.
var newParentChain = Tome.buildChain(newParent);
var oldParentChain = Tome.buildChain(this);
// convert (if not already the case) the newParent to an ObjectTome if:
// - the key is not numeric, or:
// - the key is numeric, but the parent is not an ArrayTome
// if the newKey that you're adding to newParent is numeric, allow it only
// if newParent is an ArrayTome, else (if needed) convert newParent into an
// ObjectTome.
var keyIsNumeric = (onewKey.toString() === newKey.toString());
if (!keyIsNumeric || (keyIsNumeric && newParentType !== 'array')) {
// use the string version of the newKey
newKey = onewKey;
// ensure newParent is an ObjectTome
if (newParentType !== 'object') {
newParent.__root__.emit('typeChange', newParent, newParentType, 'object');
reset(newParent);
newParent.__proto__ = ObjectTome.prototype;
}
}
// add newKey to newParent
if (newParentType === 'array') {
var arr = newParent._arr;
var len = arr.length;
arr[newKey] = this[key];
newParent[newKey] = arr[newKey];
// If the newKey is longer than the length of the array, fill to that
// point.
if (newKey >= len) {
for (var i = len; i < newKey - 1; i += 1) {
arr[i] = Tome.conjure(undefined, this, i);
emitAdd(this, i);
}
this.length = arr.length;
}
} else {
newParent[newKey] = this[key];
}
// remove key from oldParent.
if (this.typeOf() === 'array') {
// if oldParent is a tome, create an undefinedTome in it's place.
this._arr[key] = Tome.conjure(undefined, this, key);
this[key] = this._arr[key];
} else {
delete this[key];
}
// fix up newKey to reflect it's new location.
newParent[newKey].__parent__ = newParent;
newParent[newKey].__key__ = newKey;
newParent[newKey].__root__ = newParent.__root__;
// now emit the addition and deletion of the keys.
emitDel(this, key);
emitAdd(newParent, newKey);
if (this.__root__ === newParent.__root__) {
var moveOp = { key: key, newParent: newParentChain };
if (newKey !== key) {
moveOp.newKey = newKey;
}
diff(this, 'move', moveOp, oldParentChain, newParent);
} else {
diff(this, 'del', key);
diff(newParent, 'set', { key: newKey, val: newParent[newKey].valueOf() });
}
return this;
};
Tome.prototype.readAll = function () {
// Sometimes you want to just get all the diffs at once instead of
// incrementally, readAll does just that.
var out = this.__root__.__diff__;
this.__root__.__diff__ = [];
return out;
};
Tome.prototype.read = function () {
// Diffs are automatically buffered by default. They are stored on the root Tome and are
// cleared as they are read.
var out = this.__root__.__diff__.shift();
// We return null to match streams behavior.
return out || null;
};
Tome.prototype.merge = function (diff) {
// merge is used to apply diffs to our Tomes. Typically the diff would be a
// parsed JSON string or come directly from another Tome.
var diffs = Tome.typeOf(diff) === 'array' ? diff : [ diff ];
for (var i = 0, len = diffs.length; i < len; i += 1) {
var currentDiff = diffs[i];
var tome = Tome.resolveChain(this, currentDiff.chain);
var newParent;
var opVal = currentDiff.val;
switch (currentDiff.op) {
case 'assign':
tome.assign(opVal);
break;
case 'del':
tome.del(opVal);
break;
case 'move':
newParent = Tome.resolveChain(this, opVal.newParent);
tome.move(opVal.key, newParent, opVal.newKey);
break;
case 'pop':
tome.pop();
break;
case 'push':
tome.push.apply(tome, opVal);
break;
case 'rename':
tome.rename(opVal);
break;
case 'reverse':
tome.reverse();
break;
case 'set':
tome.set(opVal.key, opVal.val);