@liveblocks/client 0.17.8 → 0.17.10-debug2

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