@liveblocks/core 1.2.0-internal4 → 1.2.0-internal5

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/dist/index.js CHANGED
@@ -1,44 +1,4 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});var __defProp = Object.defineProperty;
2
- var __defProps = Object.defineProperties;
3
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
7
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
- var __spreadValues = (a, b) => {
9
- for (var prop in b || (b = {}))
10
- if (__hasOwnProp.call(b, prop))
11
- __defNormalProp(a, prop, b[prop]);
12
- if (__getOwnPropSymbols)
13
- for (var prop of __getOwnPropSymbols(b)) {
14
- if (__propIsEnum.call(b, prop))
15
- __defNormalProp(a, prop, b[prop]);
16
- }
17
- return a;
18
- };
19
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
20
- var __async = (__this, __arguments, generator) => {
21
- return new Promise((resolve, reject) => {
22
- var fulfilled = (value) => {
23
- try {
24
- step(generator.next(value));
25
- } catch (e) {
26
- reject(e);
27
- }
28
- };
29
- var rejected = (value) => {
30
- try {
31
- step(generator.throw(value));
32
- } catch (e) {
33
- reject(e);
34
- }
35
- };
36
- var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
37
- step((generator = generator.apply(__this, __arguments)).next());
38
- });
39
- };
40
-
41
- // src/lib/EventSource.ts
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }// src/lib/EventSource.ts
42
2
  function makeEventSource() {
43
3
  const _onetimeObservers = /* @__PURE__ */ new Set();
44
4
  const _observers = /* @__PURE__ */ new Set();
@@ -63,17 +23,15 @@ function makeEventSource() {
63
23
  _onetimeObservers.add(callback);
64
24
  return () => _onetimeObservers.delete(callback);
65
25
  }
66
- function waitUntil(predicate) {
67
- return __async(this, null, function* () {
68
- let unsub;
69
- return new Promise((res) => {
70
- unsub = subscribe((event) => {
71
- if (predicate === void 0 || predicate(event)) {
72
- res(event);
73
- }
74
- });
75
- }).finally(() => unsub == null ? void 0 : unsub());
76
- });
26
+ async function waitUntil(predicate) {
27
+ let unsub;
28
+ return new Promise((res) => {
29
+ unsub = subscribe((event) => {
30
+ if (predicate === void 0 || predicate(event)) {
31
+ res(event);
32
+ }
33
+ });
34
+ }).finally(() => _optionalChain([unsub, 'optionalCall', _2 => _2()]));
77
35
  }
78
36
  function notifyOrBuffer(event) {
79
37
  if (_buffer !== null) {
@@ -122,10 +80,11 @@ function sendToPanel(message, options) {
122
80
  if (process.env.NODE_ENV === "production" || typeof window === "undefined") {
123
81
  return;
124
82
  }
125
- const fullMsg = __spreadProps(__spreadValues({}, message), {
83
+ const fullMsg = {
84
+ ...message,
126
85
  source: "liveblocks-devtools-client"
127
- });
128
- if (!((options == null ? void 0 : options.force) || _bridgeActive)) {
86
+ };
87
+ if (!(_optionalChain([options, 'optionalAccess', _3 => _3.force]) || _bridgeActive)) {
129
88
  return;
130
89
  }
131
90
  window.postMessage(fullMsg, "*");
@@ -133,8 +92,7 @@ function sendToPanel(message, options) {
133
92
  var eventSource = makeEventSource();
134
93
  if (process.env.NODE_ENV !== "production" && typeof window !== "undefined") {
135
94
  window.addEventListener("message", (event) => {
136
- var _a;
137
- if (event.source === window && ((_a = event.data) == null ? void 0 : _a.source) === "liveblocks-devtools-panel") {
95
+ if (event.source === window && _optionalChain([event, 'access', _4 => _4.data, 'optionalAccess', _5 => _5.source]) === "liveblocks-devtools-panel") {
138
96
  eventSource.notify(event.data);
139
97
  } else {
140
98
  }
@@ -145,7 +103,7 @@ var onMessageFromPanel = eventSource.observable;
145
103
  // src/devtools/index.ts
146
104
  var VERSION = true ? (
147
105
  /* istanbul ignore next */
148
- "1.2.0-internal4"
106
+ "1.2.0-internal5"
149
107
  ) : "dev";
150
108
  var _devtoolsSetupHasRun = false;
151
109
  function setupDevTools(getAllRooms) {
@@ -175,8 +133,7 @@ function setupDevTools(getAllRooms) {
175
133
  }
176
134
  var unsubsByRoomId = /* @__PURE__ */ new Map();
177
135
  function stopSyncStream(roomId) {
178
- var _a;
179
- const unsubs = (_a = unsubsByRoomId.get(roomId)) != null ? _a : [];
136
+ const unsubs = _nullishCoalesce(unsubsByRoomId.get(roomId), () => ( []));
180
137
  unsubsByRoomId.delete(roomId);
181
138
  for (const unsub of unsubs) {
182
139
  unsub();
@@ -235,7 +192,6 @@ function partialSyncOthers(room) {
235
192
  }
236
193
  }
237
194
  function fullSync(room) {
238
- var _a;
239
195
  const root = room.getStorageSnapshot();
240
196
  const me = room.__internal.getSelf_forDevTools();
241
197
  const others = room.__internal.getOthers_forDevTools();
@@ -243,7 +199,7 @@ function fullSync(room) {
243
199
  msg: "room::sync::full",
244
200
  roomId: room.id,
245
201
  status: room.getStatus(),
246
- storage: (_a = root == null ? void 0 : root.toTreeNode("root").payload) != null ? _a : null,
202
+ storage: _nullishCoalesce(_optionalChain([root, 'optionalAccess', _6 => _6.toTreeNode, 'call', _7 => _7("root"), 'access', _8 => _8.payload]), () => ( null)),
247
203
  me,
248
204
  others
249
205
  });
@@ -424,7 +380,8 @@ var SafeContext = class {
424
380
  allowPatching(callback) {
425
381
  const self = this;
426
382
  let allowed = true;
427
- const patchableContext = __spreadProps(__spreadValues({}, this.curr), {
383
+ const patchableContext = {
384
+ ...this.curr,
428
385
  patch(patch) {
429
386
  if (allowed) {
430
387
  self.curr = Object.assign({}, self.curr, patch);
@@ -438,7 +395,7 @@ var SafeContext = class {
438
395
  throw new Error("Can no longer patch stale context");
439
396
  }
440
397
  }
441
- });
398
+ };
442
399
  callback(patchableContext);
443
400
  allowed = false;
444
401
  return;
@@ -650,8 +607,7 @@ var FSM = class {
650
607
  });
651
608
  }
652
609
  getTargetFn(eventName) {
653
- var _a;
654
- return (_a = this.allowedTransitions.get(this.currentState)) == null ? void 0 : _a.get(eventName);
610
+ return _optionalChain([this, 'access', _9 => _9.allowedTransitions, 'access', _10 => _10.get, 'call', _11 => _11(this.currentState), 'optionalAccess', _12 => _12.get, 'call', _13 => _13(eventName)]);
655
611
  }
656
612
  /**
657
613
  * Exits the current state, and executes any necessary cleanup functions.
@@ -666,10 +622,9 @@ var FSM = class {
666
622
  exit(levels) {
667
623
  this.eventHub.willExitState.notify(this.currentState);
668
624
  this.currentContext.allowPatching((patchableContext) => {
669
- var _a;
670
- levels = levels != null ? levels : this.cleanupStack.length;
625
+ levels = _nullishCoalesce(levels, () => ( this.cleanupStack.length));
671
626
  for (let i = 0; i < levels; i++) {
672
- (_a = this.cleanupStack.pop()) == null ? void 0 : _a(patchableContext);
627
+ _optionalChain([this, 'access', _14 => _14.cleanupStack, 'access', _15 => _15.pop, 'call', _16 => _16(), 'optionalCall', _17 => _17(patchableContext)]);
673
628
  }
674
629
  });
675
630
  }
@@ -680,12 +635,12 @@ var FSM = class {
680
635
  enter(levels) {
681
636
  const enterPatterns = patterns(
682
637
  this.currentState,
683
- levels != null ? levels : this.currentState.split(".").length + 1
638
+ _nullishCoalesce(levels, () => ( this.currentState.split(".").length + 1))
684
639
  );
685
640
  this.currentContext.allowPatching((patchableContext) => {
686
641
  for (const pattern of enterPatterns) {
687
642
  const enterFn = this.enterFns.get(pattern);
688
- const cleanupFn = enterFn == null ? void 0 : enterFn(patchableContext);
643
+ const cleanupFn = _optionalChain([enterFn, 'optionalCall', _18 => _18(patchableContext)]);
689
644
  if (typeof cleanupFn === "function") {
690
645
  this.cleanupStack.push(cleanupFn);
691
646
  } else {
@@ -761,13 +716,6 @@ var FSM = class {
761
716
  function isPlainObject(blob) {
762
717
  return blob !== null && typeof blob === "object" && Object.prototype.toString.call(blob) === "[object Object]";
763
718
  }
764
- function fromEntries(iterable) {
765
- const obj = {};
766
- for (const [key, val] of iterable) {
767
- obj[key] = val;
768
- }
769
- return obj;
770
- }
771
719
  function entries(obj) {
772
720
  return Object.entries(obj);
773
721
  }
@@ -797,7 +745,7 @@ function compact(items) {
797
745
  );
798
746
  }
799
747
  function compactObject(obj) {
800
- const newObj = __spreadValues({}, obj);
748
+ const newObj = { ...obj };
801
749
  Object.keys(obj).forEach((k) => {
802
750
  const key = k;
803
751
  if (newObj[key] === void 0) {
@@ -806,16 +754,14 @@ function compactObject(obj) {
806
754
  });
807
755
  return newObj;
808
756
  }
809
- function withTimeout(promise, millis, errmsg = "Timed out") {
810
- return __async(this, null, function* () {
811
- let timerID;
812
- const timer$ = new Promise((_, reject) => {
813
- timerID = setTimeout(() => {
814
- reject(new Error(errmsg));
815
- }, millis);
816
- });
817
- return Promise.race([promise, timer$]).finally(() => clearTimeout(timerID));
757
+ async function withTimeout(promise, millis, errmsg = "Timed out") {
758
+ let timerID;
759
+ const timer$ = new Promise((_, reject) => {
760
+ timerID = setTimeout(() => {
761
+ reject(new Error(errmsg));
762
+ }, millis);
818
763
  });
764
+ return Promise.race([promise, timer$]).finally(() => clearTimeout(timerID));
819
765
  }
820
766
 
821
767
  // src/connection.ts
@@ -873,8 +819,7 @@ var LiveblocksError = class extends Error {
873
819
  }
874
820
  };
875
821
  function nextBackoffDelay(currentDelay, delays = BACKOFF_DELAYS) {
876
- var _a;
877
- return (_a = delays.find((delay) => delay > currentDelay)) != null ? _a : delays[delays.length - 1];
822
+ return _nullishCoalesce(delays.find((delay) => delay > currentDelay), () => ( delays[delays.length - 1]));
878
823
  }
879
824
  function increaseBackoffDelay(context) {
880
825
  context.patch({ backoffDelay: nextBackoffDelay(context.backoffDelay) });
@@ -1072,7 +1017,7 @@ function createConnectionStateMachine(delegates, enableDebugLogging) {
1072
1017
  // When the "open" event happens, we're ready to transition to the
1073
1018
  // OK state. This is done by resolving the Promise.
1074
1019
  //
1075
- (ctx) => __async(this, null, function* () {
1020
+ async (ctx) => {
1076
1021
  let capturedPrematureEvent = null;
1077
1022
  const connect$ = new Promise(
1078
1023
  (resolve, rej) => {
@@ -1121,7 +1066,7 @@ function createConnectionStateMachine(delegates, enableDebugLogging) {
1121
1066
  return socket;
1122
1067
  }
1123
1068
  );
1124
- }),
1069
+ },
1125
1070
  // Only transition to OK state after a successfully opened WebSocket connection
1126
1071
  (okEvent) => ({
1127
1072
  target: "@ok.connected",
@@ -1163,8 +1108,7 @@ function createConnectionStateMachine(delegates, enableDebugLogging) {
1163
1108
  const sendHeartbeat = {
1164
1109
  target: "@ok.awaiting-pong",
1165
1110
  effect: (ctx) => {
1166
- var _a;
1167
- (_a = ctx.socket) == null ? void 0 : _a.send("ping");
1111
+ _optionalChain([ctx, 'access', _19 => _19.socket, 'optionalAccess', _20 => _20.send, 'call', _21 => _21("ping")]);
1168
1112
  }
1169
1113
  };
1170
1114
  machine.addTimedTransition("@ok.connected", HEARTBEAT_INTERVAL, sendHeartbeat).addTransitions("@ok.connected", {
@@ -1199,8 +1143,7 @@ function createConnectionStateMachine(delegates, enableDebugLogging) {
1199
1143
  // socket, or not. So always check to see if the socket is still OPEN or
1200
1144
  // not. When still OPEN, don't transition.
1201
1145
  EXPLICIT_SOCKET_ERROR: (_, context) => {
1202
- var _a;
1203
- if (((_a = context.socket) == null ? void 0 : _a.readyState) === 1) {
1146
+ if (_optionalChain([context, 'access', _22 => _22.socket, 'optionalAccess', _23 => _23.readyState]) === 1) {
1204
1147
  return null;
1205
1148
  }
1206
1149
  return {
@@ -1243,7 +1186,7 @@ function createConnectionStateMachine(delegates, enableDebugLogging) {
1243
1186
  if (typeof document !== "undefined") {
1244
1187
  const doc = typeof document !== "undefined" ? document : void 0;
1245
1188
  const win = typeof window !== "undefined" ? window : void 0;
1246
- const root = win != null ? win : doc;
1189
+ const root = _nullishCoalesce(win, () => ( doc));
1247
1190
  machine.onEnter("*", (ctx) => {
1248
1191
  function onNetworkOffline() {
1249
1192
  machine.send({ type: "NAVIGATOR_OFFLINE" });
@@ -1252,17 +1195,17 @@ function createConnectionStateMachine(delegates, enableDebugLogging) {
1252
1195
  machine.send({ type: "NAVIGATOR_ONLINE" });
1253
1196
  }
1254
1197
  function onVisibilityChange() {
1255
- if ((doc == null ? void 0 : doc.visibilityState) === "visible") {
1198
+ if (_optionalChain([doc, 'optionalAccess', _24 => _24.visibilityState]) === "visible") {
1256
1199
  machine.send({ type: "WINDOW_GOT_FOCUS" });
1257
1200
  }
1258
1201
  }
1259
- win == null ? void 0 : win.addEventListener("online", onNetworkBackOnline);
1260
- win == null ? void 0 : win.addEventListener("offline", onNetworkOffline);
1261
- root == null ? void 0 : root.addEventListener("visibilitychange", onVisibilityChange);
1202
+ _optionalChain([win, 'optionalAccess', _25 => _25.addEventListener, 'call', _26 => _26("online", onNetworkBackOnline)]);
1203
+ _optionalChain([win, 'optionalAccess', _27 => _27.addEventListener, 'call', _28 => _28("offline", onNetworkOffline)]);
1204
+ _optionalChain([root, 'optionalAccess', _29 => _29.addEventListener, 'call', _30 => _30("visibilitychange", onVisibilityChange)]);
1262
1205
  return () => {
1263
- root == null ? void 0 : root.removeEventListener("visibilitychange", onVisibilityChange);
1264
- win == null ? void 0 : win.removeEventListener("online", onNetworkBackOnline);
1265
- win == null ? void 0 : win.removeEventListener("offline", onNetworkOffline);
1206
+ _optionalChain([root, 'optionalAccess', _31 => _31.removeEventListener, 'call', _32 => _32("visibilitychange", onVisibilityChange)]);
1207
+ _optionalChain([win, 'optionalAccess', _33 => _33.removeEventListener, 'call', _34 => _34("online", onNetworkBackOnline)]);
1208
+ _optionalChain([win, 'optionalAccess', _35 => _35.removeEventListener, 'call', _36 => _36("offline", onNetworkOffline)]);
1266
1209
  teardownSocket(ctx.socket);
1267
1210
  };
1268
1211
  });
@@ -1303,7 +1246,7 @@ var ManagedSocket = class {
1303
1246
  getStatus() {
1304
1247
  try {
1305
1248
  return toNewConnectionStatus(this.machine);
1306
- } catch (e) {
1249
+ } catch (e2) {
1307
1250
  return "initial";
1308
1251
  }
1309
1252
  }
@@ -1351,8 +1294,7 @@ var ManagedSocket = class {
1351
1294
  * message if this is somehow impossible.
1352
1295
  */
1353
1296
  send(data) {
1354
- var _a;
1355
- const socket = (_a = this.machine.context) == null ? void 0 : _a.socket;
1297
+ const socket = _optionalChain([this, 'access', _37 => _37.machine, 'access', _38 => _38.context, 'optionalAccess', _39 => _39.socket]);
1356
1298
  if (socket === null) {
1357
1299
  warn("Cannot send: not connected yet", data);
1358
1300
  } else if (socket.readyState !== 1) {
@@ -1731,7 +1673,7 @@ var LiveRegister = class _LiveRegister extends AbstractCrdt {
1731
1673
  return [
1732
1674
  {
1733
1675
  type: 8 /* CREATE_REGISTER */,
1734
- opId: pool == null ? void 0 : pool.generateOpId(),
1676
+ opId: _optionalChain([pool, 'optionalAccess', _40 => _40.generateOpId, 'call', _41 => _41()]),
1735
1677
  id: this._id,
1736
1678
  parentId,
1737
1679
  parentKey,
@@ -1765,10 +1707,9 @@ var LiveRegister = class _LiveRegister extends AbstractCrdt {
1765
1707
  }
1766
1708
  /** @internal */
1767
1709
  _toTreeNode(key) {
1768
- var _a;
1769
1710
  return {
1770
1711
  type: "Json",
1771
- id: (_a = this._id) != null ? _a : nanoid(),
1712
+ id: _nullishCoalesce(this._id, () => ( nanoid())),
1772
1713
  key,
1773
1714
  payload: this._data
1774
1715
  };
@@ -1823,7 +1764,7 @@ var LiveList = class _LiveList extends AbstractCrdt {
1823
1764
  const ops = [];
1824
1765
  const op = {
1825
1766
  id: this._id,
1826
- opId: pool == null ? void 0 : pool.generateOpId(),
1767
+ opId: _optionalChain([pool, 'optionalAccess', _42 => _42.generateOpId, 'call', _43 => _43()]),
1827
1768
  type: 2 /* CREATE_LIST */,
1828
1769
  parentId,
1829
1770
  parentKey
@@ -2089,10 +2030,9 @@ var LiveList = class _LiveList extends AbstractCrdt {
2089
2030
  }
2090
2031
  /** @internal */
2091
2032
  _applyInsertUndoRedo(op) {
2092
- var _a, _b, _c;
2093
2033
  const { id, parentKey: key } = op;
2094
2034
  const child = creationOpToLiveNode(op);
2095
- if (((_a = this._pool) == null ? void 0 : _a.getNode(id)) !== void 0) {
2035
+ if (_optionalChain([this, 'access', _44 => _44._pool, 'optionalAccess', _45 => _45.getNode, 'call', _46 => _46(id)]) !== void 0) {
2096
2036
  return { modified: false };
2097
2037
  }
2098
2038
  child._attach(id, nn(this._pool));
@@ -2100,8 +2040,8 @@ var LiveList = class _LiveList extends AbstractCrdt {
2100
2040
  const existingItemIndex = this._indexOfPosition(key);
2101
2041
  let newKey = key;
2102
2042
  if (existingItemIndex !== -1) {
2103
- const before2 = (_b = this._items[existingItemIndex]) == null ? void 0 : _b._parentPos;
2104
- const after2 = (_c = this._items[existingItemIndex + 1]) == null ? void 0 : _c._parentPos;
2043
+ const before2 = _optionalChain([this, 'access', _47 => _47._items, 'access', _48 => _48[existingItemIndex], 'optionalAccess', _49 => _49._parentPos]);
2044
+ const after2 = _optionalChain([this, 'access', _50 => _50._items, 'access', _51 => _51[existingItemIndex + 1], 'optionalAccess', _52 => _52._parentPos]);
2105
2045
  newKey = makePosition(before2, after2);
2106
2046
  child._setParentLink(this, newKey);
2107
2047
  }
@@ -2114,10 +2054,9 @@ var LiveList = class _LiveList extends AbstractCrdt {
2114
2054
  }
2115
2055
  /** @internal */
2116
2056
  _applySetUndoRedo(op) {
2117
- var _a;
2118
2057
  const { id, parentKey: key } = op;
2119
2058
  const child = creationOpToLiveNode(op);
2120
- if (((_a = this._pool) == null ? void 0 : _a.getNode(id)) !== void 0) {
2059
+ if (_optionalChain([this, 'access', _53 => _53._pool, 'optionalAccess', _54 => _54.getNode, 'call', _55 => _55(id)]) !== void 0) {
2121
2060
  return { modified: false };
2122
2061
  }
2123
2062
  this._unacknowledgedSets.set(key, nn(op.opId));
@@ -2205,7 +2144,6 @@ var LiveList = class _LiveList extends AbstractCrdt {
2205
2144
  }
2206
2145
  /** @internal */
2207
2146
  _applySetChildKeyRemote(newKey, child) {
2208
- var _a;
2209
2147
  if (this._implicitlyDeletedItems.has(child)) {
2210
2148
  this._implicitlyDeletedItems.delete(child);
2211
2149
  child._setParentLink(this, newKey);
@@ -2240,7 +2178,7 @@ var LiveList = class _LiveList extends AbstractCrdt {
2240
2178
  } else {
2241
2179
  this._items[existingItemIndex]._setParentLink(
2242
2180
  this,
2243
- makePosition(newKey, (_a = this._items[existingItemIndex + 1]) == null ? void 0 : _a._parentPos)
2181
+ makePosition(newKey, _optionalChain([this, 'access', _56 => _56._items, 'access', _57 => _57[existingItemIndex + 1], 'optionalAccess', _58 => _58._parentPos]))
2244
2182
  );
2245
2183
  const previousIndex = this._items.indexOf(child);
2246
2184
  child._setParentLink(this, newKey);
@@ -2259,7 +2197,6 @@ var LiveList = class _LiveList extends AbstractCrdt {
2259
2197
  }
2260
2198
  /** @internal */
2261
2199
  _applySetChildKeyAck(newKey, child) {
2262
- var _a, _b;
2263
2200
  const previousKey = nn(child._parentKey);
2264
2201
  if (this._implicitlyDeletedItems.has(child)) {
2265
2202
  const existingItemIndex = this._indexOfPosition(newKey);
@@ -2267,7 +2204,7 @@ var LiveList = class _LiveList extends AbstractCrdt {
2267
2204
  if (existingItemIndex !== -1) {
2268
2205
  this._items[existingItemIndex]._setParentLink(
2269
2206
  this,
2270
- makePosition(newKey, (_a = this._items[existingItemIndex + 1]) == null ? void 0 : _a._parentPos)
2207
+ makePosition(newKey, _optionalChain([this, 'access', _59 => _59._items, 'access', _60 => _60[existingItemIndex + 1], 'optionalAccess', _61 => _61._parentPos]))
2271
2208
  );
2272
2209
  }
2273
2210
  child._setParentLink(this, newKey);
@@ -2286,7 +2223,7 @@ var LiveList = class _LiveList extends AbstractCrdt {
2286
2223
  if (existingItemIndex !== -1) {
2287
2224
  this._items[existingItemIndex]._setParentLink(
2288
2225
  this,
2289
- makePosition(newKey, (_b = this._items[existingItemIndex + 1]) == null ? void 0 : _b._parentPos)
2226
+ makePosition(newKey, _optionalChain([this, 'access', _62 => _62._items, 'access', _63 => _63[existingItemIndex + 1], 'optionalAccess', _64 => _64._parentPos]))
2290
2227
  );
2291
2228
  }
2292
2229
  child._setParentLink(this, newKey);
@@ -2308,14 +2245,13 @@ var LiveList = class _LiveList extends AbstractCrdt {
2308
2245
  }
2309
2246
  /** @internal */
2310
2247
  _applySetChildKeyUndoRedo(newKey, child) {
2311
- var _a;
2312
2248
  const previousKey = nn(child._parentKey);
2313
2249
  const previousIndex = this._items.indexOf(child);
2314
2250
  const existingItemIndex = this._indexOfPosition(newKey);
2315
2251
  if (existingItemIndex !== -1) {
2316
2252
  this._items[existingItemIndex]._setParentLink(
2317
2253
  this,
2318
- makePosition(newKey, (_a = this._items[existingItemIndex + 1]) == null ? void 0 : _a._parentPos)
2254
+ makePosition(newKey, _optionalChain([this, 'access', _65 => _65._items, 'access', _66 => _66[existingItemIndex + 1], 'optionalAccess', _67 => _67._parentPos]))
2319
2255
  );
2320
2256
  }
2321
2257
  child._setParentLink(this, newKey);
@@ -2373,8 +2309,7 @@ var LiveList = class _LiveList extends AbstractCrdt {
2373
2309
  * @param element The element to add to the end of the LiveList.
2374
2310
  */
2375
2311
  push(element) {
2376
- var _a;
2377
- (_a = this._pool) == null ? void 0 : _a.assertStorageIsWritable();
2312
+ _optionalChain([this, 'access', _68 => _68._pool, 'optionalAccess', _69 => _69.assertStorageIsWritable, 'call', _70 => _70()]);
2378
2313
  return this.insert(element, this.length);
2379
2314
  }
2380
2315
  /**
@@ -2383,8 +2318,7 @@ var LiveList = class _LiveList extends AbstractCrdt {
2383
2318
  * @param index The index at which you want to insert the element.
2384
2319
  */
2385
2320
  insert(element, index) {
2386
- var _a;
2387
- (_a = this._pool) == null ? void 0 : _a.assertStorageIsWritable();
2321
+ _optionalChain([this, 'access', _71 => _71._pool, 'optionalAccess', _72 => _72.assertStorageIsWritable, 'call', _73 => _73()]);
2388
2322
  if (index < 0 || index > this._items.length) {
2389
2323
  throw new Error(
2390
2324
  `Cannot insert list item at index "${index}". index should be between 0 and ${this._items.length}`
@@ -2414,8 +2348,7 @@ var LiveList = class _LiveList extends AbstractCrdt {
2414
2348
  * @param targetIndex The index where the element should be after moving.
2415
2349
  */
2416
2350
  move(index, targetIndex) {
2417
- var _a;
2418
- (_a = this._pool) == null ? void 0 : _a.assertStorageIsWritable();
2351
+ _optionalChain([this, 'access', _74 => _74._pool, 'optionalAccess', _75 => _75.assertStorageIsWritable, 'call', _76 => _76()]);
2419
2352
  if (targetIndex < 0) {
2420
2353
  throw new Error("targetIndex cannot be less than 0");
2421
2354
  }
@@ -2473,8 +2406,7 @@ var LiveList = class _LiveList extends AbstractCrdt {
2473
2406
  * @param index The index of the element to delete
2474
2407
  */
2475
2408
  delete(index) {
2476
- var _a;
2477
- (_a = this._pool) == null ? void 0 : _a.assertStorageIsWritable();
2409
+ _optionalChain([this, 'access', _77 => _77._pool, 'optionalAccess', _78 => _78.assertStorageIsWritable, 'call', _79 => _79()]);
2478
2410
  if (index < 0 || index >= this._items.length) {
2479
2411
  throw new Error(
2480
2412
  `Cannot delete list item at index "${index}". index should be between 0 and ${this._items.length - 1}`
@@ -2507,8 +2439,7 @@ var LiveList = class _LiveList extends AbstractCrdt {
2507
2439
  }
2508
2440
  }
2509
2441
  clear() {
2510
- var _a;
2511
- (_a = this._pool) == null ? void 0 : _a.assertStorageIsWritable();
2442
+ _optionalChain([this, 'access', _80 => _80._pool, 'optionalAccess', _81 => _81.assertStorageIsWritable, 'call', _82 => _82()]);
2512
2443
  if (this._pool) {
2513
2444
  const ops = [];
2514
2445
  const reverseOps = [];
@@ -2542,8 +2473,7 @@ var LiveList = class _LiveList extends AbstractCrdt {
2542
2473
  }
2543
2474
  }
2544
2475
  set(index, item) {
2545
- var _a;
2546
- (_a = this._pool) == null ? void 0 : _a.assertStorageIsWritable();
2476
+ _optionalChain([this, 'access', _83 => _83._pool, 'optionalAccess', _84 => _84.assertStorageIsWritable, 'call', _85 => _85()]);
2547
2477
  if (index < 0 || index >= this._items.length) {
2548
2478
  throw new Error(
2549
2479
  `Cannot set list item at index "${index}". index should be between 0 and ${this._items.length - 1}`
@@ -2689,19 +2619,17 @@ var LiveList = class _LiveList extends AbstractCrdt {
2689
2619
  }
2690
2620
  /** @internal */
2691
2621
  _shiftItemPosition(index, key) {
2692
- var _a;
2693
2622
  const shiftedPosition = makePosition(
2694
2623
  key,
2695
- this._items.length > index + 1 ? (_a = this._items[index + 1]) == null ? void 0 : _a._parentPos : void 0
2624
+ this._items.length > index + 1 ? _optionalChain([this, 'access', _86 => _86._items, 'access', _87 => _87[index + 1], 'optionalAccess', _88 => _88._parentPos]) : void 0
2696
2625
  );
2697
2626
  this._items[index]._setParentLink(this, shiftedPosition);
2698
2627
  }
2699
2628
  /** @internal */
2700
2629
  _toTreeNode(key) {
2701
- var _a;
2702
2630
  return {
2703
2631
  type: "LiveList",
2704
- id: (_a = this._id) != null ? _a : nanoid(),
2632
+ id: _nullishCoalesce(this._id, () => ( nanoid())),
2705
2633
  key,
2706
2634
  payload: this._items.map(
2707
2635
  (item, index) => item.toTreeNode(index.toString())
@@ -2775,10 +2703,11 @@ function HACK_addIntentAndDeletedIdToOperation(ops, deletedId) {
2775
2703
  return ops.map((op, index) => {
2776
2704
  if (index === 0) {
2777
2705
  const firstOp = op;
2778
- return __spreadProps(__spreadValues({}, firstOp), {
2706
+ return {
2707
+ ...firstOp,
2779
2708
  intent: "set",
2780
2709
  deletedId
2781
- });
2710
+ };
2782
2711
  } else {
2783
2712
  return op;
2784
2713
  }
@@ -2818,7 +2747,7 @@ var LiveMap = class _LiveMap extends AbstractCrdt {
2818
2747
  const ops = [];
2819
2748
  const op = {
2820
2749
  id: this._id,
2821
- opId: pool == null ? void 0 : pool.generateOpId(),
2750
+ opId: _optionalChain([pool, 'optionalAccess', _89 => _89.generateOpId, 'call', _90 => _90()]),
2822
2751
  type: 7 /* CREATE_MAP */,
2823
2752
  parentId,
2824
2753
  parentKey
@@ -2965,8 +2894,7 @@ var LiveMap = class _LiveMap extends AbstractCrdt {
2965
2894
  * @param value The value of the element to add. Should be serializable to JSON.
2966
2895
  */
2967
2896
  set(key, value) {
2968
- var _a;
2969
- (_a = this._pool) == null ? void 0 : _a.assertStorageIsWritable();
2897
+ _optionalChain([this, 'access', _91 => _91._pool, 'optionalAccess', _92 => _92.assertStorageIsWritable, 'call', _93 => _93()]);
2970
2898
  const oldValue = this._map.get(key);
2971
2899
  if (oldValue) {
2972
2900
  oldValue._detach();
@@ -3012,8 +2940,7 @@ var LiveMap = class _LiveMap extends AbstractCrdt {
3012
2940
  * @returns true if an element existed and has been removed, or false if the element does not exist.
3013
2941
  */
3014
2942
  delete(key) {
3015
- var _a;
3016
- (_a = this._pool) == null ? void 0 : _a.assertStorageIsWritable();
2943
+ _optionalChain([this, 'access', _94 => _94._pool, 'optionalAccess', _95 => _95.assertStorageIsWritable, 'call', _96 => _96()]);
3017
2944
  const item = this._map.get(key);
3018
2945
  if (item === void 0) {
3019
2946
  return false;
@@ -3114,10 +3041,9 @@ var LiveMap = class _LiveMap extends AbstractCrdt {
3114
3041
  }
3115
3042
  /** @internal */
3116
3043
  _toTreeNode(key) {
3117
- var _a;
3118
3044
  return {
3119
3045
  type: "LiveMap",
3120
- id: (_a = this._id) != null ? _a : nanoid(),
3046
+ id: _nullishCoalesce(this._id, () => ( nanoid())),
3121
3047
  key,
3122
3048
  payload: Array.from(this._map.entries()).map(
3123
3049
  ([key2, val]) => val.toTreeNode(key2)
@@ -3188,7 +3114,7 @@ var LiveObject = class _LiveObject extends AbstractCrdt {
3188
3114
  if (this._id === void 0) {
3189
3115
  throw new Error("Cannot serialize item is not attached");
3190
3116
  }
3191
- const opId = pool == null ? void 0 : pool.generateOpId();
3117
+ const opId = _optionalChain([pool, 'optionalAccess', _97 => _97.generateOpId, 'call', _98 => _98()]);
3192
3118
  const ops = [];
3193
3119
  const op = parentId !== void 0 && parentKey !== void 0 ? {
3194
3120
  type: 4 /* CREATE_OBJECT */,
@@ -3461,7 +3387,7 @@ var LiveObject = class _LiveObject extends AbstractCrdt {
3461
3387
  * Transform the LiveObject into a javascript object
3462
3388
  */
3463
3389
  toObject() {
3464
- return fromEntries(this._map);
3390
+ return Object.fromEntries(this._map);
3465
3391
  }
3466
3392
  /**
3467
3393
  * Adds or updates a property with a specified key and a value.
@@ -3469,8 +3395,7 @@ var LiveObject = class _LiveObject extends AbstractCrdt {
3469
3395
  * @param value The value of the property to add
3470
3396
  */
3471
3397
  set(key, value) {
3472
- var _a;
3473
- (_a = this._pool) == null ? void 0 : _a.assertStorageIsWritable();
3398
+ _optionalChain([this, 'access', _99 => _99._pool, 'optionalAccess', _100 => _100.assertStorageIsWritable, 'call', _101 => _101()]);
3474
3399
  this.update({ [key]: value });
3475
3400
  }
3476
3401
  /**
@@ -3485,8 +3410,7 @@ var LiveObject = class _LiveObject extends AbstractCrdt {
3485
3410
  * @param key The key of the property to delete
3486
3411
  */
3487
3412
  delete(key) {
3488
- var _a;
3489
- (_a = this._pool) == null ? void 0 : _a.assertStorageIsWritable();
3413
+ _optionalChain([this, 'access', _102 => _102._pool, 'optionalAccess', _103 => _103.assertStorageIsWritable, 'call', _104 => _104()]);
3490
3414
  const keyAsString = key;
3491
3415
  const oldValue = this._map.get(keyAsString);
3492
3416
  if (oldValue === void 0) {
@@ -3539,8 +3463,7 @@ var LiveObject = class _LiveObject extends AbstractCrdt {
3539
3463
  * @param patch The object used to overrides properties
3540
3464
  */
3541
3465
  update(patch) {
3542
- var _a;
3543
- (_a = this._pool) == null ? void 0 : _a.assertStorageIsWritable();
3466
+ _optionalChain([this, 'access', _105 => _105._pool, 'optionalAccess', _106 => _106.assertStorageIsWritable, 'call', _107 => _107()]);
3544
3467
  if (this._pool === void 0 || this._id === void 0) {
3545
3468
  for (const key in patch) {
3546
3469
  const newValue = patch[key];
@@ -3630,8 +3553,7 @@ var LiveObject = class _LiveObject extends AbstractCrdt {
3630
3553
  }
3631
3554
  /** @internal */
3632
3555
  _toTreeNode(key) {
3633
- var _a;
3634
- const nodeId = (_a = this._id) != null ? _a : nanoid();
3556
+ const nodeId = _nullishCoalesce(this._id, () => ( nanoid()));
3635
3557
  return {
3636
3558
  type: "LiveObject",
3637
3559
  id: nodeId,
@@ -3830,24 +3752,27 @@ function mergeObjectStorageUpdates(first, second) {
3830
3752
  for (const [key, value] of entries(second.updates)) {
3831
3753
  updates[key] = value;
3832
3754
  }
3833
- return __spreadProps(__spreadValues({}, second), {
3755
+ return {
3756
+ ...second,
3834
3757
  updates
3835
- });
3758
+ };
3836
3759
  }
3837
3760
  function mergeMapStorageUpdates(first, second) {
3838
3761
  const updates = first.updates;
3839
3762
  for (const [key, value] of entries(second.updates)) {
3840
3763
  updates[key] = value;
3841
3764
  }
3842
- return __spreadProps(__spreadValues({}, second), {
3765
+ return {
3766
+ ...second,
3843
3767
  updates
3844
- });
3768
+ };
3845
3769
  }
3846
3770
  function mergeListStorageUpdates(first, second) {
3847
3771
  const updates = first.updates;
3848
- return __spreadProps(__spreadValues({}, second), {
3772
+ return {
3773
+ ...second,
3849
3774
  updates: updates.concat(second.updates)
3850
- });
3775
+ };
3851
3776
  }
3852
3777
  function mergeStorageUpdates(first, second) {
3853
3778
  if (first === void 0) {
@@ -3989,7 +3914,7 @@ function asArrayWithLegacyMethods(arr) {
3989
3914
  // src/refs/ImmutableRef.ts
3990
3915
  function merge(target, patch) {
3991
3916
  let updated = false;
3992
- const newValue = __spreadValues({}, target);
3917
+ const newValue = { ...target };
3993
3918
  Object.keys(patch).forEach((k) => {
3994
3919
  const key = k;
3995
3920
  const val = patch[key];
@@ -4018,14 +3943,13 @@ var ImmutableRef = class {
4018
3943
  }
4019
3944
  }
4020
3945
  get current() {
4021
- var _a;
4022
- return (_a = this._cache) != null ? _a : this._cache = this._toImmutable();
3946
+ return _nullishCoalesce(this._cache, () => ( (this._cache = this._toImmutable())));
4023
3947
  }
4024
3948
  };
4025
3949
 
4026
3950
  // src/refs/OthersRef.ts
4027
3951
  function makeUser(conn, presence) {
4028
- return freeze(compactObject(__spreadProps(__spreadValues({}, conn), { presence })));
3952
+ return freeze(compactObject({ ...conn, presence }));
4029
3953
  }
4030
3954
  var OthersRef = class extends ImmutableRef {
4031
3955
  //
@@ -4204,20 +4128,19 @@ function userToTreeNode(key, user) {
4204
4128
  };
4205
4129
  }
4206
4130
  function createRoom(options, config) {
4207
- var _a, _b, _c, _d;
4208
4131
  const initialPresence = typeof options.initialPresence === "function" ? options.initialPresence(config.roomId) : options.initialPresence;
4209
4132
  const initialStorage = typeof options.initialStorage === "function" ? options.initialStorage(config.roomId) : options.initialStorage;
4210
- const delegates = (_c = config.delegates) != null ? _c : {
4133
+ const delegates = _nullishCoalesce(config.delegates, () => ( {
4211
4134
  authenticate: makeAuthDelegateForRoom(
4212
4135
  config.roomId,
4213
4136
  config.authentication,
4214
- (_a = config.polyfills) == null ? void 0 : _a.fetch
4137
+ _optionalChain([config, 'access', _108 => _108.polyfills, 'optionalAccess', _109 => _109.fetch])
4215
4138
  ),
4216
4139
  createSocket: makeCreateSocketDelegateForRoom(
4217
4140
  config.liveblocksServer,
4218
- (_b = config.polyfills) == null ? void 0 : _b.WebSocket
4141
+ _optionalChain([config, 'access', _110 => _110.polyfills, 'optionalAccess', _111 => _111.WebSocket])
4219
4142
  )
4220
- };
4143
+ }));
4221
4144
  const managedSocket = new ManagedSocket(
4222
4145
  delegates,
4223
4146
  config.enableDebugLogging
@@ -4255,11 +4178,10 @@ function createRoom(options, config) {
4255
4178
  opStackTraces: process.env.NODE_ENV !== "production" ? /* @__PURE__ */ new Map() : void 0
4256
4179
  };
4257
4180
  const doNotBatchUpdates = (cb) => cb();
4258
- const batchUpdates = (_d = config.unstable_batchedUpdates) != null ? _d : doNotBatchUpdates;
4181
+ const batchUpdates = _nullishCoalesce(config.unstable_batchedUpdates, () => ( doNotBatchUpdates));
4259
4182
  let lastToken;
4260
4183
  function onStatusDidChange(newStatus) {
4261
- var _a2;
4262
- const token = (_a2 = managedSocket.token) == null ? void 0 : _a2.parsed;
4184
+ const token = _optionalChain([managedSocket, 'access', _112 => _112.token, 'optionalAccess', _113 => _113.parsed]);
4263
4185
  if (token !== void 0 && token !== lastToken) {
4264
4186
  context.sessionInfo.set({
4265
4187
  userInfo: token.info,
@@ -4314,7 +4236,7 @@ function createRoom(options, config) {
4314
4236
  // Because context.me.current is a readonly object, we'll have to
4315
4237
  // make a copy here. Otherwise, type errors happen later when
4316
4238
  // "patching" my presence.
4317
- __spreadValues({}, context.me.current)
4239
+ { ...context.me.current }
4318
4240
  )
4319
4241
  };
4320
4242
  context.idFactory = makeIdFactory(sessionInfo.actor);
@@ -4382,8 +4304,7 @@ function createRoom(options, config) {
4382
4304
  }
4383
4305
  },
4384
4306
  assertStorageIsWritable: () => {
4385
- var _a2;
4386
- if ((_a2 = context.sessionInfo.current) == null ? void 0 : _a2.isReadOnly) {
4307
+ if (_optionalChain([context, 'access', _114 => _114.sessionInfo, 'access', _115 => _115.current, 'optionalAccess', _116 => _116.isReadOnly])) {
4387
4308
  throw new Error(
4388
4309
  "Cannot write to storage with a read only user, please ensure the user has write permissions"
4389
4310
  );
@@ -4407,11 +4328,10 @@ function createRoom(options, config) {
4407
4328
  ydoc: makeEventSource()
4408
4329
  };
4409
4330
  function sendMessages(messageOrMessages) {
4410
- var _a2, _b2;
4411
4331
  const message = JSON.stringify(messageOrMessages);
4412
4332
  if (config.unstable_fallbackToHTTP) {
4413
4333
  const size = new TextEncoder().encode(message).length;
4414
- if (size > MAX_MESSAGE_SIZE && ((_a2 = managedSocket.token) == null ? void 0 : _a2.raw) && config.httpSendEndpoint) {
4334
+ if (size > MAX_MESSAGE_SIZE && _optionalChain([managedSocket, 'access', _117 => _117.token, 'optionalAccess', _118 => _118.raw]) && config.httpSendEndpoint) {
4415
4335
  if (isTokenExpired(managedSocket.token.parsed)) {
4416
4336
  return managedSocket.reconnect();
4417
4337
  }
@@ -4419,7 +4339,7 @@ function createRoom(options, config) {
4419
4339
  message,
4420
4340
  managedSocket.token.raw,
4421
4341
  config.httpSendEndpoint,
4422
- (_b2 = config.polyfills) == null ? void 0 : _b2.fetch
4342
+ _optionalChain([config, 'access', _119 => _119.polyfills, 'optionalAccess', _120 => _120.fetch])
4423
4343
  );
4424
4344
  warn(
4425
4345
  "Message was too large for websockets and sent over HTTP instead"
@@ -4526,7 +4446,7 @@ function createRoom(options, config) {
4526
4446
  const createdNodeIds = /* @__PURE__ */ new Set();
4527
4447
  const ops = rawOps.map((op) => {
4528
4448
  if (op.type !== "presence" && !op.opId) {
4529
- return __spreadProps(__spreadValues({}, op), { opId: pool.generateOpId() });
4449
+ return { ...op, opId: pool.generateOpId() };
4530
4450
  } else {
4531
4451
  return op;
4532
4452
  }
@@ -4652,7 +4572,7 @@ function createRoom(options, config) {
4652
4572
  }
4653
4573
  context.me.patch(patch);
4654
4574
  if (context.activeBatch) {
4655
- if (options2 == null ? void 0 : options2.addToHistory) {
4575
+ if (_optionalChain([options2, 'optionalAccess', _121 => _121.addToHistory])) {
4656
4576
  context.activeBatch.reverseOps.unshift({
4657
4577
  type: "presence",
4658
4578
  data: oldValues
@@ -4662,7 +4582,7 @@ function createRoom(options, config) {
4662
4582
  } else {
4663
4583
  flushNowOrSoon();
4664
4584
  batchUpdates(() => {
4665
- if (options2 == null ? void 0 : options2.addToHistory) {
4585
+ if (_optionalChain([options2, 'optionalAccess', _122 => _122.addToHistory])) {
4666
4586
  addToUndoStack(
4667
4587
  [{ type: "presence", data: oldValues }],
4668
4588
  doNotBatchUpdates
@@ -4794,7 +4714,6 @@ function createRoom(options, config) {
4794
4714
  others: []
4795
4715
  };
4796
4716
  batchUpdates(() => {
4797
- var _a2;
4798
4717
  for (const message of messages) {
4799
4718
  switch (message.type) {
4800
4719
  case 101 /* USER_JOINED */: {
@@ -4837,7 +4756,7 @@ function createRoom(options, config) {
4837
4756
  const unacknowledgedOps = new Map(context.unacknowledgedOps);
4838
4757
  createOrUpdateRootFromMessage(message, doNotBatchUpdates);
4839
4758
  applyAndSendOps(unacknowledgedOps, doNotBatchUpdates);
4840
- _resolveStoragePromise == null ? void 0 : _resolveStoragePromise();
4759
+ _optionalChain([_resolveStoragePromise, 'optionalCall', _123 => _123()]);
4841
4760
  notifyStorageStatus();
4842
4761
  eventHub.storageDidLoad.notify();
4843
4762
  break;
@@ -4860,7 +4779,7 @@ function createRoom(options, config) {
4860
4779
  if (process.env.NODE_ENV !== "production") {
4861
4780
  const traces = /* @__PURE__ */ new Set();
4862
4781
  for (const opId of message.opIds) {
4863
- const trace = (_a2 = context.opStackTraces) == null ? void 0 : _a2.get(opId);
4782
+ const trace = _optionalChain([context, 'access', _124 => _124.opStackTraces, 'optionalAccess', _125 => _125.get, 'call', _126 => _126(opId)]);
4864
4783
  if (trace) {
4865
4784
  traces.add(trace);
4866
4785
  }
@@ -5000,18 +4919,16 @@ ${Array.from(traces).join("\n\n")}`
5000
4919
  return null;
5001
4920
  }
5002
4921
  }
5003
- function getStorage() {
5004
- return __async(this, null, function* () {
5005
- if (context.root !== void 0) {
5006
- return Promise.resolve({
5007
- root: context.root
5008
- });
5009
- }
5010
- yield startLoadingStorage();
5011
- return {
5012
- root: nn(context.root)
5013
- };
5014
- });
4922
+ async function getStorage() {
4923
+ if (context.root !== void 0) {
4924
+ return Promise.resolve({
4925
+ root: context.root
4926
+ });
4927
+ }
4928
+ await startLoadingStorage();
4929
+ return {
4930
+ root: nn(context.root)
4931
+ };
5015
4932
  }
5016
4933
  function fetchYDoc(vector) {
5017
4934
  context.buffer.messages.push({
@@ -5275,7 +5192,7 @@ function makeClassicSubscribeFn(events) {
5275
5192
  }
5276
5193
  if (isLiveNode(first)) {
5277
5194
  const node = first;
5278
- if (options == null ? void 0 : options.isDeep) {
5195
+ if (_optionalChain([options, 'optionalAccess', _127 => _127.isDeep])) {
5279
5196
  const storageCallback = second;
5280
5197
  return subscribeToLiveStructureDeeply(node, storageCallback);
5281
5198
  } else {
@@ -5292,7 +5209,7 @@ function isRoomEventName(value) {
5292
5209
  }
5293
5210
  function makeCreateSocketDelegateForRoom(liveblocksServer, WebSocketPolyfill) {
5294
5211
  return (richToken) => {
5295
- const ws = WebSocketPolyfill != null ? WebSocketPolyfill : typeof WebSocket === "undefined" ? void 0 : WebSocket;
5212
+ const ws = _nullishCoalesce(WebSocketPolyfill, () => ( (typeof WebSocket === "undefined" ? void 0 : WebSocket)));
5296
5213
  if (ws === void 0) {
5297
5214
  throw new StopRetrying(
5298
5215
  "To use Liveblocks client in a non-dom environment, you need to provide a WebSocket polyfill."
@@ -5305,29 +5222,27 @@ function makeCreateSocketDelegateForRoom(liveblocksServer, WebSocketPolyfill) {
5305
5222
  // @ts-ignore (__PACKAGE_VERSION__ will be injected by the build script)
5306
5223
  true ? (
5307
5224
  /* istanbul ignore next */
5308
- "1.2.0-internal4"
5225
+ "1.2.0-internal5"
5309
5226
  ) : "dev"}`
5310
5227
  );
5311
5228
  };
5312
5229
  }
5313
- function httpSend(message, token, endpoint, fetchPolyfill) {
5314
- return __async(this, null, function* () {
5315
- const fetcher = fetchPolyfill || /* istanbul ignore next */
5316
- fetch;
5317
- return fetcher(endpoint, {
5318
- method: "POST",
5319
- headers: {
5320
- "Content-Type": "application/json",
5321
- Authorization: `Bearer ${token}`
5322
- },
5323
- body: message
5324
- });
5230
+ async function httpSend(message, token, endpoint, fetchPolyfill) {
5231
+ const fetcher = fetchPolyfill || /* istanbul ignore next */
5232
+ fetch;
5233
+ return fetcher(endpoint, {
5234
+ method: "POST",
5235
+ headers: {
5236
+ "Content-Type": "application/json",
5237
+ Authorization: `Bearer ${token}`
5238
+ },
5239
+ body: message
5325
5240
  });
5326
5241
  }
5327
5242
  function makeAuthDelegateForRoom(roomId, authentication, fetchPolyfill) {
5328
- const fetcher = fetchPolyfill != null ? fetchPolyfill : typeof window === "undefined" ? void 0 : window.fetch;
5243
+ const fetcher = _nullishCoalesce(fetchPolyfill, () => ( (typeof window === "undefined" ? void 0 : window.fetch)));
5329
5244
  if (authentication.type === "public") {
5330
- return () => __async(this, null, function* () {
5245
+ return async () => {
5331
5246
  if (fetcher === void 0) {
5332
5247
  throw new StopRetrying(
5333
5248
  "To use Liveblocks client in a non-dom environment with a publicApiKey, you need to provide a fetch polyfill."
@@ -5337,9 +5252,9 @@ function makeAuthDelegateForRoom(roomId, authentication, fetchPolyfill) {
5337
5252
  room: roomId,
5338
5253
  publicApiKey: authentication.publicApiKey
5339
5254
  }).then(({ token }) => parseAuthToken(token));
5340
- });
5255
+ };
5341
5256
  } else if (authentication.type === "private") {
5342
- return () => __async(this, null, function* () {
5257
+ return async () => {
5343
5258
  if (fetcher === void 0) {
5344
5259
  throw new StopRetrying(
5345
5260
  "To use Liveblocks client in a non-dom environment with a url as auth endpoint, you need to provide a fetch polyfill."
@@ -5348,60 +5263,58 @@ function makeAuthDelegateForRoom(roomId, authentication, fetchPolyfill) {
5348
5263
  return fetchAuthEndpoint(fetcher, authentication.url, {
5349
5264
  room: roomId
5350
5265
  }).then(({ token }) => parseAuthToken(token));
5351
- });
5266
+ };
5352
5267
  } else if (authentication.type === "custom") {
5353
- return () => __async(this, null, function* () {
5354
- const response = yield authentication.callback(roomId);
5268
+ return async () => {
5269
+ const response = await authentication.callback(roomId);
5355
5270
  if (!response || !response.token) {
5356
5271
  throw new Error(
5357
5272
  'We expect the authentication callback to return a token, but it does not. Hint: the return value should look like: { token: "..." }'
5358
5273
  );
5359
5274
  }
5360
5275
  return parseAuthToken(response.token);
5361
- });
5276
+ };
5362
5277
  } else {
5363
5278
  throw new Error("Internal error. Unexpected authentication type");
5364
5279
  }
5365
5280
  }
5366
- function fetchAuthEndpoint(fetch2, endpoint, body) {
5367
- return __async(this, null, function* () {
5368
- const res = yield fetch2(endpoint, {
5369
- method: "POST",
5370
- headers: {
5371
- "Content-Type": "application/json"
5372
- },
5373
- // Credentials are needed to support authentication with cookies
5374
- credentials: "include",
5375
- body: JSON.stringify(body)
5376
- });
5377
- if (!res.ok) {
5378
- const reason = `${(yield res.text()).trim() || "reason not provided in auth response"} (${res.status} returned by POST ${endpoint})`;
5379
- if (res.status === 401 || res.status === 403) {
5380
- throw new StopRetrying(`Unauthorized: ${reason}`);
5381
- } else {
5382
- throw new Error(`Failed to authenticate: ${reason}`);
5383
- }
5384
- }
5385
- let data;
5386
- try {
5387
- data = yield res.json();
5388
- } catch (er) {
5389
- throw new Error(
5390
- `Expected a JSON response when doing a POST request on "${endpoint}". ${String(
5391
- er
5392
- )}`
5393
- );
5394
- }
5395
- if (!isPlainObject(data) || typeof data.token !== "string") {
5396
- throw new Error(
5397
- `Expected a JSON response of the form \`{ token: "..." }\` when doing a POST request on "${endpoint}", but got ${JSON.stringify(
5398
- data
5399
- )}`
5400
- );
5401
- }
5402
- const { token } = data;
5403
- return { token };
5281
+ async function fetchAuthEndpoint(fetch2, endpoint, body) {
5282
+ const res = await fetch2(endpoint, {
5283
+ method: "POST",
5284
+ headers: {
5285
+ "Content-Type": "application/json"
5286
+ },
5287
+ // Credentials are needed to support authentication with cookies
5288
+ credentials: "include",
5289
+ body: JSON.stringify(body)
5404
5290
  });
5291
+ if (!res.ok) {
5292
+ const reason = `${(await res.text()).trim() || "reason not provided in auth response"} (${res.status} returned by POST ${endpoint})`;
5293
+ if (res.status === 401 || res.status === 403) {
5294
+ throw new StopRetrying(`Unauthorized: ${reason}`);
5295
+ } else {
5296
+ throw new Error(`Failed to authenticate: ${reason}`);
5297
+ }
5298
+ }
5299
+ let data;
5300
+ try {
5301
+ data = await res.json();
5302
+ } catch (er) {
5303
+ throw new Error(
5304
+ `Expected a JSON response when doing a POST request on "${endpoint}". ${String(
5305
+ er
5306
+ )}`
5307
+ );
5308
+ }
5309
+ if (!isPlainObject(data) || typeof data.token !== "string") {
5310
+ throw new Error(
5311
+ `Expected a JSON response of the form \`{ token: "..." }\` when doing a POST request on "${endpoint}", but got ${JSON.stringify(
5312
+ data
5313
+ )}`
5314
+ );
5315
+ }
5316
+ const { token } = data;
5317
+ return { token };
5405
5318
  }
5406
5319
 
5407
5320
  // src/client.ts
@@ -5417,11 +5330,10 @@ function getServerFromClientOptions(clientOptions) {
5417
5330
  return typeof rawOptions.liveblocksServer === "string" ? rawOptions.liveblocksServer : "wss://api.liveblocks.io/v6";
5418
5331
  }
5419
5332
  function createClient(options) {
5420
- var _a, _b;
5421
5333
  const clientOptions = options;
5422
- const throttleDelay = getThrottle((_a = clientOptions.throttle) != null ? _a : DEFAULT_THROTTLE);
5334
+ const throttleDelay = getThrottle(_nullishCoalesce(clientOptions.throttle, () => ( DEFAULT_THROTTLE)));
5423
5335
  const lostConnectionTimeout = getLostConnectionTimeout(
5424
- (_b = clientOptions.lostConnectionTimeout) != null ? _b : DEFAULT_LOST_CONNECTION_TIMEOUT
5336
+ _nullishCoalesce(clientOptions.lostConnectionTimeout, () => ( DEFAULT_LOST_CONNECTION_TIMEOUT))
5425
5337
  );
5426
5338
  const rooms = /* @__PURE__ */ new Map();
5427
5339
  function getRoom(roomId) {
@@ -5429,7 +5341,6 @@ function createClient(options) {
5429
5341
  return room ? room : null;
5430
5342
  }
5431
5343
  function enter(roomId, options2) {
5432
- var _a2, _b2, _c;
5433
5344
  const existingRoom = rooms.get(roomId);
5434
5345
  if (existingRoom !== void 0) {
5435
5346
  return existingRoom;
@@ -5440,7 +5351,7 @@ function createClient(options) {
5440
5351
  );
5441
5352
  const newRoom = createRoom(
5442
5353
  {
5443
- initialPresence: (_a2 = options2.initialPresence) != null ? _a2 : {},
5354
+ initialPresence: _nullishCoalesce(options2.initialPresence, () => ( {})),
5444
5355
  initialStorage: options2.initialStorage
5445
5356
  },
5446
5357
  {
@@ -5450,7 +5361,7 @@ function createClient(options) {
5450
5361
  polyfills: clientOptions.polyfills,
5451
5362
  delegates: clientOptions.mockedDelegates,
5452
5363
  enableDebugLogging: clientOptions.enableDebugLogging,
5453
- unstable_batchedUpdates: options2 == null ? void 0 : options2.unstable_batchedUpdates,
5364
+ unstable_batchedUpdates: _optionalChain([options2, 'optionalAccess', _128 => _128.unstable_batchedUpdates]),
5454
5365
  liveblocksServer: getServerFromClientOptions(clientOptions),
5455
5366
  authentication: prepareAuthentication(clientOptions, roomId),
5456
5367
  httpSendEndpoint: buildLiveblocksHttpSendEndpoint(
@@ -5463,10 +5374,10 @@ function createClient(options) {
5463
5374
  rooms.set(roomId, newRoom);
5464
5375
  setupDevTools(() => Array.from(rooms.keys()));
5465
5376
  linkDevTools(roomId, newRoom);
5466
- const shouldConnect = (_b2 = options2.shouldInitiallyConnect) != null ? _b2 : true;
5377
+ const shouldConnect = _nullishCoalesce(options2.shouldInitiallyConnect, () => ( true));
5467
5378
  if (shouldConnect) {
5468
5379
  if (typeof atob === "undefined") {
5469
- if (((_c = clientOptions.polyfills) == null ? void 0 : _c.atob) === void 0) {
5380
+ if (_optionalChain([clientOptions, 'access', _129 => _129.polyfills, 'optionalAccess', _130 => _130.atob]) === void 0) {
5470
5381
  throw new Error(
5471
5382
  "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"
5472
5383
  );
@@ -5494,7 +5405,7 @@ function createClient(options) {
5494
5405
  function checkBounds(option, value, min, max, recommendedMin) {
5495
5406
  if (typeof value !== "number" || value < min || value > max) {
5496
5407
  throw new Error(
5497
- `${option} should be a number between ${recommendedMin != null ? recommendedMin : min} and ${max}.`
5408
+ `${option} should be a number between ${_nullishCoalesce(recommendedMin, () => ( min))} and ${max}.`
5498
5409
  );
5499
5410
  }
5500
5411
  return value;
@@ -5570,6 +5481,35 @@ function buildLiveblocksPublicAuthorizeEndpoint(options, roomId) {
5570
5481
  )}/public/authorize`;
5571
5482
  }
5572
5483
 
5484
+ // src/crdts/utils.ts
5485
+ function toPlainLson(lson) {
5486
+ if (lson instanceof LiveObject) {
5487
+ return {
5488
+ liveblocksType: "LiveObject",
5489
+ data: Object.fromEntries(
5490
+ Object.entries(lson.toObject()).map(([key, value]) => [
5491
+ key,
5492
+ value ? toPlainLson(value) : ""
5493
+ ])
5494
+ )
5495
+ };
5496
+ } else if (lson instanceof LiveMap) {
5497
+ return {
5498
+ liveblocksType: "LiveMap",
5499
+ data: Object.fromEntries(
5500
+ [...lson].map(([key, value]) => [key, toPlainLson(value)])
5501
+ )
5502
+ };
5503
+ } else if (lson instanceof LiveList) {
5504
+ return {
5505
+ liveblocksType: "LiveList",
5506
+ data: [...lson].map((item) => toPlainLson(item))
5507
+ };
5508
+ } else {
5509
+ return lson;
5510
+ }
5511
+ }
5512
+
5573
5513
  // src/immutable.ts
5574
5514
  function lsonObjectToJson(obj) {
5575
5515
  const result = {};
@@ -5759,7 +5699,6 @@ function legacy_patchImmutableObjectWithUpdate(state, update) {
5759
5699
  return legacy_patchImmutableNode(state, path, update);
5760
5700
  }
5761
5701
  function legacy_patchImmutableNode(state, path, update) {
5762
- var _a, _b, _c, _d;
5763
5702
  const pathItem = path.pop();
5764
5703
  if (pathItem === void 0) {
5765
5704
  switch (update.type) {
@@ -5771,12 +5710,12 @@ function legacy_patchImmutableNode(state, path, update) {
5771
5710
  }
5772
5711
  const newState = Object.assign({}, state);
5773
5712
  for (const key in update.updates) {
5774
- if (((_a = update.updates[key]) == null ? void 0 : _a.type) === "update") {
5713
+ if (_optionalChain([update, 'access', _131 => _131.updates, 'access', _132 => _132[key], 'optionalAccess', _133 => _133.type]) === "update") {
5775
5714
  const val = update.node.get(key);
5776
5715
  if (val !== void 0) {
5777
5716
  newState[key] = lsonToJson(val);
5778
5717
  }
5779
- } else if (((_b = update.updates[key]) == null ? void 0 : _b.type) === "delete") {
5718
+ } else if (_optionalChain([update, 'access', _134 => _134.updates, 'access', _135 => _135[key], 'optionalAccess', _136 => _136.type]) === "delete") {
5780
5719
  delete newState[key];
5781
5720
  }
5782
5721
  }
@@ -5837,12 +5776,12 @@ function legacy_patchImmutableNode(state, path, update) {
5837
5776
  }
5838
5777
  const newState = Object.assign({}, state);
5839
5778
  for (const key in update.updates) {
5840
- if (((_c = update.updates[key]) == null ? void 0 : _c.type) === "update") {
5779
+ if (_optionalChain([update, 'access', _137 => _137.updates, 'access', _138 => _138[key], 'optionalAccess', _139 => _139.type]) === "update") {
5841
5780
  const value = update.node.get(key);
5842
5781
  if (value !== void 0) {
5843
5782
  newState[key] = lsonToJson(value);
5844
5783
  }
5845
- } else if (((_d = update.updates[key]) == null ? void 0 : _d.type) === "delete") {
5784
+ } else if (_optionalChain([update, 'access', _140 => _140.updates, 'access', _141 => _141[key], 'optionalAccess', _142 => _142.type]) === "delete") {
5846
5785
  delete newState[key];
5847
5786
  }
5848
5787
  }
@@ -5864,9 +5803,10 @@ function legacy_patchImmutableNode(state, path, update) {
5864
5803
  return state;
5865
5804
  } else {
5866
5805
  const stateAsObj = state;
5867
- return __spreadProps(__spreadValues({}, stateAsObj), {
5806
+ return {
5807
+ ...stateAsObj,
5868
5808
  [pathItem]: legacy_patchImmutableNode(node, path, update)
5869
- });
5809
+ };
5870
5810
  }
5871
5811
  } else {
5872
5812
  return state;
@@ -5958,4 +5898,6 @@ var WebsocketCloseCodes = /* @__PURE__ */ ((WebsocketCloseCodes2) => {
5958
5898
 
5959
5899
 
5960
5900
 
5961
- exports.ClientMsgCode = ClientMsgCode; exports.CrdtType = CrdtType; exports.LiveList = LiveList; exports.LiveMap = LiveMap; exports.LiveObject = LiveObject; exports.OpCode = OpCode; exports.ServerMsgCode = ServerMsgCode; exports.WebsocketCloseCodes = WebsocketCloseCodes; exports.asArrayWithLegacyMethods = asArrayWithLegacyMethods; exports.asPos = asPos; exports.assert = assert; exports.assertNever = assertNever; exports.b64decode = b64decode; exports.createClient = createClient; exports.deprecate = deprecate; exports.deprecateIf = deprecateIf; exports.errorIf = errorIf; exports.freeze = freeze; exports.isChildCrdt = isChildCrdt; exports.isJsonArray = isJsonArray; exports.isJsonObject = isJsonObject; exports.isJsonScalar = isJsonScalar; exports.isPlainObject = isPlainObject; exports.isRootCrdt = isRootCrdt; exports.legacy_patchImmutableObject = legacy_patchImmutableObject; exports.lsonToJson = lsonToJson; exports.makePosition = makePosition; exports.nn = nn; exports.patchLiveObjectKey = patchLiveObjectKey; exports.shallow = shallow; exports.throwUsageError = throwUsageError; exports.tryParseJson = tryParseJson; exports.withTimeout = withTimeout;
5901
+
5902
+ exports.ClientMsgCode = ClientMsgCode; exports.CrdtType = CrdtType; exports.LiveList = LiveList; exports.LiveMap = LiveMap; exports.LiveObject = LiveObject; exports.OpCode = OpCode; exports.ServerMsgCode = ServerMsgCode; exports.WebsocketCloseCodes = WebsocketCloseCodes; exports.asArrayWithLegacyMethods = asArrayWithLegacyMethods; exports.asPos = asPos; exports.assert = assert; exports.assertNever = assertNever; exports.b64decode = b64decode; exports.createClient = createClient; exports.deprecate = deprecate; exports.deprecateIf = deprecateIf; exports.errorIf = errorIf; exports.freeze = freeze; exports.isChildCrdt = isChildCrdt; exports.isJsonArray = isJsonArray; exports.isJsonObject = isJsonObject; exports.isJsonScalar = isJsonScalar; exports.isPlainObject = isPlainObject; exports.isRootCrdt = isRootCrdt; exports.legacy_patchImmutableObject = legacy_patchImmutableObject; exports.lsonToJson = lsonToJson; exports.makePosition = makePosition; exports.nn = nn; exports.patchLiveObjectKey = patchLiveObjectKey; exports.shallow = shallow; exports.throwUsageError = throwUsageError; exports.toPlainLson = toPlainLson; exports.tryParseJson = tryParseJson; exports.withTimeout = withTimeout;
5903
+ //# sourceMappingURL=index.js.map