@verdant-web/store 3.0.0-next.0 → 3.0.1

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.
Files changed (134) hide show
  1. package/dist/bundle/index.js +1 -1
  2. package/dist/bundle/index.js.map +4 -4
  3. package/dist/cjs/DocumentManager.d.ts +5 -6
  4. package/dist/cjs/DocumentManager.js +2 -2
  5. package/dist/cjs/DocumentManager.js.map +1 -1
  6. package/dist/cjs/client/Client.d.ts +3 -2
  7. package/dist/cjs/client/Client.js +1 -1
  8. package/dist/cjs/client/Client.js.map +1 -1
  9. package/dist/cjs/entities/Entity.d.ts +106 -171
  10. package/dist/cjs/entities/Entity.js +558 -383
  11. package/dist/cjs/entities/Entity.js.map +1 -1
  12. package/dist/cjs/entities/Entity.test.js.map +1 -0
  13. package/dist/cjs/entities/{2/EntityCache.d.ts → EntityCache.d.ts} +1 -1
  14. package/dist/cjs/entities/{2/EntityCache.js → EntityCache.js} +1 -1
  15. package/dist/cjs/entities/EntityCache.js.map +1 -0
  16. package/dist/{esm/entities/2 → cjs/entities}/EntityMetadata.d.ts +1 -1
  17. package/dist/cjs/entities/EntityMetadata.js.map +1 -0
  18. package/dist/cjs/entities/EntityStore.d.ts +63 -68
  19. package/dist/cjs/entities/EntityStore.js +296 -424
  20. package/dist/cjs/entities/EntityStore.js.map +1 -1
  21. package/dist/{esm/entities/2 → cjs/entities}/OperationBatcher.d.ts +2 -2
  22. package/dist/cjs/entities/OperationBatcher.js.map +1 -0
  23. package/dist/cjs/entities/{2/types.js.map → types.js.map} +1 -1
  24. package/dist/cjs/files/EntityFile.d.ts +5 -4
  25. package/dist/cjs/files/EntityFile.js.map +1 -1
  26. package/dist/cjs/index.d.ts +3 -3
  27. package/dist/cjs/index.js +1 -1
  28. package/dist/cjs/index.js.map +1 -1
  29. package/dist/cjs/queries/BaseQuery.js +1 -1
  30. package/dist/cjs/queries/BaseQuery.js.map +1 -1
  31. package/dist/cjs/queries/CollectionQueries.d.ts +4 -2
  32. package/dist/cjs/queries/utils.js +1 -1
  33. package/dist/cjs/queries/utils.js.map +1 -1
  34. package/dist/esm/DocumentManager.d.ts +5 -6
  35. package/dist/esm/DocumentManager.js +2 -2
  36. package/dist/esm/DocumentManager.js.map +1 -1
  37. package/dist/esm/client/Client.d.ts +3 -2
  38. package/dist/esm/client/Client.js +1 -1
  39. package/dist/esm/client/Client.js.map +1 -1
  40. package/dist/esm/entities/Entity.d.ts +106 -171
  41. package/dist/esm/entities/Entity.js +559 -383
  42. package/dist/esm/entities/Entity.js.map +1 -1
  43. package/dist/esm/entities/Entity.test.js.map +1 -0
  44. package/dist/esm/entities/{2/EntityCache.d.ts → EntityCache.d.ts} +1 -1
  45. package/dist/esm/entities/{2/EntityCache.js → EntityCache.js} +1 -1
  46. package/dist/esm/entities/EntityCache.js.map +1 -0
  47. package/dist/{cjs/entities/2 → esm/entities}/EntityMetadata.d.ts +1 -1
  48. package/dist/esm/entities/EntityMetadata.js.map +1 -0
  49. package/dist/esm/entities/EntityStore.d.ts +63 -68
  50. package/dist/esm/entities/EntityStore.js +297 -425
  51. package/dist/esm/entities/EntityStore.js.map +1 -1
  52. package/dist/{cjs/entities/2 → esm/entities}/OperationBatcher.d.ts +2 -2
  53. package/dist/esm/entities/OperationBatcher.js.map +1 -0
  54. package/dist/esm/entities/{2/types.js.map → types.js.map} +1 -1
  55. package/dist/esm/files/EntityFile.d.ts +5 -4
  56. package/dist/esm/files/EntityFile.js.map +1 -1
  57. package/dist/esm/index.d.ts +3 -3
  58. package/dist/esm/index.js +1 -1
  59. package/dist/esm/index.js.map +1 -1
  60. package/dist/esm/queries/BaseQuery.js +1 -1
  61. package/dist/esm/queries/BaseQuery.js.map +1 -1
  62. package/dist/esm/queries/CollectionQueries.d.ts +4 -2
  63. package/dist/esm/queries/utils.js +1 -1
  64. package/dist/esm/queries/utils.js.map +1 -1
  65. package/dist/tsconfig-cjs.tsbuildinfo +1 -1
  66. package/dist/tsconfig.tsbuildinfo +1 -1
  67. package/package.json +2 -2
  68. package/src/DocumentManager.ts +7 -3
  69. package/src/__tests__/batching.test.ts +1 -1
  70. package/src/client/Client.ts +1 -1
  71. package/src/entities/{2/Entity.test.ts → Entity.test.ts} +2 -2
  72. package/src/entities/{2/Entity.ts → Entity.ts} +4 -4
  73. package/src/entities/{2/EntityCache.ts → EntityCache.ts} +1 -1
  74. package/src/entities/{2/EntityMetadata.ts → EntityMetadata.ts} +1 -1
  75. package/src/entities/{2/EntityStore.ts → EntityStore.ts} +12 -8
  76. package/src/entities/{2/OperationBatcher.ts → OperationBatcher.ts} +2 -2
  77. package/src/files/EntityFile.ts +6 -1
  78. package/src/index.ts +3 -3
  79. package/src/queries/BaseQuery.ts +1 -1
  80. package/src/queries/CollectionQueries.ts +2 -2
  81. package/src/queries/utils.ts +1 -1
  82. package/dist/cjs/entities/2/Entity.d.ts +0 -148
  83. package/dist/cjs/entities/2/Entity.js +0 -711
  84. package/dist/cjs/entities/2/Entity.js.map +0 -1
  85. package/dist/cjs/entities/2/Entity.test.js.map +0 -1
  86. package/dist/cjs/entities/2/EntityCache.js.map +0 -1
  87. package/dist/cjs/entities/2/EntityMetadata.js.map +0 -1
  88. package/dist/cjs/entities/2/EntityStore.d.ts +0 -78
  89. package/dist/cjs/entities/2/EntityStore.js +0 -352
  90. package/dist/cjs/entities/2/EntityStore.js.map +0 -1
  91. package/dist/cjs/entities/2/OperationBatcher.js.map +0 -1
  92. package/dist/cjs/entities/DocumentFamiliyCache.d.ts +0 -96
  93. package/dist/cjs/entities/DocumentFamiliyCache.js +0 -287
  94. package/dist/cjs/entities/DocumentFamiliyCache.js.map +0 -1
  95. package/dist/cjs/entities/FakeWeakRef.d.ts +0 -11
  96. package/dist/cjs/entities/FakeWeakRef.js +0 -19
  97. package/dist/cjs/entities/FakeWeakRef.js.map +0 -1
  98. package/dist/cjs/indexes.d.ts +0 -3
  99. package/dist/cjs/indexes.js +0 -20
  100. package/dist/cjs/indexes.js.map +0 -1
  101. package/dist/esm/entities/2/Entity.d.ts +0 -148
  102. package/dist/esm/entities/2/Entity.js +0 -707
  103. package/dist/esm/entities/2/Entity.js.map +0 -1
  104. package/dist/esm/entities/2/Entity.test.js.map +0 -1
  105. package/dist/esm/entities/2/EntityCache.js.map +0 -1
  106. package/dist/esm/entities/2/EntityMetadata.js.map +0 -1
  107. package/dist/esm/entities/2/EntityStore.d.ts +0 -78
  108. package/dist/esm/entities/2/EntityStore.js +0 -348
  109. package/dist/esm/entities/2/EntityStore.js.map +0 -1
  110. package/dist/esm/entities/2/OperationBatcher.js.map +0 -1
  111. package/dist/esm/entities/DocumentFamiliyCache.d.ts +0 -96
  112. package/dist/esm/entities/DocumentFamiliyCache.js +0 -283
  113. package/dist/esm/entities/DocumentFamiliyCache.js.map +0 -1
  114. package/dist/esm/entities/FakeWeakRef.d.ts +0 -11
  115. package/dist/esm/entities/FakeWeakRef.js +0 -15
  116. package/dist/esm/entities/FakeWeakRef.js.map +0 -1
  117. package/dist/esm/indexes.d.ts +0 -3
  118. package/dist/esm/indexes.js +0 -15
  119. package/dist/esm/indexes.js.map +0 -1
  120. package/src/entities/2/NOTES.md +0 -22
  121. package/src/entities/design.tldr +0 -808
  122. /package/dist/cjs/entities/{2/Entity.test.d.ts → Entity.test.d.ts} +0 -0
  123. /package/dist/cjs/entities/{2/Entity.test.js → Entity.test.js} +0 -0
  124. /package/dist/cjs/entities/{2/EntityMetadata.js → EntityMetadata.js} +0 -0
  125. /package/dist/cjs/entities/{2/OperationBatcher.js → OperationBatcher.js} +0 -0
  126. /package/dist/cjs/entities/{2/types.d.ts → types.d.ts} +0 -0
  127. /package/dist/cjs/entities/{2/types.js → types.js} +0 -0
  128. /package/dist/esm/entities/{2/Entity.test.d.ts → Entity.test.d.ts} +0 -0
  129. /package/dist/esm/entities/{2/Entity.test.js → Entity.test.js} +0 -0
  130. /package/dist/esm/entities/{2/EntityMetadata.js → EntityMetadata.js} +0 -0
  131. /package/dist/esm/entities/{2/OperationBatcher.js → OperationBatcher.js} +0 -0
  132. /package/dist/esm/entities/{2/types.d.ts → types.d.ts} +0 -0
  133. /package/dist/esm/entities/{2/types.js → types.js} +0 -0
  134. /package/src/entities/{2/types.ts → types.ts} +0 -0
