@liveblocks/client 0.17.11 → 0.18.0-beta2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -1,2057 +1,1584 @@
1
- "use strict";
2
- function _arrayLikeToArray(arr, len) {
3
- if (len == null || len > arr.length) len = arr.length;
4
- for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
5
- return arr2;
6
- }
7
- function _arrayWithHoles(arr) {
8
- if (Array.isArray(arr)) return arr;
9
- }
10
- function _arrayWithoutHoles(arr) {
11
- if (Array.isArray(arr)) return _arrayLikeToArray(arr);
12
- }
13
- function _assertThisInitialized(self) {
14
- if (self === void 0) {
15
- throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+
10
+
11
+
12
+
13
+
14
+
15
+
16
+
17
+
18
+
19
+
20
+
21
+
22
+
23
+
24
+
25
+
26
+
27
+
28
+ var _chunkRS4TQ2LTjs = require('./chunk-RS4TQ2LT.js');
29
+
30
+ // src/EventSource.ts
31
+ function makeEventSource() {
32
+ const _onetimeObservers = /* @__PURE__ */ new Set();
33
+ const _observers = /* @__PURE__ */ new Set();
34
+ function subscribe(callback) {
35
+ _observers.add(callback);
36
+ return () => _observers.delete(callback);
37
+ }
38
+ function subscribeOnce(callback) {
39
+ _onetimeObservers.add(callback);
40
+ return () => _onetimeObservers.delete(callback);
41
+ }
42
+ function notify(event) {
43
+ _onetimeObservers.forEach((callback) => callback(event));
44
+ _onetimeObservers.clear();
45
+ _observers.forEach((callback) => callback(event));
46
+ }
47
+ function clear() {
48
+ _onetimeObservers.clear();
49
+ _observers.clear();
50
+ }
51
+ return {
52
+ notify,
53
+ subscribe,
54
+ subscribeOnce,
55
+ clear,
56
+ observable: {
57
+ subscribe,
58
+ subscribeOnce
16
59
  }
17
- return self;
60
+ };
18
61
  }
19
- function _classCallCheck(instance, Constructor) {
20
- if (!(instance instanceof Constructor)) {
21
- throw new TypeError("Cannot call a class as a function");
62
+
63
+ // src/ImmutableRef.ts
64
+ function merge(target, patch) {
65
+ let updated = false;
66
+ const newValue = _chunkRS4TQ2LTjs.__spreadValues.call(void 0, {}, target);
67
+ Object.keys(patch).forEach((k) => {
68
+ const key = k;
69
+ const val = patch[key];
70
+ if (newValue[key] !== val) {
71
+ if (val === void 0) {
72
+ delete newValue[key];
73
+ } else {
74
+ newValue[key] = val;
75
+ }
76
+ updated = true;
22
77
  }
78
+ });
79
+ return updated ? newValue : target;
23
80
  }
24
- function isNativeReflectConstruct() {
25
- if (typeof Reflect === "undefined" || !Reflect.construct) return false;
26
- if (Reflect.construct.sham) return false;
27
- if (typeof Proxy === "function") return true;
28
- try {
29
- Date.prototype.toString.call(Reflect.construct(Date, [], function() {}));
30
- return true;
31
- } catch (e) {
32
- return false;
81
+ var ImmutableRef = class {
82
+ constructor() {
83
+ this._ev = makeEventSource();
84
+ }
85
+ get didInvalidate() {
86
+ return this._ev.observable;
87
+ }
88
+ invalidate() {
89
+ if (this._cache !== void 0) {
90
+ this._cache = void 0;
91
+ this._ev.notify();
33
92
  }
34
- }
35
- function _construct(Parent, args, Class) {
36
- if (isNativeReflectConstruct()) {
37
- _construct = Reflect.construct;
38
- } else {
39
- _construct = function _construct(Parent, args, Class) {
40
- var a = [
41
- null
42
- ];
43
- a.push.apply(a, args);
44
- var Constructor = Function.bind.apply(Parent, a);
45
- var instance = new Constructor();
46
- if (Class) _setPrototypeOf(instance, Class.prototype);
47
- return instance;
48
- };
93
+ }
94
+ get current() {
95
+ var _a;
96
+ return (_a = this._cache) != null ? _a : this._cache = this._toImmutable();
97
+ }
98
+ };
99
+
100
+ // src/MeRef.ts
101
+ var MeRef = class extends ImmutableRef {
102
+ constructor(initialPresence) {
103
+ super();
104
+ this._me = _chunkRS4TQ2LTjs.freeze.call(void 0, _chunkRS4TQ2LTjs.compactObject.call(void 0, initialPresence));
105
+ }
106
+ _toImmutable() {
107
+ return this._me;
108
+ }
109
+ patch(patch) {
110
+ const oldMe = this._me;
111
+ const newMe = merge(oldMe, patch);
112
+ if (oldMe !== newMe) {
113
+ this._me = _chunkRS4TQ2LTjs.freeze.call(void 0, newMe);
114
+ this.invalidate();
49
115
  }
50
- return _construct.apply(null, arguments);
116
+ }
117
+ };
118
+
119
+ // src/OthersRef.ts
120
+ function makeUser(conn, presence) {
121
+ return _chunkRS4TQ2LTjs.freeze.call(void 0, _chunkRS4TQ2LTjs.compactObject.call(void 0, _chunkRS4TQ2LTjs.__spreadProps.call(void 0, _chunkRS4TQ2LTjs.__spreadValues.call(void 0, {}, conn), { presence })));
51
122
  }
52
- function _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;
123
+ var OthersRef = class extends ImmutableRef {
124
+ constructor() {
125
+ super();
126
+ this._connections = {};
127
+ this._presences = {};
128
+ this._users = {};
129
+ }
130
+ _toImmutable() {
131
+ const users = _chunkRS4TQ2LTjs.compact.call(void 0,
132
+ Object.keys(this._presences).map(
133
+ (connectionId) => this.getUser(Number(connectionId))
134
+ )
135
+ );
136
+ return _chunkRS4TQ2LTjs.asArrayWithLegacyMethods.call(void 0, users);
137
+ }
138
+ clearOthers() {
139
+ this._connections = {};
140
+ this._presences = {};
141
+ this._users = {};
142
+ this.invalidate();
143
+ }
144
+ _getUser(connectionId) {
145
+ const conn = this._connections[connectionId];
146
+ const presence = this._presences[connectionId];
147
+ if (conn !== void 0 && presence !== void 0) {
148
+ return makeUser(conn, presence);
62
149
  }
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
- }
150
+ return void 0;
151
+ }
152
+ getUser(connectionId) {
153
+ const cachedUser = this._users[connectionId];
154
+ if (cachedUser) {
155
+ return cachedUser;
156
+ }
157
+ const computedUser = this._getUser(connectionId);
158
+ if (computedUser) {
159
+ this._users[connectionId] = computedUser;
160
+ return computedUser;
161
+ }
162
+ return void 0;
163
+ }
164
+ _invalidateUser(connectionId) {
165
+ if (this._users[connectionId] !== void 0) {
166
+ delete this._users[connectionId];
167
+ }
168
+ this.invalidate();
169
+ }
170
+ setConnection(connectionId, metaUserId, metaUserInfo) {
171
+ this._connections[connectionId] = _chunkRS4TQ2LTjs.freeze.call(void 0, {
172
+ connectionId,
173
+ id: metaUserId,
174
+ info: metaUserInfo
81
175
  });
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;
176
+ if (this._presences[connectionId] !== void 0) {
177
+ this._invalidateUser(connectionId);
89
178
  }
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
- }
179
+ }
180
+ removeConnection(connectionId) {
181
+ delete this._connections[connectionId];
182
+ delete this._presences[connectionId];
183
+ this._invalidateUser(connectionId);
184
+ }
185
+ setOther(connectionId, presence) {
186
+ this._presences[connectionId] = _chunkRS4TQ2LTjs.freeze.call(void 0, _chunkRS4TQ2LTjs.compactObject.call(void 0, presence));
187
+ if (this._connections[connectionId] !== void 0) {
188
+ this._invalidateUser(connectionId);
189
+ }
190
+ }
191
+ patchOther(connectionId, patch) {
192
+ const oldPresence = this._presences[connectionId];
193
+ if (oldPresence === void 0) {
194
+ return;
118
195
  }
119
- return _arr;
196
+ const newPresence = merge(oldPresence, patch);
197
+ if (oldPresence !== newPresence) {
198
+ this._presences[connectionId] = _chunkRS4TQ2LTjs.freeze.call(void 0, newPresence);
199
+ this._invalidateUser(connectionId);
200
+ }
201
+ }
202
+ };
203
+
204
+ // src/ValueRef.ts
205
+ var ValueRef = class extends ImmutableRef {
206
+ constructor(initialValue) {
207
+ super();
208
+ this._value = _chunkRS4TQ2LTjs.freeze.call(void 0, _chunkRS4TQ2LTjs.compactObject.call(void 0, initialValue));
209
+ }
210
+ _toImmutable() {
211
+ return this._value;
212
+ }
213
+ set(newValue) {
214
+ this._value = _chunkRS4TQ2LTjs.freeze.call(void 0, newValue);
215
+ this.invalidate();
216
+ }
217
+ };
218
+ var DerivedRef = class extends ImmutableRef {
219
+ constructor(otherRefs, transformFn) {
220
+ super();
221
+ this._refs = otherRefs;
222
+ this._refs.forEach((ref) => {
223
+ ref.didInvalidate.subscribe(() => this.invalidate());
224
+ });
225
+ this._transform = transformFn;
226
+ }
227
+ _toImmutable() {
228
+ return this._transform(this._refs[0].current, this._refs[1].current);
229
+ }
230
+ };
231
+
232
+ // src/room.ts
233
+ var BACKOFF_RETRY_DELAYS = [250, 500, 1e3, 2e3, 4e3, 8e3, 1e4];
234
+ var BACKOFF_RETRY_DELAYS_SLOW = [2e3, 3e4, 6e4, 3e5];
235
+ var HEARTBEAT_INTERVAL = 3e4;
236
+ var PONG_TIMEOUT = 2e3;
237
+ function makeIdFactory(connectionId) {
238
+ let count = 0;
239
+ return () => `${connectionId}:${count++}`;
120
240
  }
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.");
241
+ function log(..._params) {
242
+ return;
123
243
  }
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.");
244
+ function isConnectionSelfAware(connection) {
245
+ return connection.state === "open" || connection.state === "connecting";
126
246
  }
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]);
247
+ function makeStateMachine(state, config, mockedEffects) {
248
+ const pool = {
249
+ roomId: config.roomId,
250
+ getNode: (id) => state.nodes.get(id),
251
+ addNode: (id, node) => void state.nodes.set(id, node),
252
+ deleteNode: (id) => void state.nodes.delete(id),
253
+ generateId: () => `${getConnectionId()}:${state.clock++}`,
254
+ generateOpId: () => `${getConnectionId()}:${state.opClock++}`,
255
+ dispatch(ops, reverse, storageUpdates) {
256
+ const activeBatch = state.activeBatch;
257
+ if (activeBatch) {
258
+ activeBatch.ops.push(...ops);
259
+ storageUpdates.forEach((value, key) => {
260
+ activeBatch.updates.storageUpdates.set(
261
+ key,
262
+ _chunkRS4TQ2LTjs.mergeStorageUpdates.call(void 0,
263
+ activeBatch.updates.storageUpdates.get(key),
264
+ value
265
+ )
266
+ );
138
267
  });
268
+ activeBatch.reverseOps.push(...reverse);
269
+ } else {
270
+ addToUndoStack(reverse);
271
+ state.redoStack = [];
272
+ dispatchOps(ops);
273
+ notify({ storageUpdates });
274
+ }
139
275
  }
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);
276
+ };
277
+ const eventHub = {
278
+ customEvent: makeEventSource(),
279
+ me: makeEventSource(),
280
+ others: makeEventSource(),
281
+ error: makeEventSource(),
282
+ connection: makeEventSource(),
283
+ storage: makeEventSource(),
284
+ history: makeEventSource(),
285
+ storageDidLoad: makeEventSource()
286
+ };
287
+ const effects = mockedEffects || {
288
+ authenticate(auth, createWebSocket) {
289
+ const rawToken = state.token;
290
+ const parsedToken = rawToken !== null && _chunkRS4TQ2LTjs.parseRoomAuthToken.call(void 0, rawToken);
291
+ if (parsedToken && !_chunkRS4TQ2LTjs.isTokenExpired.call(void 0, parsedToken)) {
292
+ const socket = createWebSocket(rawToken);
293
+ authenticationSuccess(parsedToken, socket);
294
+ } else {
295
+ return auth(config.roomId).then(({ token }) => {
296
+ if (state.connection.current.state !== "authenticating") {
297
+ return;
298
+ }
299
+ const parsedToken2 = _chunkRS4TQ2LTjs.parseRoomAuthToken.call(void 0, token);
300
+ const socket = createWebSocket(token);
301
+ authenticationSuccess(parsedToken2, socket);
302
+ state.token = token;
303
+ }).catch(
304
+ (er) => authenticationFailure(
305
+ er instanceof Error ? er : new Error(String(er))
306
+ )
307
+ );
308
+ }
309
+ },
310
+ send(messageOrMessages) {
311
+ if (state.socket == null) {
312
+ throw new Error("Can't send message if socket is null");
313
+ }
314
+ state.socket.send(JSON.stringify(messageOrMessages));
315
+ },
316
+ delayFlush(delay) {
317
+ return setTimeout(tryFlushing, delay);
318
+ },
319
+ startHeartbeatInterval() {
320
+ return setInterval(heartbeat, HEARTBEAT_INTERVAL);
321
+ },
322
+ schedulePongTimeout() {
323
+ return setTimeout(pongTimeout, PONG_TIMEOUT);
324
+ },
325
+ scheduleReconnect(delay) {
326
+ return setTimeout(connect, delay);
152
327
  }
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));
328
+ };
329
+ const self = new DerivedRef(
330
+ [state.connection, state.me],
331
+ (conn, me) => isConnectionSelfAware(conn) ? {
332
+ connectionId: conn.id,
333
+ id: conn.userId,
334
+ info: conn.userInfo,
335
+ presence: me
336
+ } : null
337
+ );
338
+ function createOrUpdateRootFromMessage(message) {
339
+ if (message.items.length === 0) {
340
+ throw new Error("Internal error: cannot load storage without items");
341
+ }
342
+ if (state.root) {
343
+ updateRoot(message.items);
159
344
  } else {
160
- ownKeys(Object(source)).forEach(function(key) {
161
- Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
162
- });
345
+ state.root = load(message.items);
163
346
  }
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];
347
+ for (const key in state.defaultStorageRoot) {
348
+ if (state.root.get(key) == null) {
349
+ state.root.set(key, state.defaultStorageRoot[key]);
350
+ }
351
+ }
352
+ }
353
+ function buildRootAndParentToChildren(items) {
354
+ const parentToChildren = /* @__PURE__ */ new Map();
355
+ let root = null;
356
+ for (const [id, crdt] of items) {
357
+ if (_chunkRS4TQ2LTjs.isRootCrdt.call(void 0, crdt)) {
358
+ root = [id, crdt];
359
+ } else {
360
+ const tuple = [id, crdt];
361
+ const children = parentToChildren.get(crdt.parentId);
362
+ if (children != null) {
363
+ children.push(tuple);
364
+ } else {
365
+ parentToChildren.set(crdt.parentId, [tuple]);
177
366
  }
367
+ }
178
368
  }
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;
369
+ if (root == null) {
370
+ throw new Error("Root can't be null");
196
371
  }
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;
372
+ return [root, parentToChildren];
373
+ }
374
+ function updateRoot(items) {
375
+ if (!state.root) {
376
+ return;
259
377
  }
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;
378
+ const currentItems = /* @__PURE__ */ new Map();
379
+ state.nodes.forEach((node, id) => {
380
+ currentItems.set(id, node._serialize());
381
+ });
382
+ const ops = _chunkRS4TQ2LTjs.getTreesDiffOperations.call(void 0, currentItems, new Map(items));
383
+ const result = apply(ops, false);
384
+ notify(result.updates);
385
+ }
386
+ function load(items) {
387
+ const [root, parentToChildren] = buildRootAndParentToChildren(items);
388
+ return _chunkRS4TQ2LTjs.LiveObject._deserialize(root, parentToChildren, pool);
389
+ }
390
+ function addToUndoStack(historyItem) {
391
+ if (state.undoStack.length >= 50) {
392
+ state.undoStack.shift();
393
+ }
394
+ if (state.isHistoryPaused) {
395
+ state.pausedHistory.unshift(...historyItem);
280
396
  } else {
281
- return rhsFn();
397
+ state.undoStack.push(historyItem);
398
+ onHistoryChange();
282
399
  }
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
- }
400
+ }
401
+ function notify({
402
+ storageUpdates = /* @__PURE__ */ new Map(),
403
+ presence = false,
404
+ others: otherEvents = []
405
+ }) {
406
+ if (otherEvents.length > 0) {
407
+ const others = state.others.current;
408
+ for (const event of otherEvents) {
409
+ eventHub.others.notify({ others, event });
410
+ }
310
411
  }
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
- }
338
- function makeOthers(userMap) {
339
- var users = Object.values(userMap).map(function(user) {
340
- var _hasReceivedInitialPresence = user._hasReceivedInitialPresence, publicKeys = _objectWithoutProperties(user, [
341
- "_hasReceivedInitialPresence"
342
- ]);
343
- return publicKeys;
344
- });
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];
412
+ if (presence) {
413
+ eventHub.me.notify(state.me.current);
361
414
  }
