@buoy-gg/events 7.0.28 → 7.0.30

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.
@@ -1,1087 +0,0 @@
1
- /**
2
- * Auto-Discover Event Sources
3
- *
4
- * Automatically discovers and loads event stores from installed packages.
5
- * Uses try-catch pattern to safely handle missing packages - if a tool
6
- * isn't installed, it's silently skipped.
7
- *
8
- * This enables zero-config setup - just install the dev tool packages you
9
- * want and they'll automatically appear in the unified events timeline!
10
- */
11
-
12
- import type { UnifiedEvent, EventSource } from "../types";
13
-
14
- // ============================================================================
15
- // Types for discovered event sources
16
- // ============================================================================
17
-
18
- /**
19
- * Configuration for a discovered event source
20
- */
21
- export interface DiscoveredEventSource {
22
- /** Unique identifier for this source */
23
- id: string;
24
-
25
- /** Display name */
26
- name: string;
27
-
28
- /** Event sources this tool provides (can map to multiple EventSource types) */
29
- eventSources: EventSource[];
30
-
31
- /** Subscribe function - returns unsubscribe callback */
32
- subscribe: (onEvent: (event: UnifiedEvent) => void) => (() => void) | Promise<() => void>;
33
-
34
- /** Optional: Additional setup needed before subscribing */
35
- setup?: () => void | Promise<void>;
36
-
37
- /** Whether this source was successfully loaded */
38
- available: boolean;
39
- }
40
-
41
- /**
42
- * Result of auto-discovery
43
- */
44
- export interface DiscoveryResult {
45
- /** All discovered sources */
46
- sources: DiscoveredEventSource[];
47
-
48
- /** Which event source types are available */
49
- availableEventSources: Set<EventSource>;
50
- }
51
-
52
- // ============================================================================
53
- // Event transformers (inline to avoid import dependencies)
54
- // ============================================================================
55
-
56
- let eventIdCounter = 0;
57
-
58
- function generateEventId(source: string): string {
59
- return `${source}-${Date.now()}-${++eventIdCounter}`;
60
- }
61
-
62
- // ============================================================================
63
- // Storage Event Source Discovery
64
- // ============================================================================
65
-
66
- function tryLoadStorageSource(): DiscoveredEventSource | null {
67
- try {
68
- // @ts-ignore - Dynamic import that may not exist
69
- const { storageEventStore } = require("@buoy-gg/storage");
70
-
71
- return {
72
- id: "storage",
73
- name: "Storage",
74
- eventSources: ["storage-async", "storage-mmkv"],
75
- available: true,
76
- // No setup needed - onEvent() auto-starts capturing via Subscribable pattern
77
- subscribe: (onEvent) => {
78
- return storageEventStore.onEvent((event: unknown) => {
79
- const unifiedEvent = transformStorageEvent(event);
80
- onEvent(unifiedEvent);
81
- });
82
- },
83
- };
84
- } catch {
85
- return null;
86
- }
87
- }
88
-
89
- function transformStorageEvent(event: unknown): UnifiedEvent {
90
- const e = event as {
91
- storageType: "async" | "mmkv";
92
- action: string;
93
- timestamp: Date;
94
- data?: { key?: string; instanceId?: string; pairs?: unknown[]; keys?: string[] };
95
- };
96
-
97
- const source: EventSource = e.storageType === "async" ? "storage-async" : "storage-mmkv";
98
-
99
- // Get action label
100
- let title = e.action;
101
- if (e.storageType === "async") {
102
- const labelMap: Record<string, string> = {
103
- setItem: "Set Item",
104
- removeItem: "Remove Item",
105
- mergeItem: "Merge Item",
106
- clear: "Clear All",
107
- multiSet: "Multi Set",
108
- multiRemove: "Multi Remove",
109
- multiMerge: "Multi Merge",
110
- };
111
- title = labelMap[e.action] || e.action;
112
- }
113
-
114
- // Get subtitle
115
- let subtitle = "";
116
- if (e.storageType === "async") {
117
- switch (e.action) {
118
- case "setItem":
119
- case "removeItem":
120
- case "mergeItem":
121
- subtitle = e.data?.key || "unknown key";
122
- break;
123
- case "multiSet":
124
- case "multiMerge": {
125
- const pairCount = e.data?.pairs?.length || 0;
126
- subtitle = `${pairCount} key${pairCount !== 1 ? "s" : ""}`;
127
- break;
128
- }
129
- case "multiRemove": {
130
- const keyCount = e.data?.keys?.length || 0;
131
- subtitle = `${keyCount} key${keyCount !== 1 ? "s" : ""}`;
132
- break;
133
- }
134
- case "clear":
135
- subtitle = "all keys";
136
- break;
137
- }
138
- } else {
139
- subtitle = e.data?.key || e.data?.instanceId || "unknown";
140
- }
141
-
142
- // Get status
143
- let status: "success" | "error" | "pending" | "neutral" = "neutral";
144
- if (e.action.includes("set") || e.action.includes("Set") || e.action.includes("merge") || e.action.includes("Merge")) {
145
- status = "success";
146
- }
147
-
148
- return {
149
- id: generateEventId(source),
150
- source,
151
- timestamp: e.timestamp.getTime(),
152
- title,
153
- subtitle,
154
- status,
155
- originalEvent: event,
156
- };
157
- }
158
-
159
- // ============================================================================
160
- // Redux Event Source Discovery
161
- // ============================================================================
162
-
163
- function tryLoadReduxSource(): DiscoveredEventSource | null {
164
- try {
165
- // @ts-ignore - Dynamic import that may not exist
166
- const { reduxActionStore } = require("@buoy-gg/redux");
167
-
168
- let lastActionId: string | null = null;
169
-
170
- return {
171
- id: "redux",
172
- name: "Redux",
173
- eventSources: ["redux"],
174
- available: true,
175
- subscribe: (onEvent) => {
176
- return reduxActionStore.subscribe((actions: unknown[]) => {
177
- if (actions.length > 0) {
178
- const latestAction = actions[0] as { id: string };
179
- if (latestAction.id !== lastActionId) {
180
- lastActionId = latestAction.id;
181
- const unifiedEvent = transformReduxAction(latestAction);
182
- onEvent(unifiedEvent);
183
- }
184
- }
185
- });
186
- },
187
- };
188
- } catch {
189
- return null;
190
- }
191
- }
192
-
193
- function transformReduxAction(action: unknown): UnifiedEvent {
194
- const a = action as {
195
- id: string;
196
- type: string;
197
- timestamp: number;
198
- category?: "fulfilled" | "rejected" | "pending";
199
- hasStateChange?: boolean;
200
- payloadPreview?: string;
201
- diffSummary?: string;
202
- duration?: number;
203
- sliceName?: string;
204
- };
205
-
206
- // Get status
207
- let status: "success" | "error" | "pending" | "neutral" = "neutral";
208
- switch (a.category) {
209
- case "fulfilled":
210
- status = "success";
211
- break;
212
- case "rejected":
213
- status = "error";
214
- break;
215
- case "pending":
216
- status = "pending";
217
- break;
218
- default:
219
- status = a.hasStateChange ? "success" : "neutral";
220
- }
221
-
222
- // Get subtitle
223
- let subtitle = "";
224
- if (a.payloadPreview) {
225
- subtitle = a.payloadPreview;
226
- } else if (a.hasStateChange && a.diffSummary) {
227
- subtitle = a.diffSummary;
228
- } else if (a.duration !== undefined) {
229
- subtitle = `${a.duration.toFixed(1)}ms`;
230
- } else {
231
- subtitle = a.sliceName || "";
232
- }
233
-
234
- return {
235
- id: generateEventId("redux"),
236
- source: "redux",
237
- timestamp: a.timestamp,
238
- title: a.type,
239
- subtitle,
240
- status,
241
- originalEvent: action,
242
- };
243
- }
244
-
245
- // ============================================================================
246
- // Network Event Source Discovery
247
- // ============================================================================
248
-
249
- function tryLoadNetworkSource(): DiscoveredEventSource | null {
250
- try {
251
- // @ts-ignore - Dynamic import that may not exist
252
- // Note: We use networkListener (the getter) instead of startNetworkListener
253
- // because startNetworkListener is not exported from the main package
254
- const { networkEventStore, networkListener, addNetworkListener } = require("@buoy-gg/network");
255
-
256
- // Map network event IDs to unified event IDs for updates (request -> response)
257
- const networkEventIdMap = new Map<string, string>();
258
-
259
- return {
260
- id: "network",
261
- name: "Network",
262
- eventSources: ["network"],
263
- available: true,
264
- setup: () => {
265
- // Get the network listener singleton and start it if not already active
266
- const listener = networkListener();
267
- if (!listener.isActive) {
268
- listener.startListening();
269
- }
270
-
271
- // Ensure events flow into the store. The network panel does this via
272
- // addNetworkListener, but if events package loads first, we need to
273
- // set it up ourselves.
274
- if (listener.listenerCount === 0) {
275
- addNetworkListener((event: unknown) => {
276
- networkEventStore.processNetworkEvent(event);
277
- });
278
- }
279
- },
280
- subscribe: (onEvent) => {
281
- // Use onEvent() pattern - same as storage
282
- // This fires for each individual event (request or response/error update)
283
- // Pass replayExisting=false to avoid replaying up to 500 buffered events
284
- // synchronously, which causes ~30s UI freezes from mass state updates.
285
- return networkEventStore.onEvent((event: unknown) => {
286
- const ne = event as { id: string; status?: number; error?: unknown };
287
- const existingUnifiedId = networkEventIdMap.get(ne.id);
288
-
289
- if (!existingUnifiedId) {
290
- // New event (request started)
291
- const unifiedEvent = transformNetworkEvent(event);
292
- networkEventIdMap.set(ne.id, unifiedEvent.id);
293
- onEvent(unifiedEvent);
294
- } else {
295
- // Existing event updated (response received or error)
296
- const unifiedEvent = transformNetworkEvent(event);
297
- unifiedEvent.id = existingUnifiedId; // Keep the same unified ID
298
- onEvent(unifiedEvent);
299
- }
300
- }, false);
301
- },
302
- };
303
- } catch {
304
- return null;
305
- }
306
- }
307
-
308
- function transformNetworkEvent(event: unknown): UnifiedEvent {
309
- const e = event as {
310
- id: string;
311
- method: string;
312
- url: string;
313
- path?: string;
314
- host?: string;
315
- status?: number;
316
- error?: unknown;
317
- duration?: number;
318
- timestamp: number;
319
- operationName?: string;
320
- };
321
-
322
- // Get status
323
- let status: "success" | "error" | "pending" | "neutral" = "neutral";
324
- if (e.status === undefined) {
325
- status = "pending";
326
- } else if (e.error || e.status >= 400) {
327
- status = "error";
328
- } else if (e.status >= 200 && e.status < 400) {
329
- status = "success";
330
- }
331
-
332
- // Get title
333
- const title = e.operationName || `${e.method} ${e.path || e.url}`;
334
-
335
- // Get subtitle
336
- const parts: string[] = [];
337
- if (e.status !== undefined) {
338
- parts.push(`${e.status}`);
339
- } else if (e.error) {
340
- parts.push("Error");
341
- } else {
342
- parts.push("Pending");
343
- }
344
- if (e.duration !== undefined) {
345
- parts.push(`${e.duration.toFixed(0)}ms`);
346
- }
347
- if (e.host) {
348
- parts.push(e.host);
349
- }
350
-
351
- return {
352
- id: generateEventId("network"),
353
- source: "network",
354
- timestamp: e.timestamp,
355
- title,
356
- subtitle: parts.join(" · "),
357
- status,
358
- originalEvent: event,
359
- };
360
- }
361
-
362
- // ============================================================================
363
- // React Query Event Source Discovery
364
- // ============================================================================
365
-
366
- function tryLoadReactQuerySource(): DiscoveredEventSource | null {
367
- try {
368
- // @ts-ignore - Dynamic import that may not exist
369
- const { reactQueryEventStore } = require("@buoy-gg/react-query");
370
-
371
- let lastEventId: string | null = null;
372
-
373
- return {
374
- id: "react-query",
375
- name: "React Query",
376
- eventSources: ["react-query", "react-query-query", "react-query-mutation"],
377
- available: true,
378
- subscribe: (onEvent) => {
379
- return reactQueryEventStore.subscribe((events: unknown[]) => {
380
- if (events.length > 0) {
381
- const latestEvent = events[0] as { id: string };
382
- if (latestEvent.id !== lastEventId) {
383
- lastEventId = latestEvent.id;
384
- const unifiedEvent = transformReactQueryEvent(latestEvent);
385
- onEvent(unifiedEvent);
386
- }
387
- }
388
- });
389
- },
390
- };
391
- } catch {
392
- return null;
393
- }
394
- }
395
-
396
- function formatQueryKey(queryKey: unknown[] | undefined): string {
397
- if (!queryKey || queryKey.length === 0) return "unknown";
398
-
399
- return queryKey
400
- .map((part) => {
401
- if (typeof part === "string") return part;
402
- if (typeof part === "number") return String(part);
403
- if (typeof part === "object" && part !== null) {
404
- const obj = part as Record<string, unknown>;
405
- const firstValue = Object.values(obj)[0];
406
- if (typeof firstValue === "string" || typeof firstValue === "number") {
407
- return String(firstValue);
408
- }
409
- return JSON.stringify(part).slice(0, 20);
410
- }
411
- return String(part);
412
- })
413
- .join(" › ");
414
- }
415
-
416
- function transformReactQueryEvent(event: unknown): UnifiedEvent {
417
- const e = event as {
418
- id: string;
419
- type: string;
420
- timestamp: number;
421
- queryKey?: unknown[];
422
- mutationKey?: unknown[];
423
- mutationId?: number;
424
- queryHash?: string;
425
- duration?: number;
426
- };
427
-
428
- const isMutation = e.type.startsWith("mutation-");
429
- const source: EventSource = isMutation ? "react-query-mutation" : "react-query-query";
430
-
431
- // Get status
432
- let status: "success" | "error" | "pending" | "neutral" = "neutral";
433
- switch (e.type) {
434
- case "query-fetch-start":
435
- case "mutation-start":
436
- status = "pending";
437
- break;
438
- case "query-fetch-success":
439
- case "mutation-success":
440
- status = "success";
441
- break;
442
- case "query-fetch-error":
443
- case "mutation-error":
444
- status = "error";
445
- break;
446
- }
447
-
448
- // Get title
449
- let title = "";
450
- if (e.queryKey) {
451
- title = formatQueryKey(e.queryKey);
452
- } else if (e.mutationKey) {
453
- title = formatQueryKey(e.mutationKey);
454
- } else if (e.mutationId !== undefined) {
455
- title = `Mutation #${e.mutationId}`;
456
- } else {
457
- title = e.type.replace(/-/g, " ");
458
- }
459
-
460
- // Get subtitle
461
- const parts: string[] = [];
462
- switch (e.type) {
463
- case "query-fetch-start":
464
- parts.push("Fetching");
465
- break;
466
- case "query-fetch-success":
467
- parts.push("Success");
468
- break;
469
- case "query-fetch-error":
470
- parts.push("Error");
471
- break;
472
- case "query-invalidated":
473
- parts.push("Invalidated");
474
- break;
475
- case "mutation-start":
476
- parts.push("Mutating");
477
- break;
478
- case "mutation-success":
479
- parts.push("Success");
480
- break;
481
- case "mutation-error":
482
- parts.push("Error");
483
- break;
484
- }
485
- if (e.duration !== undefined) {
486
- parts.push(`${e.duration.toFixed(0)}ms`);
487
- }
488
-
489
- // Get correlation info
490
- let correlationId: string | undefined;
491
- if (e.queryHash) {
492
- correlationId = `rq-query-${e.queryHash}`;
493
- } else if (e.mutationId !== undefined) {
494
- correlationId = `rq-mutation-${e.mutationId}`;
495
- }
496
-
497
- let sequenceInGroup = 1;
498
- switch (e.type) {
499
- case "query-fetch-start":
500
- case "mutation-start":
501
- sequenceInGroup = 1;
502
- break;
503
- case "query-fetch-success":
504
- case "query-fetch-error":
505
- case "mutation-success":
506
- case "mutation-error":
507
- sequenceInGroup = 2;
508
- break;
509
- case "query-invalidated":
510
- sequenceInGroup = 3;
511
- break;
512
- }
513
-
514
- return {
515
- id: generateEventId(source),
516
- source,
517
- timestamp: e.timestamp,
518
- title,
519
- subtitle: parts.join(" · "),
520
- status,
521
- originalEvent: event,
522
- correlationId,
523
- sequenceInGroup,
524
- };
525
- }
526
-
527
- // ============================================================================
528
- // Route Events Source Discovery
529
- // ============================================================================
530
-
531
- function tryLoadRouteEventsSource(): DiscoveredEventSource | null {
532
- try {
533
- // @ts-ignore - Dynamic import that may not exist
534
- const { routeEventStore } = require("@buoy-gg/route-events");
535
-
536
- return {
537
- id: "route-events",
538
- name: "Routes",
539
- eventSources: ["route"],
540
- available: true,
541
- // No setup needed - onEvent() auto-starts listening via Subscribable pattern
542
- subscribe: (onEvent) => {
543
- return routeEventStore.onEvent((event: unknown) => {
544
- const unifiedEvent = transformRouteEvent(event);
545
- onEvent(unifiedEvent);
546
- });
547
- },
548
- };
549
- } catch {
550
- return null;
551
- }
552
- }
553
-
554
- function transformRouteEvent(event: unknown): UnifiedEvent {
555
- const e = event as {
556
- pathname: string;
557
- params: Record<string, unknown>;
558
- timestamp: number;
559
- previousPathname?: string;
560
- timeSincePrevious?: number;
561
- };
562
-
563
- // Get status
564
- let status: "success" | "error" | "pending" | "neutral" = "neutral";
565
- if (e.pathname === "/") {
566
- status = "success";
567
- } else if (Object.keys(e.params).length > 0) {
568
- status = "success";
569
- }
570
-
571
- // Get subtitle
572
- const parts: string[] = [];
573
- const paramCount = Object.keys(e.params).length;
574
- if (paramCount > 0) {
575
- parts.push(`${paramCount} param${paramCount !== 1 ? "s" : ""}`);
576
- }
577
- if (e.timeSincePrevious !== undefined && e.timeSincePrevious > 0) {
578
- if (e.timeSincePrevious < 1000) {
579
- parts.push(`${e.timeSincePrevious}ms`);
580
- } else {
581
- parts.push(`${(e.timeSincePrevious / 1000).toFixed(1)}s`);
582
- }
583
- }
584
- if (e.previousPathname && e.previousPathname !== e.pathname) {
585
- parts.push(`from ${e.previousPathname}`);
586
- }
587
-
588
- return {
589
- id: generateEventId("route"),
590
- source: "route",
591
- timestamp: e.timestamp,
592
- title: e.pathname || "/",
593
- subtitle: parts.join(" · ") || "navigation",
594
- status,
595
- originalEvent: event,
596
- };
597
- }
598
-
599
- // ============================================================================
600
- // Zustand Event Source Discovery
601
- // ============================================================================
602
-
603
- function tryLoadZustandSource(): DiscoveredEventSource | null {
604
- try {
605
- // @ts-ignore - Dynamic import that may not exist
606
- const { zustandStateStore } = require("@buoy-gg/zustand");
607
-
608
- let lastChangeId: string | null = null;
609
-
610
- return {
611
- id: "zustand",
612
- name: "Zustand",
613
- eventSources: ["zustand"],
614
- available: true,
615
- subscribe: (onEvent) => {
616
- return zustandStateStore.subscribe((changes: unknown[]) => {
617
- if (changes.length > 0) {
618
- const latestChange = changes[0] as { id: string };
619
- if (latestChange.id !== lastChangeId) {
620
- lastChangeId = latestChange.id;
621
- const unifiedEvent = transformZustandChange(latestChange);
622
- onEvent(unifiedEvent);
623
- }
624
- }
625
- });
626
- },
627
- };
628
- } catch {
629
- return null;
630
- }
631
- }
632
-
633
- function transformZustandChange(change: unknown): UnifiedEvent {
634
- const c = change as {
635
- id: string;
636
- storeName: string;
637
- timestamp: number;
638
- hasStateChange?: boolean;
639
- category?: "setState" | "replace";
640
- changedKeys?: string[];
641
- changedKeysCount?: number;
642
- diffSummary?: string;
643
- partialPreview?: string;
644
- duration?: number;
645
- isSlowUpdate?: boolean;
646
- };
647
-
648
- // Get status
649
- let status: "success" | "error" | "pending" | "neutral" = "neutral";
650
- if (c.isSlowUpdate) {
651
- status = "pending"; // Yellow for slow updates
652
- } else if (c.hasStateChange) {
653
- status = "success";
654
- }
655
-
656
- // Get subtitle
657
- const parts: string[] = [];
658
- if (c.changedKeys && c.changedKeys.length > 0) {
659
- const keys = c.changedKeys.slice(0, 3).join(", ");
660
- const more = c.changedKeys.length > 3 ? ` +${c.changedKeys.length - 3}` : "";
661
- parts.push(`${keys}${more}`);
662
- } else if (c.diffSummary) {
663
- parts.push(c.diffSummary);
664
- }
665
- if (c.duration !== undefined) {
666
- parts.push(`${c.duration.toFixed(1)}ms`);
667
- }
668
- if (c.category === "replace") {
669
- parts.push("replace");
670
- }
671
-
672
- return {
673
- id: generateEventId("zustand"),
674
- source: "zustand",
675
- timestamp: c.timestamp,
676
- title: c.storeName,
677
- subtitle: parts.join(" · ") || (c.hasStateChange ? "state changed" : "no change"),
678
- status,
679
- originalEvent: change,
680
- };
681
- }
682
-
683
- // ============================================================================
684
- // Jotai Event Source Discovery
685
- // ============================================================================
686
-
687
- function tryLoadJotaiSource(): DiscoveredEventSource | null {
688
- try {
689
- // @ts-ignore - Dynamic import that may not exist
690
- const { jotaiStateStore } = require("@buoy-gg/jotai");
691
-
692
- let lastChangeId: string | null = null;
693
-
694
- return {
695
- id: "jotai",
696
- name: "Jotai",
697
- eventSources: ["jotai"],
698
- available: true,
699
- subscribe: (onEvent) => {
700
- return jotaiStateStore.subscribe((changes: unknown[]) => {
701
- if (changes.length > 0) {
702
- const latestChange = changes[0] as { id: string };
703
- if (latestChange.id !== lastChangeId) {
704
- lastChangeId = latestChange.id;
705
- const unifiedEvent = transformJotaiChange(latestChange);
706
- onEvent(unifiedEvent);
707
- }
708
- }
709
- });
710
- },
711
- };
712
- } catch {
713
- return null;
714
- }
715
- }
716
-
717
- function transformJotaiChange(change: unknown): UnifiedEvent {
718
- const c = change as {
719
- id: string;
720
- atomLabel: string;
721
- timestamp: number;
722
- hasValueChange?: boolean;
723
- category?: "write" | "read";
724
- changedKeys?: string[];
725
- changedKeysCount?: number;
726
- diffSummary?: string;
727
- valuePreview?: string;
728
- };
729
-
730
- // Get status
731
- let status: "success" | "error" | "pending" | "neutral" = "neutral";
732
- if (c.category === "write" && c.hasValueChange) {
733
- status = "success";
734
- } else if (c.category === "read") {
735
- status = "neutral";
736
- }
737
-
738
- // Get subtitle
739
- const parts: string[] = [];
740
- if (c.valuePreview) {
741
- parts.push(c.valuePreview);
742
- } else if (c.diffSummary) {
743
- parts.push(c.diffSummary);
744
- }
745
- if (c.category) {
746
- parts.push(c.category);
747
- }
748
-
749
- return {
750
- id: generateEventId("jotai"),
751
- source: "jotai",
752
- timestamp: c.timestamp,
753
- title: c.atomLabel,
754
- subtitle: parts.join(" · ") || (c.hasValueChange ? "value changed" : "no change"),
755
- status,
756
- originalEvent: change,
757
- };
758
- }
759
-
760
- // ============================================================================
761
- // Render Events Source Discovery (Highlight Updates)
762
- // ============================================================================
763
-
764
- function tryLoadHighlightUpdatesSource(): DiscoveredEventSource | null {
765
- // Metro only treats a require() as optional when the statement sits DIRECTLY
766
- // inside a single-level try block — a require nested in a closure (even one
767
- // defined inside a try) fails the bundle when the package isn't installed.
768
- // So: require once here, and let the callbacks below close over the result.
769
- let highlightUpdates: any;
770
- try {
771
- // @ts-ignore - Dynamic import that may not exist
772
- highlightUpdates = require("@buoy-gg/highlight-updates");
773
- } catch {
774
- return null;
775
- }
776
-
777
- try {
778
- // Verify the required exports exist
779
- if (!highlightUpdates.RenderTracker || !highlightUpdates.HighlightUpdatesController) {
780
- return null;
781
- }
782
-
783
- const { RenderTracker, HighlightUpdatesController } = highlightUpdates;
784
-
785
- return {
786
- id: "render",
787
- name: "Render",
788
- eventSources: ["render"],
789
- available: true,
790
- setup: () => {
791
- // Enable background tracking (NOT the visual toggle) - this sets up render
792
- // interception without affecting the user's visual highlight toggle state
793
- if (HighlightUpdatesController) {
794
- HighlightUpdatesController.enableBackgroundTracking();
795
- }
796
- },
797
- subscribe: (onEvent) => {
798
- // Ensure background tracking is enabled (separate from visual toggle)
799
- if (HighlightUpdatesController && !HighlightUpdatesController.isBackgroundTrackingEnabled()) {
800
- HighlightUpdatesController.enableBackgroundTracking();
801
- }
802
-
803
- const unsubscribeCallback = RenderTracker.onRenderEvent((event: unknown, render: unknown) => {
804
- const unifiedEvent = transformRenderEvent(event, render);
805
- onEvent(unifiedEvent);
806
- });
807
-
808
- // Return a wrapped unsubscribe that also disables background tracking
809
- return () => {
810
- unsubscribeCallback();
811
- HighlightUpdatesController.disableBackgroundTracking();
812
- };
813
- },
814
- };
815
- } catch {
816
- return null;
817
- }
818
- }
819
-
820
- function transformRenderEvent(event: unknown, render: unknown): UnifiedEvent {
821
- const e = event as {
822
- id: string;
823
- timestamp: number;
824
- renderNumber: number;
825
- cause: {
826
- type: string;
827
- changedKeys?: string[];
828
- hookIndices?: number[];
829
- hookChanges?: Array<{
830
- index: number;
831
- type: string;
832
- description?: string;
833
- }>;
834
- componentCause?: string;
835
- componentName?: string;
836
- };
837
- };
838
-
839
- const r = render as {
840
- nativeTag: number;
841
- viewType: string;
842
- displayName: string;
843
- componentName?: string;
844
- testID?: string;
845
- renderCount: number;
846
- };
847
-
848
- // Use component name if available, otherwise display name (View, Text, etc.)
849
- const title = r.componentName || r.displayName || r.viewType;
850
-
851
- // Build subtitle from cause info
852
- const subtitleParts: string[] = [];
853
-
854
- // Add cause type
855
- const causeLabels: Record<string, string> = {
856
- mount: "mounted",
857
- props: "props changed",
858
- state: "state changed",
859
- hooks: "hooks changed",
860
- context: "context changed",
861
- parent: "parent re-rendered",
862
- unknown: "re-rendered",
863
- };
864
- subtitleParts.push(causeLabels[e.cause.type] || e.cause.type);
865
-
866
- // Add changed keys if props changed
867
- if (e.cause.type === "props" && e.cause.changedKeys?.length) {
868
- const keys = e.cause.changedKeys.slice(0, 3).join(", ");
869
- const more = e.cause.changedKeys.length > 3 ? ` +${e.cause.changedKeys.length - 3}` : "";
870
- subtitleParts.push(`[${keys}${more}]`);
871
- }
872
-
873
- // Add hook change description if available
874
- if (e.cause.hookChanges?.length) {
875
- const firstChange = e.cause.hookChanges[0];
876
- if (firstChange.description) {
877
- subtitleParts.push(firstChange.description);
878
- }
879
- }
880
-
881
- // Add render number
882
- subtitleParts.push(`#${e.renderNumber}`);
883
-
884
- // Determine status based on cause type
885
- let status: "success" | "error" | "pending" | "neutral" = "neutral";
886
- switch (e.cause.type) {
887
- case "mount":
888
- status = "neutral"; // First render is expected
889
- break;
890
- case "props":
891
- case "state":
892
- case "hooks":
893
- case "context":
894
- status = "success"; // Intentional re-renders
895
- break;
896
- case "parent":
897
- status = "pending"; // Potentially wasteful (yellow highlight)
898
- break;
899
- default:
900
- status = "neutral";
901
- }
902
-
903
- return {
904
- id: generateEventId("render"),
905
- source: "render",
906
- timestamp: e.timestamp,
907
- title,
908
- subtitle: subtitleParts.join(" · "),
909
- status,
910
- originalEvent: { event: e, render: r },
911
- };
912
- }
913
-
914
- // ============================================================================
915
- // Main Auto-Discovery Function
916
- // ============================================================================
917
-
918
- /**
919
- * Automatically discovers which event source packages are installed.
920
- *
921
- * This function attempts to load event stores from known dev tool packages.
922
- * If a package is installed, its event source will be available.
923
- * If a package is not installed, it will be silently skipped.
924
- *
925
- * @returns Discovery result with all available sources
926
- *
927
- * @example
928
- * ```tsx
929
- * const { sources, availableEventSources } = autoDiscoverEventSources();
930
- *
931
- * // sources contains all available event source configs
932
- * // availableEventSources contains the Set of EventSource types available
933
- * ```
934
- */
935
- export function autoDiscoverEventSources(): DiscoveryResult {
936
- const sources: DiscoveredEventSource[] = [];
937
- const availableEventSources = new Set<EventSource>();
938
-
939
- // Try to load each source
940
- const loaders = [
941
- tryLoadStorageSource,
942
- tryLoadReduxSource,
943
- tryLoadNetworkSource,
944
- tryLoadReactQuerySource,
945
- tryLoadRouteEventsSource,
946
- tryLoadZustandSource,
947
- tryLoadJotaiSource,
948
- tryLoadHighlightUpdatesSource,
949
- ];
950
-
951
- for (const loader of loaders) {
952
- const source = loader();
953
- if (source && source.available) {
954
- sources.push(source);
955
- source.eventSources.forEach((es) => availableEventSources.add(es));
956
- }
957
- }
958
-
959
- return { sources, availableEventSources };
960
- }
961
-
962
- /**
963
- * Get display configuration for an event source.
964
- * Returns config even for unavailable sources (for consistent UI).
965
- */
966
- export function getSourceDisplayConfig(source: EventSource): {
967
- label: string;
968
- color: string;
969
- icon: string;
970
- } {
971
- const configs: Record<EventSource, { label: string; color: string; icon: string }> = {
972
- "storage-async": { label: "Storage", color: "#8B5CF6", icon: "server-outline" },
973
- "storage-mmkv": { label: "MMKV", color: "#F59E0B", icon: "flash-outline" },
974
- redux: { label: "Redux", color: "#3B82F6", icon: "git-branch-outline" },
975
- network: { label: "Network", color: "#10B981", icon: "globe-outline" },
976
- "react-query": { label: "Query", color: "#EC4899", icon: "sync-outline" },
977
- "react-query-query": { label: "Query", color: "#EC4899", icon: "sync-outline" },
978
- "react-query-mutation": { label: "Mutation", color: "#F97316", icon: "flash-outline" },
979
- route: { label: "Route", color: "#06B6D4", icon: "navigate-outline" },
980
- zustand: { label: "Zustand", color: "#764ABC", icon: "cube-outline" },
981
- jotai: { label: "Jotai", color: "#14B8A6", icon: "ellipse-outline" },
982
- render: { label: "Render", color: "#F472B6", icon: "layers-outline" },
983
- };
984
-
985
- return configs[source] || { label: source, color: "#6B7280", icon: "help-outline" };
986
- }
987
-
988
- // Cache for discovered sources (singleton)
989
- let cachedDiscovery: DiscoveryResult | null = null;
990
-
991
- /**
992
- * Get cached discovery result, or run discovery if not cached.
993
- * Use this for performance - avoids repeated require() calls.
994
- */
995
- export function getCachedDiscovery(): DiscoveryResult {
996
- if (!cachedDiscovery) {
997
- cachedDiscovery = autoDiscoverEventSources();
998
- }
999
- return cachedDiscovery;
1000
- }
1001
-
1002
- /**
1003
- * Clear the discovery cache (useful for testing or hot reload).
1004
- */
1005
- export function clearDiscoveryCache(): void {
1006
- cachedDiscovery = null;
1007
- }
1008
-
1009
- // ============================================================================
1010
- // Subscriber Count Aggregation
1011
- // ============================================================================
1012
-
1013
- export interface SourceSubscriberCounts {
1014
- sourceId: string;
1015
- counts: {
1016
- eventCallbacks: number;
1017
- arrayListeners: number;
1018
- total: number;
1019
- };
1020
- }
1021
-
1022
- export interface AggregatedSubscriberCounts {
1023
- sources: SourceSubscriberCounts[];
1024
- totalSubscribers: number;
1025
- }
1026
-
1027
- /**
1028
- * Get subscriber counts from all discovered event stores.
1029
- * Useful for debugging and monitoring the event system.
1030
- */
1031
- export function getAggregatedSubscriberCounts(): AggregatedSubscriberCounts {
1032
- const sources: SourceSubscriberCounts[] = [];
1033
- let totalSubscribers = 0;
1034
-
1035
- // Try to get counts from storage store
1036
- try {
1037
- // @ts-ignore - Dynamic import that may not exist
1038
- const { storageEventStore } = require("@buoy-gg/storage");
1039
- const counts = storageEventStore.getSubscriberCounts();
1040
- sources.push({ sourceId: "storage", counts });
1041
- totalSubscribers += counts.total;
1042
- } catch {
1043
- // Package not installed
1044
- }
1045
-
1046
- // Try to get counts from network store
1047
- try {
1048
- // @ts-ignore - Dynamic import that may not exist
1049
- const { networkEventStore } = require("@buoy-gg/network");
1050
- const counts = networkEventStore.getSubscriberCounts();
1051
- sources.push({ sourceId: "network", counts });
1052
- totalSubscribers += counts.total;
1053
- } catch {
1054
- // Package not installed
1055
- }
1056
-
1057
- // Try to get counts from route events store
1058
- try {
1059
- // @ts-ignore - Dynamic import that may not exist
1060
- const { routeEventStore } = require("@buoy-gg/route-events");
1061
- const counts = routeEventStore.getSubscriberCounts();
1062
- sources.push({ sourceId: "route-events", counts });
1063
- totalSubscribers += counts.total;
1064
- } catch {
1065
- // Package not installed
1066
- }
1067
-
1068
- // Try to get counts from render tracker (highlight-updates)
1069
- try {
1070
- // @ts-ignore - Dynamic import that may not exist
1071
- const { RenderTracker, HighlightUpdatesController } = require("@buoy-gg/highlight-updates");
1072
- const callbackCount = RenderTracker.getRenderEventCallbackCount();
1073
- // Also count the visual highlight tool as a subscriber when enabled
1074
- const visualToolEnabled = HighlightUpdatesController?.isEnabled?.() ? 1 : 0;
1075
- const counts = {
1076
- eventCallbacks: callbackCount,
1077
- arrayListeners: visualToolEnabled,
1078
- total: callbackCount + visualToolEnabled,
1079
- };
1080
- sources.push({ sourceId: "render", counts });
1081
- totalSubscribers += counts.total;
1082
- } catch {
1083
- // Package not installed
1084
- }
1085
-
1086
- return { sources, totalSubscribers };
1087
- }