@liveblocks/zustand 0.16.4-beta2 → 0.16.6

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.
Files changed (4) hide show
  1. package/index.d.ts +1 -1
  2. package/index.js +158 -291
  3. package/index.mjs +119 -193
  4. package/package.json +9 -5
package/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { StateCreator, SetState, GetState, StoreApi } from 'zustand';
2
1
  import { Presence, Room, User, Client } from '@liveblocks/client';
2
+ import { StateCreator, SetState, GetState, StoreApi } from 'zustand';
3
3
 
4
4
  declare type LiveblocksState<TState, TPresence extends Presence = Presence> = TState & {
5
5
  /**
package/index.js CHANGED
@@ -1,318 +1,185 @@
1
- 'use strict';
1
+ "use strict";
2
2
 
3
- Object.defineProperty(exports, '__esModule', { value: true });
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: !0
5
+ });
4
6
 
5
- var client = require('@liveblocks/client');
7
+ var internal = require("@liveblocks/client/internal");
6
8
 
7
9
  function _extends() {
8
- _extends = Object.assign || function (target) {
9
- for (var i = 1; i < arguments.length; i++) {
10
- var source = arguments[i];
11
-
12
- for (var key in source) {
13
- if (Object.prototype.hasOwnProperty.call(source, key)) {
14
- target[key] = source[key];
15
- }
16
- }
17
- }
18
-
19
- return target;
20
- };
21
-
22
- return _extends.apply(this, arguments);
23
- }
24
-
25
- function _unsupportedIterableToArray(o, minLen) {
26
- if (!o) return;
27
- if (typeof o === "string") return _arrayLikeToArray(o, minLen);
28
- var n = Object.prototype.toString.call(o).slice(8, -1);
29
- if (n === "Object" && o.constructor) n = o.constructor.name;
30
- if (n === "Map" || n === "Set") return Array.from(o);
31
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
10
+ return _extends = Object.assign || function(target) {
11
+ for (var i = 1; i < arguments.length; i++) {
12
+ var source = arguments[i];
13
+ for (var key in source) Object.prototype.hasOwnProperty.call(source, key) && (target[key] = source[key]);
14
+ }
15
+ return target;
16
+ }, _extends.apply(this, arguments);
32
17
  }
33
18
 
34
19
  function _arrayLikeToArray(arr, len) {
35
- if (len == null || len > arr.length) len = arr.length;
36
-
37
- for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
38
-
39
- return arr2;
20
+ (null == len || len > arr.length) && (len = arr.length);
21
+ for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
22
+ return arr2;
40
23
  }
41
24
 
42
25
  function _createForOfIteratorHelperLoose(o, allowArrayLike) {
43
- var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
44
- if (it) return (it = it.call(o)).next.bind(it);
45
-
46
- if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
47
- if (it) o = it;
48
- var i = 0;
49
- return function () {
50
- if (i >= o.length) return {
51
- done: true
52
- };
53
- return {
54
- done: false,
55
- value: o[i++]
56
- };
57
- };
26
+ var it = "undefined" != typeof Symbol && o[Symbol.iterator] || o["@@iterator"];
27
+ if (it) return (it = it.call(o)).next.bind(it);
28
+ if (Array.isArray(o) || (it = function(o, minLen) {
29
+ if (o) {
30
+ if ("string" == typeof o) return _arrayLikeToArray(o, minLen);
31
+ var n = Object.prototype.toString.call(o).slice(8, -1);
32
+ return "Object" === n && o.constructor && (n = o.constructor.name), "Map" === n || "Set" === n ? Array.from(o) : "Arguments" === n || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n) ? _arrayLikeToArray(o, minLen) : void 0;
58
33
  }
59
-
60
- throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
34
+ }(o)) || allowArrayLike && o && "number" == typeof o.length) {
35
+ it && (o = it);
36
+ var i = 0;
37
+ return function() {
38
+ return i >= o.length ? {
39
+ done: !0
40
+ } : {
41
+ done: !1,
42
+ value: o[i++]
43
+ };
44
+ };
45
+ }
46
+ throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
61
47
  }
62
48
 
63
49
  var ERROR_PREFIX = "Invalid @liveblocks/zustand middleware config.";
64
- function missingClient() {
65
- return new Error(ERROR_PREFIX + " client is missing");
66
- }
67
- function missingMapping(mappingType) {
68
- return new Error(ERROR_PREFIX + " " + mappingType + " is missing.");
69
- }
70
- function mappingShouldBeAnObject(mappingType) {
71
- return new Error(ERROR_PREFIX + " " + mappingType + " should be an object where the values are boolean.");
72
- }
50
+
73
51
  function mappingValueShouldBeABoolean(mappingType, key) {
74
- return new Error(ERROR_PREFIX + " " + mappingType + "." + key + " value should be a boolean");
52
+ return new Error(ERROR_PREFIX + " " + mappingType + "." + key + " value should be a boolean");
75
53
  }
54
+
76
55
  function mappingShouldNotHaveTheSameKeys(key) {
77
- return new Error(ERROR_PREFIX + " \"" + key + "\" is mapped on presenceMapping and storageMapping. A key shouldn't exist on both mapping.");
56
+ return new Error(ERROR_PREFIX + ' "' + key + "\" is mapped on presenceMapping and storageMapping. A key shouldn't exist on both mapping.");
78
57
  }
58
+
79
59
  function mappingToFunctionIsNotAllowed(key) {
80
- return new Error(ERROR_PREFIX + " mapping." + key + " is invalid. Mapping to a function is not allowed.");
60
+ return new Error(ERROR_PREFIX + " mapping." + key + " is invalid. Mapping to a function is not allowed.");
81
61
  }
82
62
 
83
- var patchLiveObjectKey = client.internals.patchLiveObjectKey,
84
- patchImmutableObject = client.internals.patchImmutableObject,
85
- lsonToJson = client.internals.lsonToJson;
86
- function middleware(config, options) {
87
- if (process.env.NODE_ENV !== "production" && options.client == null) {
88
- throw missingClient();
89
- }
90
-
91
- var client = options.client;
92
- var storageMapping = validateMapping(options.storageMapping || {}, "storageMapping");
93
- var presenceMapping = validateMapping(options.presenceMapping || {}, "presenceMapping");
94
-
95
- if (process.env.NODE_ENV !== "production") {
96
- validateNoDuplicateKeys(storageMapping, presenceMapping);
97
- }
98
-
99
- return function (set, get, api) {
100
- var typedSet = set;
101
- var room = null;
102
- var isPatching = false;
103
- var storageRoot = null;
104
- var unsubscribeCallbacks = [];
105
- var store = config(function (args) {
106
- var oldState = get();
107
- set(args);
108
- var newState = get();
109
-
110
- if (room) {
111
- isPatching = true;
112
- updatePresence(room, oldState, newState, presenceMapping);
113
- room.batch(function () {
114
- if (storageRoot) {
115
- patchLiveblocksStorage(storageRoot, oldState, newState, storageMapping);
116
- }
117
- });
118
- isPatching = false;
119
- }
120
- }, get, api);
121
-
122
- function enterRoom(roomId, initialState) {
123
- if (storageRoot) {
124
- return;
125
- }
63
+ function updateZustandLiveblocksState(set, partial) {
64
+ set((function(state) {
65
+ return {
66
+ liveblocks: _extends({}, state.liveblocks, partial)
67
+ };
68
+ }));
69
+ }
126
70
 
127
- room = client.enter(roomId);
128
- updateZustandLiveblocksState(set, {
129
- isStorageLoading: true,
130
- room: room
71
+ function validateMapping(mapping, mappingType) {
72
+ if ("production" !== process.env.NODE_ENV) {
73
+ if (null == mapping) throw function(mappingType) {
74
+ return new Error(ERROR_PREFIX + " " + mappingType + " is missing.");
75
+ }(mappingType);
76
+ if (value = mapping, "[object Object]" !== Object.prototype.toString.call(value)) throw function(mappingType) {
77
+ return new Error(ERROR_PREFIX + " " + mappingType + " should be an object where the values are boolean.");
78
+ }(mappingType);
79
+ }
80
+ var value, result = {};
81
+ for (var key in mapping) {
82
+ if ("production" !== process.env.NODE_ENV && "boolean" != typeof mapping[key]) throw mappingValueShouldBeABoolean(mappingType, key);
83
+ !0 === mapping[key] && (result[key] = !0);
84
+ }
85
+ return result;
86
+ }
87
+
88
+ exports.middleware = function(config, options) {
89
+ if ("production" !== process.env.NODE_ENV && null == options.client) throw new Error(ERROR_PREFIX + " client is missing");
90
+ var client = options.client, storageMapping = validateMapping(options.storageMapping || {}, "storageMapping"), presenceMapping = validateMapping(options.presenceMapping || {}, "presenceMapping");
91
+ return "production" !== process.env.NODE_ENV && function(storageMapping, presenceMapping) {
92
+ for (var key in storageMapping) if (void 0 !== presenceMapping[key]) throw mappingShouldNotHaveTheSameKeys(key);
93
+ }(storageMapping, presenceMapping), function(set, get, api) {
94
+ var typedSet = set, room = null, isPatching = !1, storageRoot = null, unsubscribeCallbacks = [], store = config((function(args) {
95
+ var oldState = get();
96
+ set(args);
97
+ var newState = get();
98
+ room && (isPatching = !0, function(room, oldState, newState, presenceMapping) {
99
+ for (var key in presenceMapping) {
100
+ if ("function" == typeof newState[key]) throw mappingToFunctionIsNotAllowed("value");
101
+ var _room$updatePresence2;
102
+ if (oldState[key] !== newState[key]) room.updatePresence(((_room$updatePresence2 = {})[key] = newState[key],
103
+ _room$updatePresence2));
104
+ }
105
+ }(room, oldState, newState, presenceMapping), room.batch((function() {
106
+ storageRoot && function(root, oldState, newState, mapping) {
107
+ for (var key in mapping) {
108
+ if ("production" !== process.env.NODE_ENV && "function" == typeof newState[key]) throw mappingToFunctionIsNotAllowed("value");
109
+ oldState[key] !== newState[key] && internal.patchLiveObjectKey(root, key, oldState[key], newState[key]);
110
+ }
111
+ }(storageRoot, oldState, newState, storageMapping);
112
+ })), isPatching = !1);
113
+ }), get, api);
114
+ return _extends({}, store, {
115
+ liveblocks: {
116
+ enterRoom: function(roomId, initialState) {
117
+ if (!storageRoot) {
118
+ room = client.enter(roomId), updateZustandLiveblocksState(set, {
119
+ isStorageLoading: !0,
120
+ room: room
131
121
  });
132
122
  var state = get();
133
- broadcastInitialPresence(room, state, presenceMapping);
134
- unsubscribeCallbacks.push(room.subscribe("others", function (others) {
135
- updateZustandLiveblocksState(set, {
136
- others: others.toArray()
137
- });
138
- }));
139
- unsubscribeCallbacks.push(room.subscribe("connection", function () {
140
- updateZustandLiveblocksState(set, {
141
- connection: room.getConnectionState()
142
- });
143
- }));
144
- unsubscribeCallbacks.push(room.subscribe("my-presence", function () {
145
- if (isPatching === false) {
146
- set(patchPresenceState(room.getPresence(), presenceMapping));
123
+ !function(room, state, mapping) {
124
+ for (var key in mapping) {
125
+ var _room$updatePresence;
126
+ null == room || room.updatePresence(((_room$updatePresence = {})[key] = state[key],
127
+ _room$updatePresence));
128
+ }
129
+ }(room, state, presenceMapping), unsubscribeCallbacks.push(room.subscribe("others", (function(others) {
130
+ updateZustandLiveblocksState(set, {
131
+ others: others.toArray()
132
+ });
133
+ }))), unsubscribeCallbacks.push(room.subscribe("connection", (function() {
134
+ updateZustandLiveblocksState(set, {
135
+ connection: room.getConnectionState()
136
+ });
137
+ }))), unsubscribeCallbacks.push(room.subscribe("my-presence", (function() {
138
+ !1 === isPatching && set(function(presence, mapping) {
139
+ var partialState = {};
140
+ for (var key in mapping) partialState[key] = presence[key];
141
+ return partialState;
142
+ }(room.getPresence(), presenceMapping));
143
+ }))), room.getStorage().then((function(_ref) {
144
+ var root = _ref.root, updates = {};
145
+ room.batch((function() {
146
+ for (var key in storageMapping) {
147
+ var liveblocksStatePart = root.get(key);
148
+ null == liveblocksStatePart ? (updates[key] = initialState[key], internal.patchLiveObjectKey(root, key, void 0, initialState[key])) : updates[key] = internal.lsonToJson(liveblocksStatePart);
147
149
  }
150
+ })), typedSet(updates), storageRoot = root, unsubscribeCallbacks.push(room.subscribe(root, (function(updates) {
151
+ !1 === isPatching && set(function(state, updates, mapping) {
152
+ var partialState = {};
153
+ for (var key in mapping) partialState[key] = state[key];
154
+ var patched = internal.patchImmutableObject(partialState, updates), result = {};
155
+ for (var _key in mapping) result[_key] = patched[_key];
156
+ return result;
157
+ }(get(), updates, storageMapping));
158
+ }), {
159
+ isDeep: !0
160
+ })), updateZustandLiveblocksState(set, {
161
+ isStorageLoading: !1
162
+ });
148
163
  }));
149
- room.getStorage().then(function (_ref) {
150
- var root = _ref.root;
151
- var updates = {};
152
- room.batch(function () {
153
- for (var _key in storageMapping) {
154
- var liveblocksStatePart = root.get(_key);
155
-
156
- if (liveblocksStatePart == null) {
157
- updates[_key] = initialState[_key];
158
- patchLiveObjectKey(root, _key, undefined, initialState[_key]);
159
- } else {
160
- updates[_key] = lsonToJson(liveblocksStatePart);
161
- }
162
- }
163
- });
164
- typedSet(updates);
165
- storageRoot = root;
166
- unsubscribeCallbacks.push(room.subscribe(root, function (updates) {
167
- if (isPatching === false) {
168
- set(patchState(get(), updates, storageMapping));
169
- }
170
- }, {
171
- isDeep: true
172
- }));
173
- updateZustandLiveblocksState(set, {
174
- isStorageLoading: false
175
- });
176
- });
177
- }
178
-
179
- function leaveRoom(roomId) {
180
- for (var _iterator = _createForOfIteratorHelperLoose(unsubscribeCallbacks), _step; !(_step = _iterator()).done;) {
181
- var unsubscribe = _step.value;
182
- unsubscribe();
183
- }
184
-
185
- storageRoot = null;
186
- room = null;
187
- isPatching = false;
188
- unsubscribeCallbacks = [];
189
- client.leave(roomId);
190
- updateZustandLiveblocksState(set, {
191
- others: [],
192
- connection: "closed",
193
- isStorageLoading: false,
194
- room: null
195
- });
196
- }
197
-
198
- return _extends({}, store, {
199
- liveblocks: {
200
- enterRoom: enterRoom,
201
- leaveRoom: leaveRoom,
202
- room: null,
203
- others: [],
204
- connection: "closed",
205
- isStorageLoading: false
206
- }
207
- });
208
- };
209
- }
210
-
211
- function patchState(state, updates, mapping) {
212
- var partialState = {};
213
-
214
- for (var _key2 in mapping) {
215
- partialState[_key2] = state[_key2];
216
- }
217
-
218
- var patched = patchImmutableObject(partialState, updates);
219
- var result = {};
220
-
221
- for (var _key3 in mapping) {
222
- result[_key3] = patched[_key3];
223
- }
224
-
225
- return result;
226
- }
227
-
228
- function patchPresenceState(presence, mapping) {
229
- var partialState = {};
230
-
231
- for (var _key4 in mapping) {
232
- partialState[_key4] = presence[_key4];
233
- }
234
-
235
- return partialState;
236
- }
237
-
238
- function updateZustandLiveblocksState(set, partial) {
239
- set(function (state) {
240
- return {
241
- liveblocks: _extends({}, state.liveblocks, partial)
242
- };
164
+ }
165
+ },
166
+ leaveRoom: function(roomId) {
167
+ for (var _step, _iterator = _createForOfIteratorHelperLoose(unsubscribeCallbacks); !(_step = _iterator()).done; ) {
168
+ (0, _step.value)();
169
+ }
170
+ storageRoot = null, room = null, isPatching = !1, unsubscribeCallbacks = [], client.leave(roomId),
171
+ updateZustandLiveblocksState(set, {
172
+ others: [],
173
+ connection: "closed",
174
+ isStorageLoading: !1,
175
+ room: null
176
+ });
177
+ },
178
+ room: null,
179
+ others: [],
180
+ connection: "closed",
181
+ isStorageLoading: !1
182
+ }
243
183
  });
244
- }
245
-
246
- function broadcastInitialPresence(room, state, mapping) {
247
- for (var _key5 in mapping) {
248
- var _room$updatePresence;
249
-
250
- room == null ? void 0 : room.updatePresence((_room$updatePresence = {}, _room$updatePresence[_key5] = state[_key5], _room$updatePresence));
251
- }
252
- }
253
-
254
- function updatePresence(room, oldState, newState, presenceMapping) {
255
- for (var _key6 in presenceMapping) {
256
- if (typeof newState[_key6] === "function") {
257
- throw mappingToFunctionIsNotAllowed("value");
258
- }
259
-
260
- if (oldState[_key6] !== newState[_key6]) {
261
- var _room$updatePresence2;
262
-
263
- room.updatePresence((_room$updatePresence2 = {}, _room$updatePresence2[_key6] = newState[_key6], _room$updatePresence2));
264
- }
265
- }
266
- }
267
-
268
- function patchLiveblocksStorage(root, oldState, newState, mapping) {
269
- for (var _key7 in mapping) {
270
- if (process.env.NODE_ENV !== "production" && typeof newState[_key7] === "function") {
271
- throw mappingToFunctionIsNotAllowed("value");
272
- }
273
-
274
- if (oldState[_key7] !== newState[_key7]) {
275
- patchLiveObjectKey(root, _key7, oldState[_key7], newState[_key7]);
276
- }
277
- }
278
- }
279
-
280
- function isObject(value) {
281
- return Object.prototype.toString.call(value) === "[object Object]";
282
- }
283
-
284
- function validateNoDuplicateKeys(storageMapping, presenceMapping) {
285
- for (var _key8 in storageMapping) {
286
- if (presenceMapping[_key8] !== undefined) {
287
- throw mappingShouldNotHaveTheSameKeys(_key8);
288
- }
289
- }
290
- }
291
-
292
- function validateMapping(mapping, mappingType) {
293
- if (process.env.NODE_ENV !== "production") {
294
- if (mapping == null) {
295
- throw missingMapping(mappingType);
296
- }
297
-
298
- if (!isObject(mapping)) {
299
- throw mappingShouldBeAnObject(mappingType);
300
- }
301
- }
302
-
303
- var result = {};
304
-
305
- for (var _key9 in mapping) {
306
- if (process.env.NODE_ENV !== "production" && typeof mapping[_key9] !== "boolean") {
307
- throw mappingValueShouldBeABoolean(mappingType, _key9);
308
- }
309
-
310
- if (mapping[_key9] === true) {
311
- result[_key9] = true;
312
- }
313
- }
314
-
315
- return result;
316
- }
317
-
318
- exports.middleware = middleware;
184
+ };
185
+ };
package/index.mjs CHANGED
@@ -1,211 +1,137 @@
1
- import { internals } from '@liveblocks/client';
1
+ import { patchLiveObjectKey, lsonToJson, patchImmutableObject } from "@liveblocks/client/internal";
2
2
 
3
3
  const ERROR_PREFIX = "Invalid @liveblocks/zustand middleware config.";
4
- function missingClient() {
5
- return new Error(`${ERROR_PREFIX} client is missing`);
6
- }
7
- function missingMapping(mappingType) {
8
- return new Error(`${ERROR_PREFIX} ${mappingType} is missing.`);
9
- }
10
- function mappingShouldBeAnObject(mappingType) {
11
- return new Error(`${ERROR_PREFIX} ${mappingType} should be an object where the values are boolean.`);
12
- }
4
+
13
5
  function mappingValueShouldBeABoolean(mappingType, key) {
14
- return new Error(`${ERROR_PREFIX} ${mappingType}.${key} value should be a boolean`);
6
+ return new Error(`${ERROR_PREFIX} ${mappingType}.${key} value should be a boolean`);
15
7
  }
8
+
16
9
  function mappingShouldNotHaveTheSameKeys(key) {
17
- return new Error(`${ERROR_PREFIX} "${key}" is mapped on presenceMapping and storageMapping. A key shouldn't exist on both mapping.`);
10
+ return new Error(`${ERROR_PREFIX} "${key}" is mapped on presenceMapping and storageMapping. A key shouldn't exist on both mapping.`);
18
11
  }
12
+
19
13
  function mappingToFunctionIsNotAllowed(key) {
20
- return new Error(`${ERROR_PREFIX} mapping.${key} is invalid. Mapping to a function is not allowed.`);
14
+ return new Error(`${ERROR_PREFIX} mapping.${key} is invalid. Mapping to a function is not allowed.`);
21
15
  }
22
16
 
23
- const { patchLiveObjectKey, patchImmutableObject, lsonToJson } = internals;
24
17
  function middleware(config, options) {
25
- if (process.env.NODE_ENV !== "production" && options.client == null) {
26
- throw missingClient();
27
- }
28
- const client = options.client;
29
- const storageMapping = validateMapping(options.storageMapping || {}, "storageMapping");
30
- const presenceMapping = validateMapping(options.presenceMapping || {}, "presenceMapping");
31
- if (process.env.NODE_ENV !== "production") {
32
- validateNoDuplicateKeys(storageMapping, presenceMapping);
33
- }
34
- return (set, get, api) => {
35
- const typedSet = set;
36
- let room = null;
37
- let isPatching = false;
38
- let storageRoot = null;
39
- let unsubscribeCallbacks = [];
40
- const store = config((args) => {
41
- const oldState = get();
42
- set(args);
43
- const newState = get();
44
- if (room) {
45
- isPatching = true;
46
- updatePresence(room, oldState, newState, presenceMapping);
47
- room.batch(() => {
48
- if (storageRoot) {
49
- patchLiveblocksStorage(storageRoot, oldState, newState, storageMapping);
50
- }
51
- });
52
- isPatching = false;
53
- }
54
- }, get, api);
55
- function enterRoom(roomId, initialState) {
56
- if (storageRoot) {
57
- return;
58
- }
59
- room = client.enter(roomId);
60
- updateZustandLiveblocksState(set, { isStorageLoading: true, room });
61
- const state = get();
62
- broadcastInitialPresence(room, state, presenceMapping);
63
- unsubscribeCallbacks.push(room.subscribe("others", (others) => {
64
- updateZustandLiveblocksState(set, { others: others.toArray() });
65
- }));
66
- unsubscribeCallbacks.push(room.subscribe("connection", () => {
67
- updateZustandLiveblocksState(set, {
68
- connection: room.getConnectionState(),
69
- });
70
- }));
71
- unsubscribeCallbacks.push(room.subscribe("my-presence", () => {
72
- if (isPatching === false) {
73
- set(patchPresenceState(room.getPresence(), presenceMapping));
74
- }
75
- }));
76
- room.getStorage().then(({ root }) => {
77
- const updates = {};
78
- room.batch(() => {
79
- for (const key in storageMapping) {
80
- const liveblocksStatePart = root.get(key);
81
- if (liveblocksStatePart == null) {
82
- updates[key] = initialState[key];
83
- patchLiveObjectKey(root, key, undefined, initialState[key]);
84
- }
85
- else {
86
- updates[key] = lsonToJson(liveblocksStatePart);
87
- }
88
- }
89
- });
90
- typedSet(updates);
91
- storageRoot = root;
92
- unsubscribeCallbacks.push(room.subscribe(root, (updates) => {
93
- if (isPatching === false) {
94
- set(patchState(get(), updates, storageMapping));
95
- }
96
- }, { isDeep: true }));
97
- // set isLoading storage to false once storage is loaded
98
- updateZustandLiveblocksState(set, { isStorageLoading: false });
99
- });
100
- }
101
- function leaveRoom(roomId) {
102
- for (const unsubscribe of unsubscribeCallbacks) {
103
- unsubscribe();
104
- }
105
- storageRoot = null;
106
- room = null;
107
- isPatching = false;
108
- unsubscribeCallbacks = [];
109
- client.leave(roomId);
110
- updateZustandLiveblocksState(set, {
111
- others: [],
112
- connection: "closed",
113
- isStorageLoading: false,
114
- room: null,
115
- });
116
- }
117
- return Object.assign(Object.assign({}, store), { liveblocks: {
118
- enterRoom,
119
- leaveRoom,
120
- room: null,
121
- others: [],
122
- connection: "closed",
123
- isStorageLoading: false,
124
- } });
125
- };
126
- }
127
- function patchState(state, updates, // StorageUpdate
128
- mapping) {
129
- const partialState = {};
130
- for (const key in mapping) {
131
- partialState[key] = state[key];
132
- }
133
- const patched = patchImmutableObject(partialState, updates);
134
- const result = {};
135
- for (const key in mapping) {
136
- result[key] = patched[key];
137
- }
138
- return result;
139
- }
140
- function patchPresenceState(presence, mapping) {
141
- const partialState = {};
142
- for (const key in mapping) {
143
- partialState[key] = presence[key];
144
- }
145
- return partialState;
146
- }
147
- function updateZustandLiveblocksState(set, partial) {
148
- set((state) => ({ liveblocks: Object.assign(Object.assign({}, state.liveblocks), partial) }));
149
- }
150
- function broadcastInitialPresence(room, state, mapping) {
151
- for (const key in mapping) {
152
- room === null || room === void 0 ? void 0 : room.updatePresence({ [key]: state[key] });
153
- }
154
- }
155
- function updatePresence(room, oldState, newState, presenceMapping) {
18
+ if ("production" !== process.env.NODE_ENV && null == options.client) throw new Error(`${ERROR_PREFIX} client is missing`);
19
+ const client = options.client, storageMapping = validateMapping(options.storageMapping || {}, "storageMapping"), presenceMapping = validateMapping(options.presenceMapping || {}, "presenceMapping");
20
+ return "production" !== process.env.NODE_ENV && function(storageMapping, presenceMapping) {
21
+ for (const key in storageMapping) if (void 0 !== presenceMapping[key]) throw mappingShouldNotHaveTheSameKeys(key);
22
+ }(storageMapping, presenceMapping), (set, get, api) => {
23
+ const typedSet = set;
24
+ let room = null, isPatching = !1, storageRoot = null, unsubscribeCallbacks = [];
25
+ const store = config((args => {
26
+ const oldState = get();
27
+ set(args);
28
+ const newState = get();
29
+ room && (isPatching = !0, function(room, oldState, newState, presenceMapping) {
156
30
  for (const key in presenceMapping) {
157
- if (typeof newState[key] === "function") {
158
- throw mappingToFunctionIsNotAllowed("value");
159
- }
160
- if (oldState[key] !== newState[key]) {
161
- room.updatePresence({ [key]: newState[key] });
162
- }
31
+ if ("function" == typeof newState[key]) throw mappingToFunctionIsNotAllowed("value");
32
+ oldState[key] !== newState[key] && room.updatePresence({
33
+ [key]: newState[key]
34
+ });
163
35
  }
36
+ }(room, oldState, newState, presenceMapping), room.batch((() => {
37
+ storageRoot && function(root, oldState, newState, mapping) {
38
+ for (const key in mapping) {
39
+ if ("production" !== process.env.NODE_ENV && "function" == typeof newState[key]) throw mappingToFunctionIsNotAllowed("value");
40
+ oldState[key] !== newState[key] && patchLiveObjectKey(root, key, oldState[key], newState[key]);
41
+ }
42
+ }(storageRoot, oldState, newState, storageMapping);
43
+ })), isPatching = !1);
44
+ }), get, api);
45
+ return Object.assign(Object.assign({}, store), {
46
+ liveblocks: {
47
+ enterRoom: function(roomId, initialState) {
48
+ if (storageRoot) return;
49
+ room = client.enter(roomId), updateZustandLiveblocksState(set, {
50
+ isStorageLoading: !0,
51
+ room: room
52
+ });
53
+ const state = get();
54
+ !function(room, state, mapping) {
55
+ for (const key in mapping) null == room || room.updatePresence({
56
+ [key]: state[key]
57
+ });
58
+ }(room, state, presenceMapping), unsubscribeCallbacks.push(room.subscribe("others", (others => {
59
+ updateZustandLiveblocksState(set, {
60
+ others: others.toArray()
61
+ });
62
+ }))), unsubscribeCallbacks.push(room.subscribe("connection", (() => {
63
+ updateZustandLiveblocksState(set, {
64
+ connection: room.getConnectionState()
65
+ });
66
+ }))), unsubscribeCallbacks.push(room.subscribe("my-presence", (() => {
67
+ !1 === isPatching && set(function(presence, mapping) {
68
+ const partialState = {};
69
+ for (const key in mapping) partialState[key] = presence[key];
70
+ return partialState;
71
+ }(room.getPresence(), presenceMapping));
72
+ }))), room.getStorage().then((({root: root}) => {
73
+ const updates = {};
74
+ room.batch((() => {
75
+ for (const key in storageMapping) {
76
+ const liveblocksStatePart = root.get(key);
77
+ null == liveblocksStatePart ? (updates[key] = initialState[key], patchLiveObjectKey(root, key, void 0, initialState[key])) : updates[key] = lsonToJson(liveblocksStatePart);
78
+ }
79
+ })), typedSet(updates), storageRoot = root, unsubscribeCallbacks.push(room.subscribe(root, (updates => {
80
+ !1 === isPatching && set(function(state, updates, mapping) {
81
+ const partialState = {};
82
+ for (const key in mapping) partialState[key] = state[key];
83
+ const patched = patchImmutableObject(partialState, updates), result = {};
84
+ for (const key in mapping) result[key] = patched[key];
85
+ return result;
86
+ }(get(), updates, storageMapping));
87
+ }), {
88
+ isDeep: !0
89
+ })), updateZustandLiveblocksState(set, {
90
+ isStorageLoading: !1
91
+ });
92
+ }));
93
+ },
94
+ leaveRoom: function(roomId) {
95
+ for (const unsubscribe of unsubscribeCallbacks) unsubscribe();
96
+ storageRoot = null, room = null, isPatching = !1, unsubscribeCallbacks = [], client.leave(roomId),
97
+ updateZustandLiveblocksState(set, {
98
+ others: [],
99
+ connection: "closed",
100
+ isStorageLoading: !1,
101
+ room: null
102
+ });
103
+ },
104
+ room: null,
105
+ others: [],
106
+ connection: "closed",
107
+ isStorageLoading: !1
108
+ }
109
+ });
110
+ };
164
111
  }
165
- function patchLiveblocksStorage(root, oldState, newState, mapping) {
166
- for (const key in mapping) {
167
- if (process.env.NODE_ENV !== "production" &&
168
- typeof newState[key] === "function") {
169
- throw mappingToFunctionIsNotAllowed("value");
170
- }
171
- if (oldState[key] !== newState[key]) {
172
- patchLiveObjectKey(root, key, oldState[key], newState[key]);
173
- }
174
- }
175
- }
176
- function isObject(value) {
177
- return Object.prototype.toString.call(value) === "[object Object]";
178
- }
179
- function validateNoDuplicateKeys(storageMapping, presenceMapping) {
180
- for (const key in storageMapping) {
181
- if (presenceMapping[key] !== undefined) {
182
- throw mappingShouldNotHaveTheSameKeys(key);
183
- }
184
- }
112
+
113
+ function updateZustandLiveblocksState(set, partial) {
114
+ set((state => ({
115
+ liveblocks: Object.assign(Object.assign({}, state.liveblocks), partial)
116
+ })));
185
117
  }
186
- /**
187
- * Remove false keys from mapping and generate to a new object to avoid potential mutation from outside the middleware
188
- */
118
+
189
119
  function validateMapping(mapping, mappingType) {
190
- if (process.env.NODE_ENV !== "production") {
191
- if (mapping == null) {
192
- throw missingMapping(mappingType);
193
- }
194
- if (!isObject(mapping)) {
195
- throw mappingShouldBeAnObject(mappingType);
196
- }
197
- }
198
- const result = {};
199
- for (const key in mapping) {
200
- if (process.env.NODE_ENV !== "production" &&
201
- typeof mapping[key] !== "boolean") {
202
- throw mappingValueShouldBeABoolean(mappingType, key);
203
- }
204
- if (mapping[key] === true) {
205
- result[key] = true;
206
- }
207
- }
208
- return result;
120
+ if ("production" !== process.env.NODE_ENV) {
121
+ if (null == mapping) throw function(mappingType) {
122
+ return new Error(`${ERROR_PREFIX} ${mappingType} is missing.`);
123
+ }(mappingType);
124
+ if (value = mapping, "[object Object]" !== Object.prototype.toString.call(value)) throw function(mappingType) {
125
+ return new Error(`${ERROR_PREFIX} ${mappingType} should be an object where the values are boolean.`);
126
+ }(mappingType);
127
+ }
128
+ var value;
129
+ const result = {};
130
+ for (const key in mapping) {
131
+ if ("production" !== process.env.NODE_ENV && "boolean" != typeof mapping[key]) throw mappingValueShouldBeABoolean(mappingType, key);
132
+ !0 === mapping[key] && (result[key] = !0);
133
+ }
134
+ return result;
209
135
  }
210
136
 
211
137
  export { middleware };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@liveblocks/zustand",
3
- "version": "0.16.4-beta2",
3
+ "version": "0.16.6",
4
4
  "description": "A middleware to integrate Liveblocks into Zustand stores.",
5
5
  "main": "./index.js",
6
6
  "module": "./index.mjs",
@@ -18,6 +18,7 @@
18
18
  ],