362
- return;
363
- }
364
- function makeStateMachine(state, context, mockedEffects) {
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);
415
+ if (storageUpdates.size > 0) {
416
+ const updates = Array.from(storageUpdates.values());
417
+ eventHub.storage.notify(updates);
418
+ }
419
+ }
420
+ function getConnectionId() {
421
+ const conn = state.connection.current;
422
+ if (isConnectionSelfAware(conn)) {
423
+ return conn.id;
424
+ } else if (state.lastConnectionId !== null) {
425
+ return state.lastConnectionId;
426
+ }
427
+ throw new Error(
428
+ "Internal. Tried to get connection id but connection was never open"
429
+ );
430
+ }
431
+ function apply(item, isLocal) {
432
+ const result = {
433
+ reverse: [],
434
+ updates: {
435
+ storageUpdates: /* @__PURE__ */ new Map(),
436
+ presence: false
437
+ }
438
+ };
439
+ const createdNodeIds = /* @__PURE__ */ new Set();
440
+ for (const op of item) {
441
+ if (op.type === "presence") {
442
+ const reverse = {
443
+ type: "presence",
444
+ data: {}
369
445
  };
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);
378
- }
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");
446
+ for (const key in op.data) {
447
+ reverse.data[key] = state.me.current[key];
410
448
  }
411
- if (state.root) {
412
- updateRoot(message.items);
449
+ state.me.patch(op.data);
450
+ if (state.buffer.me == null) {
451
+ state.buffer.me = { type: "partial", data: op.data };
413
452
  } 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, {
486
- getItem: getItem,
487
- addItem: addItem,
488
- deleteItem: deleteItem,
489
- generateId: generateId,
490
- generateOpId: generateOpId,
491
- dispatch: storageDispatch,
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();
507
- }
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
530
- });
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
- }
643
- };
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;
453
+ for (const key in op.data) {
454
+ state.buffer.me.data[key] = op.data[key];
455
+ }
456
+ }
457
+ result.reverse.unshift(reverse);
458
+ result.updates.presence = true;
459
+ } else {
460
+ let source;
461
+ if (!op.opId) {
462
+ op.opId = pool.generateOpId();
463
+ }
464
+ if (isLocal) {
465
+ source = 0 /* UNDOREDO_RECONNECT */;
873
466
  } 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"
467
+ const deleted = state.offlineOperations.delete(_chunkRS4TQ2LTjs.nn.call(void 0, op.opId));
468
+ source = deleted ? 2 /* ACK */ : 1 /* REMOTE */;
469
+ }
470
+ const applyOpResult = applyOp(op, source);
471
+ if (applyOpResult.modified) {
472
+ const parentId = applyOpResult.modified.node.parent.type === "HasParent" ? _chunkRS4TQ2LTjs.nn.call(void 0,
473
+ applyOpResult.modified.node.parent.node._id,
474
+ "Expected parent node to have an ID"
475
+ ) : void 0;
476
+ if (!parentId || !createdNodeIds.has(parentId)) {
477
+ result.updates.storageUpdates.set(
478
+ _chunkRS4TQ2LTjs.nn.call(void 0, applyOpResult.modified.node._id),
479
+ _chunkRS4TQ2LTjs.mergeStorageUpdates.call(void 0,
480
+ result.updates.storageUpdates.get(
481
+ _chunkRS4TQ2LTjs.nn.call(void 0, applyOpResult.modified.node._id)
482
+ ),
483
+ applyOpResult.modified
484
+ )
485
+ );
486
+ result.reverse.unshift(...applyOpResult.reverse);
487
+ }
488
+ if (op.type === 2 /* CREATE_LIST */ || op.type === 7 /* CREATE_MAP */ || op.type === 4 /* CREATE_OBJECT */) {
489
+ createdNodeIds.add(_chunkRS4TQ2LTjs.nn.call(void 0, applyOpResult.modified.node._id));
490
+ }
491
+ }
492
+ }
493
+ }
494
+ return result;
495
+ }
496
+ function applyOp(op, source) {
497
+ switch (op.type) {
498
+ case 6 /* DELETE_OBJECT_KEY */:
499
+ case 3 /* UPDATE_OBJECT */:
500
+ case 5 /* DELETE_CRDT */: {
501
+ const node = state.nodes.get(op.id);
502
+ if (node == null) {
503
+ return { modified: false };
504
+ }
505
+ return node._apply(op, source === 0 /* UNDOREDO_RECONNECT */);
506
+ }
507
+ case 1 /* SET_PARENT_KEY */: {
508
+ const node = state.nodes.get(op.id);
509
+ if (node == null) {
510
+ return { modified: false };
511
+ }
512
+ if (node.parent.type === "HasParent" && _chunkRS4TQ2LTjs.isLiveList.call(void 0, node.parent.node)) {
513
+ return node.parent.node._setChildKey(op.parentKey, node, source);
514
+ }
515
+ return { modified: false };
516
+ }
517
+ case 4 /* CREATE_OBJECT */:
518
+ case 2 /* CREATE_LIST */:
519
+ case 7 /* CREATE_MAP */:
520
+ case 8 /* CREATE_REGISTER */: {
521
+ if (op.parentId === void 0) {
522
+ return { modified: false };
523
+ }
524
+ const parentNode = state.nodes.get(op.parentId);
525
+ if (parentNode == null) {
526
+ return { modified: false };
527
+ }
528
+ return parentNode._attachChild(op, source);
529
+ }
530
+ }
531
+ }
532
+ function subscribeToLiveStructureDeeply(node, callback) {
533
+ return eventHub.storage.subscribe((updates) => {
534
+ const relatedUpdates = updates.filter(
535
+ (update) => _chunkRS4TQ2LTjs.isSameNodeOrChildOf.call(void 0, update.node, node)
536
+ );
537
+ if (relatedUpdates.length > 0) {
538
+ callback(relatedUpdates);
539
+ }
540
+ });
541
+ }
542
+ function subscribeToLiveStructureShallowly(node, callback) {
543
+ return eventHub.storage.subscribe((updates) => {
544
+ for (const update of updates) {
545
+ if (update.node._id === node._id) {
546
+ callback(update.node);
547
+ }
548
+ }
549
+ });
550
+ }
551
+ function subscribe(first, second, options) {
552
+ if (typeof first === "string" && _chunkRS4TQ2LTjs.isRoomEventName.call(void 0, first)) {
553
+ if (typeof second !== "function") {
554
+ throw new Error("Second argument must be a callback function");
555
+ }
556
+ const callback = second;
557
+ switch (first) {
558
+ case "event":
559
+ return eventHub.customEvent.subscribe(
560
+ callback
561
+ );
562
+ case "my-presence":
563
+ return eventHub.me.subscribe(callback);
564
+ case "others": {
565
+ const cb = callback;
566
+ return eventHub.others.subscribe(
567
+ ({ others, event }) => cb(others, event)
568
+ );
569
+ }
570
+ case "error":
571
+ return eventHub.error.subscribe(callback);
572
+ case "connection":
573
+ return eventHub.connection.subscribe(
574
+ callback
575
+ );
576
+ case "storage":
577
+ return eventHub.storage.subscribe(
578
+ callback
579
+ );
580
+ case "history":
581
+ return eventHub.history.subscribe(callback);
582
+ default:
583
+ return _chunkRS4TQ2LTjs.assertNever.call(void 0, first, "Unknown event");
584
+ }
585
+ }
586
+ if (second === void 0 || typeof first === "function") {
587
+ if (typeof first === "function") {
588
+ const storageCallback = first;
589
+ return eventHub.storage.subscribe(storageCallback);
590
+ } else {
591
+ throw new Error("Please specify a listener callback");
592
+ }
593
+ }
594
+ if (_chunkRS4TQ2LTjs.isLiveNode.call(void 0, first)) {
595
+ const node = first;
596
+ if (options == null ? void 0 : options.isDeep) {
597
+ const storageCallback = second;
598
+ return subscribeToLiveStructureDeeply(node, storageCallback);
599
+ } else {
600
+ const nodeCallback = second;
601
+ return subscribeToLiveStructureShallowly(node, nodeCallback);
602
+ }
603
+ }
604
+ throw new Error(`"${first}" is not a valid event name`);
605
+ }
606
+ function getConnectionState() {
607
+ return state.connection.current.state;
608
+ }
609
+ function connect() {
610
+ var _a, _b, _c, _d;
611
+ if (state.connection.current.state !== "closed" && state.connection.current.state !== "unavailable") {
612
+ return null;
613
+ }
614
+ const auth = prepareAuthEndpoint(
615
+ config.authentication,
616
+ (_b = (_a = config.polyfills) == null ? void 0 : _a.fetch) != null ? _b : config.fetchPolyfill
617
+ );
618
+ const createWebSocket = prepareCreateWebSocket(
619
+ config.liveblocksServer,
620
+ (_d = (_c = config.polyfills) == null ? void 0 : _c.WebSocket) != null ? _d : config.WebSocketPolyfill
621
+ );
622
+ updateConnection({ state: "authenticating" });
623
+ effects.authenticate(auth, createWebSocket);
624
+ }
625
+ function updatePresence(patch, options) {
626
+ const oldValues = {};
627
+ if (state.buffer.me == null) {
628
+ state.buffer.me = {
629
+ type: "partial",
630
+ data: {}
631
+ };
632
+ }
633
+ for (const key in patch) {
634
+ const overrideValue = patch[key];
635
+ if (overrideValue === void 0) {
636
+ continue;
637
+ }
638
+ state.buffer.me.data[key] = overrideValue;
639
+ oldValues[key] = state.me.current[key];
640
+ }
641
+ state.me.patch(patch);
642
+ if (state.activeBatch) {
643
+ if (options == null ? void 0 : options.addToHistory) {
644
+ state.activeBatch.reverseOps.push({
645
+ type: "presence",
646
+ data: oldValues
915
647
  });
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] = {
932
- connectionId: message.actor,
933
- presence: message.data,
934
- id: void 0,
935
- info: void 0,
936
- _hasReceivedInitialPresence: true
937
- };
938
- } else {
939
- state.users[message.actor] = {
940
- id: user.id,
941
- info: user.info,
942
- connectionId: message.actor,
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] = {
648
+ }
649
+ state.activeBatch.updates.presence = true;
650
+ } else {
651
+ tryFlushing();
652
+ if (options == null ? void 0 : options.addToHistory) {
653
+ addToUndoStack([{ type: "presence", data: oldValues }]);
654
+ }
655
+ notify({ presence: true });
656
+ }
657
+ }
658
+ function authenticationSuccess(token, socket) {
659
+ socket.addEventListener("message", onMessage);
660
+ socket.addEventListener("open", onOpen);
661
+ socket.addEventListener("close", onClose);
662
+ socket.addEventListener("error", onError);
663
+ updateConnection({
664
+ state: "connecting",
665
+ id: token.actor,
666
+ userInfo: token.info,
667
+ userId: token.id
668
+ });
669
+ state.idFactory = makeIdFactory(token.actor);
670
+ state.socket = socket;
671
+ }
672
+ function authenticationFailure(error) {
673
+ if (process.env.NODE_ENV !== "production") {
674
+ console.error("Call to authentication endpoint failed", error);
675
+ }
676
+ state.token = null;
677
+ updateConnection({ state: "unavailable" });
678
+ state.numberOfRetry++;
679
+ state.timeoutHandles.reconnect = effects.scheduleReconnect(getRetryDelay());
680
+ }
681
+ function onVisibilityChange(visibilityState) {
682
+ if (visibilityState === "visible" && state.connection.current.state === "open") {
683
+ log("Heartbeat after visibility change");
684
+ heartbeat();
685
+ }
686
+ }
687
+ function onUpdatePresenceMessage(message) {
688
+ if (message.targetActor !== void 0) {
689
+ const oldUser = state.others.getUser(message.actor);
690
+ state.others.setOther(message.actor, message.data);
691
+ const newUser = state.others.getUser(message.actor);
692
+ if (oldUser === void 0 && newUser !== void 0) {
693
+ return { type: "enter", user: newUser };
694
+ }
695
+ } else {
696
+ state.others.patchOther(message.actor, message.data), message;
697
+ }
698
+ const user = state.others.getUser(message.actor);
699
+ if (user) {
700
+ return {
701
+ type: "update",
702
+ updates: message.data,
703
+ user
704
+ };
705
+ } else {
706
+ return void 0;
707
+ }
708
+ }
709
+ function onUserLeftMessage(message) {
710
+ const user = state.others.getUser(message.actor);
711
+ if (user) {
712
+ state.others.removeConnection(message.actor);
713
+ return { type: "leave", user };
714
+ }
715
+ return null;
716
+ }
717
+ function onRoomStateMessage(message) {
718
+ for (const key in message.users) {
719
+ const user = message.users[key];
720
+ const connectionId = Number(key);
721
+ state.others.setConnection(connectionId, user.id, user.info);
722
+ }
723
+ return { type: "reset" };
724
+ }
725
+ function onNavigatorOnline() {
726
+ if (state.connection.current.state === "unavailable") {
727
+ log("Try to reconnect after connectivity change");
728
+ reconnect();
729
+ }
730
+ }
731
+ function onHistoryChange() {
732
+ eventHub.history.notify({ canUndo: canUndo(), canRedo: canRedo() });
733
+ }
734
+ function onUserJoinedMessage(message) {
735
+ state.others.setConnection(message.actor, message.id, message.info);
736
+ state.buffer.messages.push({
737
+ type: 100 /* UPDATE_PRESENCE */,
738
+ data: state.me.current,
739
+ targetActor: message.actor
740
+ });
741
+ tryFlushing();
742
+ const user = state.others.getUser(message.actor);
743
+ return user ? { type: "enter", user } : void 0;
744
+ }
745
+ function parseServerMessage(data) {
746
+ if (!_chunkRS4TQ2LTjs.isJsonObject.call(void 0, data)) {
747
+ return null;
748
+ }
749
+ return data;
750
+ }
751
+ function parseServerMessages(text) {
752
+ const data = _chunkRS4TQ2LTjs.tryParseJson.call(void 0, text);
753
+ if (data === void 0) {
754
+ return null;
755
+ } else if (_chunkRS4TQ2LTjs.isJsonArray.call(void 0, data)) {
756
+ return _chunkRS4TQ2LTjs.compact.call(void 0, data.map((item) => parseServerMessage(item)));
757
+ } else {
758
+ return _chunkRS4TQ2LTjs.compact.call(void 0, [parseServerMessage(data)]);
759
+ }
760
+ }
761
+ function onMessage(event) {
762
+ if (event.data === "pong") {
763
+ clearTimeout(state.timeoutHandles.pongTimeout);
764
+ return;
765
+ }
766
+ const messages = parseServerMessages(event.data);
767
+ if (messages === null || messages.length === 0) {
768
+ return;
769
+ }
770
+ const updates = {
771
+ storageUpdates: /* @__PURE__ */ new Map(),
772
+ others: []
773
+ };
774
+ for (const message of messages) {
775
+ switch (message.type) {
776
+ case 101 /* USER_JOINED */: {
777
+ const userJoinedUpdate = onUserJoinedMessage(message);
778
+ if (userJoinedUpdate) {
779
+ updates.others.push(userJoinedUpdate);
780
+ }
781
+ break;
782
+ }
783
+ case 100 /* UPDATE_PRESENCE */: {
784
+ const othersPresenceUpdate = onUpdatePresenceMessage(message);
785
+ if (othersPresenceUpdate) {
786
+ updates.others.push(othersPresenceUpdate);
787
+ }
788
+ break;
789
+ }
790
+ case 103 /* BROADCASTED_EVENT */: {
791
+ eventHub.customEvent.notify({
1039
792
  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
- }
1163
- }
1164
- notify(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);
1333
- effects.send(messages);
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);
1340
- });
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) {
1400
- messages.push({
1401
- type: 201 /* UPDATE_STORAGE */ ,
1402
- ops: state2.buffer.storageOperations
1403
- });
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"
1430
- }
1431
- ]
1432
- });
1433
- clearListeners();
1434
- };
1435
- var clearListeners = function clearListeners() {
1436
- for(var key in state.listeners){
1437
- state.listeners[key] = [];
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
793
+ event: message.event
794
+ });
795
+ break;
796
+ }
797
+ case 102 /* USER_LEFT */: {
798
+ const event2 = onUserLeftMessage(message);
799
+ if (event2) {
800
+ updates.others.push(event2);
801
+ }
802
+ break;
803
+ }
804
+ case 104 /* ROOM_STATE */: {
805
+ updates.others.push(onRoomStateMessage(message));
806
+ break;
807
+ }
808
+ case 200 /* INITIAL_STORAGE_STATE */: {
809
+ const offlineOps = new Map(state.offlineOperations);
810
+ createOrUpdateRootFromMessage(message);
811
+ applyAndSendOfflineOps(offlineOps);
812
+ _getInitialStateResolver == null ? void 0 : _getInitialStateResolver();
813
+ eventHub.storageDidLoad.notify();
814
+ break;
815
+ }
816
+ case 201 /* UPDATE_STORAGE */: {
817
+ const applyResult = apply(message.ops, false);
818
+ applyResult.updates.storageUpdates.forEach((value, key) => {
819
+ updates.storageUpdates.set(
820
+ key,
821
+ _chunkRS4TQ2LTjs.mergeStorageUpdates.call(void 0,
822
+ updates.storageUpdates.get(key),
823
+ value
824
+ )
825
+ );
826
+ });
827
+ break;
828
+ }
829
+ }
830
+ }
831
+ notify(updates);
832
+ }
833
+ function onClose(event) {
834
+ state.socket = null;
835
+ clearTimeout(state.timeoutHandles.pongTimeout);
836
+ clearInterval(state.intervalHandles.heartbeat);
837
+ if (state.timeoutHandles.flush) {
838
+ clearTimeout(state.timeoutHandles.flush);
839
+ }
840
+ clearTimeout(state.timeoutHandles.reconnect);
841
+ state.others.clearOthers();
842
+ notify({ others: [{ type: "reset" }] });
843
+ if (event.code >= 4e3 && event.code <= 4100) {
844
+ updateConnection({ state: "failed" });
845
+ const error = new LiveblocksError(event.reason, event.code);
846
+ eventHub.error.notify(error);
847
+ const delay = getRetryDelay(true);
848
+ state.numberOfRetry++;
849
+ if (process.env.NODE_ENV !== "production") {
850
+ console.error(
851
+ `Connection to Liveblocks websocket server closed. Reason: ${error.message} (code: ${error.code}). Retrying in ${delay}ms.`
852
+ );
853
+ }
854
+ updateConnection({ state: "unavailable" });
855
+ state.timeoutHandles.reconnect = effects.scheduleReconnect(delay);
856
+ } else if (event.code === 4999 /* CLOSE_WITHOUT_RETRY */) {
857
+ updateConnection({ state: "closed" });
858
+ } else {
859
+ const delay = getRetryDelay();
860
+ state.numberOfRetry++;
861
+ if (process.env.NODE_ENV !== "production") {
862
+ console.warn(
863
+ `Connection to Liveblocks websocket server closed (code: ${event.code}). Retrying in ${delay}ms.`
864
+ );
865
+ }
866
+ updateConnection({ state: "unavailable" });
867
+ state.timeoutHandles.reconnect = effects.scheduleReconnect(delay);
868
+ }
869
+ }
870
+ function updateConnection(connection) {
871
+ state.connection.set(connection);
872
+ eventHub.connection.notify(connection.state);
873
+ }
874
+ function getRetryDelay(slow = false) {
875
+ if (slow) {
876
+ return BACKOFF_RETRY_DELAYS_SLOW[state.numberOfRetry < BACKOFF_RETRY_DELAYS_SLOW.length ? state.numberOfRetry : BACKOFF_RETRY_DELAYS_SLOW.length - 1];
877
+ }
878
+ return BACKOFF_RETRY_DELAYS[state.numberOfRetry < BACKOFF_RETRY_DELAYS.length ? state.numberOfRetry : BACKOFF_RETRY_DELAYS.length - 1];
879
+ }
880
+ function onError() {
881
+ }
882
+ function onOpen() {
883
+ clearInterval(state.intervalHandles.heartbeat);
884
+ state.intervalHandles.heartbeat = effects.startHeartbeatInterval();
885
+ if (state.connection.current.state === "connecting") {
886
+ updateConnection(_chunkRS4TQ2LTjs.__spreadProps.call(void 0, _chunkRS4TQ2LTjs.__spreadValues.call(void 0, {}, state.connection.current), { state: "open" }));
887
+ state.numberOfRetry = 0;
888
+ if (state.lastConnectionId !== void 0) {
889
+ state.buffer.me = {
890
+ type: "full",
891
+ data: state.me.current
1449
892
  };
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));
1462
893
  tryFlushing();
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
- };
894
+ }
895
+ state.lastConnectionId = state.connection.current.id;
896
+ if (state.root) {
897
+ state.buffer.messages.push({ type: 200 /* FETCH_STORAGE */ });
898
+ }
899
+ tryFlushing();
900
+ } else {
901
+ }
902
+ }
903
+ function heartbeat() {
904
+ if (state.socket == null) {
905
+ return;
906
+ }
907
+ clearTimeout(state.timeoutHandles.pongTimeout);
908
+ state.timeoutHandles.pongTimeout = effects.schedulePongTimeout();
909
+ if (state.socket.readyState === state.socket.OPEN) {
910
+ state.socket.send("ping");
911
+ }
912
+ }
913
+ function pongTimeout() {
914
+ log("Pong timeout. Trying to reconnect.");
915
+ reconnect();
916
+ }
917
+ function reconnect() {
918
+ if (state.socket) {
919
+ state.socket.removeEventListener("open", onOpen);
920
+ state.socket.removeEventListener("message", onMessage);
921
+ state.socket.removeEventListener("close", onClose);
922
+ state.socket.removeEventListener("error", onError);
923
+ state.socket.close();
924
+ state.socket = null;
925
+ }
926
+ updateConnection({ state: "unavailable" });
927
+ clearTimeout(state.timeoutHandles.pongTimeout);
928
+ if (state.timeoutHandles.flush) {
929
+ clearTimeout(state.timeoutHandles.flush);
930
+ }
931
+ clearTimeout(state.timeoutHandles.reconnect);
932
+ clearInterval(state.intervalHandles.heartbeat);
933
+ connect();
934
+ }
935
+ function applyAndSendOfflineOps(offlineOps) {
936
+ if (offlineOps.size === 0) {
937
+ return;
938
+ }
939
+ const messages = [];
940
+ const ops = Array.from(offlineOps.values());
941
+ const result = apply(ops, true);
942
+ messages.push({
943
+ type: 201 /* UPDATE_STORAGE */,
944
+ ops
945
+ });
946
+ notify(result.updates);
947
+ effects.send(messages);
948
+ }
949
+ function tryFlushing() {
950
+ const storageOps = state.buffer.storageOperations;
951
+ if (storageOps.length > 0) {
952
+ storageOps.forEach((op) => {
953
+ state.offlineOperations.set(_chunkRS4TQ2LTjs.nn.call(void 0, op.opId), op);
954
+ });
955
+ }
956
+ if (state.socket == null || state.socket.readyState !== state.socket.OPEN) {
957
+ state.buffer.storageOperations = [];
958
+ return;
959
+ }
960
+ const now = Date.now();
961
+ const elapsedTime = now - state.lastFlushTime;
962
+ if (elapsedTime > config.throttleDelay) {
963
+ const messages = flushDataToMessages(state);
964
+ if (messages.length === 0) {
965
+ return;
966
+ }
967
+ effects.send(messages);
968
+ state.buffer = {
969
+ messages: [],
970
+ storageOperations: [],
971
+ me: null
972
+ };
973
+ state.lastFlushTime = now;
974
+ } else {
975
+ if (state.timeoutHandles.flush != null) {
976
+ clearTimeout(state.timeoutHandles.flush);
977
+ }
978
+ state.timeoutHandles.flush = effects.delayFlush(
979
+ config.throttleDelay - (now - state.lastFlushTime)
980
+ );
981
+ }
982
+ }
983
+ function flushDataToMessages(state2) {
984
+ const messages = [];
985
+ if (state2.buffer.me) {
986
+ messages.push(
987
+ state2.buffer.me.type === "full" ? {
988
+ type: 100 /* UPDATE_PRESENCE */,
989
+ targetActor: -1,
990
+ data: state2.buffer.me.data
991
+ } : {
992
+ type: 100 /* UPDATE_PRESENCE */,
993
+ data: state2.buffer.me.data
994
+ }
995
+ );
996
+ }
997
+ for (const event of state2.buffer.messages) {
998
+ messages.push(event);
999
+ }
1000
+ if (state2.buffer.storageOperations.length > 0) {
1001
+ messages.push({
1002
+ type: 201 /* UPDATE_STORAGE */,
1003
+ ops: state2.buffer.storageOperations
1004
+ });
1005
+ }
1006
+ return messages;
1007
+ }
1008
+ function disconnect() {
1009
+ if (state.socket) {
1010
+ state.socket.removeEventListener("open", onOpen);
1011
+ state.socket.removeEventListener("message", onMessage);
1012
+ state.socket.removeEventListener("close", onClose);
1013
+ state.socket.removeEventListener("error", onError);
1014
+ state.socket.close();
1015
+ state.socket = null;
1016
+ }
1017
+ updateConnection({ state: "closed" });
1018
+ if (state.timeoutHandles.flush) {
1019
+ clearTimeout(state.timeoutHandles.flush);
1020
+ }
1021
+ clearTimeout(state.timeoutHandles.reconnect);
1022
+ clearTimeout(state.timeoutHandles.pongTimeout);
1023
+ clearInterval(state.intervalHandles.heartbeat);
1024
+ state.others.clearOthers();
1025
+ notify({ others: [{ type: "reset" }] });
1026
+ Object.values(eventHub).forEach((eventSource) => eventSource.clear());
1027
+ }
1028
+ function getPresence() {
1029
+ return state.me.current;
1030
+ }
1031
+ function getOthers() {
1032
+ return state.others.current;
1033
+ }
1034
+ function broadcastEvent(event, options = {
1035
+ shouldQueueEventIfNotReady: false
1036
+ }) {
1037
+ if (state.socket == null && options.shouldQueueEventIfNotReady == false) {
1038
+ return;
1039
+ }
1040
+ state.buffer.messages.push({
1041
+ type: 103 /* BROADCAST_EVENT */,
1042
+ event
1043
+ });
1044
+ tryFlushing();
1045
+ }
1046
+ function dispatchOps(ops) {
1047
+ state.buffer.storageOperations.push(...ops);
1048
+ tryFlushing();
1049
+ }
1050
+ let _getInitialStatePromise = null;
1051
+ let _getInitialStateResolver = null;
1052
+ function startLoadingStorage() {
1053
+ if (_getInitialStatePromise == null) {
1054
+ state.buffer.messages.push({ type: 200 /* FETCH_STORAGE */ });
1055
+ tryFlushing();
1056
+ _getInitialStatePromise = new Promise(
1057
+ (resolve) => _getInitialStateResolver = resolve
1058
+ );
1059
+ }
1060
+ return _getInitialStatePromise;
1061
+ }
1062
+ function getStorageSnapshot() {
1063
+ const root = state.root;
1064
+ if (root !== void 0) {
1065
+ return root;
1066
+ } else {
1067
+ startLoadingStorage();
1068
+ return null;
1069
+ }
1070
+ }
1071
+ function getStorage() {
1072
+ return _chunkRS4TQ2LTjs.__async.call(void 0, this, null, function* () {
1073
+ if (state.root) {
1074
+ return Promise.resolve({
1075
+ root: state.root
1485
1076
  });
1077
+ }
1078
+ yield startLoadingStorage();
1079
+ return {
1080
+ root: _chunkRS4TQ2LTjs.nn.call(void 0, state.root)
1081
+ };
1082
+ });
1083
+ }
1084
+ function undo() {
1085
+ if (state.activeBatch) {
1086
+ throw new Error("undo is not allowed during a batch");
1087
+ }
1088
+ const historyItem = state.undoStack.pop();
1089
+ if (historyItem == null) {
1090
+ return;
1091
+ }
1092
+ state.isHistoryPaused = false;
1093
+ const result = apply(historyItem, true);
1094
+ notify(result.updates);
1095
+ state.redoStack.push(result.reverse);
1096
+ onHistoryChange();
1097
+ for (const op of historyItem) {
1098
+ if (op.type !== "presence") {
1099
+ state.buffer.storageOperations.push(op);
1100
+ }
1101
+ }
1102
+ tryFlushing();
1103
+ }
1104
+ function canUndo() {
1105
+ return state.undoStack.length > 0;
1106
+ }
1107
+ function redo() {
1108
+ if (state.activeBatch) {
1109
+ throw new Error("redo is not allowed during a batch");
1110
+ }
1111
+ const historyItem = state.redoStack.pop();
1112
+ if (historyItem == null) {
1113
+ return;
1114
+ }
1115
+ state.isHistoryPaused = false;
1116
+ const result = apply(historyItem, true);
1117
+ notify(result.updates);
1118
+ state.undoStack.push(result.reverse);
1119
+ onHistoryChange();
1120
+ for (const op of historyItem) {
1121
+ if (op.type !== "presence") {
1122
+ state.buffer.storageOperations.push(op);
1123
+ }
1124
+ }
1125
+ tryFlushing();
1126
+ }
1127
+ function canRedo() {
1128
+ return state.redoStack.length > 0;
1129
+ }
1130
+ function batch(callback) {
1131
+ if (state.activeBatch) {
1132
+ return callback();
1133
+ }
1134
+ state.activeBatch = {
1135
+ ops: [],
1136
+ updates: {
1137
+ storageUpdates: /* @__PURE__ */ new Map(),
1138
+ presence: false,
1139
+ others: []
1140
+ },
1141
+ reverseOps: []
1486
1142
  };
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
- }
1521
- }
1522
- tryFlushing();
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
- }
1547
- }
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
- };
1143
+ try {
1144
+ return callback();
1145
+ } finally {
1146
+ const currentBatch = state.activeBatch;
1147
+ state.activeBatch = null;
1148
+ if (currentBatch.reverseOps.length > 0) {
1149
+ addToUndoStack(currentBatch.reverseOps);
1150
+ }
1151
+ if (currentBatch.ops.length > 0) {
1152
+ state.redoStack = [];
1153
+ }
1154
+ if (currentBatch.ops.length > 0) {
1155
+ dispatchOps(currentBatch.ops);
1156
+ }
1157
+ notify(currentBatch.updates);
1158
+ tryFlushing();
1159
+ }
1160
+ }
1161
+ function pauseHistory() {
1162
+ state.pausedHistory = [];
1163
+ state.isHistoryPaused = true;
1164
+ }
1165
+ function resumeHistory() {
1166
+ state.isHistoryPaused = false;
1167
+ if (state.pausedHistory.length > 0) {
1168
+ addToUndoStack(state.pausedHistory);
1169
+ }
1170
+ state.pausedHistory = [];
1171
+ }
1172
+ function simulateSocketClose() {
1173
+ if (state.socket) {
1174
+ state.socket = null;
1175
+ }
1176
+ }
1177
+ function simulateSendCloseEvent(event) {
1178
+ onClose(event);
1179
+ }
1180
+ return {
1181
+ onClose,
1182
+ onMessage,
1183
+ authenticationSuccess,
1184
+ heartbeat,
1185
+ onNavigatorOnline,
1186
+ simulateSocketClose,
1187
+ simulateSendCloseEvent,
1188
+ onVisibilityChange,
1189
+ getUndoStack: () => state.undoStack,
1190
+ getItemsCount: () => state.nodes.size,
1191
+ connect,
1192
+ disconnect,
1193
+ subscribe,
1194
+ updatePresence,
1195
+ broadcastEvent,
1196
+ batch,
1197
+ undo,
1198
+ redo,
1199
+ canUndo,
1200
+ canRedo,
1201
+ pauseHistory,
1202
+ resumeHistory,
1203
+ getStorage,
1204
+ getStorageSnapshot,
1205
+ events: {
1206
+ customEvent: eventHub.customEvent.observable,
1207
+ others: eventHub.others.observable,
1208
+ me: eventHub.me.observable,
1209
+ error: eventHub.error.observable,
1210
+ connection: eventHub.connection.observable,
1211
+ storage: eventHub.storage.observable,
1212
+ history: eventHub.history.observable,
1213
+ storageDidLoad: eventHub.storageDidLoad.observable
1214
+ },
1215
+ getConnectionState,
1216
+ isSelfAware: () => isConnectionSelfAware(state.connection.current),
1217
+ getSelf: () => self.current,
1218
+ getPresence,
1219
+ getOthers
1220
+ };
1695
1221
  }
