-
Notifications
You must be signed in to change notification settings - Fork 102
/
colyseus.dev.js
5083 lines (4897 loc) · 187 KB
/
colyseus.dev.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
/*! colyseus.js@0.13.0-alpha.10 */
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["Colyseus"] = factory();
else
root["Colyseus"] = factory();
})(self || this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 15);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __spreadArrays = (this && this.__spreadArrays) || function () {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
};
Object.defineProperty(exports, "__esModule", { value: true });
var ArraySchema = /** @class */ (function (_super) {
__extends(ArraySchema, _super);
function ArraySchema() {
var items = [];
for (var _i = 0; _i < arguments.length; _i++) {
items[_i] = arguments[_i];
}
var _this = _super.apply(this, items) || this;
Object.setPrototypeOf(_this, Object.create(ArraySchema.prototype));
Object.defineProperties(_this, {
$sorting: { value: undefined, enumerable: false, writable: true },
$changes: { value: undefined, enumerable: false, writable: true },
onAdd: { value: undefined, enumerable: false, writable: true },
onRemove: { value: undefined, enumerable: false, writable: true },
onChange: { value: undefined, enumerable: false, writable: true },
triggerAll: {
value: function () {
if (!_this.onAdd) {
return;
}
for (var i = 0; i < _this.length; i++) {
_this.onAdd(_this[i], i);
}
}
},
toJSON: {
value: function () {
var arr = [];
for (var i = 0; i < _this.length; i++) {
var objAt = _this[i];
arr.push((typeof (objAt.toJSON) === "function")
? objAt.toJSON()
: objAt);
}
return arr;
}
},
clone: {
value: function (isDecoding) {
var cloned;
if (isDecoding) {
cloned = ArraySchema.of.apply(ArraySchema, _this);
cloned.onAdd = _this.onAdd;
cloned.onRemove = _this.onRemove;
cloned.onChange = _this.onChange;
}
else {
cloned = new (ArraySchema.bind.apply(ArraySchema, __spreadArrays([void 0], _this.map(function (item) {
if (typeof (item) === "object") {
return item.clone();
}
else {
return item;
}
}))))();
}
return cloned;
}
}
});
return _this;
}
Object.defineProperty(ArraySchema, Symbol.species, {
get: function () { return ArraySchema; },
enumerable: true,
configurable: true
});
ArraySchema.prototype.sort = function (compareFn) {
this.$sorting = true;
_super.prototype.sort.call(this, compareFn);
if (this.$changes) { // allow to .slice() + .sort()
var changes = Array.from(this.$changes.changes);
for (var _i = 0, changes_1 = changes; _i < changes_1.length; _i++) {
var key = changes_1[_i];
// track index change
var previousIndex = this.$changes.getIndex(this[key]);
if (previousIndex !== undefined) {
this.$changes.mapIndexChange(this[key], previousIndex);
}
this.$changes.mapIndex(this[key], key);
}
}
this.$sorting = false;
return this;
};
ArraySchema.prototype.filter = function (callbackfn, thisArg) {
var filtered = _super.prototype.filter.call(this, callbackfn);
// TODO: apply removed items on $changes
filtered.$changes = this.$changes;
return filtered;
};
ArraySchema.prototype.splice = function (start, deleteCount) {
var insert = [];
for (var _i = 2; _i < arguments.length; _i++) {
insert[_i - 2] = arguments[_i];
}
var removedItems = Array.prototype.splice.apply(this, arguments);
var movedItems = Array.prototype.filter.call(this, function (item, idx) {
return idx >= start + deleteCount - 1;
});
removedItems.map(function (removedItem) {
var $changes = removedItem && removedItem.$changes;
// If the removed item is a schema we need to update it.
if ($changes) {
$changes.parent.deleteIndex(removedItem);
delete $changes.parent;
}
});
movedItems.forEach(function (movedItem) {
// If the moved item is a schema we need to update it.
var $changes = movedItem && movedItem.$changes;
if ($changes) {
// Update current index in parent, so subsequent changes in
// this item's properties are correctly reflected.
$changes.parentField--;
}
});
return removedItems;
};
return ArraySchema;
}(Array));
exports.ArraySchema = ArraySchema;
//# sourceMappingURL=ArraySchema.js.map
/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var MapSchema = /** @class */ (function () {
function MapSchema(obj) {
var _this = this;
if (obj === void 0) { obj = {}; }
for (var key in obj) {
this[key] = obj[key];
}
Object.defineProperties(this, {
$changes: { value: undefined, enumerable: false, writable: true },
onAdd: { value: undefined, enumerable: false, writable: true },
onRemove: { value: undefined, enumerable: false, writable: true },
onChange: { value: undefined, enumerable: false, writable: true },
clone: {
value: function (isDecoding) {
var cloned;
if (isDecoding) {
// client-side
cloned = Object.assign(new MapSchema(), _this);
cloned.onAdd = _this.onAdd;
cloned.onRemove = _this.onRemove;
cloned.onChange = _this.onChange;
}
else {
// server-side
var cloned_1 = new MapSchema();
for (var key in _this) {
if (typeof (_this[key]) === "object") {
cloned_1[key] = _this[key].clone();
}
else {
cloned_1[key] = _this[key];
}
}
}
return cloned;
}
},
triggerAll: {
value: function () {
if (!_this.onAdd) {
return;
}
for (var key in _this) {
_this.onAdd(_this[key], key);
}
}
},
toJSON: {
value: function () {
var map = {};
for (var key in _this) {
map[key] = (typeof (_this[key].toJSON) === "function")
? _this[key].toJSON()
: _this[key];
}
return map;
}
},
_indexes: { value: new Map(), enumerable: false, writable: true },
_updateIndexes: {
value: function (allKeys) {
var index = 0;
var indexes = new Map();
for (var _i = 0, allKeys_1 = allKeys; _i < allKeys_1.length; _i++) {
var key = allKeys_1[_i];
indexes.set(key, index++);
}
_this._indexes = indexes;
}
},
});
}
return MapSchema;
}());
exports.MapSchema = MapSchema;
//# sourceMappingURL=MapSchema.js.map
/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
var spec_1 = __webpack_require__(10);
var encode = __webpack_require__(8);
var decode = __webpack_require__(9);
var ArraySchema_1 = __webpack_require__(0);
var MapSchema_1 = __webpack_require__(1);
var ChangeTree_1 = __webpack_require__(13);
var EventEmitter_1 = __webpack_require__(34);
var EncodeSchemaError = /** @class */ (function (_super) {
__extends(EncodeSchemaError, _super);
function EncodeSchemaError() {
return _super !== null && _super.apply(this, arguments) || this;
}
return EncodeSchemaError;
}(Error));
function assertType(value, type, klass, field) {
var typeofTarget;
var allowNull = false;
switch (type) {
case "number":
case "int8":
case "uint8":
case "int16":
case "uint16":
case "int32":
case "uint32":
case "int64":
case "uint64":
case "float32":
case "float64":
typeofTarget = "number";
if (isNaN(value)) {
console.log("trying to encode \"NaN\" in " + klass.constructor.name + "#" + field);
}
break;
case "string":
typeofTarget = "string";
allowNull = true;
break;
case "boolean":
// boolean is always encoded as true/false based on truthiness
return;
}
if (typeof (value) !== typeofTarget && (!allowNull || (allowNull && value !== null))) {
var foundValue = "'" + JSON.stringify(value) + "'" + (value && value.constructor && " (" + value.constructor.name + ")");
throw new EncodeSchemaError("a '" + typeofTarget + "' was expected, but " + foundValue + " was provided in " + klass.constructor.name + "#" + field);
}
}
function assertInstanceType(value, type, klass, field) {
if (!(value instanceof type)) {
throw new EncodeSchemaError("a '" + type.name + "' was expected, but '" + value.constructor.name + "' was provided in " + klass.constructor.name + "#" + field);
}
}
function encodePrimitiveType(type, bytes, value, klass, field) {
assertType(value, type, klass, field);
var encodeFunc = encode[type];
if (encodeFunc) {
encodeFunc(bytes, value);
}
else {
throw new EncodeSchemaError("a '" + type + "' was expected, but " + value + " was provided in " + klass.constructor.name + "#" + field);
}
}
function decodePrimitiveType(type, bytes, it) {
return decode[type](bytes, it);
}
/**
* Schema encoder / decoder
*/
var Schema = /** @class */ (function () {
// allow inherited classes to have a constructor
function Schema() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
// fix enumerability of fields for end-user
Object.defineProperties(this, {
$changes: {
value: new ChangeTree_1.ChangeTree(this._indexes),
enumerable: false,
writable: true
},
$listeners: {
value: {},
enumerable: false,
writable: true
},
});
var descriptors = this._descriptors;
if (descriptors) {
Object.defineProperties(this, descriptors);
}
}
Schema.onError = function (e) {
console.error(e);
};
Object.defineProperty(Schema.prototype, "_schema", {
get: function () { return this.constructor._schema; },
enumerable: true,
configurable: true
});
Object.defineProperty(Schema.prototype, "_descriptors", {
get: function () { return this.constructor._descriptors; },
enumerable: true,
configurable: true
});
Object.defineProperty(Schema.prototype, "_indexes", {
get: function () { return this.constructor._indexes; },
enumerable: true,
configurable: true
});
Object.defineProperty(Schema.prototype, "_fieldsByIndex", {
get: function () { return this.constructor._fieldsByIndex; },
enumerable: true,
configurable: true
});
Object.defineProperty(Schema.prototype, "_filters", {
get: function () { return this.constructor._filters; },
enumerable: true,
configurable: true
});
Object.defineProperty(Schema.prototype, "_deprecated", {
get: function () { return this.constructor._deprecated; },
enumerable: true,
configurable: true
});
Object.defineProperty(Schema.prototype, "$changed", {
get: function () { return this.$changes.changed; },
enumerable: true,
configurable: true
});
Schema.prototype.listen = function (attr, callback) {
var _this = this;
if (!this.$listeners[attr]) {
this.$listeners[attr] = new EventEmitter_1.EventEmitter();
}
this.$listeners[attr].register(callback);
// return un-register callback.
return function () {
return _this.$listeners[attr].remove(callback);
};
};
Schema.prototype.decode = function (bytes, it) {
if (it === void 0) { it = { offset: 0 }; }
var changes = [];
var schema = this._schema;
var fieldsByIndex = this._fieldsByIndex;
var totalBytes = bytes.length;
// skip TYPE_ID of existing instances
if (bytes[it.offset] === spec_1.TYPE_ID) {
it.offset += 2;
}
var _loop_1 = function () {
var isNil = decode.nilCheck(bytes, it) && ++it.offset;
var index = bytes[it.offset++];
if (index === spec_1.END_OF_STRUCTURE) {
return "break";
}
var field = fieldsByIndex[index];
var _field = "_" + field;
var type = schema[field];
var value = void 0;
var hasChange = false;
if (!field) {
return "continue";
}
else if (isNil) {
value = null;
hasChange = true;
}
else if (type._schema) {
value = this_1[_field] || this_1.createTypeInstance(bytes, it, type);
value.decode(bytes, it);
hasChange = true;
}
else if (Array.isArray(type)) {
type = type[0];
var valueRef_1 = this_1[_field] || new ArraySchema_1.ArraySchema();
value = valueRef_1.clone(true);
var newLength_1 = decode.number(bytes, it);
var numChanges = Math.min(decode.number(bytes, it), newLength_1);
var hasRemoval = (value.length > newLength_1);
hasChange = (numChanges > 0) || hasRemoval;
// FIXME: this may not be reliable. possibly need to encode this variable during serialization
var hasIndexChange = false;
// ensure current array has the same length as encoded one
if (hasRemoval) {
// decrease removed items from number of changes.
// no need to iterate through them, as they're going to be removed.
Array.prototype.splice.call(value, newLength_1).forEach(function (itemRemoved, i) {
if (itemRemoved && itemRemoved.onRemove) {
try {
itemRemoved.onRemove();
}
catch (e) {
Schema.onError(e);
}
}
if (valueRef_1.onRemove) {
try {
valueRef_1.onRemove(itemRemoved, newLength_1 + i);
}
catch (e) {
Schema.onError(e);
}
}
});
}
for (var i = 0; i < numChanges; i++) {
var newIndex = decode.number(bytes, it);
var indexChangedFrom = void 0; // index change check
if (decode.indexChangeCheck(bytes, it)) {
decode.uint8(bytes, it);
indexChangedFrom = decode.number(bytes, it);
hasIndexChange = true;
}
var isNew = (!hasIndexChange && value[newIndex] === undefined) || (hasIndexChange && indexChangedFrom === undefined);
if (type.prototype instanceof Schema) {
var item = void 0;
if (isNew) {
item = this_1.createTypeInstance(bytes, it, type);
}
else if (indexChangedFrom !== undefined) {
item = valueRef_1[indexChangedFrom];
}
else {
item = valueRef_1[newIndex];
}
if (!item) {
item = this_1.createTypeInstance(bytes, it, type);
isNew = true;
}
item.decode(bytes, it);
value[newIndex] = item;
}
else {
value[newIndex] = decodePrimitiveType(type, bytes, it);
}
if (isNew) {
if (valueRef_1.onAdd) {
try {
valueRef_1.onAdd(value[newIndex], newIndex);
}
catch (e) {
Schema.onError(e);
}
}
}
else if (valueRef_1.onChange) {
try {
valueRef_1.onChange(value[newIndex], newIndex);
}
catch (e) {
Schema.onError(e);
}
}
}
}
else if (type.map) {
type = type.map;
var valueRef = this_1[_field] || new MapSchema_1.MapSchema();
value = valueRef.clone(true);
var length = decode.number(bytes, it);
hasChange = (length > 0);
// FIXME: this may not be reliable. possibly need to encode this variable during
// serializagion
var hasIndexChange = false;
var previousKeys = Object.keys(valueRef);
for (var i = 0; i < length; i++) {
// `encodeAll` may indicate a higher number of indexes it actually encodes
// TODO: do not encode a higher number than actual encoded entries
if (bytes[it.offset] === undefined ||
bytes[it.offset] === spec_1.END_OF_STRUCTURE) {
break;
}
var isNilItem = decode.nilCheck(bytes, it) && ++it.offset;
// index change check
var previousKey = void 0;
if (decode.indexChangeCheck(bytes, it)) {
decode.uint8(bytes, it);
previousKey = previousKeys[decode.number(bytes, it)];
hasIndexChange = true;
}
var hasMapIndex = decode.numberCheck(bytes, it);
var isSchemaType = typeof (type) !== "string";
var newKey = (hasMapIndex)
? previousKeys[decode.number(bytes, it)]
: decode.string(bytes, it);
var item = void 0;
var isNew = (!hasIndexChange && valueRef[newKey] === undefined) || (hasIndexChange && previousKey === undefined && hasMapIndex);
if (isNew && isSchemaType) {
item = this_1.createTypeInstance(bytes, it, type);
}
else if (previousKey !== undefined) {
item = valueRef[previousKey];
}
else {
item = valueRef[newKey];
}
if (isNilItem) {
if (item && item.onRemove) {
try {
item.onRemove();
}
catch (e) {
Schema.onError(e);
}
}
if (valueRef.onRemove) {
try {
valueRef.onRemove(item, newKey);
}
catch (e) {
Schema.onError(e);
}
}
delete value[newKey];
continue;
}
else if (!isSchemaType) {
value[newKey] = decodePrimitiveType(type, bytes, it);
}
else {
item.decode(bytes, it);
value[newKey] = item;
}
if (isNew) {
if (valueRef.onAdd) {
try {
valueRef.onAdd(value[newKey], newKey);
}
catch (e) {
Schema.onError(e);
}
}
}
else if (valueRef.onChange) {
try {
valueRef.onChange(value[newKey], newKey);
}
catch (e) {
Schema.onError(e);
}
}
}
}
else {
value = decodePrimitiveType(type, bytes, it);
// FIXME: should not even have encoded if value haven't changed in the first place!
// check FilterTest.ts: "should not trigger `onChange` if field haven't changed"
hasChange = (value !== this_1[_field]);
}
if (hasChange && (this_1.onChange || this_1.$listeners[field])) {
changes.push({
field: field,
value: value,
previousValue: this_1[_field]
});
}
this_1[_field] = value;
};
var this_1 = this;
while (it.offset < totalBytes) {
var state_1 = _loop_1();
if (state_1 === "break")
break;
}
this._triggerChanges(changes);
return this;
};
Schema.prototype.encode = function (root, encodeAll, client, bytes) {
var _this = this;
if (root === void 0) { root = this; }
if (encodeAll === void 0) { encodeAll = false; }
if (bytes === void 0) { bytes = []; }
// skip if nothing has changed
if (!this.$changes.changed && !encodeAll) {
this._encodeEndOfStructure(this, root, bytes);
return bytes;
}
var schema = this._schema;
var indexes = this._indexes;
var fieldsByIndex = this._fieldsByIndex;
var filters = this._filters;
var changes = Array.from((encodeAll) // || client
? this.$changes.allChanges
: this.$changes.changes).sort();
var _loop_2 = function (i, l) {
var field = fieldsByIndex[changes[i]] || changes[i];
var _field = "_" + field;
var type = schema[field];
var filter = (filters && filters[field]);
// const value = (filter && this.$allChanges[field]) || changes[field];
var value = this_2[_field];
var fieldIndex = indexes[field];
if (value === undefined) {
encode.uint8(bytes, spec_1.NIL);
encode.number(bytes, fieldIndex);
}
else if (type._schema) {
if (client && filter) {
// skip if not allowed by custom filter
if (!filter.call(this_2, client, value, root)) {
return "continue";
}
}
if (!value) {
// value has been removed
encode.uint8(bytes, spec_1.NIL);
encode.number(bytes, fieldIndex);
}
else {
// encode child object
encode.number(bytes, fieldIndex);
assertInstanceType(value, type, this_2, field);
this_2.tryEncodeTypeId(bytes, type, value.constructor);
value.encode(root, encodeAll, client, bytes);
}
}
else if (Array.isArray(type)) {
var $changes = value.$changes;
if (client && filter) {
// skip if not allowed by custom filter
if (!filter.call(this_2, client, value, root)) {
return "continue";
}
}
encode.number(bytes, fieldIndex);
// total number of items in the array
encode.number(bytes, value.length);
var arrayChanges = Array.from((encodeAll) // || client
? $changes.allChanges
: $changes.changes)
.filter(function (index) { return _this[_field][index] !== undefined; })
.sort(function (a, b) { return a - b; });
// ensure number of changes doesn't exceed array length
var numChanges = arrayChanges.length;
// number of changed items
encode.number(bytes, numChanges);
var isChildSchema = typeof (type[0]) !== "string";
// assert ArraySchema was provided
assertInstanceType(this_2[_field], ArraySchema_1.ArraySchema, this_2, field);
// encode Array of type
for (var j = 0; j < numChanges; j++) {
var index = arrayChanges[j];
var item = this_2[_field][index];
/**
* TODO: filter array by items instead of the whole object
*/
// if (client && filter) {
// // skip if not allowed by custom filter
// if (!filter.call(this, client, item, root)) {
// continue;
// }
// }
if (isChildSchema) { // is array of Schema
encode.number(bytes, index);
if (!encodeAll) {
var indexChange = $changes.getIndexChange(item);
if (indexChange !== undefined) {
encode.uint8(bytes, spec_1.INDEX_CHANGE);
encode.number(bytes, indexChange);
}
}
assertInstanceType(item, type[0], this_2, field);
this_2.tryEncodeTypeId(bytes, type[0], item.constructor);
item.encode(root, encodeAll, client, bytes);
}
else if (item !== undefined) { // is array of primitives
encode.number(bytes, index);
encodePrimitiveType(type[0], bytes, item, this_2, field);
}
}
if (!encodeAll && !client) {
$changes.discard();
}
}
else if (type.map) {
var $changes = value.$changes;
if (client && filter) {
// skip if not allowed by custom filter
if (!filter.call(this_2, client, value, root)) {
return "continue";
}
}
// encode Map of type
encode.number(bytes, fieldIndex);
// TODO: during `encodeAll`, removed entries are not going to be encoded
var keys = Array.from((encodeAll) // || client
? $changes.allChanges
: $changes.changes);
encode.number(bytes, keys.length);
// const previousKeys = Object.keys(this[_field]); // this is costly!
var previousKeys = Array.from($changes.allChanges);
var isChildSchema = typeof (type.map) !== "string";
var numChanges = keys.length;
// assert MapSchema was provided
assertInstanceType(this_2[_field], MapSchema_1.MapSchema, this_2, field);
for (var i_1 = 0; i_1 < numChanges; i_1++) {
var key = keys[i_1];
var item = this_2[_field][key];
var mapItemIndex = undefined;
/**
* TODO: filter map by items instead of the whole object
*/
// if (client && filter) {
// // skip if not allowed by custom filter
// if (!filter.call(this, client, item, root)) {
// continue;
// }
// }
if (encodeAll) {
if (item === undefined) {
// previously deleted items are skipped during `encodeAll`
continue;
}
}
else {
// encode index change
var indexChange = $changes.getIndexChange(item);
if (item && indexChange !== undefined) {
encode.uint8(bytes, spec_1.INDEX_CHANGE);
encode.number(bytes, this_2[_field]._indexes.get(indexChange));
}
/**
* - Allow item replacement
* - Allow to use the index of a deleted item to encode as NIL
*/
mapItemIndex = (!$changes.isDeleted(key) || !item)
? this_2[_field]._indexes.get(key)
: undefined;
}
var isNil = (item === undefined);
/**
* Invert NIL to prevent collision with data starting with NIL byte
*/
if (isNil) {
// TODO: remove item
// console.log("REMOVE KEY INDEX", { key });
// this[_field]._indexes.delete(key);
encode.uint8(bytes, spec_1.NIL);
}
if (mapItemIndex !== undefined) {
encode.number(bytes, mapItemIndex);
}
else {
encode.string(bytes, key);
}
if (item && isChildSchema) {
assertInstanceType(item, type.map, this_2, field);
this_2.tryEncodeTypeId(bytes, type.map, item.constructor);
item.encode(root, encodeAll, client, bytes);
}
else if (!isNil) {
encodePrimitiveType(type.map, bytes, item, this_2, field);
}
}
if (!encodeAll && !client) {
$changes.discard();
// TODO: track array/map indexes per client (for filtering)?
// TODO: do not iterate though all MapSchema indexes here.
this_2[_field]._updateIndexes(previousKeys);
}
}
else {
if (client && filter) {
// skip if not allowed by custom filter
if (!filter.call(this_2, client, value, root)) {
return "continue";
}
}
encode.number(bytes, fieldIndex);
encodePrimitiveType(type, bytes, value, this_2, field);
}
};
var this_2 = this;
for (var i = 0, l = changes.length; i < l; i++) {
_loop_2(i, l);
}
// flag end of Schema object structure
this._encodeEndOfStructure(this, root, bytes);
if (!encodeAll && !client) {
this.$changes.discard();
}
return bytes;
};
Schema.prototype.encodeFiltered = function (client, bytes) {
return this.encode(this, false, client, bytes);
};
Schema.prototype.encodeAll = function (bytes) {
return this.encode(this, true, undefined, bytes);
};
Schema.prototype.encodeAllFiltered = function (client, bytes) {
return this.encode(this, true, client, bytes);
};
Schema.prototype.clone = function () {
var cloned = new (this.constructor);
var schema = this._schema;
for (var field in schema) {
if (typeof (this[field]) === "object" &&
typeof (this[field].clone) === "function") {
// deep clone
cloned[field] = this[field].clone();
}
else {
// primitive values
cloned[field] = this[field];
}
}
return cloned;
};
Schema.prototype.triggerAll = function () {
var changes = [];
var schema = this._schema;
for (var field in schema) {
if (this[field] !== undefined) {
changes.push({
field: field,
value: this[field],
previousValue: undefined
});
}
}
try {
this._triggerChanges(changes);
}
catch (e) {
Schema.onError(e);
}
};
Schema.prototype.toJSON = function () {
var schema = this._schema;
var deprecated = this._deprecated;
var obj = {};
for (var field in schema) {
if (!deprecated[field] && this[field] !== null && typeof (this[field]) !== "undefined") {
obj[field] = (typeof (this[field].toJSON) === "function")
? this[field].toJSON()
: this["_" + field];
}
}
return obj;
};
Schema.prototype.discardAllChanges = function () {
var schema = this._schema;
var changes = Array.from(this.$changes.changes);
var fieldsByIndex = this._fieldsByIndex;
for (var index in changes) {