@nolag/feed 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,1258 @@
1
+ class EventEmitter {
2
+ constructor() {
3
+ this._handlers = new Map();
4
+ }
5
+ on(event, handler) {
6
+ if (!this._handlers.has(event)) {
7
+ this._handlers.set(event, new Set());
8
+ }
9
+ this._handlers.get(event).add(handler);
10
+ return this;
11
+ }
12
+ off(event, handler) {
13
+ if (handler) {
14
+ this._handlers.get(event)?.delete(handler);
15
+ }
16
+ else {
17
+ this._handlers.delete(event);
18
+ }
19
+ return this;
20
+ }
21
+ removeAllListeners() {
22
+ this._handlers.clear();
23
+ return this;
24
+ }
25
+ emit(event, ...args) {
26
+ const handlers = this._handlers.get(event);
27
+ if (!handlers)
28
+ return;
29
+ for (const handler of handlers) {
30
+ try {
31
+ handler(...args);
32
+ }
33
+ catch (e) {
34
+ console.error(`Error in ${String(event)} handler:`, e);
35
+ }
36
+ }
37
+ }
38
+ listenerCount(event) {
39
+ return this._handlers.get(event)?.size ?? 0;
40
+ }
41
+ }
42
+
43
+ /**
44
+ * Bounded, deduplicated post cache ordered by timestamp.
45
+ */
46
+ class PostStore {
47
+ constructor(maxSize) {
48
+ this._posts = [];
49
+ this._ids = new Set();
50
+ this._maxSize = maxSize;
51
+ }
52
+ /**
53
+ * Add a post. Returns true if the post was new (not a duplicate).
54
+ */
55
+ add(post) {
56
+ if (this._ids.has(post.id)) {
57
+ return false;
58
+ }
59
+ this._ids.add(post.id);
60
+ this._posts.push(post);
61
+ // Keep sorted by timestamp (newest last)
62
+ if (this._posts.length > 1 &&
63
+ post.timestamp < this._posts[this._posts.length - 2].timestamp) {
64
+ this._posts.sort((a, b) => a.timestamp - b.timestamp);
65
+ }
66
+ // Trim if over capacity (remove oldest)
67
+ while (this._posts.length > this._maxSize) {
68
+ const removed = this._posts.shift();
69
+ this._ids.delete(removed.id);
70
+ }
71
+ return true;
72
+ }
73
+ /**
74
+ * Get a post by ID.
75
+ */
76
+ get(id) {
77
+ return this._posts.find((p) => p.id === id);
78
+ }
79
+ /**
80
+ * Get all posts in timestamp order (oldest first).
81
+ */
82
+ getAll() {
83
+ return [...this._posts];
84
+ }
85
+ /**
86
+ * Update the like count (and likedByMe flag) for a post in-place.
87
+ */
88
+ updateLikeCount(postId, count, likedByMe) {
89
+ const post = this._posts.find((p) => p.id === postId);
90
+ if (post) {
91
+ post.likeCount = count;
92
+ post.likedByMe = likedByMe;
93
+ }
94
+ }
95
+ /**
96
+ * Increment the comment count for a post in-place.
97
+ */
98
+ incrementCommentCount(postId) {
99
+ const post = this._posts.find((p) => p.id === postId);
100
+ if (post) {
101
+ post.commentCount++;
102
+ }
103
+ }
104
+ /**
105
+ * Check if a post ID exists.
106
+ */
107
+ has(id) {
108
+ return this._ids.has(id);
109
+ }
110
+ /**
111
+ * Get post count.
112
+ */
113
+ get size() {
114
+ return this._posts.length;
115
+ }
116
+ /**
117
+ * Clear all posts.
118
+ */
119
+ clear() {
120
+ this._posts = [];
121
+ this._ids.clear();
122
+ }
123
+ }
124
+
125
+ /**
126
+ * Tracks like/unlike state per post with per-user deduplication.
127
+ *
128
+ * Internal: Map<postId, Set<userId>>
129
+ */
130
+ class ReactionManager {
131
+ constructor() {
132
+ this._likes = new Map();
133
+ }
134
+ /**
135
+ * Record a like from userId on postId.
136
+ * Returns the updated likeCount and whether this was a new like.
137
+ */
138
+ like(postId, userId) {
139
+ if (!this._likes.has(postId)) {
140
+ this._likes.set(postId, new Set());
141
+ }
142
+ const likers = this._likes.get(postId);
143
+ const isNew = !likers.has(userId);
144
+ likers.add(userId);
145
+ return { postId, likeCount: likers.size, isNew };
146
+ }
147
+ /**
148
+ * Record an unlike from userId on postId.
149
+ * Returns the updated likeCount and whether the like was removed.
150
+ */
151
+ unlike(postId, userId) {
152
+ const likers = this._likes.get(postId);
153
+ if (!likers) {
154
+ return { postId, likeCount: 0, wasLiked: false };
155
+ }
156
+ const wasLiked = likers.has(userId);
157
+ likers.delete(userId);
158
+ return { postId, likeCount: likers.size, wasLiked };
159
+ }
160
+ /**
161
+ * Check if a userId has liked a postId.
162
+ */
163
+ isLikedBy(postId, userId) {
164
+ return this._likes.get(postId)?.has(userId) ?? false;
165
+ }
166
+ /**
167
+ * Get the total like count for a post.
168
+ */
169
+ getLikeCount(postId) {
170
+ return this._likes.get(postId)?.size ?? 0;
171
+ }
172
+ /**
173
+ * Clear all reaction state.
174
+ */
175
+ clear() {
176
+ this._likes.clear();
177
+ }
178
+ }
179
+
180
+ /**
181
+ * Maps actorTokenId <-> FeedUser, filtering self.
182
+ */
183
+ class PresenceManager {
184
+ constructor(localActorId) {
185
+ this._users = new Map();
186
+ this._actorToUserId = new Map();
187
+ this._localActorId = localActorId;
188
+ }
189
+ /**
190
+ * Add or update a user from presence data.
191
+ * Returns the FeedUser if it is a remote user, null if it is self.
192
+ */
193
+ addFromPresence(actorTokenId, presence, joinedAt) {
194
+ const isLocal = actorTokenId === this._localActorId;
195
+ // Skip self
196
+ if (isLocal)
197
+ return null;
198
+ const existing = this._actorToUserId.get(actorTokenId);
199
+ const userId = presence.userId || existing || actorTokenId;
200
+ const user = {
201
+ userId,
202
+ actorTokenId,
203
+ username: presence.username,
204
+ avatar: presence.avatar,
205
+ metadata: presence.metadata,
206
+ joinedAt: joinedAt || Date.now(),
207
+ isLocal: false,
208
+ };
209
+ this._users.set(userId, user);
210
+ this._actorToUserId.set(actorTokenId, userId);
211
+ return user;
212
+ }
213
+ /**
214
+ * Remove a user by actorTokenId.
215
+ * Returns the removed user, or null if not found / is self.
216
+ */
217
+ removeByActorId(actorTokenId) {
218
+ if (actorTokenId === this._localActorId)
219
+ return null;
220
+ const userId = this._actorToUserId.get(actorTokenId);
221
+ if (!userId)
222
+ return null;
223
+ const user = this._users.get(userId) || null;
224
+ this._users.delete(userId);
225
+ this._actorToUserId.delete(actorTokenId);
226
+ return user;
227
+ }
228
+ /**
229
+ * Get a user by userId.
230
+ */
231
+ getUser(userId) {
232
+ return this._users.get(userId);
233
+ }
234
+ /**
235
+ * Get a user by actorTokenId.
236
+ */
237
+ getUserByActorId(actorTokenId) {
238
+ const userId = this._actorToUserId.get(actorTokenId);
239
+ return userId ? this._users.get(userId) : undefined;
240
+ }
241
+ /**
242
+ * Get all remote users.
243
+ */
244
+ getAll() {
245
+ return Array.from(this._users.values());
246
+ }
247
+ /**
248
+ * Get the users Map (readonly view).
249
+ */
250
+ get users() {
251
+ return this._users;
252
+ }
253
+ /**
254
+ * Clear all tracked users.
255
+ */
256
+ clear() {
257
+ this._users.clear();
258
+ this._actorToUserId.clear();
259
+ }
260
+ }
261
+
262
+ function generateId() {
263
+ if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
264
+ return crypto.randomUUID();
265
+ }
266
+ return 'xxxx-xxxx-xxxx-xxxx'.replace(/x/g, () => Math.floor(Math.random() * 16).toString(16));
267
+ }
268
+ function createLogger(prefix, enabled) {
269
+ if (!enabled) {
270
+ return (..._args) => { };
271
+ }
272
+ return (...args) => { console.log(`[${prefix}]`, ...args); };
273
+ }
274
+ // ============ Filters ============
275
+ /**
276
+ * Build the filter fragment of an emit options object.
277
+ *
278
+ * `filter` wins over `filters`: a publish is routed to exactly one topic, so
279
+ * honouring both would silently drop one of them.
280
+ */
281
+ function filterEmitOptions(opts) {
282
+ if (opts?.filter)
283
+ return { filter: opts.filter };
284
+ if (opts?.filters && opts.filters.length > 0)
285
+ return { filters: opts.filters };
286
+ return {};
287
+ }
288
+ /**
289
+ * Rebuild publish options from the filter a message arrived with, so a reply
290
+ * to it reaches the same audience the original did.
291
+ *
292
+ * The server joins AND groups into one composite value with '|', which is not
293
+ * a legal character in a plain filter, so split those back apart.
294
+ */
295
+ function inheritFilter(filter) {
296
+ if (!filter)
297
+ return {};
298
+ if (filter.includes('|'))
299
+ return { filters: filter.split('|') };
300
+ return { filter };
301
+ }
302
+ /**
303
+ * Merge OR terms into an existing filter set. AND groups (nested arrays) are
304
+ * preserved as-is — only plain string terms are deduplicated.
305
+ */
306
+ function mergeFilters(existing, add) {
307
+ const simple = new Set();
308
+ const groups = [];
309
+ for (const f of existing) {
310
+ if (typeof f === 'string')
311
+ simple.add(f);
312
+ else
313
+ groups.push(f);
314
+ }
315
+ for (const v of add)
316
+ simple.add(v);
317
+ return [...simple, ...groups];
318
+ }
319
+ /**
320
+ * Drop OR terms from a filter set. AND groups are left untouched — remove
321
+ * those by calling `setFilters` with the set you want.
322
+ */
323
+ function withoutFilters(existing, remove) {
324
+ const drop = new Set(remove);
325
+ return existing.filter((f) => typeof f !== 'string' || !drop.has(f));
326
+ }
327
+ /**
328
+ * The composite key the server derives from an AND filter group: values are
329
+ * lowercased, sorted, and joined with '|'. Mirrored here so an item created
330
+ * locally carries the same filter string as one arriving off the wire.
331
+ */
332
+ function compositeFilterKey(values) {
333
+ return [...values].map((v) => v.toLowerCase()).sort().join('|');
334
+ }
335
+ /**
336
+ * The single string form of whatever filter a publish used, for recording on
337
+ * the local copy of an item. Round-trips through `inheritFilter`.
338
+ */
339
+ function recordedFilter(opts) {
340
+ if (opts?.filter)
341
+ return opts.filter;
342
+ if (opts?.filters && opts.filters.length > 0)
343
+ return compositeFilterKey(opts.filters);
344
+ return undefined;
345
+ }
346
+ // ============ Wrapper registry ============
347
+ // One wrapper instance per (client, appName): two wrappers sharing an app on
348
+ // one connection would collide on topics, presence and the online lobby.
349
+ // Warn (not throw): HMR and tests legitimately construct before disposing.
350
+ const wrapperRegistry = new WeakMap();
351
+ /** Register a wrapper against a client + appName; warns on collision. */
352
+ function registerWrapper(client, appName, wrapperName) {
353
+ let apps = wrapperRegistry.get(client);
354
+ if (!apps) {
355
+ apps = new Map();
356
+ wrapperRegistry.set(client, apps);
357
+ }
358
+ const existing = apps.get(appName);
359
+ if (existing) {
360
+ console.warn(`[${wrapperName}] Another wrapper (${existing}) is already attached to this client for app "${appName}". ` +
361
+ `Use one wrapper per (client, app) — detach the other instance first.`);
362
+ }
363
+ apps.set(appName, wrapperName);
364
+ }
365
+ /** Release a wrapper's (client, appName) registration on detach. */
366
+ function releaseWrapper(client, appName) {
367
+ wrapperRegistry.get(client)?.delete(appName);
368
+ }
369
+
370
+ const DEFAULT_APP_NAME = 'feed';
371
+ const DEFAULT_MAX_POST_CACHE = 200;
372
+ const DEFAULT_MAX_COMMENT_CACHE = 100;
373
+ const TOPIC_POSTS = 'posts';
374
+ const TOPIC_REACTIONS = 'reactions';
375
+ const TOPIC_COMMENTS = 'comments';
376
+ const LOBBY_ID = 'online';
377
+ /** Delay before the post-setup lobby presence refetch (catches simultaneous joiners) */
378
+ const LOBBY_REFRESH_DELAY_MS = 2000;
379
+
380
+ /** The content topics a channel filter applies to, kept in step deliberately. */
381
+ const FILTERED_TOPICS = [TOPIC_POSTS, TOPIC_REACTIONS, TOPIC_COMMENTS];
382
+ /** Maps the public topic names onto the wire topics. */
383
+ const FILTER_TOPICS = {
384
+ posts: TOPIC_POSTS,
385
+ reactions: TOPIC_REACTIONS,
386
+ comments: TOPIC_COMMENTS,
387
+ };
388
+ /**
389
+ * FeedChannel — a single feed channel with posts, comments, reactions, and
390
+ * presence.
391
+ *
392
+ * Created via `NoLagFeed.joinChannel(name)`. Do not instantiate directly.
393
+ */
394
+ class FeedChannel extends EventEmitter {
395
+ /** @internal */
396
+ constructor(name, roomContext, localUser, options, log, isConnected) {
397
+ super();
398
+ this._comments = new Map();
399
+ this._unreadCount = 0;
400
+ this._active = false;
401
+ /** Filter values applied per content topic. */
402
+ this._filters = {
403
+ posts: [], reactions: [], comments: [],
404
+ };
405
+ // Stored topic handler refs — cleanup removes exactly these, never all
406
+ // handlers for a topic (the client may be shared with other consumers).
407
+ this._onPostsRef = null;
408
+ this._onReactionsRef = null;
409
+ this._onCommentsRef = null;
410
+ this.name = name;
411
+ this._roomContext = roomContext;
412
+ this._localUser = localUser;
413
+ this._options = options;
414
+ this._log = log;
415
+ this._isConnected = isConnected;
416
+ this._presenceManager = new PresenceManager(localUser.actorTokenId);
417
+ this._postStore = new PostStore(options.maxPostCache);
418
+ this._reactionManager = new ReactionManager();
419
+ }
420
+ get posts() { return this._postStore.getAll(); }
421
+ get unreadCount() { return this._unreadCount; }
422
+ get active() { return this._active; }
423
+ createPost(opts) {
424
+ const post = {
425
+ id: generateId(), userId: this._localUser.userId, username: this._localUser.username,
426
+ avatar: this._localUser.avatar, content: opts.content, media: opts.media, data: opts.data,
427
+ likeCount: 0, commentCount: 0, likedByMe: false, timestamp: Date.now(),
428
+ filter: recordedFilter(opts), status: 'sending', isReplay: false,
429
+ };
430
+ this._postStore.add(post);
431
+ this.emit('postSent', post);
432
+ this._roomContext.emit(TOPIC_POSTS, {
433
+ id: post.id, userId: post.userId, username: post.username, avatar: post.avatar,
434
+ content: post.content, media: post.media, data: post.data, timestamp: post.timestamp,
435
+ }, { echo: false, ...filterEmitOptions(opts) });
436
+ post.status = 'sent';
437
+ return post;
438
+ }
439
+ getPosts() { return this._postStore.getAll(); }
440
+ likePost(postId) {
441
+ const { likeCount, isNew } = this._reactionManager.like(postId, this._localUser.userId);
442
+ if (isNew) {
443
+ this._postStore.updateLikeCount(postId, likeCount, true);
444
+ this._roomContext.emit(TOPIC_REACTIONS, { postId, userId: this._localUser.userId, type: 'like', timestamp: Date.now() }, { echo: false, ...this._postFilter(postId) });
445
+ this.emit('postLiked', { postId, userId: this._localUser.userId, likeCount });
446
+ }
447
+ }
448
+ unlikePost(postId) {
449
+ const { likeCount, wasLiked } = this._reactionManager.unlike(postId, this._localUser.userId);
450
+ if (wasLiked) {
451
+ this._postStore.updateLikeCount(postId, likeCount, false);
452
+ this._roomContext.emit(TOPIC_REACTIONS, { postId, userId: this._localUser.userId, type: 'unlike', timestamp: Date.now() }, { echo: false, ...this._postFilter(postId) });
453
+ this.emit('postUnliked', { postId, userId: this._localUser.userId, likeCount });
454
+ }
455
+ }
456
+ addComment(postId, text) {
457
+ const comment = {
458
+ id: generateId(), postId, userId: this._localUser.userId, username: this._localUser.username,
459
+ avatar: this._localUser.avatar, text, timestamp: Date.now(), isReplay: false,
460
+ };
461
+ if (!this._comments.has(postId))
462
+ this._comments.set(postId, []);
463
+ this._comments.get(postId).push(comment);
464
+ this._postStore.incrementCommentCount(postId);
465
+ this.emit('commentSent', comment);
466
+ this._roomContext.emit(TOPIC_COMMENTS, {
467
+ id: comment.id, postId, userId: comment.userId, username: comment.username,
468
+ avatar: comment.avatar, text: comment.text, timestamp: comment.timestamp,
469
+ }, { echo: false, ...this._postFilter(postId) });
470
+ return comment;
471
+ }
472
+ // ============ Filters ============
473
+ /** The filter values currently applied to this channel, by topic. */
474
+ get filters() {
475
+ return {
476
+ posts: [...this._filters.posts],
477
+ reactions: [...this._filters.reactions],
478
+ comments: [...this._filters.comments],
479
+ };
480
+ }
481
+ /**
482
+ * Replace this channel's filters — only posts published with one of these
483
+ * values are delivered. Reactions and comments get the same set unless you
484
+ * scope the call with `{ topic }`, so you never receive a like for a post
485
+ * you cannot see.
486
+ *
487
+ * Passing an empty array clears filtering and restores the wildcard
488
+ * subscription, which receives everything.
489
+ *
490
+ * @example
491
+ * ```ts
492
+ * channel.setFilters(['sports', 'news']); // sports OR news
493
+ * channel.setFilters([['sports', 'live']]); // sports AND live
494
+ * channel.setFilters([]); // everything
495
+ * ```
496
+ */
497
+ setFilters(values, opts) {
498
+ for (const topic of this._targetTopics(opts)) {
499
+ this._filters[topic] = [...values];
500
+ // The core types filters as `string[]`, but both its implementation and
501
+ // the wire protocol accept AND groups (nested arrays).
502
+ this._roomContext.setFilters(FILTER_TOPICS[topic], values);
503
+ }
504
+ }
505
+ /** Add filter values to the existing set. Existing AND groups are kept. */
506
+ addFilters(values, opts) {
507
+ for (const topic of this._targetTopics(opts)) {
508
+ this.setFilters(mergeFilters(this._filters[topic], values), { topic });
509
+ }
510
+ }
511
+ /**
512
+ * Remove filter values from the existing set. Removing the last value
513
+ * restores the wildcard subscription.
514
+ */
515
+ removeFilters(values, opts) {
516
+ for (const topic of this._targetTopics(opts)) {
517
+ this.setFilters(withoutFilters(this._filters[topic], values), { topic });
518
+ }
519
+ }
520
+ _targetTopics(opts) {
521
+ return opts?.topic ? [opts.topic] : ['posts', 'reactions', 'comments'];
522
+ }
523
+ /**
524
+ * The publish options that put a reaction or comment in front of the same
525
+ * audience as the post it belongs to. An unknown post (never seen, or
526
+ * evicted from the cache) falls back to unfiltered.
527
+ */
528
+ _postFilter(postId) {
529
+ return inheritFilter(this._postStore.get(postId)?.filter);
530
+ }
531
+ getComments(postId) {
532
+ return this._comments.get(postId) ?? [];
533
+ }
534
+ markRead() {
535
+ if (this._unreadCount !== 0) {
536
+ this._unreadCount = 0;
537
+ this.emit('unreadChanged', { channel: this.name, count: 0 });
538
+ }
539
+ }
540
+ getUsers() { return this._presenceManager.getAll(); }
541
+ /** @internal Subscribe to post/reaction/comment topics and attach listeners (all channels) */
542
+ _subscribe(filters) {
543
+ this._log('Channel subscribe:', this.name);
544
+ const initial = filters ? [...filters] : [];
545
+ this._filters = { posts: [...initial], reactions: [...initial], comments: [...initial] };
546
+ if (initial.length > 0) {
547
+ const opts = { filters: initial };
548
+ for (const topic of FILTERED_TOPICS)
549
+ this._roomContext.subscribe(topic, opts);
550
+ }
551
+ else {
552
+ for (const topic of FILTERED_TOPICS)
553
+ this._roomContext.subscribe(topic);
554
+ }
555
+ // Listen for posts (refs stored for handler-specific removal)
556
+ this._onPostsRef = (data, meta) => {
557
+ this._handleIncomingPost(data, meta);
558
+ };
559
+ this._roomContext.on(TOPIC_POSTS, this._onPostsRef);
560
+ // Listen for reactions
561
+ this._onReactionsRef = (data) => {
562
+ this._handleIncomingReaction(data);
563
+ };
564
+ this._roomContext.on(TOPIC_REACTIONS, this._onReactionsRef);
565
+ // Listen for comments
566
+ this._onCommentsRef = (data, meta) => {
567
+ this._handleIncomingComment(data, meta);
568
+ };
569
+ this._roomContext.on(TOPIC_COMMENTS, this._onCommentsRef);
570
+ }
571
+ _activate() {
572
+ this._active = true;
573
+ this._markRead();
574
+ this._setPresence();
575
+ this._roomContext.fetchPresence().then((actors) => {
576
+ for (const actor of actors) {
577
+ if (actor.presence) {
578
+ const user = this._presenceManager.addFromPresence(actor.actorTokenId, actor.presence, actor.joinedAt);
579
+ if (user)
580
+ this.emit('subscriberJoined', user);
581
+ }
582
+ }
583
+ }).catch(() => { });
584
+ }
585
+ _deactivate() { this._active = false; this._presenceManager.clear(); }
586
+ _handlePresenceJoin(actorTokenId, presenceData) {
587
+ const user = this._presenceManager.addFromPresence(actorTokenId, presenceData);
588
+ if (user)
589
+ this.emit('subscriberJoined', user);
590
+ }
591
+ _handlePresenceLeave(actorTokenId) {
592
+ const user = this._presenceManager.removeByActorId(actorTokenId);
593
+ if (user)
594
+ this.emit('subscriberLeft', user);
595
+ }
596
+ _handlePresenceUpdate(actorTokenId, presenceData) {
597
+ this._presenceManager.addFromPresence(actorTokenId, presenceData);
598
+ }
599
+ _handleReplayStart(count) { this.emit('replayStart', { count }); }
600
+ _handleReplayEnd(replayed) { this.emit('replayEnd', { replayed }); }
601
+ _updateLocalPresence() { this._setPresence(); }
602
+ /** @internal Unsubscribe and clean up */
603
+ _cleanup() {
604
+ this._log('Channel cleanup:', this.name);
605
+ // Server unsubscribes need a live socket; skip when disconnected
606
+ // (best-effort — the core would no-op with an error callback anyway).
607
+ if (this._isConnected()) {
608
+ this._roomContext.unsubscribe(TOPIC_POSTS);
609
+ this._roomContext.unsubscribe(TOPIC_REACTIONS);
610
+ this._roomContext.unsubscribe(TOPIC_COMMENTS);
611
+ }
612
+ // Handler-specific removal only: the client may be shared, and a bare
613
+ // off(topic) would strip other consumers' handlers too.
614
+ if (this._onPostsRef)
615
+ this._roomContext.off(TOPIC_POSTS, this._onPostsRef);
616
+ if (this._onReactionsRef)
617
+ this._roomContext.off(TOPIC_REACTIONS, this._onReactionsRef);
618
+ if (this._onCommentsRef)
619
+ this._roomContext.off(TOPIC_COMMENTS, this._onCommentsRef);
620
+ this._onPostsRef = null;
621
+ this._onReactionsRef = null;
622
+ this._onCommentsRef = null;
623
+ this._postStore.clear();
624
+ this._reactionManager.clear();
625
+ this._comments.clear();
626
+ this._presenceManager.clear();
627
+ this.removeAllListeners();
628
+ }
629
+ _handleIncomingPost(data, meta) {
630
+ const raw = data;
631
+ const post = {
632
+ id: raw.id, userId: raw.userId, username: raw.username,
633
+ avatar: raw.avatar, content: raw.content,
634
+ media: raw.media, data: raw.data,
635
+ likeCount: 0, commentCount: 0, likedByMe: false,
636
+ timestamp: raw.timestamp, filter: meta.filter,
637
+ status: 'delivered', isReplay: meta.isReplay ?? false,
638
+ };
639
+ if (this._postStore.add(post)) {
640
+ this.emit('postCreated', post);
641
+ if (!this._active && !post.isReplay) {
642
+ this._unreadCount++;
643
+ this.emit('unreadChanged', { channel: this.name, count: this._unreadCount });
644
+ }
645
+ }
646
+ }
647
+ _handleIncomingReaction(data) {
648
+ const raw = data;
649
+ if (raw.type === 'like') {
650
+ const { likeCount } = this._reactionManager.like(raw.postId, raw.userId);
651
+ const likedByMe = this._reactionManager.isLikedBy(raw.postId, this._localUser.userId);
652
+ this._postStore.updateLikeCount(raw.postId, likeCount, likedByMe);
653
+ this.emit('postLiked', { postId: raw.postId, userId: raw.userId, likeCount });
654
+ }
655
+ else if (raw.type === 'unlike') {
656
+ const { likeCount } = this._reactionManager.unlike(raw.postId, raw.userId);
657
+ const likedByMe = this._reactionManager.isLikedBy(raw.postId, this._localUser.userId);
658
+ this._postStore.updateLikeCount(raw.postId, likeCount, likedByMe);
659
+ this.emit('postUnliked', { postId: raw.postId, userId: raw.userId, likeCount });
660
+ }
661
+ }
662
+ _handleIncomingComment(data, meta) {
663
+ const raw = data;
664
+ const comment = {
665
+ id: raw.id, postId: raw.postId, userId: raw.userId,
666
+ username: raw.username, avatar: raw.avatar,
667
+ text: raw.text, timestamp: raw.timestamp, isReplay: meta.isReplay ?? false,
668
+ };
669
+ if (!this._comments.has(comment.postId))
670
+ this._comments.set(comment.postId, []);
671
+ this._comments.get(comment.postId).push(comment);
672
+ this._postStore.incrementCommentCount(comment.postId);
673
+ this.emit('commentAdded', comment);
674
+ }
675
+ _markRead() {
676
+ if (this._unreadCount !== 0) {
677
+ this._unreadCount = 0;
678
+ this.emit('unreadChanged', { channel: this.name, count: 0 });
679
+ }
680
+ }
681
+ _setPresence() {
682
+ this._roomContext.setPresence({
683
+ userId: this._localUser.userId, username: this._localUser.username,
684
+ avatar: this._localUser.avatar, metadata: this._localUser.metadata,
685
+ // Scope tag: on a shared client, other apps' wrappers filter our
686
+ // presence out by this (and we filter theirs).
687
+ __scope: this._options.appName,
688
+ });
689
+ }
690
+ }
691
+
692
+ /**
693
+ * NoLagFeed — high-level activity-feed SDK built on @nolag/js-sdk.
694
+ *
695
+ * Provides multi-channel feeds, posts, likes, comments, presence (who's
696
+ * online), replay, and user mapping — all framework-agnostic via events.
697
+ *
698
+ * The wrapper NEVER manages the connection. The app owns one core NoLag
699
+ * client (shared by any number of wrappers on distinct apps) and the
700
+ * wrapper attaches to it at construction and releases it via `detach()`.
701
+ *
702
+ * @example
703
+ * ```typescript
704
+ * import { NoLag } from '@nolag/js-sdk';
705
+ * import { NoLagFeed } from '@nolag/feed';
706
+ *
707
+ * const client = NoLag(async () => (await (await fetch('/api/nolag-token')).json()).token);
708
+ * const feed = new NoLagFeed({ client, appName: 'my-feed', username: 'Alice' });
709
+ *
710
+ * feed.on('userOnline', (user) => console.log(user.username, 'is online'));
711
+ *
712
+ * await client.connect(); // the app owns the connection
713
+ * await feed.ready(); // wrapper setup done (identity, lobby, channels)
714
+ *
715
+ * const channel = feed.joinChannel('general');
716
+ * channel.on('postCreated', (post) => console.log(post.username + ':', post.content));
717
+ * channel.createPost({ content: 'Hello!' });
718
+ *
719
+ * feed.detach(); // wrapper releases its handlers and topics
720
+ * client.disconnect(); // the app closes the socket
721
+ * ```
722
+ */
723
+ class NoLagFeed extends EventEmitter {
724
+ constructor(options) {
725
+ super();
726
+ this._localUser = null;
727
+ this._channels = new Map();
728
+ this._lobby = null;
729
+ this._onlineUsers = new Map();
730
+ this._actorToUserId = new Map();
731
+ this._activeChannel = null;
732
+ // Lifecycle: one setup run per connection epoch; detach is terminal.
733
+ this._epoch = 0;
734
+ this._detached = false;
735
+ this._isReady = false;
736
+ this._lobbyRefreshTimer = null;
737
+ // Stored client handler refs. INVARIANT: every client.on() below has a
738
+ // matching client.off() in detach() — never bare off(event), never inline
739
+ // closures on the client.
740
+ this._onConnectRef = () => this._onConnect();
741
+ this._onDisconnectRef = (reason) => {
742
+ this._log('Disconnected:', reason);
743
+ this.emit('disconnected', reason);
744
+ };
745
+ this._onReconnectRef = () => {
746
+ this._log('Reconnecting...');
747
+ this.emit('reconnecting');
748
+ };
749
+ this._onErrorRef = (error) => {
750
+ this._log('Error:', error);
751
+ this.emit('error', error);
752
+ };
753
+ this._onReplayStartRef = (data) => {
754
+ const event = data;
755
+ for (const channel of this._channels.values()) {
756
+ channel._handleReplayStart(event.count);
757
+ }
758
+ };
759
+ this._onReplayEndRef = (data) => {
760
+ const event = data;
761
+ for (const channel of this._channels.values()) {
762
+ channel._handleReplayEnd(event.replayed);
763
+ }
764
+ };
765
+ this._onPresenceJoinRef = (data) => this._handleRoomPresenceJoin(data);
766
+ this._onPresenceLeaveRef = (data) => this._handleRoomPresenceLeave(data);
767
+ this._onPresenceUpdateRef = (data) => this._handleRoomPresenceUpdate(data);
768
+ this._onLobbyJoinRef = (data) => this._handleLobbyJoin(data);
769
+ this._onLobbyLeaveRef = (data) => this._handleLobbyLeave(data);
770
+ this._onLobbyUpdateRef = (data) => this._handleLobbyUpdate(data);
771
+ if (!options?.client) {
772
+ throw new TypeError('NoLagFeed requires an injected NoLag client: new NoLagFeed({ client, username, ... })');
773
+ }
774
+ this._client = options.client;
775
+ this._userId = generateId();
776
+ this._options = {
777
+ username: options.username,
778
+ avatar: options.avatar,
779
+ metadata: options.metadata,
780
+ appName: options.appName ?? DEFAULT_APP_NAME,
781
+ maxPostCache: options.maxPostCache ?? DEFAULT_MAX_POST_CACHE,
782
+ maxCommentCache: options.maxCommentCache ?? DEFAULT_MAX_COMMENT_CACHE,
783
+ debug: options.debug ?? false,
784
+ channels: options.channels ?? [],
785
+ };
786
+ this._log = createLogger('NoLagFeed', this._options.debug);
787
+ this._readyPromise = new Promise((resolve, reject) => {
788
+ this._readyResolve = resolve;
789
+ this._readyReject = reject;
790
+ });
791
+ // ready() rejection is only meaningful to callers that await it
792
+ this._readyPromise.catch(() => { });
793
+ registerWrapper(this._client, this._options.appName, 'NoLagFeed');
794
+ // Construction = attach: wire everything now, with stored refs.
795
+ this._client.on('connect', this._onConnectRef);
796
+ this._client.on('disconnect', this._onDisconnectRef);
797
+ this._client.on('reconnect', this._onReconnectRef);
798
+ this._client.on('error', this._onErrorRef);
799
+ this._client.on('replay:start', this._onReplayStartRef);
800
+ this._client.on('replay:end', this._onReplayEndRef);
801
+ this._client.on('presence:join', this._onPresenceJoinRef);
802
+ this._client.on('presence:leave', this._onPresenceLeaveRef);
803
+ this._client.on('presence:update', this._onPresenceUpdateRef);
804
+ this._client.on('lobbyPresence:join', this._onLobbyJoinRef);
805
+ this._client.on('lobbyPresence:leave', this._onLobbyLeaveRef);
806
+ this._client.on('lobbyPresence:update', this._onLobbyUpdateRef);
807
+ // Attach-to-connected: if the client is already authenticated, run setup.
808
+ // The microtask lets the caller wire wrapper event handlers synchronously
809
+ // first; a racing real 'connect' event wins via the epoch guard.
810
+ queueMicrotask(() => {
811
+ if (this._epoch === 0 && !this._detached && this._client.connected) {
812
+ this._onConnect();
813
+ }
814
+ });
815
+ }
816
+ // ============ Public Properties ============
817
+ /** Whether the underlying connection is established (connected ≠ ready) */
818
+ get connected() {
819
+ return !this._detached && this._client.connected;
820
+ }
821
+ /** The injected core client (owned by the app, not the wrapper) */
822
+ get client() {
823
+ return this._client;
824
+ }
825
+ /** The local user's info (available after ready) */
826
+ get localUser() {
827
+ return this._localUser;
828
+ }
829
+ /** All currently joined channels */
830
+ get channels() {
831
+ return this._channels;
832
+ }
833
+ // ============ Lifecycle ============
834
+ /**
835
+ * Resolves once the wrapper's first setup completed (identity, lobby and
836
+ * configured channels ready — equivalently, once 'connected' has fired).
837
+ * Rejects only if detach() is called before that. Client auth failures
838
+ * surface via the app's own `await client.connect()`, not here.
839
+ */
840
+ ready() {
841
+ return this._readyPromise;
842
+ }
843
+ /**
844
+ * Detach from the client: remove every handler this wrapper added,
845
+ * unsubscribe its topics and lobby (when connected), clear state.
846
+ * Terminal and idempotent; never touches the socket. To use the feed again,
847
+ * construct a new instance.
848
+ */
849
+ detach() {
850
+ if (this._detached)
851
+ return;
852
+ this._log('Detaching...');
853
+ this._detached = true;
854
+ this._epoch++; // aborts any in-flight setup at its next checkpoint
855
+ if (this._lobbyRefreshTimer) {
856
+ clearTimeout(this._lobbyRefreshTimer);
857
+ this._lobbyRefreshTimer = null;
858
+ }
859
+ // Remove all client handlers by stored ref
860
+ this._client.off('connect', this._onConnectRef);
861
+ this._client.off('disconnect', this._onDisconnectRef);
862
+ this._client.off('reconnect', this._onReconnectRef);
863
+ this._client.off('error', this._onErrorRef);
864
+ this._client.off('replay:start', this._onReplayStartRef);
865
+ this._client.off('replay:end', this._onReplayEndRef);
866
+ this._client.off('presence:join', this._onPresenceJoinRef);
867
+ this._client.off('presence:leave', this._onPresenceLeaveRef);
868
+ this._client.off('presence:update', this._onPresenceUpdateRef);
869
+ this._client.off('lobbyPresence:join', this._onLobbyJoinRef);
870
+ this._client.off('lobbyPresence:leave', this._onLobbyLeaveRef);
871
+ this._client.off('lobbyPresence:update', this._onLobbyUpdateRef);
872
+ // Channels: handler-specific off + connected-gated server unsubscribe
873
+ for (const name of [...this._channels.keys()]) {
874
+ this._channels.get(name)._cleanup();
875
+ this._channels.delete(name);
876
+ }
877
+ this._activeChannel = null;
878
+ // Lobby: server unsubscribe is best-effort and needs a live socket
879
+ if (this._lobby && this._client.connected) {
880
+ try {
881
+ this._lobby.unsubscribe();
882
+ }
883
+ catch {
884
+ /* best-effort */
885
+ }
886
+ }
887
+ this._lobby = null;
888
+ this._onlineUsers.clear();
889
+ this._actorToUserId.clear();
890
+ this._localUser = null;
891
+ releaseWrapper(this._client, this._options.appName);
892
+ if (!this._isReady) {
893
+ this._readyReject(new Error('NoLagFeed detached before ready'));
894
+ }
895
+ }
896
+ // ============ Private: Epoch Setup ============
897
+ _onConnect() {
898
+ this._epoch++;
899
+ void this._runSetup(this._epoch);
900
+ }
901
+ /**
902
+ * One setup pass per connection epoch. Serves both initial setup (epoch 1)
903
+ * and reconnect restore (epoch > 1). Aborts silently whenever a newer
904
+ * epoch started or the wrapper detached — checked after every await.
905
+ */
906
+ async _runSetup(epoch) {
907
+ const stale = () => epoch !== this._epoch || this._detached;
908
+ this._log(this._isReady ? 'Restoring after reconnect...' : 'Setting up...');
909
+ // Identity (client.actorId is guaranteed post-auth)
910
+ if (!this._localUser) {
911
+ this._localUser = {
912
+ userId: this._userId,
913
+ actorTokenId: this._client.actorId,
914
+ username: this._options.username,
915
+ avatar: this._options.avatar,
916
+ metadata: this._options.metadata,
917
+ joinedAt: Date.now(),
918
+ isLocal: true,
919
+ };
920
+ this._log('Local user:', this._localUser.userId, '→', this._localUser.actorTokenId);
921
+ }
922
+ else {
923
+ this._localUser.actorTokenId = this._client.actorId;
924
+ }
925
+ // Lobby: subscribe every epoch (idempotent server-side) and diff-hydrate
926
+ // from the returned snapshot — one path for setup and restore.
927
+ if (!this._lobby) {
928
+ this._lobby = this._client.setApp(this._options.appName).setLobby(LOBBY_ID);
929
+ }
930
+ try {
931
+ const state = await this._lobby.subscribe();
932
+ if (stale())
933
+ return;
934
+ this._diffHydrateOnlineUsers(state);
935
+ this._log('Lobby subscribed, online users:', this._onlineUsers.size);
936
+ }
937
+ catch (err) {
938
+ if (stale())
939
+ return;
940
+ this._log('Lobby subscription failed:', err);
941
+ }
942
+ if (!this._isReady) {
943
+ // First successful setup: pre-subscribe configured channels
944
+ // (posts only, no presence)
945
+ for (const channelName of this._options.channels) {
946
+ this._subscribeChannelInternal(channelName);
947
+ }
948
+ }
949
+ else if (this._activeChannel) {
950
+ // Server auto-restored topic subscriptions; only channel-scoped presence
951
+ // needs re-applying (the core does not restore it).
952
+ this._channels.get(this._activeChannel)?._updateLocalPresence();
953
+ }
954
+ if (stale())
955
+ return;
956
+ // Ready keys on the first setup that COMPLETES, not on epoch 1: an
957
+ // epoch aborted by a racing reconnect must not strand ready().
958
+ if (!this._isReady) {
959
+ this._isReady = true;
960
+ this._readyResolve();
961
+ this.emit('connected');
962
+ }
963
+ else {
964
+ this.emit('reconnected');
965
+ }
966
+ // Deferred lobby refetch: catches users who joined during the setup
967
+ // window (e.g. simultaneous multi-tab connects).
968
+ this._scheduleLobbyRefresh(epoch);
969
+ }
970
+ _scheduleLobbyRefresh(epoch) {
971
+ if (this._lobbyRefreshTimer)
972
+ clearTimeout(this._lobbyRefreshTimer);
973
+ this._lobbyRefreshTimer = setTimeout(() => {
974
+ this._lobbyRefreshTimer = null;
975
+ if (epoch !== this._epoch || this._detached || !this._client.connected || !this._lobby) {
976
+ return;
977
+ }
978
+ this._lobby
979
+ .fetchPresence()
980
+ .then((state) => {
981
+ if (epoch !== this._epoch || this._detached)
982
+ return;
983
+ this._diffHydrateOnlineUsers(state);
984
+ })
985
+ .catch(() => {
986
+ /* best-effort */
987
+ });
988
+ }, LOBBY_REFRESH_DELAY_MS);
989
+ }
990
+ // ============ Channel Management ============
991
+ /**
992
+ * Join (activate) a feed channel. Deactivates the previous active channel.
993
+ * If the channel was pre-subscribed via the `channels` option, activates it.
994
+ * Otherwise creates, subscribes, and activates it.
995
+ */
996
+ joinChannel(name, opts) {
997
+ this._assertUsable();
998
+ // Deactivate the current active channel
999
+ if (this._activeChannel && this._activeChannel !== name) {
1000
+ const prev = this._channels.get(this._activeChannel);
1001
+ if (prev)
1002
+ prev._deactivate();
1003
+ }
1004
+ // Get or create the channel
1005
+ let channel = this._channels.get(name);
1006
+ if (!channel) {
1007
+ channel = this._subscribeChannelInternal(name, opts?.filters);
1008
+ }
1009
+ else if (opts?.filters) {
1010
+ // Already subscribed (pre-subscribed via the `channels` option, or an
1011
+ // earlier join). Re-point its filters rather than ignoring them.
1012
+ channel.setFilters(opts.filters);
1013
+ }
1014
+ this._activeChannel = name;
1015
+ channel._activate();
1016
+ return channel;
1017
+ }
1018
+ /**
1019
+ * Leave a feed channel. Fully unsubscribes and removes it.
1020
+ */
1021
+ leaveChannel(name) {
1022
+ const channel = this._channels.get(name);
1023
+ if (!channel)
1024
+ return;
1025
+ this._log('Leaving channel:', name);
1026
+ channel._cleanup();
1027
+ this._channels.delete(name);
1028
+ if (this._activeChannel === name) {
1029
+ this._activeChannel = null;
1030
+ }
1031
+ }
1032
+ /**
1033
+ * Get all joined channels.
1034
+ */
1035
+ getChannels() {
1036
+ return Array.from(this._channels.values());
1037
+ }
1038
+ // ============ Global Presence ============
1039
+ /**
1040
+ * Get all users currently online across all channels.
1041
+ */
1042
+ getOnlineUsers() {
1043
+ return Array.from(this._onlineUsers.values());
1044
+ }
1045
+ // ============ Profile ============
1046
+ /**
1047
+ * Update the local user's profile info (broadcast to the active channel).
1048
+ */
1049
+ updateProfile(updates) {
1050
+ if (!this._localUser)
1051
+ return;
1052
+ if (updates.username !== undefined) {
1053
+ this._localUser.username = updates.username;
1054
+ this._options.username = updates.username;
1055
+ }
1056
+ if (updates.avatar !== undefined) {
1057
+ this._localUser.avatar = updates.avatar;
1058
+ this._options.avatar = updates.avatar;
1059
+ }
1060
+ if (updates.metadata !== undefined) {
1061
+ this._localUser.metadata = { ...this._localUser.metadata, ...updates.metadata };
1062
+ this._options.metadata = this._localUser.metadata;
1063
+ }
1064
+ // Re-set presence only on the active channel
1065
+ if (this._activeChannel) {
1066
+ const activeChannel = this._channels.get(this._activeChannel);
1067
+ if (activeChannel)
1068
+ activeChannel._updateLocalPresence();
1069
+ }
1070
+ }
1071
+ // ============ Private: Guards ============
1072
+ _assertUsable() {
1073
+ if (this._detached) {
1074
+ throw new Error('NoLagFeed has been detached — construct a new instance');
1075
+ }
1076
+ if (!this._isReady || !this._localUser) {
1077
+ throw new Error('NoLagFeed not ready — await ready() or the "connected" event');
1078
+ }
1079
+ }
1080
+ // ============ Private: Channel Setup ============
1081
+ _subscribeChannelInternal(name, filters) {
1082
+ this._log('Subscribing channel:', name);
1083
+ const roomContext = this._client.setApp(this._options.appName).setRoom(name);
1084
+ const channel = new FeedChannel(name, roomContext, this._localUser, this._options, createLogger(`FeedChannel:${name}`, this._options.debug), () => this._client.connected);
1085
+ this._channels.set(name, channel);
1086
+ channel._subscribe(filters);
1087
+ return channel;
1088
+ }
1089
+ // ============ Private: Scope Filtering ============
1090
+ /**
1091
+ * On a shared client, presence events from other apps' wrappers arrive on
1092
+ * the same connection-level events. Wrappers stamp their presence with a
1093
+ * `__scope` (their appName); a mismatched tag means another app's data.
1094
+ * Untagged presence is accepted (older peers in this same app).
1095
+ */
1096
+ _foreignScope(data) {
1097
+ const scope = data?.__scope;
1098
+ return typeof scope === 'string' && scope !== this._options.appName;
1099
+ }
1100
+ // ============ Private: Channel Presence → Active Channel ============
1101
+ _handleRoomPresenceJoin(data) {
1102
+ if (data.actorTokenId === this._localUser?.actorTokenId)
1103
+ return;
1104
+ const presenceData = data.presence;
1105
+ if (!presenceData?.userId || this._foreignScope(presenceData))
1106
+ return;
1107
+ // Track as online user
1108
+ const user = this._presenceToUser(data.actorTokenId, presenceData);
1109
+ this._actorToUserId.set(data.actorTokenId, user.userId);
1110
+ if (!this._onlineUsers.has(user.userId)) {
1111
+ this._onlineUsers.set(user.userId, user);
1112
+ this.emit('userOnline', user);
1113
+ }
1114
+ const channel = this._activeChannel ? this._channels.get(this._activeChannel) : undefined;
1115
+ if (channel) {
1116
+ channel._handlePresenceJoin(data.actorTokenId, presenceData);
1117
+ }
1118
+ }
1119
+ _handleRoomPresenceLeave(data) {
1120
+ if (data.actorTokenId === this._localUser?.actorTokenId)
1121
+ return;
1122
+ // Channel leave ≠ offline — user may still be in another channel.
1123
+ // Lobby leave handles actual offline status.
1124
+ const channel = this._activeChannel ? this._channels.get(this._activeChannel) : undefined;
1125
+ if (channel) {
1126
+ channel._handlePresenceLeave(data.actorTokenId);
1127
+ }
1128
+ }
1129
+ _handleRoomPresenceUpdate(data) {
1130
+ if (data.actorTokenId === this._localUser?.actorTokenId)
1131
+ return;
1132
+ const presenceData = data.presence;
1133
+ if (!presenceData?.userId || this._foreignScope(presenceData))
1134
+ return;
1135
+ // Update online user info if we already track them
1136
+ if (this._onlineUsers.has(presenceData.userId)) {
1137
+ const user = this._presenceToUser(data.actorTokenId, presenceData);
1138
+ this._onlineUsers.set(user.userId, user);
1139
+ }
1140
+ const channel = this._activeChannel ? this._channels.get(this._activeChannel) : undefined;
1141
+ if (channel) {
1142
+ channel._handlePresenceUpdate(data.actorTokenId, presenceData);
1143
+ }
1144
+ }
1145
+ // ============ Private: Lobby ============
1146
+ _handleLobbyJoin(event) {
1147
+ const { actorId, data } = event;
1148
+ if (actorId === this._localUser?.actorTokenId)
1149
+ return;
1150
+ const presenceData = data;
1151
+ if (!presenceData.userId || this._foreignScope(presenceData))
1152
+ return;
1153
+ const user = this._presenceToUser(actorId, presenceData);
1154
+ this._actorToUserId.set(actorId, user.userId);
1155
+ if (!this._onlineUsers.has(user.userId)) {
1156
+ this._onlineUsers.set(user.userId, user);
1157
+ this.emit('userOnline', user);
1158
+ }
1159
+ }
1160
+ _handleLobbyLeave(event) {
1161
+ const { actorId, data } = event;
1162
+ if (actorId === this._localUser?.actorTokenId)
1163
+ return;
1164
+ const presenceData = data;
1165
+ if (this._foreignScope(presenceData))
1166
+ return;
1167
+ const userId = presenceData?.userId
1168
+ || this._actorToUserId.get(actorId)
1169
+ || this._findUserIdByActorId(actorId);
1170
+ if (userId) {
1171
+ const user = this._onlineUsers.get(userId);
1172
+ if (user) {
1173
+ this._onlineUsers.delete(userId);
1174
+ this._actorToUserId.delete(actorId);
1175
+ this.emit('userOffline', user);
1176
+ }
1177
+ }
1178
+ }
1179
+ _handleLobbyUpdate(event) {
1180
+ const { actorId, data } = event;
1181
+ if (actorId === this._localUser?.actorTokenId)
1182
+ return;
1183
+ const presenceData = data;
1184
+ if (!presenceData.userId || this._foreignScope(presenceData))
1185
+ return;
1186
+ const user = this._presenceToUser(actorId, presenceData);
1187
+ this._onlineUsers.set(user.userId, user);
1188
+ }
1189
+ /**
1190
+ * Reconcile the online-user map against a fresh lobby snapshot, emitting
1191
+ * only the deltas (userOffline for vanished, userOnline for new). One path
1192
+ * for initial hydration, reconnect restore, and the deferred refetch.
1193
+ */
1194
+ _diffHydrateOnlineUsers(state) {
1195
+ // Build the fresh user set from the snapshot
1196
+ const fresh = new Map();
1197
+ const freshActors = new Map();
1198
+ for (const roomId of Object.keys(state)) {
1199
+ const roomPresence = state[roomId];
1200
+ for (const actorId of Object.keys(roomPresence)) {
1201
+ if (actorId === this._localUser?.actorTokenId)
1202
+ continue;
1203
+ const raw = roomPresence[actorId];
1204
+ // Server returns full actor records with presence nested under .presence
1205
+ const presenceData = (raw?.presence ?? raw);
1206
+ if (presenceData?.userId && !this._foreignScope(presenceData)) {
1207
+ if (!fresh.has(presenceData.userId)) {
1208
+ fresh.set(presenceData.userId, this._presenceToUser(actorId, presenceData));
1209
+ }
1210
+ freshActors.set(actorId, presenceData.userId);
1211
+ }
1212
+ }
1213
+ }
1214
+ // Vanished users
1215
+ for (const [userId, user] of [...this._onlineUsers]) {
1216
+ if (!fresh.has(userId)) {
1217
+ this._onlineUsers.delete(userId);
1218
+ for (const [actorId, mappedUserId] of [...this._actorToUserId]) {
1219
+ if (mappedUserId === userId)
1220
+ this._actorToUserId.delete(actorId);
1221
+ }
1222
+ this.emit('userOffline', user);
1223
+ }
1224
+ }
1225
+ // New users
1226
+ for (const [userId, user] of fresh) {
1227
+ if (!this._onlineUsers.has(userId)) {
1228
+ this._onlineUsers.set(userId, user);
1229
+ this.emit('userOnline', user);
1230
+ }
1231
+ }
1232
+ for (const [actorId, userId] of freshActors) {
1233
+ this._actorToUserId.set(actorId, userId);
1234
+ }
1235
+ }
1236
+ // ============ Private: Helpers ============
1237
+ _presenceToUser(actorTokenId, data) {
1238
+ return {
1239
+ userId: data.userId,
1240
+ actorTokenId,
1241
+ username: data.username,
1242
+ avatar: data.avatar,
1243
+ metadata: data.metadata,
1244
+ joinedAt: Date.now(),
1245
+ isLocal: false,
1246
+ };
1247
+ }
1248
+ _findUserIdByActorId(actorTokenId) {
1249
+ for (const user of this._onlineUsers.values()) {
1250
+ if (user.actorTokenId === actorTokenId)
1251
+ return user.userId;
1252
+ }
1253
+ return undefined;
1254
+ }
1255
+ }
1256
+
1257
+ export { EventEmitter, FeedChannel, NoLagFeed };
1258
+ //# sourceMappingURL=react-native.js.map