1696
1222
  function defaultState(initialPresence, initialStorage) {
1697
- return {
1698
- connection: {
1699
- state: "closed"
1700
- },
1701
- token: null,
1702
- lastConnectionId: null,
1703
- socket: null,
1704
- listeners: {
1705
- event: [],
1706
- others: [],
1707
- "my-presence": [],
1708
- error: [],
1709
- connection: [],
1710
- storage: [],
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
- },
1725
- messages: [],
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: {
1746
- ops: [],
1747
- updates: {
1748
- storageUpdates: /* @__PURE__ */ new Map(),
1749
- presence: false,
1750
- others: []
1751
- },
1752
- reverseOps: []
1753
- },
1754
- offlineOperations: /* @__PURE__ */ new Map()
1755
- };
1223
+ const others = new OthersRef();
1224
+ const connection = new ValueRef({ state: "closed" });
1225
+ return {
1226
+ token: null,
1227
+ lastConnectionId: null,
1228
+ socket: null,
1229
+ numberOfRetry: 0,
1230
+ lastFlushTime: 0,
1231
+ timeoutHandles: {
1232
+ flush: null,
1233
+ reconnect: 0,
1234
+ pongTimeout: 0
1235
+ },
1236
+ buffer: {
1237
+ me: {
1238
+ type: "full",
1239
+ data: initialPresence
1240
+ },
1241
+ messages: [],
1242
+ storageOperations: []
1243
+ },
1244
+ intervalHandles: {
1245
+ heartbeat: 0
1246
+ },
1247
+ connection,
1248
+ me: new MeRef(initialPresence),
1249
+ others,
1250
+ defaultStorageRoot: initialStorage,
1251
+ idFactory: null,
1252
+ clock: 0,
1253
+ opClock: 0,
1254
+ nodes: /* @__PURE__ */ new Map(),
1255
+ root: void 0,
1256
+ undoStack: [],
1257
+ redoStack: [],
1258
+ isHistoryPaused: false,
1259
+ pausedHistory: [],
1260
+ activeBatch: null,
1261
+ offlineOperations: /* @__PURE__ */ new Map()
1262
+ };
1756
1263
  }