@@ -1,707 +0,0 @@
1
- import { EventSubscriber, assert, assignOid, cloneDeep, compareRefs, createFileRef, createRef, getChildFieldSchema, getDefault, hasDefault, isFileRef, isNullable, isObject, isRef, maybeGetOid, memoByKeys, traverseCollectionFieldsAndApplyDefaults, validateEntityField, } from '@verdant-web/common';
2
- import { isFile, processValueFiles } from '../../files/utils.js';
3
- import { EntityFile } from '../../index.js';
4
- import { EntityCache } from './EntityCache.js';
5
- export class Entity extends EventSubscriber {
6
- constructor({ oid, schema, entityFamily: childCache, parent, ctx, metadataFamily, readonlyKeys, files, patchCreator, events, }) {
7
- super();
8
- this.fieldPath = [];
9
- // an internal representation of this Entity.
10
- // if present, this is the cached, known value. If null,
11
- // the entity is deleted. If undefined, we need to recompute
12
- // the view.
13
- this._viewData = undefined;
14
- this.validationError = undefined;
15
- this.cachedDeepUpdatedAt = null;
16
- // only used for root entities to track delete/restore state.
17
- this.wasDeletedLastChange = false;
18
- this.cachedView = undefined;
19
- this.onAdd = (_store, data) => {
20
- if (data.oid === this.oid) {
21
- this.addConfirmedData(data);
22
- }
23
- };
24
- this.onReplace = (_store, data) => {
25
- if (data.oid === this.oid) {
26
- this.replaceAllData(data);
27
- }
28
- };
29
- this.onResetAll = () => {
30
- this.resetAllData();
31
- };
32
- this.childIsNull = (child) => {
33
- if (child instanceof Entity) {
34
- const childView = child.view;
35
- return childView === null || childView === undefined;
36
- }
37
- return child === null || child === undefined;
38
- };
39
- /**
40
- * Pruning - when entities have invalid children, we 'prune' that
41
- * data up to the nearest prunable point - a nullable field,
42
- * or a list.
43
- */
44
- this.validate = memoByKeys(() => {
45
- var _a;
46
- this.validationError =
47
- (_a = validateEntityField({
48
- field: this.schema,
49
- value: this.rawView,
50
- fieldPath: this.fieldPath,
51
- depth: 1,
52
- })) !== null && _a !== void 0 ? _a : undefined;
53
- return this.validationError;
54
- }, () => [this.viewData]);
55
- this.viewWithMappedChildren = (mapper) => {
56
- const view = this.view;
57
- if (!view) {
58
- return null;
59
- }
60
- if (Array.isArray(view)) {
61
- const mapped = view.map((value) => {
62
- if (value instanceof Entity || value instanceof EntityFile) {
63
- return mapper(value);
64
- }
65
- else {
66
- return value;
67
- }
68
- });
69
- assignOid(mapped, this.oid);
70
- return mapped;
71
- }
72
- else {
73
- const mapped = Object.entries(view).reduce((acc, [key, value]) => {
74
- if (value instanceof Entity || value instanceof EntityFile) {
75
- acc[key] = mapper(value);
76
- }
77
- else {
78
- acc[key] = value;
79
- }
80
- return acc;
81
- }, {});
82
- assignOid(mapped, this.oid);
83
- return mapped;
84
- }
85
- };
86
- /**
87
- * A current snapshot of this Entity's data, including nested
88
- * Entities.
89
- */
90
- this.getSnapshot = () => {
91
- return this.viewWithMappedChildren((child) => child.getSnapshot());
92
- };
93
- // change management methods (internal use only)
94
- this.addPendingOperations = (operations) => {
95
- this.ctx.log('debug', 'Entity: adding pending operations', this.oid);
96
- const changes = this.metadataFamily.addPendingData(operations);
97
- for (const change of changes) {
98
- this.change(change);
99
- }
100
- };
101
- this.addConfirmedData = (data) => {
102
- this.ctx.log('debug', 'Entity: adding confirmed data', this.oid);
103
- const changes = this.metadataFamily.addConfirmedData(data);
104
- for (const change of changes) {
105
- this.change(change);
106
- }
107
- };
108
- this.replaceAllData = (data) => {
109
- this.ctx.log('debug', 'Entity: replacing all data', this.oid);
110
- const changes = this.metadataFamily.replaceAllData(data);
111
- for (const change of changes) {
112
- this.change(change);
113
- }
114
- };
115
- this.resetAllData = () => {
116
- this.ctx.log('debug', 'Entity: resetting all data', this.oid);
117
- this.cachedDeepUpdatedAt = null;
118
- this.cachedView = undefined;
119
- this._viewData = undefined;
120
- const changes = this.metadataFamily.replaceAllData({});
121
- for (const change of changes) {
122
- this.change(change);
123
- }
124
- };
125
- this.change = (ev) => {
126
- if (ev.oid === this.oid) {
127
- // reset cached view
128
- this._viewData = undefined;
129
- this.cachedView = undefined;
130
- // chain deepChanges to parents
131
- this.deepChange(this, ev);
132
- // emit the change, it's for us
133
- this.ctx.log('Emitting change event', this.oid);
134
- this.emit('change', { isLocal: ev.isLocal });
135
- // for root entities, we need to go ahead and decide if we're
136
- // deleted or not - so queries can exclude us if we are.
137
- if (!this.parent) {
138
- // newly deleted - emit event
139
- if (this.deleted && !this.wasDeletedLastChange) {
140
- this.ctx.log('debug', 'Entity deleted', this.oid);
141
- this.emit('delete', { isLocal: ev.isLocal });
142
- this.wasDeletedLastChange = true;
143
- }
144
- else if (!this.deleted && this.wasDeletedLastChange) {
145
- this.ctx.log('debug', 'Entity restored', this.oid);
146
- // newly restored - emit event
147
- this.emit('restore', { isLocal: ev.isLocal });
148
- this.wasDeletedLastChange = false;
149
- }
150
- }
151
- }
152
- else {
153
- // forward it to the correct family member. if none exists
154
- // in cache, no one will hear it anyways.
155
- const other = this.entityFamily.getCached(ev.oid);
156
- if (other && other instanceof Entity) {
157
- other.change(ev);
158
- }
159
- }
160
- };
161
- this.deepChange = (target, ev) => {
162
- var _a;
163
- // reset cached deep updated at timestamp; either this
164
- // entity or children have changed
165
- this.cachedDeepUpdatedAt = null;
166
- // reset this flag to recompute snapshot data - children
167
- // or self has changed. new pruning needs to happen.
168
- this.cachedView = undefined;
169
- this.ctx.log('debug', 'Deep change detected at', this.oid, 'reset cached view');
170
- this.ctx.log('debug', 'Emitting deep change event', this.oid);
171
- this.emit('changeDeep', target, ev);
172
- (_a = this.parent) === null || _a === void 0 ? void 0 : _a.deepChange(target, ev);
173
- };
174
- this.getChild = (key, oid) => {
175
- const schema = getChildFieldSchema(this.schema, key);
176
- if (!schema) {
177
- throw new Error(`No schema for key ${String(key)} in ${JSON.stringify(this.schema)}`);
178
- }
179
- return this.entityFamily.get({
180
- oid,
181
- schema,
182
- entityFamily: this.entityFamily,
183
- metadataFamily: this.metadataFamily,
184
- parent: this,
185
- ctx: this.ctx,
186
- files: this.files,
187
- fieldPath: [...this.fieldPath, key],
188
- patchCreator: this.patchCreator,
189
- events: this.events,
190
- });
191
- };
192
- // generic entity methods
193
- /**
194
- * Gets a value from this Entity. If the value
195
- * is an object, it will be wrapped in another
196
- * Entity.
197
- */
198
- this.get = (key) => {
199
- assertNotSymbol(key);
200
- const view = this.rawView;
201
- if (!view) {
202
- throw new Error(`Cannot access data at key ${key} on deleted entity ${this.oid}`);
203
- }
204
- const child = view[key];
205
- const schema = getChildFieldSchema(this.schema, key);
206
- if (!schema) {
207
- throw new Error(`No schema for key ${String(key)} in ${JSON.stringify(this.schema)}`);
208
- }
209
- if (isRef(child)) {
210
- if (isFileRef(child)) {
211
- if (schema.type !== 'file') {
212
- throw new Error(`Expected file schema for key ${String(key)}, got ${schema.type}`);
213
- }
214
- const file = this.files.get(child.id, {
215
- downloadRemote: !!schema.downloadRemote,
216
- });
217
- // FIXME: this seems bad and inconsistent
218
- file.subscribe('change', () => {
219
- this.deepChange(this, { isLocal: false, oid: this.oid });
220
- });
221
- return file;
222
- }
223
- else {
224
- return this.getChild(key, child.id);
225
- }
226
- }
227
- else {
228
- // prune invalid primitive fields
229
- if (validateEntityField({
230
- field: schema,
231
- value: child,
232
- fieldPath: [...this.fieldPath, key],
233
- depth: 1,
234
- requireDefaults: true,
235
- })) {
236
- if (hasDefault(schema)) {
237
- return getDefault(schema);
238
- }
239
- if (isNullable(schema)) {
240
- return null;
241
- }
242
- return undefined;
243
- }
244
- return child;
245
- }
246
- };
247
- this.processInputValue = (value, key) => {
248
- if (this.readonlyKeys.includes(key)) {
249
- throw new Error(`Cannot set readonly key ${key.toString()}`);
250
- }
251
- // disassociate incoming OIDs on values and generally break object
252
- // references. cloning doesn't work on files so those are
253
- // filtered out.
254
- // The goal here is to be safe about a bunch of cases that could
255
- // result in corrupt data, like...
256
- // ent1.set('objField', ent2.get('objField'))
257
- // or
258
- // var shared = { foo: 'bar' };
259
- // ent1.set('objField', shared);
260
- // ent2.set('objField', shared);
261
- // ... each of these would result in the same object being
262
- // referenced in multiple entities, which could mean introduction
263
- // of foreign OIDs, or one object being assigned different OIDs
264
- // with unexpected results.
265
- if (!isFile(value)) {
266
- value = cloneDeep(value, false);
267
- }
268
- const fieldSchema = getChildFieldSchema(this.schema, key);
269
- if (fieldSchema) {
270
- traverseCollectionFieldsAndApplyDefaults(value, fieldSchema);
271
- const validationError = validateEntityField({
272
- field: fieldSchema,
273
- value,
274
- fieldPath: [...this.fieldPath, key],
275
- });
276
- if (validationError) {
277
- // TODO: is it a good idea to throw an error here? a runtime error won't be that helpful,
278
- // but also we don't really want invalid data supplied.
279
- throw new Error(validationError.message);
280
- }
281
- }
282
- return processValueFiles(value, this.files.add);
283
- };
284
- this.getDeleteMode = (key) => {
285
- if (this.readonlyKeys.includes(key)) {
286
- return false;
287
- }
288
- // any is always deletable, and map values
289
- if (this.schema.type === 'any' || this.schema.type === 'map') {
290
- return 'delete';
291
- }
292
- if (this.schema.type === 'object') {
293
- const property = this.schema.properties[key];
294
- if (!property) {
295
- // huh, the property doesn't exist. it's ok to
296
- // remove I suppose.
297
- return 'delete';
298
- }
299
- if (property.type === 'any')
300
- return 'delete';
301
- // map can't be nullable. should it be?
302
- if (property.type === 'map')
303
- return false;
304
- if (property.nullable)
305
- return 'null';
306
- }
307
- // no other types are deletable
308
- return false;
309
- };
310
- /**
311
- * Returns the referent value of an item in the list, used for
312
- * operations which act on items. if the item is an object,
313
- * it will attempt to create an OID reference to it. If it
314
- * is a primitive, it will return the primitive.
315
- */
316
- this.getItemRefValue = (item) => {
317
- if (item instanceof Entity) {
318
- return createRef(item.oid);
319
- }
320
- if (item instanceof EntityFile) {
321
- return createFileRef(item.id);
322
- }
323
- if (typeof item === 'object') {
324
- const itemOid = maybeGetOid(item);
325
- if (!itemOid || !this.entityFamily.has(itemOid)) {
326
- throw new Error(`Cannot move object ${JSON.stringify(item)} which does not exist in this list`);
327
- }
328
- return createRef(itemOid);
329
- }
330
- else {
331
- return item;
332
- }
333
- };
334
- this.set = (key, value) => {
335
- assertNotSymbol(key);
336
- this.addPendingOperations(this.patchCreator.createSet(this.oid, key, this.processInputValue(value, key)));
337
- };
338
- /**
339
- * Returns a destructured version of this Entity, where child
340
- * Entities are accessible at their respective keys.
341
- */
342
- this.getAll = () => {
343
- return this.view;
344
- };
345
- this.delete = (key) => {
346
- if (this.isList) {
347
- assertNumber(key);
348
- this.addPendingOperations(this.patchCreator.createListDelete(this.oid, key));
349
- }
350
- else {
351
- // the key must be deletable - i.e. optional in the schema.
352
- const deleteMode = this.getDeleteMode(key);
353
- if (!deleteMode) {
354
- throw new Error(`Cannot delete key ${key.toString()} - the property is not marked as optional in the schema.`);
355
- }
356
- if (deleteMode === 'delete') {
357
- this.addPendingOperations(this.patchCreator.createRemove(this.oid, key));
358
- }
359
- else {
360
- this.addPendingOperations(this.patchCreator.createSet(this.oid, key, null));
361
- }
362
- }
363
- };
364
- // object entity methods
365
- this.keys = () => {
366
- if (!this.view)
367
- return [];
368
- return Object.keys(this.view);
369
- };
370
- this.entries = () => {
371
- if (!this.view)
372
- return [];
373
- return Object.entries(this.view);
374
- };
375
- this.values = () => {
376
- if (!this.view)
377
- return [];
378
- return Object.values(this.view);
379
- };
380
- this.update = (data, { merge = true, replaceSubObjects = false, } = {}) => {
381
- if (!merge && this.schema.type !== 'any' && this.schema.type !== 'map') {
382
- throw new Error('Cannot use .update without merge if the field has a strict schema type. merge: false is only available on "any" or "map" types.');
383
- }
384
- const changes = {};
385
- assignOid(changes, this.oid);
386
- for (const [key, field] of Object.entries(data)) {
387
- if (this.readonlyKeys.includes(key)) {
388
- throw new Error(`Cannot set readonly key ${key.toString()}`);
389
- }
390
- const fieldSchema = getChildFieldSchema(this.schema, key);
391
- if (fieldSchema) {
392
- traverseCollectionFieldsAndApplyDefaults(field, fieldSchema);
393
- }
394
- changes[key] = this.processInputValue(field, key);
395
- }
396
- this.addPendingOperations(this.patchCreator.createDiff(this.getSnapshot(), changes, {
397
- mergeUnknownObjects: !replaceSubObjects,
398
- defaultUndefined: merge,
399
- }));
400
- };
401
- this.push = (value) => {
402
- this.addPendingOperations(this.patchCreator.createListPush(this.oid, this.processInputValue(value, this.view.length)));
403
- };
404
- this.insert = (index, value) => {
405
- this.addPendingOperations(this.patchCreator.createListInsert(this.oid, index, this.processInputValue(value, index)));
406
- };
407
- this.move = (from, to) => {
408
- this.addPendingOperations(this.patchCreator.createListMoveByIndex(this.oid, from, to));
409
- };
410
- this.moveItem = (item, to) => {
411
- const itemRef = this.getItemRefValue(item);
412
- if (isRef(itemRef)) {
413
- this.addPendingOperations(this.patchCreator.createListMoveByRef(this.oid, itemRef, to));
414
- }
415
- else {
416
- const index = this.view.indexOf(item);
417
- if (index === -1) {
418
- throw new Error(`Cannot move item ${JSON.stringify(item)} which does not exist in this list`);
419
- }
420
- this.move(index, to);
421
- }
422
- };
423
- this.add = (value) => {
424
- this.addPendingOperations(this.patchCreator.createListAdd(this.oid, this.processInputValue(value, this.view.length)));
425
- };
426
- this.removeAll = (item) => {
427
- this.addPendingOperations(this.patchCreator.createListRemove(this.oid, this.getItemRefValue(item)));
428
- };
429
- this.removeFirst = (item) => {
430
- this.addPendingOperations(this.patchCreator.createListRemove(this.oid, this.getItemRefValue(item), 'first'));
431
- };
432
- this.removeLast = (item) => {
433
- this.addPendingOperations(this.patchCreator.createListRemove(this.oid, this.getItemRefValue(item), 'last'));
434
- };
435
- this.map = (callback) => {
436
- return this.view.map(callback);
437
- };
438
- this.filter = (callback) => {
439
- return this.view.filter(callback);
440
- };
441
- this.has = (value) => {
442
- if (!this.isList) {
443
- throw new Error('has() is only available on list entities');
444
- }
445
- const itemRef = this.getItemRefValue(value);
446
- if (isRef(itemRef)) {
447
- return this.view.some((item) => {
448
- if (isRef(item)) {
449
- return compareRefs(item, itemRef);
450
- }
451
- });
452
- }
453
- else {
454
- return this.view.includes(value);
455
- }
456
- };
457
- this.forEach = (callback) => {
458
- this.view.forEach(callback);
459
- };
460
- this.some = (predicate) => {
461
- return this.view.some(predicate);
462
- };
463
- this.every = (predicate) => {
464
- return this.view.every(predicate);
465
- };
466
- this.find = (predicate) => {
467
- return this.view.find(predicate);
468
- };
469
- this.includes = this.has;
470
- // TODO: make these escape hatches unnecessary
471
- this.__getViewData__ = (oid, type) => {
472
- return this.metadataFamily.get(oid).computeView(type === 'confirmed');
473
- };
474
- this.__getFamilyOids__ = () => this.metadataFamily.getAllOids();
475
- assert(!!oid, 'oid is required');
476
- this.oid = oid;
477
- this.readonlyKeys = readonlyKeys || [];
478
- this.ctx = ctx;
479
- this.files = files;
480
- this.schema = schema;
481
- this.entityFamily =
482
- childCache ||
483
- new EntityCache({
484
- initial: [this],
485
- });
486
- this.patchCreator = patchCreator;
487
- this.metadataFamily = metadataFamily;
488
- this.events = events;
489
- this.parent = parent;
490
- // TODO: should any but the root entity be listening to these?
491
- if (!this.parent) {
492
- events.add.attach(this.onAdd);
493
- events.replace.attach(this.onReplace);
494
- events.resetAll.attach(this.onResetAll);
495
- }
496
- }
497
- get metadata() {
498
- return this.metadataFamily.get(this.oid);
499
- }
500
- /**
501
- * The view of this Entity, not including nested
502
- * entities (that's the snapshot - see #getSnapshot())
503
- *
504
- * Nested entities are represented by refs.
505
- */
506
- get viewData() {
507
- if (this._viewData === undefined) {
508
- this._viewData = this.metadata.computeView();
509
- this.validate();
510
- }
511
- return this._viewData;
512
- }
513
- /** convenience getter for viewData.view */
514
- get rawView() {
515
- return this.viewData.view;
516
- }
517
- /**
518
- * An Entity's View includes the rendering of its underlying data,
519
- * connecting of children where refs were, and validation
520
- * and pruning according to schema.
521
- */
522
- get view() {
523
- if (this.cachedView !== undefined) {
524
- return this.cachedView;
525
- }
526
- if (this.viewData.deleted) {
527
- return null;
528
- }
529
- // can't use invalid data - but this should be bubbled up to
530
- // a prune point
531
- const rawView = this.rawView;
532
- const viewIsWrongType = (!rawView && !isNullable(this.schema)) ||
533
- (this.schema.type === 'array' && !Array.isArray(rawView)) ||
534
- ((this.schema.type === 'object' || this.schema.type === 'map') &&
535
- !isObject(rawView));
536
- if (viewIsWrongType) {
537
- // this will cover lists and maps, too.
538
- if (hasDefault(this.schema)) {
539
- return getDefault(this.schema);
540
- }
541
- // force null - invalid - will require parent prune
542
- return null;
543
- }
544
- this.cachedView = this.isList ? [] : {};
545
- assignOid(this.cachedView, this.oid);
546
- if (Array.isArray(rawView)) {
547
- const schema = getChildFieldSchema(this.schema, 0);
548
- if (!schema) {
549
- /**
550
- * PRUNE - this is a prune point. we can't continue
551
- * to render this data, so we'll just return [].
552
- * This skips the loop.
553
- */
554
- this.ctx.log('error', 'No child field schema for list entity.', this.oid);
555
- }
556
- else {
557
- for (let i = 0; i < rawView.length; i++) {
558
- const child = this.get(i);
559
- if (this.childIsNull(child) && !isNullable(schema)) {
560
- this.ctx.log('error', 'Child missing in non-nullable field', this.oid, 'index:', i);
561
- // this item will be pruned.
562
- }
563
- else {
564
- this.cachedView.push(child);
565
- }
566
- }
567
- }
568
- }
569
- else if (isObject(rawView)) {
570
- // iterate over known properties in object-type entities;
571
- // for maps, we just iterate over the keys.
572
- const keys = this.schema.type === 'object'
573
- ? Object.keys(this.schema.properties)
574
- : Object.keys(rawView);
575
- for (const key of keys) {
576
- const schema = getChildFieldSchema(this.schema, key);
577
- if (!schema) {
578
- /**
579
- * PRUNE - this is a prune point. we can't continue
580
- * to render this data. If this is a map, it will be
581
- * pruned empty. Otherwise, prune moves upward.
582
- *
583
- * This exits the loop.
584
- */
585
- this.ctx.log('error', 'No child field schema for object entity at key', key);
586
- if (this.schema.type === 'map') {
587
- // it's valid to prune here if it's a map
588
- this.cachedView = {};
589
- }
590
- else {
591
- // otherwise prune moves upward
592
- this.cachedView = null;
593
- }
594
- break;
595
- }
596
- const child = this.get(key);
597
- if (this.childIsNull(child) && !isNullable(schema)) {
598
- this.ctx.log('error', 'Child entity is missing for non-nullable field', this.oid, 'key:', key);
599
- /**
600
- * PRUNE - this is a prune point. we can't continue
601
- * to render this data. If this is a map, we can ignore
602
- * this value. Otherwise we must prune upward.
603
- * This exits the loop.
604
- */
605
- if (this.schema.type !== 'map') {
606
- this.cachedView = null;
607
- break;
608
- }
609
- }
610
- else {
611
- this.cachedView[key] = child;
612
- }
613
- }
614
- }
615
- return this.cachedView;
616
- }
617
- get uid() {
618
- return this.oid;
619
- }
620
- get deleted() {
621
- return this.viewData.deleted || this.view === null;
622
- }
623
- get invalid() {
624
- return !!this.validate();
625
- }
626
- get isList() {
627
- // have to turn TS off here as our two interfaces both implement
628
- // const values for this boolean.
629
- return (this.schema.type === 'array' || Array.isArray(this.viewData.view));
630
- }
631
- get updatedAt() {
632
- return this.viewData.updatedAt;
633
- }
634
- get deepUpdatedAt() {
635
- if (this.cachedDeepUpdatedAt)
636
- return this.cachedDeepUpdatedAt;
637
- // iterate over all children and take the latest timestamp
638
- let latest = this.updatedAt;
639
- if (this.isList) {
640
- this.forEach((child) => {
641
- if (child instanceof Entity) {
642
- const childTimestamp = child.deepUpdatedAt;
643
- if (childTimestamp && (!latest || childTimestamp > latest)) {
644
- latest = childTimestamp;
645
- }
646
- }
647
- });
648
- }
649
- else {
650
- this.values().forEach((child) => {
651
- if (child instanceof Entity) {
652
- const childTimestamp = child.deepUpdatedAt;
653
- if (childTimestamp && (!latest || childTimestamp > latest)) {
654
- latest = childTimestamp;
655
- }
656
- }
657
- });
658
- }
659
- this.cachedDeepUpdatedAt = latest;
660
- return latest;
661
- }
662
- /**
663
- * @internal - this is relevant to Verdant's system, not users.
664
- *
665
- * Indicates whether this document is from an outdated version
666
- * of the schema - which means it cannot be used until it is upgraded.
667
- */
668
- get isOutdatedVersion() {
669
- if (this.parent)
670
- return this.parent.isOutdatedVersion;
671
- return this.viewData.fromOlderVersion;
672
- }
673
- // array entity methods
674
- get length() {
675
- return this.view.length;
676
- }
677
- // list implements an iterator which maps items to wrapped
678
- // versions
679
- [Symbol.iterator]() {
680
- var _a;
681
- let index = 0;
682
- let length = (_a = this.view) === null || _a === void 0 ? void 0 : _a.length;
683
- return {
684
- next: () => {
685
- if (index < length) {
686
- return {
687
- value: this.get(index++),
688
- done: false,
689
- };
690
- }
691
- return {
692
- value: undefined,
693
- done: true,
694
- };
695
- },
696
- };
697
- }
698
- }
699
- function assertNotSymbol(key) {
700
- if (typeof key === 'symbol')
701
- throw new Error("Symbol keys aren't supported");
702
- }
703
- function assertNumber(key) {
704
- if (typeof key !== 'number')
705
- throw new Error('Only number keys are supported in list entities');
706
- }
707
- //# sourceMappingURL=Entity.js.map