19
19
  "scripts": {
20
20
  "build": "rollup -c && cp ./package.json ./README.md ./lib",
21
+ "format": "eslint --fix src/ test/ && prettier --write src/ test/",
21
22
  "lint": "eslint src/ test/",
22
23
  "test": "jest --watch",
23
24
  "test-ci": "jest",
@@ -30,13 +31,13 @@
30
31
  "directory": "packages/liveblocks-zustand"
31
32
  },
32
33
  "peerDependencies": {
33
- "@liveblocks/client": "0.16.4-beta2",
34
+ "@liveblocks/client": "0.16.6",
34
35
  "zustand": "^3"
35
36
  },
36
37
  "devDependencies": {
37
- "@babel/core": "^7.16.7",
38
- "@babel/plugin-transform-typescript": "^7.16.8",
39
- "@babel/preset-env": "^7.16.8",
38
+ "@babel/core": "^7.17.10",
39
+ "@babel/preset-env": "^7.17.10",
40
+ "@babel/preset-typescript": "^7.16.7",
40
41
  "@definitelytyped/dtslint": "^0.0.103",
41
42
  "@rollup/plugin-babel": "^5.3.0",
42
43
  "@rollup/plugin-node-resolve": "^13.1.3",
@@ -49,11 +50,14 @@
49
50
  "@typescript-eslint/eslint-plugin": "^5.18.0",
50
51
  "@typescript-eslint/parser": "^5.18.0",
51
52
  "eslint": "^8.12.0",
53
+ "eslint-plugin-import": "^2.26.0",
54
+ "eslint-plugin-simple-import-sort": "^7.0.0",
52
55
  "jest": "^27.4.7",
53
56
  "msw": "^0.36.4",
54
57
  "rollup": "^2.64.0",
55
58
  "rollup-plugin-command": "^1.1.3",
56
59
  "rollup-plugin-dts": "^4.2.1",
60
+ "rollup-plugin-terser": "^7.0.2",
57
61
  "whatwg-fetch": "^3.6.2",
58
62
  "zustand": "^3.6.9"
59
63
  },