@pluv/client 0.0.0

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 ADDED
@@ -0,0 +1,1001 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __defProps = Object.defineProperties;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
10
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
11
+ var __spreadValues = (a, b) => {
12
+ for (var prop in b || (b = {}))
13
+ if (__hasOwnProp.call(b, prop))
14
+ __defNormalProp(a, prop, b[prop]);
15
+ if (__getOwnPropSymbols)
16
+ for (var prop of __getOwnPropSymbols(b)) {
17
+ if (__propIsEnum.call(b, prop))
18
+ __defNormalProp(a, prop, b[prop]);
19
+ }
20
+ return a;
21
+ };
22
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
23
+ var __export = (target, all) => {
24
+ for (var name in all)
25
+ __defProp(target, name, { get: all[name], enumerable: true });
26
+ };
27
+ var __copyProps = (to, from, except, desc) => {
28
+ if (from && typeof from === "object" || typeof from === "function") {
29
+ for (let key of __getOwnPropNames(from))
30
+ if (!__hasOwnProp.call(to, key) && key !== except)
31
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
32
+ }
33
+ return to;
34
+ };
35
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
36
+ var __async = (__this, __arguments, generator) => {
37
+ return new Promise((resolve, reject) => {
38
+ var fulfilled = (value) => {
39
+ try {
40
+ step(generator.next(value));
41
+ } catch (e) {
42
+ reject(e);
43
+ }
44
+ };
45
+ var rejected = (value) => {
46
+ try {
47
+ step(generator.throw(value));
48
+ } catch (e) {
49
+ reject(e);
50
+ }
51
+ };
52
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
53
+ step((generator = generator.apply(__this, __arguments)).next());
54
+ });
55
+ };
56
+
57
+ // src/index.ts
58
+ var src_exports = {};
59
+ __export(src_exports, {
60
+ ConnectionState: () => ConnectionState,
61
+ PluvClient: () => PluvClient,
62
+ PluvRoom: () => PluvRoom,
63
+ createClient: () => createClient,
64
+ y: () => y_exports
65
+ });
66
+ module.exports = __toCommonJS(src_exports);
67
+
68
+ // src/PluvRoom.ts
69
+ var import_crdt_yjs2 = require("@pluv/crdt-yjs");
70
+
71
+ // src/CrdtManager.ts
72
+ var import_crdt_yjs = require("@pluv/crdt-yjs");
73
+ var CrdtManager = class {
74
+ constructor(options = {}) {
75
+ const { encodedState, initialStorage } = options;
76
+ const doc1 = encodedState ? (0, import_crdt_yjs.doc)().applyUpdate(encodedState) : null;
77
+ if (doc1 && !!Object.keys(doc1.toJSON()).length) {
78
+ this.doc = doc1;
79
+ return;
80
+ }
81
+ doc1 == null ? void 0 : doc1.destroy();
82
+ this.doc = (0, import_crdt_yjs.doc)(initialStorage == null ? void 0 : initialStorage());
83
+ }
84
+ destroy() {
85
+ this.doc.destroy();
86
+ }
87
+ get(key) {
88
+ return this.doc.get(key);
89
+ }
90
+ };
91
+
92
+ // src/CrdtNotifier.ts
93
+ var import_wonka = require("wonka");
94
+ var CrdtNotifier = class {
95
+ constructor() {
96
+ this.subjects = /* @__PURE__ */ new Map();
97
+ }
98
+ subject(key) {
99
+ const subject = this.subjects.get(key);
100
+ if (subject) {
101
+ return subject;
102
+ }
103
+ const newSubject = (0, import_wonka.makeSubject)();
104
+ this.subjects.set(key, newSubject);
105
+ return newSubject;
106
+ }
107
+ subscribe(key, callback) {
108
+ const subject = this.subject(key);
109
+ return (0, import_wonka.subscribe)(callback)(subject.source).unsubscribe;
110
+ }
111
+ };
112
+
113
+ // src/EventNotifier.ts
114
+ var import_wonka2 = require("wonka");
115
+ var EventNotifier = class {
116
+ constructor() {
117
+ this.subjects = /* @__PURE__ */ new Map();
118
+ }
119
+ subject(name) {
120
+ const subject = this.subjects.get(name);
121
+ if (subject)
122
+ return subject;
123
+ const newSubject = (0, import_wonka2.makeSubject)();
124
+ this.subjects.set(name, newSubject);
125
+ return newSubject;
126
+ }
127
+ subscribe(name, callback) {
128
+ const subject = this.subject(name);
129
+ return (0, import_wonka2.subscribe)(callback)(subject.source).unsubscribe;
130
+ }
131
+ };
132
+
133
+ // src/OtherNotifier.ts
134
+ var import_wonka3 = require("wonka");
135
+ var OtherNotifier = class {
136
+ constructor() {
137
+ this.subjects = /* @__PURE__ */ new Map();
138
+ }
139
+ subject(name) {
140
+ const subject = this.subjects.get(name);
141
+ if (subject)
142
+ return subject;
143
+ const newSubject = (0, import_wonka3.makeSubject)();
144
+ this.subjects.set(name, newSubject);
145
+ return newSubject;
146
+ }
147
+ subscribe(name, callback) {
148
+ const source = this.subject(name).source;
149
+ return (0, import_wonka3.subscribe)(callback)(source).unsubscribe;
150
+ }
151
+ };
152
+
153
+ // src/StateNotifier.ts
154
+ var import_wonka4 = require("wonka");
155
+ var StateNotifier = class {
156
+ constructor() {
157
+ this.subjects = {
158
+ connection: (0, import_wonka4.makeSubject)(),
159
+ "my-presence": (0, import_wonka4.makeSubject)(),
160
+ myself: (0, import_wonka4.makeSubject)(),
161
+ others: (0, import_wonka4.makeSubject)()
162
+ };
163
+ }
164
+ subscribe(name, callback) {
165
+ var _a;
166
+ const source = (_a = this.subjects[name]) == null ? void 0 : _a.source;
167
+ if (!source)
168
+ throw new Error(`Could not subscribe to source: ${name}`);
169
+ return (0, import_wonka4.subscribe)(callback)(source).unsubscribe;
170
+ }
171
+ };
172
+
173
+ // src/types.ts
174
+ var ConnectionState = /* @__PURE__ */ ((ConnectionState2) => {
175
+ ConnectionState2["Closed"] = "Closed";
176
+ ConnectionState2["Connecting"] = "Connecting";
177
+ ConnectionState2["Open"] = "Open";
178
+ ConnectionState2["Unavailable"] = "Unavailable";
179
+ ConnectionState2["Untouched"] = "Untouched";
180
+ return ConnectionState2;
181
+ })(ConnectionState || {});
182
+
183
+ // src/UsersManager.ts
184
+ var UsersManager = class {
185
+ constructor(config) {
186
+ this._myself = null;
187
+ this._others = /* @__PURE__ */ new Map();
188
+ this._presence = null;
189
+ const { initialPresence, presence = null } = config;
190
+ this._initialPresence = initialPresence;
191
+ this._presence = presence;
192
+ }
193
+ get myself() {
194
+ return this._myself;
195
+ }
196
+ clear() {
197
+ this._others.clear();
198
+ }
199
+ getOther(connectionId) {
200
+ var _a;
201
+ return (_a = this._others.get(connectionId)) != null ? _a : null;
202
+ }
203
+ getOthers() {
204
+ return Array.from(this._others.values());
205
+ }
206
+ patchPresence(connectionId, patch) {
207
+ var _a, _b;
208
+ if (((_a = this._myself) == null ? void 0 : _a.connectionId) === connectionId) {
209
+ this._myself.presence = Object.assign(
210
+ /* @__PURE__ */ Object.create(null),
211
+ this._myself.presence,
212
+ patch
213
+ );
214
+ return;
215
+ }
216
+ const other = this._others.get(connectionId);
217
+ if (!other)
218
+ return;
219
+ const presence = Object.assign(
220
+ /* @__PURE__ */ Object.create(null),
221
+ other.presence,
222
+ patch
223
+ );
224
+ (_b = this._presence) == null ? void 0 : _b.parse(presence);
225
+ this._others.set(connectionId, __spreadProps(__spreadValues({}, other), { presence }));
226
+ }
227
+ removeMyself() {
228
+ this._myself = null;
229
+ }
230
+ removeUser(connectionId) {
231
+ this._others.delete(connectionId);
232
+ }
233
+ setMyself(connectionId, user) {
234
+ this._myself = {
235
+ connectionId,
236
+ presence: this._initialPresence,
237
+ user
238
+ };
239
+ }
240
+ setPresence(connectionId, presence) {
241
+ var _a;
242
+ if (((_a = this._myself) == null ? void 0 : _a.connectionId) === connectionId) {
243
+ this._myself.presence = presence;
244
+ return;
245
+ }
246
+ const other = this._others.get(connectionId);
247
+ if (!other)
248
+ return;
249
+ this._others.set(connectionId, __spreadProps(__spreadValues({}, other), { presence }));
250
+ }
251
+ setUser(connectionId, user) {
252
+ var _a;
253
+ if (((_a = this._myself) == null ? void 0 : _a.connectionId) === connectionId)
254
+ return;
255
+ const other = this._others.get(connectionId);
256
+ if (other)
257
+ return;
258
+ this._others.set(connectionId, {
259
+ connectionId,
260
+ presence: this._initialPresence,
261
+ user
262
+ });
263
+ }
264
+ };
265
+
266
+ // src/PluvRoom.ts
267
+ var HEARTBEAT_INTERVAL_MS = 1e4;
268
+ var PONG_TIMEOUT_MS = 2e3;
269
+ var RECONNECT_TIMEOUT_MS = 3e4;
270
+ var PluvRoom = class {
271
+ constructor(room, options) {
272
+ this._crdtManager = null;
273
+ this._crdtNotifier = new CrdtNotifier();
274
+ this._eventNotifier = new EventNotifier();
275
+ this._initialStorage = null;
276
+ this._intervals = {
277
+ heartbeat: null
278
+ };
279
+ this._otherNotifier = new OtherNotifier();
280
+ this._state = {
281
+ authorization: {
282
+ token: null,
283
+ user: null
284
+ },
285
+ connection: {
286
+ id: null,
287
+ state: "Untouched" /* Untouched */
288
+ },
289
+ webSocket: null
290
+ };
291
+ this._stateNotifier = new StateNotifier();
292
+ this._subscriptions = {
293
+ observeCrdt: null
294
+ };
295
+ this._timeouts = {
296
+ pong: null,
297
+ reconnect: null
298
+ };
299
+ this._windowListeners = null;
300
+ this._wsListeners = null;
301
+ this.event = (name, callback) => {
302
+ return this._eventNotifier.subscribe(name, callback);
303
+ };
304
+ this.getMyPresence = () => {
305
+ var _a, _b;
306
+ return (_b = (_a = this._usersManager.myself) == null ? void 0 : _a.presence) != null ? _b : null;
307
+ };
308
+ this.getMyself = () => {
309
+ return this._usersManager.myself;
310
+ };
311
+ this.getOther = (connectionId) => {
312
+ return this._usersManager.getOther(connectionId);
313
+ };
314
+ this.getOthers = () => {
315
+ return this._usersManager.getOthers();
316
+ };
317
+ this.getStorage = (key) => {
318
+ var _a, _b;
319
+ return (_b = (_a = this._crdtManager) == null ? void 0 : _a.get(key)) != null ? _b : null;
320
+ };
321
+ this.other = (connectionId, callback) => {
322
+ return this._otherNotifier.subscribe(connectionId, callback);
323
+ };
324
+ this.storage = (key, fn) => {
325
+ return this._crdtNotifier.subscribe(key, fn);
326
+ };
327
+ this.subscribe = (name, callback) => {
328
+ return this._stateNotifier.subscribe(name, callback);
329
+ };
330
+ const {
331
+ authEndpoint,
332
+ debug = false,
333
+ initialPresence,
334
+ initialStorage,
335
+ onAuthorizationFail,
336
+ presence,
337
+ wsEndpoint
338
+ } = options;
339
+ this.room = room;
340
+ this._debug = debug;
341
+ this._endpoints = {
342
+ authEndpoint,
343
+ wsEndpoint
344
+ };
345
+ this._listeners = {
346
+ onAuthorizationFail: (error) => {
347
+ this._clearTimeout(this._timeouts.reconnect);
348
+ this._timeouts.reconnect = setTimeout(
349
+ this._reconnect.bind(this),
350
+ RECONNECT_TIMEOUT_MS
351
+ );
352
+ onAuthorizationFail == null ? void 0 : onAuthorizationFail(error);
353
+ }
354
+ };
355
+ this._usersManager = new UsersManager({
356
+ initialPresence,
357
+ presence
358
+ });
359
+ if (initialStorage)
360
+ this._initialStorage = initialStorage;
361
+ }
362
+ get webSocket() {
363
+ return this._state.webSocket;
364
+ }
365
+ broadcast(message) {
366
+ if (!this._state.webSocket)
367
+ return;
368
+ if (this._state.connection.state !== "Open" /* Open */)
369
+ return;
370
+ this._sendMessage(message);
371
+ }
372
+ connect() {
373
+ return __async(this, null, function* () {
374
+ if (!this._endpoints.wsEndpoint) {
375
+ throw new Error("Must provide an wsEndpoint.");
376
+ }
377
+ const canConnect = [
378
+ "Closed" /* Closed */,
379
+ "Untouched" /* Untouched */
380
+ ].some((state) => this._state.connection.state === state);
381
+ if (!canConnect)
382
+ return;
383
+ this._clearTimeout(this._timeouts.reconnect);
384
+ this._updateState((oldState) => {
385
+ oldState.connection.state = "Connecting" /* Connecting */;
386
+ return oldState;
387
+ });
388
+ const url = new URL(this._getWsEndpoint(this.room));
389
+ let authToken = null;
390
+ try {
391
+ authToken = yield this._getAuthorization(this.room);
392
+ } catch (err) {
393
+ this._onAuthorizationFail(err);
394
+ return;
395
+ }
396
+ authToken && url.searchParams.set("token", encodeURIComponent(authToken));
397
+ let webSocket;
398
+ try {
399
+ webSocket = new WebSocket(url.toString());
400
+ } catch (err) {
401
+ this._onAuthorizationFail(err);
402
+ return;
403
+ }
404
+ this._updateState((oldState) => {
405
+ oldState.authorization.token = authToken;
406
+ oldState.webSocket = webSocket;
407
+ return oldState;
408
+ });
409
+ this._attachWindowListeners();
410
+ this._attachWsListeners();
411
+ });
412
+ }
413
+ disconnect() {
414
+ var _a;
415
+ if (!this._endpoints.wsEndpoint) {
416
+ throw new Error("Must provide an wsEndpoint.");
417
+ }
418
+ if (!this._state.webSocket)
419
+ return;
420
+ const canDisconnect = [
421
+ "Connecting" /* Connecting */,
422
+ "Open" /* Open */
423
+ ].some((state) => this._state.connection.state === state);
424
+ if (!canDisconnect)
425
+ return;
426
+ this._closeWs();
427
+ (_a = this._crdtManager) == null ? void 0 : _a.destroy();
428
+ this._updateState((oldState) => {
429
+ oldState.authorization.token = null;
430
+ oldState.connection.state = "Closed" /* Closed */;
431
+ oldState.webSocket = null;
432
+ return oldState;
433
+ });
434
+ }
435
+ getConnection() {
436
+ return Object.freeze(
437
+ JSON.parse(JSON.stringify(this._state.connection))
438
+ );
439
+ }
440
+ _attachWindowListeners() {
441
+ if (typeof window === "undefined")
442
+ return;
443
+ if (typeof document === "undefined")
444
+ return;
445
+ this._windowListeners = {
446
+ onNavigatorOnline: this._onNavigatorOnline.bind(this),
447
+ onVisibilityChange: this._onVisibilityChange.bind(this)
448
+ };
449
+ window.addEventListener(
450
+ "online",
451
+ this._windowListeners.onNavigatorOnline
452
+ );
453
+ document.addEventListener(
454
+ "visibilitychange",
455
+ this._windowListeners.onVisibilityChange
456
+ );
457
+ }
458
+ _attachWsListeners() {
459
+ if (!this._state.webSocket)
460
+ return;
461
+ this._wsListeners = {
462
+ onClose: this._onClose.bind(this),
463
+ onError: this._onError.bind(this),
464
+ onMessage: this._onMessage.bind(this),
465
+ onOpen: this._onOpen.bind(this)
466
+ };
467
+ this._state.webSocket.addEventListener(
468
+ "close",
469
+ this._wsListeners.onClose
470
+ );
471
+ this._state.webSocket.addEventListener(
472
+ "error",
473
+ this._wsListeners.onError
474
+ );
475
+ this._state.webSocket.addEventListener(
476
+ "message",
477
+ this._wsListeners.onMessage
478
+ );
479
+ this._state.webSocket.addEventListener(
480
+ "open",
481
+ this._wsListeners.onOpen
482
+ );
483
+ }
484
+ _clearInterval(interval) {
485
+ if (Number.isNaN(interval))
486
+ return;
487
+ clearInterval(interval);
488
+ }
489
+ _clearTimeout(timeout) {
490
+ if (Number.isNaN(timeout))
491
+ return;
492
+ clearTimeout(timeout);
493
+ }
494
+ _closeWs() {
495
+ var _a, _b;
496
+ if (!this._state.webSocket)
497
+ return;
498
+ (_b = (_a = this._subscriptions).observeCrdt) == null ? void 0 : _b.call(_a);
499
+ this._clearInterval(this._intervals.heartbeat);
500
+ this._clearTimeout(this._timeouts.pong);
501
+ this._clearTimeout(this._timeouts.reconnect);
502
+ this._detachWindowListeners();
503
+ this._usersManager.removeMyself();
504
+ const canClose = [WebSocket.CONNECTING, WebSocket.OPEN].some(
505
+ (readyState) => {
506
+ var _a2;
507
+ return readyState === ((_a2 = this._state.webSocket) == null ? void 0 : _a2.readyState);
508
+ }
509
+ );
510
+ if (canClose)
511
+ this._state.webSocket.close();
512
+ this._detachWsListeners();
513
+ this._stateNotifier.subjects["my-presence"].next(null);
514
+ this._stateNotifier.subjects["myself"].next(null);
515
+ }
516
+ _detachWindowListeners() {
517
+ if (!this._windowListeners)
518
+ return;
519
+ if (typeof window === "undefined")
520
+ return;
521
+ if (typeof document === "undefined")
522
+ return;
523
+ window.removeEventListener(
524
+ "online",
525
+ this._windowListeners.onNavigatorOnline
526
+ );
527
+ document.removeEventListener(
528
+ "visibilitychange",
529
+ this._windowListeners.onVisibilityChange
530
+ );
531
+ this._windowListeners = null;
532
+ }
533
+ _detachWsListeners() {
534
+ if (!this._state.webSocket || !this._wsListeners)
535
+ return;
536
+ this._state.webSocket.removeEventListener(
537
+ "close",
538
+ this._wsListeners.onClose
539
+ );
540
+ this._state.webSocket.removeEventListener(
541
+ "error",
542
+ this._wsListeners.onError
543
+ );
544
+ this._state.webSocket.removeEventListener(
545
+ "message",
546
+ this._wsListeners.onMessage
547
+ );
548
+ this._state.webSocket.removeEventListener(
549
+ "open",
550
+ this._wsListeners.onOpen
551
+ );
552
+ this._wsListeners = null;
553
+ }
554
+ _getAuthorization(room) {
555
+ return __async(this, null, function* () {
556
+ if (!this._endpoints.authEndpoint)
557
+ return null;
558
+ if (typeof this._endpoints.authEndpoint === "string") {
559
+ const token2 = yield fetch(this._endpoints.authEndpoint).then((res) => res.text()).then((text2) => text2.trim());
560
+ return token2;
561
+ }
562
+ const config = this._endpoints.authEndpoint(room);
563
+ const endpoint = typeof config === "string" ? config : config.url;
564
+ const options = typeof config === "string" ? void 0 : config.options;
565
+ const token = yield fetch(endpoint, options).then((res) => res.text()).then((text2) => text2.trim());
566
+ return token;
567
+ });
568
+ }
569
+ _getWsEndpoint(room) {
570
+ if (typeof this._endpoints.wsEndpoint === "string") {
571
+ return this._endpoints.wsEndpoint;
572
+ }
573
+ return this._endpoints.wsEndpoint(room);
574
+ }
575
+ _handleExit(message) {
576
+ const { connectionId } = message;
577
+ if (!connectionId)
578
+ return;
579
+ if (!this._state.webSocket)
580
+ throw new Error("Could not find WebSocket");
581
+ this._usersManager.removeUser(connectionId);
582
+ const others = this._usersManager.getOthers();
583
+ this._stateNotifier.subjects.others.next(others);
584
+ this._otherNotifier.subject(connectionId).next(null);
585
+ this._otherNotifier.subjects.delete(connectionId);
586
+ }
587
+ _handlePresenceUpdatedMessage(message) {
588
+ var _a, _b, _c;
589
+ const { connectionId } = message;
590
+ if (!connectionId)
591
+ return;
592
+ if (!this._state.webSocket)
593
+ throw new Error("Could not find WebSocket");
594
+ const data = message.data;
595
+ this._usersManager.patchPresence(
596
+ connectionId,
597
+ data.presence
598
+ );
599
+ const myPresence = (_b = (_a = this._usersManager.myself) == null ? void 0 : _a.presence) != null ? _b : null;
600
+ const myself = (_c = this._usersManager.myself) != null ? _c : null;
601
+ if ((myself == null ? void 0 : myself.connectionId) === connectionId) {
602
+ this._stateNotifier.subjects["my-presence"].next(myPresence);
603
+ this._stateNotifier.subjects["myself"].next(myself);
604
+ return;
605
+ }
606
+ const other = this._usersManager.getOther(connectionId);
607
+ const others = this._usersManager.getOthers();
608
+ this._otherNotifier.subject(connectionId).next(other);
609
+ this._stateNotifier.subjects["others"].next(others);
610
+ }
611
+ _handleReceiveOthers(message) {
612
+ if (!message.connectionId)
613
+ return;
614
+ if (!this._state.webSocket)
615
+ throw new Error("Could not find WebSocket");
616
+ const data = message.data;
617
+ Object.keys(data.others).forEach((connectionId) => {
618
+ const { presence, user } = data.others[connectionId];
619
+ if (!user)
620
+ return;
621
+ this._usersManager.setUser(connectionId, user);
622
+ const other = this._usersManager.getOther(connectionId);
623
+ !!presence && this._usersManager.patchPresence(
624
+ connectionId,
625
+ presence
626
+ );
627
+ this._otherNotifier.subject(connectionId).next(other);
628
+ });
629
+ const others = this._usersManager.getOthers();
630
+ this._stateNotifier.subjects["others"].next(others);
631
+ }
632
+ _handleRegisteredMessage(message) {
633
+ var _a, _b, _c;
634
+ const { connectionId, user } = message;
635
+ if (!connectionId)
636
+ return;
637
+ if (!this._state.webSocket)
638
+ throw new Error("Could not find WebSocket");
639
+ this._updateState((oldState) => {
640
+ oldState.connection.id = connectionId;
641
+ oldState.authorization.user = user;
642
+ return oldState;
643
+ });
644
+ this._usersManager.setMyself(
645
+ connectionId,
646
+ user
647
+ );
648
+ const myPresence = (_b = (_a = this._usersManager.myself) == null ? void 0 : _a.presence) != null ? _b : null;
649
+ const myself = (_c = this._usersManager.myself) != null ? _c : null;
650
+ this._stateNotifier.subjects["my-presence"].next(myPresence);
651
+ this._stateNotifier.subjects["myself"].next(myself);
652
+ this._sendMessage({ type: "$GET_OTHERS", data: {} });
653
+ }
654
+ _handleStorageReceivedMessage(message) {
655
+ var _a;
656
+ const { connectionId } = message;
657
+ if (!connectionId)
658
+ return;
659
+ if (!this._state.webSocket)
660
+ throw new Error("Could not find WebSocket");
661
+ const data = message.data;
662
+ this._crdtManager = new CrdtManager({
663
+ encodedState: data.state,
664
+ initialStorage: (_a = this._initialStorage) != null ? _a : void 0
665
+ });
666
+ this._observeCrdt();
667
+ const sharedTypes = this._crdtManager.doc.getSharedTypes();
668
+ Object.keys(sharedTypes).forEach((key) => {
669
+ const sharedType = sharedTypes[key];
670
+ const serialized = sharedType.toJSON();
671
+ this._crdtNotifier.subject(key).next(serialized);
672
+ });
673
+ const update = this._crdtManager.doc.encodeStateAsUpdate();
674
+ this._sendMessage({
675
+ type: "$UPDATE_STORAGE",
676
+ data: { origin: "$STORAGE_RECEIVED", update }
677
+ });
678
+ }
679
+ _handleStorageUpdatedMessage(message) {
680
+ const { connectionId } = message;
681
+ if (!connectionId)
682
+ return;
683
+ if (!this._state.webSocket)
684
+ throw new Error("Could not find WebSocket");
685
+ const data = message.data;
686
+ if (!this._crdtManager)
687
+ return;
688
+ const test = (0, import_crdt_yjs2.doc)({});
689
+ test.applyUpdate(data.state);
690
+ this._crdtManager.doc.applyUpdate(data.state, "$STORAGE_UPDATED");
691
+ const sharedTypes = this._crdtManager.doc.getSharedTypes();
692
+ Object.keys(sharedTypes).forEach((key) => {
693
+ if (!this._crdtManager)
694
+ return;
695
+ const sharedType = sharedTypes[key];
696
+ if (!sharedType)
697
+ return;
698
+ const serialized = sharedType.toJSON();
699
+ this._crdtNotifier.subject(key).next(serialized);
700
+ });
701
+ }
702
+ _handleUserJoinedMessage(message) {
703
+ const { connectionId } = message;
704
+ if (!connectionId)
705
+ return;
706
+ if (!this._state.webSocket)
707
+ throw new Error("Could not find WebSocket");
708
+ if (!this._usersManager.myself)
709
+ return;
710
+ const data = message.data;
711
+ this._usersManager.setUser(connectionId, data.user);
712
+ const other = this._usersManager.getOther(connectionId);
713
+ const others = this._usersManager.getOthers();
714
+ this._otherNotifier.subject(connectionId).next(other);
715
+ this._stateNotifier.subjects["others"].next(others);
716
+ }
717
+ _heartbeat() {
718
+ if (!this._state.webSocket)
719
+ return;
720
+ if (!this._state.connection.id)
721
+ return;
722
+ if (this._state.webSocket.readyState !== this._state.webSocket.OPEN) {
723
+ return;
724
+ }
725
+ this._clearTimeout(this._timeouts.pong);
726
+ this._timeouts.pong = setTimeout(
727
+ this._reconnect.bind(this),
728
+ PONG_TIMEOUT_MS
729
+ );
730
+ this._sendMessage({ type: "$PING", data: {} });
731
+ }
732
+ _logDebug(...data) {
733
+ var _a;
734
+ if (((_a = process == null ? void 0 : process.env) == null ? void 0 : _a.NODE_ENV) === "production")
735
+ return;
736
+ this._debug && console.log(...data);
737
+ }
738
+ _observeCrdt() {
739
+ var _a, _b;
740
+ (_b = (_a = this._subscriptions).observeCrdt) == null ? void 0 : _b.call(_a);
741
+ if (!this._crdtManager)
742
+ return;
743
+ const unsubscribe = this._crdtManager.doc.subscribe(
744
+ (update, _origin) => {
745
+ const origin = _origin != null ? _origin : null;
746
+ if (!this._crdtManager)
747
+ return;
748
+ if (!this._state.webSocket)
749
+ return;
750
+ if (!this._state.connection.id)
751
+ return;
752
+ if (this._state.webSocket.readyState !== WebSocket.OPEN)
753
+ return;
754
+ if (origin === "$STORAGE_UPDATED")
755
+ return;
756
+ this._sendMessage({
757
+ type: "$UPDATE_STORAGE",
758
+ data: { origin, update }
759
+ });
760
+ }
761
+ );
762
+ this._subscriptions.observeCrdt = unsubscribe;
763
+ }
764
+ _onAuthorizationFail(error) {
765
+ const authError = error instanceof Error ? error : new Error("Authorization failed");
766
+ this._listeners.onAuthorizationFail(authError);
767
+ this._updateState((oldState) => {
768
+ oldState.connection.state = "Unavailable" /* Unavailable */;
769
+ return oldState;
770
+ });
771
+ }
772
+ _onClose(event) {
773
+ this._logDebug("WebSocket closed");
774
+ !!event.reason && this._logDebug(event.reason);
775
+ this._clearInterval(this._intervals.heartbeat);
776
+ this._clearTimeout(this._timeouts.pong);
777
+ this._updateState((oldState) => {
778
+ oldState.connection.state = "Closed" /* Closed */;
779
+ oldState.webSocket = null;
780
+ return oldState;
781
+ });
782
+ }
783
+ _onError() {
784
+ }
785
+ _onMessage(event) {
786
+ const message = this._parseMessage(event);
787
+ if (!message)
788
+ return;
789
+ const shouldLog = typeof this._debug === "boolean" ? this._debug : this._debug.output.find((value) => value === message.type);
790
+ if (shouldLog) {
791
+ this._logDebug("WebSocket event received: ", message.type, message);
792
+ }
793
+ this._eventNotifier.subject(message.type).next(message);
794
+ const { connectionId } = message;
795
+ if (!connectionId)
796
+ return;
797
+ switch (message.type) {
798
+ case "$EXIT": {
799
+ this._handleExit(message);
800
+ return;
801
+ }
802
+ case "$OTHERS_RECEIVED": {
803
+ this._handleReceiveOthers(message);
804
+ return;
805
+ }
806
+ case "$PONG": {
807
+ this._clearTimeout(this._timeouts.pong);
808
+ return;
809
+ }
810
+ case "$PRESENCE_UPDATED": {
811
+ this._handlePresenceUpdatedMessage(message);
812
+ return;
813
+ }
814
+ case "$REGISTERED": {
815
+ this._handleRegisteredMessage(message);
816
+ return;
817
+ }
818
+ case "$STORAGE_RECEIVED": {
819
+ this._handleStorageReceivedMessage(message);
820
+ return;
821
+ }
822
+ case "$STORAGE_UPDATED": {
823
+ this._handleStorageUpdatedMessage(message);
824
+ return;
825
+ }
826
+ case "$USER_JOINED": {
827
+ this._handleUserJoinedMessage(message);
828
+ return;
829
+ }
830
+ default:
831
+ }
832
+ }
833
+ _onOpen() {
834
+ if (this._state.connection.state !== "Connecting" /* Connecting */)
835
+ return;
836
+ this._logDebug("WebSocket connected");
837
+ this._updateState((oldState) => {
838
+ oldState.connection.state = "Open" /* Open */;
839
+ return oldState;
840
+ });
841
+ this._clearInterval(this._intervals.heartbeat);
842
+ this._intervals.heartbeat = setInterval(
843
+ this._heartbeat.bind(this),
844
+ HEARTBEAT_INTERVAL_MS
845
+ );
846
+ }
847
+ _onNavigatorOnline() {
848
+ return __async(this, null, function* () {
849
+ if (this._state.connection.state !== "Unavailable" /* Unavailable */) {
850
+ return;
851
+ }
852
+ yield this._reconnect();
853
+ });
854
+ }
855
+ _onVisibilityChange() {
856
+ return __async(this, null, function* () {
857
+ if (typeof document === "undefined")
858
+ return;
859
+ if (document.visibilityState !== "visible")
860
+ return;
861
+ switch (this._state.connection.state) {
862
+ case "Open" /* Open */:
863
+ this._clearInterval(this._intervals.heartbeat);
864
+ setInterval(this._heartbeat.bind(this), HEARTBEAT_INTERVAL_MS);
865
+ return;
866
+ case "Unavailable" /* Unavailable */:
867
+ yield this._reconnect();
868
+ return;
869
+ default:
870
+ }
871
+ });
872
+ }
873
+ _parseMessage(message) {
874
+ if (typeof message.data !== "string")
875
+ return null;
876
+ try {
877
+ const config = JSON.parse(message.data);
878
+ if (typeof config !== "object")
879
+ return null;
880
+ if (typeof config.type !== "string")
881
+ return null;
882
+ if (typeof config.data !== "object")
883
+ return null;
884
+ return config;
885
+ } catch (e) {
886
+ return null;
887
+ }
888
+ }
889
+ _reconnect() {
890
+ return __async(this, null, function* () {
891
+ if (!this._endpoints.wsEndpoint) {
892
+ throw new Error("Must provide an wsEndpoint.");
893
+ }
894
+ if (!this._state.webSocket)
895
+ return;
896
+ this._closeWs();
897
+ this._updateState((oldState) => {
898
+ oldState.authorization.token = null;
899
+ oldState.connection.state = "Unavailable" /* Unavailable */;
900
+ oldState.webSocket = null;
901
+ return oldState;
902
+ });
903
+ yield this.connect();
904
+ });
905
+ }
906
+ _sendMessage(data) {
907
+ const webSocket = this._state.webSocket;
908
+ if ((webSocket == null ? void 0 : webSocket.readyState) !== WebSocket.OPEN)
909
+ return;
910
+ const shouldLog = typeof this._debug === "boolean" ? this._debug : this._debug.input.find((value) => value === data.type);
911
+ if (shouldLog) {
912
+ this._logDebug("WebSocket event sent: ", data.type, data);
913
+ }
914
+ webSocket.send(JSON.stringify(data));
915
+ }
916
+ _updateState(updater) {
917
+ let authorization;
918
+ try {
919
+ authorization = JSON.parse(
920
+ JSON.stringify(this._state.authorization)
921
+ );
922
+ } catch (e) {
923
+ throw new Error("User is not JSON serializable");
924
+ }
925
+ const oldState = __spreadProps(__spreadValues({}, this._state), {
926
+ authorization,
927
+ connection: JSON.parse(JSON.stringify(this._state.connection)),
928
+ webSocket: this._state.webSocket
929
+ });
930
+ const newState = updater(oldState);
931
+ this._logDebug("WebSocket new state: ", newState);
932
+ this._state = newState;
933
+ this._stateNotifier.subjects.connection.next(newState);
934
+ return newState;
935
+ }
936
+ };
937
+
938
+ // src/PluvClient.ts
939
+ var PluvClient = class {
940
+ constructor(options) {
941
+ this._rooms = /* @__PURE__ */ new Map();
942
+ this.createRoom = (room, options) => {
943
+ const oldRoom = this.getRoom(room);
944
+ if (oldRoom)
945
+ return oldRoom;
946
+ const newRoom = new PluvRoom(room, {
947
+ authEndpoint: this._authEndpoint,
948
+ debug: options.debug,
949
+ initialPresence: options.initialPresence,
950
+ initialStorage: options.initialStorage,
951
+ onAuthorizationFail: options.onAuthorizationFail,
952
+ wsEndpoint: this._wsEndpoint
953
+ });
954
+ this._rooms.set(room, newRoom);
955
+ return newRoom;
956
+ };
957
+ this.enter = (room) => __async(this, null, function* () {
958
+ const toEnter = this.getRoom(room);
959
+ if (!toEnter) {
960
+ throw new Error(`Could not find room: ${room}.`);
961
+ }
962
+ yield toEnter.connect();
963
+ });
964
+ this.getRoom = (room) => {
965
+ const found = this._rooms.get(room);
966
+ return found != null ? found : null;
967
+ };
968
+ this.leave = (room) => {
969
+ const toLeave = this.getRoom(room);
970
+ if (!toLeave)
971
+ return;
972
+ toLeave.disconnect();
973
+ this._rooms.delete(room);
974
+ };
975
+ this._authEndpoint = options.authEndpoint;
976
+ this._wsEndpoint = options.wsEndpoint;
977
+ }
978
+ };
979
+
980
+ // src/createClient.ts
981
+ var createClient = (options) => {
982
+ return new PluvClient(options);
983
+ };
984
+
985
+ // src/y.ts
986
+ var y_exports = {};
987
+ __export(y_exports, {
988
+ array: () => import_crdt_yjs3.array,
989
+ map: () => import_crdt_yjs3.map,
990
+ text: () => import_crdt_yjs3.text,
991
+ unstable__object: () => import_crdt_yjs3.unstable__object
992
+ });
993
+ var import_crdt_yjs3 = require("@pluv/crdt-yjs");
994
+ // Annotate the CommonJS export names for ESM import in node:
995
+ 0 && (module.exports = {
996
+ ConnectionState,
997
+ PluvClient,
998
+ PluvRoom,
999
+ createClient,
1000
+ y
1001
+ });