1757
- function createRoom(options, context) {
1758
- var initialPresence = _nullishCoalesce(options.initialPresence, function() {
1759
- return options.defaultPresence;
1760
- });
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
- };
1790
- return {
1791
- connect: machine.connect,
1792
- disconnect: machine.disconnect,
1793
- onNavigatorOnline: machine.onNavigatorOnline,
1794
- onVisibilityChange: machine.onVisibilityChange,
1795
- room: room
1796
- };
1264
+ function createRoom(options, config) {
1265
+ const { initialPresence, initialStorage } = options;
1266
+ const state = defaultState(
1267
+ typeof initialPresence === "function" ? initialPresence(config.roomId) : initialPresence,
1268
+ typeof initialStorage === "function" ? initialStorage(config.roomId) : initialStorage
1269
+ );
1270
+ const machine = makeStateMachine(
1271
+ state,
1272
+ config
1273
+ );
1274
+ const room = {
1275
+ id: config.roomId,
1276
+ getConnectionState: machine.getConnectionState,
1277
+ isSelfAware: machine.isSelfAware,
1278
+ getSelf: machine.getSelf,
1279
+ subscribe: machine.subscribe,
1280
+ getPresence: machine.getPresence,
1281
+ updatePresence: machine.updatePresence,
1282
+ getOthers: machine.getOthers,
1283
+ broadcastEvent: machine.broadcastEvent,
1284
+ getStorage: machine.getStorage,
1285
+ getStorageSnapshot: machine.getStorageSnapshot,
1286
+ events: machine.events,
1287
+ batch: machine.batch,
1288
+ history: {
1289
+ undo: machine.undo,
1290
+ redo: machine.redo,
1291
+ canUndo: machine.canUndo,
1292
+ canRedo: machine.canRedo,
1293
+ pause: machine.pauseHistory,
1294
+ resume: machine.resumeHistory
1295
+ },
1296
+ __INTERNAL_DO_NOT_USE: {
1297
+ simulateCloseWebsocket: machine.simulateSocketClose,
1298
+ simulateSendCloseEvent: machine.simulateSendCloseEvent
1299
+ }
1300
+ };
1301
+ return {
1302
+ connect: machine.connect,
1303
+ disconnect: machine.disconnect,
1304
+ onNavigatorOnline: machine.onNavigatorOnline,
1305
+ onVisibilityChange: machine.onVisibilityChange,
1306
+ room
1307
+ };
1797
1308
  }
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));
1309
+ var LiveblocksError = class extends Error {
1310
+ constructor(message, code) {
1311
+ super(message);
1312
+ this.code = code;
1313
+ }
1314
+ };
1810
1315
  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.11" : "dev"));
