@liveblocks/client 0.18.3 → 0.18.5

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.
package/chunk-UV2F4F4R.js DELETED
@@ -1,2457 +0,0 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});var __defProp = Object.defineProperty;
2
- var __defProps = Object.defineProperties;
3
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
7
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
- var __spreadValues = (a, b) => {
9
- for (var prop in b || (b = {}))
10
- if (__hasOwnProp.call(b, prop))
11
- __defNormalProp(a, prop, b[prop]);
12
- if (__getOwnPropSymbols)
13
- for (var prop of __getOwnPropSymbols(b)) {
14
- if (__propIsEnum.call(b, prop))
15
- __defNormalProp(a, prop, b[prop]);
16
- }
17
- return a;
18
- };
19
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
20
- var __objRest = (source, exclude) => {
21
- var target = {};
22
- for (var prop in source)
23
- if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
24
- target[prop] = source[prop];
25
- if (source != null && __getOwnPropSymbols)
26
- for (var prop of __getOwnPropSymbols(source)) {
27
- if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
28
- target[prop] = source[prop];
29
- }
30
- return target;
31
- };
32
- var __async = (__this, __arguments, generator) => {
33
- return new Promise((resolve, reject) => {
34
- var fulfilled = (value) => {
35
- try {
36
- step(generator.next(value));
37
- } catch (e) {
38
- reject(e);
39
- }
40
- };
41
- var rejected = (value) => {
42
- try {
43
- step(generator.throw(value));
44
- } catch (e) {
45
- reject(e);
46
- }
47
- };
48
- var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
49
- step((generator = generator.apply(__this, __arguments)).next());
50
- });
51
- };
52
-
53
- // src/deprecation.ts
54
- var _emittedDeprecationWarnings = /* @__PURE__ */ new Set();
55
- function deprecate(message, key = message) {
56
- if (process.env.NODE_ENV !== "production") {
57
- if (!_emittedDeprecationWarnings.has(key)) {
58
- _emittedDeprecationWarnings.add(key);
59
- console.error(`DEPRECATION WARNING: ${message}`);
60
- }
61
- }
62
- }
63
- function deprecateIf(condition, message, key = message) {
64
- if (process.env.NODE_ENV !== "production") {
65
- if (condition) {
66
- deprecate(message, key);
67
- }
68
- }
69
- }
70
- function throwUsageError(message) {
71
- if (process.env.NODE_ENV !== "production") {
72
- const usageError = new Error(message);
73
- usageError.name = "Usage error";
74
- throw usageError;
75
- }
76
- }
77
- function errorIf(condition, message) {
78
- if (process.env.NODE_ENV !== "production") {
79
- if (condition) {
80
- throwUsageError(message);
81
- }
82
- }
83
- }
84
-
85
- // src/assert.ts
86
- function assertNever(_value, errmsg) {
87
- throw new Error(errmsg);
88
- }
89
- function assert(condition, errmsg) {
90
- if (process.env.NODE_ENV !== "production" && !condition) {
91
- const err = new Error(errmsg);
92
- err.name = "Assertion failure";
93
- throw err;
94
- }
95
- }
96
- function nn(value, errmsg = "Expected value to be non-nullable") {
97
- assert(value !== null && value !== void 0, errmsg);
98
- return value;
99
- }
100
-
101
- // src/types/ClientMsg.ts
102
- var ClientMsgCode = /* @__PURE__ */ ((ClientMsgCode2) => {
103
- ClientMsgCode2[ClientMsgCode2["UPDATE_PRESENCE"] = 100] = "UPDATE_PRESENCE";
104
- ClientMsgCode2[ClientMsgCode2["BROADCAST_EVENT"] = 103] = "BROADCAST_EVENT";
105
- ClientMsgCode2[ClientMsgCode2["FETCH_STORAGE"] = 200] = "FETCH_STORAGE";
106
- ClientMsgCode2[ClientMsgCode2["UPDATE_STORAGE"] = 201] = "UPDATE_STORAGE";
107
- return ClientMsgCode2;
108
- })(ClientMsgCode || {});
109
-
110
- // src/types/Op.ts
111
- var OpCode = /* @__PURE__ */ ((OpCode2) => {
112
- OpCode2[OpCode2["INIT"] = 0] = "INIT";
113
- OpCode2[OpCode2["SET_PARENT_KEY"] = 1] = "SET_PARENT_KEY";
114
- OpCode2[OpCode2["CREATE_LIST"] = 2] = "CREATE_LIST";
115
- OpCode2[OpCode2["UPDATE_OBJECT"] = 3] = "UPDATE_OBJECT";
116
- OpCode2[OpCode2["CREATE_OBJECT"] = 4] = "CREATE_OBJECT";
117
- OpCode2[OpCode2["DELETE_CRDT"] = 5] = "DELETE_CRDT";
118
- OpCode2[OpCode2["DELETE_OBJECT_KEY"] = 6] = "DELETE_OBJECT_KEY";
119
- OpCode2[OpCode2["CREATE_MAP"] = 7] = "CREATE_MAP";
120
- OpCode2[OpCode2["CREATE_REGISTER"] = 8] = "CREATE_REGISTER";
121
- return OpCode2;
122
- })(OpCode || {});
123
-
124
- // src/types/SerializedCrdt.ts
125
- var CrdtType = /* @__PURE__ */ ((CrdtType2) => {
126
- CrdtType2[CrdtType2["OBJECT"] = 0] = "OBJECT";
127
- CrdtType2[CrdtType2["LIST"] = 1] = "LIST";
128
- CrdtType2[CrdtType2["MAP"] = 2] = "MAP";
129
- CrdtType2[CrdtType2["REGISTER"] = 3] = "REGISTER";
130
- return CrdtType2;
131
- })(CrdtType || {});
132
- function isRootCrdt(crdt) {
133
- return crdt.type === 0 /* OBJECT */ && !isChildCrdt(crdt);
134
- }
135
- function isChildCrdt(crdt) {
136
- return crdt.parentId !== void 0 && crdt.parentKey !== void 0;
137
- }
138
-
139
- // src/types/ServerMsg.ts
140
- var ServerMsgCode = /* @__PURE__ */ ((ServerMsgCode2) => {
141
- ServerMsgCode2[ServerMsgCode2["UPDATE_PRESENCE"] = 100] = "UPDATE_PRESENCE";
142
- ServerMsgCode2[ServerMsgCode2["USER_JOINED"] = 101] = "USER_JOINED";
143
- ServerMsgCode2[ServerMsgCode2["USER_LEFT"] = 102] = "USER_LEFT";
144
- ServerMsgCode2[ServerMsgCode2["BROADCASTED_EVENT"] = 103] = "BROADCASTED_EVENT";
145
- ServerMsgCode2[ServerMsgCode2["ROOM_STATE"] = 104] = "ROOM_STATE";
146
- ServerMsgCode2[ServerMsgCode2["INITIAL_STORAGE_STATE"] = 200] = "INITIAL_STORAGE_STATE";
147
- ServerMsgCode2[ServerMsgCode2["UPDATE_STORAGE"] = 201] = "UPDATE_STORAGE";
148
- return ServerMsgCode2;
149
- })(ServerMsgCode || {});
150
-
151
- // src/types/index.ts
152
- function isRoomEventName(value) {
153
- return value === "my-presence" || value === "others" || value === "event" || value === "error" || value === "connection" || value === "history";
154
- }
155
- var WebsocketCloseCodes = /* @__PURE__ */ ((WebsocketCloseCodes2) => {
156
- WebsocketCloseCodes2[WebsocketCloseCodes2["CLOSE_ABNORMAL"] = 1006] = "CLOSE_ABNORMAL";
157
- WebsocketCloseCodes2[WebsocketCloseCodes2["INVALID_MESSAGE_FORMAT"] = 4e3] = "INVALID_MESSAGE_FORMAT";
158
- WebsocketCloseCodes2[WebsocketCloseCodes2["NOT_ALLOWED"] = 4001] = "NOT_ALLOWED";
159
- WebsocketCloseCodes2[WebsocketCloseCodes2["MAX_NUMBER_OF_MESSAGES_PER_SECONDS"] = 4002] = "MAX_NUMBER_OF_MESSAGES_PER_SECONDS";
160
- WebsocketCloseCodes2[WebsocketCloseCodes2["MAX_NUMBER_OF_CONCURRENT_CONNECTIONS"] = 4003] = "MAX_NUMBER_OF_CONCURRENT_CONNECTIONS";
161
- WebsocketCloseCodes2[WebsocketCloseCodes2["MAX_NUMBER_OF_MESSAGES_PER_DAY_PER_APP"] = 4004] = "MAX_NUMBER_OF_MESSAGES_PER_DAY_PER_APP";
162
- WebsocketCloseCodes2[WebsocketCloseCodes2["MAX_NUMBER_OF_CONCURRENT_CONNECTIONS_PER_ROOM"] = 4005] = "MAX_NUMBER_OF_CONCURRENT_CONNECTIONS_PER_ROOM";
163
- WebsocketCloseCodes2[WebsocketCloseCodes2["CLOSE_WITHOUT_RETRY"] = 4999] = "CLOSE_WITHOUT_RETRY";
164
- return WebsocketCloseCodes2;
165
- })(WebsocketCloseCodes || {});
166
-
167
- // src/position.ts
168
- var min = 32;
169
- var max = 126;
170
- function makePosition(before, after) {
171
- if (before !== void 0 && after !== void 0) {
172
- return pos(makePositionFromCodes(posCodes(before), posCodes(after)));
173
- } else if (before !== void 0) {
174
- return getNextPosition(before);
175
- } else if (after !== void 0) {
176
- return getPreviousPosition(after);
177
- }
178
- return pos([min + 1]);
179
- }
180
- function getPreviousPosition(after) {
181
- const result = [];
182
- const afterCodes = posCodes(after);
183
- for (let i = 0; i < afterCodes.length; i++) {
184
- const code = afterCodes[i];
185
- if (code <= min + 1) {
186
- result.push(min);
187
- if (afterCodes.length - 1 === i) {
188
- result.push(max);
189
- break;
190
- }
191
- } else {
192
- result.push(code - 1);
193
- break;
194
- }
195
- }
196
- return pos(result);
197
- }
198
- function getNextPosition(before) {
199
- const result = [];
200
- const beforeCodes = posCodes(before);
201
- for (let i = 0; i < beforeCodes.length; i++) {
202
- const code = beforeCodes[i];
203
- if (code === max) {
204
- result.push(code);
205
- if (beforeCodes.length - 1 === i) {
206
- result.push(min + 1);
207
- break;
208
- }
209
- } else {
210
- result.push(code + 1);
211
- break;
212
- }
213
- }
214
- return pos(result);
215
- }
216
- function makePositionFromCodes(before, after) {
217
- let index = 0;
218
- const result = [];
219
- while (true) {
220
- const beforeDigit = before[index] || min;
221
- const afterDigit = after[index] || max;
222
- if (beforeDigit > afterDigit) {
223
- throw new Error(
224
- `Impossible to generate position between ${before} and ${after}`
225
- );
226
- }
227
- if (beforeDigit === afterDigit) {
228
- result.push(beforeDigit);
229
- index++;
230
- continue;
231
- }
232
- if (afterDigit - beforeDigit === 1) {
233
- result.push(beforeDigit);
234
- result.push(...makePositionFromCodes(before.slice(index + 1), []));
235
- break;
236
- }
237
- const mid = afterDigit + beforeDigit >> 1;
238
- result.push(mid);
239
- break;
240
- }
241
- return result;
242
- }
243
- function posCodes(str) {
244
- const codes = [];
245
- for (let i = 0; i < str.length; i++) {
246
- codes.push(str.charCodeAt(i));
247
- }
248
- return codes;
249
- }
250
- function pos(codes) {
251
- return String.fromCharCode(...codes);
252
- }
253
- function comparePosition(posA, posB) {
254
- const aCodes = posCodes(posA);
255
- const bCodes = posCodes(posB);
256
- const maxLength = Math.max(aCodes.length, bCodes.length);
257
- for (let i = 0; i < maxLength; i++) {
258
- const a = aCodes[i] === void 0 ? min : aCodes[i];
259
- const b = bCodes[i] === void 0 ? min : bCodes[i];
260
- if (a === b) {
261
- continue;
262
- } else {
263
- return a - b;
264
- }
265
- }
266
- throw new Error(
267
- `Impossible to compare similar position "${posA}" and "${posB}"`
268
- );
269
- }
270
-
271
- // src/AbstractCrdt.ts
272
- function crdtAsLiveNode(value) {
273
- return value;
274
- }
275
- function HasParent(node, key) {
276
- return Object.freeze({ type: "HasParent", node, key });
277
- }
278
- var NoParent = Object.freeze({ type: "NoParent" });
279
- function Orphaned(oldKey) {
280
- return Object.freeze({ type: "Orphaned", oldKey });
281
- }
282
- var AbstractCrdt = class {
283
- constructor() {
284
- this._parent = NoParent;
285
- }
286
- _getParentKeyOrThrow() {
287
- switch (this.parent.type) {
288
- case "HasParent":
289
- return this.parent.key;
290
- case "NoParent":
291
- throw new Error("Parent key is missing");
292
- case "Orphaned":
293
- return this.parent.oldKey;
294
- default:
295
- return assertNever(this.parent, "Unknown state");
296
- }
297
- }
298
- get _pool() {
299
- return this.__pool;
300
- }
301
- get roomId() {
302
- return this.__pool ? this.__pool.roomId : null;
303
- }
304
- get _id() {
305
- return this.__id;
306
- }
307
- get parent() {
308
- return this._parent;
309
- }
310
- get _parentNode() {
311
- switch (this.parent.type) {
312
- case "HasParent":
313
- return this.parent.node;
314
- case "NoParent":
315
- return null;
316
- case "Orphaned":
317
- return null;
318
- default:
319
- return assertNever(this.parent, "Unknown state");
320
- }
321
- }
322
- get _parentKey() {
323
- switch (this.parent.type) {
324
- case "HasParent":
325
- return this.parent.key;
326
- case "NoParent":
327
- return null;
328
- case "Orphaned":
329
- return this.parent.oldKey;
330
- default:
331
- return assertNever(this.parent, "Unknown state");
332
- }
333
- }
334
- _apply(op, _isLocal) {
335
- switch (op.type) {
336
- case 5 /* DELETE_CRDT */: {
337
- if (this.parent.type === "HasParent") {
338
- return this.parent.node._detachChild(crdtAsLiveNode(this));
339
- }
340
- return { modified: false };
341
- }
342
- }
343
- return { modified: false };
344
- }
345
- _setParentLink(newParentNode, newParentKey) {
346
- switch (this.parent.type) {
347
- case "HasParent":
348
- if (this.parent.node !== newParentNode) {
349
- throw new Error("Cannot set parent: node already has a parent");
350
- } else {
351
- this._parent = HasParent(newParentNode, newParentKey);
352
- return;
353
- }
354
- case "Orphaned":
355
- case "NoParent": {
356
- this._parent = HasParent(newParentNode, newParentKey);
357
- return;
358
- }
359
- default:
360
- return assertNever(this.parent, "Unknown state");
361
- }
362
- }
363
- _attach(id, pool) {
364
- if (this.__id || this.__pool) {
365
- throw new Error("Cannot attach node: already attached");
366
- }
367
- pool.addNode(id, crdtAsLiveNode(this));
368
- this.__id = id;
369
- this.__pool = pool;
370
- }
371
- _detach() {
372
- if (this.__pool && this.__id) {
373
- this.__pool.deleteNode(this.__id);
374
- }
375
- switch (this.parent.type) {
376
- case "HasParent": {
377
- this._parent = Orphaned(this.parent.key);
378
- break;
379
- }
380
- case "NoParent": {
381
- this._parent = NoParent;
382
- break;
383
- }
384
- case "Orphaned": {
385
- this._parent = Orphaned(this.parent.oldKey);
386
- break;
387
- }
388
- default:
389
- assertNever(this.parent, "Unknown state");
390
- }
391
- this.__pool = void 0;
392
- }
393
- invalidate() {
394
- if (this._cachedImmutable !== void 0) {
395
- this._cachedImmutable = void 0;
396
- if (this.parent.type === "HasParent") {
397
- this.parent.node.invalidate();
398
- }
399
- }
400
- }
401
- toImmutable() {
402
- if (this._cachedImmutable === void 0) {
403
- this._cachedImmutable = this._toImmutable();
404
- }
405
- return this._cachedImmutable;
406
- }
407
- };
408
-
409
- // src/LiveRegister.ts
410
- var LiveRegister = class extends AbstractCrdt {
411
- constructor(data) {
412
- super();
413
- this._data = data;
414
- }
415
- get data() {
416
- return this._data;
417
- }
418
- static _deserialize([id, item], _parentToChildren, pool) {
419
- const register = new LiveRegister(item.data);
420
- register._attach(id, pool);
421
- return register;
422
- }
423
- _toOps(parentId, parentKey, pool) {
424
- if (this._id === void 0) {
425
- throw new Error(
426
- "Cannot serialize register if parentId or parentKey is undefined"
427
- );
428
- }
429
- return [
430
- {
431
- type: 8 /* CREATE_REGISTER */,
432
- opId: pool == null ? void 0 : pool.generateOpId(),
433
- id: this._id,
434
- parentId,
435
- parentKey,
436
- data: this.data
437
- }
438
- ];
439
- }
440
- _serialize() {
441
- if (this.parent.type !== "HasParent") {
442
- throw new Error("Cannot serialize LiveRegister if parent is missing");
443
- }
444
- return {
445
- type: 3 /* REGISTER */,
446
- parentId: nn(this.parent.node._id, "Parent node expected to have ID"),
447
- parentKey: this.parent.key,
448
- data: this.data
449
- };
450
- }
451
- _attachChild(_op) {
452
- throw new Error("Method not implemented.");
453
- }
454
- _detachChild(_crdt) {
455
- throw new Error("Method not implemented.");
456
- }
457
- _apply(op, isLocal) {
458
- return super._apply(op, isLocal);
459
- }
460
- _toImmutable() {
461
- return this._data;
462
- }
463
- };
464
-
465
- // src/LiveMap.ts
466
- var LiveMap = class extends AbstractCrdt {
467
- constructor(entries2) {
468
- super();
469
- this.unacknowledgedSet = /* @__PURE__ */ new Map();
470
- if (entries2) {
471
- const mappedEntries = [];
472
- for (const entry of entries2) {
473
- const value = lsonToLiveNode(entry[1]);
474
- value._setParentLink(this, entry[0]);
475
- mappedEntries.push([entry[0], value]);
476
- }
477
- this._map = new Map(mappedEntries);
478
- } else {
479
- this._map = /* @__PURE__ */ new Map();
480
- }
481
- }
482
- _toOps(parentId, parentKey, pool) {
483
- if (this._id === void 0) {
484
- throw new Error("Cannot serialize item is not attached");
485
- }
486
- const ops = [];
487
- const op = {
488
- id: this._id,
489
- opId: pool == null ? void 0 : pool.generateOpId(),
490
- type: 7 /* CREATE_MAP */,
491
- parentId,
492
- parentKey
493
- };
494
- ops.push(op);
495
- for (const [key, value] of this._map) {
496
- ops.push(...value._toOps(this._id, key, pool));
497
- }
498
- return ops;
499
- }
500
- static _deserialize([id, _item], parentToChildren, pool) {
501
- const map = new LiveMap();
502
- map._attach(id, pool);
503
- const children = parentToChildren.get(id);
504
- if (children === void 0) {
505
- return map;
506
- }
507
- for (const [id2, crdt] of children) {
508
- const child = deserialize([id2, crdt], parentToChildren, pool);
509
- child._setParentLink(map, crdt.parentKey);
510
- map._map.set(crdt.parentKey, child);
511
- map.invalidate();
512
- }
513
- return map;
514
- }
515
- _attach(id, pool) {
516
- super._attach(id, pool);
517
- for (const [_key, value] of this._map) {
518
- if (isLiveNode(value)) {
519
- value._attach(pool.generateId(), pool);
520
- }
521
- }
522
- }
523
- _attachChild(op, source) {
524
- if (this._pool === void 0) {
525
- throw new Error("Can't attach child if managed pool is not present");
526
- }
527
- const { id, parentKey, opId } = op;
528
- const key = parentKey;
529
- const child = creationOpToLiveNode(op);
530
- if (this._pool.getNode(id) !== void 0) {
531
- return { modified: false };
532
- }
533
- if (source === 2 /* ACK */) {
534
- const lastUpdateOpId = this.unacknowledgedSet.get(key);
535
- if (lastUpdateOpId === opId) {
536
- this.unacknowledgedSet.delete(key);
537
- return { modified: false };
538
- } else if (lastUpdateOpId !== void 0) {
539
- return { modified: false };
540
- }
541
- } else if (source === 1 /* REMOTE */) {
542
- this.unacknowledgedSet.delete(key);
543
- }
544
- const previousValue = this._map.get(key);
545
- let reverse;
546
- if (previousValue) {
547
- const thisId = nn(this._id);
548
- reverse = previousValue._toOps(thisId, key);
549
- previousValue._detach();
550
- } else {
551
- reverse = [{ type: 5 /* DELETE_CRDT */, id }];
552
- }
553
- child._setParentLink(this, key);
554
- child._attach(id, this._pool);
555
- this._map.set(key, child);
556
- this.invalidate();
557
- return {
558
- modified: {
559
- node: this,
560
- type: "LiveMap",
561
- updates: { [key]: { type: "update" } }
562
- },
563
- reverse
564
- };
565
- }
566
- _detach() {
567
- super._detach();
568
- for (const item of this._map.values()) {
569
- item._detach();
570
- }
571
- }
572
- _detachChild(child) {
573
- const id = nn(this._id);
574
- const parentKey = nn(child._parentKey);
575
- const reverse = child._toOps(id, parentKey, this._pool);
576
- for (const [key, value] of this._map) {
577
- if (value === child) {
578
- this._map.delete(key);
579
- this.invalidate();
580
- }
581
- }
582
- child._detach();
583
- const storageUpdate = {
584
- node: this,
585
- type: "LiveMap",
586
- updates: { [parentKey]: { type: "delete" } }
587
- };
588
- return { modified: storageUpdate, reverse };
589
- }
590
- _serialize() {
591
- if (this.parent.type !== "HasParent") {
592
- throw new Error("Cannot serialize LiveMap if parent is missing");
593
- }
594
- return {
595
- type: 2 /* MAP */,
596
- parentId: nn(this.parent.node._id, "Parent node expected to have ID"),
597
- parentKey: this.parent.key
598
- };
599
- }
600
- get(key) {
601
- const value = this._map.get(key);
602
- if (value === void 0) {
603
- return void 0;
604
- }
605
- return liveNodeToLson(value);
606
- }
607
- set(key, value) {
608
- const oldValue = this._map.get(key);
609
- if (oldValue) {
610
- oldValue._detach();
611
- }
612
- const item = lsonToLiveNode(value);
613
- item._setParentLink(this, key);
614
- this._map.set(key, item);
615
- this.invalidate();
616
- if (this._pool && this._id) {
617
- const id = this._pool.generateId();
618
- item._attach(id, this._pool);
619
- const storageUpdates = /* @__PURE__ */ new Map();
620
- storageUpdates.set(this._id, {
621
- node: this,
622
- type: "LiveMap",
623
- updates: { [key]: { type: "update" } }
624
- });
625
- const ops = item._toOps(this._id, key, this._pool);
626
- this.unacknowledgedSet.set(key, nn(ops[0].opId));
627
- this._pool.dispatch(
628
- item._toOps(this._id, key, this._pool),
629
- oldValue ? oldValue._toOps(this._id, key) : [{ type: 5 /* DELETE_CRDT */, id }],
630
- storageUpdates
631
- );
632
- }
633
- }
634
- get size() {
635
- return this._map.size;
636
- }
637
- has(key) {
638
- return this._map.has(key);
639
- }
640
- delete(key) {
641
- const item = this._map.get(key);
642
- if (item === void 0) {
643
- return false;
644
- }
645
- item._detach();
646
- this._map.delete(key);
647
- this.invalidate();
648
- if (this._pool && item._id) {
649
- const thisId = nn(this._id);
650
- const storageUpdates = /* @__PURE__ */ new Map();
651
- storageUpdates.set(thisId, {
652
- node: this,
653
- type: "LiveMap",
654
- updates: { [key]: { type: "delete" } }
655
- });
656
- this._pool.dispatch(
657
- [
658
- {
659
- type: 5 /* DELETE_CRDT */,
660
- id: item._id,
661
- opId: this._pool.generateOpId()
662
- }
663
- ],
664
- item._toOps(thisId, key),
665
- storageUpdates
666
- );
667
- }
668
- return true;
669
- }
670
- entries() {
671
- const innerIterator = this._map.entries();
672
- return {
673
- [Symbol.iterator]() {
674
- return this;
675
- },
676
- next() {
677
- const iteratorValue = innerIterator.next();
678
- if (iteratorValue.done) {
679
- return {
680
- done: true,
681
- value: void 0
682
- };
683
- }
684
- const entry = iteratorValue.value;
685
- const key = entry[0];
686
- const value = liveNodeToLson(iteratorValue.value[1]);
687
- return {
688
- value: [key, value]
689
- };
690
- }
691
- };
692
- }
693
- [Symbol.iterator]() {
694
- return this.entries();
695
- }
696
- keys() {
697
- return this._map.keys();
698
- }
699
- values() {
700
- const innerIterator = this._map.values();
701
- return {
702
- [Symbol.iterator]() {
703
- return this;
704
- },
705
- next() {
706
- const iteratorValue = innerIterator.next();
707
- if (iteratorValue.done) {
708
- return {
709
- done: true,
710
- value: void 0
711
- };
712
- }
713
- const value = liveNodeToLson(iteratorValue.value);
714
- return { value };
715
- }
716
- };
717
- }
718
- forEach(callback) {
719
- for (const entry of this) {
720
- callback(entry[1], entry[0], this);
721
- }
722
- }
723
- toImmutable() {
724
- return super.toImmutable();
725
- }
726
- _toImmutable() {
727
- const result = /* @__PURE__ */ new Map();
728
- for (const [key, value] of this._map) {
729
- result.set(key, value.toImmutable());
730
- }
731
- return freeze(result);
732
- }
733
- };
734
-
735
- // src/LiveObject.ts
736
- var LiveObject = class extends AbstractCrdt {
737
- constructor(obj = {}) {
738
- super();
739
- this._propToLastUpdate = /* @__PURE__ */ new Map();
740
- for (const key in obj) {
741
- const value = obj[key];
742
- if (value === void 0) {
743
- continue;
744
- } else if (isLiveNode(value)) {
745
- value._setParentLink(this, key);
746
- }
747
- }
748
- this._map = new Map(Object.entries(obj));
749
- }
750
- _toOps(parentId, parentKey, pool) {
751
- if (this._id === void 0) {
752
- throw new Error("Cannot serialize item is not attached");
753
- }
754
- const opId = pool == null ? void 0 : pool.generateOpId();
755
- const ops = [];
756
- const op = parentId !== void 0 && parentKey !== void 0 ? {
757
- type: 4 /* CREATE_OBJECT */,
758
- id: this._id,
759
- opId,
760
- parentId,
761
- parentKey,
762
- data: {}
763
- } : { type: 4 /* CREATE_OBJECT */, id: this._id, opId, data: {} };
764
- ops.push(op);
765
- for (const [key, value] of this._map) {
766
- if (isLiveNode(value)) {
767
- ops.push(...value._toOps(this._id, key, pool));
768
- } else {
769
- op.data[key] = value;
770
- }
771
- }
772
- return ops;
773
- }
774
- static _deserialize([id, item], parentToChildren, pool) {
775
- const liveObj = new LiveObject(item.data);
776
- liveObj._attach(id, pool);
777
- return this._deserializeChildren(liveObj, parentToChildren, pool);
778
- }
779
- static _deserializeChildren(liveObj, parentToChildren, pool) {
780
- const children = parentToChildren.get(nn(liveObj._id));
781
- if (children === void 0) {
782
- return liveObj;
783
- }
784
- for (const [id, crdt] of children) {
785
- const child = deserializeToLson([id, crdt], parentToChildren, pool);
786
- if (isLiveStructure(child)) {
787
- child._setParentLink(liveObj, crdt.parentKey);
788
- }
789
- liveObj._map.set(crdt.parentKey, child);
790
- liveObj.invalidate();
791
- }
792
- return liveObj;
793
- }
794
- _attach(id, pool) {
795
- super._attach(id, pool);
796
- for (const [_key, value] of this._map) {
797
- if (isLiveNode(value)) {
798
- value._attach(pool.generateId(), pool);
799
- }
800
- }
801
- }
802
- _attachChild(op, source) {
803
- if (this._pool === void 0) {
804
- throw new Error("Can't attach child if managed pool is not present");
805
- }
806
- const { id, opId, parentKey: key } = op;
807
- const child = creationOpToLson(op);
808
- if (this._pool.getNode(id) !== void 0) {
809
- if (this._propToLastUpdate.get(key) === opId) {
810
- this._propToLastUpdate.delete(key);
811
- }
812
- return { modified: false };
813
- }
814
- if (source === 0 /* UNDOREDO_RECONNECT */) {
815
- this._propToLastUpdate.set(key, nn(opId));
816
- } else if (this._propToLastUpdate.get(key) === void 0) {
817
- } else if (this._propToLastUpdate.get(key) === opId) {
818
- this._propToLastUpdate.delete(key);
819
- return { modified: false };
820
- } else {
821
- return { modified: false };
822
- }
823
- const thisId = nn(this._id);
824
- const previousValue = this._map.get(key);
825
- let reverse;
826
- if (isLiveNode(previousValue)) {
827
- reverse = previousValue._toOps(thisId, key);
828
- previousValue._detach();
829
- } else if (previousValue === void 0) {
830
- reverse = [{ type: 6 /* DELETE_OBJECT_KEY */, id: thisId, key }];
831
- } else {
832
- reverse = [
833
- {
834
- type: 3 /* UPDATE_OBJECT */,
835
- id: thisId,
836
- data: { [key]: previousValue }
837
- }
838
- ];
839
- }
840
- this._map.set(key, child);
841
- this.invalidate();
842
- if (isLiveStructure(child)) {
843
- child._setParentLink(this, key);
844
- child._attach(id, this._pool);
845
- }
846
- return {
847
- reverse,
848
- modified: {
849
- node: this,
850
- type: "LiveObject",
851
- updates: { [key]: { type: "update" } }
852
- }
853
- };
854
- }
855
- _detachChild(child) {
856
- if (child) {
857
- const id = nn(this._id);
858
- const parentKey = nn(child._parentKey);
859
- const reverse = child._toOps(id, parentKey, this._pool);
860
- for (const [key, value] of this._map) {
861
- if (value === child) {
862
- this._map.delete(key);
863
- this.invalidate();
864
- }
865
- }
866
- child._detach();
867
- const storageUpdate = {
868
- node: this,
869
- type: "LiveObject",
870
- updates: {
871
- [parentKey]: { type: "delete" }
872
- }
873
- };
874
- return { modified: storageUpdate, reverse };
875
- }
876
- return { modified: false };
877
- }
878
- _detach() {
879
- super._detach();
880
- for (const value of this._map.values()) {
881
- if (isLiveNode(value)) {
882
- value._detach();
883
- }
884
- }
885
- }
886
- _apply(op, isLocal) {
887
- if (op.type === 3 /* UPDATE_OBJECT */) {
888
- return this._applyUpdate(op, isLocal);
889
- } else if (op.type === 6 /* DELETE_OBJECT_KEY */) {
890
- return this._applyDeleteObjectKey(op);
891
- }
892
- return super._apply(op, isLocal);
893
- }
894
- _serialize() {
895
- const data = {};
896
- for (const [key, value] of this._map) {
897
- if (!isLiveNode(value)) {
898
- data[key] = value;
899
- }
900
- }
901
- if (this.parent.type === "HasParent" && this.parent.node._id) {
902
- return {
903
- type: 0 /* OBJECT */,
904
- parentId: this.parent.node._id,
905
- parentKey: this.parent.key,
906
- data
907
- };
908
- } else {
909
- return {
910
- type: 0 /* OBJECT */,
911
- data
912
- };
913
- }
914
- }
915
- _applyUpdate(op, isLocal) {
916
- let isModified = false;
917
- const id = nn(this._id);
918
- const reverse = [];
919
- const reverseUpdate = {
920
- type: 3 /* UPDATE_OBJECT */,
921
- id,
922
- data: {}
923
- };
924
- reverse.push(reverseUpdate);
925
- for (const key in op.data) {
926
- const oldValue = this._map.get(key);
927
- if (isLiveNode(oldValue)) {
928
- reverse.push(...oldValue._toOps(id, key));
929
- oldValue._detach();
930
- } else if (oldValue !== void 0) {
931
- reverseUpdate.data[key] = oldValue;
932
- } else if (oldValue === void 0) {
933
- reverse.push({ type: 6 /* DELETE_OBJECT_KEY */, id, key });
934
- }
935
- }
936
- const updateDelta = {};
937
- for (const key in op.data) {
938
- const value = op.data[key];
939
- if (value === void 0) {
940
- continue;
941
- }
942
- if (isLocal) {
943
- this._propToLastUpdate.set(key, nn(op.opId));
944
- } else if (this._propToLastUpdate.get(key) === void 0) {
945
- isModified = true;
946
- } else if (this._propToLastUpdate.get(key) === op.opId) {
947
- this._propToLastUpdate.delete(key);
948
- continue;
949
- } else {
950
- continue;
951
- }
952
- const oldValue = this._map.get(key);
953
- if (isLiveNode(oldValue)) {
954
- oldValue._detach();
955
- }
956
- isModified = true;
957
- updateDelta[key] = { type: "update" };
958
- this._map.set(key, value);
959
- this.invalidate();
960
- }
961
- if (Object.keys(reverseUpdate.data).length !== 0) {
962
- reverse.unshift(reverseUpdate);
963
- }
964
- return isModified ? {
965
- modified: {
966
- node: this,
967
- type: "LiveObject",
968
- updates: updateDelta
969
- },
970
- reverse
971
- } : { modified: false };
972
- }
973
- _applyDeleteObjectKey(op) {
974
- const key = op.key;
975
- if (this._map.has(key) === false) {
976
- return { modified: false };
977
- }
978
- if (this._propToLastUpdate.get(key) !== void 0) {
979
- return { modified: false };
980
- }
981
- const oldValue = this._map.get(key);
982
- const id = nn(this._id);
983
- let reverse = [];
984
- if (isLiveNode(oldValue)) {
985
- reverse = oldValue._toOps(id, op.key);
986
- oldValue._detach();
987
- } else if (oldValue !== void 0) {
988
- reverse = [
989
- {
990
- type: 3 /* UPDATE_OBJECT */,
991
- id,
992
- data: { [key]: oldValue }
993
- }
994
- ];
995
- }
996
- this._map.delete(key);
997
- this.invalidate();
998
- return {
999
- modified: {
1000
- node: this,
1001
- type: "LiveObject",
1002
- updates: { [op.key]: { type: "delete" } }
1003
- },
1004
- reverse
1005
- };
1006
- }
1007
- toObject() {
1008
- return fromEntries(this._map);
1009
- }
1010
- set(key, value) {
1011
- this.update({ [key]: value });
1012
- }
1013
- get(key) {
1014
- return this._map.get(key);
1015
- }
1016
- delete(key) {
1017
- const keyAsString = key;
1018
- const oldValue = this._map.get(keyAsString);
1019
- if (oldValue === void 0) {
1020
- return;
1021
- }
1022
- if (this._pool === void 0 || this._id === void 0) {
1023
- if (isLiveNode(oldValue)) {
1024
- oldValue._detach();
1025
- }
1026
- this._map.delete(keyAsString);
1027
- this.invalidate();
1028
- return;
1029
- }
1030
- let reverse;
1031
- if (isLiveNode(oldValue)) {
1032
- oldValue._detach();
1033
- reverse = oldValue._toOps(this._id, keyAsString);
1034
- } else {
1035
- reverse = [
1036
- {
1037
- type: 3 /* UPDATE_OBJECT */,
1038
- data: { [keyAsString]: oldValue },
1039
- id: this._id
1040
- }
1041
- ];
1042
- }
1043
- this._map.delete(keyAsString);
1044
- this.invalidate();
1045
- const storageUpdates = /* @__PURE__ */ new Map();
1046
- storageUpdates.set(this._id, {
1047
- node: this,
1048
- type: "LiveObject",
1049
- updates: { [key]: { type: "delete" } }
1050
- });
1051
- this._pool.dispatch(
1052
- [
1053
- {
1054
- type: 6 /* DELETE_OBJECT_KEY */,
1055
- key: keyAsString,
1056
- id: this._id,
1057
- opId: this._pool.generateOpId()
1058
- }
1059
- ],
1060
- reverse,
1061
- storageUpdates
1062
- );
1063
- }
1064
- update(patch) {
1065
- if (this._pool === void 0 || this._id === void 0) {
1066
- for (const key in patch) {
1067
- const newValue = patch[key];
1068
- if (newValue === void 0) {
1069
- continue;
1070
- }
1071
- const oldValue = this._map.get(key);
1072
- if (isLiveNode(oldValue)) {
1073
- oldValue._detach();
1074
- }
1075
- if (isLiveNode(newValue)) {
1076
- newValue._setParentLink(this, key);
1077
- }
1078
- this._map.set(key, newValue);
1079
- this.invalidate();
1080
- }
1081
- return;
1082
- }
1083
- const ops = [];
1084
- const reverseOps = [];
1085
- const opId = this._pool.generateOpId();
1086
- const updatedProps = {};
1087
- const reverseUpdateOp = {
1088
- id: this._id,
1089
- type: 3 /* UPDATE_OBJECT */,
1090
- data: {}
1091
- };
1092
- const updateDelta = {};
1093
- for (const key in patch) {
1094
- const newValue = patch[key];
1095
- if (newValue === void 0) {
1096
- continue;
1097
- }
1098
- const oldValue = this._map.get(key);
1099
- if (isLiveNode(oldValue)) {
1100
- reverseOps.push(...oldValue._toOps(this._id, key));
1101
- oldValue._detach();
1102
- } else if (oldValue === void 0) {
1103
- reverseOps.push({ type: 6 /* DELETE_OBJECT_KEY */, id: this._id, key });
1104
- } else {
1105
- reverseUpdateOp.data[key] = oldValue;
1106
- }
1107
- if (isLiveNode(newValue)) {
1108
- newValue._setParentLink(this, key);
1109
- newValue._attach(this._pool.generateId(), this._pool);
1110
- const newAttachChildOps = newValue._toOps(this._id, key, this._pool);
1111
- const createCrdtOp = newAttachChildOps.find(
1112
- (op) => op.parentId === this._id
1113
- );
1114
- if (createCrdtOp) {
1115
- this._propToLastUpdate.set(key, nn(createCrdtOp.opId));
1116
- }
1117
- ops.push(...newAttachChildOps);
1118
- } else {
1119
- updatedProps[key] = newValue;
1120
- this._propToLastUpdate.set(key, opId);
1121
- }
1122
- this._map.set(key, newValue);
1123
- this.invalidate();
1124
- updateDelta[key] = { type: "update" };
1125
- }
1126
- if (Object.keys(reverseUpdateOp.data).length !== 0) {
1127
- reverseOps.unshift(reverseUpdateOp);
1128
- }
1129
- if (Object.keys(updatedProps).length !== 0) {
1130
- ops.unshift({
1131
- opId,
1132
- id: this._id,
1133
- type: 3 /* UPDATE_OBJECT */,
1134
- data: updatedProps
1135
- });
1136
- }
1137
- const storageUpdates = /* @__PURE__ */ new Map();
1138
- storageUpdates.set(this._id, {
1139
- node: this,
1140
- type: "LiveObject",
1141
- updates: updateDelta
1142
- });
1143
- this._pool.dispatch(ops, reverseOps, storageUpdates);
1144
- }
1145
- toImmutable() {
1146
- return super.toImmutable();
1147
- }
1148
- _toImmutable() {
1149
- const result = {};
1150
- for (const [key, val] of this._map) {
1151
- result[key] = isLiveStructure(val) ? val.toImmutable() : val;
1152
- }
1153
- return process.env.NODE_ENV === "production" ? result : Object.freeze(result);
1154
- }
1155
- };
1156
-
1157
- // src/utils.ts
1158
- var freeze = process.env.NODE_ENV === "production" ? (x) => x : Object.freeze;
1159
- function compact(items) {
1160
- return items.filter(
1161
- (item) => item !== null && item !== void 0
1162
- );
1163
- }
1164
- function compactObject(obj) {
1165
- const newObj = __spreadValues({}, obj);
1166
- Object.keys(obj).forEach((k) => {
1167
- const key = k;
1168
- if (newObj[key] === void 0) {
1169
- delete newObj[key];
1170
- }
1171
- });
1172
- return newObj;
1173
- }
1174
- function creationOpToLiveNode(op) {
1175
- return lsonToLiveNode(creationOpToLson(op));
1176
- }
1177
- function creationOpToLson(op) {
1178
- switch (op.type) {
1179
- case 8 /* CREATE_REGISTER */:
1180
- return op.data;
1181
- case 4 /* CREATE_OBJECT */:
1182
- return new LiveObject(op.data);
1183
- case 7 /* CREATE_MAP */:
1184
- return new LiveMap();
1185
- case 2 /* CREATE_LIST */:
1186
- return new LiveList();
1187
- default:
1188
- return assertNever(op, "Unknown creation Op");
1189
- }
1190
- }
1191
- function isSameNodeOrChildOf(node, parent) {
1192
- if (node === parent) {
1193
- return true;
1194
- }
1195
- if (node.parent.type === "HasParent") {
1196
- return isSameNodeOrChildOf(node.parent.node, parent);
1197
- }
1198
- return false;
1199
- }
1200
- function deserialize([id, crdt], parentToChildren, pool) {
1201
- switch (crdt.type) {
1202
- case 0 /* OBJECT */: {
1203
- return LiveObject._deserialize([id, crdt], parentToChildren, pool);
1204
- }
1205
- case 1 /* LIST */: {
1206
- return LiveList._deserialize([id, crdt], parentToChildren, pool);
1207
- }
1208
- case 2 /* MAP */: {
1209
- return LiveMap._deserialize([id, crdt], parentToChildren, pool);
1210
- }
1211
- case 3 /* REGISTER */: {
1212
- return LiveRegister._deserialize([id, crdt], parentToChildren, pool);
1213
- }
1214
- default: {
1215
- throw new Error("Unexpected CRDT type");
1216
- }
1217
- }
1218
- }
1219
- function deserializeToLson([id, crdt], parentToChildren, pool) {
1220
- switch (crdt.type) {
1221
- case 0 /* OBJECT */: {
1222
- return LiveObject._deserialize([id, crdt], parentToChildren, pool);
1223
- }
1224
- case 1 /* LIST */: {
1225
- return LiveList._deserialize([id, crdt], parentToChildren, pool);
1226
- }
1227
- case 2 /* MAP */: {
1228
- return LiveMap._deserialize([id, crdt], parentToChildren, pool);
1229
- }
1230
- case 3 /* REGISTER */: {
1231
- return crdt.data;
1232
- }
1233
- default: {
1234
- throw new Error("Unexpected CRDT type");
1235
- }
1236
- }
1237
- }
1238
- function isLiveStructure(value) {
1239
- return isLiveList(value) || isLiveMap(value) || isLiveObject(value);
1240
- }
1241
- function isLiveNode(value) {
1242
- return isLiveStructure(value) || isLiveRegister(value);
1243
- }
1244
- function isLiveList(value) {
1245
- return value instanceof LiveList;
1246
- }
1247
- function isLiveMap(value) {
1248
- return value instanceof LiveMap;
1249
- }
1250
- function isLiveObject(value) {
1251
- return value instanceof LiveObject;
1252
- }
1253
- function isLiveRegister(value) {
1254
- return value instanceof LiveRegister;
1255
- }
1256
- function liveNodeToLson(obj) {
1257
- if (obj instanceof LiveRegister) {
1258
- return obj.data;
1259
- } else if (obj instanceof LiveList || obj instanceof LiveMap || obj instanceof LiveObject) {
1260
- return obj;
1261
- } else {
1262
- return assertNever(obj, "Unknown AbstractCrdt");
1263
- }
1264
- }
1265
- function lsonToLiveNode(value) {
1266
- if (value instanceof LiveObject || value instanceof LiveMap || value instanceof LiveList) {
1267
- return value;
1268
- } else {
1269
- return new LiveRegister(value);
1270
- }
1271
- }
1272
- function getTreesDiffOperations(currentItems, newItems) {
1273
- const ops = [];
1274
- currentItems.forEach((_, id) => {
1275
- if (!newItems.get(id)) {
1276
- ops.push({
1277
- type: 5 /* DELETE_CRDT */,
1278
- id
1279
- });
1280
- }
1281
- });
1282
- newItems.forEach((crdt, id) => {
1283
- const currentCrdt = currentItems.get(id);
1284
- if (currentCrdt) {
1285
- if (crdt.type === 0 /* OBJECT */) {
1286
- if (currentCrdt.type !== 0 /* OBJECT */ || JSON.stringify(crdt.data) !== JSON.stringify(currentCrdt.data)) {
1287
- ops.push({
1288
- type: 3 /* UPDATE_OBJECT */,
1289
- id,
1290
- data: crdt.data
1291
- });
1292
- }
1293
- }
1294
- if (crdt.parentKey !== currentCrdt.parentKey) {
1295
- ops.push({
1296
- type: 1 /* SET_PARENT_KEY */,
1297
- id,
1298
- parentKey: nn(crdt.parentKey, "Parent key must not be missing")
1299
- });
1300
- }
1301
- } else {
1302
- switch (crdt.type) {
1303
- case 3 /* REGISTER */:
1304
- ops.push({
1305
- type: 8 /* CREATE_REGISTER */,
1306
- id,
1307
- parentId: crdt.parentId,
1308
- parentKey: crdt.parentKey,
1309
- data: crdt.data
1310
- });
1311
- break;
1312
- case 1 /* LIST */:
1313
- ops.push({
1314
- type: 2 /* CREATE_LIST */,
1315
- id,
1316
- parentId: crdt.parentId,
1317
- parentKey: crdt.parentKey
1318
- });
1319
- break;
1320
- case 0 /* OBJECT */:
1321
- ops.push(
1322
- crdt.parentId ? {
1323
- type: 4 /* CREATE_OBJECT */,
1324
- id,
1325
- parentId: crdt.parentId,
1326
- parentKey: crdt.parentKey,
1327
- data: crdt.data
1328
- } : { type: 4 /* CREATE_OBJECT */, id, data: crdt.data }
1329
- );
1330
- break;
1331
- case 2 /* MAP */:
1332
- ops.push({
1333
- type: 7 /* CREATE_MAP */,
1334
- id,
1335
- parentId: crdt.parentId,
1336
- parentKey: crdt.parentKey
1337
- });
1338
- break;
1339
- }
1340
- }
1341
- });
1342
- return ops;
1343
- }
1344
- function mergeObjectStorageUpdates(first, second) {
1345
- const updates = first.updates;
1346
- for (const [key, value] of entries(second.updates)) {
1347
- updates[key] = value;
1348
- }
1349
- return __spreadProps(__spreadValues({}, second), {
1350
- updates
1351
- });
1352
- }
1353
- function mergeMapStorageUpdates(first, second) {
1354
- const updates = first.updates;
1355
- for (const [key, value] of entries(second.updates)) {
1356
- updates[key] = value;
1357
- }
1358
- return __spreadProps(__spreadValues({}, second), {
1359
- updates
1360
- });
1361
- }
1362
- function mergeListStorageUpdates(first, second) {
1363
- const updates = first.updates;
1364
- return __spreadProps(__spreadValues({}, second), {
1365
- updates: updates.concat(second.updates)
1366
- });
1367
- }
1368
- function mergeStorageUpdates(first, second) {
1369
- if (!first) {
1370
- return second;
1371
- }
1372
- if (first.type === "LiveObject" && second.type === "LiveObject") {
1373
- return mergeObjectStorageUpdates(first, second);
1374
- } else if (first.type === "LiveMap" && second.type === "LiveMap") {
1375
- return mergeMapStorageUpdates(first, second);
1376
- } else if (first.type === "LiveList" && second.type === "LiveList") {
1377
- return mergeListStorageUpdates(first, second);
1378
- } else {
1379
- }
1380
- return second;
1381
- }
1382
- function isPlain(value) {
1383
- const type = typeof value;
1384
- return value === void 0 || value === null || type === "string" || type === "boolean" || type === "number" || Array.isArray(value) || isPlainObject(value);
1385
- }
1386
- function isPlainObject(blob) {
1387
- return blob !== null && typeof blob === "object" && Object.prototype.toString.call(blob) === "[object Object]";
1388
- }
1389
- function findNonSerializableValue(value, path = "") {
1390
- if (!isPlain) {
1391
- return {
1392
- path: path || "root",
1393
- value
1394
- };
1395
- }
1396
- if (typeof value !== "object" || value === null) {
1397
- return false;
1398
- }
1399
- for (const [key, nestedValue] of Object.entries(value)) {
1400
- const nestedPath = path ? path + "." + key : key;
1401
- if (!isPlain(nestedValue)) {
1402
- return {
1403
- path: nestedPath,
1404
- value: nestedValue
1405
- };
1406
- }
1407
- if (typeof nestedValue === "object") {
1408
- const nonSerializableNestedValue = findNonSerializableValue(
1409
- nestedValue,
1410
- nestedPath
1411
- );
1412
- if (nonSerializableNestedValue) {
1413
- return nonSerializableNestedValue;
1414
- }
1415
- }
1416
- }
1417
- return false;
1418
- }
1419
- function fromEntries(iterable) {
1420
- const obj = {};
1421
- for (const [key, val] of iterable) {
1422
- obj[key] = val;
1423
- }
1424
- return obj;
1425
- }
1426
- function entries(obj) {
1427
- return Object.entries(obj);
1428
- }
1429
- function tryParseJson(rawMessage) {
1430
- try {
1431
- return JSON.parse(rawMessage);
1432
- } catch (e) {
1433
- return void 0;
1434
- }
1435
- }
1436
- function b64decode(b64value) {
1437
- try {
1438
- const formattedValue = b64value.replace(/-/g, "+").replace(/_/g, "/");
1439
- const decodedValue = decodeURIComponent(
1440
- atob(formattedValue).split("").map(function(c) {
1441
- return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
1442
- }).join("")
1443
- );
1444
- return decodedValue;
1445
- } catch (err) {
1446
- return atob(b64value);
1447
- }
1448
- }
1449
-
1450
- // src/LiveList.ts
1451
- function compareNodePosition(itemA, itemB) {
1452
- return comparePosition(
1453
- itemA._getParentKeyOrThrow(),
1454
- itemB._getParentKeyOrThrow()
1455
- );
1456
- }
1457
- var LiveList = class extends AbstractCrdt {
1458
- constructor(items = []) {
1459
- super();
1460
- this._items = [];
1461
- this._implicitlyDeletedItems = /* @__PURE__ */ new WeakSet();
1462
- this._unacknowledgedSets = /* @__PURE__ */ new Map();
1463
- let position = void 0;
1464
- for (let i = 0; i < items.length; i++) {
1465
- const newPosition = makePosition(position);
1466
- const item = lsonToLiveNode(items[i]);
1467
- item._setParentLink(this, newPosition);
1468
- this._items.push(item);
1469
- position = newPosition;
1470
- }
1471
- }
1472
- static _deserialize([id], parentToChildren, pool) {
1473
- const list = new LiveList();
1474
- list._attach(id, pool);
1475
- const children = parentToChildren.get(id);
1476
- if (children === void 0) {
1477
- return list;
1478
- }
1479
- for (const [id2, crdt] of children) {
1480
- const child = deserialize([id2, crdt], parentToChildren, pool);
1481
- child._setParentLink(list, crdt.parentKey);
1482
- list._insertAndSort(child);
1483
- }
1484
- return list;
1485
- }
1486
- _toOps(parentId, parentKey, pool) {
1487
- if (this._id === void 0) {
1488
- throw new Error("Cannot serialize item is not attached");
1489
- }
1490
- const ops = [];
1491
- const op = {
1492
- id: this._id,
1493
- opId: pool == null ? void 0 : pool.generateOpId(),
1494
- type: 2 /* CREATE_LIST */,
1495
- parentId,
1496
- parentKey
1497
- };
1498
- ops.push(op);
1499
- for (const item of this._items) {
1500
- ops.push(...item._toOps(this._id, item._getParentKeyOrThrow(), pool));
1501
- }
1502
- return ops;
1503
- }
1504
- _insertAndSort(item) {
1505
- this._items.push(item);
1506
- this._sortItems();
1507
- }
1508
- _sortItems() {
1509
- this._items.sort(compareNodePosition);
1510
- this.invalidate();
1511
- }
1512
- _indexOfPosition(position) {
1513
- return this._items.findIndex(
1514
- (item) => item._getParentKeyOrThrow() === position
1515
- );
1516
- }
1517
- _attach(id, pool) {
1518
- super._attach(id, pool);
1519
- for (const item of this._items) {
1520
- item._attach(pool.generateId(), pool);
1521
- }
1522
- }
1523
- _detach() {
1524
- super._detach();
1525
- for (const item of this._items) {
1526
- item._detach();
1527
- }
1528
- }
1529
- _applySetRemote(op) {
1530
- if (this._pool === void 0) {
1531
- throw new Error("Can't attach child if managed pool is not present");
1532
- }
1533
- const { id, parentKey: key } = op;
1534
- const child = creationOpToLiveNode(op);
1535
- child._attach(id, this._pool);
1536
- child._setParentLink(this, key);
1537
- const deletedId = op.deletedId;
1538
- const indexOfItemWithSamePosition = this._indexOfPosition(key);
1539
- if (indexOfItemWithSamePosition !== -1) {
1540
- const itemWithSamePosition = this._items[indexOfItemWithSamePosition];
1541
- if (itemWithSamePosition._id === deletedId) {
1542
- itemWithSamePosition._detach();
1543
- this._items[indexOfItemWithSamePosition] = child;
1544
- return {
1545
- modified: makeUpdate(this, [
1546
- setDelta(indexOfItemWithSamePosition, child)
1547
- ]),
1548
- reverse: []
1549
- };
1550
- } else {
1551
- this._implicitlyDeletedItems.add(itemWithSamePosition);
1552
- this._items[indexOfItemWithSamePosition] = child;
1553
- const delta = [
1554
- setDelta(indexOfItemWithSamePosition, child)
1555
- ];
1556
- const deleteDelta2 = this._detachItemAssociatedToSetOperation(
1557
- op.deletedId
1558
- );
1559
- if (deleteDelta2) {
1560
- delta.push(deleteDelta2);
1561
- }
1562
- return {
1563
- modified: makeUpdate(this, delta),
1564
- reverse: []
1565
- };
1566
- }
1567
- } else {
1568
- const updates = [];
1569
- const deleteDelta2 = this._detachItemAssociatedToSetOperation(
1570
- op.deletedId
1571
- );
1572
- if (deleteDelta2) {
1573
- updates.push(deleteDelta2);
1574
- }
1575
- this._insertAndSort(child);
1576
- updates.push(insertDelta(this._indexOfPosition(key), child));
1577
- return {
1578
- reverse: [],
1579
- modified: makeUpdate(this, updates)
1580
- };
1581
- }
1582
- }
1583
- _applySetAck(op) {
1584
- if (this._pool === void 0) {
1585
- throw new Error("Can't attach child if managed pool is not present");
1586
- }
1587
- const delta = [];
1588
- const deletedDelta = this._detachItemAssociatedToSetOperation(op.deletedId);
1589
- if (deletedDelta) {
1590
- delta.push(deletedDelta);
1591
- }
1592
- const unacknowledgedOpId = this._unacknowledgedSets.get(op.parentKey);
1593
- if (unacknowledgedOpId !== void 0) {
1594
- if (unacknowledgedOpId !== op.opId) {
1595
- return delta.length === 0 ? { modified: false } : { modified: makeUpdate(this, delta), reverse: [] };
1596
- } else {
1597
- this._unacknowledgedSets.delete(op.parentKey);
1598
- }
1599
- }
1600
- const indexOfItemWithSamePosition = this._indexOfPosition(op.parentKey);
1601
- const existingItem = this._items.find((item) => item._id === op.id);
1602
- if (existingItem !== void 0) {
1603
- if (existingItem._parentKey === op.parentKey) {
1604
- return {
1605
- modified: delta.length > 0 ? makeUpdate(this, delta) : false,
1606
- reverse: []
1607
- };
1608
- }
1609
- if (indexOfItemWithSamePosition !== -1) {
1610
- this._implicitlyDeletedItems.add(
1611
- this._items[indexOfItemWithSamePosition]
1612
- );
1613
- this._items.splice(indexOfItemWithSamePosition, 1);
1614
- delta.push(deleteDelta(indexOfItemWithSamePosition));
1615
- }
1616
- const previousIndex = this._items.indexOf(existingItem);
1617
- existingItem._setParentLink(this, op.parentKey);
1618
- this._sortItems();
1619
- const newIndex = this._items.indexOf(existingItem);
1620
- if (newIndex !== previousIndex) {
1621
- delta.push(moveDelta(previousIndex, newIndex, existingItem));
1622
- }
1623
- return {
1624
- modified: delta.length > 0 ? makeUpdate(this, delta) : false,
1625
- reverse: []
1626
- };
1627
- } else {
1628
- const orphan = this._pool.getNode(op.id);
1629
- if (orphan && this._implicitlyDeletedItems.has(orphan)) {
1630
- orphan._setParentLink(this, op.parentKey);
1631
- this._implicitlyDeletedItems.delete(orphan);
1632
- this._insertAndSort(orphan);
1633
- const recreatedItemIndex = this._items.indexOf(orphan);
1634
- return {
1635
- modified: makeUpdate(this, [
1636
- indexOfItemWithSamePosition === -1 ? insertDelta(recreatedItemIndex, orphan) : setDelta(recreatedItemIndex, orphan),
1637
- ...delta
1638
- ]),
1639
- reverse: []
1640
- };
1641
- } else {
1642
- if (indexOfItemWithSamePosition !== -1) {
1643
- this._items.splice(indexOfItemWithSamePosition, 1);
1644
- }
1645
- const { newItem, newIndex } = this._createAttachItemAndSort(
1646
- op,
1647
- op.parentKey
1648
- );
1649
- return {
1650
- modified: makeUpdate(this, [
1651
- indexOfItemWithSamePosition === -1 ? insertDelta(newIndex, newItem) : setDelta(newIndex, newItem),
1652
- ...delta
1653
- ]),
1654
- reverse: []
1655
- };
1656
- }
1657
- }
1658
- }
1659
- _detachItemAssociatedToSetOperation(deletedId) {
1660
- if (deletedId === void 0 || this._pool === void 0) {
1661
- return null;
1662
- }
1663
- const deletedItem = this._pool.getNode(deletedId);
1664
- if (deletedItem === void 0) {
1665
- return null;
1666
- }
1667
- const result = this._detachChild(deletedItem);
1668
- if (result.modified === false) {
1669
- return null;
1670
- }
1671
- return result.modified.updates[0];
1672
- }
1673
- _applyRemoteInsert(op) {
1674
- if (this._pool === void 0) {
1675
- throw new Error("Can't attach child if managed pool is not present");
1676
- }
1677
- const key = op.parentKey;
1678
- const existingItemIndex = this._indexOfPosition(key);
1679
- if (existingItemIndex !== -1) {
1680
- this._shiftItemPosition(existingItemIndex, key);
1681
- }
1682
- const { newItem, newIndex } = this._createAttachItemAndSort(op, key);
1683
- return {
1684
- modified: makeUpdate(this, [insertDelta(newIndex, newItem)]),
1685
- reverse: []
1686
- };
1687
- }
1688
- _applyInsertAck(op) {
1689
- const existingItem = this._items.find((item) => item._id === op.id);
1690
- const key = op.parentKey;
1691
- const itemIndexAtPosition = this._indexOfPosition(key);
1692
- if (existingItem) {
1693
- if (existingItem._parentKey === key) {
1694
- return {
1695
- modified: false
1696
- };
1697
- } else {
1698
- const oldPositionIndex = this._items.indexOf(existingItem);
1699
- if (itemIndexAtPosition !== -1) {
1700
- this._shiftItemPosition(itemIndexAtPosition, key);
1701
- }
1702
- existingItem._setParentLink(this, key);
1703
- this._sortItems();
1704
- const newIndex = this._indexOfPosition(key);
1705
- if (newIndex === oldPositionIndex) {
1706
- return { modified: false };
1707
- }
1708
- return {
1709
- modified: makeUpdate(this, [
1710
- moveDelta(oldPositionIndex, newIndex, existingItem)
1711
- ]),
1712
- reverse: []
1713
- };
1714
- }
1715
- } else {
1716
- const orphan = nn(this._pool).getNode(op.id);
1717
- if (orphan && this._implicitlyDeletedItems.has(orphan)) {
1718
- orphan._setParentLink(this, key);
1719
- this._implicitlyDeletedItems.delete(orphan);
1720
- this._insertAndSort(orphan);
1721
- const newIndex = this._indexOfPosition(key);
1722
- return {
1723
- modified: makeUpdate(this, [insertDelta(newIndex, orphan)]),
1724
- reverse: []
1725
- };
1726
- } else {
1727
- if (itemIndexAtPosition !== -1) {
1728
- this._shiftItemPosition(itemIndexAtPosition, key);
1729
- }
1730
- const { newItem, newIndex } = this._createAttachItemAndSort(op, key);
1731
- return {
1732
- modified: makeUpdate(this, [insertDelta(newIndex, newItem)]),
1733
- reverse: []
1734
- };
1735
- }
1736
- }
1737
- }
1738
- _applyInsertUndoRedo(op) {
1739
- var _a;
1740
- const { id, parentKey: key } = op;
1741
- const child = creationOpToLiveNode(op);
1742
- if (((_a = this._pool) == null ? void 0 : _a.getNode(id)) !== void 0) {
1743
- return { modified: false };
1744
- }
1745
- child._attach(id, nn(this._pool));
1746
- child._setParentLink(this, key);
1747
- const existingItemIndex = this._indexOfPosition(key);
1748
- let newKey = key;
1749
- if (existingItemIndex !== -1) {
1750
- const before = this._items[existingItemIndex] ? this._items[existingItemIndex]._getParentKeyOrThrow() : void 0;
1751
- const after = this._items[existingItemIndex + 1] ? this._items[existingItemIndex + 1]._getParentKeyOrThrow() : void 0;
1752
- newKey = makePosition(before, after);
1753
- child._setParentLink(this, newKey);
1754
- }
1755
- this._insertAndSort(child);
1756
- const newIndex = this._indexOfPosition(newKey);
1757
- return {
1758
- modified: makeUpdate(this, [insertDelta(newIndex, child)]),
1759
- reverse: [{ type: 5 /* DELETE_CRDT */, id }]
1760
- };
1761
- }
1762
- _applySetUndoRedo(op) {
1763
- var _a;
1764
- const { id, parentKey: key } = op;
1765
- const child = creationOpToLiveNode(op);
1766
- if (((_a = this._pool) == null ? void 0 : _a.getNode(id)) !== void 0) {
1767
- return { modified: false };
1768
- }
1769
- this._unacknowledgedSets.set(key, nn(op.opId));
1770
- const indexOfItemWithSameKey = this._indexOfPosition(key);
1771
- child._attach(id, nn(this._pool));
1772
- child._setParentLink(this, key);
1773
- const newKey = key;
1774
- if (indexOfItemWithSameKey !== -1) {
1775
- const existingItem = this._items[indexOfItemWithSameKey];
1776
- existingItem._detach();
1777
- this._items[indexOfItemWithSameKey] = child;
1778
- const reverse = existingItem._toOps(nn(this._id), key, this._pool);
1779
- addIntentAndDeletedIdToOperation(reverse, op.id);
1780
- const delta = [setDelta(indexOfItemWithSameKey, child)];
1781
- const deletedDelta = this._detachItemAssociatedToSetOperation(
1782
- op.deletedId
1783
- );
1784
- if (deletedDelta) {
1785
- delta.push(deletedDelta);
1786
- }
1787
- return {
1788
- modified: makeUpdate(this, delta),
1789
- reverse
1790
- };
1791
- } else {
1792
- this._insertAndSort(child);
1793
- this._detachItemAssociatedToSetOperation(op.deletedId);
1794
- const newIndex = this._indexOfPosition(newKey);
1795
- return {
1796
- reverse: [{ type: 5 /* DELETE_CRDT */, id }],
1797
- modified: makeUpdate(this, [insertDelta(newIndex, child)])
1798
- };
1799
- }
1800
- }
1801
- _attachChild(op, source) {
1802
- if (this._pool === void 0) {
1803
- throw new Error("Can't attach child if managed pool is not present");
1804
- }
1805
- let result;
1806
- if (op.intent === "set") {
1807
- if (source === 1 /* REMOTE */) {
1808
- result = this._applySetRemote(op);
1809
- } else if (source === 2 /* ACK */) {
1810
- result = this._applySetAck(op);
1811
- } else {
1812
- result = this._applySetUndoRedo(op);
1813
- }
1814
- } else {
1815
- if (source === 1 /* REMOTE */) {
1816
- result = this._applyRemoteInsert(op);
1817
- } else if (source === 2 /* ACK */) {
1818
- result = this._applyInsertAck(op);
1819
- } else {
1820
- result = this._applyInsertUndoRedo(op);
1821
- }
1822
- }
1823
- if (result.modified !== false) {
1824
- this.invalidate();
1825
- }
1826
- return result;
1827
- }
1828
- _detachChild(child) {
1829
- if (child) {
1830
- const parentKey = nn(child._parentKey);
1831
- const reverse = child._toOps(nn(this._id), parentKey, this._pool);
1832
- const indexToDelete = this._items.indexOf(child);
1833
- if (indexToDelete === -1) {
1834
- return {
1835
- modified: false
1836
- };
1837
- }
1838
- this._items.splice(indexToDelete, 1);
1839
- this.invalidate();
1840
- child._detach();
1841
- return {
1842
- modified: makeUpdate(this, [deleteDelta(indexToDelete)]),
1843
- reverse
1844
- };
1845
- }
1846
- return { modified: false };
1847
- }
1848
- _applySetChildKeyRemote(newKey, child) {
1849
- var _a;
1850
- if (this._implicitlyDeletedItems.has(child)) {
1851
- this._implicitlyDeletedItems.delete(child);
1852
- child._setParentLink(this, newKey);
1853
- this._insertAndSort(child);
1854
- const newIndex = this._items.indexOf(child);
1855
- return {
1856
- modified: makeUpdate(this, [insertDelta(newIndex, child)]),
1857
- reverse: []
1858
- };
1859
- }
1860
- const previousKey = child._parentKey;
1861
- if (newKey === previousKey) {
1862
- return {
1863
- modified: false
1864
- };
1865
- }
1866
- const existingItemIndex = this._indexOfPosition(newKey);
1867
- if (existingItemIndex === -1) {
1868
- const previousIndex = this._items.indexOf(child);
1869
- child._setParentLink(this, newKey);
1870
- this._sortItems();
1871
- const newIndex = this._items.indexOf(child);
1872
- if (newIndex === previousIndex) {
1873
- return {
1874
- modified: false
1875
- };
1876
- }
1877
- return {
1878
- modified: makeUpdate(this, [moveDelta(previousIndex, newIndex, child)]),
1879
- reverse: []
1880
- };
1881
- } else {
1882
- this._items[existingItemIndex]._setParentLink(
1883
- this,
1884
- makePosition(
1885
- newKey,
1886
- (_a = this._items[existingItemIndex + 1]) == null ? void 0 : _a._getParentKeyOrThrow()
1887
- )
1888
- );
1889
- const previousIndex = this._items.indexOf(child);
1890
- child._setParentLink(this, newKey);
1891
- this._sortItems();
1892
- const newIndex = this._items.indexOf(child);
1893
- if (newIndex === previousIndex) {
1894
- return {
1895
- modified: false
1896
- };
1897
- }
1898
- return {
1899
- modified: makeUpdate(this, [moveDelta(previousIndex, newIndex, child)]),
1900
- reverse: []
1901
- };
1902
- }
1903
- }
1904
- _applySetChildKeyAck(newKey, child) {
1905
- var _a, _b;
1906
- const previousKey = nn(child._parentKey);
1907
- if (this._implicitlyDeletedItems.has(child)) {
1908
- const existingItemIndex = this._indexOfPosition(newKey);
1909
- this._implicitlyDeletedItems.delete(child);
1910
- if (existingItemIndex !== -1) {
1911
- this._items[existingItemIndex]._setParentLink(
1912
- this,
1913
- makePosition(
1914
- newKey,
1915
- (_a = this._items[existingItemIndex + 1]) == null ? void 0 : _a._getParentKeyOrThrow()
1916
- )
1917
- );
1918
- }
1919
- child._setParentLink(this, newKey);
1920
- this._insertAndSort(child);
1921
- return {
1922
- modified: false
1923
- };
1924
- } else {
1925
- if (newKey === previousKey) {
1926
- return {
1927
- modified: false
1928
- };
1929
- }
1930
- const previousIndex = this._items.indexOf(child);
1931
- const existingItemIndex = this._indexOfPosition(newKey);
1932
- if (existingItemIndex !== -1) {
1933
- this._items[existingItemIndex]._setParentLink(
1934
- this,
1935
- makePosition(
1936
- newKey,
1937
- (_b = this._items[existingItemIndex + 1]) == null ? void 0 : _b._getParentKeyOrThrow()
1938
- )
1939
- );
1940
- }
1941
- child._setParentLink(this, newKey);
1942
- this._sortItems();
1943
- const newIndex = this._items.indexOf(child);
1944
- if (previousIndex === newIndex) {
1945
- return {
1946
- modified: false
1947
- };
1948
- } else {
1949
- return {
1950
- modified: makeUpdate(this, [
1951
- moveDelta(previousIndex, newIndex, child)
1952
- ]),
1953
- reverse: []
1954
- };
1955
- }
1956
- }
1957
- }
1958
- _applySetChildKeyUndoRedo(newKey, child) {
1959
- var _a;
1960
- const previousKey = nn(child._parentKey);
1961
- const previousIndex = this._items.indexOf(child);
1962
- const existingItemIndex = this._indexOfPosition(newKey);
1963
- if (existingItemIndex !== -1) {
1964
- this._items[existingItemIndex]._setParentLink(
1965
- this,
1966
- makePosition(
1967
- newKey,
1968
- (_a = this._items[existingItemIndex + 1]) == null ? void 0 : _a._getParentKeyOrThrow()
1969
- )
1970
- );
1971
- }
1972
- child._setParentLink(this, newKey);
1973
- this._sortItems();
1974
- const newIndex = this._items.indexOf(child);
1975
- if (previousIndex === newIndex) {
1976
- return {
1977
- modified: false
1978
- };
1979
- }
1980
- return {
1981
- modified: makeUpdate(this, [moveDelta(previousIndex, newIndex, child)]),
1982
- reverse: [
1983
- {
1984
- type: 1 /* SET_PARENT_KEY */,
1985
- id: nn(child._id),
1986
- parentKey: previousKey
1987
- }
1988
- ]
1989
- };
1990
- }
1991
- _setChildKey(newKey, child, source) {
1992
- if (source === 1 /* REMOTE */) {
1993
- return this._applySetChildKeyRemote(newKey, child);
1994
- } else if (source === 2 /* ACK */) {
1995
- return this._applySetChildKeyAck(newKey, child);
1996
- } else {
1997
- return this._applySetChildKeyUndoRedo(newKey, child);
1998
- }
1999
- }
2000
- _apply(op, isLocal) {
2001
- return super._apply(op, isLocal);
2002
- }
2003
- _serialize() {
2004
- if (this.parent.type !== "HasParent") {
2005
- throw new Error("Cannot serialize LiveList if parent is missing");
2006
- }
2007
- return {
2008
- type: 1 /* LIST */,
2009
- parentId: nn(this.parent.node._id, "Parent node expected to have ID"),
2010
- parentKey: this.parent.key
2011
- };
2012
- }
2013
- get length() {
2014
- return this._items.length;
2015
- }
2016
- push(element) {
2017
- return this.insert(element, this.length);
2018
- }
2019
- insert(element, index) {
2020
- if (index < 0 || index > this._items.length) {
2021
- throw new Error(
2022
- `Cannot insert list item at index "${index}". index should be between 0 and ${this._items.length}`
2023
- );
2024
- }
2025
- const before = this._items[index - 1] ? this._items[index - 1]._getParentKeyOrThrow() : void 0;
2026
- const after = this._items[index] ? this._items[index]._getParentKeyOrThrow() : void 0;
2027
- const position = makePosition(before, after);
2028
- const value = lsonToLiveNode(element);
2029
- value._setParentLink(this, position);
2030
- this._insertAndSort(value);
2031
- if (this._pool && this._id) {
2032
- const id = this._pool.generateId();
2033
- value._attach(id, this._pool);
2034
- this._pool.dispatch(
2035
- value._toOps(this._id, position, this._pool),
2036
- [{ type: 5 /* DELETE_CRDT */, id }],
2037
- /* @__PURE__ */ new Map([
2038
- [this._id, makeUpdate(this, [insertDelta(index, value)])]
2039
- ])
2040
- );
2041
- }
2042
- }
2043
- move(index, targetIndex) {
2044
- if (targetIndex < 0) {
2045
- throw new Error("targetIndex cannot be less than 0");
2046
- }
2047
- if (targetIndex >= this._items.length) {
2048
- throw new Error(
2049
- "targetIndex cannot be greater or equal than the list length"
2050
- );
2051
- }
2052
- if (index < 0) {
2053
- throw new Error("index cannot be less than 0");
2054
- }
2055
- if (index >= this._items.length) {
2056
- throw new Error("index cannot be greater or equal than the list length");
2057
- }
2058
- let beforePosition = null;
2059
- let afterPosition = null;
2060
- if (index < targetIndex) {
2061
- afterPosition = targetIndex === this._items.length - 1 ? void 0 : this._items[targetIndex + 1]._getParentKeyOrThrow();
2062
- beforePosition = this._items[targetIndex]._getParentKeyOrThrow();
2063
- } else {
2064
- afterPosition = this._items[targetIndex]._getParentKeyOrThrow();
2065
- beforePosition = targetIndex === 0 ? void 0 : this._items[targetIndex - 1]._getParentKeyOrThrow();
2066
- }
2067
- const position = makePosition(beforePosition, afterPosition);
2068
- const item = this._items[index];
2069
- const previousPosition = item._getParentKeyOrThrow();
2070
- item._setParentLink(this, position);
2071
- this._sortItems();
2072
- if (this._pool && this._id) {
2073
- const storageUpdates = /* @__PURE__ */ new Map([
2074
- [this._id, makeUpdate(this, [moveDelta(index, targetIndex, item)])]
2075
- ]);
2076
- this._pool.dispatch(
2077
- [
2078
- {
2079
- type: 1 /* SET_PARENT_KEY */,
2080
- id: nn(item._id),
2081
- opId: this._pool.generateOpId(),
2082
- parentKey: position
2083
- }
2084
- ],
2085
- [
2086
- {
2087
- type: 1 /* SET_PARENT_KEY */,
2088
- id: nn(item._id),
2089
- parentKey: previousPosition
2090
- }
2091
- ],
2092
- storageUpdates
2093
- );
2094
- }
2095
- }
2096
- delete(index) {
2097
- if (index < 0 || index >= this._items.length) {
2098
- throw new Error(
2099
- `Cannot delete list item at index "${index}". index should be between 0 and ${this._items.length - 1}`
2100
- );
2101
- }
2102
- const item = this._items[index];
2103
- item._detach();
2104
- this._items.splice(index, 1);
2105
- this.invalidate();
2106
- if (this._pool) {
2107
- const childRecordId = item._id;
2108
- if (childRecordId) {
2109
- const storageUpdates = /* @__PURE__ */ new Map();
2110
- storageUpdates.set(
2111
- nn(this._id),
2112
- makeUpdate(this, [deleteDelta(index)])
2113
- );
2114
- this._pool.dispatch(
2115
- [
2116
- {
2117
- id: childRecordId,
2118
- opId: this._pool.generateOpId(),
2119
- type: 5 /* DELETE_CRDT */
2120
- }
2121
- ],
2122
- item._toOps(nn(this._id), item._getParentKeyOrThrow()),
2123
- storageUpdates
2124
- );
2125
- }
2126
- }
2127
- }
2128
- clear() {
2129
- if (this._pool) {
2130
- const ops = [];
2131
- const reverseOps = [];
2132
- const updateDelta = [];
2133
- for (const item of this._items) {
2134
- item._detach();
2135
- const childId = item._id;
2136
- if (childId) {
2137
- ops.push({
2138
- type: 5 /* DELETE_CRDT */,
2139
- id: childId,
2140
- opId: this._pool.generateOpId()
2141
- });
2142
- reverseOps.push(
2143
- ...item._toOps(nn(this._id), item._getParentKeyOrThrow())
2144
- );
2145
- updateDelta.push(deleteDelta(0));
2146
- }
2147
- }
2148
- this._items = [];
2149
- this.invalidate();
2150
- const storageUpdates = /* @__PURE__ */ new Map();
2151
- storageUpdates.set(nn(this._id), makeUpdate(this, updateDelta));
2152
- this._pool.dispatch(ops, reverseOps, storageUpdates);
2153
- } else {
2154
- for (const item of this._items) {
2155
- item._detach();
2156
- }
2157
- this._items = [];
2158
- this.invalidate();
2159
- }
2160
- }
2161
- set(index, item) {
2162
- if (index < 0 || index >= this._items.length) {
2163
- throw new Error(
2164
- `Cannot set list item at index "${index}". index should be between 0 and ${this._items.length - 1}`
2165
- );
2166
- }
2167
- const existingItem = this._items[index];
2168
- const position = existingItem._getParentKeyOrThrow();
2169
- const existingId = existingItem._id;
2170
- existingItem._detach();
2171
- const value = lsonToLiveNode(item);
2172
- value._setParentLink(this, position);
2173
- this._items[index] = value;
2174
- this.invalidate();
2175
- if (this._pool && this._id) {
2176
- const id = this._pool.generateId();
2177
- value._attach(id, this._pool);
2178
- const storageUpdates = /* @__PURE__ */ new Map();
2179
- storageUpdates.set(this._id, makeUpdate(this, [setDelta(index, value)]));
2180
- const ops = value._toOps(this._id, position, this._pool);
2181
- addIntentAndDeletedIdToOperation(ops, existingId);
2182
- this._unacknowledgedSets.set(position, nn(ops[0].opId));
2183
- const reverseOps = existingItem._toOps(this._id, position, void 0);
2184
- addIntentAndDeletedIdToOperation(reverseOps, id);
2185
- this._pool.dispatch(ops, reverseOps, storageUpdates);
2186
- }
2187
- }
2188
- toArray() {
2189
- return this._items.map(
2190
- (entry) => liveNodeToLson(entry)
2191
- );
2192
- }
2193
- every(predicate) {
2194
- return this.toArray().every(predicate);
2195
- }
2196
- filter(predicate) {
2197
- return this.toArray().filter(predicate);
2198
- }
2199
- find(predicate) {
2200
- return this.toArray().find(predicate);
2201
- }
2202
- findIndex(predicate) {
2203
- return this.toArray().findIndex(predicate);
2204
- }
2205
- forEach(callbackfn) {
2206
- return this.toArray().forEach(callbackfn);
2207
- }
2208
- get(index) {
2209
- if (index < 0 || index >= this._items.length) {
2210
- return void 0;
2211
- }
2212
- return liveNodeToLson(this._items[index]);
2213
- }
2214
- indexOf(searchElement, fromIndex) {
2215
- return this.toArray().indexOf(searchElement, fromIndex);
2216
- }
2217
- lastIndexOf(searchElement, fromIndex) {
2218
- return this.toArray().lastIndexOf(searchElement, fromIndex);
2219
- }
2220
- map(callback) {
2221
- return this._items.map(
2222
- (entry, i) => callback(
2223
- liveNodeToLson(entry),
2224
- i
2225
- )
2226
- );
2227
- }
2228
- some(predicate) {
2229
- return this.toArray().some(predicate);
2230
- }
2231
- [Symbol.iterator]() {
2232
- return new LiveListIterator(this._items);
2233
- }
2234
- _createAttachItemAndSort(op, key) {
2235
- const newItem = creationOpToLiveNode(op);
2236
- newItem._attach(op.id, nn(this._pool));
2237
- newItem._setParentLink(this, key);
2238
- this._insertAndSort(newItem);
2239
- const newIndex = this._indexOfPosition(key);
2240
- return { newItem, newIndex };
2241
- }
2242
- _shiftItemPosition(index, key) {
2243
- var _a;
2244
- const shiftedPosition = makePosition(
2245
- key,
2246
- this._items.length > index + 1 ? (_a = this._items[index + 1]) == null ? void 0 : _a._getParentKeyOrThrow() : void 0
2247
- );
2248
- this._items[index]._setParentLink(this, shiftedPosition);
2249
- }
2250
- toImmutable() {
2251
- return super.toImmutable();
2252
- }
2253
- _toImmutable() {
2254
- const result = this._items.map((node) => node.toImmutable());
2255
- return process.env.NODE_ENV === "production" ? result : Object.freeze(result);
2256
- }
2257
- };
2258
- var LiveListIterator = class {
2259
- constructor(items) {
2260
- this._innerIterator = items[Symbol.iterator]();
2261
- }
2262
- [Symbol.iterator]() {
2263
- return this;
2264
- }
2265
- next() {
2266
- const result = this._innerIterator.next();
2267
- if (result.done) {
2268
- return {
2269
- done: true,
2270
- value: void 0
2271
- };
2272
- }
2273
- const value = liveNodeToLson(result.value);
2274
- return { value };
2275
- }
2276
- };
2277
- function makeUpdate(liveList, deltaUpdates) {
2278
- return {
2279
- node: liveList,
2280
- type: "LiveList",
2281
- updates: deltaUpdates
2282
- };
2283
- }
2284
- function setDelta(index, item) {
2285
- return {
2286
- index,
2287
- type: "set",
2288
- item: item instanceof LiveRegister ? item.data : item
2289
- };
2290
- }
2291
- function deleteDelta(index) {
2292
- return {
2293
- index,
2294
- type: "delete"
2295
- };
2296
- }
2297
- function insertDelta(index, item) {
2298
- return {
2299
- index,
2300
- type: "insert",
2301
- item: item instanceof LiveRegister ? item.data : item
2302
- };
2303
- }
2304
- function moveDelta(previousIndex, index, item) {
2305
- return {
2306
- index,
2307
- type: "move",
2308
- previousIndex,
2309
- item: item instanceof LiveRegister ? item.data : item
2310
- };
2311
- }
2312
- function addIntentAndDeletedIdToOperation(ops, deletedId) {
2313
- if (ops.length === 0) {
2314
- throw new Error(
2315
- "Internal error. Serialized LiveStructure should have at least 1 operation"
2316
- );
2317
- }
2318
- const firstOp = ops[0];
2319
- firstOp.intent = "set";
2320
- firstOp.deletedId = deletedId;
2321
- }
2322
-
2323
- // src/AuthToken.ts
2324
- var SCOPES = [
2325
- "websocket:presence",
2326
- "websocket:storage",
2327
- "room:read",
2328
- "room:write",
2329
- "rooms:read",
2330
- "rooms:write"
2331
- ];
2332
- function hasJwtMeta(data) {
2333
- if (!isPlainObject(data)) {
2334
- return false;
2335
- }
2336
- const { iat, exp } = data;
2337
- return typeof iat === "number" && typeof exp === "number";
2338
- }
2339
- function isTokenExpired(token) {
2340
- const now = Date.now() / 1e3;
2341
- return now > token.exp - 300 || now < token.iat + 300;
2342
- }
2343
- function isScope(value) {
2344
- return SCOPES.includes(value);
2345
- }
2346
- function isStringList(value) {
2347
- return Array.isArray(value) && value.every((i) => typeof i === "string");
2348
- }
2349
- function isAppOnlyAuthToken(data) {
2350
- return typeof data.appId === "string" && data.roomId === void 0 && isStringList(data.scopes);
2351
- }
2352
- function isRoomAuthToken(data) {
2353
- return typeof data.appId === "string" && typeof data.roomId === "string" && typeof data.actor === "number" && (data.id === void 0 || typeof data.id === "string") && isStringList(data.scopes) && (data.maxConnectionsPerRoom === void 0 || typeof data.maxConnectionsPerRoom === "number");
2354
- }
2355
- function isAuthToken(data) {
2356
- return isAppOnlyAuthToken(data) || isRoomAuthToken(data);
2357
- }
2358
- function parseJwtToken(token) {
2359
- const tokenParts = token.split(".");
2360
- if (tokenParts.length !== 3) {
2361
- throw new Error("Authentication error: invalid JWT token");
2362
- }
2363
- const data = tryParseJson(b64decode(tokenParts[1]));
2364
- if (data && hasJwtMeta(data)) {
2365
- return data;
2366
- } else {
2367
- throw new Error("Authentication error: missing JWT metadata");
2368
- }
2369
- }
2370
- function parseRoomAuthToken(tokenString) {
2371
- const data = parseJwtToken(tokenString);
2372
- if (data && isRoomAuthToken(data)) {
2373
- const _a = data, {
2374
- maxConnections: _legacyField
2375
- } = _a, token = __objRest(_a, [
2376
- "maxConnections"
2377
- ]);
2378
- return token;
2379
- } else {
2380
- throw new Error(
2381
- "Authentication error: we expected a room token but did not get one. Hint: if you are using a callback, ensure the room is passed when creating the token. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClientCallback"
2382
- );
2383
- }
2384
- }
2385
-
2386
- // src/LegacyArray.ts
2387
- function asArrayWithLegacyMethods(arr) {
2388
- Object.defineProperty(arr, "count", {
2389
- value: arr.length,
2390
- enumerable: false
2391
- });
2392
- Object.defineProperty(arr, "toArray", {
2393
- value: () => arr,
2394
- enumerable: false
2395
- });
2396
- return freeze(arr);
2397
- }
2398
-
2399
- // src/types/Json.ts
2400
- function isJsonScalar(data) {
2401
- return data === null || typeof data === "string" || typeof data === "number" || typeof data === "boolean";
2402
- }
2403
- function isJsonArray(data) {
2404
- return Array.isArray(data);
2405
- }
2406
- function isJsonObject(data) {
2407
- return !isJsonScalar(data) && !isJsonArray(data);
2408
- }
2409
-
2410
-
2411
-
2412
-
2413
-
2414
-
2415
-
2416
-
2417
-
2418
-
2419
-
2420
-
2421
-
2422
-
2423
-
2424
-
2425
-
2426
-
2427
-
2428
-
2429
-
2430
-
2431
-
2432
-
2433
-
2434
-
2435
-
2436
-
2437
-
2438
-
2439
-
2440
-
2441
-
2442
-
2443
-
2444
-
2445
-
2446
-
2447
-
2448
-
2449
-
2450
-
2451
-
2452
-
2453
-
2454
-
2455
-
2456
-
2457
- exports.__spreadValues = __spreadValues; exports.__spreadProps = __spreadProps; exports.__async = __async; exports.deprecate = deprecate; exports.deprecateIf = deprecateIf; exports.throwUsageError = throwUsageError; exports.errorIf = errorIf; exports.assertNever = assertNever; exports.nn = nn; exports.ClientMsgCode = ClientMsgCode; exports.OpCode = OpCode; exports.CrdtType = CrdtType; exports.isRootCrdt = isRootCrdt; exports.isChildCrdt = isChildCrdt; exports.ServerMsgCode = ServerMsgCode; exports.isRoomEventName = isRoomEventName; exports.WebsocketCloseCodes = WebsocketCloseCodes; exports.LiveRegister = LiveRegister; exports.makePosition = makePosition; exports.comparePosition = comparePosition; exports.LiveList = LiveList; exports.LiveMap = LiveMap; exports.LiveObject = LiveObject; exports.freeze = freeze; exports.compact = compact; exports.compactObject = compactObject; exports.isSameNodeOrChildOf = isSameNodeOrChildOf; exports.isLiveNode = isLiveNode; exports.isLiveList = isLiveList; exports.isLiveObject = isLiveObject; exports.getTreesDiffOperations = getTreesDiffOperations; exports.mergeStorageUpdates = mergeStorageUpdates; exports.isPlainObject = isPlainObject; exports.findNonSerializableValue = findNonSerializableValue; exports.tryParseJson = tryParseJson; exports.b64decode = b64decode; exports.isTokenExpired = isTokenExpired; exports.isScope = isScope; exports.isAppOnlyAuthToken = isAppOnlyAuthToken; exports.isRoomAuthToken = isRoomAuthToken; exports.isAuthToken = isAuthToken; exports.parseRoomAuthToken = parseRoomAuthToken; exports.asArrayWithLegacyMethods = asArrayWithLegacyMethods; exports.isJsonScalar = isJsonScalar; exports.isJsonArray = isJsonArray; exports.isJsonObject = isJsonObject;