@liveblocks/client 0.18.0-beta1 → 0.18.0-beta2

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/index.js CHANGED
@@ -1,2252 +1,1584 @@
1
- "use strict";
2
- function _arrayLikeToArray(arr, len) {
3
- if (len == null || len > arr.length) len = arr.length;
4
- for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
5
- return arr2;
6
- }
7
- function _arrayWithHoles(arr) {
8
- if (Array.isArray(arr)) return arr;
9
- }
10
- function _arrayWithoutHoles(arr) {
11
- if (Array.isArray(arr)) return _arrayLikeToArray(arr);
12
- }
13
- function _assertThisInitialized(self) {
14
- if (self === void 0) {
15
- throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+
10
+
11
+
12
+
13
+
14
+
15
+
16
+
17
+
18
+
19
+
20
+
21
+
22
+
23
+
24
+
25
+
26
+
27
+
28
+ var _chunkRS4TQ2LTjs = require('./chunk-RS4TQ2LT.js');
29
+
30
+ // src/EventSource.ts
31
+ function makeEventSource() {
32
+ const _onetimeObservers = /* @__PURE__ */ new Set();
33
+ const _observers = /* @__PURE__ */ new Set();
34
+ function subscribe(callback) {
35
+ _observers.add(callback);
36
+ return () => _observers.delete(callback);
37
+ }
38
+ function subscribeOnce(callback) {
39
+ _onetimeObservers.add(callback);
40
+ return () => _onetimeObservers.delete(callback);
41
+ }
42
+ function notify(event) {
43
+ _onetimeObservers.forEach((callback) => callback(event));
44
+ _onetimeObservers.clear();
45
+ _observers.forEach((callback) => callback(event));
46
+ }
47
+ function clear() {
48
+ _onetimeObservers.clear();
49
+ _observers.clear();
50
+ }
51
+ return {
52
+ notify,
53
+ subscribe,
54
+ subscribeOnce,
55
+ clear,
56
+ observable: {
57
+ subscribe,
58
+ subscribeOnce
16
59
  }
17
- return self;
60
+ };
18
61
  }
19
- function _classCallCheck(instance, Constructor) {
20
- if (!(instance instanceof Constructor)) {
21
- throw new TypeError("Cannot call a class as a function");
62
+
63
+ // src/ImmutableRef.ts
64
+ function merge(target, patch) {
65
+ let updated = false;
66
+ const newValue = _chunkRS4TQ2LTjs.__spreadValues.call(void 0, {}, target);
67
+ Object.keys(patch).forEach((k) => {
68
+ const key = k;
69
+ const val = patch[key];
70
+ if (newValue[key] !== val) {
71
+ if (val === void 0) {
72
+ delete newValue[key];
73
+ } else {
74
+ newValue[key] = val;
75
+ }
76
+ updated = true;
22
77
  }
78
+ });
79
+ return updated ? newValue : target;
23
80
  }
24
- function isNativeReflectConstruct() {
25
- if (typeof Reflect === "undefined" || !Reflect.construct) return false;
26
- if (Reflect.construct.sham) return false;
27
- if (typeof Proxy === "function") return true;
28
- try {
29
- Date.prototype.toString.call(Reflect.construct(Date, [], function() {}));
30
- return true;
31
- } catch (e) {
32
- return false;
81
+ var ImmutableRef = class {
82
+ constructor() {
83
+ this._ev = makeEventSource();
84
+ }
85
+ get didInvalidate() {
86
+ return this._ev.observable;
87
+ }
88
+ invalidate() {
89
+ if (this._cache !== void 0) {
90
+ this._cache = void 0;
91
+ this._ev.notify();
33
92
  }
34
- }
35
- function _construct(Parent, args, Class) {
36
- if (isNativeReflectConstruct()) {
37
- _construct = Reflect.construct;
38
- } else {
39
- _construct = function _construct(Parent, args, Class) {
40
- var a = [
41
- null
42
- ];
43
- a.push.apply(a, args);
44
- var Constructor = Function.bind.apply(Parent, a);
45
- var instance = new Constructor();
46
- if (Class) _setPrototypeOf(instance, Class.prototype);
47
- return instance;
48
- };
93
+ }
94
+ get current() {
95
+ var _a;
96
+ return (_a = this._cache) != null ? _a : this._cache = this._toImmutable();
97
+ }
98
+ };
99
+
100
+ // src/MeRef.ts
101
+ var MeRef = class extends ImmutableRef {
102
+ constructor(initialPresence) {
103
+ super();
104
+ this._me = _chunkRS4TQ2LTjs.freeze.call(void 0, _chunkRS4TQ2LTjs.compactObject.call(void 0, initialPresence));
105
+ }
106
+ _toImmutable() {
107
+ return this._me;
108
+ }
109
+ patch(patch) {
110
+ const oldMe = this._me;
111
+ const newMe = merge(oldMe, patch);
112
+ if (oldMe !== newMe) {
113
+ this._me = _chunkRS4TQ2LTjs.freeze.call(void 0, newMe);
114
+ this.invalidate();
49
115
  }
50
- return _construct.apply(null, arguments);
116
+ }
117
+ };
118
+
119
+ // src/OthersRef.ts
120
+ function makeUser(conn, presence) {
121
+ return _chunkRS4TQ2LTjs.freeze.call(void 0, _chunkRS4TQ2LTjs.compactObject.call(void 0, _chunkRS4TQ2LTjs.__spreadProps.call(void 0, _chunkRS4TQ2LTjs.__spreadValues.call(void 0, {}, conn), { presence })));
51
122
  }
52
- function _defineProperties(target, props) {
53
- for(var i = 0; i < props.length; i++){
54
- var descriptor = props[i];
55
- descriptor.enumerable = descriptor.enumerable || false;
56
- descriptor.configurable = true;
57
- if ("value" in descriptor) descriptor.writable = true;
58
- Object.defineProperty(target, descriptor.key, descriptor);
123
+ var OthersRef = class extends ImmutableRef {
124
+ constructor() {
125
+ super();
126
+ this._connections = {};
127
+ this._presences = {};
128
+ this._users = {};
129
+ }
130
+ _toImmutable() {
131
+ const users = _chunkRS4TQ2LTjs.compact.call(void 0,
132
+ Object.keys(this._presences).map(
133
+ (connectionId) => this.getUser(Number(connectionId))
134
+ )
135
+ );
136
+ return _chunkRS4TQ2LTjs.asArrayWithLegacyMethods.call(void 0, users);
137
+ }
138
+ clearOthers() {
139
+ this._connections = {};
140
+ this._presences = {};
141
+ this._users = {};
142
+ this.invalidate();
143
+ }
144
+ _getUser(connectionId) {
145
+ const conn = this._connections[connectionId];
146
+ const presence = this._presences[connectionId];
147
+ if (conn !== void 0 && presence !== void 0) {
148
+ return makeUser(conn, presence);
59
149
  }
60
- }
61
- function _createClass(Constructor, protoProps, staticProps) {
62
- if (protoProps) _defineProperties(Constructor.prototype, protoProps);
63
- if (staticProps) _defineProperties(Constructor, staticProps);
64
- return Constructor;
65
- }
66
- function _defineProperty(obj, key, value) {
67
- if (key in obj) {
68
- Object.defineProperty(obj, key, {
69
- value: value,
70
- enumerable: true,
71
- configurable: true,
72
- writable: true
73
- });
74
- } else {
75
- obj[key] = value;
150
+ return void 0;
151
+ }
152
+ getUser(connectionId) {
153
+ const cachedUser = this._users[connectionId];
154
+ if (cachedUser) {
155
+ return cachedUser;
76
156
  }
77
- return obj;
78
- }
79
- function _getPrototypeOf(o) {
80
- _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
81
- return o.__proto__ || Object.getPrototypeOf(o);
82
- };
83
- return _getPrototypeOf(o);
84
- }
85
- function _inherits(subClass, superClass) {
86
- if (typeof superClass !== "function" && superClass !== null) {
87
- throw new TypeError("Super expression must either be null or a function");
88
- }
89
- subClass.prototype = Object.create(superClass && superClass.prototype, {
90
- constructor: {
91
- value: subClass,
92
- writable: true,
93
- configurable: true
94
- }
95
- });
96
- if (superClass) _setPrototypeOf(subClass, superClass);
97
- }
98
- function _instanceof(left, right) {
99
- if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
100
- return !!right[Symbol.hasInstance](left);
101
- } else {
102
- return left instanceof right;
157
+ const computedUser = this._getUser(connectionId);
158
+ if (computedUser) {
159
+ this._users[connectionId] = computedUser;
160
+ return computedUser;
103
161
  }
104
- }
105
- function _isNativeFunction(fn) {
106
- return Function.toString.call(fn).indexOf("[native code]") !== -1;
107
- }
108
- function _iterableToArray(iter) {
109
- if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
110
- }
111
- function _iterableToArrayLimit(arr, i) {
112
- var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
113
- if (_i == null) return;
114
- var _arr = [];
115
- var _n = true;
116
- var _d = false;
117
- var _s, _e;
118
- try {
119
- for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
120
- _arr.push(_s.value);
121
- if (i && _arr.length === i) break;
122
- }
123
- } catch (err) {
124
- _d = true;
125
- _e = err;
126
- } finally{
127
- try {
128
- if (!_n && _i["return"] != null) _i["return"]();
129
- } finally{
130
- if (_d) throw _e;
131
- }
162
+ return void 0;
163
+ }
164
+ _invalidateUser(connectionId) {
165
+ if (this._users[connectionId] !== void 0) {
166
+ delete this._users[connectionId];
132
167
  }
133
- return _arr;
134
- }
135
- function _nonIterableRest() {
136
- throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
137
- }
138
- function _nonIterableSpread() {
139
- throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
140
- }
141
- function _objectSpread(target) {
142
- for(var i = 1; i < arguments.length; i++){
143
- var source = arguments[i] != null ? arguments[i] : {};
144
- var ownKeys = Object.keys(source);
145
- if (typeof Object.getOwnPropertySymbols === "function") {
146
- ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
147
- return Object.getOwnPropertyDescriptor(source, sym).enumerable;
148
- }));
149
- }
150
- ownKeys.forEach(function(key) {
151
- _defineProperty(target, key, source[key]);
152
- });
168
+ this.invalidate();
169
+ }
170
+ setConnection(connectionId, metaUserId, metaUserInfo) {
171
+ this._connections[connectionId] = _chunkRS4TQ2LTjs.freeze.call(void 0, {
172
+ connectionId,
173
+ id: metaUserId,
174
+ info: metaUserInfo
175
+ });
176
+ if (this._presences[connectionId] !== void 0) {
177
+ this._invalidateUser(connectionId);
153
178
  }
154
- return target;
155
- }
156
- function ownKeys(object, enumerableOnly) {
157
- var keys = Object.keys(object);
158
- if (Object.getOwnPropertySymbols) {
159
- var symbols = Object.getOwnPropertySymbols(object);
160
- if (enumerableOnly) {
161
- symbols = symbols.filter(function(sym) {
162
- return Object.getOwnPropertyDescriptor(object, sym).enumerable;
163
- });
164
- }
165
- keys.push.apply(keys, symbols);
179
+ }
180
+ removeConnection(connectionId) {
181
+ delete this._connections[connectionId];
182
+ delete this._presences[connectionId];
183
+ this._invalidateUser(connectionId);
184
+ }
185
+ setOther(connectionId, presence) {
186
+ this._presences[connectionId] = _chunkRS4TQ2LTjs.freeze.call(void 0, _chunkRS4TQ2LTjs.compactObject.call(void 0, presence));
187
+ if (this._connections[connectionId] !== void 0) {
188
+ this._invalidateUser(connectionId);
166
189
  }
167
- return keys;
168
- }
169
- function _objectSpreadProps(target, source) {
170
- source = source != null ? source : {};
171
- if (Object.getOwnPropertyDescriptors) {
172
- Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
173
- } else {
174
- ownKeys(Object(source)).forEach(function(key) {
175
- Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
176
- });
190
+ }
191
+ patchOther(connectionId, patch) {
192
+ const oldPresence = this._presences[connectionId];
193
+ if (oldPresence === void 0) {
194
+ return;
177
195
  }
178
- return target;
179
- }
180
- function _possibleConstructorReturn(self, call) {
181
- if (call && (_typeof(call) === "object" || typeof call === "function")) {
182
- return call;
196
+ const newPresence = merge(oldPresence, patch);
197
+ if (oldPresence !== newPresence) {
198
+ this._presences[connectionId] = _chunkRS4TQ2LTjs.freeze.call(void 0, newPresence);
199
+ this._invalidateUser(connectionId);
183
200
  }
184
- return _assertThisInitialized(self);
185
- }
186
- function _setPrototypeOf(o, p) {
187
- _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
188
- o.__proto__ = p;
189
- return o;
190
- };
191
- return _setPrototypeOf(o, p);
192
- }
193
- function _slicedToArray(arr, i) {
194
- return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
195
- }
196
- function _toConsumableArray(arr) {
197
- return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
198
- }
199
- var _typeof = function(obj) {
200
- "@swc/helpers - typeof";
201
- return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
201
+ }
202
202
  };
203
- function _unsupportedIterableToArray(o, minLen) {
204
- if (!o) return;
205
- if (typeof o === "string") return _arrayLikeToArray(o, minLen);
206
- var n = Object.prototype.toString.call(o).slice(8, -1);
207
- if (n === "Object" && o.constructor) n = o.constructor.name;
208
- if (n === "Map" || n === "Set") return Array.from(n);
209
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
210
- }
211
- function _wrapNativeSuper(Class) {
212
- var _cache = typeof Map === "function" ? new Map() : undefined;
213
- _wrapNativeSuper = function _wrapNativeSuper(Class) {
214
- if (Class === null || !_isNativeFunction(Class)) return Class;
215
- if (typeof Class !== "function") {
216
- throw new TypeError("Super expression must either be null or a function");
217
- }
218
- if (typeof _cache !== "undefined") {
219
- if (_cache.has(Class)) return _cache.get(Class);
220
- _cache.set(Class, Wrapper);
221
- }
222
- function Wrapper() {
223
- return _construct(Class, arguments, _getPrototypeOf(this).constructor);
224
- }
225
- Wrapper.prototype = Object.create(Class.prototype, {
226
- constructor: {
227
- value: Wrapper,
228
- enumerable: false,
229
- writable: true,
230
- configurable: true
231
- }
232
- });
233
- return _setPrototypeOf(Wrapper, Class);
234
- };
235
- return _wrapNativeSuper(Class);
236
- }
237
- function _isNativeReflectConstruct() {
238
- if (typeof Reflect === "undefined" || !Reflect.construct) return false;
239
- if (Reflect.construct.sham) return false;
240
- if (typeof Proxy === "function") return true;
241
- try {
242
- Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
243
- return true;
244
- } catch (e) {
245
- return false;
246
- }
247
- }
248
- function _createSuper(Derived) {
249
- var hasNativeReflectConstruct = _isNativeReflectConstruct();
250
- return function _createSuperInternal() {
251
- var Super = _getPrototypeOf(Derived), result;
252
- if (hasNativeReflectConstruct) {
253
- var NewTarget = _getPrototypeOf(this).constructor;
254
- result = Reflect.construct(Super, arguments, NewTarget);
255
- } else {
256
- result = Super.apply(this, arguments);
257
- }
258
- return _possibleConstructorReturn(this, result);
259
- };
260
- }
261
- Object.defineProperty(exports, "__esModule", {
262
- value: true
263
- });
264
- function _nullishCoalesce(lhs, rhsFn) {
265
- if (lhs != null) {
266
- return lhs;
267
- } else {
268
- return rhsFn();
269
- }
270
- }
271
- function _optionalChain(ops) {
272
- var lastAccessLHS = undefined;
273
- var value = ops[0];
274
- var i = 1;
275
- while(i < ops.length){
276
- var op = ops[i];
277
- var fn = ops[i + 1];
278
- i += 2;
279
- if ((op === "optionalAccess" || op === "optionalCall") && value == null) {
280
- return undefined;
281
- }
282
- if (op === "access" || op === "optionalAccess") {
283
- lastAccessLHS = value;
284
- value = fn(value);
285
- } else if (op === "call" || op === "optionalCall") {
286
- var _value;
287
- value = fn(function() {
288
- for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
289
- args[_key] = arguments[_key];
290
- }
291
- return (_value = value).call.apply(_value, [
292
- lastAccessLHS
293
- ].concat(_toConsumableArray(args)));
294
- });
295
- lastAccessLHS = undefined;
296
- }
297
- }
298
- return value;
299
- }
300
- var _chunkZNCSOBAXjs = require("./chunk-ZNCSOBAX.js");
301
- // src/EventSource.ts
302
- function makeEventSource() {
303
- var subscribe = function subscribe(callback) {
304
- _observers.add(callback);
305
- return function() {
306
- return _observers.delete(callback);
307
- };
308
- };
309
- var subscribeOnce = function subscribeOnce(callback) {
310
- _onetimeObservers.add(callback);
311
- return function() {
312
- return _onetimeObservers.delete(callback);
313
- };
314
- };
315
- var notify = function notify(event) {
316
- _onetimeObservers.forEach(function(callback) {
317
- return callback(event);
318
- });
319
- _onetimeObservers.clear();
320
- _observers.forEach(function(callback) {
321
- return callback(event);
322
- });
323
- };
324
- var clear = function clear() {
325
- _onetimeObservers.clear();
326
- _observers.clear();
327
- };
328
- var _onetimeObservers = /* @__PURE__ */ new Set();
329
- var _observers = /* @__PURE__ */ new Set();
330
- return {
331
- notify: notify,
332
- subscribe: subscribe,
333
- subscribeOnce: subscribeOnce,
334
- clear: clear,
335
- observable: {
336
- subscribe: subscribe,
337
- subscribeOnce: subscribeOnce
338
- }
339
- };
340
- }
341
- // src/ImmutableRef.ts
342
- function merge(target, patch) {
343
- var updated = false;
344
- var newValue = _objectSpread({}, target);
345
- Object.keys(patch).forEach(function(k) {
346
- var key = k;
347
- var val = patch[key];
348
- if (newValue[key] !== val) {
349
- if (val === void 0) {
350
- delete newValue[key];
351
- } else {
352
- newValue[key] = val;
353
- }
354
- updated = true;
355
- }
356
- });
357
- return updated ? newValue : target;
358
- }
359
- var ImmutableRef = /*#__PURE__*/ function() {
360
- function ImmutableRef() {
361
- _classCallCheck(this, ImmutableRef);
362
- this._ev = makeEventSource();
363
- }
364
- _createClass(ImmutableRef, [
365
- {
366
- key: "didInvalidate",
367
- get: function get() {
368
- return this._ev.observable;
369
- }
370
- },
371
- {
372
- key: "invalidate",
373
- value: function invalidate() {
374
- if (this._cache !== void 0) {
375
- this._cache = void 0;
376
- this._ev.notify();
377
- }
378
- }
379
- },
380
- {
381
- key: "current",
382
- get: function get() {
383
- var _this = this;
384
- return _nullishCoalesce(this._cache, function() {
385
- return _this._cache = _this._toImmutable();
386
- });
387
- }
388
- }
389
- ]);
390
- return ImmutableRef;
391
- }();
392
- // src/MeRef.ts
393
- var MeRef = /*#__PURE__*/ function(ImmutableRef) {
394
- _inherits(MeRef, ImmutableRef);
395
- var _super = _createSuper(MeRef);
396
- function MeRef(initialPresence) {
397
- _classCallCheck(this, MeRef);
398
- var _this;
399
- _this = _super.call(this);
400
- _this._me = _chunkZNCSOBAXjs.freeze.call(void 0, _chunkZNCSOBAXjs.compactObject.call(void 0, initialPresence));
401
- return _this;
402
- }
403
- _createClass(MeRef, [
404
- {
405
- key: "_toImmutable",
406
- value: function _toImmutable() {
407
- return this._me;
408
- }
409
- },
410
- {
411
- key: "patch",
412
- value: function patch(patch1) {
413
- var oldMe = this._me;
414
- var newMe = merge(oldMe, patch1);
415
- if (oldMe !== newMe) {
416
- this._me = _chunkZNCSOBAXjs.freeze.call(void 0, newMe);
417
- this.invalidate();
418
- }
419
- }
420
- }
421
- ]);
422
- return MeRef;
423
- }(ImmutableRef);
424
- // src/OthersRef.ts
425
- function makeUser(conn, presence) {
426
- return _chunkZNCSOBAXjs.freeze.call(void 0, _chunkZNCSOBAXjs.compactObject.call(void 0, _objectSpreadProps(_objectSpread({}, conn), {
427
- presence: presence
428
- })));
429
- }
430
- var OthersRef = /*#__PURE__*/ function(ImmutableRef) {
431
- _inherits(OthersRef, ImmutableRef);
432
- var _super = _createSuper(OthersRef);
433
- function OthersRef() {
434
- _classCallCheck(this, OthersRef);
435
- var _this;
436
- _this = _super.call(this);
437
- _this._connections = {};
438
- _this._presences = {};
439
- _this._users = {};
440
- return _this;
441
- }
442
- _createClass(OthersRef, [
443
- {
444
- key: "_toImmutable",
445
- value: function _toImmutable() {
446
- var _this = this;
447
- var users = _chunkZNCSOBAXjs.compact.call(void 0, Object.keys(this._presences).map(function(connectionId) {
448
- return _this.getUser(Number(connectionId));
449
- }));
450
- return _chunkZNCSOBAXjs.asArrayWithLegacyMethods.call(void 0, users);
451
- }
452
- },
453
- {
454
- key: "clearOthers",
455
- value: function clearOthers() {
456
- this._connections = {};
457
- this._presences = {};
458
- this._users = {};
459
- this.invalidate();
460
- }
461
- },
462
- {
463
- key: "_getUser",
464
- value: function _getUser(connectionId) {
465
- var conn = this._connections[connectionId];
466
- var presence = this._presences[connectionId];
467
- if (conn !== void 0 && presence !== void 0) {
468
- return makeUser(conn, presence);
469
- }
470
- return void 0;
471
- }
472
- },
473
- {
474
- key: "getUser",
475
- value: function getUser(connectionId) {
476
- var cachedUser = this._users[connectionId];
477
- if (cachedUser) {
478
- return cachedUser;
479
- }
480
- var computedUser = this._getUser(connectionId);
481
- if (computedUser) {
482
- this._users[connectionId] = computedUser;
483
- return computedUser;
484
- }
485
- return void 0;
486
- }
487
- },
488
- {
489
- key: "_invalidateUser",
490
- value: function _invalidateUser(connectionId) {
491
- if (this._users[connectionId] !== void 0) {
492
- delete this._users[connectionId];
493
- }
494
- this.invalidate();
495
- }
496
- },
497
- {
498
- key: "setConnection",
499
- value: function setConnection(connectionId, metaUserId, metaUserInfo) {
500
- this._connections[connectionId] = _chunkZNCSOBAXjs.freeze.call(void 0, {
501
- connectionId: connectionId,
502
- id: metaUserId,
503
- info: metaUserInfo
504
- });
505
- if (this._presences[connectionId] !== void 0) {
506
- this._invalidateUser(connectionId);
507
- }
508
- }
509
- },
510
- {
511
- key: "removeConnection",
512
- value: function removeConnection(connectionId) {
513
- delete this._connections[connectionId];
514
- delete this._presences[connectionId];
515
- this._invalidateUser(connectionId);
516
- }
517
- },
518
- {
519
- key: "setOther",
520
- value: function setOther(connectionId, presence) {
521
- this._presences[connectionId] = _chunkZNCSOBAXjs.freeze.call(void 0, _chunkZNCSOBAXjs.compactObject.call(void 0, presence));
522
- if (this._connections[connectionId] !== void 0) {
523
- this._invalidateUser(connectionId);
524
- }
525
- }
526
- },
527
- {
528
- key: "patchOther",
529
- value: function patchOther(connectionId, patch) {
530
- var oldPresence = this._presences[connectionId];
531
- if (oldPresence === void 0) {
532
- return;
533
- }
534
- var newPresence = merge(oldPresence, patch);
535
- if (oldPresence !== newPresence) {
536
- this._presences[connectionId] = _chunkZNCSOBAXjs.freeze.call(void 0, newPresence);
537
- this._invalidateUser(connectionId);
538
- }
539
- }
540
- }
541
- ]);
542
- return OthersRef;
543
- }(ImmutableRef);
203
+
544
204
  // src/ValueRef.ts
545
- var ValueRef = /*#__PURE__*/ function(ImmutableRef) {
546
- _inherits(ValueRef, ImmutableRef);
547
- var _super = _createSuper(ValueRef);
548
- function ValueRef(initialValue) {
549
- _classCallCheck(this, ValueRef);
550
- var _this;
551
- _this = _super.call(this);
552
- _this._value = _chunkZNCSOBAXjs.freeze.call(void 0, _chunkZNCSOBAXjs.compactObject.call(void 0, initialValue));
553
- return _this;
554
- }
555
- _createClass(ValueRef, [
556
- {
557
- key: "_toImmutable",
558
- value: function _toImmutable() {
559
- return this._value;
560
- }
561
- },
562
- {
563
- key: "set",
564
- value: function set(newValue) {
565
- this._value = _chunkZNCSOBAXjs.freeze.call(void 0, newValue);
566
- this.invalidate();
567
- }
568
- }
569
- ]);
570
- return ValueRef;
571
- }(ImmutableRef);
572
- var DerivedRef = /*#__PURE__*/ function(ImmutableRef) {
573
- _inherits(DerivedRef, ImmutableRef);
574
- var _super = _createSuper(DerivedRef);
575
- function DerivedRef(otherRefs, transformFn) {
576
- _classCallCheck(this, DerivedRef);
577
- var _this;
578
- _this = _super.call(this);
579
- _this._refs = otherRefs;
580
- _this._refs.forEach(function(ref) {
581
- ref.didInvalidate.subscribe(function() {
582
- return _this.invalidate();
583
- });
584
- });
585
- _this._transform = transformFn;
586
- return _this;
587
- }
588
- _createClass(DerivedRef, [
589
- {
590
- key: "_toImmutable",
591
- value: function _toImmutable() {
592
- return this._transform(this._refs[0].current, this._refs[1].current);
593
- }
594
- }
595
- ]);
596
- return DerivedRef;
597
- }(ImmutableRef);
205
+ var ValueRef = class extends ImmutableRef {
206
+ constructor(initialValue) {
207
+ super();
208
+ this._value = _chunkRS4TQ2LTjs.freeze.call(void 0, _chunkRS4TQ2LTjs.compactObject.call(void 0, initialValue));
209
+ }
210
+ _toImmutable() {
211
+ return this._value;
212
+ }
213
+ set(newValue) {
214
+ this._value = _chunkRS4TQ2LTjs.freeze.call(void 0, newValue);
215
+ this.invalidate();
216
+ }
217
+ };
218
+ var DerivedRef = class extends ImmutableRef {
219
+ constructor(otherRefs, transformFn) {
220
+ super();
221
+ this._refs = otherRefs;
222
+ this._refs.forEach((ref) => {
223
+ ref.didInvalidate.subscribe(() => this.invalidate());
224
+ });
225
+ this._transform = transformFn;
226
+ }
227
+ _toImmutable() {
228
+ return this._transform(this._refs[0].current, this._refs[1].current);
229
+ }
230
+ };
231
+
598
232
  // src/room.ts
599
- var BACKOFF_RETRY_DELAYS = [
600
- 250,
601
- 500,
602
- 1e3,
603
- 2e3,
604
- 4e3,
605
- 8e3,
606
- 1e4
607
- ];
608
- var BACKOFF_RETRY_DELAYS_SLOW = [
609
- 2e3,
610
- 3e4,
611
- 6e4,
612
- 3e5
613
- ];
233
+ var BACKOFF_RETRY_DELAYS = [250, 500, 1e3, 2e3, 4e3, 8e3, 1e4];
234
+ var BACKOFF_RETRY_DELAYS_SLOW = [2e3, 3e4, 6e4, 3e5];
614
235
  var HEARTBEAT_INTERVAL = 3e4;
615
236
  var PONG_TIMEOUT = 2e3;
616
237
  function makeIdFactory(connectionId) {
617
- var count = 0;
618
- return function() {
619
- return "".concat(connectionId, ":").concat(count++);
620
- };
238
+ let count = 0;
239
+ return () => `${connectionId}:${count++}`;
621
240
  }
622
- function log() {
623
- for(var _len = arguments.length, _params = new Array(_len), _key = 0; _key < _len; _key++){
624
- _params[_key] = arguments[_key];
625
- }
626
- return;
241
+ function log(..._params) {
242
+ return;
627
243
  }
628
244
  function isConnectionSelfAware(connection) {
629
- return connection.state === "open" || connection.state === "connecting";
245
+ return connection.state === "open" || connection.state === "connecting";
630
246
  }
631
247
  function makeStateMachine(state, config, mockedEffects) {
632
- var createOrUpdateRootFromMessage = function createOrUpdateRootFromMessage(message) {
633
- if (message.items.length === 0) {
634
- throw new Error("Internal error: cannot load storage without items");
635
- }
636
- if (state.root) {
637
- updateRoot(message.items);
638
- } else {
639
- state.root = load(message.items);
640
- }
641
- for(var key in state.defaultStorageRoot){
642
- if (state.root.get(key) == null) {
643
- state.root.set(key, state.defaultStorageRoot[key]);
644
- }
645
- }
646
- };
647
- var buildRootAndParentToChildren = function buildRootAndParentToChildren(items) {
648
- var parentToChildren = /* @__PURE__ */ new Map();
649
- var root = null;
650
- var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
651
- try {
652
- for(var _iterator = items[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
653
- var _value = _slicedToArray(_step.value, 2), id = _value[0], crdt = _value[1];
654
- if (_chunkZNCSOBAXjs.isRootCrdt.call(void 0, crdt)) {
655
- root = [
656
- id,
657
- crdt
658
- ];
659
- } else {
660
- var tuple = [
661
- id,
662
- crdt
663
- ];
664
- var children = parentToChildren.get(crdt.parentId);
665
- if (children != null) {
666
- children.push(tuple);
667
- } else {
668
- parentToChildren.set(crdt.parentId, [
669
- tuple
670
- ]);
671
- }
672
- }
673
- }
674
- } catch (err) {
675
- _didIteratorError = true;
676
- _iteratorError = err;
677
- } finally{
678
- try {
679
- if (!_iteratorNormalCompletion && _iterator.return != null) {
680
- _iterator.return();
681
- }
682
- } finally{
683
- if (_didIteratorError) {
684
- throw _iteratorError;
685
- }
686
- }
687
- }
688
- if (root == null) {
689
- throw new Error("Root can't be null");
690
- }
691
- return [
692
- root,
693
- parentToChildren
694
- ];
695
- };
696
- var updateRoot = function updateRoot(items) {
697
- if (!state.root) {
698
- return;
699
- }
700
- var currentItems = /* @__PURE__ */ new Map();
701
- state.nodes.forEach(function(node, id) {
702
- currentItems.set(id, node._serialize());
248
+ const pool = {
249
+ roomId: config.roomId,
250
+ getNode: (id) => state.nodes.get(id),
251
+ addNode: (id, node) => void state.nodes.set(id, node),
252
+ deleteNode: (id) => void state.nodes.delete(id),
253
+ generateId: () => `${getConnectionId()}:${state.clock++}`,
254
+ generateOpId: () => `${getConnectionId()}:${state.opClock++}`,
255
+ dispatch(ops, reverse, storageUpdates) {
256
+ const activeBatch = state.activeBatch;
257
+ if (activeBatch) {
258
+ activeBatch.ops.push(...ops);
259
+ storageUpdates.forEach((value, key) => {
260
+ activeBatch.updates.storageUpdates.set(
261
+ key,
262
+ _chunkRS4TQ2LTjs.mergeStorageUpdates.call(void 0,
263
+ activeBatch.updates.storageUpdates.get(key),
264
+ value
265
+ )
266
+ );
703
267
  });
704
- var ops = _chunkZNCSOBAXjs.getTreesDiffOperations.call(void 0, currentItems, new Map(items));
705
- var result = apply(ops, false);
706
- notify(result.updates);
707
- };
708
- var load = function load(items) {
709
- var ref = _slicedToArray(buildRootAndParentToChildren(items), 2), root = ref[0], parentToChildren = ref[1];
710
- return _chunkZNCSOBAXjs.LiveObject._deserialize(root, parentToChildren, pool);
711
- };
712
- var addToUndoStack = function addToUndoStack(historyItem) {
713
- if (state.undoStack.length >= 50) {
714
- state.undoStack.shift();
715
- }
716
- if (state.isHistoryPaused) {
717
- var _pausedHistory;
718
- (_pausedHistory = state.pausedHistory).unshift.apply(_pausedHistory, _toConsumableArray(historyItem));
268
+ activeBatch.reverseOps.push(...reverse);
269
+ } else {
270
+ addToUndoStack(reverse);
271
+ state.redoStack = [];
272
+ dispatchOps(ops);
273
+ notify({ storageUpdates });
274
+ }
275
+ }
276
+ };
277
+ const eventHub = {
278
+ customEvent: makeEventSource(),
279
+ me: makeEventSource(),
280
+ others: makeEventSource(),
281
+ error: makeEventSource(),
282
+ connection: makeEventSource(),
283
+ storage: makeEventSource(),
284
+ history: makeEventSource(),
285
+ storageDidLoad: makeEventSource()
286
+ };
287
+ const effects = mockedEffects || {
288
+ authenticate(auth, createWebSocket) {
289
+ const rawToken = state.token;
290
+ const parsedToken = rawToken !== null && _chunkRS4TQ2LTjs.parseRoomAuthToken.call(void 0, rawToken);
291
+ if (parsedToken && !_chunkRS4TQ2LTjs.isTokenExpired.call(void 0, parsedToken)) {
292
+ const socket = createWebSocket(rawToken);
293
+ authenticationSuccess(parsedToken, socket);
294
+ } else {
295
+ return auth(config.roomId).then(({ token }) => {
296
+ if (state.connection.current.state !== "authenticating") {
297
+ return;
298
+ }
299
+ const parsedToken2 = _chunkRS4TQ2LTjs.parseRoomAuthToken.call(void 0, token);
300
+ const socket = createWebSocket(token);
301
+ authenticationSuccess(parsedToken2, socket);
302
+ state.token = token;
303
+ }).catch(
304
+ (er) => authenticationFailure(
305
+ er instanceof Error ? er : new Error(String(er))
306
+ )
307
+ );
308
+ }
309
+ },
310
+ send(messageOrMessages) {
311
+ if (state.socket == null) {
312
+ throw new Error("Can't send message if socket is null");
313
+ }
314
+ state.socket.send(JSON.stringify(messageOrMessages));
315
+ },
316
+ delayFlush(delay) {
317
+ return setTimeout(tryFlushing, delay);
318
+ },
319
+ startHeartbeatInterval() {
320
+ return setInterval(heartbeat, HEARTBEAT_INTERVAL);
321
+ },
322
+ schedulePongTimeout() {
323
+ return setTimeout(pongTimeout, PONG_TIMEOUT);
324
+ },
325
+ scheduleReconnect(delay) {
326
+ return setTimeout(connect, delay);
327
+ }
328
+ };
329
+ const self = new DerivedRef(
330
+ [state.connection, state.me],
331
+ (conn, me) => isConnectionSelfAware(conn) ? {
332
+ connectionId: conn.id,
333
+ id: conn.userId,
334
+ info: conn.userInfo,
335
+ presence: me
336
+ } : null
337
+ );
338
+ function createOrUpdateRootFromMessage(message) {
339
+ if (message.items.length === 0) {
340
+ throw new Error("Internal error: cannot load storage without items");
341
+ }
342
+ if (state.root) {
343
+ updateRoot(message.items);
344
+ } else {
345
+ state.root = load(message.items);
346
+ }
347
+ for (const key in state.defaultStorageRoot) {
348
+ if (state.root.get(key) == null) {
349
+ state.root.set(key, state.defaultStorageRoot[key]);
350
+ }
351
+ }
352
+ }
353
+ function buildRootAndParentToChildren(items) {
354
+ const parentToChildren = /* @__PURE__ */ new Map();
355
+ let root = null;
356
+ for (const [id, crdt] of items) {
357
+ if (_chunkRS4TQ2LTjs.isRootCrdt.call(void 0, crdt)) {
358
+ root = [id, crdt];
359
+ } else {
360
+ const tuple = [id, crdt];
361
+ const children = parentToChildren.get(crdt.parentId);
362
+ if (children != null) {
363
+ children.push(tuple);
719
364
  } else {
720
- state.undoStack.push(historyItem);
721
- onHistoryChange();
722
- }
723
- };
724
- var notify = function notify(param) {
725
- var _storageUpdates = param.storageUpdates, storageUpdates = _storageUpdates === void 0 ? /* @__PURE__ */ new Map() : _storageUpdates, _presence = param.presence, presence = _presence === void 0 ? false : _presence, tmp = param.others, otherEvents = tmp === void 0 ? [] : tmp;
726
- if (otherEvents.length > 0) {
727
- var others = state.others.current;
728
- var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
729
- try {
730
- for(var _iterator = otherEvents[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
731
- var event = _step.value;
732
- eventHub.others.notify({
733
- others: others,
734
- event: event
735
- });
736
- }
737
- } catch (err) {
738
- _didIteratorError = true;
739
- _iteratorError = err;
740
- } finally{
741
- try {
742
- if (!_iteratorNormalCompletion && _iterator.return != null) {
743
- _iterator.return();
744
- }
745
- } finally{
746
- if (_didIteratorError) {
747
- throw _iteratorError;
748
- }
749
- }
750
- }
751
- }
752
- if (presence) {
753
- eventHub.me.notify(state.me.current);
365
+ parentToChildren.set(crdt.parentId, [tuple]);
754
366
  }
755
- if (storageUpdates.size > 0) {
756
- var updates = Array.from(storageUpdates.values());
757
- eventHub.storage.notify(updates);
758
- }
759
- };
760
- var getConnectionId = function getConnectionId() {
761
- var conn = state.connection.current;
762
- if (isConnectionSelfAware(conn)) {
763
- return conn.id;
764
- } else if (state.lastConnectionId !== null) {
765
- return state.lastConnectionId;
766
- }
767
- throw new Error("Internal. Tried to get connection id but connection was never open");
768
- };
769
- var apply = function apply(item, isLocal) {
770
- var result = {
771
- reverse: [],
772
- updates: {
773
- storageUpdates: /* @__PURE__ */ new Map(),
774
- presence: false
775
- }
367
+ }
368
+ }
369
+ if (root == null) {
370
+ throw new Error("Root can't be null");
371
+ }
372
+ return [root, parentToChildren];
373
+ }
374
+ function updateRoot(items) {
375
+ if (!state.root) {
376
+ return;
377
+ }
378
+ const currentItems = /* @__PURE__ */ new Map();
379
+ state.nodes.forEach((node, id) => {
380
+ currentItems.set(id, node._serialize());
381
+ });
382
+ const ops = _chunkRS4TQ2LTjs.getTreesDiffOperations.call(void 0, currentItems, new Map(items));
383
+ const result = apply(ops, false);
384
+ notify(result.updates);
385
+ }
386
+ function load(items) {
387
+ const [root, parentToChildren] = buildRootAndParentToChildren(items);
388
+ return _chunkRS4TQ2LTjs.LiveObject._deserialize(root, parentToChildren, pool);
389
+ }
390
+ function addToUndoStack(historyItem) {
391
+ if (state.undoStack.length >= 50) {
392
+ state.undoStack.shift();
393
+ }
394
+ if (state.isHistoryPaused) {
395
+ state.pausedHistory.unshift(...historyItem);
396
+ } else {
397
+ state.undoStack.push(historyItem);
398
+ onHistoryChange();
399
+ }
400
+ }
401
+ function notify({
402
+ storageUpdates = /* @__PURE__ */ new Map(),
403
+ presence = false,
404
+ others: otherEvents = []
405
+ }) {
406
+ if (otherEvents.length > 0) {
407
+ const others = state.others.current;
408
+ for (const event of otherEvents) {
409
+ eventHub.others.notify({ others, event });
410
+ }
411
+ }
412
+ if (presence) {
413
+ eventHub.me.notify(state.me.current);
414
+ }
415
+ if (storageUpdates.size > 0) {
416
+ const updates = Array.from(storageUpdates.values());
417
+ eventHub.storage.notify(updates);
418
+ }
419
+ }
420
+ function getConnectionId() {
421
+ const conn = state.connection.current;
422
+ if (isConnectionSelfAware(conn)) {
423
+ return conn.id;
424
+ } else if (state.lastConnectionId !== null) {
425
+ return state.lastConnectionId;
426
+ }
427
+ throw new Error(
428
+ "Internal. Tried to get connection id but connection was never open"
429
+ );
430
+ }
431
+ function apply(item, isLocal) {
432
+ const result = {
433
+ reverse: [],
434
+ updates: {
435
+ storageUpdates: /* @__PURE__ */ new Map(),
436
+ presence: false
437
+ }
438
+ };
439
+ const createdNodeIds = /* @__PURE__ */ new Set();
440
+ for (const op of item) {
441
+ if (op.type === "presence") {
442
+ const reverse = {
443
+ type: "presence",
444
+ data: {}
776
445
  };
777
- var createdNodeIds = /* @__PURE__ */ new Set();
778
- var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
779
- try {
780
- for(var _iterator = item[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
781
- var op = _step.value;
782
- if (op.type === "presence") {
783
- var reverse = {
784
- type: "presence",
785
- data: {}
786
- };
787
- for(var key in op.data){
788
- reverse.data[key] = state.me.current[key];
789
- }
790
- state.me.patch(op.data);
791
- if (state.buffer.me == null) {
792
- state.buffer.me = {
793
- type: "partial",
794
- data: op.data
795
- };
796
- } else {
797
- for(var key1 in op.data){
798
- state.buffer.me.data[key1] = op.data[key1];
799
- }
800
- }
801
- result.reverse.unshift(reverse);
802
- result.updates.presence = true;
803
- } else {
804
- var source = void 0;
805
- if (!op.opId) {
806
- op.opId = pool.generateOpId();
807
- }
808
- if (isLocal) {
809
- source = 0 /* UNDOREDO_RECONNECT */ ;
810
- } else {
811
- var deleted = state.offlineOperations.delete(_chunkZNCSOBAXjs.nn.call(void 0, op.opId));
812
- source = deleted ? 2 /* ACK */ : 1 /* REMOTE */ ;
813
- }
814
- var applyOpResult = applyOp(op, source);
815
- if (applyOpResult.modified) {
816
- var parentId = applyOpResult.modified.node.parent.type === "HasParent" ? _chunkZNCSOBAXjs.nn.call(void 0, applyOpResult.modified.node.parent.node._id, "Expected parent node to have an ID") : void 0;
817
- if (!parentId || !createdNodeIds.has(parentId)) {
818
- var _reverse;
819
- result.updates.storageUpdates.set(_chunkZNCSOBAXjs.nn.call(void 0, applyOpResult.modified.node._id), _chunkZNCSOBAXjs.mergeStorageUpdates.call(void 0, result.updates.storageUpdates.get(_chunkZNCSOBAXjs.nn.call(void 0, applyOpResult.modified.node._id)), applyOpResult.modified));
820
- (_reverse = result.reverse).unshift.apply(_reverse, _toConsumableArray(applyOpResult.reverse));
821
- }
822
- if (op.type === 2 /* CREATE_LIST */ || op.type === 7 /* CREATE_MAP */ || op.type === 4 /* CREATE_OBJECT */ ) {
823
- createdNodeIds.add(_chunkZNCSOBAXjs.nn.call(void 0, applyOpResult.modified.node._id));
824
- }
825
- }
826
- }
827
- }
828
- } catch (err) {
829
- _didIteratorError = true;
830
- _iteratorError = err;
831
- } finally{
832
- try {
833
- if (!_iteratorNormalCompletion && _iterator.return != null) {
834
- _iterator.return();
835
- }
836
- } finally{
837
- if (_didIteratorError) {
838
- throw _iteratorError;
839
- }
840
- }
841
- }
842
- return result;
843
- };
844
- var applyOp = function applyOp(op, source) {
845
- switch(op.type){
846
- case 6 /* DELETE_OBJECT_KEY */ :
847
- case 3 /* UPDATE_OBJECT */ :
848
- case 5 /* DELETE_CRDT */ :
849
- {
850
- var node = state.nodes.get(op.id);
851
- if (node == null) {
852
- return {
853
- modified: false
854
- };
855
- }
856
- return node._apply(op, source === 0 /* UNDOREDO_RECONNECT */ );
857
- }
858
- case 1 /* SET_PARENT_KEY */ :
859
- {
860
- var node1 = state.nodes.get(op.id);
861
- if (node1 == null) {
862
- return {
863
- modified: false
864
- };
865
- }
866
- if (node1.parent.type === "HasParent" && _chunkZNCSOBAXjs.isLiveList.call(void 0, node1.parent.node)) {
867
- return node1.parent.node._setChildKey(op.parentKey, node1, source);
868
- }
869
- return {
870
- modified: false
871
- };
872
- }
873
- case 4 /* CREATE_OBJECT */ :
874
- case 2 /* CREATE_LIST */ :
875
- case 7 /* CREATE_MAP */ :
876
- case 8 /* CREATE_REGISTER */ :
877
- {
878
- if (op.parentId === void 0) {
879
- return {
880
- modified: false
881
- };
882
- }
883
- var parentNode = state.nodes.get(op.parentId);
884
- if (parentNode == null) {
885
- return {
886
- modified: false
887
- };
888
- }
889
- return parentNode._attachChild(op, source);
890
- }
891
- }
892
- };
893
- var subscribeToLiveStructureDeeply = function subscribeToLiveStructureDeeply(node, callback) {
894
- return eventHub.storage.subscribe(function(updates) {
895
- var relatedUpdates = updates.filter(function(update) {
896
- return _chunkZNCSOBAXjs.isSameNodeOrChildOf.call(void 0, update.node, node);
897
- });
898
- if (relatedUpdates.length > 0) {
899
- callback(relatedUpdates);
900
- }
901
- });
902
- };
903
- var subscribeToLiveStructureShallowly = function subscribeToLiveStructureShallowly(node, callback) {
904
- return eventHub.storage.subscribe(function(updates) {
905
- var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
906
- try {
907
- for(var _iterator = updates[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
908
- var update = _step.value;
909
- if (update.node._id === node._id) {
910
- callback(update.node);
911
- }
912
- }
913
- } catch (err) {
914
- _didIteratorError = true;
915
- _iteratorError = err;
916
- } finally{
917
- try {
918
- if (!_iteratorNormalCompletion && _iterator.return != null) {
919
- _iterator.return();
920
- }
921
- } finally{
922
- if (_didIteratorError) {
923
- throw _iteratorError;
924
- }
925
- }
926
- }
927
- });
928
- };
929
- var subscribe = function subscribe(first, second, options) {
930
- if (typeof first === "string" && _chunkZNCSOBAXjs.isRoomEventName.call(void 0, first)) {
931
- if (typeof second !== "function") {
932
- throw new Error("Second argument must be a callback function");
933
- }
934
- var callback = second;
935
- switch(first){
936
- case "event":
937
- return eventHub.customEvent.subscribe(callback);
938
- case "my-presence":
939
- return eventHub.me.subscribe(callback);
940
- case "others":
941
- {
942
- var cb = callback;
943
- return eventHub.others.subscribe(function(param) {
944
- var others = param.others, event = param.event;
945
- return cb(others, event);
946
- });
947
- }
948
- case "error":
949
- return eventHub.error.subscribe(callback);
950
- case "connection":
951
- return eventHub.connection.subscribe(callback);
952
- case "storage":
953
- return eventHub.storage.subscribe(callback);
954
- case "history":
955
- return eventHub.history.subscribe(callback);
956
- default:
957
- return _chunkZNCSOBAXjs.assertNever.call(void 0, first, "Unknown event");
958
- }
959
- }
960
- if (second === void 0 || typeof first === "function") {
961
- if (typeof first === "function") {
962
- var storageCallback = first;
963
- return eventHub.storage.subscribe(storageCallback);
964
- } else {
965
- throw new Error("Please specify a listener callback");
966
- }
967
- }
968
- if (_chunkZNCSOBAXjs.isLiveNode.call(void 0, first)) {
969
- var node = first;
970
- if (_optionalChain([
971
- options,
972
- "optionalAccess",
973
- function(_) {
974
- return _.isDeep;
975
- }
976
- ])) {
977
- var storageCallback1 = second;
978
- return subscribeToLiveStructureDeeply(node, storageCallback1);
979
- } else {
980
- var nodeCallback = second;
981
- return subscribeToLiveStructureShallowly(node, nodeCallback);
982
- }
446
+ for (const key in op.data) {
447
+ reverse.data[key] = state.me.current[key];
983
448
  }
984
- throw new Error('"'.concat(first, '" is not a valid event name'));
985
- };
986
- var getConnectionState = function getConnectionState() {
987
- return state.connection.current.state;
988
- };
989
- var connect = function connect() {
990
- if (state.connection.current.state !== "closed" && state.connection.current.state !== "unavailable") {
991
- return null;
992
- }
993
- var auth = prepareAuthEndpoint(config.authentication, _nullishCoalesce(_optionalChain([
994
- config,
995
- "access",
996
- function(_2) {
997
- return _2.polyfills;
998
- },
999
- "optionalAccess",
1000
- function(_3) {
1001
- return _3.fetch;
1002
- }
1003
- ]), function() {
1004
- return config.fetchPolyfill;
1005
- }));
1006
- var createWebSocket = prepareCreateWebSocket(config.liveblocksServer, _nullishCoalesce(_optionalChain([
1007
- config,
1008
- "access",
1009
- function(_4) {
1010
- return _4.polyfills;
1011
- },
1012
- "optionalAccess",
1013
- function(_5) {
1014
- return _5.WebSocket;
1015
- }
1016
- ]), function() {
1017
- return config.WebSocketPolyfill;
1018
- }));
1019
- updateConnection({
1020
- state: "authenticating"
1021
- });
1022
- effects.authenticate(auth, createWebSocket);
1023
- };
1024
- var updatePresence = function updatePresence(patch, options) {
1025
- var oldValues = {};
449
+ state.me.patch(op.data);
1026
450
  if (state.buffer.me == null) {
1027
- state.buffer.me = {
1028
- type: "partial",
1029
- data: {}
1030
- };
1031
- }
1032
- for(var key in patch){
1033
- var overrideValue = patch[key];
1034
- if (overrideValue === void 0) {
1035
- continue;
1036
- }
1037
- state.buffer.me.data[key] = overrideValue;
1038
- oldValues[key] = state.me.current[key];
1039
- }
1040
- state.me.patch(patch);
1041
- if (state.isBatching) {
1042
- if (_optionalChain([
1043
- options,
1044
- "optionalAccess",
1045
- function(_6) {
1046
- return _6.addToHistory;
1047
- }
1048
- ])) {
1049
- state.batch.reverseOps.push({
1050
- type: "presence",
1051
- data: oldValues
1052
- });
1053
- }
1054
- state.batch.updates.presence = true;
1055
- } else {
1056
- tryFlushing();
1057
- if (_optionalChain([
1058
- options,
1059
- "optionalAccess",
1060
- function(_7) {
1061
- return _7.addToHistory;
1062
- }
1063
- ])) {
1064
- addToUndoStack([
1065
- {
1066
- type: "presence",
1067
- data: oldValues
1068
- }
1069
- ]);
1070
- }
1071
- notify({
1072
- presence: true
1073
- });
1074
- }
1075
- };
1076
- var authenticationSuccess = function authenticationSuccess(token, socket) {
1077
- socket.addEventListener("message", onMessage);
1078
- socket.addEventListener("open", onOpen);
1079
- socket.addEventListener("close", onClose);
1080
- socket.addEventListener("error", onError);
1081
- updateConnection({
1082
- state: "connecting",
1083
- id: token.actor,
1084
- userInfo: token.info,
1085
- userId: token.id
1086
- });
1087
- state.idFactory = makeIdFactory(token.actor);
1088
- state.socket = socket;
1089
- };
1090
- var authenticationFailure = function authenticationFailure(error) {
1091
- if (process.env.NODE_ENV !== "production") {
1092
- console.error("Call to authentication endpoint failed", error);
1093
- }
1094
- state.token = null;
1095
- updateConnection({
1096
- state: "unavailable"
1097
- });
1098
- state.numberOfRetry++;
1099
- state.timeoutHandles.reconnect = effects.scheduleReconnect(getRetryDelay());
1100
- };
1101
- var onVisibilityChange = function onVisibilityChange(visibilityState) {
1102
- if (visibilityState === "visible" && state.connection.current.state === "open") {
1103
- log("Heartbeat after visibility change");
1104
- heartbeat();
1105
- }
1106
- };
1107
- var onUpdatePresenceMessage = function onUpdatePresenceMessage(message) {
1108
- if (message.targetActor !== void 0) {
1109
- var oldUser = state.others.getUser(message.actor);
1110
- state.others.setOther(message.actor, message.data);
1111
- var newUser = state.others.getUser(message.actor);
1112
- if (oldUser === void 0 && newUser !== void 0) {
1113
- return {
1114
- type: "enter",
1115
- user: newUser
1116
- };
1117
- }
451
+ state.buffer.me = { type: "partial", data: op.data };
1118
452
  } else {
1119
- state.others.patchOther(message.actor, message.data), message;
1120
- }
1121
- var user = state.others.getUser(message.actor);
1122
- if (user) {
1123
- return {
1124
- type: "update",
1125
- updates: message.data,
1126
- user: user
1127
- };
1128
- } else {
1129
- return void 0;
1130
- }
1131
- };
1132
- var onUserLeftMessage = function onUserLeftMessage(message) {
1133
- var user = state.others.getUser(message.actor);
1134
- if (user) {
1135
- state.others.removeConnection(message.actor);
1136
- return {
1137
- type: "leave",
1138
- user: user
1139
- };
1140
- }
1141
- return null;
1142
- };
1143
- var onRoomStateMessage = function onRoomStateMessage(message) {
1144
- for(var key in message.users){
1145
- var user = message.users[key];
1146
- var connectionId = Number(key);
1147
- state.others.setConnection(connectionId, user.id, user.info);
1148
- }
1149
- return {
1150
- type: "reset"
1151
- };
1152
- };
1153
- var onNavigatorOnline = function onNavigatorOnline() {
1154
- if (state.connection.current.state === "unavailable") {
1155
- log("Try to reconnect after connectivity change");
1156
- reconnect();
1157
- }
1158
- };
1159
- var onHistoryChange = function onHistoryChange() {
1160
- eventHub.history.notify({
1161
- canUndo: canUndo(),
1162
- canRedo: canRedo()
1163
- });
1164
- };
1165
- var onUserJoinedMessage = function onUserJoinedMessage(message) {
1166
- state.others.setConnection(message.actor, message.id, message.info);
1167
- state.buffer.messages.push({
1168
- type: 100 /* UPDATE_PRESENCE */ ,
1169
- data: state.me.current,
1170
- targetActor: message.actor
1171
- });
1172
- tryFlushing();
1173
- var user = state.others.getUser(message.actor);
1174
- return user ? {
1175
- type: "enter",
1176
- user: user
1177
- } : void 0;
1178
- };
1179
- var parseServerMessage = function parseServerMessage(data) {
1180
- if (!_chunkZNCSOBAXjs.isJsonObject.call(void 0, data)) {
1181
- return null;
1182
- }
1183
- return data;
1184
- };
1185
- var parseServerMessages = function parseServerMessages(text) {
1186
- var data = _chunkZNCSOBAXjs.tryParseJson.call(void 0, text);
1187
- if (data === void 0) {
1188
- return null;
1189
- } else if (_chunkZNCSOBAXjs.isJsonArray.call(void 0, data)) {
1190
- return _chunkZNCSOBAXjs.compact.call(void 0, data.map(function(item) {
1191
- return parseServerMessage(item);
1192
- }));
1193
- } else {
1194
- return _chunkZNCSOBAXjs.compact.call(void 0, [
1195
- parseServerMessage(data)
1196
- ]);
1197
- }
1198
- };
1199
- var onMessage = function onMessage(event) {
1200
- if (event.data === "pong") {
1201
- clearTimeout(state.timeoutHandles.pongTimeout);
1202
- return;
1203
- }
1204
- var messages = parseServerMessages(event.data);
1205
- if (messages === null || messages.length === 0) {
1206
- return;
1207
- }
1208
- var updates = {
1209
- storageUpdates: /* @__PURE__ */ new Map(),
1210
- others: []
1211
- };
1212
- var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
1213
- try {
1214
- for(var _iterator = messages[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
1215
- var message = _step.value;
1216
- switch(message.type){
1217
- case 101 /* USER_JOINED */ :
1218
- {
1219
- var userJoinedUpdate = onUserJoinedMessage(message);
1220
- if (userJoinedUpdate) {
1221
- updates.others.push(userJoinedUpdate);
1222
- }
1223
- break;
1224
- }
1225
- case 100 /* UPDATE_PRESENCE */ :
1226
- {
1227
- var othersPresenceUpdate = onUpdatePresenceMessage(message);
1228
- if (othersPresenceUpdate) {
1229
- updates.others.push(othersPresenceUpdate);
1230
- }
1231
- break;
1232
- }
1233
- case 103 /* BROADCASTED_EVENT */ :
1234
- {
1235
- eventHub.customEvent.notify({
1236
- connectionId: message.actor,
1237
- event: message.event
1238
- });
1239
- break;
1240
- }
1241
- case 102 /* USER_LEFT */ :
1242
- {
1243
- var event2 = onUserLeftMessage(message);
1244
- if (event2) {
1245
- updates.others.push(event2);
1246
- }
1247
- break;
1248
- }
1249
- case 104 /* ROOM_STATE */ :
1250
- {
1251
- updates.others.push(onRoomStateMessage(message));
1252
- break;
1253
- }
1254
- case 200 /* INITIAL_STORAGE_STATE */ :
1255
- {
1256
- var offlineOps = new Map(state.offlineOperations);
1257
- createOrUpdateRootFromMessage(message);
1258
- applyAndSendOfflineOps(offlineOps);
1259
- _optionalChain([
1260
- _getInitialStateResolver,
1261
- "optionalCall",
1262
- function(_8) {
1263
- return _8();
1264
- }
1265
- ]);
1266
- eventHub.storageDidLoad.notify();
1267
- break;
1268
- }
1269
- case 201 /* UPDATE_STORAGE */ :
1270
- {
1271
- var applyResult = apply(message.ops, false);
1272
- applyResult.updates.storageUpdates.forEach(function(value, key) {
1273
- updates.storageUpdates.set(key, _chunkZNCSOBAXjs.mergeStorageUpdates.call(void 0, updates.storageUpdates.get(key), value));
1274
- });
1275
- break;
1276
- }
1277
- }
1278
- }
1279
- } catch (err) {
1280
- _didIteratorError = true;
1281
- _iteratorError = err;
1282
- } finally{
1283
- try {
1284
- if (!_iteratorNormalCompletion && _iterator.return != null) {
1285
- _iterator.return();
1286
- }
1287
- } finally{
1288
- if (_didIteratorError) {
1289
- throw _iteratorError;
1290
- }
1291
- }
1292
- }
1293
- notify(updates);
1294
- };
1295
- var onClose = function onClose(event) {
1296
- state.socket = null;
1297
- clearTimeout(state.timeoutHandles.pongTimeout);
1298
- clearInterval(state.intervalHandles.heartbeat);
1299
- if (state.timeoutHandles.flush) {
1300
- clearTimeout(state.timeoutHandles.flush);
1301
- }
1302
- clearTimeout(state.timeoutHandles.reconnect);
1303
- state.others.clearOthers();
1304
- notify({
1305
- others: [
1306
- {
1307
- type: "reset"
1308
- }
1309
- ]
1310
- });
1311
- if (event.code >= 4e3 && event.code <= 4100) {
1312
- updateConnection({
1313
- state: "failed"
1314
- });
1315
- var error = new LiveblocksError(event.reason, event.code);
1316
- eventHub.error.notify(error);
1317
- var delay = getRetryDelay(true);
1318
- state.numberOfRetry++;
1319
- if (process.env.NODE_ENV !== "production") {
1320
- console.error("Connection to Liveblocks websocket server closed. Reason: ".concat(error.message, " (code: ").concat(error.code, "). Retrying in ").concat(delay, "ms."));
1321
- }
1322
- updateConnection({
1323
- state: "unavailable"
1324
- });
1325
- state.timeoutHandles.reconnect = effects.scheduleReconnect(delay);
1326
- } else if (event.code === 4999 /* CLOSE_WITHOUT_RETRY */ ) {
1327
- updateConnection({
1328
- state: "closed"
1329
- });
1330
- } else {
1331
- var delay1 = getRetryDelay();
1332
- state.numberOfRetry++;
1333
- if (process.env.NODE_ENV !== "production") {
1334
- console.warn("Connection to Liveblocks websocket server closed (code: ".concat(event.code, "). Retrying in ").concat(delay1, "ms."));
1335
- }
1336
- updateConnection({
1337
- state: "unavailable"
1338
- });
1339
- state.timeoutHandles.reconnect = effects.scheduleReconnect(delay1);
1340
- }
1341
- };
1342
- var updateConnection = function updateConnection(connection) {
1343
- state.connection.set(connection);
1344
- eventHub.connection.notify(connection.state);
1345
- };
1346
- var getRetryDelay = function getRetryDelay() {
1347
- var slow = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : false;
1348
- if (slow) {
1349
- return BACKOFF_RETRY_DELAYS_SLOW[state.numberOfRetry < BACKOFF_RETRY_DELAYS_SLOW.length ? state.numberOfRetry : BACKOFF_RETRY_DELAYS_SLOW.length - 1];
1350
- }
1351
- return BACKOFF_RETRY_DELAYS[state.numberOfRetry < BACKOFF_RETRY_DELAYS.length ? state.numberOfRetry : BACKOFF_RETRY_DELAYS.length - 1];
1352
- };
1353
- var onError = function onError() {};
1354
- var onOpen = function onOpen() {
1355
- clearInterval(state.intervalHandles.heartbeat);
1356
- state.intervalHandles.heartbeat = effects.startHeartbeatInterval();
1357
- if (state.connection.current.state === "connecting") {
1358
- updateConnection(_objectSpreadProps(_objectSpread({}, state.connection.current), {
1359
- state: "open"
1360
- }));
1361
- state.numberOfRetry = 0;
1362
- if (state.lastConnectionId !== void 0) {
1363
- state.buffer.me = {
1364
- type: "full",
1365
- data: state.me.current
1366
- };
1367
- tryFlushing();
1368
- }
1369
- state.lastConnectionId = state.connection.current.id;
1370
- if (state.root) {
1371
- state.buffer.messages.push({
1372
- type: 200 /* FETCH_STORAGE */
1373
- });
1374
- }
1375
- tryFlushing();
1376
- } else {}
1377
- };
1378
- var heartbeat = function heartbeat() {
1379
- if (state.socket == null) {
1380
- return;
1381
- }
1382
- clearTimeout(state.timeoutHandles.pongTimeout);
1383
- state.timeoutHandles.pongTimeout = effects.schedulePongTimeout();
1384
- if (state.socket.readyState === state.socket.OPEN) {
1385
- state.socket.send("ping");
1386
- }
1387
- };
1388
- var pongTimeout = function pongTimeout() {
1389
- log("Pong timeout. Trying to reconnect.");
1390
- reconnect();
1391
- };
1392
- var reconnect = function reconnect() {
1393
- if (state.socket) {
1394
- state.socket.removeEventListener("open", onOpen);
1395
- state.socket.removeEventListener("message", onMessage);
1396
- state.socket.removeEventListener("close", onClose);
1397
- state.socket.removeEventListener("error", onError);
1398
- state.socket.close();
1399
- state.socket = null;
1400
- }
1401
- updateConnection({
1402
- state: "unavailable"
1403
- });
1404
- clearTimeout(state.timeoutHandles.pongTimeout);
1405
- if (state.timeoutHandles.flush) {
1406
- clearTimeout(state.timeoutHandles.flush);
1407
- }
1408
- clearTimeout(state.timeoutHandles.reconnect);
1409
- clearInterval(state.intervalHandles.heartbeat);
1410
- connect();
1411
- };
1412
- var applyAndSendOfflineOps = function applyAndSendOfflineOps(offlineOps) {
1413
- if (offlineOps.size === 0) {
1414
- return;
1415
- }
1416
- var messages = [];
1417
- var ops = Array.from(offlineOps.values());
1418
- var result = apply(ops, true);
1419
- messages.push({
1420
- type: 201 /* UPDATE_STORAGE */ ,
1421
- ops: ops
1422
- });
1423
- notify(result.updates);
1424
- effects.send(messages);
1425
- };
1426
- var tryFlushing = function tryFlushing() {
1427
- var storageOps = state.buffer.storageOperations;
1428
- if (storageOps.length > 0) {
1429
- storageOps.forEach(function(op) {
1430
- state.offlineOperations.set(_chunkZNCSOBAXjs.nn.call(void 0, op.opId), op);
1431
- });
1432
- }
1433
- if (state.socket == null || state.socket.readyState !== state.socket.OPEN) {
1434
- state.buffer.storageOperations = [];
1435
- return;
1436
- }
1437
- var now = Date.now();
1438
- var elapsedTime = now - state.lastFlushTime;
1439
- if (elapsedTime > config.throttleDelay) {
1440
- var messages = flushDataToMessages(state);
1441
- if (messages.length === 0) {
1442
- return;
1443
- }
1444
- effects.send(messages);
1445
- state.buffer = {
1446
- messages: [],
1447
- storageOperations: [],
1448
- me: null
1449
- };
1450
- state.lastFlushTime = now;
453
+ for (const key in op.data) {
454
+ state.buffer.me.data[key] = op.data[key];
455
+ }
456
+ }
457
+ result.reverse.unshift(reverse);
458
+ result.updates.presence = true;
459
+ } else {
460
+ let source;
461
+ if (!op.opId) {
462
+ op.opId = pool.generateOpId();
463
+ }
464
+ if (isLocal) {
465
+ source = 0 /* UNDOREDO_RECONNECT */;
1451
466
  } else {
1452
- if (state.timeoutHandles.flush != null) {
1453
- clearTimeout(state.timeoutHandles.flush);
1454
- }
1455
- state.timeoutHandles.flush = effects.delayFlush(config.throttleDelay - (now - state.lastFlushTime));
1456
- }
1457
- };
1458
- var flushDataToMessages = function flushDataToMessages(state2) {
1459
- var messages = [];
1460
- if (state2.buffer.me) {
1461
- messages.push(state2.buffer.me.type === "full" ? {
1462
- type: 100 /* UPDATE_PRESENCE */ ,
1463
- targetActor: -1,
1464
- data: state2.buffer.me.data
1465
- } : {
1466
- type: 100 /* UPDATE_PRESENCE */ ,
1467
- data: state2.buffer.me.data
1468
- });
1469
- }
1470
- var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
1471
- try {
1472
- for(var _iterator = state2.buffer.messages[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
1473
- var event = _step.value;
1474
- messages.push(event);
1475
- }
1476
- } catch (err) {
1477
- _didIteratorError = true;
1478
- _iteratorError = err;
1479
- } finally{
1480
- try {
1481
- if (!_iteratorNormalCompletion && _iterator.return != null) {
1482
- _iterator.return();
1483
- }
1484
- } finally{
1485
- if (_didIteratorError) {
1486
- throw _iteratorError;
1487
- }
1488
- }
1489
- }
1490
- if (state2.buffer.storageOperations.length > 0) {
1491
- messages.push({
1492
- type: 201 /* UPDATE_STORAGE */ ,
1493
- ops: state2.buffer.storageOperations
1494
- });
1495
- }
1496
- return messages;
1497
- };
1498
- var disconnect = function disconnect() {
1499
- if (state.socket) {
1500
- state.socket.removeEventListener("open", onOpen);
1501
- state.socket.removeEventListener("message", onMessage);
1502
- state.socket.removeEventListener("close", onClose);
1503
- state.socket.removeEventListener("error", onError);
1504
- state.socket.close();
1505
- state.socket = null;
1506
- }
1507
- updateConnection({
1508
- state: "closed"
1509
- });
1510
- if (state.timeoutHandles.flush) {
1511
- clearTimeout(state.timeoutHandles.flush);
1512
- }
1513
- clearTimeout(state.timeoutHandles.reconnect);
1514
- clearTimeout(state.timeoutHandles.pongTimeout);
1515
- clearInterval(state.intervalHandles.heartbeat);
1516
- state.others.clearOthers();
1517
- notify({
1518
- others: [
1519
- {
1520
- type: "reset"
1521
- }
1522
- ]
1523
- });
1524
- Object.values(eventHub).forEach(function(eventSource) {
1525
- return eventSource.clear();
467
+ const deleted = state.offlineOperations.delete(_chunkRS4TQ2LTjs.nn.call(void 0, op.opId));
468
+ source = deleted ? 2 /* ACK */ : 1 /* REMOTE */;
469
+ }
470
+ const applyOpResult = applyOp(op, source);
471
+ if (applyOpResult.modified) {
472
+ const parentId = applyOpResult.modified.node.parent.type === "HasParent" ? _chunkRS4TQ2LTjs.nn.call(void 0,
473
+ applyOpResult.modified.node.parent.node._id,
474
+ "Expected parent node to have an ID"
475
+ ) : void 0;
476
+ if (!parentId || !createdNodeIds.has(parentId)) {
477
+ result.updates.storageUpdates.set(
478
+ _chunkRS4TQ2LTjs.nn.call(void 0, applyOpResult.modified.node._id),
479
+ _chunkRS4TQ2LTjs.mergeStorageUpdates.call(void 0,
480
+ result.updates.storageUpdates.get(
481
+ _chunkRS4TQ2LTjs.nn.call(void 0, applyOpResult.modified.node._id)
482
+ ),
483
+ applyOpResult.modified
484
+ )
485
+ );
486
+ result.reverse.unshift(...applyOpResult.reverse);
487
+ }
488
+ if (op.type === 2 /* CREATE_LIST */ || op.type === 7 /* CREATE_MAP */ || op.type === 4 /* CREATE_OBJECT */) {
489
+ createdNodeIds.add(_chunkRS4TQ2LTjs.nn.call(void 0, applyOpResult.modified.node._id));
490
+ }
491
+ }
492
+ }
493
+ }
494
+ return result;
495
+ }
496
+ function applyOp(op, source) {
497
+ switch (op.type) {
498
+ case 6 /* DELETE_OBJECT_KEY */:
499
+ case 3 /* UPDATE_OBJECT */:
500
+ case 5 /* DELETE_CRDT */: {
501
+ const node = state.nodes.get(op.id);
502
+ if (node == null) {
503
+ return { modified: false };
504
+ }
505
+ return node._apply(op, source === 0 /* UNDOREDO_RECONNECT */);
506
+ }
507
+ case 1 /* SET_PARENT_KEY */: {
508
+ const node = state.nodes.get(op.id);
509
+ if (node == null) {
510
+ return { modified: false };
511
+ }
512
+ if (node.parent.type === "HasParent" && _chunkRS4TQ2LTjs.isLiveList.call(void 0, node.parent.node)) {
513
+ return node.parent.node._setChildKey(op.parentKey, node, source);
514
+ }
515
+ return { modified: false };
516
+ }
517
+ case 4 /* CREATE_OBJECT */:
518
+ case 2 /* CREATE_LIST */:
519
+ case 7 /* CREATE_MAP */:
520
+ case 8 /* CREATE_REGISTER */: {
521
+ if (op.parentId === void 0) {
522
+ return { modified: false };
523
+ }
524
+ const parentNode = state.nodes.get(op.parentId);
525
+ if (parentNode == null) {
526
+ return { modified: false };
527
+ }
528
+ return parentNode._attachChild(op, source);
529
+ }
530
+ }
531
+ }
532
+ function subscribeToLiveStructureDeeply(node, callback) {
533
+ return eventHub.storage.subscribe((updates) => {
534
+ const relatedUpdates = updates.filter(
535
+ (update) => _chunkRS4TQ2LTjs.isSameNodeOrChildOf.call(void 0, update.node, node)
536
+ );
537
+ if (relatedUpdates.length > 0) {
538
+ callback(relatedUpdates);
539
+ }
540
+ });
541
+ }
542
+ function subscribeToLiveStructureShallowly(node, callback) {
543
+ return eventHub.storage.subscribe((updates) => {
544
+ for (const update of updates) {
545
+ if (update.node._id === node._id) {
546
+ callback(update.node);
547
+ }
548
+ }
549
+ });
550
+ }
551
+ function subscribe(first, second, options) {
552
+ if (typeof first === "string" && _chunkRS4TQ2LTjs.isRoomEventName.call(void 0, first)) {
553
+ if (typeof second !== "function") {
554
+ throw new Error("Second argument must be a callback function");
555
+ }
556
+ const callback = second;
557
+ switch (first) {
558
+ case "event":
559
+ return eventHub.customEvent.subscribe(
560
+ callback
561
+ );
562
+ case "my-presence":
563
+ return eventHub.me.subscribe(callback);
564
+ case "others": {
565
+ const cb = callback;
566
+ return eventHub.others.subscribe(
567
+ ({ others, event }) => cb(others, event)
568
+ );
569
+ }
570
+ case "error":
571
+ return eventHub.error.subscribe(callback);
572
+ case "connection":
573
+ return eventHub.connection.subscribe(
574
+ callback
575
+ );
576
+ case "storage":
577
+ return eventHub.storage.subscribe(
578
+ callback
579
+ );
580
+ case "history":
581
+ return eventHub.history.subscribe(callback);
582
+ default:
583
+ return _chunkRS4TQ2LTjs.assertNever.call(void 0, first, "Unknown event");
584
+ }
585
+ }
586
+ if (second === void 0 || typeof first === "function") {
587
+ if (typeof first === "function") {
588
+ const storageCallback = first;
589
+ return eventHub.storage.subscribe(storageCallback);
590
+ } else {
591
+ throw new Error("Please specify a listener callback");
592
+ }
593
+ }
594
+ if (_chunkRS4TQ2LTjs.isLiveNode.call(void 0, first)) {
595
+ const node = first;
596
+ if (options == null ? void 0 : options.isDeep) {
597
+ const storageCallback = second;
598
+ return subscribeToLiveStructureDeeply(node, storageCallback);
599
+ } else {
600
+ const nodeCallback = second;
601
+ return subscribeToLiveStructureShallowly(node, nodeCallback);
602
+ }
603
+ }
604
+ throw new Error(`"${first}" is not a valid event name`);
605
+ }
606
+ function getConnectionState() {
607
+ return state.connection.current.state;
608
+ }
609
+ function connect() {
610
+ var _a, _b, _c, _d;
611
+ if (state.connection.current.state !== "closed" && state.connection.current.state !== "unavailable") {
612
+ return null;
613
+ }
614
+ const auth = prepareAuthEndpoint(
615
+ config.authentication,
616
+ (_b = (_a = config.polyfills) == null ? void 0 : _a.fetch) != null ? _b : config.fetchPolyfill
617
+ );
618
+ const createWebSocket = prepareCreateWebSocket(
619
+ config.liveblocksServer,
620
+ (_d = (_c = config.polyfills) == null ? void 0 : _c.WebSocket) != null ? _d : config.WebSocketPolyfill
621
+ );
622
+ updateConnection({ state: "authenticating" });
623
+ effects.authenticate(auth, createWebSocket);
624
+ }
625
+ function updatePresence(patch, options) {
626
+ const oldValues = {};
627
+ if (state.buffer.me == null) {
628
+ state.buffer.me = {
629
+ type: "partial",
630
+ data: {}
631
+ };
632
+ }
633
+ for (const key in patch) {
634
+ const overrideValue = patch[key];
635
+ if (overrideValue === void 0) {
636
+ continue;
637
+ }
638
+ state.buffer.me.data[key] = overrideValue;
639
+ oldValues[key] = state.me.current[key];
640
+ }
641
+ state.me.patch(patch);
642
+ if (state.activeBatch) {
643
+ if (options == null ? void 0 : options.addToHistory) {
644
+ state.activeBatch.reverseOps.push({
645
+ type: "presence",
646
+ data: oldValues
1526
647
  });
1527
- };
1528
- var getPresence = function getPresence() {
1529
- return state.me.current;
1530
- };
1531
- var getOthers = function getOthers() {
1532
- return state.others.current;
1533
- };
1534
- var broadcastEvent = function broadcastEvent(event) {
1535
- var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {
1536
- shouldQueueEventIfNotReady: false
648
+ }
649
+ state.activeBatch.updates.presence = true;
650
+ } else {
651
+ tryFlushing();
652
+ if (options == null ? void 0 : options.addToHistory) {
653
+ addToUndoStack([{ type: "presence", data: oldValues }]);
654
+ }
655
+ notify({ presence: true });
656
+ }
657
+ }
658
+ function authenticationSuccess(token, socket) {
659
+ socket.addEventListener("message", onMessage);
660
+ socket.addEventListener("open", onOpen);
661
+ socket.addEventListener("close", onClose);
662
+ socket.addEventListener("error", onError);
663
+ updateConnection({
664
+ state: "connecting",
665
+ id: token.actor,
666
+ userInfo: token.info,
667
+ userId: token.id
668
+ });
669
+ state.idFactory = makeIdFactory(token.actor);
670
+ state.socket = socket;
671
+ }
672
+ function authenticationFailure(error) {
673
+ if (process.env.NODE_ENV !== "production") {
674
+ console.error("Call to authentication endpoint failed", error);
675
+ }
676
+ state.token = null;
677
+ updateConnection({ state: "unavailable" });
678
+ state.numberOfRetry++;
679
+ state.timeoutHandles.reconnect = effects.scheduleReconnect(getRetryDelay());
680
+ }
681
+ function onVisibilityChange(visibilityState) {
682
+ if (visibilityState === "visible" && state.connection.current.state === "open") {
683
+ log("Heartbeat after visibility change");
684
+ heartbeat();
685
+ }
686
+ }
687
+ function onUpdatePresenceMessage(message) {
688
+ if (message.targetActor !== void 0) {
689
+ const oldUser = state.others.getUser(message.actor);
690
+ state.others.setOther(message.actor, message.data);
691
+ const newUser = state.others.getUser(message.actor);
692
+ if (oldUser === void 0 && newUser !== void 0) {
693
+ return { type: "enter", user: newUser };
694
+ }
695
+ } else {
696
+ state.others.patchOther(message.actor, message.data), message;
697
+ }
698
+ const user = state.others.getUser(message.actor);
699
+ if (user) {
700
+ return {
701
+ type: "update",
702
+ updates: message.data,
703
+ user
704
+ };
705
+ } else {
706
+ return void 0;
707
+ }
708
+ }
709
+ function onUserLeftMessage(message) {
710
+ const user = state.others.getUser(message.actor);
711
+ if (user) {
712
+ state.others.removeConnection(message.actor);
713
+ return { type: "leave", user };
714
+ }
715
+ return null;
716
+ }
717
+ function onRoomStateMessage(message) {
718
+ for (const key in message.users) {
719
+ const user = message.users[key];
720
+ const connectionId = Number(key);
721
+ state.others.setConnection(connectionId, user.id, user.info);
722
+ }
723
+ return { type: "reset" };
724
+ }
725
+ function onNavigatorOnline() {
726
+ if (state.connection.current.state === "unavailable") {
727
+ log("Try to reconnect after connectivity change");
728
+ reconnect();
729
+ }
730
+ }
731
+ function onHistoryChange() {
732
+ eventHub.history.notify({ canUndo: canUndo(), canRedo: canRedo() });
733
+ }
734
+ function onUserJoinedMessage(message) {
735
+ state.others.setConnection(message.actor, message.id, message.info);
736
+ state.buffer.messages.push({
737
+ type: 100 /* UPDATE_PRESENCE */,
738
+ data: state.me.current,
739
+ targetActor: message.actor
740
+ });
741
+ tryFlushing();
742
+ const user = state.others.getUser(message.actor);
743
+ return user ? { type: "enter", user } : void 0;
744
+ }
745
+ function parseServerMessage(data) {
746
+ if (!_chunkRS4TQ2LTjs.isJsonObject.call(void 0, data)) {
747
+ return null;
748
+ }
749
+ return data;
750
+ }
751
+ function parseServerMessages(text) {
752
+ const data = _chunkRS4TQ2LTjs.tryParseJson.call(void 0, text);
753
+ if (data === void 0) {
754
+ return null;
755
+ } else if (_chunkRS4TQ2LTjs.isJsonArray.call(void 0, data)) {
756
+ return _chunkRS4TQ2LTjs.compact.call(void 0, data.map((item) => parseServerMessage(item)));
757
+ } else {
758
+ return _chunkRS4TQ2LTjs.compact.call(void 0, [parseServerMessage(data)]);
759
+ }
760
+ }
761
+ function onMessage(event) {
762
+ if (event.data === "pong") {
763
+ clearTimeout(state.timeoutHandles.pongTimeout);
764
+ return;
765
+ }
766
+ const messages = parseServerMessages(event.data);
767
+ if (messages === null || messages.length === 0) {
768
+ return;
769
+ }
770
+ const updates = {
771
+ storageUpdates: /* @__PURE__ */ new Map(),
772
+ others: []
773
+ };
774
+ for (const message of messages) {
775
+ switch (message.type) {
776
+ case 101 /* USER_JOINED */: {
777
+ const userJoinedUpdate = onUserJoinedMessage(message);
778
+ if (userJoinedUpdate) {
779
+ updates.others.push(userJoinedUpdate);
780
+ }
781
+ break;
782
+ }
783
+ case 100 /* UPDATE_PRESENCE */: {
784
+ const othersPresenceUpdate = onUpdatePresenceMessage(message);
785
+ if (othersPresenceUpdate) {
786
+ updates.others.push(othersPresenceUpdate);
787
+ }
788
+ break;
789
+ }
790
+ case 103 /* BROADCASTED_EVENT */: {
791
+ eventHub.customEvent.notify({
792
+ connectionId: message.actor,
793
+ event: message.event
794
+ });
795
+ break;
796
+ }
797
+ case 102 /* USER_LEFT */: {
798
+ const event2 = onUserLeftMessage(message);
799
+ if (event2) {
800
+ updates.others.push(event2);
801
+ }
802
+ break;
803
+ }
804
+ case 104 /* ROOM_STATE */: {
805
+ updates.others.push(onRoomStateMessage(message));
806
+ break;
807
+ }
808
+ case 200 /* INITIAL_STORAGE_STATE */: {
809
+ const offlineOps = new Map(state.offlineOperations);
810
+ createOrUpdateRootFromMessage(message);
811
+ applyAndSendOfflineOps(offlineOps);
812
+ _getInitialStateResolver == null ? void 0 : _getInitialStateResolver();
813
+ eventHub.storageDidLoad.notify();
814
+ break;
815
+ }
816
+ case 201 /* UPDATE_STORAGE */: {
817
+ const applyResult = apply(message.ops, false);
818
+ applyResult.updates.storageUpdates.forEach((value, key) => {
819
+ updates.storageUpdates.set(
820
+ key,
821
+ _chunkRS4TQ2LTjs.mergeStorageUpdates.call(void 0,
822
+ updates.storageUpdates.get(key),
823
+ value
824
+ )
825
+ );
826
+ });
827
+ break;
828
+ }
829
+ }
830
+ }
831
+ notify(updates);
832
+ }
833
+ function onClose(event) {
834
+ state.socket = null;
835
+ clearTimeout(state.timeoutHandles.pongTimeout);
836
+ clearInterval(state.intervalHandles.heartbeat);
837
+ if (state.timeoutHandles.flush) {
838
+ clearTimeout(state.timeoutHandles.flush);
839
+ }
840
+ clearTimeout(state.timeoutHandles.reconnect);
841
+ state.others.clearOthers();
842
+ notify({ others: [{ type: "reset" }] });
843
+ if (event.code >= 4e3 && event.code <= 4100) {
844
+ updateConnection({ state: "failed" });
845
+ const error = new LiveblocksError(event.reason, event.code);
846
+ eventHub.error.notify(error);
847
+ const delay = getRetryDelay(true);
848
+ state.numberOfRetry++;
849
+ if (process.env.NODE_ENV !== "production") {
850
+ console.error(
851
+ `Connection to Liveblocks websocket server closed. Reason: ${error.message} (code: ${error.code}). Retrying in ${delay}ms.`
852
+ );
853
+ }
854
+ updateConnection({ state: "unavailable" });
855
+ state.timeoutHandles.reconnect = effects.scheduleReconnect(delay);
856
+ } else if (event.code === 4999 /* CLOSE_WITHOUT_RETRY */) {
857
+ updateConnection({ state: "closed" });
858
+ } else {
859
+ const delay = getRetryDelay();
860
+ state.numberOfRetry++;
861
+ if (process.env.NODE_ENV !== "production") {
862
+ console.warn(
863
+ `Connection to Liveblocks websocket server closed (code: ${event.code}). Retrying in ${delay}ms.`
864
+ );
865
+ }
866
+ updateConnection({ state: "unavailable" });
867
+ state.timeoutHandles.reconnect = effects.scheduleReconnect(delay);
868
+ }
869
+ }
870
+ function updateConnection(connection) {
871
+ state.connection.set(connection);
872
+ eventHub.connection.notify(connection.state);
873
+ }
874
+ function getRetryDelay(slow = false) {
875
+ if (slow) {
876
+ return BACKOFF_RETRY_DELAYS_SLOW[state.numberOfRetry < BACKOFF_RETRY_DELAYS_SLOW.length ? state.numberOfRetry : BACKOFF_RETRY_DELAYS_SLOW.length - 1];
877
+ }
878
+ return BACKOFF_RETRY_DELAYS[state.numberOfRetry < BACKOFF_RETRY_DELAYS.length ? state.numberOfRetry : BACKOFF_RETRY_DELAYS.length - 1];
879
+ }
880
+ function onError() {
881
+ }
882
+ function onOpen() {
883
+ clearInterval(state.intervalHandles.heartbeat);
884
+ state.intervalHandles.heartbeat = effects.startHeartbeatInterval();
885
+ if (state.connection.current.state === "connecting") {
886
+ updateConnection(_chunkRS4TQ2LTjs.__spreadProps.call(void 0, _chunkRS4TQ2LTjs.__spreadValues.call(void 0, {}, state.connection.current), { state: "open" }));
887
+ state.numberOfRetry = 0;
888
+ if (state.lastConnectionId !== void 0) {
889
+ state.buffer.me = {
890
+ type: "full",
891
+ data: state.me.current
1537
892
  };
1538
- if (state.socket == null && options.shouldQueueEventIfNotReady == false) {
1539
- return;
1540
- }
1541
- state.buffer.messages.push({
1542
- type: 103 /* BROADCAST_EVENT */ ,
1543
- event: event
1544
- });
1545
893
  tryFlushing();
1546
- };
1547
- var dispatchOps = function dispatchOps(ops) {
1548
- var _storageOperations;
1549
- (_storageOperations = state.buffer.storageOperations).push.apply(_storageOperations, _toConsumableArray(ops));
1550
- tryFlushing();
1551
- };
1552
- var startLoadingStorage = function startLoadingStorage() {
1553
- if (_getInitialStatePromise == null) {
1554
- state.buffer.messages.push({
1555
- type: 200 /* FETCH_STORAGE */
1556
- });
1557
- tryFlushing();
1558
- _getInitialStatePromise = new Promise(function(resolve) {
1559
- return _getInitialStateResolver = resolve;
1560
- });
1561
- }
1562
- return _getInitialStatePromise;
1563
- };
1564
- var getStorageSnapshot = function getStorageSnapshot() {
1565
- var root = state.root;
1566
- if (root !== void 0) {
1567
- return root;
1568
- } else {
1569
- startLoadingStorage();
1570
- return null;
1571
- }
1572
- };
1573
- var getStorage = function getStorage() {
1574
- if (state.root) {
1575
- return Promise.resolve({
1576
- root: state.root
1577
- });
1578
- }
1579
- return startLoadingStorage().then(function() {
1580
- return {
1581
- root: _chunkZNCSOBAXjs.nn.call(void 0, state.root)
1582
- };
894
+ }
895
+ state.lastConnectionId = state.connection.current.id;
896
+ if (state.root) {
897
+ state.buffer.messages.push({ type: 200 /* FETCH_STORAGE */ });
898
+ }
899
+ tryFlushing();
900
+ } else {
901
+ }
902
+ }
903
+ function heartbeat() {
904
+ if (state.socket == null) {
905
+ return;
906
+ }
907
+ clearTimeout(state.timeoutHandles.pongTimeout);
908
+ state.timeoutHandles.pongTimeout = effects.schedulePongTimeout();
909
+ if (state.socket.readyState === state.socket.OPEN) {
910
+ state.socket.send("ping");
911
+ }
912
+ }
913
+ function pongTimeout() {
914
+ log("Pong timeout. Trying to reconnect.");
915
+ reconnect();
916
+ }
917
+ function reconnect() {
918
+ if (state.socket) {
919
+ state.socket.removeEventListener("open", onOpen);
920
+ state.socket.removeEventListener("message", onMessage);
921
+ state.socket.removeEventListener("close", onClose);
922
+ state.socket.removeEventListener("error", onError);
923
+ state.socket.close();
924
+ state.socket = null;
925
+ }
926
+ updateConnection({ state: "unavailable" });
927
+ clearTimeout(state.timeoutHandles.pongTimeout);
928
+ if (state.timeoutHandles.flush) {
929
+ clearTimeout(state.timeoutHandles.flush);
930
+ }
931
+ clearTimeout(state.timeoutHandles.reconnect);
932
+ clearInterval(state.intervalHandles.heartbeat);
933
+ connect();
934
+ }
935
+ function applyAndSendOfflineOps(offlineOps) {
936
+ if (offlineOps.size === 0) {
937
+ return;
938
+ }
939
+ const messages = [];
940
+ const ops = Array.from(offlineOps.values());
941
+ const result = apply(ops, true);
942
+ messages.push({
943
+ type: 201 /* UPDATE_STORAGE */,
944
+ ops
945
+ });
946
+ notify(result.updates);
947
+ effects.send(messages);
948
+ }
949
+ function tryFlushing() {
950
+ const storageOps = state.buffer.storageOperations;
951
+ if (storageOps.length > 0) {
952
+ storageOps.forEach((op) => {
953
+ state.offlineOperations.set(_chunkRS4TQ2LTjs.nn.call(void 0, op.opId), op);
954
+ });
955
+ }
956
+ if (state.socket == null || state.socket.readyState !== state.socket.OPEN) {
957
+ state.buffer.storageOperations = [];
958
+ return;
959
+ }
960
+ const now = Date.now();
961
+ const elapsedTime = now - state.lastFlushTime;
962
+ if (elapsedTime > config.throttleDelay) {
963
+ const messages = flushDataToMessages(state);
964
+ if (messages.length === 0) {
965
+ return;
966
+ }
967
+ effects.send(messages);
968
+ state.buffer = {
969
+ messages: [],
970
+ storageOperations: [],
971
+ me: null
972
+ };
973
+ state.lastFlushTime = now;
974
+ } else {
975
+ if (state.timeoutHandles.flush != null) {
976
+ clearTimeout(state.timeoutHandles.flush);
977
+ }
978
+ state.timeoutHandles.flush = effects.delayFlush(
979
+ config.throttleDelay - (now - state.lastFlushTime)
980
+ );
981
+ }
982
+ }
983
+ function flushDataToMessages(state2) {
984
+ const messages = [];
985
+ if (state2.buffer.me) {
986
+ messages.push(
987
+ state2.buffer.me.type === "full" ? {
988
+ type: 100 /* UPDATE_PRESENCE */,
989
+ targetActor: -1,
990
+ data: state2.buffer.me.data
991
+ } : {
992
+ type: 100 /* UPDATE_PRESENCE */,
993
+ data: state2.buffer.me.data
994
+ }
995
+ );
996
+ }
997
+ for (const event of state2.buffer.messages) {
998
+ messages.push(event);
999
+ }
1000
+ if (state2.buffer.storageOperations.length > 0) {
1001
+ messages.push({
1002
+ type: 201 /* UPDATE_STORAGE */,
1003
+ ops: state2.buffer.storageOperations
1004
+ });
1005
+ }
1006
+ return messages;
1007
+ }
1008
+ function disconnect() {
1009
+ if (state.socket) {
1010
+ state.socket.removeEventListener("open", onOpen);
1011
+ state.socket.removeEventListener("message", onMessage);
1012
+ state.socket.removeEventListener("close", onClose);
1013
+ state.socket.removeEventListener("error", onError);
1014
+ state.socket.close();
1015
+ state.socket = null;
1016
+ }
1017
+ updateConnection({ state: "closed" });
1018
+ if (state.timeoutHandles.flush) {
1019
+ clearTimeout(state.timeoutHandles.flush);
1020
+ }
1021
+ clearTimeout(state.timeoutHandles.reconnect);
1022
+ clearTimeout(state.timeoutHandles.pongTimeout);
1023
+ clearInterval(state.intervalHandles.heartbeat);
1024
+ state.others.clearOthers();
1025
+ notify({ others: [{ type: "reset" }] });
1026
+ Object.values(eventHub).forEach((eventSource) => eventSource.clear());
1027
+ }
1028
+ function getPresence() {
1029
+ return state.me.current;
1030
+ }
1031
+ function getOthers() {
1032
+ return state.others.current;
1033
+ }
1034
+ function broadcastEvent(event, options = {
1035
+ shouldQueueEventIfNotReady: false
1036
+ }) {
1037
+ if (state.socket == null && options.shouldQueueEventIfNotReady == false) {
1038
+ return;
1039
+ }
1040
+ state.buffer.messages.push({
1041
+ type: 103 /* BROADCAST_EVENT */,
1042
+ event
1043
+ });
1044
+ tryFlushing();
1045
+ }
1046
+ function dispatchOps(ops) {
1047
+ state.buffer.storageOperations.push(...ops);
1048
+ tryFlushing();
1049
+ }
1050
+ let _getInitialStatePromise = null;
1051
+ let _getInitialStateResolver = null;
1052
+ function startLoadingStorage() {
1053
+ if (_getInitialStatePromise == null) {
1054
+ state.buffer.messages.push({ type: 200 /* FETCH_STORAGE */ });
1055
+ tryFlushing();
1056
+ _getInitialStatePromise = new Promise(
1057
+ (resolve) => _getInitialStateResolver = resolve
1058
+ );
1059
+ }
1060
+ return _getInitialStatePromise;
1061
+ }
1062
+ function getStorageSnapshot() {
1063
+ const root = state.root;
1064
+ if (root !== void 0) {
1065
+ return root;
1066
+ } else {
1067
+ startLoadingStorage();
1068
+ return null;
1069
+ }
1070
+ }
1071
+ function getStorage() {
1072
+ return _chunkRS4TQ2LTjs.__async.call(void 0, this, null, function* () {
1073
+ if (state.root) {
1074
+ return Promise.resolve({
1075
+ root: state.root
1583
1076
  });
1584
- };
1585
- var undo = function undo() {
1586
- if (state.isBatching) {
1587
- throw new Error("undo is not allowed during a batch");
1588
- }
1589
- var historyItem = state.undoStack.pop();
1590
- if (historyItem == null) {
1591
- return;
1592
- }
1593
- state.isHistoryPaused = false;
1594
- var result = apply(historyItem, true);
1595
- notify(result.updates);
1596
- state.redoStack.push(result.reverse);
1597
- onHistoryChange();
1598
- var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
1599
- try {
1600
- for(var _iterator = historyItem[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
1601
- var op = _step.value;
1602
- if (op.type !== "presence") {
1603
- state.buffer.storageOperations.push(op);
1604
- }
1605
- }
1606
- } catch (err) {
1607
- _didIteratorError = true;
1608
- _iteratorError = err;
1609
- } finally{
1610
- try {
1611
- if (!_iteratorNormalCompletion && _iterator.return != null) {
1612
- _iterator.return();
1613
- }
1614
- } finally{
1615
- if (_didIteratorError) {
1616
- throw _iteratorError;
1617
- }
1618
- }
1619
- }
1620
- tryFlushing();
1621
- };
1622
- var canUndo = function canUndo() {
1623
- return state.undoStack.length > 0;
1624
- };
1625
- var redo = function redo() {
1626
- if (state.isBatching) {
1627
- throw new Error("redo is not allowed during a batch");
1628
- }
1629
- var historyItem = state.redoStack.pop();
1630
- if (historyItem == null) {
1631
- return;
1632
- }
1633
- state.isHistoryPaused = false;
1634
- var result = apply(historyItem, true);
1635
- notify(result.updates);
1636
- state.undoStack.push(result.reverse);
1637
- onHistoryChange();
1638
- var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
1639
- try {
1640
- for(var _iterator = historyItem[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
1641
- var op = _step.value;
1642
- if (op.type !== "presence") {
1643
- state.buffer.storageOperations.push(op);
1644
- }
1645
- }
1646
- } catch (err) {
1647
- _didIteratorError = true;
1648
- _iteratorError = err;
1649
- } finally{
1650
- try {
1651
- if (!_iteratorNormalCompletion && _iterator.return != null) {
1652
- _iterator.return();
1653
- }
1654
- } finally{
1655
- if (_didIteratorError) {
1656
- throw _iteratorError;
1657
- }
1658
- }
1659
- }
1660
- tryFlushing();
1661
- };
1662
- var canRedo = function canRedo() {
1663
- return state.redoStack.length > 0;
1664
- };
1665
- var batch = function batch(callback) {
1666
- if (state.isBatching) {
1667
- throw new Error("batch should not be called during a batch");
1668
- }
1669
- state.isBatching = true;
1670
- try {
1671
- callback();
1672
- } finally{
1673
- state.isBatching = false;
1674
- if (state.batch.reverseOps.length > 0) {
1675
- addToUndoStack(state.batch.reverseOps);
1676
- }
1677
- if (state.batch.ops.length > 0) {
1678
- state.redoStack = [];
1679
- }
1680
- if (state.batch.ops.length > 0) {
1681
- dispatchOps(state.batch.ops);
1682
- }
1683
- notify(state.batch.updates);
1684
- state.batch = {
1685
- ops: [],
1686
- reverseOps: [],
1687
- updates: {
1688
- others: [],
1689
- storageUpdates: /* @__PURE__ */ new Map(),
1690
- presence: false
1691
- }
1692
- };
1693
- tryFlushing();
1694
- }
1695
- };
1696
- var pauseHistory = function pauseHistory() {
1697
- state.pausedHistory = [];
1698
- state.isHistoryPaused = true;
1699
- };
1700
- var resumeHistory = function resumeHistory() {
1701
- state.isHistoryPaused = false;
1702
- if (state.pausedHistory.length > 0) {
1703
- addToUndoStack(state.pausedHistory);
1704
- }
1705
- state.pausedHistory = [];
1706
- };
1707
- var simulateSocketClose = function simulateSocketClose() {
1708
- if (state.socket) {
1709
- state.socket = null;
1710
- }
1711
- };
1712
- var simulateSendCloseEvent = function simulateSendCloseEvent(event) {
1713
- onClose(event);
1714
- };
1715
- var pool = {
1716
- roomId: config.roomId,
1717
- getNode: function(id) {
1718
- return state.nodes.get(id);
1719
- },
1720
- addNode: function(id, node) {
1721
- return void state.nodes.set(id, node);
1722
- },
1723
- deleteNode: function(id) {
1724
- return void state.nodes.delete(id);
1725
- },
1726
- generateId: function() {
1727
- return "".concat(getConnectionId(), ":").concat(state.clock++);
1728
- },
1729
- generateOpId: function() {
1730
- return "".concat(getConnectionId(), ":").concat(state.opClock++);
1731
- },
1732
- dispatch: function dispatch(ops, reverse, storageUpdates) {
1733
- if (state.isBatching) {
1734
- var _ops, _reverseOps;
1735
- (_ops = state.batch.ops).push.apply(_ops, _toConsumableArray(ops));
1736
- storageUpdates.forEach(function(value, key) {
1737
- state.batch.updates.storageUpdates.set(key, _chunkZNCSOBAXjs.mergeStorageUpdates.call(void 0, state.batch.updates.storageUpdates.get(key), value));
1738
- });
1739
- (_reverseOps = state.batch.reverseOps).push.apply(_reverseOps, _toConsumableArray(reverse));
1740
- } else {
1741
- addToUndoStack(reverse);
1742
- state.redoStack = [];
1743
- dispatchOps(ops);
1744
- notify({
1745
- storageUpdates: storageUpdates
1746
- });
1747
- }
1748
- }
1749
- };
1750
- var eventHub = {
1751
- customEvent: makeEventSource(),
1752
- me: makeEventSource(),
1753
- others: makeEventSource(),
1754
- error: makeEventSource(),
1755
- connection: makeEventSource(),
1756
- storage: makeEventSource(),
1757
- history: makeEventSource(),
1758
- storageDidLoad: makeEventSource()
1759
- };
1760
- var effects = mockedEffects || {
1761
- authenticate: function authenticate(auth, createWebSocket) {
1762
- var rawToken = state.token;
1763
- var parsedToken = rawToken !== null && _chunkZNCSOBAXjs.parseRoomAuthToken.call(void 0, rawToken);
1764
- if (parsedToken && !_chunkZNCSOBAXjs.isTokenExpired.call(void 0, parsedToken)) {
1765
- var socket = createWebSocket(rawToken);
1766
- authenticationSuccess(parsedToken, socket);
1767
- } else {
1768
- return auth(config.roomId).then(function(param) {
1769
- var token = param.token;
1770
- if (state.connection.current.state !== "authenticating") {
1771
- return;
1772
- }
1773
- var parsedToken2 = _chunkZNCSOBAXjs.parseRoomAuthToken.call(void 0, token);
1774
- var socket = createWebSocket(token);
1775
- authenticationSuccess(parsedToken2, socket);
1776
- state.token = token;
1777
- }).catch(function(er) {
1778
- return authenticationFailure(_instanceof(er, Error) ? er : new Error(String(er)));
1779
- });
1780
- }
1781
- },
1782
- send: function send(messageOrMessages) {
1783
- if (state.socket == null) {
1784
- throw new Error("Can't send message if socket is null");
1785
- }
1786
- state.socket.send(JSON.stringify(messageOrMessages));
1787
- },
1788
- delayFlush: function delayFlush(delay) {
1789
- return setTimeout(tryFlushing, delay);
1790
- },
1791
- startHeartbeatInterval: function startHeartbeatInterval() {
1792
- return setInterval(heartbeat, HEARTBEAT_INTERVAL);
1793
- },
1794
- schedulePongTimeout: function schedulePongTimeout() {
1795
- return setTimeout(pongTimeout, PONG_TIMEOUT);
1796
- },
1797
- scheduleReconnect: function scheduleReconnect(delay) {
1798
- return setTimeout(connect, delay);
1799
- }
1800
- };
1801
- var self = new DerivedRef([
1802
- state.connection,
1803
- state.me
1804
- ], function(conn, me) {
1805
- return isConnectionSelfAware(conn) ? {
1806
- connectionId: conn.id,
1807
- id: conn.userId,
1808
- info: conn.userInfo,
1809
- presence: me
1810
- } : null;
1077
+ }
1078
+ yield startLoadingStorage();
1079
+ return {
1080
+ root: _chunkRS4TQ2LTjs.nn.call(void 0, state.root)
1081
+ };
1811
1082
  });
1812
- var _getInitialStatePromise = null;
1813
- var _getInitialStateResolver = null;
1814
- return {
1815
- onClose: onClose,
1816
- onMessage: onMessage,
1817
- authenticationSuccess: authenticationSuccess,
1818
- heartbeat: heartbeat,
1819
- onNavigatorOnline: onNavigatorOnline,
1820
- simulateSocketClose: simulateSocketClose,
1821
- simulateSendCloseEvent: simulateSendCloseEvent,
1822
- onVisibilityChange: onVisibilityChange,
1823
- getUndoStack: function() {
1824
- return state.undoStack;
1825
- },
1826
- getItemsCount: function() {
1827
- return state.nodes.size;
1828
- },
1829
- connect: connect,
1830
- disconnect: disconnect,
1831
- subscribe: subscribe,
1832
- updatePresence: updatePresence,
1833
- broadcastEvent: broadcastEvent,
1834
- batch: batch,
1835
- undo: undo,
1836
- redo: redo,
1837
- canUndo: canUndo,
1838
- canRedo: canRedo,
1839
- pauseHistory: pauseHistory,
1840
- resumeHistory: resumeHistory,
1841
- getStorage: getStorage,
1842
- getStorageSnapshot: getStorageSnapshot,
1843
- events: {
1844
- customEvent: eventHub.customEvent.observable,
1845
- others: eventHub.others.observable,
1846
- me: eventHub.me.observable,
1847
- error: eventHub.error.observable,
1848
- connection: eventHub.connection.observable,
1849
- storage: eventHub.storage.observable,
1850
- history: eventHub.history.observable,
1851
- storageDidLoad: eventHub.storageDidLoad.observable
1852
- },
1853
- getConnectionState: getConnectionState,
1854
- isSelfAware: function() {
1855
- return isConnectionSelfAware(state.connection.current);
1856
- },
1857
- getSelf: function() {
1858
- return self.current;
1859
- },
1860
- getPresence: getPresence,
1861
- getOthers: getOthers
1083
+ }
1084
+ function undo() {
1085
+ if (state.activeBatch) {
1086
+ throw new Error("undo is not allowed during a batch");
1087
+ }
1088
+ const historyItem = state.undoStack.pop();
1089
+ if (historyItem == null) {
1090
+ return;
1091
+ }
1092
+ state.isHistoryPaused = false;
1093
+ const result = apply(historyItem, true);
1094
+ notify(result.updates);
1095
+ state.redoStack.push(result.reverse);
1096
+ onHistoryChange();
1097
+ for (const op of historyItem) {
1098
+ if (op.type !== "presence") {
1099
+ state.buffer.storageOperations.push(op);
1100
+ }
1101
+ }
1102
+ tryFlushing();
1103
+ }
1104
+ function canUndo() {
1105
+ return state.undoStack.length > 0;
1106
+ }
1107
+ function redo() {
1108
+ if (state.activeBatch) {
1109
+ throw new Error("redo is not allowed during a batch");
1110
+ }
1111
+ const historyItem = state.redoStack.pop();
1112
+ if (historyItem == null) {
1113
+ return;
1114
+ }
1115
+ state.isHistoryPaused = false;
1116
+ const result = apply(historyItem, true);
1117
+ notify(result.updates);
1118
+ state.undoStack.push(result.reverse);
1119
+ onHistoryChange();
1120
+ for (const op of historyItem) {
1121
+ if (op.type !== "presence") {
1122
+ state.buffer.storageOperations.push(op);
1123
+ }
1124
+ }
1125
+ tryFlushing();
1126
+ }
1127
+ function canRedo() {
1128
+ return state.redoStack.length > 0;
1129
+ }
1130
+ function batch(callback) {
1131
+ if (state.activeBatch) {
1132
+ return callback();
1133
+ }
1134
+ state.activeBatch = {
1135
+ ops: [],
1136
+ updates: {
1137
+ storageUpdates: /* @__PURE__ */ new Map(),
1138
+ presence: false,
1139
+ others: []
1140
+ },
1141
+ reverseOps: []
1862
1142
  };
1143
+ try {
1144
+ return callback();
1145
+ } finally {
1146
+ const currentBatch = state.activeBatch;
1147
+ state.activeBatch = null;
1148
+ if (currentBatch.reverseOps.length > 0) {
1149
+ addToUndoStack(currentBatch.reverseOps);
1150
+ }
1151
+ if (currentBatch.ops.length > 0) {
1152
+ state.redoStack = [];
1153
+ }
1154
+ if (currentBatch.ops.length > 0) {
1155
+ dispatchOps(currentBatch.ops);
1156
+ }
1157
+ notify(currentBatch.updates);
1158
+ tryFlushing();
1159
+ }
1160
+ }
1161
+ function pauseHistory() {
1162
+ state.pausedHistory = [];
1163
+ state.isHistoryPaused = true;
1164
+ }
1165
+ function resumeHistory() {
1166
+ state.isHistoryPaused = false;
1167
+ if (state.pausedHistory.length > 0) {
1168
+ addToUndoStack(state.pausedHistory);
1169
+ }
1170
+ state.pausedHistory = [];
1171
+ }
1172
+ function simulateSocketClose() {
1173
+ if (state.socket) {
1174
+ state.socket = null;
1175
+ }
1176
+ }
1177
+ function simulateSendCloseEvent(event) {
1178
+ onClose(event);
1179
+ }
1180
+ return {
1181
+ onClose,
1182
+ onMessage,
1183
+ authenticationSuccess,
1184
+ heartbeat,
1185
+ onNavigatorOnline,
1186
+ simulateSocketClose,
1187
+ simulateSendCloseEvent,
1188
+ onVisibilityChange,
1189
+ getUndoStack: () => state.undoStack,
1190
+ getItemsCount: () => state.nodes.size,
1191
+ connect,
1192
+ disconnect,
1193
+ subscribe,
1194
+ updatePresence,
1195
+ broadcastEvent,
1196
+ batch,
1197
+ undo,
1198
+ redo,
1199
+ canUndo,
1200
+ canRedo,
1201
+ pauseHistory,
1202
+ resumeHistory,
1203
+ getStorage,
1204
+ getStorageSnapshot,
1205
+ events: {
1206
+ customEvent: eventHub.customEvent.observable,
1207
+ others: eventHub.others.observable,
1208
+ me: eventHub.me.observable,
1209
+ error: eventHub.error.observable,
1210
+ connection: eventHub.connection.observable,
1211
+ storage: eventHub.storage.observable,
1212
+ history: eventHub.history.observable,
1213
+ storageDidLoad: eventHub.storageDidLoad.observable
1214
+ },
1215
+ getConnectionState,
1216
+ isSelfAware: () => isConnectionSelfAware(state.connection.current),
1217
+ getSelf: () => self.current,
1218
+ getPresence,
1219
+ getOthers
1220
+ };
1863
1221
  }
1864
1222
  function defaultState(initialPresence, initialStorage) {
1865
- var others = new OthersRef();
1866
- var connection = new ValueRef({
1867
- state: "closed"
1868
- });
1869
- return {
1870
- token: null,
1871
- lastConnectionId: null,
1872
- socket: null,
1873
- numberOfRetry: 0,
1874
- lastFlushTime: 0,
1875
- timeoutHandles: {
1876
- flush: null,
1877
- reconnect: 0,
1878
- pongTimeout: 0
1879
- },
1880
- buffer: {
1881
- me: {
1882
- type: "full",
1883
- data: initialPresence
1884
- },
1885
- messages: [],
1886
- storageOperations: []
1887
- },
1888
- intervalHandles: {
1889
- heartbeat: 0
1890
- },
1891
- connection: connection,
1892
- me: new MeRef(initialPresence),
1893
- others: others,
1894
- defaultStorageRoot: initialStorage,
1895
- idFactory: null,
1896
- clock: 0,
1897
- opClock: 0,
1898
- nodes: /* @__PURE__ */ new Map(),
1899
- root: void 0,
1900
- undoStack: [],
1901
- redoStack: [],
1902
- isHistoryPaused: false,
1903
- pausedHistory: [],
1904
- isBatching: false,
1905
- batch: {
1906
- ops: [],
1907
- updates: {
1908
- storageUpdates: /* @__PURE__ */ new Map(),
1909
- presence: false,
1910
- others: []
1911
- },
1912
- reverseOps: []
1913
- },
1914
- offlineOperations: /* @__PURE__ */ new Map()
1915
- };
1223
+ const others = new OthersRef();
1224
+ const connection = new ValueRef({ state: "closed" });
1225
+ return {
1226
+ token: null,
1227
+ lastConnectionId: null,
1228
+ socket: null,
1229
+ numberOfRetry: 0,
1230
+ lastFlushTime: 0,
1231
+ timeoutHandles: {
1232
+ flush: null,
1233
+ reconnect: 0,
1234
+ pongTimeout: 0
1235
+ },
1236
+ buffer: {
1237
+ me: {
1238
+ type: "full",
1239
+ data: initialPresence
1240
+ },
1241
+ messages: [],
1242
+ storageOperations: []
1243
+ },
1244
+ intervalHandles: {
1245
+ heartbeat: 0
1246
+ },
1247
+ connection,
1248
+ me: new MeRef(initialPresence),
1249
+ others,
1250
+ defaultStorageRoot: initialStorage,
1251
+ idFactory: null,
1252
+ clock: 0,
1253
+ opClock: 0,
1254
+ nodes: /* @__PURE__ */ new Map(),
1255
+ root: void 0,
1256
+ undoStack: [],
1257
+ redoStack: [],
1258
+ isHistoryPaused: false,
1259
+ pausedHistory: [],
1260
+ activeBatch: null,
1261
+ offlineOperations: /* @__PURE__ */ new Map()
1262
+ };
1916
1263
  }
1917
1264
  function createRoom(options, config) {
1918
- var initialPresence = options.initialPresence, initialStorage = options.initialStorage;
1919
- var state = defaultState(typeof initialPresence === "function" ? initialPresence(config.roomId) : initialPresence, typeof initialStorage === "function" ? initialStorage(config.roomId) : initialStorage);
1920
- var machine = makeStateMachine(state, config);
1921
- var room = {
1922
- id: config.roomId,
1923
- getConnectionState: machine.getConnectionState,
1924
- isSelfAware: machine.isSelfAware,
1925
- getSelf: machine.getSelf,
1926
- subscribe: machine.subscribe,
1927
- getPresence: machine.getPresence,
1928
- updatePresence: machine.updatePresence,
1929
- getOthers: machine.getOthers,
1930
- broadcastEvent: machine.broadcastEvent,
1931
- getStorage: machine.getStorage,
1932
- getStorageSnapshot: machine.getStorageSnapshot,
1933
- events: machine.events,
1934
- batch: machine.batch,
1935
- history: {
1936
- undo: machine.undo,
1937
- redo: machine.redo,
1938
- canUndo: machine.canUndo,
1939
- canRedo: machine.canRedo,
1940
- pause: machine.pauseHistory,
1941
- resume: machine.resumeHistory
1942
- },
1943
- __INTERNAL_DO_NOT_USE: {
1944
- simulateCloseWebsocket: machine.simulateSocketClose,
1945
- simulateSendCloseEvent: machine.simulateSendCloseEvent
1946
- }
1947
- };
1948
- return {
1949
- connect: machine.connect,
1950
- disconnect: machine.disconnect,
1951
- onNavigatorOnline: machine.onNavigatorOnline,
1952
- onVisibilityChange: machine.onVisibilityChange,
1953
- room: room
1954
- };
1265
+ const { initialPresence, initialStorage } = options;
1266
+ const state = defaultState(
1267
+ typeof initialPresence === "function" ? initialPresence(config.roomId) : initialPresence,
1268
+ typeof initialStorage === "function" ? initialStorage(config.roomId) : initialStorage
1269
+ );
1270
+ const machine = makeStateMachine(
1271
+ state,
1272
+ config
1273
+ );
1274
+ const room = {
1275
+ id: config.roomId,
1276
+ getConnectionState: machine.getConnectionState,
1277
+ isSelfAware: machine.isSelfAware,
1278
+ getSelf: machine.getSelf,
1279
+ subscribe: machine.subscribe,
1280
+ getPresence: machine.getPresence,
1281
+ updatePresence: machine.updatePresence,
1282
+ getOthers: machine.getOthers,
1283
+ broadcastEvent: machine.broadcastEvent,
1284
+ getStorage: machine.getStorage,
1285
+ getStorageSnapshot: machine.getStorageSnapshot,
1286
+ events: machine.events,
1287
+ batch: machine.batch,
1288
+ history: {
1289
+ undo: machine.undo,
1290
+ redo: machine.redo,
1291
+ canUndo: machine.canUndo,
1292
+ canRedo: machine.canRedo,
1293
+ pause: machine.pauseHistory,
1294
+ resume: machine.resumeHistory
1295
+ },
1296
+ __INTERNAL_DO_NOT_USE: {
1297
+ simulateCloseWebsocket: machine.simulateSocketClose,
1298
+ simulateSendCloseEvent: machine.simulateSendCloseEvent
1299
+ }
1300
+ };
1301
+ return {
1302
+ connect: machine.connect,
1303
+ disconnect: machine.disconnect,
1304
+ onNavigatorOnline: machine.onNavigatorOnline,
1305
+ onVisibilityChange: machine.onVisibilityChange,
1306
+ room
1307
+ };
1955
1308
  }
1956
- var LiveblocksError = /*#__PURE__*/ function(Error1) {
1957
- _inherits(LiveblocksError, Error1);
1958
- var _super = _createSuper(LiveblocksError);
1959
- function LiveblocksError(message, code) {
1960
- _classCallCheck(this, LiveblocksError);
1961
- var _this;
1962
- _this = _super.call(this, message);
1963
- _this.code = code;
1964
- return _this;
1965
- }
1966
- return LiveblocksError;
1967
- }(_wrapNativeSuper(Error));
1309
+ var LiveblocksError = class extends Error {
1310
+ constructor(message, code) {
1311
+ super(message);
1312
+ this.code = code;
1313
+ }
1314
+ };
1968
1315
  function prepareCreateWebSocket(liveblocksServer, WebSocketPolyfill) {
1969
- if (typeof window === "undefined" && WebSocketPolyfill == null) {
1970
- throw new Error("To use Liveblocks client in a non-dom environment, you need to provide a WebSocket polyfill.");
1971
- }
1972
- var ws = WebSocketPolyfill || WebSocket;
1973
- return function(token) {
1974
- return new ws("".concat(liveblocksServer, "/?token=").concat(token, "&version=").concat(true ? "0.18.0-beta1" : "dev"));
1975
- };
1316
+ if (typeof window === "undefined" && WebSocketPolyfill == null) {
1317
+ throw new Error(
1318
+ "To use Liveblocks client in a non-dom environment, you need to provide a WebSocket polyfill."
1319
+ );
1320
+ }
1321
+ const ws = WebSocketPolyfill || WebSocket;
1322
+ return (token) => {
1323
+ return new ws(
1324
+ `${liveblocksServer}/?token=${token}&version=${true ? "0.18.0-beta2" : "dev"}`
1325
+ );
1326
+ };
1976
1327
  }
1977
1328
  function prepareAuthEndpoint(authentication, fetchPolyfill) {
1978
- if (authentication.type === "public") {
1979
- if (typeof window === "undefined" && fetchPolyfill == null) {
1980
- throw new Error("To use Liveblocks client in a non-dom environment with a publicApiKey, you need to provide a fetch polyfill.");
1981
- }
1982
- return function(room) {
1983
- return fetchAuthEndpoint(fetchPolyfill || fetch, authentication.url, {
1984
- room: room,
1985
- publicApiKey: authentication.publicApiKey
1986
- });
1987
- };
1329
+ if (authentication.type === "public") {
1330
+ if (typeof window === "undefined" && fetchPolyfill == null) {
1331
+ throw new Error(
1332
+ "To use Liveblocks client in a non-dom environment with a publicApiKey, you need to provide a fetch polyfill."
1333
+ );
1988
1334
  }
1989
- if (authentication.type === "private") {
1990
- if (typeof window === "undefined" && fetchPolyfill == null) {
1991
- throw new Error("To use Liveblocks client in a non-dom environment with a url as auth endpoint, you need to provide a fetch polyfill.");
1992
- }
1993
- return function(room) {
1994
- return fetchAuthEndpoint(fetchPolyfill || fetch, authentication.url, {
1995
- room: room
1996
- });
1997
- };
1998
- }
1999
- if (authentication.type === "custom") {
2000
- var authWithResponseValidation = function(room) {
2001
- return authentication.callback(room).then(function(response) {
2002
- if (!response || !response.token) {
2003
- throw new Error('Authentication error. We expect the authentication callback to return a token, but it does not. Hint: the return value should look like: { token: "..." }');
2004
- }
2005
- return response;
2006
- });
2007
- };
2008
- return authWithResponseValidation;
1335
+ return (room) => fetchAuthEndpoint(fetchPolyfill || fetch, authentication.url, {
1336
+ room,
1337
+ publicApiKey: authentication.publicApiKey
1338
+ });
1339
+ }
1340
+ if (authentication.type === "private") {
1341
+ if (typeof window === "undefined" && fetchPolyfill == null) {
1342
+ throw new Error(
1343
+ "To use Liveblocks client in a non-dom environment with a url as auth endpoint, you need to provide a fetch polyfill."
1344
+ );
2009
1345
  }
2010
- throw new Error("Internal error. Unexpected authentication type");
1346
+ return (room) => fetchAuthEndpoint(fetchPolyfill || fetch, authentication.url, {
1347
+ room
1348
+ });
1349
+ }
1350
+ if (authentication.type === "custom") {
1351
+ return (room) => _chunkRS4TQ2LTjs.__async.call(void 0, this, null, function* () {
1352
+ const response = yield authentication.callback(room);
1353
+ if (!response || !response.token) {
1354
+ throw new Error(
1355
+ 'Authentication error. We expect the authentication callback to return a token, but it does not. Hint: the return value should look like: { token: "..." }'
1356
+ );
1357
+ }
1358
+ return response;
1359
+ });
1360
+ }
1361
+ throw new Error("Internal error. Unexpected authentication type");
2011
1362
  }
2012
1363
  function fetchAuthEndpoint(fetch2, endpoint, body) {
2013
- return fetch2(endpoint, {
2014
- method: "POST",
2015
- headers: {
2016
- "Content-Type": "application/json"
2017
- },
2018
- body: JSON.stringify(body)
2019
- }).then(function(res) {
2020
- if (!res.ok) {
2021
- throw new AuthenticationError("Expected a status 200 but got ".concat(res.status, ' when doing a POST request on "').concat(endpoint, '"'));
2022
- }
2023
- return res.json().catch(function(er) {
2024
- throw new AuthenticationError('Expected a JSON response when doing a POST request on "'.concat(endpoint, '". ').concat(er));
2025
- });
2026
- }).then(function(data) {
2027
- if (!_chunkZNCSOBAXjs.isPlainObject.call(void 0, data) || typeof data.token !== "string") {
2028
- throw new AuthenticationError('Expected a JSON response of the form `{ token: "..." }` when doing a POST request on "'.concat(endpoint, '", but got ').concat(JSON.stringify(data)));
2029
- }
2030
- var token = data.token;
2031
- return {
2032
- token: token
2033
- };
1364
+ return _chunkRS4TQ2LTjs.__async.call(void 0, this, null, function* () {
1365
+ const res = yield fetch2(endpoint, {
1366
+ method: "POST",
1367
+ headers: {
1368
+ "Content-Type": "application/json"
1369
+ },
1370
+ body: JSON.stringify(body)
2034
1371
  });
1372
+ if (!res.ok) {
1373
+ throw new AuthenticationError(
1374
+ `Expected a status 200 but got ${res.status} when doing a POST request on "${endpoint}"`
1375
+ );
1376
+ }
1377
+ let data;
1378
+ try {
1379
+ data = yield res.json();
1380
+ } catch (er) {
1381
+ throw new AuthenticationError(
1382
+ `Expected a JSON response when doing a POST request on "${endpoint}". ${er}`
1383
+ );
1384
+ }
1385
+ if (!_chunkRS4TQ2LTjs.isPlainObject.call(void 0, data) || typeof data.token !== "string") {
1386
+ throw new AuthenticationError(
1387
+ `Expected a JSON response of the form \`{ token: "..." }\` when doing a POST request on "${endpoint}", but got ${JSON.stringify(
1388
+ data
1389
+ )}`
1390
+ );
1391
+ }
1392
+ const { token } = data;
1393
+ return { token };
1394
+ });
2035
1395
  }
2036
- var AuthenticationError = /*#__PURE__*/ function(Error1) {
2037
- _inherits(AuthenticationError, Error1);
2038
- var _super = _createSuper(AuthenticationError);
2039
- function AuthenticationError(message) {
2040
- _classCallCheck(this, AuthenticationError);
2041
- return _super.call(this, message);
2042
- }
2043
- return AuthenticationError;
2044
- }(_wrapNativeSuper(Error));
1396
+ var AuthenticationError = class extends Error {
1397
+ constructor(message) {
1398
+ super(message);
1399
+ }
1400
+ };
1401
+
2045
1402
  // src/client.ts
2046
1403
  function createClient(options) {
2047
- var getRoom = function getRoom(roomId) {
2048
- var internalRoom = rooms.get(roomId);
2049
- return internalRoom ? internalRoom.room : null;
2050
- };
2051
- var enter = function enter(roomId, options2) {
2052
- var internalRoom = rooms.get(roomId);
2053
- if (internalRoom) {
2054
- return internalRoom.room;
2055
- }
2056
- _chunkZNCSOBAXjs.deprecateIf.call(void 0, options2.initialPresence == null, "Please provide an initial presence value for the current user when entering the room.");
2057
- internalRoom = createRoom({
2058
- initialPresence: _nullishCoalesce(options2.initialPresence, function() {
2059
- return {};
2060
- }),
2061
- initialStorage: options2.initialStorage
2062
- }, {
2063
- roomId: roomId,
2064
- throttleDelay: throttleDelay,
2065
- polyfills: clientOptions.polyfills,
2066
- WebSocketPolyfill: clientOptions.WebSocketPolyfill,
2067
- fetchPolyfill: clientOptions.fetchPolyfill,
2068
- liveblocksServer: _optionalChain([
2069
- clientOptions,
2070
- "optionalAccess",
2071
- function(_9) {
2072
- return _9.liveblocksServer;
2073
- }
2074
- ]) || "wss://api.liveblocks.io/v6",
2075
- authentication: prepareAuthentication(clientOptions, roomId)
2076
- });
2077
- rooms.set(roomId, internalRoom);
2078
- if (!options2.DO_NOT_USE_withoutConnecting) {
2079
- if (typeof atob == "undefined") {
2080
- if (_optionalChain([
2081
- clientOptions,
2082
- "access",
2083
- function(_10) {
2084
- return _10.polyfills;
2085
- },
2086
- "optionalAccess",
2087
- function(_11) {
2088
- return _11.atob;
2089
- }
2090
- ]) == void 0) {
2091
- throw new Error("You need to polyfill atob to use the client in your environment. Please follow the instructions at https://liveblocks.io/docs/errors/liveblocks-client/atob-polyfill");
2092
- }
2093
- global.atob = clientOptions.polyfills.atob;
2094
- }
2095
- internalRoom.connect();
2096
- }
2097
- return internalRoom.room;
2098
- };
2099
- var leave = function leave(roomId) {
2100
- var room = rooms.get(roomId);
2101
- if (room) {
2102
- room.disconnect();
2103
- rooms.delete(roomId);
2104
- }
2105
- };
2106
- var clientOptions = options;
2107
- var throttleDelay = getThrottleDelayFromOptions(options);
2108
- var rooms = /* @__PURE__ */ new Map();
2109
- if (typeof window !== "undefined" && typeof window.addEventListener !== "undefined") {
2110
- window.addEventListener("online", function() {
2111
- var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
2112
- try {
2113
- for(var _iterator = rooms[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
2114
- var _value = _slicedToArray(_step.value, 2), room = _value[1];
2115
- room.onNavigatorOnline();
2116
- }
2117
- } catch (err) {
2118
- _didIteratorError = true;
2119
- _iteratorError = err;
2120
- } finally{
2121
- try {
2122
- if (!_iteratorNormalCompletion && _iterator.return != null) {
2123
- _iterator.return();
2124
- }
2125
- } finally{
2126
- if (_didIteratorError) {
2127
- throw _iteratorError;
2128
- }
2129
- }
2130
- }
2131
- });
1404
+ const clientOptions = options;
1405
+ const throttleDelay = getThrottleDelayFromOptions(options);
1406
+ const rooms = /* @__PURE__ */ new Map();
1407
+ function getRoom(roomId) {
1408
+ const internalRoom = rooms.get(roomId);
1409
+ return internalRoom ? internalRoom.room : null;
1410
+ }
1411
+ function enter(roomId, options2) {
1412
+ var _a, _b;
1413
+ let internalRoom = rooms.get(roomId);
1414
+ if (internalRoom) {
1415
+ return internalRoom.room;
2132
1416
  }
2133
- if (typeof document !== "undefined") {
2134
- document.addEventListener("visibilitychange", function() {
2135
- var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
2136
- try {
2137
- for(var _iterator = rooms[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
2138
- var _value = _slicedToArray(_step.value, 2), room = _value[1];
2139
- room.onVisibilityChange(document.visibilityState);
2140
- }
2141
- } catch (err) {
2142
- _didIteratorError = true;
2143
- _iteratorError = err;
2144
- } finally{
2145
- try {
2146
- if (!_iteratorNormalCompletion && _iterator.return != null) {
2147
- _iterator.return();
2148
- }
2149
- } finally{
2150
- if (_didIteratorError) {
2151
- throw _iteratorError;
2152
- }
2153
- }
2154
- }
2155
- });
1417
+ _chunkRS4TQ2LTjs.deprecateIf.call(void 0,
1418
+ options2.initialPresence == null,
1419
+ "Please provide an initial presence value for the current user when entering the room."
1420
+ );
1421
+ internalRoom = createRoom(
1422
+ {
1423
+ initialPresence: (_a = options2.initialPresence) != null ? _a : {},
1424
+ initialStorage: options2.initialStorage
1425
+ },
1426
+ {
1427
+ roomId,
1428
+ throttleDelay,
1429
+ polyfills: clientOptions.polyfills,
1430
+ WebSocketPolyfill: clientOptions.WebSocketPolyfill,
1431
+ fetchPolyfill: clientOptions.fetchPolyfill,
1432
+ liveblocksServer: (clientOptions == null ? void 0 : clientOptions.liveblocksServer) || "wss://api.liveblocks.io/v6",
1433
+ authentication: prepareAuthentication(clientOptions, roomId)
1434
+ }
1435
+ );
1436
+ rooms.set(
1437
+ roomId,
1438
+ internalRoom
1439
+ );
1440
+ if (!options2.DO_NOT_USE_withoutConnecting) {
1441
+ if (typeof atob == "undefined") {
1442
+ if (((_b = clientOptions.polyfills) == null ? void 0 : _b.atob) == void 0) {
1443
+ throw new Error(
1444
+ "You need to polyfill atob to use the client in your environment. Please follow the instructions at https://liveblocks.io/docs/errors/liveblocks-client/atob-polyfill"
1445
+ );
1446
+ }
1447
+ global.atob = clientOptions.polyfills.atob;
1448
+ }
1449
+ internalRoom.connect();
2156
1450
  }
2157
- return {
2158
- getRoom: getRoom,
2159
- enter: enter,
2160
- leave: leave
2161
- };
1451
+ return internalRoom.room;
1452
+ }
1453
+ function leave(roomId) {
1454
+ const room = rooms.get(roomId);
1455
+ if (room) {
1456
+ room.disconnect();
1457
+ rooms.delete(roomId);
1458
+ }
1459
+ }
1460
+ if (typeof window !== "undefined" && typeof window.addEventListener !== "undefined") {
1461
+ window.addEventListener("online", () => {
1462
+ for (const [, room] of rooms) {
1463
+ room.onNavigatorOnline();
1464
+ }
1465
+ });
1466
+ }
1467
+ if (typeof document !== "undefined") {
1468
+ document.addEventListener("visibilitychange", () => {
1469
+ for (const [, room] of rooms) {
1470
+ room.onVisibilityChange(document.visibilityState);
1471
+ }
1472
+ });
1473
+ }
1474
+ return {
1475
+ getRoom,
1476
+ enter,
1477
+ leave
1478
+ };
2162
1479
  }
2163
1480
  function getThrottleDelayFromOptions(options) {
2164
- if (options.throttle === void 0) {
2165
- return 100;
2166
- }
2167
- if (typeof options.throttle !== "number" || options.throttle < 80 || options.throttle > 1e3) {
2168
- throw new Error("throttle should be a number between 80 and 1000.");
2169
- }
2170
- return options.throttle;
1481
+ if (options.throttle === void 0) {
1482
+ return 100;
1483
+ }
1484
+ if (typeof options.throttle !== "number" || options.throttle < 80 || options.throttle > 1e3) {
1485
+ throw new Error("throttle should be a number between 80 and 1000.");
1486
+ }
1487
+ return options.throttle;
2171
1488
  }
2172
1489
  function prepareAuthentication(clientOptions, roomId) {
2173
- var publicApiKey = clientOptions.publicApiKey, authEndpoint = clientOptions.authEndpoint;
2174
- if (authEndpoint !== void 0 && publicApiKey !== void 0) {
2175
- throw new Error("You cannot use both publicApiKey and authEndpoint. Please use either publicApiKey or authEndpoint, but not both. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClient");
2176
- }
2177
- if (typeof publicApiKey === "string") {
2178
- if (publicApiKey.startsWith("sk_")) {
2179
- throw new Error("Invalid publicApiKey. You are using the secret key which is not supported. Please use the public key instead. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClientPublicKey");
2180
- } else if (!publicApiKey.startsWith("pk_")) {
2181
- throw new Error("Invalid key. Please use the public key format: pk_<public key>. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClientPublicKey");
2182
- }
2183
- return {
2184
- type: "public",
2185
- publicApiKey: publicApiKey,
2186
- url: buildLiveblocksPublicAuthorizeEndpoint(clientOptions, roomId)
2187
- };
2188
- }
2189
- if (typeof authEndpoint === "string") {
2190
- return {
2191
- type: "private",
2192
- url: authEndpoint
2193
- };
2194
- } else if (typeof authEndpoint === "function") {
2195
- return {
2196
- type: "custom",
2197
- callback: authEndpoint
2198
- };
2199
- } else if (authEndpoint !== void 0) {
2200
- throw new Error("authEndpoint must be a string or a function. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClientAuthEndpoint");
1490
+ const { publicApiKey, authEndpoint } = clientOptions;
1491
+ if (authEndpoint !== void 0 && publicApiKey !== void 0) {
1492
+ throw new Error(
1493
+ "You cannot use both publicApiKey and authEndpoint. Please use either publicApiKey or authEndpoint, but not both. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClient"
1494
+ );
1495
+ }
1496
+ if (typeof publicApiKey === "string") {
1497
+ if (publicApiKey.startsWith("sk_")) {
1498
+ throw new Error(
1499
+ "Invalid publicApiKey. You are using the secret key which is not supported. Please use the public key instead. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClientPublicKey"
1500
+ );
1501
+ } else if (!publicApiKey.startsWith("pk_")) {
1502
+ throw new Error(
1503
+ "Invalid key. Please use the public key format: pk_<public key>. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClientPublicKey"
1504
+ );
2201
1505
  }
2202
- throw new Error("Invalid Liveblocks client options. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClient");
1506
+ return {
1507
+ type: "public",
1508
+ publicApiKey,
1509
+ url: buildLiveblocksPublicAuthorizeEndpoint(clientOptions, roomId)
1510
+ };
1511
+ }
1512
+ if (typeof authEndpoint === "string") {
1513
+ return {
1514
+ type: "private",
1515
+ url: authEndpoint
1516
+ };
1517
+ } else if (typeof authEndpoint === "function") {
1518
+ return {
1519
+ type: "custom",
1520
+ callback: authEndpoint
1521
+ };
1522
+ } else if (authEndpoint !== void 0) {
1523
+ throw new Error(
1524
+ "authEndpoint must be a string or a function. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClientAuthEndpoint"
1525
+ );
1526
+ }
1527
+ throw new Error(
1528
+ "Invalid Liveblocks client options. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClient"
1529
+ );
2203
1530
  }
2204
1531
  function buildLiveblocksPublicAuthorizeEndpoint(options, roomId) {
2205
- if (options.publicAuthorizeEndpoint) {
2206
- return options.publicAuthorizeEndpoint.replace("{roomId}", roomId);
2207
- }
2208
- return "https://api.liveblocks.io/v2/rooms/".concat(encodeURIComponent(roomId), "/public/authorize");
1532
+ if (options.publicAuthorizeEndpoint) {
1533
+ return options.publicAuthorizeEndpoint.replace("{roomId}", roomId);
1534
+ }
1535
+ return `https://api.liveblocks.io/v2/rooms/${encodeURIComponent(
1536
+ roomId
1537
+ )}/public/authorize`;
2209
1538
  }
1539
+
2210
1540
  // src/shallow.ts
2211
1541
  function shallowArray(xs, ys) {
2212
- if (xs.length !== ys.length) {
2213
- return false;
2214
- }
2215
- for(var i = 0; i < xs.length; i++){
2216
- if (!Object.is(xs[i], ys[i])) {
2217
- return false;
2218
- }
1542
+ if (xs.length !== ys.length) {
1543
+ return false;
1544
+ }
1545
+ for (let i = 0; i < xs.length; i++) {
1546
+ if (!Object.is(xs[i], ys[i])) {
1547
+ return false;
2219
1548
  }
2220
- return true;
1549
+ }
1550
+ return true;
2221
1551
  }
2222
1552
  function shallowObj(objA, objB) {
2223
- if (typeof objA !== "object" || objA === null || typeof objB !== "object" || objB === null || Object.prototype.toString.call(objA) !== "[object Object]" || Object.prototype.toString.call(objB) !== "[object Object]") {
2224
- return false;
2225
- }
2226
- var keysA = Object.keys(objA);
2227
- if (keysA.length !== Object.keys(objB).length) {
2228
- return false;
2229
- }
2230
- return keysA.every(function(key) {
2231
- return Object.prototype.hasOwnProperty.call(objB, key) && Object.is(objA[key], objB[key]);
2232
- });
1553
+ if (typeof objA !== "object" || objA === null || typeof objB !== "object" || objB === null || Object.prototype.toString.call(objA) !== "[object Object]" || Object.prototype.toString.call(objB) !== "[object Object]") {
1554
+ return false;
1555
+ }
1556
+ const keysA = Object.keys(objA);
1557
+ if (keysA.length !== Object.keys(objB).length) {
1558
+ return false;
1559
+ }
1560
+ return keysA.every(
1561
+ (key) => Object.prototype.hasOwnProperty.call(objB, key) && Object.is(objA[key], objB[key])
1562
+ );
2233
1563
  }
2234
1564
  function shallow(a, b) {
2235
- if (Object.is(a, b)) {
2236
- return true;
2237
- }
2238
- var isArrayA = Array.isArray(a);
2239
- var isArrayB = Array.isArray(b);
2240
- if (isArrayA || isArrayB) {
2241
- if (!isArrayA || !isArrayB) {
2242
- return false;
2243
- }
2244
- return shallowArray(a, b);
1565
+ if (Object.is(a, b)) {
1566
+ return true;
1567
+ }
1568
+ const isArrayA = Array.isArray(a);
1569
+ const isArrayB = Array.isArray(b);
1570
+ if (isArrayA || isArrayB) {
1571
+ if (!isArrayA || !isArrayB) {
1572
+ return false;
2245
1573
  }
2246
- return shallowObj(a, b);
1574
+ return shallowArray(a, b);
1575
+ }
1576
+ return shallowObj(a, b);
2247
1577
  }
2248
- exports.LiveList = _chunkZNCSOBAXjs.LiveList;
2249
- exports.LiveMap = _chunkZNCSOBAXjs.LiveMap;
2250
- exports.LiveObject = _chunkZNCSOBAXjs.LiveObject;
2251
- exports.createClient = createClient;
2252
- exports.shallow = shallow;
1578
+
1579
+
1580
+
1581
+
1582
+
1583
+
1584
+ exports.LiveList = _chunkRS4TQ2LTjs.LiveList; exports.LiveMap = _chunkRS4TQ2LTjs.LiveMap; exports.LiveObject = _chunkRS4TQ2LTjs.LiveObject; exports.createClient = createClient; exports.shallow = shallow;