1817
- };
1316
+ if (typeof window === "undefined" && WebSocketPolyfill == null) {
1317
+ throw new Error(
1318
+ "To use Liveblocks client in a non-dom environment, you need to provide a WebSocket polyfill."
1319
+ );
1320
+ }
1321
+ const ws = WebSocketPolyfill || WebSocket;
1322
+ return (token) => {
1323
+ return new ws(
1324
+ `${liveblocksServer}/?token=${token}&version=${true ? "0.18.0-beta2" : "dev"}`
1325
+ );
1326
+ };
1818
1327
  }
1819
1328
  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
- };
1329
+ if (authentication.type === "public") {
1330
+ if (typeof window === "undefined" && fetchPolyfill == null) {
1331
+ throw new Error(
1332
+ "To use Liveblocks client in a non-dom environment with a publicApiKey, you need to provide a fetch polyfill."
1333
+ );
1840
1334
  }
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;
1335
+ return (room) => fetchAuthEndpoint(fetchPolyfill || fetch, authentication.url, {
1336
+ room,
1337
+ publicApiKey: authentication.publicApiKey
1338
+ });
1339
+ }
1340
+ if (authentication.type === "private") {
1341
+ if (typeof window === "undefined" && fetchPolyfill == null) {
1342
+ throw new Error(
1343
+ "To use Liveblocks client in a non-dom environment with a url as auth endpoint, you need to provide a fetch polyfill."
1344
+ );
1851
1345
  }
1852
- throw new Error("Internal error. Unexpected authentication type");
1346
+ return (room) => fetchAuthEndpoint(fetchPolyfill || fetch, authentication.url, {
1347
+ room
1348
+ });
1349
+ }
1350
+ if (authentication.type === "custom") {
1351
+ return (room) => _chunkRS4TQ2LTjs.__async.call(void 0, this, null, function* () {
1352
+ const response = yield authentication.callback(room);
1353
+ if (!response || !response.token) {
1354
+ throw new Error(
1355
+ 'Authentication error. We expect the authentication callback to return a token, but it does not. Hint: the return value should look like: { token: "..." }'
1356
+ );
1357
+ }
1358
+ return response;
1359
+ });
1360
+ }
1361
+ throw new Error("Internal error. Unexpected authentication type");
1853
1362
  }
