@nolag/dash 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,949 @@
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
+ class MetricStore {
44
+ constructor(maxPerStream) {
45
+ this._streams = new Map();
46
+ this._ids = new Set();
47
+ this._maxPerStream = maxPerStream;
48
+ }
49
+ add(point) {
50
+ if (this._ids.has(point.id))
51
+ return false;
52
+ this._ids.add(point.id);
53
+ if (!this._streams.has(point.streamId))
54
+ this._streams.set(point.streamId, []);
55
+ const points = this._streams.get(point.streamId);
56
+ points.push(point);
57
+ if (points.length > 1 && point.timestamp < points[points.length - 2].timestamp) {
58
+ points.sort((a, b) => a.timestamp - b.timestamp);
59
+ }
60
+ while (points.length > this._maxPerStream) {
61
+ const removed = points.shift();
62
+ this._ids.delete(removed.id);
63
+ }
64
+ return true;
65
+ }
66
+ getAll(streamId) {
67
+ if (streamId)
68
+ return [...(this._streams.get(streamId) ?? [])];
69
+ const all = [];
70
+ for (const points of this._streams.values())
71
+ all.push(...points);
72
+ return all.sort((a, b) => a.timestamp - b.timestamp);
73
+ }
74
+ getAggregation(streamId, windowMs) {
75
+ const points = this._streams.get(streamId) ?? [];
76
+ const now = Date.now();
77
+ const window = windowMs ?? 60000;
78
+ const filtered = points.filter(p => p.timestamp >= now - window);
79
+ if (filtered.length === 0) {
80
+ return { streamId, min: 0, max: 0, avg: 0, sum: 0, count: 0, last: 0, windowMs: window };
81
+ }
82
+ let min = Infinity, max = -Infinity, sum = 0;
83
+ for (const p of filtered) {
84
+ if (p.value < min)
85
+ min = p.value;
86
+ if (p.value > max)
87
+ max = p.value;
88
+ sum += p.value;
89
+ }
90
+ return { streamId, min, max, avg: sum / filtered.length, sum, count: filtered.length, last: filtered[filtered.length - 1].value, windowMs: window };
91
+ }
92
+ has(id) { return this._ids.has(id); }
93
+ get size() { return this._ids.size; }
94
+ clear() {
95
+ this._streams.clear();
96
+ this._ids.clear();
97
+ }
98
+ }
99
+
100
+ class WidgetManager {
101
+ constructor() {
102
+ this._widgets = new Map();
103
+ }
104
+ update(widget) {
105
+ this._widgets.set(widget.widgetId, widget);
106
+ }
107
+ get(widgetId) {
108
+ return this._widgets.get(widgetId);
109
+ }
110
+ getAll() {
111
+ return Array.from(this._widgets.values());
112
+ }
113
+ clear() {
114
+ this._widgets.clear();
115
+ }
116
+ }
117
+
118
+ class PresenceManager {
119
+ constructor(localActorId) {
120
+ this._users = new Map();
121
+ this._actorToViewerId = new Map();
122
+ this._localActorId = localActorId;
123
+ }
124
+ addFromPresence(actorTokenId, presence, joinedAt) {
125
+ if (actorTokenId === this._localActorId)
126
+ return null;
127
+ const viewerId = presence.viewerId || this._actorToViewerId.get(actorTokenId) || actorTokenId;
128
+ const viewer = { viewerId, actorTokenId, username: presence.username, metadata: presence.metadata, joinedAt: joinedAt || Date.now(), isLocal: false };
129
+ this._users.set(viewerId, viewer);
130
+ this._actorToViewerId.set(actorTokenId, viewerId);
131
+ return viewer;
132
+ }
133
+ removeByActorId(actorTokenId) {
134
+ if (actorTokenId === this._localActorId)
135
+ return null;
136
+ const viewerId = this._actorToViewerId.get(actorTokenId);
137
+ if (!viewerId)
138
+ return null;
139
+ const viewer = this._users.get(viewerId) || null;
140
+ this._users.delete(viewerId);
141
+ this._actorToViewerId.delete(actorTokenId);
142
+ return viewer;
143
+ }
144
+ getAll() { return Array.from(this._users.values()); }
145
+ get users() { return this._users; }
146
+ clear() { this._users.clear(); this._actorToViewerId.clear(); }
147
+ }
148
+
149
+ function generateId() {
150
+ if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
151
+ return crypto.randomUUID();
152
+ }
153
+ return 'xxxx-xxxx-xxxx-xxxx'.replace(/x/g, () => Math.floor(Math.random() * 16).toString(16));
154
+ }
155
+ function createLogger(prefix, enabled) {
156
+ if (!enabled) {
157
+ return (..._args) => { };
158
+ }
159
+ return (...args) => { console.log(`[${prefix}]`, ...args); };
160
+ }
161
+ // ============ Filters ============
162
+ /**
163
+ * Build the filter fragment of an emit options object.
164
+ *
165
+ * `filter` wins over `filters`: a publish is routed to exactly one topic, so
166
+ * honouring both would silently drop one of them.
167
+ */
168
+ function filterEmitOptions(opts) {
169
+ if (opts?.filter)
170
+ return { filter: opts.filter };
171
+ if (opts?.filters && opts.filters.length > 0)
172
+ return { filters: opts.filters };
173
+ return {};
174
+ }
175
+ /**
176
+ * Merge OR terms into an existing filter set. AND groups (nested arrays) are
177
+ * preserved as-is — only plain string terms are deduplicated.
178
+ */
179
+ function mergeFilters(existing, add) {
180
+ const simple = new Set();
181
+ const groups = [];
182
+ for (const f of existing) {
183
+ if (typeof f === 'string')
184
+ simple.add(f);
185
+ else
186
+ groups.push(f);
187
+ }
188
+ for (const v of add)
189
+ simple.add(v);
190
+ return [...simple, ...groups];
191
+ }
192
+ /**
193
+ * Drop OR terms from a filter set. AND groups are left untouched — remove
194
+ * those by calling `setFilters` with the set you want.
195
+ */
196
+ function withoutFilters(existing, remove) {
197
+ const drop = new Set(remove);
198
+ return existing.filter((f) => typeof f !== 'string' || !drop.has(f));
199
+ }
200
+ // ============ Wrapper registry ============
201
+ // One wrapper instance per (client, appName): two wrappers sharing an app on
202
+ // one connection would collide on topics, presence and the online lobby.
203
+ // Warn (not throw): HMR and tests legitimately construct before disposing.
204
+ const wrapperRegistry = new WeakMap();
205
+ /** Register a wrapper against a client + appName; warns on collision. */
206
+ function registerWrapper(client, appName, wrapperName) {
207
+ let apps = wrapperRegistry.get(client);
208
+ if (!apps) {
209
+ apps = new Map();
210
+ wrapperRegistry.set(client, apps);
211
+ }
212
+ const existing = apps.get(appName);
213
+ if (existing) {
214
+ console.warn(`[${wrapperName}] Another wrapper (${existing}) is already attached to this client for app "${appName}". ` +
215
+ `Use one wrapper per (client, app) — detach the other instance first.`);
216
+ }
217
+ apps.set(appName, wrapperName);
218
+ }
219
+ /** Release a wrapper's (client, appName) registration on detach. */
220
+ function releaseWrapper(client, appName) {
221
+ wrapperRegistry.get(client)?.delete(appName);
222
+ }
223
+
224
+ const DEFAULT_APP_NAME = 'dash';
225
+ const DEFAULT_MAX_METRIC_POINTS = 1000;
226
+ const DEFAULT_AGGREGATION_WINDOW = 60000; // 1 minute
227
+ const TOPIC_METRICS = 'metrics';
228
+ const TOPIC_WIDGETS = 'widgets';
229
+ const LOBBY_ID = 'online';
230
+ /** Delay before the post-setup lobby presence refetch (catches simultaneous joiners) */
231
+ const LOBBY_REFRESH_DELAY_MS = 2000;
232
+
233
+ /** Maps the public topic names onto the wire topics. */
234
+ const FILTER_TOPICS = {
235
+ metrics: TOPIC_METRICS,
236
+ widgets: TOPIC_WIDGETS,
237
+ };
238
+ class DashboardPanel extends EventEmitter {
239
+ /** @internal */
240
+ constructor(name, roomContext, localViewerId, localActorId, options, log, isConnected) {
241
+ super();
242
+ // Stored topic handler refs — cleanup removes exactly these, never all
243
+ // handlers for a topic (the client may be shared with other consumers).
244
+ this._onMetricsRef = null;
245
+ this._onWidgetsRef = null;
246
+ /**
247
+ * Filter values applied per topic. Mirrors what was actually sent to the
248
+ * server, including the `__none__` placeholder, so add/remove merge against
249
+ * the real subscription rather than a cleaner-looking copy of it.
250
+ */
251
+ this._filters = { metrics: [], widgets: [] };
252
+ this.name = name;
253
+ this._roomContext = roomContext;
254
+ this._localViewerId = localViewerId;
255
+ this._options = options;
256
+ this._log = log;
257
+ this._isConnected = isConnected;
258
+ this._presenceManager = new PresenceManager(localActorId);
259
+ this._metricStore = new MetricStore(options.maxMetricPoints);
260
+ this._widgetManager = new WidgetManager();
261
+ }
262
+ publishMetric(streamId, value, opts) {
263
+ const point = { id: generateId(), streamId, value, unit: opts?.unit, tags: opts?.tags, timestamp: Date.now(), isReplay: false };
264
+ this._metricStore.add(point);
265
+ this._roomContext.emit(TOPIC_METRICS, { id: point.id, streamId, value, unit: point.unit, tags: point.tags, timestamp: point.timestamp }, { echo: false, ...filterEmitOptions(opts) });
266
+ return point;
267
+ }
268
+ // ============ Filters ============
269
+ /** The filter values currently applied to this panel, by topic. */
270
+ get filters() {
271
+ return { metrics: [...this._filters.metrics], widgets: [...this._filters.widgets] };
272
+ }
273
+ /**
274
+ * Replace this panel's filters — only data published with one of these
275
+ * values is delivered. Applies to metrics and widgets unless you scope the
276
+ * call to one with `{ topic }`.
277
+ *
278
+ * Passing an empty array clears filtering and restores the wildcard
279
+ * subscription, which receives everything.
280
+ *
281
+ * @example
282
+ * ```ts
283
+ * panel.setFilters(['cpu', 'mem']); // both topics
284
+ * panel.setFilters(['cpu'], { topic: 'metrics' }); // metrics only
285
+ * panel.setFilters([['cpu', 'prod']]); // cpu AND prod
286
+ * panel.setFilters([]); // everything
287
+ * ```
288
+ */
289
+ setFilters(values, opts) {
290
+ for (const topic of this._targetTopics(opts)) {
291
+ this._filters[topic] = [...values];
292
+ // The core types filters as `string[]`, but both its implementation and
293
+ // the wire protocol accept AND groups (nested arrays).
294
+ this._roomContext.setFilters(FILTER_TOPICS[topic], values);
295
+ }
296
+ }
297
+ /** Add filter values to the existing set. Existing AND groups are kept. */
298
+ addFilters(values, opts) {
299
+ for (const topic of this._targetTopics(opts)) {
300
+ this.setFilters(mergeFilters(this._filters[topic], values), { topic });
301
+ }
302
+ }
303
+ /**
304
+ * Remove filter values from the existing set. Removing the last value
305
+ * restores the wildcard subscription.
306
+ */
307
+ removeFilters(values, opts) {
308
+ for (const topic of this._targetTopics(opts)) {
309
+ this.setFilters(withoutFilters(this._filters[topic], values), { topic });
310
+ }
311
+ }
312
+ _targetTopics(opts) {
313
+ return opts?.topic ? [opts.topic] : ['metrics', 'widgets'];
314
+ }
315
+ /** Replace all metric filters — alias for `setFilters(values, { topic: 'metrics' })`. */
316
+ setMetricFilters(filters) {
317
+ this.setFilters(filters, { topic: 'metrics' });
318
+ }
319
+ /** Add filter values to the existing metric filter set. */
320
+ addMetricFilters(filters) {
321
+ this.addFilters(filters, { topic: 'metrics' });
322
+ }
323
+ /** Remove specific filter values from the metric filter set. */
324
+ removeMetricFilters(filters) {
325
+ this.removeFilters(filters, { topic: 'metrics' });
326
+ }
327
+ publishWidget(widgetId, type, data, label, opts) {
328
+ const update = { id: generateId(), widgetId, type, data, label, timestamp: Date.now(), isReplay: false };
329
+ this._widgetManager.update(update);
330
+ this._roomContext.emit(TOPIC_WIDGETS, { id: update.id, widgetId, type, data, label, timestamp: update.timestamp }, { echo: false, ...filterEmitOptions(opts) });
331
+ return update;
332
+ }
333
+ getMetrics(streamId) { return this._metricStore.getAll(streamId); }
334
+ getAggregation(streamId, windowMs) { return this._metricStore.getAggregation(streamId, windowMs); }
335
+ getWidget(widgetId) { return this._widgetManager.get(widgetId); }
336
+ getWidgets() { return this._widgetManager.getAll(); }
337
+ getViewers() { return this._presenceManager.getAll(); }
338
+ _subscribe(metricFilters, filters) {
339
+ if (filters && filters.length > 0) {
340
+ // Uniform filter API: applies to both content topics, and an empty array
341
+ // means "everything" (the wildcard), matching the other blueprint SDKs.
342
+ this._filters = { metrics: [...filters], widgets: [...filters] };
343
+ this._roomContext.subscribe(TOPIC_METRICS, { filters });
344
+ this._roomContext.subscribe(TOPIC_WIDGETS, { filters });
345
+ this._attachHandlers();
346
+ return;
347
+ }
348
+ if (metricFilters !== undefined) {
349
+ // Legacy `metricFilters` path. If empty array, use a no-match placeholder
350
+ // to avoid wildcard subscription (which receives everything).
351
+ const resolved = metricFilters.length > 0 ? metricFilters : ['__none__'];
352
+ this._filters.metrics = [...resolved];
353
+ this._roomContext.subscribe(TOPIC_METRICS, { filters: resolved });
354
+ }
355
+ else {
356
+ this._roomContext.subscribe(TOPIC_METRICS);
357
+ }
358
+ this._roomContext.subscribe(TOPIC_WIDGETS);
359
+ this._attachHandlers();
360
+ }
361
+ /** @internal Attach the metric and widget listeners. */
362
+ _attachHandlers() {
363
+ // Listen for metrics (refs stored for handler-specific removal)
364
+ this._onMetricsRef = (data, meta) => {
365
+ const raw = data;
366
+ const point = { id: raw.id, streamId: raw.streamId, value: raw.value, unit: raw.unit, tags: raw.tags, timestamp: raw.timestamp, isReplay: meta.isReplay ?? false };
367
+ if (this._metricStore.add(point))
368
+ this.emit('metric', point);
369
+ };
370
+ this._roomContext.on(TOPIC_METRICS, this._onMetricsRef);
371
+ // Listen for widget updates
372
+ this._onWidgetsRef = (data, meta) => {
373
+ const raw = data;
374
+ const update = { id: raw.id, widgetId: raw.widgetId, type: raw.type, data: raw.data, label: raw.label, timestamp: raw.timestamp, isReplay: meta.isReplay ?? false };
375
+ this._widgetManager.update(update);
376
+ this.emit('widgetUpdate', update);
377
+ };
378
+ this._roomContext.on(TOPIC_WIDGETS, this._onWidgetsRef);
379
+ }
380
+ _activate() {
381
+ this._setPresence();
382
+ this._roomContext.fetchPresence().then((actors) => {
383
+ for (const actor of actors) {
384
+ if (actor.presence) {
385
+ const v = this._presenceManager.addFromPresence(actor.actorTokenId, actor.presence, actor.joinedAt);
386
+ if (v)
387
+ this.emit('viewerJoined', v);
388
+ }
389
+ }
390
+ }).catch(() => { });
391
+ }
392
+ _deactivate() { this._presenceManager.clear(); }
393
+ _handlePresenceJoin(actorTokenId, pd) { const v = this._presenceManager.addFromPresence(actorTokenId, pd); if (v)
394
+ this.emit('viewerJoined', v); }
395
+ _handlePresenceLeave(actorTokenId) { const v = this._presenceManager.removeByActorId(actorTokenId); if (v)
396
+ this.emit('viewerLeft', v); }
397
+ _handlePresenceUpdate(actorTokenId, pd) { this._presenceManager.addFromPresence(actorTokenId, pd); }
398
+ _handleReplayStart(count) { this.emit('replayStart', { count }); }
399
+ _handleReplayEnd(replayed) { this.emit('replayEnd', { replayed }); }
400
+ _updateLocalPresence() { this._setPresence(); }
401
+ _cleanup() {
402
+ this._log('Panel cleanup:', this.name);
403
+ // Server unsubscribes need a live socket; skip when disconnected
404
+ // (best-effort — the core would no-op with an error callback anyway).
405
+ if (this._isConnected()) {
406
+ this._roomContext.unsubscribe(TOPIC_METRICS);
407
+ this._roomContext.unsubscribe(TOPIC_WIDGETS);
408
+ }
409
+ // Handler-specific removal only: the client may be shared, and a bare
410
+ // off(topic) would strip other consumers' handlers too.
411
+ if (this._onMetricsRef)
412
+ this._roomContext.off(TOPIC_METRICS, this._onMetricsRef);
413
+ if (this._onWidgetsRef)
414
+ this._roomContext.off(TOPIC_WIDGETS, this._onWidgetsRef);
415
+ this._onMetricsRef = null;
416
+ this._onWidgetsRef = null;
417
+ this._metricStore.clear();
418
+ this._widgetManager.clear();
419
+ this._presenceManager.clear();
420
+ this.removeAllListeners();
421
+ }
422
+ _setPresence() {
423
+ this._roomContext.setPresence({
424
+ viewerId: this._localViewerId,
425
+ username: this._options.username,
426
+ metadata: this._options.metadata,
427
+ // Scope tag: on a shared client, other apps' wrappers filter our
428
+ // presence out by this (and we filter theirs).
429
+ __scope: this._options.appName,
430
+ });
431
+ }
432
+ }
433
+
434
+ /**
435
+ * NoLagDash — high-level live dashboard SDK built on @nolag/js-sdk.
436
+ *
437
+ * Provides multi-panel dashboards, real-time metric streams with
438
+ * aggregation, widget updates, viewer presence, and replay — all
439
+ * framework-agnostic via events.
440
+ *
441
+ * The wrapper NEVER manages the connection. The app owns one core NoLag
442
+ * client (shared by any number of wrappers on distinct apps) and the
443
+ * wrapper attaches to it at construction and releases it via `detach()`.
444
+ *
445
+ * @example
446
+ * ```typescript
447
+ * import { NoLag } from '@nolag/js-sdk';
448
+ * import { NoLagDash } from '@nolag/dash';
449
+ *
450
+ * const client = NoLag(async () => (await (await fetch('/api/nolag-token')).json()).token);
451
+ * const dash = new NoLagDash({ client, appName: 'my-dash', username: 'Alice' });
452
+ *
453
+ * dash.on('viewerOnline', (v) => console.log(v.username, 'is watching'));
454
+ *
455
+ * await client.connect(); // the app owns the connection
456
+ * await dash.ready(); // wrapper setup done (identity, lobby, panels)
457
+ *
458
+ * const panel = dash.joinPanel('overview');
459
+ * panel.on('metric', (m) => console.log(m.streamId, m.value));
460
+ * panel.publishMetric('cpu', 75);
461
+ *
462
+ * dash.detach(); // wrapper releases its handlers and topics
463
+ * client.disconnect(); // the app closes the socket
464
+ * ```
465
+ */
466
+ class NoLagDash extends EventEmitter {
467
+ constructor(options) {
468
+ super();
469
+ this._localViewer = null;
470
+ this._panels = new Map();
471
+ this._lobby = null;
472
+ this._onlineViewers = new Map();
473
+ this._actorToViewerId = new Map();
474
+ // Lifecycle: one setup run per connection epoch; detach is terminal.
475
+ this._epoch = 0;
476
+ this._detached = false;
477
+ this._isReady = false;
478
+ this._lobbyRefreshTimer = null;
479
+ // Stored client handler refs. INVARIANT: every client.on() below has a
480
+ // matching client.off() in detach() — never bare off(event), never inline
481
+ // closures on the client.
482
+ this._onConnectRef = () => this._onConnect();
483
+ this._onDisconnectRef = (reason) => {
484
+ this._log('Disconnected:', reason);
485
+ this.emit('disconnected', reason);
486
+ };
487
+ this._onReconnectRef = () => {
488
+ this._log('Reconnecting...');
489
+ this.emit('reconnecting');
490
+ };
491
+ this._onErrorRef = (error) => {
492
+ this._log('Error:', error);
493
+ this.emit('error', error);
494
+ };
495
+ this._onReplayStartRef = (data) => {
496
+ const event = data;
497
+ for (const panel of this._panels.values()) {
498
+ panel._handleReplayStart(event.count);
499
+ }
500
+ };
501
+ this._onReplayEndRef = (data) => {
502
+ const event = data;
503
+ for (const panel of this._panels.values()) {
504
+ panel._handleReplayEnd(event.replayed);
505
+ }
506
+ };
507
+ this._onPresenceJoinRef = (data) => this._handlePresenceJoin(data);
508
+ this._onPresenceLeaveRef = (data) => this._handlePresenceLeave(data);
509
+ this._onPresenceUpdateRef = (data) => this._handlePresenceUpdate(data);
510
+ this._onLobbyJoinRef = (data) => this._handleLobbyJoin(data);
511
+ this._onLobbyLeaveRef = (data) => this._handleLobbyLeave(data);
512
+ this._onLobbyUpdateRef = (data) => this._handleLobbyUpdate(data);
513
+ if (!options?.client) {
514
+ throw new TypeError('NoLagDash requires an injected NoLag client: new NoLagDash({ client, appName, ... })');
515
+ }
516
+ this._client = options.client;
517
+ this._viewerId = generateId();
518
+ this._options = {
519
+ username: options.username,
520
+ metadata: options.metadata,
521
+ appName: options.appName ?? DEFAULT_APP_NAME,
522
+ maxMetricPoints: options.maxMetricPoints ?? DEFAULT_MAX_METRIC_POINTS,
523
+ aggregationWindow: options.aggregationWindow ?? DEFAULT_AGGREGATION_WINDOW,
524
+ debug: options.debug ?? false,
525
+ panels: options.panels ?? [],
526
+ };
527
+ this._log = createLogger('NoLagDash', this._options.debug);
528
+ this._readyPromise = new Promise((resolve, reject) => {
529
+ this._readyResolve = resolve;
530
+ this._readyReject = reject;
531
+ });
532
+ // ready() rejection is only meaningful to callers that await it
533
+ this._readyPromise.catch(() => { });
534
+ registerWrapper(this._client, this._options.appName, 'NoLagDash');
535
+ // Construction = attach: wire everything now, with stored refs.
536
+ this._client.on('connect', this._onConnectRef);
537
+ this._client.on('disconnect', this._onDisconnectRef);
538
+ this._client.on('reconnect', this._onReconnectRef);
539
+ this._client.on('error', this._onErrorRef);
540
+ this._client.on('replay:start', this._onReplayStartRef);
541
+ this._client.on('replay:end', this._onReplayEndRef);
542
+ this._client.on('presence:join', this._onPresenceJoinRef);
543
+ this._client.on('presence:leave', this._onPresenceLeaveRef);
544
+ this._client.on('presence:update', this._onPresenceUpdateRef);
545
+ this._client.on('lobbyPresence:join', this._onLobbyJoinRef);
546
+ this._client.on('lobbyPresence:leave', this._onLobbyLeaveRef);
547
+ this._client.on('lobbyPresence:update', this._onLobbyUpdateRef);
548
+ // Attach-to-connected: if the client is already authenticated, run setup.
549
+ // The microtask lets the caller wire wrapper event handlers synchronously
550
+ // first; a racing real 'connect' event wins via the epoch guard.
551
+ queueMicrotask(() => {
552
+ if (this._epoch === 0 && !this._detached && this._client.connected) {
553
+ this._onConnect();
554
+ }
555
+ });
556
+ }
557
+ // ============ Public Properties ============
558
+ /** Whether the underlying connection is established (connected ≠ ready) */
559
+ get connected() {
560
+ return !this._detached && this._client.connected;
561
+ }
562
+ /** The injected core client (owned by the app, not the wrapper) */
563
+ get client() {
564
+ return this._client;
565
+ }
566
+ /** The local viewer's info (available after ready) */
567
+ get localViewer() {
568
+ return this._localViewer;
569
+ }
570
+ /** All currently joined panels */
571
+ get panels() {
572
+ return this._panels;
573
+ }
574
+ // ============ Lifecycle ============
575
+ /**
576
+ * Resolves once the wrapper's first setup completed (identity, lobby and
577
+ * configured panels ready — equivalently, once 'connected' has fired).
578
+ * Rejects only if detach() is called before that. Client auth failures
579
+ * surface via the app's own `await client.connect()`, not here.
580
+ */
581
+ ready() {
582
+ return this._readyPromise;
583
+ }
584
+ /**
585
+ * Detach from the client: remove every handler this wrapper added,
586
+ * unsubscribe its topics and lobby (when connected), clear state.
587
+ * Terminal and idempotent; never touches the socket. To use dash again,
588
+ * construct a new instance.
589
+ */
590
+ detach() {
591
+ if (this._detached)
592
+ return;
593
+ this._log('Detaching...');
594
+ this._detached = true;
595
+ this._epoch++; // aborts any in-flight setup at its next checkpoint
596
+ if (this._lobbyRefreshTimer) {
597
+ clearTimeout(this._lobbyRefreshTimer);
598
+ this._lobbyRefreshTimer = null;
599
+ }
600
+ // Remove all client handlers by stored ref
601
+ this._client.off('connect', this._onConnectRef);
602
+ this._client.off('disconnect', this._onDisconnectRef);
603
+ this._client.off('reconnect', this._onReconnectRef);
604
+ this._client.off('error', this._onErrorRef);
605
+ this._client.off('replay:start', this._onReplayStartRef);
606
+ this._client.off('replay:end', this._onReplayEndRef);
607
+ this._client.off('presence:join', this._onPresenceJoinRef);
608
+ this._client.off('presence:leave', this._onPresenceLeaveRef);
609
+ this._client.off('presence:update', this._onPresenceUpdateRef);
610
+ this._client.off('lobbyPresence:join', this._onLobbyJoinRef);
611
+ this._client.off('lobbyPresence:leave', this._onLobbyLeaveRef);
612
+ this._client.off('lobbyPresence:update', this._onLobbyUpdateRef);
613
+ // Panels: handler-specific off + connected-gated server unsubscribe
614
+ for (const name of [...this._panels.keys()]) {
615
+ this._panels.get(name)._cleanup();
616
+ this._panels.delete(name);
617
+ }
618
+ // Lobby: server unsubscribe is best-effort and needs a live socket
619
+ if (this._lobby && this._client.connected) {
620
+ try {
621
+ this._lobby.unsubscribe();
622
+ }
623
+ catch {
624
+ /* best-effort */
625
+ }
626
+ }
627
+ this._lobby = null;
628
+ this._onlineViewers.clear();
629
+ this._actorToViewerId.clear();
630
+ this._localViewer = null;
631
+ releaseWrapper(this._client, this._options.appName);
632
+ if (!this._isReady) {
633
+ this._readyReject(new Error('NoLagDash detached before ready'));
634
+ }
635
+ }
636
+ // ============ Private: Epoch Setup ============
637
+ _onConnect() {
638
+ this._epoch++;
639
+ void this._runSetup(this._epoch);
640
+ }
641
+ /**
642
+ * One setup pass per connection epoch. Serves both initial setup (epoch 1)
643
+ * and reconnect restore (epoch > 1). Aborts silently whenever a newer
644
+ * epoch started or the wrapper detached — checked after every await.
645
+ */
646
+ async _runSetup(epoch) {
647
+ const stale = () => epoch !== this._epoch || this._detached;
648
+ this._log(this._isReady ? 'Restoring after reconnect...' : 'Setting up...');
649
+ // Identity (client.actorId is guaranteed post-auth)
650
+ if (!this._localViewer) {
651
+ this._localViewer = {
652
+ viewerId: this._viewerId,
653
+ actorTokenId: this._client.actorId,
654
+ username: this._options.username,
655
+ metadata: this._options.metadata,
656
+ joinedAt: Date.now(),
657
+ isLocal: true,
658
+ };
659
+ this._log('Local viewer:', this._localViewer.viewerId, '→', this._localViewer.actorTokenId);
660
+ }
661
+ else {
662
+ this._localViewer.actorTokenId = this._client.actorId;
663
+ }
664
+ // Lobby: subscribe every epoch (idempotent server-side) and diff-hydrate
665
+ // from the returned snapshot — one path for setup and restore.
666
+ if (!this._lobby) {
667
+ this._lobby = this._client.setApp(this._options.appName).setLobby(LOBBY_ID);
668
+ }
669
+ try {
670
+ const state = await this._lobby.subscribe();
671
+ if (stale())
672
+ return;
673
+ this._diffHydrateOnlineViewers(state);
674
+ this._log('Lobby subscribed, online viewers:', this._onlineViewers.size);
675
+ }
676
+ catch (err) {
677
+ if (stale())
678
+ return;
679
+ this._log('Lobby subscription failed:', err);
680
+ }
681
+ if (!this._isReady) {
682
+ // First successful setup: pre-subscribe configured panels
683
+ for (const panelName of this._options.panels) {
684
+ this._subscribePanelInternal(panelName);
685
+ }
686
+ }
687
+ else {
688
+ // Server auto-restored topic subscriptions; only panel-scoped presence
689
+ // needs re-applying (the core does not restore it).
690
+ for (const panel of this._panels.values()) {
691
+ panel._updateLocalPresence();
692
+ }
693
+ }
694
+ if (stale())
695
+ return;
696
+ // Ready keys on the first setup that COMPLETES, not on epoch 1: an
697
+ // epoch aborted by a racing reconnect must not strand ready().
698
+ if (!this._isReady) {
699
+ this._isReady = true;
700
+ this._readyResolve();
701
+ this.emit('connected');
702
+ }
703
+ else {
704
+ this.emit('reconnected');
705
+ }
706
+ // Deferred lobby refetch: catches viewers who joined during the setup
707
+ // window (e.g. simultaneous multi-tab connects).
708
+ this._scheduleLobbyRefresh(epoch);
709
+ }
710
+ _scheduleLobbyRefresh(epoch) {
711
+ if (this._lobbyRefreshTimer)
712
+ clearTimeout(this._lobbyRefreshTimer);
713
+ this._lobbyRefreshTimer = setTimeout(() => {
714
+ this._lobbyRefreshTimer = null;
715
+ if (epoch !== this._epoch || this._detached || !this._client.connected || !this._lobby) {
716
+ return;
717
+ }
718
+ this._lobby
719
+ .fetchPresence()
720
+ .then((state) => {
721
+ if (epoch !== this._epoch || this._detached)
722
+ return;
723
+ this._diffHydrateOnlineViewers(state);
724
+ })
725
+ .catch(() => {
726
+ /* best-effort */
727
+ });
728
+ }, LOBBY_REFRESH_DELAY_MS);
729
+ }
730
+ // ============ Panel Management ============
731
+ /**
732
+ * Join a dashboard panel. If the panel was pre-subscribed via the `panels`
733
+ * option, activates it. Otherwise creates, subscribes, and activates it.
734
+ */
735
+ joinPanel(name, opts) {
736
+ this._assertUsable();
737
+ let panel = this._panels.get(name);
738
+ if (!panel) {
739
+ panel = this._subscribePanelInternal(name, opts?.metricFilters, opts?.filters);
740
+ }
741
+ else if (opts?.filters) {
742
+ // Already subscribed — re-point its filters rather than ignoring them.
743
+ panel.setFilters(opts.filters);
744
+ }
745
+ panel._activate();
746
+ return panel;
747
+ }
748
+ /**
749
+ * Leave a dashboard panel. Fully unsubscribes and removes it.
750
+ */
751
+ leavePanel(name) {
752
+ const panel = this._panels.get(name);
753
+ if (!panel)
754
+ return;
755
+ this._log('Leaving panel:', name);
756
+ panel._cleanup();
757
+ this._panels.delete(name);
758
+ }
759
+ /**
760
+ * Get all joined panels.
761
+ */
762
+ getPanels() {
763
+ return Array.from(this._panels.values());
764
+ }
765
+ // ============ Global Presence ============
766
+ /**
767
+ * Get all viewers currently online across all panels.
768
+ */
769
+ getOnlineViewers() {
770
+ return Array.from(this._onlineViewers.values());
771
+ }
772
+ // ============ Private: Guards ============
773
+ _assertUsable() {
774
+ if (this._detached) {
775
+ throw new Error('NoLagDash has been detached — construct a new instance');
776
+ }
777
+ if (!this._isReady || !this._localViewer) {
778
+ throw new Error('NoLagDash not ready — await ready() or the "connected" event');
779
+ }
780
+ }
781
+ // ============ Private: Panel Setup ============
782
+ _subscribePanelInternal(name, metricFilters, filters) {
783
+ this._log('Subscribing panel:', name);
784
+ const roomContext = this._client.setApp(this._options.appName).setRoom(name);
785
+ const panel = new DashboardPanel(name, roomContext, this._viewerId, this._client.actorId, this._options, createLogger(`DashPanel:${name}`, this._options.debug), () => this._client.connected);
786
+ this._panels.set(name, panel);
787
+ panel._subscribe(metricFilters, filters);
788
+ return panel;
789
+ }
790
+ // ============ Private: Scope Filtering ============
791
+ /**
792
+ * On a shared client, presence events from other apps' wrappers arrive on
793
+ * the same connection-level events. Wrappers stamp their presence with a
794
+ * `__scope` (their appName); a mismatched tag means another app's data.
795
+ * Untagged presence is accepted (older peers in this same app).
796
+ */
797
+ _foreignScope(data) {
798
+ const scope = data?.__scope;
799
+ return typeof scope === 'string' && scope !== this._options.appName;
800
+ }
801
+ // ============ Private: Room Presence → Panels ============
802
+ _handlePresenceJoin(data) {
803
+ if (data.actorTokenId === this._localViewer?.actorTokenId)
804
+ return;
805
+ const pd = data.presence;
806
+ if (!pd?.viewerId || this._foreignScope(pd))
807
+ return;
808
+ const viewer = this._toViewer(data.actorTokenId, pd);
809
+ this._actorToViewerId.set(data.actorTokenId, viewer.viewerId);
810
+ if (!this._onlineViewers.has(viewer.viewerId)) {
811
+ this._onlineViewers.set(viewer.viewerId, viewer);
812
+ this.emit('viewerOnline', viewer);
813
+ }
814
+ for (const panel of this._panels.values()) {
815
+ panel._handlePresenceJoin(data.actorTokenId, pd);
816
+ }
817
+ }
818
+ _handlePresenceLeave(data) {
819
+ if (data.actorTokenId === this._localViewer?.actorTokenId)
820
+ return;
821
+ // Panel leave ≠ offline — viewer may still be on another panel.
822
+ // Lobby leave handles actual offline status.
823
+ for (const panel of this._panels.values()) {
824
+ panel._handlePresenceLeave(data.actorTokenId);
825
+ }
826
+ }
827
+ _handlePresenceUpdate(data) {
828
+ if (data.actorTokenId === this._localViewer?.actorTokenId)
829
+ return;
830
+ const pd = data.presence;
831
+ if (!pd?.viewerId || this._foreignScope(pd))
832
+ return;
833
+ for (const panel of this._panels.values()) {
834
+ panel._handlePresenceUpdate(data.actorTokenId, pd);
835
+ }
836
+ }
837
+ // ============ Private: Lobby ============
838
+ _handleLobbyJoin(event) {
839
+ const { actorId, data } = event;
840
+ if (actorId === this._localViewer?.actorTokenId)
841
+ return;
842
+ const pd = data;
843
+ if (!pd?.viewerId || this._foreignScope(pd))
844
+ return;
845
+ const viewer = this._toViewer(actorId, pd);
846
+ this._actorToViewerId.set(actorId, viewer.viewerId);
847
+ if (!this._onlineViewers.has(viewer.viewerId)) {
848
+ this._onlineViewers.set(viewer.viewerId, viewer);
849
+ this.emit('viewerOnline', viewer);
850
+ }
851
+ }
852
+ _handleLobbyLeave(event) {
853
+ const { actorId, data } = event;
854
+ if (actorId === this._localViewer?.actorTokenId)
855
+ return;
856
+ const pd = data;
857
+ if (this._foreignScope(pd))
858
+ return;
859
+ const viewerId = pd?.viewerId
860
+ || this._actorToViewerId.get(actorId)
861
+ || this._findViewerIdByActorId(actorId);
862
+ if (viewerId) {
863
+ const viewer = this._onlineViewers.get(viewerId);
864
+ if (viewer) {
865
+ this._onlineViewers.delete(viewerId);
866
+ this._actorToViewerId.delete(actorId);
867
+ this.emit('viewerOffline', viewer);
868
+ }
869
+ }
870
+ }
871
+ _handleLobbyUpdate(event) {
872
+ const { actorId, data } = event;
873
+ if (actorId === this._localViewer?.actorTokenId)
874
+ return;
875
+ const pd = data;
876
+ if (!pd?.viewerId || this._foreignScope(pd))
877
+ return;
878
+ const viewer = this._toViewer(actorId, pd);
879
+ this._onlineViewers.set(viewer.viewerId, viewer);
880
+ }
881
+ /**
882
+ * Reconcile the online-viewer map against a fresh lobby snapshot, emitting
883
+ * only the deltas (viewerOffline for vanished, viewerOnline for new). One
884
+ * path for initial hydration, reconnect restore, and the deferred refetch.
885
+ */
886
+ _diffHydrateOnlineViewers(state) {
887
+ // Build the fresh viewer set from the snapshot
888
+ const fresh = new Map();
889
+ const freshActors = new Map();
890
+ for (const roomId of Object.keys(state)) {
891
+ const roomPresence = state[roomId];
892
+ for (const actorId of Object.keys(roomPresence)) {
893
+ if (actorId === this._localViewer?.actorTokenId)
894
+ continue;
895
+ const raw = roomPresence[actorId];
896
+ // Server returns full actor records with presence nested under .presence
897
+ const pd = (raw?.presence ?? raw);
898
+ if (pd?.viewerId && !this._foreignScope(pd)) {
899
+ if (!fresh.has(pd.viewerId)) {
900
+ fresh.set(pd.viewerId, this._toViewer(actorId, pd));
901
+ }
902
+ freshActors.set(actorId, pd.viewerId);
903
+ }
904
+ }
905
+ }
906
+ // Vanished viewers
907
+ for (const [viewerId, viewer] of [...this._onlineViewers]) {
908
+ if (!fresh.has(viewerId)) {
909
+ this._onlineViewers.delete(viewerId);
910
+ for (const [actorId, mappedViewerId] of [...this._actorToViewerId]) {
911
+ if (mappedViewerId === viewerId)
912
+ this._actorToViewerId.delete(actorId);
913
+ }
914
+ this.emit('viewerOffline', viewer);
915
+ }
916
+ }
917
+ // New viewers
918
+ for (const [viewerId, viewer] of fresh) {
919
+ if (!this._onlineViewers.has(viewerId)) {
920
+ this._onlineViewers.set(viewerId, viewer);
921
+ this.emit('viewerOnline', viewer);
922
+ }
923
+ }
924
+ for (const [actorId, viewerId] of freshActors) {
925
+ this._actorToViewerId.set(actorId, viewerId);
926
+ }
927
+ }
928
+ // ============ Private: Helpers ============
929
+ _toViewer(actorTokenId, data) {
930
+ return {
931
+ viewerId: data.viewerId,
932
+ actorTokenId,
933
+ username: data.username,
934
+ metadata: data.metadata,
935
+ joinedAt: Date.now(),
936
+ isLocal: false,
937
+ };
938
+ }
939
+ _findViewerIdByActorId(actorTokenId) {
940
+ for (const viewer of this._onlineViewers.values()) {
941
+ if (viewer.actorTokenId === actorTokenId)
942
+ return viewer.viewerId;
943
+ }
944
+ return undefined;
945
+ }
946
+ }
947
+
948
+ export { DashboardPanel, EventEmitter, NoLagDash };
949
+ //# sourceMappingURL=react-native.js.map