@nolag/notify 1.0.0 → 1.2.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.
@@ -0,0 +1,1016 @@
1
+ /**
2
+ * Tiny typed event emitter — framework-agnostic base for NoLag SDKs.
3
+ */
4
+ class EventEmitter {
5
+ constructor() {
6
+ this._handlers = new Map();
7
+ }
8
+ on(event, handler) {
9
+ if (!this._handlers.has(event)) {
10
+ this._handlers.set(event, new Set());
11
+ }
12
+ this._handlers.get(event).add(handler);
13
+ return this;
14
+ }
15
+ off(event, handler) {
16
+ if (handler) {
17
+ this._handlers.get(event)?.delete(handler);
18
+ }
19
+ else {
20
+ this._handlers.delete(event);
21
+ }
22
+ return this;
23
+ }
24
+ removeAllListeners() {
25
+ this._handlers.clear();
26
+ return this;
27
+ }
28
+ emit(event, ...args) {
29
+ const handlers = this._handlers.get(event);
30
+ if (!handlers)
31
+ return;
32
+ for (const handler of handlers) {
33
+ try {
34
+ handler(...args);
35
+ }
36
+ catch (e) {
37
+ console.error(`Error in ${String(event)} handler:`, e);
38
+ }
39
+ }
40
+ }
41
+ listenerCount(event) {
42
+ return this._handlers.get(event)?.size ?? 0;
43
+ }
44
+ }
45
+
46
+ /**
47
+ * Bounded, deduplicated notification cache ordered by timestamp,
48
+ * with read/unread tracking.
49
+ */
50
+ class NotificationStore {
51
+ constructor(maxSize) {
52
+ this._notifications = [];
53
+ this._ids = new Set();
54
+ this._maxSize = maxSize;
55
+ }
56
+ /**
57
+ * Add a notification. Returns true if the notification was new (not a duplicate).
58
+ */
59
+ add(notification) {
60
+ if (this._ids.has(notification.id)) {
61
+ return false;
62
+ }
63
+ this._ids.add(notification.id);
64
+ this._notifications.push(notification);
65
+ // Keep sorted by timestamp
66
+ if (this._notifications.length > 1 &&
67
+ notification.timestamp < this._notifications[this._notifications.length - 2].timestamp) {
68
+ this._notifications.sort((a, b) => a.timestamp - b.timestamp);
69
+ }
70
+ // Trim if over capacity
71
+ while (this._notifications.length > this._maxSize) {
72
+ const removed = this._notifications.shift();
73
+ this._ids.delete(removed.id);
74
+ }
75
+ return true;
76
+ }
77
+ /**
78
+ * Mark a notification as read by id.
79
+ * Returns true if the notification was found.
80
+ */
81
+ markRead(id) {
82
+ const notification = this._notifications.find((n) => n.id === id);
83
+ if (!notification)
84
+ return false;
85
+ notification.read = true;
86
+ return true;
87
+ }
88
+ /**
89
+ * Mark all notifications as read.
90
+ */
91
+ markAllRead() {
92
+ for (const notification of this._notifications) {
93
+ notification.read = true;
94
+ }
95
+ }
96
+ /**
97
+ * Get all notifications in timestamp order.
98
+ */
99
+ getAll() {
100
+ return [...this._notifications];
101
+ }
102
+ /**
103
+ * Get all unread notifications.
104
+ */
105
+ getUnread() {
106
+ return this._notifications.filter((n) => !n.read);
107
+ }
108
+ /**
109
+ * Get the number of unread notifications.
110
+ */
111
+ get unreadCount() {
112
+ return this._notifications.filter((n) => !n.read).length;
113
+ }
114
+ /**
115
+ * Get notification count.
116
+ */
117
+ get size() {
118
+ return this._notifications.length;
119
+ }
120
+ /**
121
+ * Check if a notification ID exists.
122
+ */
123
+ has(id) {
124
+ return this._ids.has(id);
125
+ }
126
+ /**
127
+ * Clear all notifications.
128
+ */
129
+ clear() {
130
+ this._notifications = [];
131
+ this._ids.clear();
132
+ }
133
+ }
134
+
135
+ function generateId() {
136
+ if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
137
+ return crypto.randomUUID();
138
+ }
139
+ return 'xxxx-xxxx-xxxx-xxxx'.replace(/x/g, () => Math.floor(Math.random() * 16).toString(16));
140
+ }
141
+ function createLogger(prefix, enabled) {
142
+ if (!enabled) {
143
+ return (..._args) => { };
144
+ }
145
+ return (...args) => {
146
+ console.log(`[${prefix}]`, ...args);
147
+ };
148
+ }
149
+ // ============ Filters ============
150
+ /**
151
+ * Build the filter fragment of an emit options object.
152
+ *
153
+ * `filter` wins over `filters`: a publish is routed to exactly one topic, so
154
+ * honouring both would silently drop one of them.
155
+ */
156
+ function filterEmitOptions(opts) {
157
+ if (opts?.filter)
158
+ return { filter: opts.filter };
159
+ if (opts?.filters && opts.filters.length > 0)
160
+ return { filters: opts.filters };
161
+ return {};
162
+ }
163
+ /**
164
+ * Merge OR terms into an existing filter set. AND groups (nested arrays) are
165
+ * preserved as-is — only plain string terms are deduplicated.
166
+ */
167
+ function mergeFilters(existing, add) {
168
+ const simple = new Set();
169
+ const groups = [];
170
+ for (const f of existing) {
171
+ if (typeof f === 'string')
172
+ simple.add(f);
173
+ else
174
+ groups.push(f);
175
+ }
176
+ for (const v of add)
177
+ simple.add(v);
178
+ return [...simple, ...groups];
179
+ }
180
+ /**
181
+ * Drop OR terms from a filter set. AND groups are left untouched — remove
182
+ * those by calling `setFilters` with the set you want.
183
+ */
184
+ function withoutFilters(existing, remove) {
185
+ const drop = new Set(remove);
186
+ return existing.filter((f) => typeof f !== 'string' || !drop.has(f));
187
+ }
188
+ // ============ Wrapper registry ============
189
+ // One wrapper instance per (client, appName): two wrappers sharing an app on
190
+ // one connection would collide on topics, presence and the online lobby.
191
+ // Warn (not throw): HMR and tests legitimately construct before disposing.
192
+ const wrapperRegistry = new WeakMap();
193
+ /** Register a wrapper against a client + appName; warns on collision. */
194
+ function registerWrapper(client, appName, wrapperName) {
195
+ let apps = wrapperRegistry.get(client);
196
+ if (!apps) {
197
+ apps = new Map();
198
+ wrapperRegistry.set(client, apps);
199
+ }
200
+ const existing = apps.get(appName);
201
+ if (existing) {
202
+ console.warn(`[${wrapperName}] Another wrapper (${existing}) is already attached to this client for app "${appName}". ` +
203
+ `Use one wrapper per (client, app) — detach the other instance first.`);
204
+ }
205
+ apps.set(appName, wrapperName);
206
+ }
207
+ /** Release a wrapper's (client, appName) registration on detach. */
208
+ function releaseWrapper(client, appName) {
209
+ wrapperRegistry.get(client)?.delete(appName);
210
+ }
211
+
212
+ /** Default app name for channel topic prefixes */
213
+ const DEFAULT_APP_NAME = 'notify';
214
+ /** Default max notifications kept per channel */
215
+ const DEFAULT_MAX_NOTIFICATION_CACHE = 500;
216
+ /** Topic name for notifications within a channel */
217
+ const TOPIC_NOTIFICATIONS = 'notifications';
218
+ /** Topic name for read receipts within a channel */
219
+ const TOPIC_READ = '_read';
220
+ /** Lobby ID for global online presence */
221
+ const LOBBY_ID = 'online';
222
+ /** Delay before the post-setup lobby presence refetch (catches simultaneous joiners) */
223
+ const LOBBY_REFRESH_DELAY_MS = 2000;
224
+
225
+ /**
226
+ * NotifyChannel — a single notification channel with read/unread tracking.
227
+ *
228
+ * Created via `NoLagNotify.subscribe(name)`. Do not instantiate directly.
229
+ */
230
+ class NotifyChannel extends EventEmitter {
231
+ /** @internal */
232
+ constructor(name, roomContext, options, log, isConnected) {
233
+ super();
234
+ this._active = false;
235
+ this._filters = [];
236
+ // Stored topic handler refs — cleanup removes exactly these, never all
237
+ // handlers for a topic (the client may be shared with other consumers).
238
+ this._onNotificationsRef = null;
239
+ this._onReadRef = null;
240
+ this.name = name;
241
+ this._roomContext = roomContext;
242
+ this._options = options;
243
+ this._store = new NotificationStore(options.maxNotificationCache);
244
+ this._log = log;
245
+ this._isConnected = isConnected;
246
+ }
247
+ // ============ Public Properties ============
248
+ /** All notifications in this channel (timestamp order) */
249
+ get notifications() {
250
+ return this._store.getAll();
251
+ }
252
+ /** Number of unread notifications */
253
+ get unreadCount() {
254
+ return this._store.unreadCount;
255
+ }
256
+ /** Whether this channel is currently active */
257
+ get active() {
258
+ return this._active;
259
+ }
260
+ // ============ Sending ============
261
+ /**
262
+ * Send a notification to this channel.
263
+ */
264
+ send(title, opts) {
265
+ const notification = {
266
+ id: generateId(),
267
+ channel: this.name,
268
+ title,
269
+ body: opts?.body,
270
+ icon: opts?.icon,
271
+ data: opts?.data,
272
+ timestamp: Date.now()};
273
+ const payload = {
274
+ id: notification.id,
275
+ channel: notification.channel,
276
+ title: notification.title,
277
+ body: notification.body,
278
+ icon: notification.icon,
279
+ data: notification.data,
280
+ timestamp: notification.timestamp,
281
+ };
282
+ // Only pass options when there is a filter: an unfiltered send should look
283
+ // exactly as it did before filters existed.
284
+ const emitOpts = filterEmitOptions(opts);
285
+ if (Object.keys(emitOpts).length > 0) {
286
+ this._roomContext.emit(TOPIC_NOTIFICATIONS, payload, emitOpts);
287
+ }
288
+ else {
289
+ this._roomContext.emit(TOPIC_NOTIFICATIONS, payload);
290
+ }
291
+ }
292
+ // ============ Filters ============
293
+ /** The filter values currently applied to this channel. */
294
+ get filters() {
295
+ return [...this._filters];
296
+ }
297
+ /**
298
+ * Replace this channel's filters — only notifications published with one of
299
+ * these values are delivered. Subscribe with your own user id (or role) to
300
+ * receive only what was addressed to you.
301
+ *
302
+ * Passing an empty array clears filtering and restores the wildcard
303
+ * subscription, which receives every notification on the channel.
304
+ *
305
+ * @example
306
+ * ```ts
307
+ * channel.setFilters(['user-42', 'all-hands']); // mine OR broadcast
308
+ * channel.setFilters([['eu', 'admin']]); // eu AND admin
309
+ * channel.setFilters([]); // everything
310
+ * ```
311
+ */
312
+ setFilters(values) {
313
+ this._filters = [...values];
314
+ // The core types filters as `string[]`, but both its implementation and
315
+ // the wire protocol accept AND groups (nested arrays).
316
+ this._roomContext.setFilters(TOPIC_NOTIFICATIONS, this._filters);
317
+ }
318
+ /** Add filter values to the existing set. Existing AND groups are kept. */
319
+ addFilters(values) {
320
+ this.setFilters(mergeFilters(this._filters, values));
321
+ }
322
+ /**
323
+ * Remove filter values from the existing set. Removing the last value
324
+ * restores the wildcard subscription.
325
+ */
326
+ removeFilters(values) {
327
+ this.setFilters(withoutFilters(this._filters, values));
328
+ }
329
+ // ============ Read Tracking ============
330
+ /**
331
+ * Mark a single notification as read by id.
332
+ * Emits the read receipt to the _read topic for cross-tab sync.
333
+ */
334
+ markRead(id) {
335
+ if (this._store.markRead(id)) {
336
+ this._log('Mark read:', id);
337
+ this._roomContext.emit(TOPIC_READ, { id, channel: this.name });
338
+ this.emit('read', id);
339
+ }
340
+ }
341
+ /**
342
+ * Mark all notifications in this channel as read.
343
+ */
344
+ markAllRead() {
345
+ this._store.markAllRead();
346
+ this._log('Mark all read:', this.name);
347
+ this._roomContext.emit(TOPIC_READ, { all: true, channel: this.name });
348
+ this.emit('readAll');
349
+ }
350
+ /**
351
+ * Get all notifications (alias for the notifications getter).
352
+ */
353
+ getNotifications() {
354
+ return this._store.getAll();
355
+ }
356
+ /**
357
+ * Get all unread notifications.
358
+ */
359
+ getUnread() {
360
+ return this._store.getUnread();
361
+ }
362
+ // ============ Internal (called by NoLagNotify) ============
363
+ /** @internal Subscribe to notifications and _read topics */
364
+ _subscribe(filters) {
365
+ this._log('Channel subscribe:', this.name);
366
+ this._filters = filters ? [...filters] : [];
367
+ // Read receipts stay unfiltered: they are this user's own cross-tab sync.
368
+ if (this._filters.length > 0) {
369
+ this._roomContext.subscribe(TOPIC_NOTIFICATIONS, { filters: this._filters });
370
+ }
371
+ else {
372
+ this._roomContext.subscribe(TOPIC_NOTIFICATIONS);
373
+ }
374
+ this._roomContext.subscribe(TOPIC_READ);
375
+ // Listen for notifications (refs stored for handler-specific removal)
376
+ this._onNotificationsRef = (data, meta) => {
377
+ this._handleIncomingNotification(data, meta);
378
+ };
379
+ this._roomContext.on(TOPIC_NOTIFICATIONS, this._onNotificationsRef);
380
+ this._onReadRef = (data) => {
381
+ this._handleIncomingRead(data);
382
+ };
383
+ this._roomContext.on(TOPIC_READ, this._onReadRef);
384
+ }
385
+ /** @internal Activate this channel (mark as visible/active) */
386
+ _activate() {
387
+ this._log('Channel activate:', this.name);
388
+ this._active = true;
389
+ }
390
+ /** @internal Deactivate this channel */
391
+ _deactivate() {
392
+ this._log('Channel deactivate:', this.name);
393
+ this._active = false;
394
+ }
395
+ /** @internal Handle replay start event */
396
+ _handleReplayStart(count) {
397
+ this.emit('replayStart', { count });
398
+ }
399
+ /** @internal Handle replay end event */
400
+ _handleReplayEnd(replayed) {
401
+ this.emit('replayEnd', { replayed });
402
+ }
403
+ /** @internal Unsubscribe and clean up */
404
+ _cleanup() {
405
+ this._log('Channel cleanup:', this.name);
406
+ // Server unsubscribes need a live socket; skip when disconnected
407
+ // (best-effort — the core would no-op with an error callback anyway).
408
+ if (this._isConnected()) {
409
+ this._roomContext.unsubscribe(TOPIC_NOTIFICATIONS);
410
+ this._roomContext.unsubscribe(TOPIC_READ);
411
+ }
412
+ // Handler-specific removal only: the client may be shared, and a bare
413
+ // off(topic) would strip other consumers' handlers too.
414
+ if (this._onNotificationsRef)
415
+ this._roomContext.off(TOPIC_NOTIFICATIONS, this._onNotificationsRef);
416
+ if (this._onReadRef)
417
+ this._roomContext.off(TOPIC_READ, this._onReadRef);
418
+ this._onNotificationsRef = null;
419
+ this._onReadRef = null;
420
+ this._store.clear();
421
+ this.removeAllListeners();
422
+ }
423
+ // ============ Private ============
424
+ _handleIncomingNotification(data, meta) {
425
+ const raw = data;
426
+ const notification = {
427
+ id: raw.id || generateId(),
428
+ channel: this.name,
429
+ title: raw.title,
430
+ body: raw.body,
431
+ icon: raw.icon,
432
+ data: raw.data,
433
+ timestamp: raw.timestamp || Date.now(),
434
+ read: false,
435
+ isReplay: meta.isReplay ?? false,
436
+ };
437
+ if (this._store.add(notification)) {
438
+ this._log('Notification received:', notification.id, notification.title);
439
+ this.emit('notification', notification);
440
+ }
441
+ }
442
+ _handleIncomingRead(data) {
443
+ const raw = data;
444
+ if (raw.all === true) {
445
+ this._store.markAllRead();
446
+ this.emit('readAll');
447
+ }
448
+ else if (typeof raw.id === 'string') {
449
+ if (this._store.markRead(raw.id)) {
450
+ this.emit('read', raw.id);
451
+ }
452
+ }
453
+ }
454
+ }
455
+
456
+ /**
457
+ * Aggregates unread notification counts across channels.
458
+ */
459
+ class BadgeManager {
460
+ constructor() {
461
+ this._counts = new Map();
462
+ }
463
+ /**
464
+ * Update the unread count for a channel.
465
+ */
466
+ update(channel, unreadCount) {
467
+ this._counts.set(channel, unreadCount);
468
+ }
469
+ /**
470
+ * Get the unread count for a specific channel.
471
+ */
472
+ get(channel) {
473
+ return this._counts.get(channel) ?? 0;
474
+ }
475
+ /**
476
+ * Get all badge counts — total and per-channel breakdown.
477
+ */
478
+ getAll() {
479
+ const byChannel = {};
480
+ let total = 0;
481
+ for (const [channel, count] of this._counts) {
482
+ byChannel[channel] = count;
483
+ total += count;
484
+ }
485
+ return { total, byChannel };
486
+ }
487
+ /**
488
+ * Clear all counts.
489
+ */
490
+ clear() {
491
+ this._counts.clear();
492
+ }
493
+ }
494
+
495
+ /**
496
+ * Maps actorTokenId to NotifyUser for global presence tracking.
497
+ */
498
+ class PresenceManager {
499
+ constructor() {
500
+ this._users = new Map();
501
+ this._actorToUserId = new Map();
502
+ }
503
+ /**
504
+ * Add or update a user from presence data.
505
+ * Returns the NotifyUser, or null if presence data is invalid.
506
+ */
507
+ addFromPresence(actorTokenId, presenceData, joinedAt) {
508
+ if (!presenceData?.userId)
509
+ return null;
510
+ const existing = this._actorToUserId.get(actorTokenId);
511
+ const userId = presenceData.userId || existing || actorTokenId;
512
+ const user = {
513
+ userId,
514
+ actorTokenId,
515
+ metadata: presenceData.metadata,
516
+ joinedAt: joinedAt || Date.now(),
517
+ };
518
+ this._users.set(userId, user);
519
+ this._actorToUserId.set(actorTokenId, userId);
520
+ return user;
521
+ }
522
+ /**
523
+ * Remove a user by actorTokenId.
524
+ * Returns the removed user, or null if not found.
525
+ */
526
+ removeByActorId(actorTokenId) {
527
+ const userId = this._actorToUserId.get(actorTokenId);
528
+ if (!userId)
529
+ return null;
530
+ const user = this._users.get(userId) || null;
531
+ this._users.delete(userId);
532
+ this._actorToUserId.delete(actorTokenId);
533
+ return user;
534
+ }
535
+ /**
536
+ * Get a user by userId.
537
+ */
538
+ getUser(userId) {
539
+ return this._users.get(userId);
540
+ }
541
+ /**
542
+ * Get a user by actorTokenId.
543
+ */
544
+ getUserByActorId(actorTokenId) {
545
+ const userId = this._actorToUserId.get(actorTokenId);
546
+ return userId ? this._users.get(userId) : undefined;
547
+ }
548
+ /**
549
+ * Get all tracked users.
550
+ */
551
+ getAll() {
552
+ return Array.from(this._users.values());
553
+ }
554
+ /**
555
+ * Clear all tracked users.
556
+ */
557
+ clear() {
558
+ this._users.clear();
559
+ this._actorToUserId.clear();
560
+ }
561
+ }
562
+
563
+ /**
564
+ * NoLagNotify — high-level notifications SDK built on @nolag/js-sdk.
565
+ *
566
+ * Provides multi-channel notifications, read/unread tracking, badge counts,
567
+ * message replay, and global presence — all framework-agnostic via events.
568
+ *
569
+ * The wrapper NEVER manages the connection. The app owns one core NoLag
570
+ * client (shared by any number of wrappers on distinct apps) and the
571
+ * wrapper attaches to it at construction and releases it via `detach()`.
572
+ *
573
+ * @example
574
+ * ```typescript
575
+ * import { NoLag } from '@nolag/js-sdk';
576
+ * import { NoLagNotify } from '@nolag/notify';
577
+ *
578
+ * const client = NoLag(async () => (await (await fetch('/api/nolag-token')).json()).token);
579
+ * const notify = new NoLagNotify({ client, appName: 'my-notify' });
580
+ *
581
+ * notify.on('notification', (n) => console.log('New notification:', n.title));
582
+ *
583
+ * await client.connect(); // the app owns the connection
584
+ * await notify.ready(); // wrapper setup done (identity, lobby, channels)
585
+ *
586
+ * const alerts = notify.subscribe('alerts');
587
+ * alerts.on('notification', (n) => console.log(n.title));
588
+ *
589
+ * notify.detach(); // wrapper releases its handlers and topics
590
+ * client.disconnect(); // the app closes the socket
591
+ * ```
592
+ */
593
+ class NoLagNotify extends EventEmitter {
594
+ constructor(options) {
595
+ super();
596
+ this._channels = new Map();
597
+ this._lobby = null;
598
+ this._badgeManager = new BadgeManager();
599
+ this._presenceManager = new PresenceManager();
600
+ this._actorToUserId = new Map();
601
+ // Lifecycle: one setup run per connection epoch; detach is terminal.
602
+ this._epoch = 0;
603
+ this._detached = false;
604
+ this._isReady = false;
605
+ this._lobbyRefreshTimer = null;
606
+ // Stored client handler refs. INVARIANT: every client.on() below has a
607
+ // matching client.off() in detach() — never bare off(event), never inline
608
+ // closures on the client.
609
+ this._onConnectRef = () => this._onConnect();
610
+ this._onDisconnectRef = (reason) => {
611
+ this._log('Disconnected:', reason);
612
+ this.emit('disconnected', reason);
613
+ };
614
+ this._onReconnectRef = () => {
615
+ this._log('Reconnecting...');
616
+ this.emit('reconnecting');
617
+ };
618
+ this._onErrorRef = (error) => {
619
+ this._log('Error:', error);
620
+ this.emit('error', error);
621
+ };
622
+ this._onReplayStartRef = (data) => {
623
+ const event = data;
624
+ for (const channel of this._channels.values()) {
625
+ channel._handleReplayStart(event.count);
626
+ }
627
+ };
628
+ this._onReplayEndRef = (data) => {
629
+ const event = data;
630
+ for (const channel of this._channels.values()) {
631
+ channel._handleReplayEnd(event.replayed);
632
+ }
633
+ };
634
+ this._onPresenceJoinRef = (data) => this._handleRoomPresenceJoin(data);
635
+ this._onPresenceLeaveRef = (data) => this._handleRoomPresenceLeave(data);
636
+ this._onPresenceUpdateRef = (data) => this._handleRoomPresenceUpdate(data);
637
+ this._onLobbyJoinRef = (data) => this._handleLobbyJoin(data);
638
+ this._onLobbyLeaveRef = (data) => this._handleLobbyLeave(data);
639
+ this._onLobbyUpdateRef = (data) => this._handleLobbyUpdate(data);
640
+ if (!options?.client) {
641
+ throw new TypeError('NoLagNotify requires an injected NoLag client: new NoLagNotify({ client, ... })');
642
+ }
643
+ this._client = options.client;
644
+ this._userId = generateId();
645
+ this._options = {
646
+ metadata: options.metadata,
647
+ appName: options.appName ?? DEFAULT_APP_NAME,
648
+ maxNotificationCache: options.maxNotificationCache ?? DEFAULT_MAX_NOTIFICATION_CACHE,
649
+ debug: options.debug ?? false,
650
+ channels: options.channels ?? [],
651
+ };
652
+ this._log = createLogger('NoLagNotify', this._options.debug);
653
+ this._readyPromise = new Promise((resolve, reject) => {
654
+ this._readyResolve = resolve;
655
+ this._readyReject = reject;
656
+ });
657
+ // ready() rejection is only meaningful to callers that await it
658
+ this._readyPromise.catch(() => { });
659
+ registerWrapper(this._client, this._options.appName, 'NoLagNotify');
660
+ // Construction = attach: wire everything now, with stored refs.
661
+ this._client.on('connect', this._onConnectRef);
662
+ this._client.on('disconnect', this._onDisconnectRef);
663
+ this._client.on('reconnect', this._onReconnectRef);
664
+ this._client.on('error', this._onErrorRef);
665
+ this._client.on('replay:start', this._onReplayStartRef);
666
+ this._client.on('replay:end', this._onReplayEndRef);
667
+ this._client.on('presence:join', this._onPresenceJoinRef);
668
+ this._client.on('presence:leave', this._onPresenceLeaveRef);
669
+ this._client.on('presence:update', this._onPresenceUpdateRef);
670
+ this._client.on('lobbyPresence:join', this._onLobbyJoinRef);
671
+ this._client.on('lobbyPresence:leave', this._onLobbyLeaveRef);
672
+ this._client.on('lobbyPresence:update', this._onLobbyUpdateRef);
673
+ // Attach-to-connected: if the client is already authenticated, run setup.
674
+ // The microtask lets the caller wire wrapper event handlers synchronously
675
+ // first; a racing real 'connect' event wins via the epoch guard.
676
+ queueMicrotask(() => {
677
+ if (this._epoch === 0 && !this._detached && this._client.connected) {
678
+ this._onConnect();
679
+ }
680
+ });
681
+ }
682
+ // ============ Public Properties ============
683
+ /** Whether the underlying connection is established (connected ≠ ready) */
684
+ get connected() {
685
+ return !this._detached && this._client.connected;
686
+ }
687
+ /** The injected core client (owned by the app, not the wrapper) */
688
+ get client() {
689
+ return this._client;
690
+ }
691
+ /** All currently subscribed channels */
692
+ get channels() {
693
+ return this._channels;
694
+ }
695
+ // ============ Lifecycle ============
696
+ /**
697
+ * Resolves once the wrapper's first setup completed (identity, lobby and
698
+ * configured channels ready — equivalently, once 'connected' has fired).
699
+ * Rejects only if detach() is called before that. Client auth failures
700
+ * surface via the app's own `await client.connect()`, not here.
701
+ */
702
+ ready() {
703
+ return this._readyPromise;
704
+ }
705
+ /**
706
+ * Detach from the client: remove every handler this wrapper added,
707
+ * unsubscribe its topics and lobby (when connected), clear state.
708
+ * Terminal and idempotent; never touches the socket. To use notify again,
709
+ * construct a new instance.
710
+ */
711
+ detach() {
712
+ if (this._detached)
713
+ return;
714
+ this._log('Detaching...');
715
+ this._detached = true;
716
+ this._epoch++; // aborts any in-flight setup at its next checkpoint
717
+ if (this._lobbyRefreshTimer) {
718
+ clearTimeout(this._lobbyRefreshTimer);
719
+ this._lobbyRefreshTimer = null;
720
+ }
721
+ // Remove all client handlers by stored ref
722
+ this._client.off('connect', this._onConnectRef);
723
+ this._client.off('disconnect', this._onDisconnectRef);
724
+ this._client.off('reconnect', this._onReconnectRef);
725
+ this._client.off('error', this._onErrorRef);
726
+ this._client.off('replay:start', this._onReplayStartRef);
727
+ this._client.off('replay:end', this._onReplayEndRef);
728
+ this._client.off('presence:join', this._onPresenceJoinRef);
729
+ this._client.off('presence:leave', this._onPresenceLeaveRef);
730
+ this._client.off('presence:update', this._onPresenceUpdateRef);
731
+ this._client.off('lobbyPresence:join', this._onLobbyJoinRef);
732
+ this._client.off('lobbyPresence:leave', this._onLobbyLeaveRef);
733
+ this._client.off('lobbyPresence:update', this._onLobbyUpdateRef);
734
+ // Channels: handler-specific off + connected-gated server unsubscribe
735
+ for (const name of [...this._channels.keys()]) {
736
+ this._channels.get(name)._cleanup();
737
+ this._channels.delete(name);
738
+ }
739
+ // Lobby: server unsubscribe is best-effort and needs a live socket
740
+ if (this._lobby && this._client.connected) {
741
+ try {
742
+ this._lobby.unsubscribe();
743
+ }
744
+ catch {
745
+ /* best-effort */
746
+ }
747
+ }
748
+ this._lobby = null;
749
+ this._badgeManager.clear();
750
+ this._presenceManager.clear();
751
+ this._actorToUserId.clear();
752
+ releaseWrapper(this._client, this._options.appName);
753
+ if (!this._isReady) {
754
+ this._readyReject(new Error('NoLagNotify detached before ready'));
755
+ }
756
+ }
757
+ // ============ Private: Epoch Setup ============
758
+ _onConnect() {
759
+ this._epoch++;
760
+ void this._runSetup(this._epoch);
761
+ }
762
+ /**
763
+ * One setup pass per connection epoch. Serves both initial setup (epoch 1)
764
+ * and reconnect restore (epoch > 1). Aborts silently whenever a newer
765
+ * epoch started or the wrapper detached — checked after every await.
766
+ */
767
+ async _runSetup(epoch) {
768
+ const stale = () => epoch !== this._epoch || this._detached;
769
+ this._log(this._isReady ? 'Restoring after reconnect...' : 'Setting up...');
770
+ this._log('Local userId:', this._userId, '→ actorId:', this._client.actorId);
771
+ // Lobby: subscribe every epoch (idempotent server-side) and diff-hydrate
772
+ // from the returned snapshot — one path for setup and restore.
773
+ if (!this._lobby) {
774
+ this._lobby = this._client.setApp(this._options.appName).setLobby(LOBBY_ID);
775
+ }
776
+ try {
777
+ const state = await this._lobby.subscribe();
778
+ if (stale())
779
+ return;
780
+ this._diffHydratePresence(state);
781
+ this._log('Lobby subscribed');
782
+ }
783
+ catch (err) {
784
+ if (stale())
785
+ return;
786
+ this._log('Lobby subscription failed:', err);
787
+ }
788
+ // First successful setup: pre-subscribe configured channels. The core
789
+ // auto-restores topic subscriptions on reconnect, so later epochs skip it.
790
+ if (!this._isReady) {
791
+ for (const channelName of this._options.channels) {
792
+ this._subscribeChannel(channelName);
793
+ }
794
+ }
795
+ if (stale())
796
+ return;
797
+ // Ready keys on the first setup that COMPLETES, not on epoch 1: an
798
+ // epoch aborted by a racing reconnect must not strand ready().
799
+ if (!this._isReady) {
800
+ this._isReady = true;
801
+ this._readyResolve();
802
+ this.emit('connected');
803
+ }
804
+ else {
805
+ this.emit('reconnected');
806
+ }
807
+ // Deferred lobby refetch: catches users who joined during the setup
808
+ // window (e.g. simultaneous multi-tab connects).
809
+ this._scheduleLobbyRefresh(epoch);
810
+ }
811
+ _scheduleLobbyRefresh(epoch) {
812
+ if (this._lobbyRefreshTimer)
813
+ clearTimeout(this._lobbyRefreshTimer);
814
+ this._lobbyRefreshTimer = setTimeout(() => {
815
+ this._lobbyRefreshTimer = null;
816
+ if (epoch !== this._epoch || this._detached || !this._client.connected || !this._lobby) {
817
+ return;
818
+ }
819
+ this._lobby
820
+ .fetchPresence()
821
+ .then((state) => {
822
+ if (epoch !== this._epoch || this._detached)
823
+ return;
824
+ this._diffHydratePresence(state);
825
+ })
826
+ .catch(() => {
827
+ /* best-effort */
828
+ });
829
+ }, LOBBY_REFRESH_DELAY_MS);
830
+ }
831
+ // ============ Channel Management ============
832
+ /**
833
+ * Subscribe to a notification channel (idempotent).
834
+ * Returns the NotifyChannel instance.
835
+ */
836
+ subscribe(channelName, opts) {
837
+ this._assertUsable();
838
+ const existing = this._channels.get(channelName);
839
+ if (existing) {
840
+ // Already subscribed — re-point its filters rather than ignoring them.
841
+ if (opts?.filters)
842
+ existing.setFilters(opts.filters);
843
+ return existing;
844
+ }
845
+ const channel = this._subscribeChannel(channelName, opts?.filters);
846
+ channel._activate();
847
+ return channel;
848
+ }
849
+ /**
850
+ * Unsubscribe from a notification channel.
851
+ */
852
+ unsubscribe(channelName) {
853
+ const channel = this._channels.get(channelName);
854
+ if (!channel)
855
+ return;
856
+ this._log('Unsubscribing channel:', channelName);
857
+ channel._cleanup();
858
+ this._channels.delete(channelName);
859
+ this._badgeManager.update(channelName, 0);
860
+ this._emitBadgeUpdated();
861
+ }
862
+ // ============ Badge Counts ============
863
+ /**
864
+ * Get the current badge counts across all channels.
865
+ */
866
+ getBadgeCounts() {
867
+ return this._badgeManager.getAll();
868
+ }
869
+ // ============ Read Tracking ============
870
+ /**
871
+ * Mark all notifications as read across all channels.
872
+ */
873
+ markAllRead() {
874
+ for (const channel of this._channels.values()) {
875
+ channel.markAllRead();
876
+ }
877
+ }
878
+ // ============ Private: Guards ============
879
+ _assertUsable() {
880
+ if (this._detached) {
881
+ throw new Error('NoLagNotify has been detached — construct a new instance');
882
+ }
883
+ if (!this._isReady) {
884
+ throw new Error('NoLagNotify not ready — await ready() or the "connected" event');
885
+ }
886
+ }
887
+ // ============ Private: Channel Setup ============
888
+ _subscribeChannel(name, filters) {
889
+ this._log('Subscribing channel:', name);
890
+ const roomContext = this._client.setApp(this._options.appName).setRoom(name);
891
+ const channel = new NotifyChannel(name, roomContext, this._options, createLogger(`NotifyChannel:${name}`, this._options.debug), () => this._client.connected);
892
+ this._channels.set(name, channel);
893
+ channel._subscribe(filters);
894
+ // Relay notifications up to the main client and update badges
895
+ channel.on('notification', (notification) => {
896
+ this._badgeManager.update(name, channel.unreadCount);
897
+ this._emitBadgeUpdated();
898
+ this.emit('notification', notification);
899
+ });
900
+ channel.on('read', () => {
901
+ this._badgeManager.update(name, channel.unreadCount);
902
+ this._emitBadgeUpdated();
903
+ });
904
+ channel.on('readAll', () => {
905
+ this._badgeManager.update(name, 0);
906
+ this._emitBadgeUpdated();
907
+ });
908
+ return channel;
909
+ }
910
+ _emitBadgeUpdated() {
911
+ this.emit('badgeUpdated', this._badgeManager.getAll());
912
+ }
913
+ // ============ Private: Scope Filtering ============
914
+ /**
915
+ * On a shared client, presence events from other apps' wrappers arrive on
916
+ * the same connection-level events. Wrappers stamp their presence with a
917
+ * `__scope` (their appName); a mismatched tag means another app's data.
918
+ * Untagged presence is accepted (older peers in this same app).
919
+ */
920
+ _foreignScope(data) {
921
+ const scope = data?.__scope;
922
+ return typeof scope === 'string' && scope !== this._options.appName;
923
+ }
924
+ // ============ Private: Room Presence ============
925
+ _handleRoomPresenceJoin(data) {
926
+ if (data.actorTokenId === this._client.actorId)
927
+ return;
928
+ const presenceData = data.presence;
929
+ if (!presenceData?.userId || this._foreignScope(presenceData))
930
+ return;
931
+ const user = this._presenceManager.addFromPresence(data.actorTokenId, presenceData);
932
+ if (user) {
933
+ this._actorToUserId.set(data.actorTokenId, user.userId);
934
+ }
935
+ }
936
+ _handleRoomPresenceLeave(data) {
937
+ if (data.actorTokenId === this._client.actorId)
938
+ return;
939
+ this._presenceManager.removeByActorId(data.actorTokenId);
940
+ }
941
+ _handleRoomPresenceUpdate(data) {
942
+ if (data.actorTokenId === this._client.actorId)
943
+ return;
944
+ const presenceData = data.presence;
945
+ if (!presenceData?.userId || this._foreignScope(presenceData))
946
+ return;
947
+ this._presenceManager.addFromPresence(data.actorTokenId, presenceData);
948
+ }
949
+ // ============ Private: Lobby ============
950
+ _handleLobbyJoin(event) {
951
+ const { actorId, data } = event;
952
+ if (actorId === this._client.actorId)
953
+ return;
954
+ const presenceData = data;
955
+ if (!presenceData?.userId || this._foreignScope(presenceData))
956
+ return;
957
+ const user = this._presenceManager.addFromPresence(actorId, presenceData);
958
+ if (user) {
959
+ this._actorToUserId.set(actorId, user.userId);
960
+ }
961
+ }
962
+ _handleLobbyLeave(event) {
963
+ const { actorId, data } = event;
964
+ if (actorId === this._client.actorId)
965
+ return;
966
+ const presenceData = data;
967
+ if (this._foreignScope(presenceData))
968
+ return;
969
+ this._presenceManager.removeByActorId(actorId);
970
+ this._actorToUserId.delete(actorId);
971
+ }
972
+ _handleLobbyUpdate(event) {
973
+ const { actorId, data } = event;
974
+ if (actorId === this._client.actorId)
975
+ return;
976
+ const presenceData = data;
977
+ if (!presenceData?.userId || this._foreignScope(presenceData))
978
+ return;
979
+ this._presenceManager.addFromPresence(actorId, presenceData);
980
+ }
981
+ /**
982
+ * Reconcile tracked presence against a fresh lobby snapshot. One path for
983
+ * initial hydration, reconnect restore, and the deferred refetch.
984
+ */
985
+ _diffHydratePresence(state) {
986
+ // Build the fresh actor set from the snapshot
987
+ const freshActors = new Set();
988
+ for (const roomId of Object.keys(state)) {
989
+ const roomPresence = state[roomId];
990
+ for (const actorId of Object.keys(roomPresence)) {
991
+ if (actorId === this._client.actorId)
992
+ continue;
993
+ const raw = roomPresence[actorId];
994
+ // Server returns full actor records with presence nested under .presence
995
+ const presenceData = (raw?.presence ?? raw);
996
+ if (presenceData?.userId && !this._foreignScope(presenceData)) {
997
+ freshActors.add(actorId);
998
+ const user = this._presenceManager.addFromPresence(actorId, presenceData);
999
+ if (user) {
1000
+ this._actorToUserId.set(actorId, user.userId);
1001
+ }
1002
+ }
1003
+ }
1004
+ }
1005
+ // Vanished actors: present locally but absent from the fresh snapshot
1006
+ for (const [actorId] of [...this._actorToUserId]) {
1007
+ if (!freshActors.has(actorId)) {
1008
+ this._presenceManager.removeByActorId(actorId);
1009
+ this._actorToUserId.delete(actorId);
1010
+ }
1011
+ }
1012
+ }
1013
+ }
1014
+
1015
+ export { EventEmitter, NoLagNotify, NotifyChannel };
1016
+ //# sourceMappingURL=react-native.js.map