1854
1363
  function fetchAuthEndpoint(fetch2, endpoint, body) {
1855
- return fetch2(endpoint, {
1856
- method: "POST",
1857
- headers: {
1858
- "Content-Type": "application/json"
1859
- },
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
- };
1364
+ return _chunkRS4TQ2LTjs.__async.call(void 0, this, null, function* () {
1365
+ const res = yield fetch2(endpoint, {
1366
+ method: "POST",
1367
+ headers: {
1368
+ "Content-Type": "application/json"
1369
+ },
1370
+ body: JSON.stringify(body)
1876
1371
  });
1372
+ if (!res.ok) {
1373
+ throw new AuthenticationError(
1374
+ `Expected a status 200 but got ${res.status} when doing a POST request on "${endpoint}"`
1375
+ );
1376
+ }
1377
+ let data;
1378
+ try {
1379
+ data = yield res.json();
1380
+ } catch (er) {
1381
+ throw new AuthenticationError(
1382
+ `Expected a JSON response when doing a POST request on "${endpoint}". ${er}`
1383
+ );
1384
+ }
1385
+ if (!_chunkRS4TQ2LTjs.isPlainObject.call(void 0, data) || typeof data.token !== "string") {
1386
+ throw new AuthenticationError(
1387
+ `Expected a JSON response of the form \`{ token: "..." }\` when doing a POST request on "${endpoint}", but got ${JSON.stringify(
1388
+ data
1389
+ )}`
1390
+ );
1391
+ }
1392
+ const { token } = data;
1393
+ return { token };
1394
+ });
1877
1395
  }
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));
1396
+ var AuthenticationError = class extends Error {
1397
+ constructor(message) {
1398
+ super(message);
1399
+ }
1400
+ };
1401
+
1887
1402
  // src/client.ts
