@colyseus/schema 3.0.52 → 3.0.53

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2189,7 +2189,7 @@
2189
2189
  const allChangesIndex = this.items.findIndex(item => item === this.items[0]);
2190
2190
  changeTree.delete(index, exports.OPERATION.DELETE, allChangesIndex);
2191
2191
  changeTree.shiftAllChangeIndexes(-1, allChangesIndex);
2192
- // this.deletedIndexes[index] = true;
2192
+ this.deletedIndexes[index] = true;
2193
2193
  return this.items.shift();
2194
2194
  }
2195
2195
  /**
@@ -2824,448 +2824,174 @@
2824
2824
  }
2825
2825
  registerType("map", { constructor: MapSchema });
2826
2826
 
2827
- const DEFAULT_VIEW_TAG = -1;
2828
- function entity(constructor) {
2829
- TypeContext.register(constructor);
2830
- return constructor;
2831
- }
2832
- /**
2833
- * [See documentation](https://docs.colyseus.io/state/schema/)
2834
- *
2835
- * Annotate a Schema property to be serializeable.
2836
- * \@type()'d fields are automatically flagged as "dirty" for the next patch.
2837
- *
2838
- * @example Standard usage, with automatic change tracking.
2839
- * ```
2840
- * \@type("string") propertyName: string;
2841
- * ```
2842
- *
2843
- * @example You can provide the "manual" option if you'd like to manually control your patches via .setDirty().
2844
- * ```
2845
- * \@type("string", { manual: true })
2846
- * ```
2847
- */
2848
- // export function type(type: DefinitionType, options?: TypeOptions) {
2849
- // return function ({ get, set }, context: ClassAccessorDecoratorContext): ClassAccessorDecoratorResult<Schema, any> {
2850
- // if (context.kind !== "accessor") {
2851
- // throw new Error("@type() is only supported for class accessor properties");
2852
- // }
2853
- // const field = context.name.toString();
2854
- // //
2855
- // // detect index for this field, considering inheritance
2856
- // //
2857
- // const parent = Object.getPrototypeOf(context.metadata);
2858
- // let fieldIndex: number = context.metadata[$numFields] // current structure already has fields defined
2859
- // ?? (parent && parent[$numFields]) // parent structure has fields defined
2860
- // ?? -1; // no fields defined
2861
- // fieldIndex++;
2862
- // if (
2863
- // !parent && // the parent already initializes the `$changes` property
2864
- // !Metadata.hasFields(context.metadata)
2865
- // ) {
2866
- // context.addInitializer(function (this: Ref) {
2867
- // Object.defineProperty(this, $changes, {
2868
- // value: new ChangeTree(this),
2869
- // enumerable: false,
2870
- // writable: true
2871
- // });
2872
- // });
2873
- // }
2874
- // Metadata.addField(context.metadata, fieldIndex, field, type);
2875
- // const isArray = ArraySchema.is(type);
2876
- // const isMap = !isArray && MapSchema.is(type);
2877
- // // if (options && options.manual) {
2878
- // // // do not declare getter/setter descriptor
2879
- // // definition.descriptors[field] = {
2880
- // // enumerable: true,
2881
- // // configurable: true,
2882
- // // writable: true,
2883
- // // };
2884
- // // return;
2885
- // // }
2886
- // return {
2887
- // init(value) {
2888
- // // TODO: may need to convert ArraySchema/MapSchema here
2889
- // // do not flag change if value is undefined.
2890
- // if (value !== undefined) {
2891
- // this[$changes].change(fieldIndex);
2892
- // // automaticallty transform Array into ArraySchema
2893
- // if (isArray) {
2894
- // if (!(value instanceof ArraySchema)) {
2895
- // value = new ArraySchema(...value);
2896
- // }
2897
- // value[$childType] = Object.values(type)[0];
2898
- // }
2899
- // // automaticallty transform Map into MapSchema
2900
- // if (isMap) {
2901
- // if (!(value instanceof MapSchema)) {
2902
- // value = new MapSchema(value);
2903
- // }
2904
- // value[$childType] = Object.values(type)[0];
2905
- // }
2906
- // // try to turn provided structure into a Proxy
2907
- // if (value['$proxy'] === undefined) {
2908
- // if (isMap) {
2909
- // value = getMapProxy(value);
2910
- // }
2911
- // }
2912
- // }
2913
- // return value;
2914
- // },
2915
- // get() {
2916
- // return get.call(this);
2917
- // },
2918
- // set(value: any) {
2919
- // /**
2920
- // * Create Proxy for array or map items
2921
- // */
2922
- // // skip if value is the same as cached.
2923
- // if (value === get.call(this)) {
2924
- // return;
2925
- // }
2926
- // if (
2927
- // value !== undefined &&
2928
- // value !== null
2929
- // ) {
2930
- // // automaticallty transform Array into ArraySchema
2931
- // if (isArray) {
2932
- // if (!(value instanceof ArraySchema)) {
2933
- // value = new ArraySchema(...value);
2934
- // }
2935
- // value[$childType] = Object.values(type)[0];
2936
- // }
2937
- // // automaticallty transform Map into MapSchema
2938
- // if (isMap) {
2939
- // if (!(value instanceof MapSchema)) {
2940
- // value = new MapSchema(value);
2941
- // }
2942
- // value[$childType] = Object.values(type)[0];
2943
- // }
2944
- // // try to turn provided structure into a Proxy
2945
- // if (value['$proxy'] === undefined) {
2946
- // if (isMap) {
2947
- // value = getMapProxy(value);
2948
- // }
2949
- // }
2950
- // // flag the change for encoding.
2951
- // this[$changes].change(fieldIndex);
2952
- // //
2953
- // // call setParent() recursively for this and its child
2954
- // // structures.
2955
- // //
2956
- // if (value[$changes]) {
2957
- // value[$changes].setParent(
2958
- // this,
2959
- // this[$changes].root,
2960
- // Metadata.getIndex(context.metadata, field),
2961
- // );
2962
- // }
2963
- // } else if (get.call(this)) {
2964
- // //
2965
- // // Setting a field to `null` or `undefined` will delete it.
2966
- // //
2967
- // this[$changes].delete(field);
2968
- // }
2969
- // set.call(this, value);
2970
- // },
2971
- // };
2972
- // }
2973
- // }
2974
- function view(tag = DEFAULT_VIEW_TAG) {
2975
- return function (target, fieldName) {
2976
- const constructor = target.constructor;
2977
- const parentClass = Object.getPrototypeOf(constructor);
2978
- const parentMetadata = parentClass[Symbol.metadata];
2979
- // TODO: use Metadata.initialize()
2980
- const metadata = (constructor[Symbol.metadata] ??= Object.assign({}, constructor[Symbol.metadata], parentMetadata ?? Object.create(null)));
2981
- // const fieldIndex = metadata[fieldName];
2982
- // if (!metadata[fieldIndex]) {
2983
- // //
2984
- // // detect index for this field, considering inheritance
2985
- // //
2986
- // metadata[fieldIndex] = {
2987
- // type: undefined,
2988
- // index: (metadata[$numFields] // current structure already has fields defined
2989
- // ?? (parentMetadata && parentMetadata[$numFields]) // parent structure has fields defined
2990
- // ?? -1) + 1 // no fields defined
2991
- // }
2992
- // }
2993
- Metadata.setTag(metadata, fieldName, tag);
2994
- };
2995
- }
2996
- function type(type, options) {
2997
- return function (target, field) {
2998
- const constructor = target.constructor;
2999
- if (!type) {
3000
- throw new Error(`${constructor.name}: @type() reference provided for "${field}" is undefined. Make sure you don't have any circular dependencies.`);
3001
- }
3002
- // for inheritance support
3003
- TypeContext.register(constructor);
3004
- const parentClass = Object.getPrototypeOf(constructor);
3005
- const parentMetadata = parentClass[Symbol.metadata];
3006
- const metadata = Metadata.initialize(constructor);
3007
- let fieldIndex = metadata[field];
3008
- /**
3009
- * skip if descriptor already exists for this field (`@deprecated()`)
3010
- */
3011
- if (metadata[fieldIndex] !== undefined) {
3012
- if (metadata[fieldIndex].deprecated) {
3013
- // do not create accessors for deprecated properties.
3014
- return;
3015
- }
3016
- else if (metadata[fieldIndex].type !== undefined) {
3017
- // trying to define same property multiple times across inheritance.
3018
- // https://github.com/colyseus/colyseus-unity3d/issues/131#issuecomment-814308572
3019
- try {
3020
- throw new Error(`@colyseus/schema: Duplicate '${field}' definition on '${constructor.name}'.\nCheck @type() annotation`);
3021
- }
3022
- catch (e) {
3023
- const definitionAtLine = e.stack.split("\n")[4].trim();
3024
- throw new Error(`${e.message} ${definitionAtLine}`);
3025
- }
3026
- }
2827
+ var _a$2, _b$2;
2828
+ class CollectionSchema {
2829
+ static { this[_a$2] = encodeKeyValueOperation; }
2830
+ static { this[_b$2] = decodeKeyValueOperation; }
2831
+ /**
2832
+ * Determine if a property must be filtered.
2833
+ * - If returns false, the property is NOT going to be encoded.
2834
+ * - If returns true, the property is going to be encoded.
2835
+ *
2836
+ * Encoding with "filters" happens in two steps:
2837
+ * - First, the encoder iterates over all "not owned" properties and encodes them.
2838
+ * - Then, the encoder iterates over all "owned" properties per instance and encodes them.
2839
+ */
2840
+ static [(_a$2 = $encoder, _b$2 = $decoder, $filter)](ref, index, view) {
2841
+ return (!view ||
2842
+ typeof (ref[$childType]) === "string" ||
2843
+ view.isChangeTreeVisible((ref[$getByIndex](index) ?? ref.deletedItems[index])[$changes]));
2844
+ }
2845
+ static is(type) {
2846
+ return type['collection'] !== undefined;
2847
+ }
2848
+ constructor(initialValues) {
2849
+ this.$items = new Map();
2850
+ this.$indexes = new Map();
2851
+ this.deletedItems = {};
2852
+ this.$refId = 0;
2853
+ this[$changes] = new ChangeTree(this);
2854
+ this[$changes].indexes = {};
2855
+ if (initialValues) {
2856
+ initialValues.forEach((v) => this.add(v));
3027
2857
  }
3028
- else {
3029
- //
3030
- // detect index for this field, considering inheritance
3031
- //
3032
- fieldIndex = metadata[$numFields] // current structure already has fields defined
3033
- ?? (parentMetadata && parentMetadata[$numFields]) // parent structure has fields defined
3034
- ?? -1; // no fields defined
3035
- fieldIndex++;
2858
+ Object.defineProperty(this, $childType, {
2859
+ value: undefined,
2860
+ enumerable: false,
2861
+ writable: true,
2862
+ configurable: true,
2863
+ });
2864
+ }
2865
+ add(value) {
2866
+ // set "index" for reference.
2867
+ const index = this.$refId++;
2868
+ const isRef = (value[$changes]) !== undefined;
2869
+ if (isRef) {
2870
+ value[$changes].setParent(this, this[$changes].root, index);
3036
2871
  }
3037
- if (options && options.manual) {
3038
- Metadata.addField(metadata, fieldIndex, field, type, {
3039
- // do not declare getter/setter descriptor
3040
- enumerable: true,
3041
- configurable: true,
3042
- writable: true,
3043
- });
3044
- }
3045
- else {
3046
- const complexTypeKlass = (Array.isArray(type))
3047
- ? getType("array")
3048
- : (typeof (Object.keys(type)[0]) === "string") && getType(Object.keys(type)[0]);
3049
- const childType = (complexTypeKlass)
3050
- ? Object.values(type)[0]
3051
- : type;
3052
- Metadata.addField(metadata, fieldIndex, field, type, getPropertyDescriptor(`_${field}`, fieldIndex, childType, complexTypeKlass));
3053
- }
3054
- };
3055
- }
3056
- function getPropertyDescriptor(fieldCached, fieldIndex, type, complexTypeKlass) {
3057
- return {
3058
- get: function () { return this[fieldCached]; },
3059
- set: function (value) {
3060
- const previousValue = this[fieldCached] ?? undefined;
3061
- // skip if value is the same as cached.
3062
- if (value === previousValue) {
3063
- return;
3064
- }
3065
- if (value !== undefined &&
3066
- value !== null) {
3067
- if (complexTypeKlass) {
3068
- // automaticallty transform Array into ArraySchema
3069
- if (complexTypeKlass.constructor === ArraySchema && !(value instanceof ArraySchema)) {
3070
- value = new ArraySchema(...value);
3071
- }
3072
- // automaticallty transform Map into MapSchema
3073
- if (complexTypeKlass.constructor === MapSchema && !(value instanceof MapSchema)) {
3074
- value = new MapSchema(value);
3075
- }
3076
- value[$childType] = type;
3077
- }
3078
- else if (typeof (type) !== "string") {
3079
- assertInstanceType(value, type, this, fieldCached.substring(1));
3080
- }
3081
- else {
3082
- assertType(value, type, this, fieldCached.substring(1));
3083
- }
3084
- const changeTree = this[$changes];
3085
- //
3086
- // Replacing existing "ref", remove it from root.
3087
- //
3088
- if (previousValue !== undefined && previousValue[$changes]) {
3089
- changeTree.root?.remove(previousValue[$changes]);
3090
- this.constructor[$track](changeTree, fieldIndex, exports.OPERATION.DELETE_AND_ADD);
3091
- }
3092
- else {
3093
- this.constructor[$track](changeTree, fieldIndex, exports.OPERATION.ADD);
3094
- }
3095
- //
3096
- // call setParent() recursively for this and its child
3097
- // structures.
3098
- //
3099
- value[$changes]?.setParent(this, changeTree.root, fieldIndex);
3100
- }
3101
- else if (previousValue !== undefined) {
3102
- //
3103
- // Setting a field to `null` or `undefined` will delete it.
3104
- //
3105
- this[$changes].delete(fieldIndex);
3106
- }
3107
- this[fieldCached] = value;
3108
- },
3109
- enumerable: true,
3110
- configurable: true
3111
- };
3112
- }
3113
- /**
3114
- * `@deprecated()` flag a field as deprecated.
3115
- * The previous `@type()` annotation should remain along with this one.
3116
- */
3117
- function deprecated(throws = true) {
3118
- return function (klass, field) {
3119
- //
3120
- // FIXME: the following block of code is repeated across `@type()`, `@deprecated()` and `@unreliable()` decorators.
3121
- //
3122
- const constructor = klass.constructor;
3123
- const parentClass = Object.getPrototypeOf(constructor);
3124
- const parentMetadata = parentClass[Symbol.metadata];
3125
- const metadata = (constructor[Symbol.metadata] ??= Object.assign({}, constructor[Symbol.metadata], parentMetadata ?? Object.create(null)));
3126
- const fieldIndex = metadata[field];
3127
- // if (!metadata[field]) {
3128
- // //
3129
- // // detect index for this field, considering inheritance
3130
- // //
3131
- // metadata[field] = {
3132
- // type: undefined,
3133
- // index: (metadata[$numFields] // current structure already has fields defined
3134
- // ?? (parentMetadata && parentMetadata[$numFields]) // parent structure has fields defined
3135
- // ?? -1) + 1 // no fields defined
3136
- // }
3137
- // }
3138
- metadata[fieldIndex].deprecated = true;
3139
- if (throws) {
3140
- metadata[$descriptors] ??= {};
3141
- metadata[$descriptors][field] = {
3142
- get: function () { throw new Error(`${field} is deprecated.`); },
3143
- set: function (value) { },
3144
- enumerable: false,
3145
- configurable: true
3146
- };
3147
- }
3148
- // flag metadata[field] as non-enumerable
3149
- Object.defineProperty(metadata, fieldIndex, {
3150
- value: metadata[fieldIndex],
3151
- enumerable: false,
3152
- configurable: true
3153
- });
3154
- };
3155
- }
3156
- function defineTypes(target, fields, options) {
3157
- for (let field in fields) {
3158
- type(fields[field], options)(target.prototype, field);
2872
+ this[$changes].indexes[index] = index;
2873
+ this.$indexes.set(index, index);
2874
+ this.$items.set(index, value);
2875
+ this[$changes].change(index);
2876
+ return index;
3159
2877
  }
3160
- return target;
3161
- }
3162
- function schema(fieldsAndMethods, name, inherits = Schema) {
3163
- const fields = {};
3164
- const methods = {};
3165
- const defaultValues = {};
3166
- const viewTagFields = {};
3167
- for (let fieldName in fieldsAndMethods) {
3168
- const value = fieldsAndMethods[fieldName];
3169
- if (typeof (value) === "object") {
3170
- if (value['default'] !== undefined) {
3171
- defaultValues[fieldName] = value['default'];
2878
+ at(index) {
2879
+ const key = Array.from(this.$items.keys())[index];
2880
+ return this.$items.get(key);
2881
+ }
2882
+ entries() {
2883
+ return this.$items.entries();
2884
+ }
2885
+ delete(item) {
2886
+ const entries = this.$items.entries();
2887
+ let index;
2888
+ let entry;
2889
+ while (entry = entries.next()) {
2890
+ if (entry.done) {
2891
+ break;
3172
2892
  }
3173
- if (value['view'] !== undefined) {
3174
- viewTagFields[fieldName] = (typeof (value['view']) === "boolean")
3175
- ? DEFAULT_VIEW_TAG
3176
- : value['view'];
2893
+ if (item === entry.value[1]) {
2894
+ index = entry.value[0];
2895
+ break;
3177
2896
  }
3178
- fields[fieldName] = value;
3179
- }
3180
- else if (typeof (value) === "function") {
3181
- methods[fieldName] = value;
3182
2897
  }
3183
- else {
3184
- fields[fieldName] = value;
2898
+ if (index === undefined) {
2899
+ return false;
3185
2900
  }
2901
+ this.deletedItems[index] = this[$changes].delete(index);
2902
+ this.$indexes.delete(index);
2903
+ return this.$items.delete(index);
3186
2904
  }
3187
- const klass = Metadata.setFields(class extends inherits {
3188
- constructor(...args) {
3189
- args[0] = Object.assign({}, defaultValues, args[0]);
3190
- super(...args);
3191
- }
3192
- }, fields);
3193
- for (let fieldName in viewTagFields) {
3194
- view(viewTagFields[fieldName])(klass.prototype, fieldName);
2905
+ clear() {
2906
+ const changeTree = this[$changes];
2907
+ // discard previous operations.
2908
+ changeTree.discard(true);
2909
+ changeTree.indexes = {};
2910
+ // remove children references
2911
+ changeTree.forEachChild((childChangeTree, _) => {
2912
+ changeTree.root?.remove(childChangeTree);
2913
+ });
2914
+ // clear previous indexes
2915
+ this.$indexes.clear();
2916
+ // clear items
2917
+ this.$items.clear();
2918
+ changeTree.operation(exports.OPERATION.CLEAR);
3195
2919
  }
3196
- for (let methodName in methods) {
3197
- klass.prototype[methodName] = methods[methodName];
2920
+ has(value) {
2921
+ return Array.from(this.$items.values()).some((v) => v === value);
3198
2922
  }
3199
- if (name) {
3200
- Object.defineProperty(klass, "name", { value: name });
2923
+ forEach(callbackfn) {
2924
+ this.$items.forEach((value, key, _) => callbackfn(value, key, this));
3201
2925
  }
3202
- klass.extends = (fields, name) => schema(fields, name, klass);
3203
- return klass;
3204
- }
3205
-
3206
- function getIndent(level) {
3207
- return (new Array(level).fill(0)).map((_, i) => (i === level - 1) ? `└─ ` : ` `).join("");
3208
- }
3209
- function dumpChanges(schema) {
3210
- const $root = schema[$changes].root;
3211
- const dump = {
3212
- ops: {},
3213
- refs: []
3214
- };
3215
- // for (const refId in $root.changes) {
3216
- let current = $root.changes.next;
3217
- while (current) {
3218
- const changeTree = current.changeTree;
3219
- // skip if ChangeTree is undefined
3220
- if (changeTree === undefined) {
3221
- current = current.next;
3222
- continue;
3223
- }
3224
- const changes = changeTree.indexedOperations;
3225
- dump.refs.push(`refId#${changeTree.refId}`);
3226
- for (const index in changes) {
3227
- const op = changes[index];
3228
- const opName = exports.OPERATION[op];
3229
- if (!dump.ops[opName]) {
3230
- dump.ops[opName] = 0;
3231
- }
3232
- dump.ops[exports.OPERATION[op]]++;
3233
- }
3234
- current = current.next;
2926
+ values() {
2927
+ return this.$items.values();
3235
2928
  }
3236
- return dump;
3237
- }
3238
-
3239
- var _a$2, _b$2;
3240
- /**
3241
- * Schema encoder / decoder
3242
- */
3243
- class Schema {
3244
- static { this[_a$2] = encodeSchemaOperation; }
3245
- static { this[_b$2] = decodeSchemaOperation; }
3246
- /**
3247
- * Assign the property descriptors required to track changes on this instance.
3248
- * @param instance
3249
- */
3250
- static initialize(instance) {
3251
- Object.defineProperty(instance, $changes, {
3252
- value: new ChangeTree(instance),
3253
- enumerable: false,
3254
- writable: true
3255
- });
3256
- Object.defineProperties(instance, instance.constructor[Symbol.metadata]?.[$descriptors] || {});
2929
+ get size() {
2930
+ return this.$items.size;
3257
2931
  }
3258
- static is(type) {
3259
- return typeof (type[Symbol.metadata]) === "object";
3260
- // const metadata = type[Symbol.metadata];
3261
- // return metadata && Object.prototype.hasOwnProperty.call(metadata, -1);
2932
+ /** Iterator */
2933
+ [Symbol.iterator]() {
2934
+ return this.$items.values();
3262
2935
  }
3263
- /**
3264
- * Track property changes
3265
- */
3266
- static [(_a$2 = $encoder, _b$2 = $decoder, $track)](changeTree, index, operation = exports.OPERATION.ADD) {
3267
- changeTree.change(index, operation);
2936
+ setIndex(index, key) {
2937
+ this.$indexes.set(index, key);
2938
+ }
2939
+ getIndex(index) {
2940
+ return this.$indexes.get(index);
2941
+ }
2942
+ [$getByIndex](index) {
2943
+ return this.$items.get(this.$indexes.get(index));
2944
+ }
2945
+ [$deleteByIndex](index) {
2946
+ const key = this.$indexes.get(index);
2947
+ this.$items.delete(key);
2948
+ this.$indexes.delete(index);
2949
+ }
2950
+ [$onEncodeEnd]() {
2951
+ this.deletedItems = {};
2952
+ }
2953
+ toArray() {
2954
+ return Array.from(this.$items.values());
2955
+ }
2956
+ toJSON() {
2957
+ const values = [];
2958
+ this.forEach((value, key) => {
2959
+ values.push((typeof (value['toJSON']) === "function")
2960
+ ? value['toJSON']()
2961
+ : value);
2962
+ });
2963
+ return values;
2964
+ }
2965
+ //
2966
+ // Decoding utilities
2967
+ //
2968
+ clone(isDecoding) {
2969
+ let cloned;
2970
+ if (isDecoding) {
2971
+ // client-side
2972
+ cloned = Object.assign(new CollectionSchema(), this);
2973
+ }
2974
+ else {
2975
+ // server-side
2976
+ cloned = new CollectionSchema();
2977
+ this.forEach((value) => {
2978
+ if (value[$changes]) {
2979
+ cloned.add(value['clone']());
2980
+ }
2981
+ else {
2982
+ cloned.add(value);
2983
+ }
2984
+ });
2985
+ }
2986
+ return cloned;
3268
2987
  }
2988
+ }
2989
+ registerType("collection", { constructor: CollectionSchema, });
2990
+
2991
+ var _a$1, _b$1;
2992
+ class SetSchema {
2993
+ static { this[_a$1] = encodeKeyValueOperation; }
2994
+ static { this[_b$1] = decodeKeyValueOperation; }
3269
2995
  /**
3270
2996
  * Determine if a property must be filtered.
3271
2997
  * - If returns false, the property is NOT going to be encoded.
@@ -3275,418 +3001,652 @@
3275
3001
  * - First, the encoder iterates over all "not owned" properties and encodes them.
3276
3002
  * - Then, the encoder iterates over all "owned" properties per instance and encodes them.
3277
3003
  */
3278
- static [$filter](ref, index, view) {
3279
- const metadata = ref.constructor[Symbol.metadata];
3280
- const tag = metadata[index]?.tag;
3281
- if (view === undefined) {
3282
- // shared pass/encode: encode if doesn't have a tag
3283
- return tag === undefined;
3284
- }
3285
- else if (tag === undefined) {
3286
- // view pass: no tag
3287
- return true;
3288
- }
3289
- else if (tag === DEFAULT_VIEW_TAG) {
3290
- // view pass: default tag
3291
- return view.isChangeTreeVisible(ref[$changes]);
3292
- }
3293
- else {
3294
- // view pass: custom tag
3295
- const tags = view.tags?.get(ref[$changes]);
3296
- return tags && tags.has(tag);
3297
- }
3004
+ static [(_a$1 = $encoder, _b$1 = $decoder, $filter)](ref, index, view) {
3005
+ return (!view ||
3006
+ typeof (ref[$childType]) === "string" ||
3007
+ view.visible.has((ref[$getByIndex](index) ?? ref.deletedItems[index])[$changes]));
3298
3008
  }
3299
- // allow inherited classes to have a constructor
3300
- constructor(...args) {
3301
- //
3302
- // inline
3303
- // Schema.initialize(this);
3304
- //
3305
- Schema.initialize(this);
3306
- //
3307
- // Assign initial values
3308
- //
3309
- if (args[0]) {
3310
- Object.assign(this, args[0]);
3009
+ static is(type) {
3010
+ return type['set'] !== undefined;
3011
+ }
3012
+ constructor(initialValues) {
3013
+ this.$items = new Map();
3014
+ this.$indexes = new Map();
3015
+ this.deletedItems = {};
3016
+ this.$refId = 0;
3017
+ this[$changes] = new ChangeTree(this);
3018
+ this[$changes].indexes = {};
3019
+ if (initialValues) {
3020
+ initialValues.forEach((v) => this.add(v));
3311
3021
  }
3022
+ Object.defineProperty(this, $childType, {
3023
+ value: undefined,
3024
+ enumerable: false,
3025
+ writable: true,
3026
+ configurable: true,
3027
+ });
3312
3028
  }
3313
- assign(props) {
3314
- Object.assign(this, props);
3315
- return this;
3029
+ add(value) {
3030
+ // immediatelly return false if value already added.
3031
+ if (this.has(value)) {
3032
+ return false;
3033
+ }
3034
+ // set "index" for reference.
3035
+ const index = this.$refId++;
3036
+ if ((value[$changes]) !== undefined) {
3037
+ value[$changes].setParent(this, this[$changes].root, index);
3038
+ }
3039
+ const operation = this[$changes].indexes[index]?.op ?? exports.OPERATION.ADD;
3040
+ this[$changes].indexes[index] = index;
3041
+ this.$indexes.set(index, index);
3042
+ this.$items.set(index, value);
3043
+ this[$changes].change(index, operation);
3044
+ return index;
3316
3045
  }
3317
- /**
3318
- * (Server-side): Flag a property to be encoded for the next patch.
3319
- * @param instance Schema instance
3320
- * @param property string representing the property name, or number representing the index of the property.
3321
- * @param operation OPERATION to perform (detected automatically)
3322
- */
3323
- setDirty(property, operation) {
3324
- const metadata = this.constructor[Symbol.metadata];
3325
- this[$changes].change(metadata[metadata[property]].index, operation);
3046
+ entries() {
3047
+ return this.$items.entries();
3326
3048
  }
3327
- clone() {
3328
- const cloned = new (this.constructor);
3329
- const metadata = this.constructor[Symbol.metadata];
3330
- //
3331
- // TODO: clone all properties, not only annotated ones
3332
- //
3333
- // for (const field in this) {
3334
- for (const fieldIndex in metadata) {
3335
- // const field = metadata[metadata[fieldIndex]].name;
3336
- const field = metadata[fieldIndex].name;
3337
- if (typeof (this[field]) === "object" &&
3338
- typeof (this[field]?.clone) === "function") {
3339
- // deep clone
3340
- cloned[field] = this[field].clone();
3049
+ delete(item) {
3050
+ const entries = this.$items.entries();
3051
+ let index;
3052
+ let entry;
3053
+ while (entry = entries.next()) {
3054
+ if (entry.done) {
3055
+ break;
3341
3056
  }
3342
- else {
3343
- // primitive values
3344
- cloned[field] = this[field];
3057
+ if (item === entry.value[1]) {
3058
+ index = entry.value[0];
3059
+ break;
3345
3060
  }
3346
3061
  }
3347
- return cloned;
3062
+ if (index === undefined) {
3063
+ return false;
3064
+ }
3065
+ this.deletedItems[index] = this[$changes].delete(index);
3066
+ this.$indexes.delete(index);
3067
+ return this.$items.delete(index);
3348
3068
  }
3349
- toJSON() {
3350
- const obj = {};
3351
- const metadata = this.constructor[Symbol.metadata];
3352
- for (const index in metadata) {
3353
- const field = metadata[index];
3354
- const fieldName = field.name;
3355
- if (!field.deprecated && this[fieldName] !== null && typeof (this[fieldName]) !== "undefined") {
3356
- obj[fieldName] = (typeof (this[fieldName]['toJSON']) === "function")
3357
- ? this[fieldName]['toJSON']()
3358
- : this[fieldName];
3069
+ clear() {
3070
+ const changeTree = this[$changes];
3071
+ // discard previous operations.
3072
+ changeTree.discard(true);
3073
+ changeTree.indexes = {};
3074
+ // clear previous indexes
3075
+ this.$indexes.clear();
3076
+ // clear items
3077
+ this.$items.clear();
3078
+ changeTree.operation(exports.OPERATION.CLEAR);
3079
+ }
3080
+ has(value) {
3081
+ const values = this.$items.values();
3082
+ let has = false;
3083
+ let entry;
3084
+ while (entry = values.next()) {
3085
+ if (entry.done) {
3086
+ break;
3087
+ }
3088
+ if (value === entry.value) {
3089
+ has = true;
3090
+ break;
3359
3091
  }
3360
3092
  }
3361
- return obj;
3093
+ return has;
3362
3094
  }
3363
- /**
3364
- * Used in tests only
3365
- * @internal
3366
- */
3367
- discardAllChanges() {
3368
- this[$changes].discardAll();
3095
+ forEach(callbackfn) {
3096
+ this.$items.forEach((value, key, _) => callbackfn(value, key, this));
3097
+ }
3098
+ values() {
3099
+ return this.$items.values();
3100
+ }
3101
+ get size() {
3102
+ return this.$items.size;
3103
+ }
3104
+ /** Iterator */
3105
+ [Symbol.iterator]() {
3106
+ return this.$items.values();
3107
+ }
3108
+ setIndex(index, key) {
3109
+ this.$indexes.set(index, key);
3110
+ }
3111
+ getIndex(index) {
3112
+ return this.$indexes.get(index);
3369
3113
  }
3370
3114
  [$getByIndex](index) {
3371
- const metadata = this.constructor[Symbol.metadata];
3372
- return this[metadata[index].name];
3115
+ return this.$items.get(this.$indexes.get(index));
3373
3116
  }
3374
3117
  [$deleteByIndex](index) {
3375
- const metadata = this.constructor[Symbol.metadata];
3376
- this[metadata[index].name] = undefined;
3118
+ const key = this.$indexes.get(index);
3119
+ this.$items.delete(key);
3120
+ this.$indexes.delete(index);
3377
3121
  }
3378
- /**
3379
- * Inspect the `refId` of all Schema instances in the tree. Optionally display the contents of the instance.
3380
- *
3381
- * @param ref Schema instance
3382
- * @param showContents display JSON contents of the instance
3383
- * @returns
3384
- */
3385
- static debugRefIds(ref, showContents = false, level = 0, decoder, keyPrefix = "") {
3386
- const contents = (showContents) ? ` - ${JSON.stringify(ref.toJSON())}` : "";
3387
- const changeTree = ref[$changes];
3388
- const refId = (decoder) ? decoder.root.refIds.get(ref) : changeTree.refId;
3389
- const root = (decoder) ? decoder.root : changeTree.root;
3390
- // log reference count if > 1
3391
- const refCount = (root?.refCount?.[refId] > 1)
3392
- ? ` [×${root.refCount[refId]}]`
3393
- : '';
3394
- let output = `${getIndent(level)}${keyPrefix}${ref.constructor.name} (refId: ${refId})${refCount}${contents}\n`;
3395
- changeTree.forEachChild((childChangeTree, indexOrKey) => {
3396
- let key = indexOrKey;
3397
- if (typeof indexOrKey === 'number' && ref['$indexes']) {
3398
- // MapSchema
3399
- key = ref['$indexes'].get(indexOrKey) ?? indexOrKey;
3400
- }
3401
- const keyPrefix = (ref['forEach'] !== undefined && key !== undefined) ? `["${key}"]: ` : "";
3402
- output += this.debugRefIds(childChangeTree.ref, showContents, level + 1, decoder, keyPrefix);
3403
- });
3404
- return output;
3122
+ [$onEncodeEnd]() {
3123
+ this.deletedItems = {};
3405
3124
  }
3406
- static debugRefIdEncodingOrder(ref, changeSet = 'allChanges') {
3407
- let encodeOrder = [];
3408
- let current = ref[$changes].root[changeSet].next;
3409
- while (current) {
3410
- if (current.changeTree) {
3411
- encodeOrder.push(current.changeTree.refId);
3412
- }
3413
- current = current.next;
3414
- }
3415
- return encodeOrder;
3125
+ toArray() {
3126
+ return Array.from(this.$items.values());
3416
3127
  }
3417
- static debugRefIdsFromDecoder(decoder) {
3418
- return this.debugRefIds(decoder.state, false, 0, decoder);
3128
+ toJSON() {
3129
+ const values = [];
3130
+ this.forEach((value, key) => {
3131
+ values.push((typeof (value['toJSON']) === "function")
3132
+ ? value['toJSON']()
3133
+ : value);
3134
+ });
3135
+ return values;
3419
3136
  }
3420
- /**
3421
- * Return a string representation of the changes on a Schema instance.
3422
- * The list of changes is cleared after each encode.
3423
- *
3424
- * @param instance Schema instance
3425
- * @param isEncodeAll Return "full encode" instead of current change set.
3426
- * @returns
3427
- */
3428
- static debugChanges(instance, isEncodeAll = false) {
3429
- const changeTree = instance[$changes];
3430
- const changeSet = (isEncodeAll) ? changeTree.allChanges : changeTree.changes;
3431
- const changeSetName = (isEncodeAll) ? "allChanges" : "changes";
3432
- let output = `${instance.constructor.name} (${changeTree.refId}) -> .${changeSetName}:\n`;
3433
- function dumpChangeSet(changeSet) {
3434
- changeSet.operations
3435
- .filter(op => op)
3436
- .forEach((index) => {
3437
- const operation = changeTree.indexedOperations[index];
3438
- console.log({ index, operation });
3439
- output += `- [${index}]: ${exports.OPERATION[operation]} (${JSON.stringify(changeTree.getValue(Number(index), isEncodeAll))})\n`;
3440
- });
3441
- }
3442
- dumpChangeSet(changeSet);
3443
- // display filtered changes
3444
- if (!isEncodeAll &&
3445
- changeTree.filteredChanges &&
3446
- (changeTree.filteredChanges.operations).filter(op => op).length > 0) {
3447
- output += `${instance.constructor.name} (${changeTree.refId}) -> .filteredChanges:\n`;
3448
- dumpChangeSet(changeTree.filteredChanges);
3137
+ //
3138
+ // Decoding utilities
3139
+ //
3140
+ clone(isDecoding) {
3141
+ let cloned;
3142
+ if (isDecoding) {
3143
+ // client-side
3144
+ cloned = Object.assign(new SetSchema(), this);
3449
3145
  }
3450
- // display filtered changes
3451
- if (isEncodeAll &&
3452
- changeTree.allFilteredChanges &&
3453
- (changeTree.allFilteredChanges.operations).filter(op => op).length > 0) {
3454
- output += `${instance.constructor.name} (${changeTree.refId}) -> .allFilteredChanges:\n`;
3455
- dumpChangeSet(changeTree.allFilteredChanges);
3146
+ else {
3147
+ // server-side
3148
+ cloned = new SetSchema();
3149
+ this.forEach((value) => {
3150
+ if (value[$changes]) {
3151
+ cloned.add(value['clone']());
3152
+ }
3153
+ else {
3154
+ cloned.add(value);
3155
+ }
3156
+ });
3456
3157
  }
3457
- return output;
3158
+ return cloned;
3458
3159
  }
3459
- static debugChangesDeep(ref, changeSetName = "changes") {
3460
- let output = "";
3461
- const rootChangeTree = ref[$changes];
3462
- const root = rootChangeTree.root;
3463
- const changeTrees = new Map();
3464
- const instanceRefIds = [];
3465
- let totalOperations = 0;
3466
- // TODO: FIXME: this method is not working as expected
3467
- for (const [refId, changes] of Object.entries(root[changeSetName])) {
3468
- const changeTree = root.changeTrees[refId];
3469
- if (!changeTree) {
3470
- continue;
3160
+ }
3161
+ registerType("set", { constructor: SetSchema });
3162
+
3163
+ const DEFAULT_VIEW_TAG = -1;
3164
+ function entity(constructor) {
3165
+ TypeContext.register(constructor);
3166
+ return constructor;
3167
+ }
3168
+ /**
3169
+ * [See documentation](https://docs.colyseus.io/state/schema/)
3170
+ *
3171
+ * Annotate a Schema property to be serializeable.
3172
+ * \@type()'d fields are automatically flagged as "dirty" for the next patch.
3173
+ *
3174
+ * @example Standard usage, with automatic change tracking.
3175
+ * ```
3176
+ * \@type("string") propertyName: string;
3177
+ * ```
3178
+ *
3179
+ * @example You can provide the "manual" option if you'd like to manually control your patches via .setDirty().
3180
+ * ```
3181
+ * \@type("string", { manual: true })
3182
+ * ```
3183
+ */
3184
+ // export function type(type: DefinitionType, options?: TypeOptions) {
3185
+ // return function ({ get, set }, context: ClassAccessorDecoratorContext): ClassAccessorDecoratorResult<Schema, any> {
3186
+ // if (context.kind !== "accessor") {
3187
+ // throw new Error("@type() is only supported for class accessor properties");
3188
+ // }
3189
+ // const field = context.name.toString();
3190
+ // //
3191
+ // // detect index for this field, considering inheritance
3192
+ // //
3193
+ // const parent = Object.getPrototypeOf(context.metadata);
3194
+ // let fieldIndex: number = context.metadata[$numFields] // current structure already has fields defined
3195
+ // ?? (parent && parent[$numFields]) // parent structure has fields defined
3196
+ // ?? -1; // no fields defined
3197
+ // fieldIndex++;
3198
+ // if (
3199
+ // !parent && // the parent already initializes the `$changes` property
3200
+ // !Metadata.hasFields(context.metadata)
3201
+ // ) {
3202
+ // context.addInitializer(function (this: Ref) {
3203
+ // Object.defineProperty(this, $changes, {
3204
+ // value: new ChangeTree(this),
3205
+ // enumerable: false,
3206
+ // writable: true
3207
+ // });
3208
+ // });
3209
+ // }
3210
+ // Metadata.addField(context.metadata, fieldIndex, field, type);
3211
+ // const isArray = ArraySchema.is(type);
3212
+ // const isMap = !isArray && MapSchema.is(type);
3213
+ // // if (options && options.manual) {
3214
+ // // // do not declare getter/setter descriptor
3215
+ // // definition.descriptors[field] = {
3216
+ // // enumerable: true,
3217
+ // // configurable: true,
3218
+ // // writable: true,
3219
+ // // };
3220
+ // // return;
3221
+ // // }
3222
+ // return {
3223
+ // init(value) {
3224
+ // // TODO: may need to convert ArraySchema/MapSchema here
3225
+ // // do not flag change if value is undefined.
3226
+ // if (value !== undefined) {
3227
+ // this[$changes].change(fieldIndex);
3228
+ // // automaticallty transform Array into ArraySchema
3229
+ // if (isArray) {
3230
+ // if (!(value instanceof ArraySchema)) {
3231
+ // value = new ArraySchema(...value);
3232
+ // }
3233
+ // value[$childType] = Object.values(type)[0];
3234
+ // }
3235
+ // // automaticallty transform Map into MapSchema
3236
+ // if (isMap) {
3237
+ // if (!(value instanceof MapSchema)) {
3238
+ // value = new MapSchema(value);
3239
+ // }
3240
+ // value[$childType] = Object.values(type)[0];
3241
+ // }
3242
+ // // try to turn provided structure into a Proxy
3243
+ // if (value['$proxy'] === undefined) {
3244
+ // if (isMap) {
3245
+ // value = getMapProxy(value);
3246
+ // }
3247
+ // }
3248
+ // }
3249
+ // return value;
3250
+ // },
3251
+ // get() {
3252
+ // return get.call(this);
3253
+ // },
3254
+ // set(value: any) {
3255
+ // /**
3256
+ // * Create Proxy for array or map items
3257
+ // */
3258
+ // // skip if value is the same as cached.
3259
+ // if (value === get.call(this)) {
3260
+ // return;
3261
+ // }
3262
+ // if (
3263
+ // value !== undefined &&
3264
+ // value !== null
3265
+ // ) {
3266
+ // // automaticallty transform Array into ArraySchema
3267
+ // if (isArray) {
3268
+ // if (!(value instanceof ArraySchema)) {
3269
+ // value = new ArraySchema(...value);
3270
+ // }
3271
+ // value[$childType] = Object.values(type)[0];
3272
+ // }
3273
+ // // automaticallty transform Map into MapSchema
3274
+ // if (isMap) {
3275
+ // if (!(value instanceof MapSchema)) {
3276
+ // value = new MapSchema(value);
3277
+ // }
3278
+ // value[$childType] = Object.values(type)[0];
3279
+ // }
3280
+ // // try to turn provided structure into a Proxy
3281
+ // if (value['$proxy'] === undefined) {
3282
+ // if (isMap) {
3283
+ // value = getMapProxy(value);
3284
+ // }
3285
+ // }
3286
+ // // flag the change for encoding.
3287
+ // this[$changes].change(fieldIndex);
3288
+ // //
3289
+ // // call setParent() recursively for this and its child
3290
+ // // structures.
3291
+ // //
3292
+ // if (value[$changes]) {
3293
+ // value[$changes].setParent(
3294
+ // this,
3295
+ // this[$changes].root,
3296
+ // Metadata.getIndex(context.metadata, field),
3297
+ // );
3298
+ // }
3299
+ // } else if (get.call(this)) {
3300
+ // //
3301
+ // // Setting a field to `null` or `undefined` will delete it.
3302
+ // //
3303
+ // this[$changes].delete(field);
3304
+ // }
3305
+ // set.call(this, value);
3306
+ // },
3307
+ // };
3308
+ // }
3309
+ // }
3310
+ function view(tag = DEFAULT_VIEW_TAG) {
3311
+ return function (target, fieldName) {
3312
+ const constructor = target.constructor;
3313
+ const parentClass = Object.getPrototypeOf(constructor);
3314
+ const parentMetadata = parentClass[Symbol.metadata];
3315
+ // TODO: use Metadata.initialize()
3316
+ const metadata = (constructor[Symbol.metadata] ??= Object.assign({}, constructor[Symbol.metadata], parentMetadata ?? Object.create(null)));
3317
+ // const fieldIndex = metadata[fieldName];
3318
+ // if (!metadata[fieldIndex]) {
3319
+ // //
3320
+ // // detect index for this field, considering inheritance
3321
+ // //
3322
+ // metadata[fieldIndex] = {
3323
+ // type: undefined,
3324
+ // index: (metadata[$numFields] // current structure already has fields defined
3325
+ // ?? (parentMetadata && parentMetadata[$numFields]) // parent structure has fields defined
3326
+ // ?? -1) + 1 // no fields defined
3327
+ // }
3328
+ // }
3329
+ Metadata.setTag(metadata, fieldName, tag);
3330
+ };
3331
+ }
3332
+ function type(type, options) {
3333
+ return function (target, field) {
3334
+ const constructor = target.constructor;
3335
+ if (!type) {
3336
+ throw new Error(`${constructor.name}: @type() reference provided for "${field}" is undefined. Make sure you don't have any circular dependencies.`);
3337
+ }
3338
+ // for inheritance support
3339
+ TypeContext.register(constructor);
3340
+ const parentClass = Object.getPrototypeOf(constructor);
3341
+ const parentMetadata = parentClass[Symbol.metadata];
3342
+ const metadata = Metadata.initialize(constructor);
3343
+ let fieldIndex = metadata[field];
3344
+ /**
3345
+ * skip if descriptor already exists for this field (`@deprecated()`)
3346
+ */
3347
+ if (metadata[fieldIndex] !== undefined) {
3348
+ if (metadata[fieldIndex].deprecated) {
3349
+ // do not create accessors for deprecated properties.
3350
+ return;
3351
+ }
3352
+ else if (metadata[fieldIndex].type !== undefined) {
3353
+ // trying to define same property multiple times across inheritance.
3354
+ // https://github.com/colyseus/colyseus-unity3d/issues/131#issuecomment-814308572
3355
+ try {
3356
+ throw new Error(`@colyseus/schema: Duplicate '${field}' definition on '${constructor.name}'.\nCheck @type() annotation`);
3357
+ }
3358
+ catch (e) {
3359
+ const definitionAtLine = e.stack.split("\n")[4].trim();
3360
+ throw new Error(`${e.message} ${definitionAtLine}`);
3361
+ }
3471
3362
  }
3472
- let includeChangeTree = false;
3473
- let parentChangeTrees = [];
3474
- let parentChangeTree = changeTree.parent?.[$changes];
3475
- if (changeTree === rootChangeTree) {
3476
- includeChangeTree = true;
3363
+ }
3364
+ else {
3365
+ //
3366
+ // detect index for this field, considering inheritance
3367
+ //
3368
+ fieldIndex = metadata[$numFields] // current structure already has fields defined
3369
+ ?? (parentMetadata && parentMetadata[$numFields]) // parent structure has fields defined
3370
+ ?? -1; // no fields defined
3371
+ fieldIndex++;
3372
+ }
3373
+ if (options && options.manual) {
3374
+ Metadata.addField(metadata, fieldIndex, field, type, {
3375
+ // do not declare getter/setter descriptor
3376
+ enumerable: true,
3377
+ configurable: true,
3378
+ writable: true,
3379
+ });
3380
+ }
3381
+ else {
3382
+ const complexTypeKlass = (Array.isArray(type))
3383
+ ? getType("array")
3384
+ : (typeof (Object.keys(type)[0]) === "string") && getType(Object.keys(type)[0]);
3385
+ const childType = (complexTypeKlass)
3386
+ ? Object.values(type)[0]
3387
+ : type;
3388
+ Metadata.addField(metadata, fieldIndex, field, type, getPropertyDescriptor(`_${field}`, fieldIndex, childType, complexTypeKlass));
3389
+ }
3390
+ };
3391
+ }
3392
+ function getPropertyDescriptor(fieldCached, fieldIndex, type, complexTypeKlass) {
3393
+ return {
3394
+ get: function () { return this[fieldCached]; },
3395
+ set: function (value) {
3396
+ const previousValue = this[fieldCached] ?? undefined;
3397
+ // skip if value is the same as cached.
3398
+ if (value === previousValue) {
3399
+ return;
3477
3400
  }
3478
- else {
3479
- while (parentChangeTree !== undefined) {
3480
- parentChangeTrees.push(parentChangeTree);
3481
- if (parentChangeTree.ref === ref) {
3482
- includeChangeTree = true;
3483
- break;
3401
+ if (value !== undefined &&
3402
+ value !== null) {
3403
+ if (complexTypeKlass) {
3404
+ // automaticallty transform Array into ArraySchema
3405
+ if (complexTypeKlass.constructor === ArraySchema && !(value instanceof ArraySchema)) {
3406
+ value = new ArraySchema(...value);
3484
3407
  }
3485
- parentChangeTree = parentChangeTree.parent?.[$changes];
3408
+ // automaticallty transform Map into MapSchema
3409
+ if (complexTypeKlass.constructor === MapSchema && !(value instanceof MapSchema)) {
3410
+ value = new MapSchema(value);
3411
+ }
3412
+ value[$childType] = type;
3486
3413
  }
3487
- }
3488
- if (includeChangeTree) {
3489
- instanceRefIds.push(changeTree.refId);
3490
- totalOperations += Object.keys(changes).length;
3491
- changeTrees.set(changeTree, parentChangeTrees.reverse());
3492
- }
3493
- }
3494
- output += "---\n";
3495
- output += `root refId: ${rootChangeTree.refId}\n`;
3496
- output += `Total instances: ${instanceRefIds.length} (refIds: ${instanceRefIds.join(", ")})\n`;
3497
- output += `Total changes: ${totalOperations}\n`;
3498
- output += "---\n";
3499
- // based on root.changes, display a tree of changes that has the "ref" instance as parent
3500
- const visitedParents = new WeakSet();
3501
- for (const [changeTree, parentChangeTrees] of changeTrees.entries()) {
3502
- parentChangeTrees.forEach((parentChangeTree, level) => {
3503
- if (!visitedParents.has(parentChangeTree)) {
3504
- output += `${getIndent(level)}${parentChangeTree.ref.constructor.name} (refId: ${parentChangeTree.refId})\n`;
3505
- visitedParents.add(parentChangeTree);
3414
+ else if (typeof (type) !== "string") {
3415
+ assertInstanceType(value, type, this, fieldCached.substring(1));
3506
3416
  }
3507
- });
3508
- const changes = changeTree.indexedOperations;
3509
- const level = parentChangeTrees.length;
3510
- const indent = getIndent(level);
3511
- const parentIndex = (level > 0) ? `(${changeTree.parentIndex}) ` : "";
3512
- output += `${indent}${parentIndex}${changeTree.ref.constructor.name} (refId: ${changeTree.refId}) - changes: ${Object.keys(changes).length}\n`;
3513
- for (const index in changes) {
3514
- const operation = changes[index];
3515
- output += `${getIndent(level + 1)}${exports.OPERATION[operation]}: ${index}\n`;
3417
+ else {
3418
+ assertType(value, type, this, fieldCached.substring(1));
3419
+ }
3420
+ const changeTree = this[$changes];
3421
+ //
3422
+ // Replacing existing "ref", remove it from root.
3423
+ //
3424
+ if (previousValue !== undefined && previousValue[$changes]) {
3425
+ changeTree.root?.remove(previousValue[$changes]);
3426
+ this.constructor[$track](changeTree, fieldIndex, exports.OPERATION.DELETE_AND_ADD);
3427
+ }
3428
+ else {
3429
+ this.constructor[$track](changeTree, fieldIndex, exports.OPERATION.ADD);
3430
+ }
3431
+ //
3432
+ // call setParent() recursively for this and its child
3433
+ // structures.
3434
+ //
3435
+ value[$changes]?.setParent(this, changeTree.root, fieldIndex);
3516
3436
  }
3517
- }
3518
- return `${output}`;
3519
- }
3437
+ else if (previousValue !== undefined) {
3438
+ //
3439
+ // Setting a field to `null` or `undefined` will delete it.
3440
+ //
3441
+ this[$changes].delete(fieldIndex);
3442
+ }
3443
+ this[fieldCached] = value;
3444
+ },
3445
+ enumerable: true,
3446
+ configurable: true
3447
+ };
3520
3448
  }
3521
-
3522
- var _a$1, _b$1;
3523
- class CollectionSchema {
3524
- static { this[_a$1] = encodeKeyValueOperation; }
3525
- static { this[_b$1] = decodeKeyValueOperation; }
3526
- /**
3527
- * Determine if a property must be filtered.
3528
- * - If returns false, the property is NOT going to be encoded.
3529
- * - If returns true, the property is going to be encoded.
3530
- *
3531
- * Encoding with "filters" happens in two steps:
3532
- * - First, the encoder iterates over all "not owned" properties and encodes them.
3533
- * - Then, the encoder iterates over all "owned" properties per instance and encodes them.
3534
- */
3535
- static [(_a$1 = $encoder, _b$1 = $decoder, $filter)](ref, index, view) {
3536
- return (!view ||
3537
- typeof (ref[$childType]) === "string" ||
3538
- view.isChangeTreeVisible((ref[$getByIndex](index) ?? ref.deletedItems[index])[$changes]));
3539
- }
3540
- static is(type) {
3541
- return type['collection'] !== undefined;
3542
- }
3543
- constructor(initialValues) {
3544
- this.$items = new Map();
3545
- this.$indexes = new Map();
3546
- this.deletedItems = {};
3547
- this.$refId = 0;
3548
- this[$changes] = new ChangeTree(this);
3549
- this[$changes].indexes = {};
3550
- if (initialValues) {
3551
- initialValues.forEach((v) => this.add(v));
3449
+ /**
3450
+ * `@deprecated()` flag a field as deprecated.
3451
+ * The previous `@type()` annotation should remain along with this one.
3452
+ */
3453
+ function deprecated(throws = true) {
3454
+ return function (klass, field) {
3455
+ //
3456
+ // FIXME: the following block of code is repeated across `@type()`, `@deprecated()` and `@unreliable()` decorators.
3457
+ //
3458
+ const constructor = klass.constructor;
3459
+ const parentClass = Object.getPrototypeOf(constructor);
3460
+ const parentMetadata = parentClass[Symbol.metadata];
3461
+ const metadata = (constructor[Symbol.metadata] ??= Object.assign({}, constructor[Symbol.metadata], parentMetadata ?? Object.create(null)));
3462
+ const fieldIndex = metadata[field];
3463
+ // if (!metadata[field]) {
3464
+ // //
3465
+ // // detect index for this field, considering inheritance
3466
+ // //
3467
+ // metadata[field] = {
3468
+ // type: undefined,
3469
+ // index: (metadata[$numFields] // current structure already has fields defined
3470
+ // ?? (parentMetadata && parentMetadata[$numFields]) // parent structure has fields defined
3471
+ // ?? -1) + 1 // no fields defined
3472
+ // }
3473
+ // }
3474
+ metadata[fieldIndex].deprecated = true;
3475
+ if (throws) {
3476
+ metadata[$descriptors] ??= {};
3477
+ metadata[$descriptors][field] = {
3478
+ get: function () { throw new Error(`${field} is deprecated.`); },
3479
+ set: function (value) { },
3480
+ enumerable: false,
3481
+ configurable: true
3482
+ };
3552
3483
  }
3553
- Object.defineProperty(this, $childType, {
3554
- value: undefined,
3484
+ // flag metadata[field] as non-enumerable
3485
+ Object.defineProperty(metadata, fieldIndex, {
3486
+ value: metadata[fieldIndex],
3555
3487
  enumerable: false,
3556
- writable: true,
3557
- configurable: true,
3488
+ configurable: true
3558
3489
  });
3490
+ };
3491
+ }
3492
+ function defineTypes(target, fields, options) {
3493
+ for (let field in fields) {
3494
+ type(fields[field], options)(target.prototype, field);
3559
3495
  }
3560
- add(value) {
3561
- // set "index" for reference.
3562
- const index = this.$refId++;
3563
- const isRef = (value[$changes]) !== undefined;
3564
- if (isRef) {
3565
- value[$changes].setParent(this, this[$changes].root, index);
3496
+ return target;
3497
+ }
3498
+ function schema(fieldsAndMethods, name, inherits = Schema) {
3499
+ const fields = {};
3500
+ const methods = {};
3501
+ const defaultValues = {};
3502
+ const viewTagFields = {};
3503
+ for (let fieldName in fieldsAndMethods) {
3504
+ const value = fieldsAndMethods[fieldName];
3505
+ if (typeof (value) === "object") {
3506
+ if (value['view'] !== undefined) {
3507
+ viewTagFields[fieldName] = (typeof (value['view']) === "boolean")
3508
+ ? DEFAULT_VIEW_TAG
3509
+ : value['view'];
3510
+ }
3511
+ fields[fieldName] = value;
3512
+ // If no explicit default provided, handle automatic instantiation for collection types
3513
+ if (!Object.prototype.hasOwnProperty.call(value, 'default')) {
3514
+ if (Array.isArray(value) || value['array'] !== undefined) {
3515
+ // Collection: Array → new ArraySchema()
3516
+ defaultValues[fieldName] = new ArraySchema();
3517
+ }
3518
+ else if (value['map'] !== undefined) {
3519
+ // Collection: Map → new MapSchema()
3520
+ defaultValues[fieldName] = new MapSchema();
3521
+ }
3522
+ else if (value['collection'] !== undefined) {
3523
+ // Collection: Collection → new CollectionSchema()
3524
+ defaultValues[fieldName] = new CollectionSchema();
3525
+ }
3526
+ else if (value['set'] !== undefined) {
3527
+ // Collection: Set → new SetSchema()
3528
+ defaultValues[fieldName] = new SetSchema();
3529
+ }
3530
+ else if (value['type'] !== undefined && Schema.is(value['type'])) {
3531
+ // Direct Schema type: Type → new Type()
3532
+ defaultValues[fieldName] = new value['type']();
3533
+ }
3534
+ }
3535
+ else {
3536
+ defaultValues[fieldName] = value['default'];
3537
+ }
3566
3538
  }
3567
- this[$changes].indexes[index] = index;
3568
- this.$indexes.set(index, index);
3569
- this.$items.set(index, value);
3570
- this[$changes].change(index);
3571
- return index;
3572
- }
3573
- at(index) {
3574
- const key = Array.from(this.$items.keys())[index];
3575
- return this.$items.get(key);
3576
- }
3577
- entries() {
3578
- return this.$items.entries();
3579
- }
3580
- delete(item) {
3581
- const entries = this.$items.entries();
3582
- let index;
3583
- let entry;
3584
- while (entry = entries.next()) {
3585
- if (entry.done) {
3586
- break;
3539
+ else if (typeof (value) === "function") {
3540
+ if (Schema.is(value)) {
3541
+ // Direct Schema type: Type → new Type()
3542
+ defaultValues[fieldName] = new value();
3543
+ fields[fieldName] = value;
3587
3544
  }
3588
- if (item === entry.value[1]) {
3589
- index = entry.value[0];
3590
- break;
3545
+ else {
3546
+ methods[fieldName] = value;
3591
3547
  }
3592
3548
  }
3593
- if (index === undefined) {
3594
- return false;
3549
+ else {
3550
+ fields[fieldName] = value;
3595
3551
  }
3596
- this.deletedItems[index] = this[$changes].delete(index);
3597
- this.$indexes.delete(index);
3598
- return this.$items.delete(index);
3599
- }
3600
- clear() {
3601
- const changeTree = this[$changes];
3602
- // discard previous operations.
3603
- changeTree.discard(true);
3604
- changeTree.indexes = {};
3605
- // remove children references
3606
- changeTree.forEachChild((childChangeTree, _) => {
3607
- changeTree.root?.remove(childChangeTree);
3608
- });
3609
- // clear previous indexes
3610
- this.$indexes.clear();
3611
- // clear items
3612
- this.$items.clear();
3613
- changeTree.operation(exports.OPERATION.CLEAR);
3614
- }
3615
- has(value) {
3616
- return Array.from(this.$items.values()).some((v) => v === value);
3617
- }
3618
- forEach(callbackfn) {
3619
- this.$items.forEach((value, key, _) => callbackfn(value, key, this));
3620
- }
3621
- values() {
3622
- return this.$items.values();
3623
3552
  }
3624
- get size() {
3625
- return this.$items.size;
3626
- }
3627
- /** Iterator */
3628
- [Symbol.iterator]() {
3629
- return this.$items.values();
3630
- }
3631
- setIndex(index, key) {
3632
- this.$indexes.set(index, key);
3633
- }
3634
- getIndex(index) {
3635
- return this.$indexes.get(index);
3636
- }
3637
- [$getByIndex](index) {
3638
- return this.$items.get(this.$indexes.get(index));
3639
- }
3640
- [$deleteByIndex](index) {
3641
- const key = this.$indexes.get(index);
3642
- this.$items.delete(key);
3643
- this.$indexes.delete(index);
3644
- }
3645
- [$onEncodeEnd]() {
3646
- this.deletedItems = {};
3553
+ const getDefaultValues = () => {
3554
+ const defaults = {};
3555
+ for (const fieldName in defaultValues) {
3556
+ const defaultValue = defaultValues[fieldName];
3557
+ // If the default value has a clone method, use it to get a fresh instance
3558
+ if (defaultValue && typeof defaultValue.clone === 'function') {
3559
+ defaults[fieldName] = defaultValue.clone();
3560
+ }
3561
+ else {
3562
+ // Otherwise, use the value as-is (for primitives and non-cloneable objects)
3563
+ defaults[fieldName] = defaultValue;
3564
+ }
3565
+ }
3566
+ return defaults;
3567
+ };
3568
+ const klass = Metadata.setFields(class extends inherits {
3569
+ constructor(...args) {
3570
+ args[0] = Object.assign({}, getDefaultValues(), args[0]);
3571
+ super(...args);
3572
+ }
3573
+ }, fields);
3574
+ for (let fieldName in viewTagFields) {
3575
+ view(viewTagFields[fieldName])(klass.prototype, fieldName);
3647
3576
  }
3648
- toArray() {
3649
- return Array.from(this.$items.values());
3577
+ for (let methodName in methods) {
3578
+ klass.prototype[methodName] = methods[methodName];
3650
3579
  }
3651
- toJSON() {
3652
- const values = [];
3653
- this.forEach((value, key) => {
3654
- values.push((typeof (value['toJSON']) === "function")
3655
- ? value['toJSON']()
3656
- : value);
3657
- });
3658
- return values;
3580
+ if (name) {
3581
+ Object.defineProperty(klass, "name", { value: name });
3659
3582
  }
3660
- //
3661
- // Decoding utilities
3662
- //
3663
- clone(isDecoding) {
3664
- let cloned;
3665
- if (isDecoding) {
3666
- // client-side
3667
- cloned = Object.assign(new CollectionSchema(), this);
3583
+ klass.extends = (fields, name) => schema(fields, name, klass);
3584
+ return klass;
3585
+ }
3586
+
3587
+ function getIndent(level) {
3588
+ return (new Array(level).fill(0)).map((_, i) => (i === level - 1) ? `└─ ` : ` `).join("");
3589
+ }
3590
+ function dumpChanges(schema) {
3591
+ const $root = schema[$changes].root;
3592
+ const dump = {
3593
+ ops: {},
3594
+ refs: []
3595
+ };
3596
+ // for (const refId in $root.changes) {
3597
+ let current = $root.changes.next;
3598
+ while (current) {
3599
+ const changeTree = current.changeTree;
3600
+ // skip if ChangeTree is undefined
3601
+ if (changeTree === undefined) {
3602
+ current = current.next;
3603
+ continue;
3668
3604
  }
3669
- else {
3670
- // server-side
3671
- cloned = new CollectionSchema();
3672
- this.forEach((value) => {
3673
- if (value[$changes]) {
3674
- cloned.add(value['clone']());
3675
- }
3676
- else {
3677
- cloned.add(value);
3678
- }
3679
- });
3605
+ const changes = changeTree.indexedOperations;
3606
+ dump.refs.push(`refId#${changeTree.refId}`);
3607
+ for (const index in changes) {
3608
+ const op = changes[index];
3609
+ const opName = exports.OPERATION[op];
3610
+ if (!dump.ops[opName]) {
3611
+ dump.ops[opName] = 0;
3612
+ }
3613
+ dump.ops[exports.OPERATION[op]]++;
3680
3614
  }
3681
- return cloned;
3615
+ current = current.next;
3682
3616
  }
3617
+ return dump;
3683
3618
  }
3684
- registerType("collection", { constructor: CollectionSchema, });
3685
3619
 
3686
3620
  var _a, _b;
3687
- class SetSchema {
3688
- static { this[_a] = encodeKeyValueOperation; }
3689
- static { this[_b] = decodeKeyValueOperation; }
3621
+ /**
3622
+ * Schema encoder / decoder
3623
+ */
3624
+ class Schema {
3625
+ static { this[_a] = encodeSchemaOperation; }
3626
+ static { this[_b] = decodeSchemaOperation; }
3627
+ /**
3628
+ * Assign the property descriptors required to track changes on this instance.
3629
+ * @param instance
3630
+ */
3631
+ static initialize(instance) {
3632
+ Object.defineProperty(instance, $changes, {
3633
+ value: new ChangeTree(instance),
3634
+ enumerable: false,
3635
+ writable: true
3636
+ });
3637
+ Object.defineProperties(instance, instance.constructor[Symbol.metadata]?.[$descriptors] || {});
3638
+ }
3639
+ static is(type) {
3640
+ return typeof (type[Symbol.metadata]) === "object";
3641
+ // const metadata = type[Symbol.metadata];
3642
+ // return metadata && Object.prototype.hasOwnProperty.call(metadata, -1);
3643
+ }
3644
+ /**
3645
+ * Track property changes
3646
+ */
3647
+ static [(_a = $encoder, _b = $decoder, $track)](changeTree, index, operation = exports.OPERATION.ADD) {
3648
+ changeTree.change(index, operation);
3649
+ }
3690
3650
  /**
3691
3651
  * Determine if a property must be filtered.
3692
3652
  * - If returns false, the property is NOT going to be encoded.
@@ -3696,164 +3656,248 @@
3696
3656
  * - First, the encoder iterates over all "not owned" properties and encodes them.
3697
3657
  * - Then, the encoder iterates over all "owned" properties per instance and encodes them.
3698
3658
  */
3699
- static [(_a = $encoder, _b = $decoder, $filter)](ref, index, view) {
3700
- return (!view ||
3701
- typeof (ref[$childType]) === "string" ||
3702
- view.visible.has((ref[$getByIndex](index) ?? ref.deletedItems[index])[$changes]));
3703
- }
3704
- static is(type) {
3705
- return type['set'] !== undefined;
3706
- }
3707
- constructor(initialValues) {
3708
- this.$items = new Map();
3709
- this.$indexes = new Map();
3710
- this.deletedItems = {};
3711
- this.$refId = 0;
3712
- this[$changes] = new ChangeTree(this);
3713
- this[$changes].indexes = {};
3714
- if (initialValues) {
3715
- initialValues.forEach((v) => this.add(v));
3716
- }
3717
- Object.defineProperty(this, $childType, {
3718
- value: undefined,
3719
- enumerable: false,
3720
- writable: true,
3721
- configurable: true,
3722
- });
3723
- }
3724
- add(value) {
3725
- // immediatelly return false if value already added.
3726
- if (this.has(value)) {
3727
- return false;
3728
- }
3729
- // set "index" for reference.
3730
- const index = this.$refId++;
3731
- if ((value[$changes]) !== undefined) {
3732
- value[$changes].setParent(this, this[$changes].root, index);
3733
- }
3734
- const operation = this[$changes].indexes[index]?.op ?? exports.OPERATION.ADD;
3735
- this[$changes].indexes[index] = index;
3736
- this.$indexes.set(index, index);
3737
- this.$items.set(index, value);
3738
- this[$changes].change(index, operation);
3739
- return index;
3740
- }
3741
- entries() {
3742
- return this.$items.entries();
3743
- }
3744
- delete(item) {
3745
- const entries = this.$items.entries();
3746
- let index;
3747
- let entry;
3748
- while (entry = entries.next()) {
3749
- if (entry.done) {
3750
- break;
3751
- }
3752
- if (item === entry.value[1]) {
3753
- index = entry.value[0];
3754
- break;
3755
- }
3659
+ static [$filter](ref, index, view) {
3660
+ const metadata = ref.constructor[Symbol.metadata];
3661
+ const tag = metadata[index]?.tag;
3662
+ if (view === undefined) {
3663
+ // shared pass/encode: encode if doesn't have a tag
3664
+ return tag === undefined;
3756
3665
  }
3757
- if (index === undefined) {
3758
- return false;
3666
+ else if (tag === undefined) {
3667
+ // view pass: no tag
3668
+ return true;
3759
3669
  }
3760
- this.deletedItems[index] = this[$changes].delete(index);
3761
- this.$indexes.delete(index);
3762
- return this.$items.delete(index);
3763
- }
3764
- clear() {
3765
- const changeTree = this[$changes];
3766
- // discard previous operations.
3767
- changeTree.discard(true);
3768
- changeTree.indexes = {};
3769
- // clear previous indexes
3770
- this.$indexes.clear();
3771
- // clear items
3772
- this.$items.clear();
3773
- changeTree.operation(exports.OPERATION.CLEAR);
3774
- }
3775
- has(value) {
3776
- const values = this.$items.values();
3777
- let has = false;
3778
- let entry;
3779
- while (entry = values.next()) {
3780
- if (entry.done) {
3781
- break;
3782
- }
3783
- if (value === entry.value) {
3784
- has = true;
3785
- break;
3786
- }
3670
+ else if (tag === DEFAULT_VIEW_TAG) {
3671
+ // view pass: default tag
3672
+ return view.isChangeTreeVisible(ref[$changes]);
3673
+ }
3674
+ else {
3675
+ // view pass: custom tag
3676
+ const tags = view.tags?.get(ref[$changes]);
3677
+ return tags && tags.has(tag);
3787
3678
  }
3788
- return has;
3789
3679
  }
3790
- forEach(callbackfn) {
3791
- this.$items.forEach((value, key, _) => callbackfn(value, key, this));
3680
+ // allow inherited classes to have a constructor
3681
+ constructor(...args) {
3682
+ //
3683
+ // inline
3684
+ // Schema.initialize(this);
3685
+ //
3686
+ Schema.initialize(this);
3687
+ //
3688
+ // Assign initial values
3689
+ //
3690
+ if (args[0]) {
3691
+ Object.assign(this, args[0]);
3692
+ }
3792
3693
  }
3793
- values() {
3794
- return this.$items.values();
3694
+ assign(props) {
3695
+ Object.assign(this, props);
3696
+ return this;
3795
3697
  }
3796
- get size() {
3797
- return this.$items.size;
3698
+ /**
3699
+ * (Server-side): Flag a property to be encoded for the next patch.
3700
+ * @param instance Schema instance
3701
+ * @param property string representing the property name, or number representing the index of the property.
3702
+ * @param operation OPERATION to perform (detected automatically)
3703
+ */
3704
+ setDirty(property, operation) {
3705
+ const metadata = this.constructor[Symbol.metadata];
3706
+ this[$changes].change(metadata[metadata[property]].index, operation);
3798
3707
  }
3799
- /** Iterator */
3800
- [Symbol.iterator]() {
3801
- return this.$items.values();
3708
+ clone() {
3709
+ const cloned = new (this.constructor);
3710
+ const metadata = this.constructor[Symbol.metadata];
3711
+ //
3712
+ // TODO: clone all properties, not only annotated ones
3713
+ //
3714
+ // for (const field in this) {
3715
+ for (const fieldIndex in metadata) {
3716
+ // const field = metadata[metadata[fieldIndex]].name;
3717
+ const field = metadata[fieldIndex].name;
3718
+ if (typeof (this[field]) === "object" &&
3719
+ typeof (this[field]?.clone) === "function") {
3720
+ // deep clone
3721
+ cloned[field] = this[field].clone();
3722
+ }
3723
+ else {
3724
+ // primitive values
3725
+ cloned[field] = this[field];
3726
+ }
3727
+ }
3728
+ return cloned;
3802
3729
  }
3803
- setIndex(index, key) {
3804
- this.$indexes.set(index, key);
3730
+ toJSON() {
3731
+ const obj = {};
3732
+ const metadata = this.constructor[Symbol.metadata];
3733
+ for (const index in metadata) {
3734
+ const field = metadata[index];
3735
+ const fieldName = field.name;
3736
+ if (!field.deprecated && this[fieldName] !== null && typeof (this[fieldName]) !== "undefined") {
3737
+ obj[fieldName] = (typeof (this[fieldName]['toJSON']) === "function")
3738
+ ? this[fieldName]['toJSON']()
3739
+ : this[fieldName];
3740
+ }
3741
+ }
3742
+ return obj;
3805
3743
  }
3806
- getIndex(index) {
3807
- return this.$indexes.get(index);
3744
+ /**
3745
+ * Used in tests only
3746
+ * @internal
3747
+ */
3748
+ discardAllChanges() {
3749
+ this[$changes].discardAll();
3808
3750
  }
3809
3751
  [$getByIndex](index) {
3810
- return this.$items.get(this.$indexes.get(index));
3752
+ const metadata = this.constructor[Symbol.metadata];
3753
+ return this[metadata[index].name];
3811
3754
  }
3812
3755
  [$deleteByIndex](index) {
3813
- const key = this.$indexes.get(index);
3814
- this.$items.delete(key);
3815
- this.$indexes.delete(index);
3756
+ const metadata = this.constructor[Symbol.metadata];
3757
+ this[metadata[index].name] = undefined;
3816
3758
  }
3817
- [$onEncodeEnd]() {
3818
- this.deletedItems = {};
3759
+ /**
3760
+ * Inspect the `refId` of all Schema instances in the tree. Optionally display the contents of the instance.
3761
+ *
3762
+ * @param ref Schema instance
3763
+ * @param showContents display JSON contents of the instance
3764
+ * @returns
3765
+ */
3766
+ static debugRefIds(ref, showContents = false, level = 0, decoder, keyPrefix = "") {
3767
+ const contents = (showContents) ? ` - ${JSON.stringify(ref.toJSON())}` : "";
3768
+ const changeTree = ref[$changes];
3769
+ const refId = (decoder) ? decoder.root.refIds.get(ref) : changeTree.refId;
3770
+ const root = (decoder) ? decoder.root : changeTree.root;
3771
+ // log reference count if > 1
3772
+ const refCount = (root?.refCount?.[refId] > 1)
3773
+ ? ` [×${root.refCount[refId]}]`
3774
+ : '';
3775
+ let output = `${getIndent(level)}${keyPrefix}${ref.constructor.name} (refId: ${refId})${refCount}${contents}\n`;
3776
+ changeTree.forEachChild((childChangeTree, indexOrKey) => {
3777
+ let key = indexOrKey;
3778
+ if (typeof indexOrKey === 'number' && ref['$indexes']) {
3779
+ // MapSchema
3780
+ key = ref['$indexes'].get(indexOrKey) ?? indexOrKey;
3781
+ }
3782
+ const keyPrefix = (ref['forEach'] !== undefined && key !== undefined) ? `["${key}"]: ` : "";
3783
+ output += this.debugRefIds(childChangeTree.ref, showContents, level + 1, decoder, keyPrefix);
3784
+ });
3785
+ return output;
3819
3786
  }
3820
- toArray() {
3821
- return Array.from(this.$items.values());
3787
+ static debugRefIdEncodingOrder(ref, changeSet = 'allChanges') {
3788
+ let encodeOrder = [];
3789
+ let current = ref[$changes].root[changeSet].next;
3790
+ while (current) {
3791
+ if (current.changeTree) {
3792
+ encodeOrder.push(current.changeTree.refId);
3793
+ }
3794
+ current = current.next;
3795
+ }
3796
+ return encodeOrder;
3822
3797
  }
3823
- toJSON() {
3824
- const values = [];
3825
- this.forEach((value, key) => {
3826
- values.push((typeof (value['toJSON']) === "function")
3827
- ? value['toJSON']()
3828
- : value);
3829
- });
3830
- return values;
3798
+ static debugRefIdsFromDecoder(decoder) {
3799
+ return this.debugRefIds(decoder.state, false, 0, decoder);
3831
3800
  }
3832
- //
3833
- // Decoding utilities
3834
- //
3835
- clone(isDecoding) {
3836
- let cloned;
3837
- if (isDecoding) {
3838
- // client-side
3839
- cloned = Object.assign(new SetSchema(), this);
3801
+ /**
3802
+ * Return a string representation of the changes on a Schema instance.
3803
+ * The list of changes is cleared after each encode.
3804
+ *
3805
+ * @param instance Schema instance
3806
+ * @param isEncodeAll Return "full encode" instead of current change set.
3807
+ * @returns
3808
+ */
3809
+ static debugChanges(instance, isEncodeAll = false) {
3810
+ const changeTree = instance[$changes];
3811
+ const changeSet = (isEncodeAll) ? changeTree.allChanges : changeTree.changes;
3812
+ const changeSetName = (isEncodeAll) ? "allChanges" : "changes";
3813
+ let output = `${instance.constructor.name} (${changeTree.refId}) -> .${changeSetName}:\n`;
3814
+ function dumpChangeSet(changeSet) {
3815
+ changeSet.operations
3816
+ .filter(op => op)
3817
+ .forEach((index) => {
3818
+ const operation = changeTree.indexedOperations[index];
3819
+ output += `- [${index}]: ${exports.OPERATION[operation]} (${JSON.stringify(changeTree.getValue(Number(index), isEncodeAll))})\n`;
3820
+ });
3840
3821
  }
3841
- else {
3842
- // server-side
3843
- cloned = new SetSchema();
3844
- this.forEach((value) => {
3845
- if (value[$changes]) {
3846
- cloned.add(value['clone']());
3822
+ dumpChangeSet(changeSet);
3823
+ // display filtered changes
3824
+ if (!isEncodeAll &&
3825
+ changeTree.filteredChanges &&
3826
+ (changeTree.filteredChanges.operations).filter(op => op).length > 0) {
3827
+ output += `${instance.constructor.name} (${changeTree.refId}) -> .filteredChanges:\n`;
3828
+ dumpChangeSet(changeTree.filteredChanges);
3829
+ }
3830
+ // display filtered changes
3831
+ if (isEncodeAll &&
3832
+ changeTree.allFilteredChanges &&
3833
+ (changeTree.allFilteredChanges.operations).filter(op => op).length > 0) {
3834
+ output += `${instance.constructor.name} (${changeTree.refId}) -> .allFilteredChanges:\n`;
3835
+ dumpChangeSet(changeTree.allFilteredChanges);
3836
+ }
3837
+ return output;
3838
+ }
3839
+ static debugChangesDeep(ref, changeSetName = "changes") {
3840
+ let output = "";
3841
+ const rootChangeTree = ref[$changes];
3842
+ const root = rootChangeTree.root;
3843
+ const changeTrees = new Map();
3844
+ const instanceRefIds = [];
3845
+ let totalOperations = 0;
3846
+ // TODO: FIXME: this method is not working as expected
3847
+ for (const [refId, changes] of Object.entries(root[changeSetName])) {
3848
+ const changeTree = root.changeTrees[refId];
3849
+ if (!changeTree) {
3850
+ continue;
3851
+ }
3852
+ let includeChangeTree = false;
3853
+ let parentChangeTrees = [];
3854
+ let parentChangeTree = changeTree.parent?.[$changes];
3855
+ if (changeTree === rootChangeTree) {
3856
+ includeChangeTree = true;
3857
+ }
3858
+ else {
3859
+ while (parentChangeTree !== undefined) {
3860
+ parentChangeTrees.push(parentChangeTree);
3861
+ if (parentChangeTree.ref === ref) {
3862
+ includeChangeTree = true;
3863
+ break;
3864
+ }
3865
+ parentChangeTree = parentChangeTree.parent?.[$changes];
3847
3866
  }
3848
- else {
3849
- cloned.add(value);
3867
+ }
3868
+ if (includeChangeTree) {
3869
+ instanceRefIds.push(changeTree.refId);
3870
+ totalOperations += Object.keys(changes).length;
3871
+ changeTrees.set(changeTree, parentChangeTrees.reverse());
3872
+ }
3873
+ }
3874
+ output += "---\n";
3875
+ output += `root refId: ${rootChangeTree.refId}\n`;
3876
+ output += `Total instances: ${instanceRefIds.length} (refIds: ${instanceRefIds.join(", ")})\n`;
3877
+ output += `Total changes: ${totalOperations}\n`;
3878
+ output += "---\n";
3879
+ // based on root.changes, display a tree of changes that has the "ref" instance as parent
3880
+ const visitedParents = new WeakSet();
3881
+ for (const [changeTree, parentChangeTrees] of changeTrees.entries()) {
3882
+ parentChangeTrees.forEach((parentChangeTree, level) => {
3883
+ if (!visitedParents.has(parentChangeTree)) {
3884
+ output += `${getIndent(level)}${parentChangeTree.ref.constructor.name} (refId: ${parentChangeTree.refId})\n`;
3885
+ visitedParents.add(parentChangeTree);
3850
3886
  }
3851
3887
  });
3888
+ const changes = changeTree.indexedOperations;
3889
+ const level = parentChangeTrees.length;
3890
+ const indent = getIndent(level);
3891
+ const parentIndex = (level > 0) ? `(${changeTree.parentIndex}) ` : "";
3892
+ output += `${indent}${parentIndex}${changeTree.ref.constructor.name} (refId: ${changeTree.refId}) - changes: ${Object.keys(changes).length}\n`;
3893
+ for (const index in changes) {
3894
+ const operation = changes[index];
3895
+ output += `${getIndent(level + 1)}${exports.OPERATION[operation]}: ${index}\n`;
3896
+ }
3852
3897
  }
3853
- return cloned;
3898
+ return `${output}`;
3854
3899
  }
3855
3900
  }
3856
- registerType("set", { constructor: SetSchema });
3857
3901
 
3858
3902
  /******************************************************************************
3859
3903
  Copyright (c) Microsoft Corporation.