1888
1403
  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;
1938
- }
1939
- internalRoom.connect();
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
- });
1404
+ const clientOptions = options;
1405
+ const throttleDelay = getThrottleDelayFromOptions(options);
1406
+ const rooms = /* @__PURE__ */ new Map();
1407
+ function getRoom(roomId) {
1408
+ const internalRoom = rooms.get(roomId);
1409
+ return internalRoom ? internalRoom.room : null;
1410
+ }
1411
+ function enter(roomId, options2) {
1412
+ var _a, _b;
1413
+ let internalRoom = rooms.get(roomId);
1414
+ if (internalRoom) {
1415
+ return internalRoom.room;
1976
1416
  }
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
- });
1417
+ _chunkRS4TQ2LTjs.deprecateIf.call(void 0,
1418
+ options2.initialPresence == null,
1419
+ "Please provide an initial presence value for the current user when entering the room."
1420
+ );
1421
+ internalRoom = createRoom(
1422
+ {
1423
+ initialPresence: (_a = options2.initialPresence) != null ? _a : {},
1424
+ initialStorage: options2.initialStorage
1425
+ },
1426
+ {
1427
+ roomId,
1428
+ throttleDelay,
1429
+ polyfills: clientOptions.polyfills,
1430
+ WebSocketPolyfill: clientOptions.WebSocketPolyfill,
1431
+ fetchPolyfill: clientOptions.fetchPolyfill,
1432
+ liveblocksServer: (clientOptions == null ? void 0 : clientOptions.liveblocksServer) || "wss://api.liveblocks.io/v6",
1433
+ authentication: prepareAuthentication(clientOptions, roomId)
1434
+ }
1435
+ );
1436
+ rooms.set(
1437
+ roomId,
1438
+ internalRoom
1439
+ );
1440
+ if (!options2.DO_NOT_USE_withoutConnecting) {
1441
+ if (typeof atob == "undefined") {
1442
+ if (((_b = clientOptions.polyfills) == null ? void 0 : _b.atob) == void 0) {
1443
+ throw new Error(
1444
+ "You need to polyfill atob to use the client in your environment. Please follow the instructions at https://liveblocks.io/docs/errors/liveblocks-client/atob-polyfill"
1445
+ );
1446
+ }
1447
+ global.atob = clientOptions.polyfills.atob;
1448
+ }
1449
+ internalRoom.connect();
2000
1450
  }
2001
- return {
2002
- getRoom: getRoom,
2003
- enter: enter,
2004
- leave: leave
2005
- };
1451
+ return internalRoom.room;
1452
+ }
1453
+ function leave(roomId) {
1454
+ const room = rooms.get(roomId);
1455
+ if (room) {
1456
+ room.disconnect();
1457
+ rooms.delete(roomId);
1458
+ }
1459
+ }
1460
+ if (typeof window !== "undefined" && typeof window.addEventListener !== "undefined") {
1461
+ window.addEventListener("online", () => {
1462
+ for (const [, room] of rooms) {
1463
+ room.onNavigatorOnline();
1464
+ }
1465
+ });
1466
+ }
1467
+ if (typeof document !== "undefined") {
1468
+ document.addEventListener("visibilitychange", () => {
1469
+ for (const [, room] of rooms) {
1470
+ room.onVisibilityChange(document.visibilityState);
1471
+ }
1472
+ });
1473
+ }
1474
+ return {
1475
+ getRoom,
1476
+ enter,
1477
+ leave
1478
+ };
2006
1479
  }
2007
1480
  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;
1481
+ if (options.throttle === void 0) {
1482
+ return 100;
1483
+ }
1484
+ if (typeof options.throttle !== "number" || options.throttle < 80 || options.throttle > 1e3) {
1485
+ throw new Error("throttle should be a number between 80 and 1000.");
1486
+ }
1487
+ return options.throttle;
2015
1488
  }
2016
1489
  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
- };
1490
+ const { publicApiKey, authEndpoint } = clientOptions;
1491
+ if (authEndpoint !== void 0 && publicApiKey !== void 0) {
1492
+ throw new Error(
1493
+ "You cannot use both publicApiKey and authEndpoint. Please use either publicApiKey or authEndpoint, but not both. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClient"
1494
+ );
1495
+ }
1496
+ if (typeof publicApiKey === "string") {
1497
+ if (publicApiKey.startsWith("sk_")) {
1498
+ throw new Error(
1499
+ "Invalid publicApiKey. You are using the secret key which is not supported. Please use the public key instead. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClientPublicKey"
1500
+ );
1501
+ } else if (!publicApiKey.startsWith("pk_")) {
1502
+ throw new Error(
1503
+ "Invalid key. Please use the public key format: pk_<public key>. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClientPublicKey"
1504
+ );
2032
1505
  }
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");
1506
+ return {
1507
+ type: "public",
1508
+ publicApiKey,
1509
+ url: buildLiveblocksPublicAuthorizeEndpoint(clientOptions, roomId)
1510
+ };
1511
+ }
1512
+ if (typeof authEndpoint === "string") {
1513
+ return {
1514
+ type: "private",
1515
+ url: authEndpoint
1516
+ };
1517
+ } else if (typeof authEndpoint === "function") {
1518
+ return {
1519
+ type: "custom",
1520
+ callback: authEndpoint
1521
+ };
1522
+ } else if (authEndpoint !== void 0) {
1523
+ throw new Error(
1524
+ "authEndpoint must be a string or a function. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClientAuthEndpoint"
1525
+ );
1526
+ }
1527
+ throw new Error(
1528
+ "Invalid Liveblocks client options. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClient"
1529
+ );
2047
1530
  }
2048
1531
  function buildLiveblocksPublicAuthorizeEndpoint(options, roomId) {
2049
- if (options.publicAuthorizeEndpoint) {
2050
- return options.publicAuthorizeEndpoint.replace("{roomId}", roomId);
1532
+ if (options.publicAuthorizeEndpoint) {
1533
+ return options.publicAuthorizeEndpoint.replace("{roomId}", roomId);
1534
+ }
1535
+ return `https://api.liveblocks.io/v2/rooms/${encodeURIComponent(
1536
+ roomId
1537
+ )}/public/authorize`;
1538
+ }
1539
+
1540
+ // src/shallow.ts
1541
+ function shallowArray(xs, ys) {
1542
+ if (xs.length !== ys.length) {
1543
+ return false;
1544
+ }
1545
+ for (let i = 0; i < xs.length; i++) {
1546
+ if (!Object.is(xs[i], ys[i])) {
1547
+ return false;
1548
+ }
1549
+ }
1550
+ return true;
1551
+ }
1552
+ function shallowObj(objA, objB) {
1553
+ if (typeof objA !== "object" || objA === null || typeof objB !== "object" || objB === null || Object.prototype.toString.call(objA) !== "[object Object]" || Object.prototype.toString.call(objB) !== "[object Object]") {
1554
+ return false;
1555
+ }
1556
+ const keysA = Object.keys(objA);
1557
+ if (keysA.length !== Object.keys(objB).length) {
1558
+ return false;
1559
+ }
1560
+ return keysA.every(
1561
+ (key) => Object.prototype.hasOwnProperty.call(objB, key) && Object.is(objA[key], objB[key])
1562
+ );
1563
+ }
1564
+ function shallow(a, b) {
1565
+ if (Object.is(a, b)) {
1566
+ return true;
1567
+ }
1568
+ const isArrayA = Array.isArray(a);
1569
+ const isArrayB = Array.isArray(b);
1570
+ if (isArrayA || isArrayB) {
1571
+ if (!isArrayA || !isArrayB) {
1572
+ return false;
2051
1573
  }
2052
- return "https://api.liveblocks.io/v2/rooms/".concat(encodeURIComponent(roomId), "/public/authorize");
1574
+ return shallowArray(a, b);
1575
+ }
1576
+ return shallowObj(a, b);
2053
1577
  }
2054
- exports.LiveList = _chunkQLMVHHAZjs.LiveList;
2055
- exports.LiveMap = _chunkQLMVHHAZjs.LiveMap;
2056
- exports.LiveObject = _chunkQLMVHHAZjs.LiveObject;
2057
- exports.createClient = createClient;
1578
+
1579
+
1580
+
1581
+
1582
+
1583
+
1584
+ exports.LiveList = _chunkRS4TQ2LTjs.LiveList; exports.LiveMap = _chunkRS4TQ2LTjs.LiveMap; exports.LiveObject = _chunkRS4TQ2LTjs.LiveObject; exports.createClient = createClient; exports.shallow = shallow;