@flotrace/runtime 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,4417 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ DEFAULT_CONFIG: () => DEFAULT_CONFIG,
34
+ FloTraceProvider: () => FloTraceProvider,
35
+ FloTraceWebSocketClient: () => FloTraceWebSocketClient,
36
+ disposeWebSocketClient: () => disposeWebSocketClient,
37
+ getDetailedRenderReason: () => getDetailedRenderReason,
38
+ getFiberRefMap: () => getFiberRefMap,
39
+ getNodeEffects: () => getNodeEffects,
40
+ getNodeHooks: () => getNodeHooks,
41
+ getTimeline: () => getTimeline,
42
+ getWebSocketClient: () => getWebSocketClient,
43
+ inspectEffects: () => inspectEffects,
44
+ inspectHooks: () => inspectHooks,
45
+ installFiberTreeWalker: () => installFiberTreeWalker,
46
+ installNetworkTracker: () => installNetworkTracker,
47
+ installReduxTracker: () => installReduxTracker,
48
+ installRouterTracker: () => installRouterTracker,
49
+ installTanStackQueryTracker: () => installTanStackQueryTracker,
50
+ installTimelineTracker: () => installTimelineTracker,
51
+ installZustandTracker: () => installZustandTracker,
52
+ isReduxStore: () => isReduxStore,
53
+ isTanStackQueryClient: () => isTanStackQueryClient,
54
+ recordTimelineEvent: () => recordTimelineEvent,
55
+ requestTreeSnapshot: () => requestTreeSnapshot,
56
+ serializeProps: () => serializeProps,
57
+ serializeValue: () => serializeValue,
58
+ uninstallFiberTreeWalker: () => uninstallFiberTreeWalker,
59
+ uninstallNetworkTracker: () => uninstallNetworkTracker,
60
+ uninstallReduxTracker: () => uninstallReduxTracker,
61
+ uninstallRouterTracker: () => uninstallRouterTracker,
62
+ uninstallTanStackQueryTracker: () => uninstallTanStackQueryTracker,
63
+ uninstallTimelineTracker: () => uninstallTimelineTracker,
64
+ uninstallZustandTracker: () => uninstallZustandTracker,
65
+ useFloTrace: () => useFloTrace,
66
+ useTrackProps: () => useTrackProps,
67
+ withFloTrace: () => withFloTrace
68
+ });
69
+ module.exports = __toCommonJS(index_exports);
70
+
71
+ // src/FloTraceProvider.tsx
72
+ var import_react = __toESM(require("react"));
73
+
74
+ // src/types.ts
75
+ var DEFAULT_CONFIG = {
76
+ port: 3457,
77
+ appName: "React App",
78
+ enabled: process.env.NODE_ENV === "development",
79
+ autoReconnect: true,
80
+ reconnectInterval: 2e3,
81
+ trackAllRenders: true,
82
+ includeProps: true,
83
+ trackZustand: true,
84
+ trackRedux: true,
85
+ trackRouter: true,
86
+ trackContext: true,
87
+ trackTanstackQuery: true
88
+ };
89
+
90
+ // src/websocketClient.ts
91
+ var _FloTraceWebSocketClient = class _FloTraceWebSocketClient {
92
+ constructor(config = {}) {
93
+ this.ws = null;
94
+ this.messageQueue = [];
95
+ this.flushTimeout = null;
96
+ this.reconnectTimeout = null;
97
+ this.isConnecting = false;
98
+ this.reconnectAttempts = 0;
99
+ // Prevent unbounded queue growth when disconnected
100
+ this.messageHandlers = /* @__PURE__ */ new Set();
101
+ this.connectionHandlers = /* @__PURE__ */ new Set();
102
+ this.config = { ...DEFAULT_CONFIG, ...config };
103
+ }
104
+ /**
105
+ * Connect to the FloTrace WebSocket server
106
+ */
107
+ connect() {
108
+ if (this.ws || this.isConnecting) {
109
+ return;
110
+ }
111
+ if (!this.config.enabled) {
112
+ console.log("[FloTrace] Runtime disabled, skipping connection");
113
+ return;
114
+ }
115
+ if (typeof window === "undefined" || typeof WebSocket === "undefined") {
116
+ console.log("[FloTrace] Not in browser environment, skipping connection");
117
+ return;
118
+ }
119
+ this.isConnecting = true;
120
+ try {
121
+ const url = `ws://127.0.0.1:${this.config.port}`;
122
+ console.log(`[FloTrace] Connecting to ${url}...`);
123
+ this.ws = new WebSocket(url);
124
+ this.ws.onopen = () => {
125
+ this.isConnecting = false;
126
+ this.reconnectAttempts = 0;
127
+ console.log("[FloTrace] Connected to VS Code extension");
128
+ this.notifyConnectionChange(true);
129
+ this.send({
130
+ type: "runtime:ready",
131
+ appName: this.config.appName,
132
+ reactVersion: this.getReactVersion(),
133
+ appUrl: typeof window !== "undefined" ? window.location.href : void 0
134
+ });
135
+ this.flush();
136
+ };
137
+ this.ws.onmessage = (event) => {
138
+ try {
139
+ const message = JSON.parse(event.data);
140
+ this.handleMessage(message);
141
+ } catch (error) {
142
+ console.error("[FloTrace] Failed to parse message:", error);
143
+ }
144
+ };
145
+ this.ws.onclose = () => {
146
+ this.isConnecting = false;
147
+ this.ws = null;
148
+ console.log("[FloTrace] Disconnected from VS Code extension");
149
+ this.notifyConnectionChange(false);
150
+ if (this.config.autoReconnect) {
151
+ this.scheduleReconnect();
152
+ }
153
+ };
154
+ this.ws.onerror = (error) => {
155
+ this.isConnecting = false;
156
+ console.error("[FloTrace] WebSocket error:", error);
157
+ };
158
+ } catch (error) {
159
+ this.isConnecting = false;
160
+ console.error("[FloTrace] Failed to connect:", error);
161
+ if (this.config.autoReconnect) {
162
+ this.scheduleReconnect();
163
+ }
164
+ }
165
+ }
166
+ /**
167
+ * Disconnect from the server
168
+ */
169
+ disconnect() {
170
+ if (this.reconnectTimeout) {
171
+ clearTimeout(this.reconnectTimeout);
172
+ this.reconnectTimeout = null;
173
+ }
174
+ if (this.flushTimeout) {
175
+ clearTimeout(this.flushTimeout);
176
+ this.flushTimeout = null;
177
+ }
178
+ if (this.ws) {
179
+ try {
180
+ this.send({ type: "runtime:disconnect", reason: "Client disconnect" });
181
+ } catch (error) {
182
+ console.error("[FloTrace] Error sending disconnect message:", error);
183
+ }
184
+ this.ws.close();
185
+ this.ws = null;
186
+ }
187
+ }
188
+ /**
189
+ * Send a message to the extension (queued and batched)
190
+ */
191
+ send(message) {
192
+ if (!this.config.enabled) {
193
+ return;
194
+ }
195
+ this.messageQueue.push(message);
196
+ if (this.messageQueue.length > _FloTraceWebSocketClient.MAX_QUEUE_SIZE) {
197
+ this.messageQueue = this.messageQueue.slice(-_FloTraceWebSocketClient.MAX_QUEUE_SIZE);
198
+ }
199
+ if (!this.flushTimeout) {
200
+ this.flushTimeout = setTimeout(() => {
201
+ this.flush();
202
+ }, _FloTraceWebSocketClient.BATCH_FLUSH_MS);
203
+ }
204
+ if (this.messageQueue.length >= (this.config.trackAllRenders ? 50 : 10)) {
205
+ this.flush();
206
+ }
207
+ }
208
+ /**
209
+ * Send a message immediately (not batched)
210
+ */
211
+ sendImmediate(message) {
212
+ if (!this.config.enabled || !this.ws || this.ws.readyState !== WebSocket.OPEN) {
213
+ return;
214
+ }
215
+ try {
216
+ this.ws.send(JSON.stringify(message));
217
+ } catch (error) {
218
+ console.error("[FloTrace] Failed to send message:", error);
219
+ }
220
+ }
221
+ /**
222
+ * Flush the message queue
223
+ */
224
+ flush() {
225
+ if (this.flushTimeout) {
226
+ clearTimeout(this.flushTimeout);
227
+ this.flushTimeout = null;
228
+ }
229
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN || this.messageQueue.length === 0) {
230
+ return;
231
+ }
232
+ try {
233
+ for (const message of this.messageQueue) {
234
+ this.ws.send(JSON.stringify(message));
235
+ }
236
+ this.messageQueue = [];
237
+ } catch (error) {
238
+ console.error("[FloTrace] Failed to flush messages:", error);
239
+ }
240
+ }
241
+ /**
242
+ * Schedule a reconnection attempt
243
+ */
244
+ scheduleReconnect() {
245
+ if (this.reconnectTimeout) {
246
+ return;
247
+ }
248
+ if (this.reconnectAttempts >= _FloTraceWebSocketClient.MAX_RECONNECT_ATTEMPTS) {
249
+ console.warn(
250
+ `[FloTrace] Reconnection budget exhausted (${_FloTraceWebSocketClient.MAX_RECONNECT_ATTEMPTS} attempts). Reload the page or restart the extension to retry.`
251
+ );
252
+ return;
253
+ }
254
+ const baseDelay = this.config.reconnectInterval || 2e3;
255
+ const delay = Math.min(
256
+ baseDelay * Math.pow(2, this.reconnectAttempts),
257
+ _FloTraceWebSocketClient.MAX_RECONNECT_INTERVAL
258
+ );
259
+ this.reconnectAttempts++;
260
+ console.log(
261
+ `[FloTrace] Reconnecting in ${delay}ms (attempt ${this.reconnectAttempts}/${_FloTraceWebSocketClient.MAX_RECONNECT_ATTEMPTS})`
262
+ );
263
+ this.reconnectTimeout = setTimeout(() => {
264
+ this.reconnectTimeout = null;
265
+ this.connect();
266
+ }, delay);
267
+ }
268
+ /**
269
+ * Handle incoming message from extension
270
+ */
271
+ handleMessage(message) {
272
+ for (const handler of this.messageHandlers) {
273
+ try {
274
+ handler(message);
275
+ } catch (error) {
276
+ console.error("[FloTrace] Message handler error:", error);
277
+ }
278
+ }
279
+ }
280
+ /**
281
+ * Notify connection state change
282
+ */
283
+ notifyConnectionChange(connected) {
284
+ for (const handler of this.connectionHandlers) {
285
+ try {
286
+ handler(connected);
287
+ } catch (error) {
288
+ console.error("[FloTrace] Connection handler error:", error);
289
+ }
290
+ }
291
+ }
292
+ /**
293
+ * Add a message handler
294
+ */
295
+ onMessage(handler) {
296
+ this.messageHandlers.add(handler);
297
+ return () => this.messageHandlers.delete(handler);
298
+ }
299
+ /**
300
+ * Add a connection state handler
301
+ */
302
+ onConnectionChange(handler) {
303
+ this.connectionHandlers.add(handler);
304
+ return () => this.connectionHandlers.delete(handler);
305
+ }
306
+ /**
307
+ * Check if connected
308
+ */
309
+ get connected() {
310
+ return this.ws !== null && this.ws.readyState === WebSocket.OPEN;
311
+ }
312
+ /**
313
+ * Get React version if available
314
+ */
315
+ getReactVersion() {
316
+ try {
317
+ if (typeof window !== "undefined") {
318
+ const React2 = window.React;
319
+ return React2?.version;
320
+ }
321
+ } catch {
322
+ }
323
+ return void 0;
324
+ }
325
+ };
326
+ _FloTraceWebSocketClient.MAX_RECONNECT_ATTEMPTS = 10;
327
+ _FloTraceWebSocketClient.MAX_RECONNECT_INTERVAL = 3e4;
328
+ // 30s cap
329
+ _FloTraceWebSocketClient.BATCH_FLUSH_MS = 100;
330
+ // Flush batched messages every 100ms
331
+ _FloTraceWebSocketClient.MAX_QUEUE_SIZE = 500;
332
+ var FloTraceWebSocketClient = _FloTraceWebSocketClient;
333
+ var clientInstance = null;
334
+ function getWebSocketClient(config) {
335
+ if (!clientInstance) {
336
+ clientInstance = new FloTraceWebSocketClient(config);
337
+ }
338
+ return clientInstance;
339
+ }
340
+ function disposeWebSocketClient() {
341
+ if (clientInstance) {
342
+ clientInstance.disconnect();
343
+ clientInstance = null;
344
+ }
345
+ }
346
+
347
+ // src/serializer.ts
348
+ var MAX_DEPTH = 5;
349
+ var MAX_STRING_LENGTH = 500;
350
+ var MAX_ARRAY_LENGTH = 50;
351
+ var MAX_OBJECT_KEYS = 30;
352
+ function serializeValue(value, depth = 0, seen = /* @__PURE__ */ new WeakSet()) {
353
+ if (value === null) {
354
+ return null;
355
+ }
356
+ if (value === void 0) {
357
+ return { __type: "undefined" };
358
+ }
359
+ if (typeof value === "boolean") {
360
+ return value;
361
+ }
362
+ if (typeof value === "number") {
363
+ if (Number.isNaN(value)) return "NaN";
364
+ if (!Number.isFinite(value)) return value > 0 ? "Infinity" : "-Infinity";
365
+ return value;
366
+ }
367
+ if (typeof value === "string") {
368
+ if (value.length > MAX_STRING_LENGTH) {
369
+ return {
370
+ __type: "truncated",
371
+ originalType: "string",
372
+ length: value.length
373
+ };
374
+ }
375
+ return value;
376
+ }
377
+ if (typeof value === "symbol") {
378
+ return {
379
+ __type: "symbol",
380
+ description: value.description
381
+ };
382
+ }
383
+ if (typeof value === "function") {
384
+ return {
385
+ __type: "function",
386
+ name: value.name || "anonymous"
387
+ };
388
+ }
389
+ if (typeof value === "object") {
390
+ if (seen.has(value)) {
391
+ return { __type: "circular" };
392
+ }
393
+ if (depth >= MAX_DEPTH) {
394
+ return {
395
+ __type: "truncated",
396
+ originalType: Array.isArray(value) ? "array" : "object"
397
+ };
398
+ }
399
+ seen.add(value);
400
+ if (Array.isArray(value)) {
401
+ if (value.length > MAX_ARRAY_LENGTH) {
402
+ const truncated = value.slice(0, MAX_ARRAY_LENGTH).map((item) => serializeValue(item, depth + 1, seen));
403
+ return [
404
+ ...truncated,
405
+ {
406
+ __type: "truncated",
407
+ originalType: "array",
408
+ length: value.length
409
+ }
410
+ ];
411
+ }
412
+ return value.map((item) => serializeValue(item, depth + 1, seen));
413
+ }
414
+ if (value instanceof Date) {
415
+ return value.toISOString();
416
+ }
417
+ if (value instanceof Error) {
418
+ return {
419
+ name: value.name,
420
+ message: value.message
421
+ };
422
+ }
423
+ if (value instanceof Map) {
424
+ const obj = {};
425
+ let count = 0;
426
+ for (const [k, v] of value.entries()) {
427
+ if (count >= MAX_OBJECT_KEYS) {
428
+ obj.__truncated = { __type: "truncated", originalType: "Map", length: value.size };
429
+ break;
430
+ }
431
+ obj[String(k)] = serializeValue(v, depth + 1, seen);
432
+ count++;
433
+ }
434
+ return obj;
435
+ }
436
+ if (value instanceof Set) {
437
+ const arr = Array.from(value);
438
+ if (arr.length > MAX_ARRAY_LENGTH) {
439
+ return {
440
+ __type: "truncated",
441
+ originalType: "Set",
442
+ length: arr.length
443
+ };
444
+ }
445
+ return arr.map((item) => serializeValue(item, depth + 1, seen));
446
+ }
447
+ if (value instanceof RegExp) {
448
+ return value.toString();
449
+ }
450
+ const keys = Object.keys(value);
451
+ const result = {};
452
+ for (let i = 0; i < Math.min(keys.length, MAX_OBJECT_KEYS); i++) {
453
+ const key = keys[i];
454
+ try {
455
+ result[key] = serializeValue(
456
+ value[key],
457
+ depth + 1,
458
+ seen
459
+ );
460
+ } catch {
461
+ result[key] = { __type: "truncated", originalType: "error" };
462
+ }
463
+ }
464
+ if (keys.length > MAX_OBJECT_KEYS) {
465
+ result.__truncated = {
466
+ __type: "truncated",
467
+ originalType: "object",
468
+ length: keys.length
469
+ };
470
+ }
471
+ return result;
472
+ }
473
+ return { __type: "truncated", originalType: typeof value };
474
+ }
475
+ function serializeProps(props) {
476
+ const result = {};
477
+ for (const [key, value] of Object.entries(props)) {
478
+ if (key === "children" || key === "key" || key === "ref") {
479
+ continue;
480
+ }
481
+ if (key.startsWith("__")) {
482
+ continue;
483
+ }
484
+ try {
485
+ result[key] = serializeValue(value);
486
+ } catch (error) {
487
+ console.error(`[FloTrace] Error serializing prop "${key}":`, error);
488
+ result[key] = { __type: "truncated", originalType: "error" };
489
+ }
490
+ }
491
+ return result;
492
+ }
493
+ function getChangedKeys(prev, next) {
494
+ if (!prev) {
495
+ return Object.keys(next);
496
+ }
497
+ const changed = [];
498
+ const allKeys = /* @__PURE__ */ new Set([...Object.keys(prev), ...Object.keys(next)]);
499
+ for (const key of allKeys) {
500
+ if (!Object.is(prev[key], next[key])) {
501
+ changed.push(key);
502
+ }
503
+ }
504
+ return changed;
505
+ }
506
+
507
+ // src/fiberConstants.ts
508
+ var HOOK_HAS_EFFECT = 1;
509
+ var HOOK_INSERTION = 2;
510
+ var HOOK_LAYOUT = 4;
511
+ var HOOK_PASSIVE = 8;
512
+ function collectCircularList(lastEffect) {
513
+ const list = [];
514
+ let effect = lastEffect.next;
515
+ if (!effect) return list;
516
+ do {
517
+ list.push(effect);
518
+ effect = effect.next;
519
+ } while (effect && effect !== lastEffect.next);
520
+ return list;
521
+ }
522
+
523
+ // src/hookInspector.ts
524
+ function inspectHooks(fiber) {
525
+ const hooks = [];
526
+ let hookState = fiber.memoizedState;
527
+ const effects = fiber.updateQueue?.lastEffect ? collectCircularList(fiber.updateQueue.lastEffect) : [];
528
+ let effectIndex = 0;
529
+ const debugTypes = fiber._debugHookTypes ?? null;
530
+ let index = 0;
531
+ while (hookState) {
532
+ try {
533
+ const debugLabel = debugTypes?.[index] ?? void 0;
534
+ const hookInfo = classifyHook(hookState, index, effects, effectIndex, debugLabel);
535
+ hooks.push(hookInfo);
536
+ if (hookInfo.type === "useEffect" || hookInfo.type === "useLayoutEffect" || hookInfo.type === "useInsertionEffect") {
537
+ effectIndex++;
538
+ }
539
+ } catch (error) {
540
+ hooks.push({ index, type: "unknown", value: { __type: "truncated", originalType: "error" } });
541
+ }
542
+ hookState = hookState.next;
543
+ index++;
544
+ }
545
+ return hooks;
546
+ }
547
+ function classifyHook(state, index, effects, effectIdx, debugLabel) {
548
+ const ms = state.memoizedState;
549
+ if (debugLabel) {
550
+ return classifyFromDebugLabel(state, index, effects, effectIdx, debugLabel);
551
+ }
552
+ if (state.queue !== null) {
553
+ const queue = state.queue;
554
+ const isReducer = queue.lastRenderedReducer && typeof queue.lastRenderedReducer === "function" && queue.lastRenderedReducer.name !== "" && queue.lastRenderedReducer.name !== "basicStateReducer";
555
+ return {
556
+ index,
557
+ type: isReducer ? "useReducer" : "useState",
558
+ value: serializeValue(ms, 0, /* @__PURE__ */ new WeakSet())
559
+ };
560
+ }
561
+ if (ms !== null && typeof ms === "object" && !Array.isArray(ms) && "current" in ms) {
562
+ const keys = Object.keys(ms);
563
+ if (keys.length === 1 && keys[0] === "current") {
564
+ return {
565
+ index,
566
+ type: "useRef",
567
+ value: serializeValue(ms.current, 0, /* @__PURE__ */ new WeakSet())
568
+ };
569
+ }
570
+ }
571
+ if (Array.isArray(ms) && ms.length === 2 && Array.isArray(ms[1])) {
572
+ const isCallback = typeof ms[0] === "function";
573
+ return {
574
+ index,
575
+ type: isCallback ? "useCallback" : "useMemo",
576
+ value: serializeValue(ms[0], 0, /* @__PURE__ */ new WeakSet()),
577
+ deps: ms[1].map((d) => serializeValue(d, 0, /* @__PURE__ */ new WeakSet()))
578
+ };
579
+ }
580
+ if (effectIdx < effects.length) {
581
+ const effect = effects[effectIdx];
582
+ if (typeof ms === "number" || isEffectShape(ms)) {
583
+ const type = (effect.tag & HOOK_PASSIVE) !== 0 ? "useEffect" : (effect.tag & HOOK_LAYOUT) !== 0 ? "useLayoutEffect" : (effect.tag & HOOK_INSERTION) !== 0 ? "useInsertionEffect" : "useEffect";
584
+ return {
585
+ index,
586
+ type,
587
+ value: { __type: "function", name: "effect" },
588
+ deps: effect.deps ? effect.deps.map((d) => serializeValue(d, 0, /* @__PURE__ */ new WeakSet())) : void 0
589
+ };
590
+ }
591
+ }
592
+ if (Array.isArray(ms) && ms.length === 2 && typeof ms[0] === "boolean" && typeof ms[1] === "function") {
593
+ return {
594
+ index,
595
+ type: "useTransition",
596
+ value: serializeValue(ms[0], 0, /* @__PURE__ */ new WeakSet())
597
+ };
598
+ }
599
+ if (typeof ms === "string" && ms.startsWith(":")) {
600
+ return {
601
+ index,
602
+ type: "useId",
603
+ value: ms
604
+ };
605
+ }
606
+ return { index, type: "unknown", value: serializeValue(ms, 0, /* @__PURE__ */ new WeakSet()) };
607
+ }
608
+ function classifyFromDebugLabel(state, index, effects, effectIdx, debugLabel) {
609
+ const ms = state.memoizedState;
610
+ const normalizedLabel = debugLabel.toLowerCase().replace(/\s/g, "");
611
+ const labelMap = {
612
+ "usestate": "useState",
613
+ "usereducer": "useReducer",
614
+ "useref": "useRef",
615
+ "usememo": "useMemo",
616
+ "usecallback": "useCallback",
617
+ "useeffect": "useEffect",
618
+ "uselayouteffect": "useLayoutEffect",
619
+ "useinsertioneffect": "useInsertionEffect",
620
+ "usecontext": "useContext",
621
+ "useimperativehandle": "useImperativeHandle",
622
+ "usedebugvalue": "useDebugValue",
623
+ "usetransition": "useTransition",
624
+ "usedeferredvalue": "useDeferredValue",
625
+ "useid": "useId",
626
+ "usesyncexternalstore": "useSyncExternalStore",
627
+ "useoptimistic": "useOptimistic",
628
+ "useformstatus": "useFormStatus"
629
+ };
630
+ const hookType = labelMap[normalizedLabel] ?? "unknown";
631
+ const base = { index, type: hookType, value: serializeValue(ms, 0, /* @__PURE__ */ new WeakSet()), debugLabel };
632
+ if (hookType === "useEffect" || hookType === "useLayoutEffect" || hookType === "useInsertionEffect") {
633
+ if (effectIdx < effects.length) {
634
+ const effect = effects[effectIdx];
635
+ base.value = { __type: "function", name: "effect" };
636
+ base.deps = effect.deps ? effect.deps.map((d) => serializeValue(d, 0, /* @__PURE__ */ new WeakSet())) : void 0;
637
+ }
638
+ }
639
+ if ((hookType === "useMemo" || hookType === "useCallback") && Array.isArray(ms) && ms.length === 2 && Array.isArray(ms[1])) {
640
+ base.value = serializeValue(ms[0], 0, /* @__PURE__ */ new WeakSet());
641
+ base.deps = ms[1].map((d) => serializeValue(d, 0, /* @__PURE__ */ new WeakSet()));
642
+ }
643
+ if (hookType === "useRef" && ms !== null && typeof ms === "object" && "current" in ms) {
644
+ base.value = serializeValue(ms.current, 0, /* @__PURE__ */ new WeakSet());
645
+ }
646
+ return base;
647
+ }
648
+ function isEffectShape(ms) {
649
+ if (ms === null || ms === void 0) return false;
650
+ if (typeof ms === "object" && ms !== null) {
651
+ const obj = ms;
652
+ return "tag" in obj && "create" in obj && "deps" in obj;
653
+ }
654
+ return false;
655
+ }
656
+
657
+ // src/effectInspector.ts
658
+ function inspectEffects(fiber) {
659
+ const results = [];
660
+ const lastEffect = fiber.updateQueue?.lastEffect;
661
+ if (!lastEffect) return results;
662
+ const currEffects = collectCircularList(lastEffect);
663
+ const prevEffects = fiber.alternate?.updateQueue?.lastEffect ? collectCircularList(fiber.alternate.updateQueue.lastEffect) : [];
664
+ const hookIndexMap = buildEffectToHookIndexMap(fiber, currEffects);
665
+ for (let i = 0; i < currEffects.length; i++) {
666
+ try {
667
+ const curr = currEffects[i];
668
+ const prev = prevEffects[i] ?? null;
669
+ const type = (curr.tag & HOOK_PASSIVE) !== 0 ? "useEffect" : (curr.tag & HOOK_LAYOUT) !== 0 ? "useLayoutEffect" : (curr.tag & HOOK_INSERTION) !== 0 ? "useInsertionEffect" : "useEffect";
670
+ const willRun = (curr.tag & HOOK_HAS_EFFECT) !== 0;
671
+ const changedDepIndices = diffDeps(prev?.deps ?? null, curr.deps);
672
+ const hasCleanup = typeof curr.destroy === "function";
673
+ results.push({
674
+ index: i,
675
+ hookIndex: hookIndexMap.get(i) ?? -1,
676
+ type,
677
+ deps: serializeDeps(curr.deps),
678
+ prevDeps: prev ? serializeDeps(prev.deps) : null,
679
+ changedDepIndices,
680
+ willRun,
681
+ hasCleanup
682
+ });
683
+ } catch (error) {
684
+ results.push({
685
+ index: i,
686
+ hookIndex: -1,
687
+ type: "useEffect",
688
+ deps: null,
689
+ prevDeps: null,
690
+ changedDepIndices: [],
691
+ willRun: false,
692
+ hasCleanup: false
693
+ });
694
+ }
695
+ }
696
+ return results;
697
+ }
698
+ function buildEffectToHookIndexMap(fiber, effects) {
699
+ const map = /* @__PURE__ */ new Map();
700
+ let hookState = fiber.memoizedState;
701
+ let hookIndex = 0;
702
+ let effectIndex = 0;
703
+ while (hookState && effectIndex < effects.length) {
704
+ const ms = hookState.memoizedState;
705
+ if (isLikelyEffectHook(ms, hookState)) {
706
+ map.set(effectIndex, hookIndex);
707
+ effectIndex++;
708
+ }
709
+ hookState = hookState.next;
710
+ hookIndex++;
711
+ }
712
+ return map;
713
+ }
714
+ function isLikelyEffectHook(ms, state) {
715
+ if (state.queue !== null) return false;
716
+ if (ms !== null && typeof ms === "object") {
717
+ const obj = ms;
718
+ if ("tag" in obj && "create" in obj && "deps" in obj) return true;
719
+ }
720
+ return false;
721
+ }
722
+ function diffDeps(prev, curr) {
723
+ if (!prev || !curr) return [];
724
+ const changed = [];
725
+ const len = Math.max(prev.length, curr.length);
726
+ for (let i = 0; i < len; i++) {
727
+ if (!Object.is(prev[i], curr[i])) {
728
+ changed.push(i);
729
+ }
730
+ }
731
+ return changed;
732
+ }
733
+ function serializeDeps(deps) {
734
+ if (deps === null) return null;
735
+ return deps.map((d) => serializeValue(d, 0, /* @__PURE__ */ new WeakSet()));
736
+ }
737
+
738
+ // src/timelineTracker.ts
739
+ var MAX_EVENTS_PER_COMPONENT = 100;
740
+ var FLUSH_INTERVAL_MS = 500;
741
+ var MAX_PENDING_EVENTS = 200;
742
+ var timelines = /* @__PURE__ */ new Map();
743
+ var pendingEvents = [];
744
+ var client = null;
745
+ var flushTimer = null;
746
+ var isInstalled = false;
747
+ function installTimelineTracker(wsClient) {
748
+ if (isInstalled) return;
749
+ client = wsClient;
750
+ isInstalled = true;
751
+ flushTimer = setInterval(flushPendingEvents, FLUSH_INTERVAL_MS);
752
+ }
753
+ function uninstallTimelineTracker() {
754
+ if (!isInstalled) return;
755
+ if (flushTimer) {
756
+ clearInterval(flushTimer);
757
+ flushTimer = null;
758
+ }
759
+ flushPendingEvents();
760
+ timelines.clear();
761
+ pendingEvents = [];
762
+ client = null;
763
+ isInstalled = false;
764
+ }
765
+ function recordTimelineEvent(nodeId, componentName, eventType, detail, duration) {
766
+ if (!isInstalled) return;
767
+ const event = {
768
+ type: eventType,
769
+ timestamp: Date.now(),
770
+ duration,
771
+ detail: detail !== void 0 ? serializeValue(detail, 0, /* @__PURE__ */ new WeakSet()) : void 0
772
+ };
773
+ let events = timelines.get(nodeId);
774
+ if (!events) {
775
+ events = [];
776
+ timelines.set(nodeId, events);
777
+ }
778
+ events.push(event);
779
+ if (events.length > MAX_EVENTS_PER_COMPONENT) {
780
+ events.shift();
781
+ }
782
+ if (pendingEvents.length < MAX_PENDING_EVENTS) {
783
+ pendingEvents.push({ nodeId, componentName, event });
784
+ }
785
+ }
786
+ function getTimeline(nodeId) {
787
+ return timelines.get(nodeId) ?? [];
788
+ }
789
+ function flushPendingEvents() {
790
+ if (!client?.connected || pendingEvents.length === 0) return;
791
+ for (const { nodeId, componentName, event } of pendingEvents) {
792
+ client.send({
793
+ type: "runtime:timelineEvent",
794
+ nodeId,
795
+ componentName,
796
+ event
797
+ });
798
+ }
799
+ pendingEvents = [];
800
+ }
801
+
802
+ // src/fiberUtils.ts
803
+ function getFiberDisplayName(type) {
804
+ if (!type) return "Unknown";
805
+ if (typeof type === "function") {
806
+ return type.displayName || type.name || "Anonymous";
807
+ }
808
+ if (typeof type === "object") {
809
+ const t = type;
810
+ return t.type?.displayName || t.type?.name || t.render?.name || t.displayName || t.name || "Unknown";
811
+ }
812
+ return "Unknown";
813
+ }
814
+
815
+ // src/dispatchWrapper.ts
816
+ var MAX_TRIGGERS = 200;
817
+ var triggerBuffer = [];
818
+ var triggerSeq = 0;
819
+ var wrappedDispatchers = /* @__PURE__ */ new WeakSet();
820
+ var currentBatchId = null;
821
+ function nextBatchId() {
822
+ if (!currentBatchId) {
823
+ currentBatchId = String(Date.now()) + "-" + (Math.random() * 65535 | 0).toString(16);
824
+ queueMicrotask(() => {
825
+ currentBatchId = null;
826
+ });
827
+ }
828
+ return currentBatchId;
829
+ }
830
+ function nextTriggerId() {
831
+ return "tr-" + (++triggerSeq).toString(36);
832
+ }
833
+ var STACK_DEPTH_LIMIT = 15;
834
+ var NOISE_PATTERNS = [
835
+ "node_modules",
836
+ "react-dom",
837
+ "react-reconciler",
838
+ "@flotrace/runtime",
839
+ "flotrace/runtime",
840
+ "/runtime/src/",
841
+ "webpack-internal",
842
+ "webpack/bootstrap",
843
+ "<anonymous>"
844
+ ];
845
+ function isUserCodeFrame(fileName) {
846
+ if (!fileName) return false;
847
+ for (const pattern of NOISE_PATTERNS) {
848
+ if (fileName.includes(pattern)) return false;
849
+ }
850
+ return true;
851
+ }
852
+ function captureStack() {
853
+ const frames = [];
854
+ try {
855
+ const originalPrepare = Error.prepareStackTrace;
856
+ Error.prepareStackTrace = (_err, callSites) => {
857
+ for (const site of callSites) {
858
+ if (frames.length >= STACK_DEPTH_LIMIT) break;
859
+ const fileName = site.getFileName();
860
+ frames.push({
861
+ functionName: site.getFunctionName() ?? site.getMethodName(),
862
+ fileName,
863
+ lineNumber: site.getLineNumber(),
864
+ columnNumber: site.getColumnNumber(),
865
+ isUserCode: isUserCodeFrame(fileName)
866
+ });
867
+ }
868
+ return "";
869
+ };
870
+ const err = new Error();
871
+ void err.stack;
872
+ Error.prepareStackTrace = originalPrepare;
873
+ } catch {
874
+ try {
875
+ const raw = new Error().stack ?? "";
876
+ const lines = raw.split("\n").slice(1);
877
+ for (const line of lines) {
878
+ if (frames.length >= STACK_DEPTH_LIMIT) break;
879
+ const match = line.match(/^\s+at (?:(.+?) \()?(.+?):(\d+):(\d+)\)?$/);
880
+ if (match) {
881
+ const fileName = match[2] ?? null;
882
+ frames.push({
883
+ functionName: match[1] ?? null,
884
+ fileName,
885
+ lineNumber: match[3] ? parseInt(match[3], 10) : null,
886
+ columnNumber: match[4] ? parseInt(match[4], 10) : null,
887
+ isUserCode: isUserCodeFrame(fileName)
888
+ });
889
+ }
890
+ }
891
+ } catch {
892
+ }
893
+ }
894
+ return frames;
895
+ }
896
+ var FIBER_TAG_FUNCTION = 0;
897
+ var FIBER_TAG_CLASS = 1;
898
+ var FIBER_TAG_FORWARD = 11;
899
+ var FIBER_TAG_MEMO = 14;
900
+ var FIBER_TAG_SIMPLEMEMO = 15;
901
+ function getComponentName(fiber) {
902
+ return getFiberDisplayName(fiber.type);
903
+ }
904
+ function wrapFunctionComponentDispatchers(fiber) {
905
+ let hookNode = fiber.memoizedState;
906
+ let hookIndex = 0;
907
+ while (hookNode && hookIndex < 100) {
908
+ try {
909
+ const queue = hookNode.queue;
910
+ if (queue && typeof queue.dispatch === "function") {
911
+ const original = queue.dispatch;
912
+ if (!wrappedDispatchers.has(original)) {
913
+ const componentName = getComponentName(fiber);
914
+ const fiberId = getFiberId(fiber);
915
+ const capturedHookIndex = hookIndex;
916
+ const hookType = typeof queue.lastRenderedReducer === "function" && queue.lastRenderedReducer?.toString().includes("action") ? "reducer" : "state";
917
+ const wrapped = function dispatchWithCapture(action) {
918
+ try {
919
+ const stack = captureStack();
920
+ const record = {
921
+ triggerId: nextTriggerId(),
922
+ fiberId,
923
+ componentName,
924
+ hookIndex: capturedHookIndex,
925
+ hookType,
926
+ stack,
927
+ timestamp: performance.now(),
928
+ action: serializeValue(action, 2),
929
+ batchId: nextBatchId()
930
+ };
931
+ addTrigger(record);
932
+ } catch {
933
+ }
934
+ return original(action);
935
+ };
936
+ wrappedDispatchers.add(wrapped);
937
+ queue.dispatch = wrapped;
938
+ }
939
+ }
940
+ } catch {
941
+ }
942
+ hookNode = hookNode.next;
943
+ hookIndex++;
944
+ }
945
+ }
946
+ function wrapClassComponentInstance(fiber) {
947
+ const instance = fiber.stateNode;
948
+ if (!instance || instance.__ftWrapped) return;
949
+ const componentName = getComponentName(fiber);
950
+ const fiberId = getFiberId(fiber);
951
+ if (typeof instance.setState === "function") {
952
+ const origSetState = instance.setState;
953
+ instance.setState = function wrappedSetState(updater, callback) {
954
+ try {
955
+ const stack = captureStack();
956
+ addTrigger({
957
+ triggerId: nextTriggerId(),
958
+ fiberId,
959
+ componentName,
960
+ hookIndex: 0,
961
+ hookType: "setState",
962
+ stack,
963
+ timestamp: performance.now(),
964
+ action: serializeValue(updater, 2),
965
+ batchId: nextBatchId()
966
+ });
967
+ } catch {
968
+ }
969
+ return origSetState.call(this, updater, callback);
970
+ };
971
+ }
972
+ if (typeof instance.forceUpdate === "function") {
973
+ const origForceUpdate = instance.forceUpdate;
974
+ instance.forceUpdate = function wrappedForceUpdate(callback) {
975
+ try {
976
+ const stack = captureStack();
977
+ addTrigger({
978
+ triggerId: nextTriggerId(),
979
+ fiberId,
980
+ componentName,
981
+ hookIndex: 0,
982
+ hookType: "forceUpdate",
983
+ stack,
984
+ timestamp: performance.now(),
985
+ action: null,
986
+ batchId: nextBatchId()
987
+ });
988
+ } catch {
989
+ }
990
+ return origForceUpdate.call(this, callback);
991
+ };
992
+ }
993
+ instance.__ftWrapped = true;
994
+ }
995
+ var fiberIds = /* @__PURE__ */ new WeakMap();
996
+ var fiberIdSeq = 0;
997
+ function getFiberId(fiber) {
998
+ let id = fiberIds.get(fiber);
999
+ if (!id) {
1000
+ id = getComponentName(fiber) + "-" + (++fiberIdSeq).toString(36);
1001
+ fiberIds.set(fiber, id);
1002
+ }
1003
+ return id;
1004
+ }
1005
+ function addTrigger(record) {
1006
+ if (triggerBuffer.length >= MAX_TRIGGERS) {
1007
+ triggerBuffer.shift();
1008
+ }
1009
+ triggerBuffer.push(record);
1010
+ }
1011
+ function wrapFiberDispatchers(root) {
1012
+ try {
1013
+ walkAndWrap(root.current);
1014
+ } catch {
1015
+ }
1016
+ }
1017
+ function walkAndWrap(rootFiber) {
1018
+ if (!rootFiber) return;
1019
+ const stack = [rootFiber];
1020
+ while (stack.length > 0) {
1021
+ const fiber = stack.pop();
1022
+ try {
1023
+ const tag = fiber.tag;
1024
+ if (tag === FIBER_TAG_FUNCTION || tag === FIBER_TAG_FORWARD || tag === FIBER_TAG_MEMO || tag === FIBER_TAG_SIMPLEMEMO) {
1025
+ wrapFunctionComponentDispatchers(fiber);
1026
+ } else if (tag === FIBER_TAG_CLASS) {
1027
+ wrapClassComponentInstance(fiber);
1028
+ }
1029
+ } catch {
1030
+ }
1031
+ if (fiber.sibling) stack.push(fiber.sibling);
1032
+ if (fiber.child) stack.push(fiber.child);
1033
+ }
1034
+ }
1035
+ function peekTriggers() {
1036
+ return triggerBuffer;
1037
+ }
1038
+ function clearTriggers() {
1039
+ triggerBuffer.length = 0;
1040
+ }
1041
+
1042
+ // src/laneDetector.ts
1043
+ var SyncHydrationLane = 1;
1044
+ var SyncLane = 2;
1045
+ var InputContinuousHydrationLane = 4;
1046
+ var InputContinuousLane = 8;
1047
+ var DefaultHydrationLane = 16;
1048
+ var DefaultLane = 32;
1049
+ var TransitionLanes = 4194240;
1050
+ var RetryLanes = 62914560;
1051
+ var SelectiveHydrationLane = 67108864;
1052
+ var IdleHydrationLane = 134217728;
1053
+ var IdleLane = 268435456;
1054
+ var OffscreenLane = 536870912;
1055
+ function classifyLanes(lanes) {
1056
+ try {
1057
+ if (lanes & SyncHydrationLane || lanes & SyncLane) {
1058
+ return { priority: "sync", lanes, isTransition: false, isBlocking: true };
1059
+ }
1060
+ if (lanes & InputContinuousHydrationLane || lanes & InputContinuousLane) {
1061
+ return { priority: "discrete", lanes, isTransition: false, isBlocking: true };
1062
+ }
1063
+ if (lanes & DefaultHydrationLane || lanes & DefaultLane) {
1064
+ return { priority: "default", lanes, isTransition: false, isBlocking: false };
1065
+ }
1066
+ if (lanes & TransitionLanes) {
1067
+ return { priority: "transition", lanes, isTransition: true, isBlocking: false };
1068
+ }
1069
+ if (lanes & RetryLanes || lanes & SelectiveHydrationLane) {
1070
+ return { priority: "deferred", lanes, isTransition: false, isBlocking: false };
1071
+ }
1072
+ if (lanes & IdleHydrationLane || lanes & IdleLane) {
1073
+ return { priority: "idle", lanes, isTransition: false, isBlocking: false };
1074
+ }
1075
+ if (lanes & OffscreenLane) {
1076
+ return { priority: "offscreen", lanes, isTransition: false, isBlocking: false };
1077
+ }
1078
+ } catch {
1079
+ }
1080
+ return { priority: "default", lanes, isTransition: false, isBlocking: false };
1081
+ }
1082
+ function getFinishedLanes(root) {
1083
+ try {
1084
+ return root.finishedLanes ?? root.pendingLanes ?? 0;
1085
+ } catch {
1086
+ return 0;
1087
+ }
1088
+ }
1089
+
1090
+ // src/cascadeAnalyzer.ts
1091
+ var PerformedWork = 1;
1092
+ var ForceUpdateFlag = 256;
1093
+ var FunctionComponent = 0;
1094
+ var ClassComponent = 1;
1095
+ var ForwardRef = 11;
1096
+ var MemoComponent = 14;
1097
+ var SimpleMemoComponent = 15;
1098
+ var USER_TAGS = /* @__PURE__ */ new Set([FunctionComponent, ClassComponent, ForwardRef, MemoComponent, SimpleMemoComponent]);
1099
+ function isMemoizedFiber(fiber) {
1100
+ return fiber.tag === MemoComponent || fiber.tag === SimpleMemoComponent;
1101
+ }
1102
+ function propsChanged(prev, next) {
1103
+ if (prev === next) return false;
1104
+ if (!prev || !next) return true;
1105
+ const prevKeys = Object.keys(prev);
1106
+ const nextKeys = Object.keys(next);
1107
+ if (prevKeys.length !== nextKeys.length) return true;
1108
+ for (const key of nextKeys) {
1109
+ if (key === "children") continue;
1110
+ if (prev[key] !== next[key]) return true;
1111
+ }
1112
+ return false;
1113
+ }
1114
+ function getChangedPropKeys(prev, next) {
1115
+ if (!prev || !next) return [];
1116
+ const changed = [];
1117
+ const allKeys = /* @__PURE__ */ new Set([...Object.keys(prev), ...Object.keys(next)]);
1118
+ for (const key of allKeys) {
1119
+ if (key === "children") continue;
1120
+ if (prev[key] !== next[key]) changed.push(key);
1121
+ }
1122
+ return changed;
1123
+ }
1124
+ function hadOwnUpdate(fiber) {
1125
+ try {
1126
+ const uq = fiber.updateQueue;
1127
+ if (!uq) return false;
1128
+ if (uq.shared && uq.shared.pending != null) return true;
1129
+ if (fiber.lanes !== 0) return true;
1130
+ return false;
1131
+ } catch {
1132
+ return false;
1133
+ }
1134
+ }
1135
+ function hadContextUpdate(fiber) {
1136
+ try {
1137
+ return !!fiber.dependencies?.firstContext;
1138
+ } catch {
1139
+ return false;
1140
+ }
1141
+ }
1142
+ function classifyFiber(fiber, didRender, parentRerendered) {
1143
+ if (!didRender) {
1144
+ if (fiber.alternate && isMemoizedFiber(fiber)) return "bailed-out";
1145
+ return null;
1146
+ }
1147
+ if (fiber.flags & ForceUpdateFlag) return "force-update";
1148
+ if (hadContextUpdate(fiber)) return "context-update";
1149
+ if (hadOwnUpdate(fiber)) return "state-update";
1150
+ if (parentRerendered) {
1151
+ const alt = fiber.alternate;
1152
+ if (alt && propsChanged(alt.memoizedProps, fiber.memoizedProps)) {
1153
+ return "props-changed";
1154
+ }
1155
+ return "parent-cascade";
1156
+ }
1157
+ return "state-update";
1158
+ }
1159
+ function computeSubtreeDuration(node) {
1160
+ let total = node.renderDuration;
1161
+ for (const child of node.children) {
1162
+ total += computeSubtreeDuration(child);
1163
+ }
1164
+ node.subtreeDuration = total;
1165
+ return total;
1166
+ }
1167
+ var commitIdSeq = 0;
1168
+ function nextCommitId() {
1169
+ return "c-" + (++commitIdSeq).toString(36) + "-" + (Date.now() % 1e5).toString(36);
1170
+ }
1171
+ function buildCascadeTree(rootFiber, triggers) {
1172
+ const rootCauses = [];
1173
+ let totalComponents = 0;
1174
+ let avoidableCount = 0;
1175
+ let avoidableDuration = 0;
1176
+ const triggerByName = /* @__PURE__ */ new Map();
1177
+ for (const t of triggers) {
1178
+ if (!triggerByName.has(t.componentName)) {
1179
+ triggerByName.set(t.componentName, t);
1180
+ }
1181
+ }
1182
+ const stack = [{
1183
+ fiber: rootFiber,
1184
+ depth: 0,
1185
+ parentRerendered: false,
1186
+ parentNode: null,
1187
+ isRoot: true
1188
+ }];
1189
+ while (stack.length > 0) {
1190
+ const entry = stack.pop();
1191
+ const { fiber, depth, parentRerendered, parentNode, isRoot } = entry;
1192
+ if (!fiber) continue;
1193
+ if (depth > 150) continue;
1194
+ const didRender = !!(fiber.flags & PerformedWork);
1195
+ const isNewMount = !fiber.alternate;
1196
+ if (isNewMount && !didRender) {
1197
+ let child2 = fiber.child;
1198
+ while (child2) {
1199
+ stack.push({ fiber: child2, depth: depth + 1, parentRerendered: false, parentNode, isRoot: false });
1200
+ child2 = child2.sibling;
1201
+ }
1202
+ continue;
1203
+ }
1204
+ if (!USER_TAGS.has(fiber.tag)) {
1205
+ let child2 = fiber.child;
1206
+ while (child2) {
1207
+ stack.push({ fiber: child2, depth: depth + 1, parentRerendered: didRender || parentRerendered, parentNode, isRoot: false });
1208
+ child2 = child2.sibling;
1209
+ }
1210
+ continue;
1211
+ }
1212
+ const reason = classifyFiber(fiber, didRender, parentRerendered);
1213
+ if (reason === null) {
1214
+ let child2 = fiber.child;
1215
+ while (child2) {
1216
+ stack.push({ fiber: child2, depth: depth + 1, parentRerendered: false, parentNode, isRoot: false });
1217
+ child2 = child2.sibling;
1218
+ }
1219
+ continue;
1220
+ }
1221
+ const componentName = getFiberDisplayName(fiber.type);
1222
+ const renderDuration = fiber.actualDuration ?? 0;
1223
+ let changedProps;
1224
+ if (reason === "props-changed" && fiber.alternate) {
1225
+ changedProps = getChangedPropKeys(fiber.alternate.memoizedProps, fiber.memoizedProps);
1226
+ }
1227
+ let triggerId;
1228
+ if (reason === "state-update" || reason === "context-update" || reason === "force-update") {
1229
+ triggerId = triggerByName.get(componentName)?.triggerId;
1230
+ }
1231
+ const node = {
1232
+ nodeId: componentName + "-" + depth + "-" + totalComponents,
1233
+ componentName,
1234
+ reason,
1235
+ renderDuration,
1236
+ subtreeDuration: renderDuration,
1237
+ // will be updated from children
1238
+ changedProps,
1239
+ triggerId,
1240
+ children: [],
1241
+ depth,
1242
+ isMemoized: isMemoizedFiber(fiber)
1243
+ };
1244
+ totalComponents++;
1245
+ if (reason === "parent-cascade") {
1246
+ avoidableCount++;
1247
+ avoidableDuration += renderDuration;
1248
+ }
1249
+ if (parentNode) {
1250
+ parentNode.children.push(node);
1251
+ } else if (reason === "state-update" || reason === "context-update" || reason === "force-update" || isRoot) {
1252
+ rootCauses.push(node);
1253
+ } else if (parentRerendered) {
1254
+ rootCauses.push(node);
1255
+ }
1256
+ let child = fiber.child;
1257
+ while (child) {
1258
+ stack.push({
1259
+ fiber: child,
1260
+ depth: depth + 1,
1261
+ parentRerendered: didRender,
1262
+ parentNode: reason !== "bailed-out" ? node : parentNode,
1263
+ isRoot: false
1264
+ });
1265
+ child = child.sibling;
1266
+ }
1267
+ }
1268
+ for (const root of rootCauses) computeSubtreeDuration(root);
1269
+ return { rootCauses, totalComponents, avoidableCount, avoidableDuration };
1270
+ }
1271
+ function analyzeCascade(root, triggers) {
1272
+ try {
1273
+ const finishedLanes = getFinishedLanes(root);
1274
+ const lane = classifyLanes(finishedLanes);
1275
+ const { rootCauses, totalComponents, avoidableCount, avoidableDuration } = buildCascadeTree(root.current, triggers);
1276
+ if (totalComponents === 0) return null;
1277
+ const totalDuration = rootCauses.reduce((sum, n) => sum + n.subtreeDuration, 0);
1278
+ const triggerIds = triggers.map((t) => t.triggerId);
1279
+ return {
1280
+ commitId: nextCommitId(),
1281
+ timestamp: performance.now(),
1282
+ totalDuration,
1283
+ totalComponents,
1284
+ avoidableCount,
1285
+ avoidableDuration,
1286
+ rootCauses,
1287
+ lane,
1288
+ triggerIds
1289
+ };
1290
+ } catch {
1291
+ return null;
1292
+ }
1293
+ }
1294
+
1295
+ // src/propDrillingAnalyzer.ts
1296
+ var ANALYZE_INTERVAL_MS = 2e3;
1297
+ var DRILLING_THRESHOLD = 3;
1298
+ var EXCLUDED_PROP_NAMES = /* @__PURE__ */ new Set([
1299
+ // React internals
1300
+ "children",
1301
+ "key",
1302
+ "ref",
1303
+ // Common HTML attributes
1304
+ "className",
1305
+ "style",
1306
+ "id",
1307
+ "name",
1308
+ "type",
1309
+ "value",
1310
+ "placeholder",
1311
+ "disabled",
1312
+ "readOnly",
1313
+ "required",
1314
+ "autoFocus",
1315
+ "tabIndex",
1316
+ "role",
1317
+ "aria-label",
1318
+ "aria-describedby",
1319
+ "aria-hidden",
1320
+ "title",
1321
+ "lang",
1322
+ "dir",
1323
+ "hidden",
1324
+ // Common layout props
1325
+ "width",
1326
+ "height",
1327
+ "size",
1328
+ "variant",
1329
+ "color",
1330
+ "theme",
1331
+ // Test IDs
1332
+ "data-testid",
1333
+ "testID"
1334
+ ]);
1335
+ function isExcluded(propName) {
1336
+ return EXCLUDED_PROP_NAMES.has(propName) || propName.startsWith("on");
1337
+ }
1338
+ var analyzeTimer = null;
1339
+ var lastAnalysisTime = 0;
1340
+ function valueFingerprint(value, depth = 0) {
1341
+ if (depth > 3) return "__deep__";
1342
+ if (value === null || value === void 0) return "null";
1343
+ if (typeof value === "function") return `fn:${value.name || "anon"}`;
1344
+ if (typeof value !== "object") return `${typeof value}:${String(value)}`;
1345
+ if (Array.isArray(value)) {
1346
+ const arr = value;
1347
+ return `arr:${arr.length}:${arr.slice(0, 5).map((v) => valueFingerprint(v, depth + 1)).join(",")}`;
1348
+ }
1349
+ const obj = value;
1350
+ const keys = Object.keys(obj).sort();
1351
+ return `obj:${keys.slice(0, 10).map((k) => `${k}=${valueFingerprint(obj[k], depth + 1)}`).join(",")}`;
1352
+ }
1353
+ function shouldFlagRename(value) {
1354
+ if (value === null || value === void 0) return false;
1355
+ if (typeof value !== "object") return false;
1356
+ if (Array.isArray(value) && value.length === 0) return false;
1357
+ if (!Array.isArray(value) && Object.keys(value).length === 0) return false;
1358
+ return true;
1359
+ }
1360
+ function computePropIntersectionRatio(nodeProps, childrenProps) {
1361
+ const nodeKeys = Object.keys(nodeProps).filter((k) => !isExcluded(k));
1362
+ if (nodeKeys.length === 0) return 0;
1363
+ let forwarded = 0;
1364
+ for (const key of nodeKeys) {
1365
+ const fp = valueFingerprint(nodeProps[key]);
1366
+ const isForwarded = childrenProps.some(
1367
+ (cp) => Object.values(cp).some((v) => valueFingerprint(v) === fp)
1368
+ );
1369
+ if (isForwarded) forwarded++;
1370
+ }
1371
+ return forwarded / nodeKeys.length;
1372
+ }
1373
+ function classifyNode(nodeId, drilledPropFp, parentNodeId, childNodeIds, getProps, hookCounts, contextFlags) {
1374
+ if (!parentNodeId) return "source";
1375
+ const parentProps = getProps(parentNodeId);
1376
+ const parentHasProp = Object.values(parentProps).some(
1377
+ (v) => valueFingerprint(v) === drilledPropFp
1378
+ );
1379
+ if (!parentHasProp) return "source";
1380
+ const forwardsToChild = childNodeIds.some((cid) => {
1381
+ const childProps = getProps(cid);
1382
+ return Object.values(childProps).some((v) => valueFingerprint(v) === drilledPropFp);
1383
+ });
1384
+ if (!forwardsToChild) return "consumer";
1385
+ const hookCount = hookCounts.get(nodeId) ?? 0;
1386
+ const hasContext = contextFlags.get(nodeId) ?? false;
1387
+ if (hookCount === 0) return "passthrough";
1388
+ if (hasContext) return "consumer";
1389
+ const nodeProps = getProps(nodeId);
1390
+ const childrenProps = childNodeIds.map(getProps);
1391
+ const intersectionRatio = computePropIntersectionRatio(nodeProps, childrenProps);
1392
+ if (intersectionRatio > 0.7 && hookCount <= 1) return "passthrough";
1393
+ return "consumer";
1394
+ }
1395
+ function calculateSeverity(depth, passthroughCount, consumerCount) {
1396
+ if (depth >= 5) return "critical";
1397
+ if (passthroughCount >= 3) return "critical";
1398
+ if (consumerCount >= 3 && depth >= 4) return "critical";
1399
+ if (depth >= 4) return "warning";
1400
+ if (passthroughCount >= 2) return "warning";
1401
+ if (consumerCount >= 2) return "warning";
1402
+ return "info";
1403
+ }
1404
+ function makeChainId(sourceNodeId, fp, consumerNodeId) {
1405
+ return `${sourceNodeId}::${fp.slice(0, 20)}::${consumerNodeId}`;
1406
+ }
1407
+ function flattenTree(node, parentId, parentMap, childrenMap, nodeMap) {
1408
+ if (node.isFramework) {
1409
+ for (const child of node.children) {
1410
+ flattenTree(child, parentId, parentMap, childrenMap, nodeMap);
1411
+ }
1412
+ return;
1413
+ }
1414
+ nodeMap.set(node.id, node);
1415
+ if (parentId) {
1416
+ parentMap.set(node.id, parentId);
1417
+ const siblings = childrenMap.get(parentId) ?? [];
1418
+ siblings.push(node.id);
1419
+ childrenMap.set(parentId, siblings);
1420
+ }
1421
+ if (!childrenMap.has(node.id)) {
1422
+ childrenMap.set(node.id, []);
1423
+ }
1424
+ for (const child of node.children) {
1425
+ flattenTree(child, node.id, parentMap, childrenMap, nodeMap);
1426
+ }
1427
+ }
1428
+ function runAnalysis(tree, fiberRefMap2) {
1429
+ const parentMap = /* @__PURE__ */ new Map();
1430
+ const childrenMap = /* @__PURE__ */ new Map();
1431
+ const nodeMap = /* @__PURE__ */ new Map();
1432
+ flattenTree(tree, void 0, parentMap, childrenMap, nodeMap);
1433
+ const allNodeIds = Array.from(nodeMap.keys());
1434
+ function getProps(nodeId) {
1435
+ try {
1436
+ return fiberRefMap2.get(nodeId)?.memoizedProps ?? {};
1437
+ } catch {
1438
+ return {};
1439
+ }
1440
+ }
1441
+ const hookCounts = /* @__PURE__ */ new Map();
1442
+ const contextFlags = /* @__PURE__ */ new Map();
1443
+ for (const nodeId of allNodeIds) {
1444
+ const node = nodeMap.get(nodeId);
1445
+ hookCounts.set(nodeId, node.hookCount ?? 0);
1446
+ contextFlags.set(nodeId, node.hasContextHook ?? false);
1447
+ }
1448
+ const edges = [];
1449
+ for (const nodeId of allNodeIds) {
1450
+ const parentId = parentMap.get(nodeId);
1451
+ if (!parentId) continue;
1452
+ const parentProps = getProps(parentId);
1453
+ const childProps = getProps(nodeId);
1454
+ const childKeys = Object.keys(childProps).filter((k) => !isExcluded(k));
1455
+ const parentKeys = Object.keys(parentProps).filter((k) => !isExcluded(k));
1456
+ for (const childKey of childKeys) {
1457
+ const childVal = childProps[childKey];
1458
+ if (typeof childVal === "function") continue;
1459
+ const childFp = valueFingerprint(childVal);
1460
+ if (childFp === "null") continue;
1461
+ for (const parentKey of parentKeys) {
1462
+ const parentVal = parentProps[parentKey];
1463
+ if (typeof parentVal === "function") continue;
1464
+ const parentFp = valueFingerprint(parentVal);
1465
+ if (parentFp === childFp) {
1466
+ const isRename = parentKey !== childKey;
1467
+ if (!isRename || shouldFlagRename(parentVal)) {
1468
+ edges.push({
1469
+ parentNodeId: parentId,
1470
+ childNodeId: nodeId,
1471
+ propKey: parentKey,
1472
+ childPropKey: childKey,
1473
+ fp: childFp
1474
+ });
1475
+ break;
1476
+ }
1477
+ }
1478
+ }
1479
+ }
1480
+ }
1481
+ const edgesByFp = /* @__PURE__ */ new Map();
1482
+ for (const edge of edges) {
1483
+ const group = edgesByFp.get(edge.fp) ?? [];
1484
+ group.push(edge);
1485
+ edgesByFp.set(edge.fp, group);
1486
+ }
1487
+ const chains = [];
1488
+ const passthroughNodeIdSet = /* @__PURE__ */ new Set();
1489
+ for (const [fp, fpEdges] of edgesByFp) {
1490
+ const outEdges = /* @__PURE__ */ new Map();
1491
+ const inNodes = /* @__PURE__ */ new Set();
1492
+ for (const edge of fpEdges) {
1493
+ const out = outEdges.get(edge.parentNodeId) ?? [];
1494
+ out.push(edge);
1495
+ outEdges.set(edge.parentNodeId, out);
1496
+ inNodes.add(edge.childNodeId);
1497
+ }
1498
+ const sourceNodeIds = /* @__PURE__ */ new Set();
1499
+ for (const edge of fpEdges) {
1500
+ if (!inNodes.has(edge.parentNodeId)) {
1501
+ sourceNodeIds.add(edge.parentNodeId);
1502
+ }
1503
+ }
1504
+ for (const sourceId of sourceNodeIds) {
1505
+ let dfs2 = function(currentId, currentPropKey, currentPath, visited) {
1506
+ if (visited.has(currentId)) return;
1507
+ visited.add(currentId);
1508
+ const outgoing = outEdges.get(currentId);
1509
+ if (!outgoing || outgoing.length === 0) {
1510
+ if (currentPath.length >= DRILLING_THRESHOLD) {
1511
+ allPaths.push([...currentPath]);
1512
+ }
1513
+ visited.delete(currentId);
1514
+ return;
1515
+ }
1516
+ for (const edge of outgoing) {
1517
+ const isRename = edge.propKey !== edge.childPropKey;
1518
+ dfs2(
1519
+ edge.childNodeId,
1520
+ edge.childPropKey,
1521
+ [...currentPath, { nodeId: edge.childNodeId, propKey: edge.childPropKey, isRename }],
1522
+ new Set(visited)
1523
+ );
1524
+ }
1525
+ visited.delete(currentId);
1526
+ };
1527
+ var dfs = dfs2;
1528
+ const firstEdge = outEdges.get(sourceId)?.[0];
1529
+ if (!firstEdge) continue;
1530
+ const sourcePropName = firstEdge.propKey;
1531
+ const allPaths = [];
1532
+ dfs2(
1533
+ sourceId,
1534
+ sourcePropName,
1535
+ [{ nodeId: sourceId, propKey: sourcePropName, isRename: false }],
1536
+ /* @__PURE__ */ new Set()
1537
+ );
1538
+ if (allPaths.length === 0) continue;
1539
+ for (const path of allPaths) {
1540
+ if (path.length < DRILLING_THRESHOLD) continue;
1541
+ const consumerNodeId = path[path.length - 1].nodeId;
1542
+ const consumerNode = nodeMap.get(consumerNodeId);
1543
+ if (!consumerNode) continue;
1544
+ const chainNodes = path.map((p, i) => {
1545
+ const parentIdForNode = i === 0 ? void 0 : path[i - 1].nodeId;
1546
+ const childNodeIds = i < path.length - 1 ? [path[i + 1].nodeId] : [];
1547
+ const role = classifyNode(
1548
+ p.nodeId,
1549
+ fp,
1550
+ parentIdForNode,
1551
+ childNodeIds,
1552
+ getProps,
1553
+ hookCounts,
1554
+ contextFlags
1555
+ );
1556
+ if (role === "passthrough") {
1557
+ passthroughNodeIdSet.add(p.nodeId);
1558
+ }
1559
+ const n = nodeMap.get(p.nodeId);
1560
+ return {
1561
+ nodeId: p.nodeId,
1562
+ componentName: n?.name ?? p.nodeId,
1563
+ propKey: p.propKey,
1564
+ role,
1565
+ hookCount: hookCounts.get(p.nodeId) ?? 0,
1566
+ hasContextHook: contextFlags.get(p.nodeId) ?? false
1567
+ };
1568
+ });
1569
+ const passthroughCount = chainNodes.filter((n) => n.role === "passthrough").length;
1570
+ const sourceNode = nodeMap.get(sourceId);
1571
+ const renames = path.flatMap(
1572
+ (p, idx) => p.isRename ? [{ atNodeId: p.nodeId, fromKey: idx > 0 ? path[idx - 1].propKey : sourcePropName, toKey: p.propKey }] : []
1573
+ );
1574
+ chains.push({
1575
+ chainId: makeChainId(sourceId, fp, consumerNodeId),
1576
+ propName: sourcePropName,
1577
+ sourceNodeId: sourceId,
1578
+ sourceComponentName: sourceNode?.name ?? sourceId,
1579
+ consumerNodeIds: [consumerNodeId],
1580
+ consumerComponentNames: [consumerNode.name],
1581
+ path: chainNodes,
1582
+ depth: path.length,
1583
+ passthroughCount,
1584
+ severity: calculateSeverity(path.length, passthroughCount, 1),
1585
+ renames
1586
+ });
1587
+ }
1588
+ }
1589
+ }
1590
+ const seen = /* @__PURE__ */ new Set();
1591
+ const dedupedChains = chains.filter((c) => {
1592
+ if (seen.has(c.chainId)) return false;
1593
+ seen.add(c.chainId);
1594
+ return true;
1595
+ });
1596
+ const severityOrder = { critical: 0, warning: 1, info: 2 };
1597
+ dedupedChains.sort((a, b) => {
1598
+ const s = severityOrder[a.severity] - severityOrder[b.severity];
1599
+ if (s !== 0) return s;
1600
+ return b.depth - a.depth;
1601
+ });
1602
+ return {
1603
+ chains: dedupedChains.slice(0, 50),
1604
+ // cap at 50 chains
1605
+ passthroughNodeIds: Array.from(passthroughNodeIdSet)
1606
+ };
1607
+ }
1608
+ function schedulePropDrillingAnalysis(tree, fiberRefMap2, client4) {
1609
+ if (analyzeTimer) clearTimeout(analyzeTimer);
1610
+ const now = Date.now();
1611
+ const elapsed = now - lastAnalysisTime;
1612
+ const delay = elapsed >= ANALYZE_INTERVAL_MS ? 0 : ANALYZE_INTERVAL_MS - elapsed;
1613
+ analyzeTimer = setTimeout(() => {
1614
+ analyzeTimer = null;
1615
+ if (!client4.connected) return;
1616
+ try {
1617
+ lastAnalysisTime = Date.now();
1618
+ const { chains, passthroughNodeIds } = runAnalysis(tree, fiberRefMap2);
1619
+ client4.sendImmediate({
1620
+ type: "runtime:propDrilling",
1621
+ payload: {
1622
+ chains,
1623
+ passthroughNodeIds,
1624
+ analysisTimestamp: lastAnalysisTime,
1625
+ treeSize: fiberRefMap2.size
1626
+ }
1627
+ });
1628
+ } catch (err) {
1629
+ if (typeof console !== "undefined") {
1630
+ console.warn("[FloTrace] Prop drilling analysis error:", err);
1631
+ }
1632
+ }
1633
+ }, delay);
1634
+ }
1635
+
1636
+ // src/compilerAnalyzer.ts
1637
+ var MEMO_CACHE_SENTINEL = /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel");
1638
+ var FUNCTION_COMPONENT = 0;
1639
+ var SIMPLE_MEMO = 15;
1640
+ function detectCompilerStatus(fiber) {
1641
+ if (fiber.tag === SIMPLE_MEMO) return "manual";
1642
+ if (fiber.tag !== FUNCTION_COMPONENT) return void 0;
1643
+ const firstHook = fiber.memoizedState;
1644
+ if (!firstHook) return "unoptimized";
1645
+ const cache = firstHook.memoizedState;
1646
+ if (!Array.isArray(cache) || cache.length === 0) return "unoptimized";
1647
+ const hasSentinel = cache.some((v) => v === MEMO_CACHE_SENTINEL);
1648
+ if (!hasSentinel) return "unoptimized";
1649
+ const allSentinel = cache.every((v) => v === MEMO_CACHE_SENTINEL);
1650
+ if (allSentinel && fiber.alternate != null) return "de-opted";
1651
+ return "compiled";
1652
+ }
1653
+
1654
+ // src/nextjsDetector.ts
1655
+ var SERVER_COMPONENT_PATTERNS = [
1656
+ /\.server\.[jt]sx?$/,
1657
+ // explicit .server.tsx convention
1658
+ /[\\/]app[\\/].+[\\/]page\.[jt]sx?$/,
1659
+ // Next.js app router page
1660
+ /[\\/]app[\\/].+[\\/]layout\.[jt]sx?$/,
1661
+ // Next.js app router layout
1662
+ /[\\/]app[\\/].+[\\/]loading\.[jt]sx?$/,
1663
+ // Next.js loading UI
1664
+ /[\\/]app[\\/].+[\\/]error\.[jt]sx?$/
1665
+ // Next.js error UI
1666
+ ];
1667
+ var SERVER_REFERENCE_PATTERNS = [
1668
+ /_ServerReference$/,
1669
+ /^RSC_/
1670
+ ];
1671
+ var detectionEmitted = false;
1672
+ function maybeEmitNextjsContext(client4) {
1673
+ if (detectionEmitted) return;
1674
+ try {
1675
+ const win = globalThis;
1676
+ const hasNextData = "__NEXT_DATA__" in win;
1677
+ const hasNextRouter = "__next_router_state_tree__" in win;
1678
+ const hasNext = "next" in win && win.next !== null;
1679
+ if (!hasNextData && !hasNextRouter && !hasNext) return;
1680
+ detectionEmitted = true;
1681
+ let version;
1682
+ let isAppRouter = false;
1683
+ let initialRoute;
1684
+ try {
1685
+ const nextData = win.__NEXT_DATA__;
1686
+ if (nextData) {
1687
+ version = typeof nextData.buildId === "string" ? nextData.buildId : void 0;
1688
+ initialRoute = typeof nextData.page === "string" ? nextData.page : void 0;
1689
+ }
1690
+ isAppRouter = hasNextRouter || !!win.__next_router_state_tree__;
1691
+ } catch {
1692
+ }
1693
+ client4.sendImmediate({
1694
+ type: "runtime:nextjsContext",
1695
+ detected: true,
1696
+ version,
1697
+ isAppRouter,
1698
+ initialRoute,
1699
+ timestamp: Date.now()
1700
+ });
1701
+ } catch {
1702
+ }
1703
+ }
1704
+ function detectServerComponent(fiber) {
1705
+ const type = fiber.type;
1706
+ if (type) {
1707
+ const name = type.displayName || type.name || "";
1708
+ if (SERVER_REFERENCE_PATTERNS.some((p) => p.test(name))) return true;
1709
+ }
1710
+ const fileName = fiber._debugSource?.fileName;
1711
+ if (fileName) {
1712
+ if (SERVER_COMPONENT_PATTERNS.some((p) => p.test(fileName))) return true;
1713
+ }
1714
+ return false;
1715
+ }
1716
+ function resetNextjsDetection() {
1717
+ detectionEmitted = false;
1718
+ }
1719
+
1720
+ // src/actionStateTracker.ts
1721
+ var prevActionStateMap = /* @__PURE__ */ new Map();
1722
+ var ACTION_STATE_HOOK_NAMES = /* @__PURE__ */ new Set(["useActionState"]);
1723
+ var OPTIMISTIC_HOOK_NAMES = /* @__PURE__ */ new Set(["useOptimistic"]);
1724
+ function extractActionEntries(fiber) {
1725
+ const hookTypes = fiber._debugHookTypes;
1726
+ if (!hookTypes) return null;
1727
+ const entries = [];
1728
+ let hookState = fiber.memoizedState;
1729
+ let hookIdx = 0;
1730
+ for (const hookType of hookTypes) {
1731
+ if (!hookState) break;
1732
+ if (ACTION_STATE_HOOK_NAMES.has(hookType)) {
1733
+ const ms = hookState.memoizedState;
1734
+ if (Array.isArray(ms) && ms.length >= 3) {
1735
+ entries.push({
1736
+ hookIndex: hookIdx,
1737
+ hookKind: "action",
1738
+ isPending: ms[2] === true,
1739
+ state: serializeValue(ms[0])
1740
+ });
1741
+ }
1742
+ } else if (OPTIMISTIC_HOOK_NAMES.has(hookType)) {
1743
+ const ms = hookState.memoizedState;
1744
+ if (Array.isArray(ms)) {
1745
+ entries.push({
1746
+ hookIndex: hookIdx,
1747
+ hookKind: "optimistic",
1748
+ isPending: false,
1749
+ // optimistic values are "immediately applied"
1750
+ state: serializeValue(ms[0])
1751
+ });
1752
+ }
1753
+ }
1754
+ hookState = hookState.next;
1755
+ hookIdx++;
1756
+ }
1757
+ return entries.length > 0 ? entries : null;
1758
+ }
1759
+ function scanActionStateChanges(fiberRefMap2, client4) {
1760
+ try {
1761
+ for (const [nodeId, fiber] of fiberRefMap2) {
1762
+ const entries = extractActionEntries(fiber);
1763
+ if (!entries) continue;
1764
+ const snapshot = JSON.stringify(entries.map((e) => ({ i: e.hookIndex, p: e.isPending, s: e.state })));
1765
+ if (prevActionStateMap.get(nodeId) === snapshot) continue;
1766
+ prevActionStateMap.set(nodeId, snapshot);
1767
+ const componentName = nodeId.split("/").pop()?.replace(/-\d+$/, "") ?? "Unknown";
1768
+ client4.send({
1769
+ type: "runtime:actionState",
1770
+ nodeId,
1771
+ componentName,
1772
+ actions: entries,
1773
+ timestamp: Date.now()
1774
+ });
1775
+ }
1776
+ } catch {
1777
+ }
1778
+ }
1779
+ function clearActionStateCache() {
1780
+ prevActionStateMap.clear();
1781
+ }
1782
+
1783
+ // src/rscPayloadInterceptor.ts
1784
+ var RSC_URL_PATTERNS = [
1785
+ /\?_rsc=/,
1786
+ // App Router RSC param
1787
+ /\?__RSC__=/,
1788
+ // Older Next.js RSC param
1789
+ /\/_next\/data\//,
1790
+ // Pages Router getServerSideProps / getStaticProps
1791
+ /\/__nextjs_original-stack-frame/
1792
+ ];
1793
+ function parseCacheStatus(headers) {
1794
+ const raw = headers.get("x-nextjs-cache") || headers.get("x-vercel-cache") || "";
1795
+ switch (raw.toUpperCase()) {
1796
+ case "HIT":
1797
+ return "HIT";
1798
+ case "MISS":
1799
+ return "MISS";
1800
+ case "STALE":
1801
+ return "STALE";
1802
+ default:
1803
+ return "unknown";
1804
+ }
1805
+ }
1806
+ function extractRoute(url) {
1807
+ try {
1808
+ const u = new URL(url, globalThis.location?.href ?? "http://localhost");
1809
+ return u.pathname;
1810
+ } catch {
1811
+ return url.split("?")[0] ?? url;
1812
+ }
1813
+ }
1814
+ var originalFetch = null;
1815
+ var interceptorClient = null;
1816
+ var isInstalled2 = false;
1817
+ function installRscPayloadInterceptor(client4) {
1818
+ if (isInstalled2 || typeof globalThis.fetch !== "function") return;
1819
+ isInstalled2 = true;
1820
+ interceptorClient = client4;
1821
+ originalFetch = globalThis.fetch;
1822
+ globalThis.fetch = async function patchedFetch(input, init) {
1823
+ const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
1824
+ const isRscRequest = RSC_URL_PATTERNS.some((p) => p.test(url));
1825
+ const response = await originalFetch.call(globalThis, input, init);
1826
+ if (isRscRequest && interceptorClient?.connected) {
1827
+ try {
1828
+ const sizeHeader = response.headers.get("content-length");
1829
+ const payloadSizeBytes = sizeHeader ? parseInt(sizeHeader, 10) : 0;
1830
+ interceptorClient.send({
1831
+ type: "runtime:rscPayload",
1832
+ route: extractRoute(url),
1833
+ payloadSizeBytes: isNaN(payloadSizeBytes) ? 0 : payloadSizeBytes,
1834
+ cacheStatus: parseCacheStatus(response.headers),
1835
+ timestamp: Date.now()
1836
+ });
1837
+ } catch {
1838
+ }
1839
+ }
1840
+ return response;
1841
+ };
1842
+ }
1843
+ function uninstallRscPayloadInterceptor() {
1844
+ if (!isInstalled2 || !originalFetch) return;
1845
+ globalThis.fetch = originalFetch;
1846
+ originalFetch = null;
1847
+ interceptorClient = null;
1848
+ isInstalled2 = false;
1849
+ }
1850
+
1851
+ // src/fiberAttribution.ts
1852
+ function isFiberLike(val) {
1853
+ if (!val || typeof val !== "object") return false;
1854
+ const obj = val;
1855
+ return typeof obj.tag === "number" && "type" in obj && "return" in obj && ("memoizedState" in obj || "stateNode" in obj);
1856
+ }
1857
+ function getCurrentRenderingFiber() {
1858
+ try {
1859
+ const win = window;
1860
+ const secret = win.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
1861
+ if (secret?.ReactCurrentOwner?.current) return secret.ReactCurrentOwner.current;
1862
+ const client4 = win.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;
1863
+ if (client4) {
1864
+ for (const val of Object.values(client4)) {
1865
+ if (isFiberLike(val)) return val;
1866
+ }
1867
+ }
1868
+ return null;
1869
+ } catch {
1870
+ return null;
1871
+ }
1872
+ }
1873
+ function getComponentNameFromFiber(fiber) {
1874
+ const type = fiber.type;
1875
+ if (!type) return null;
1876
+ if (typeof type === "function") {
1877
+ return type.displayName || type.name || null;
1878
+ }
1879
+ if (typeof type === "object" && type !== null) {
1880
+ if (type.type) {
1881
+ return type.type.displayName || type.type.name || null;
1882
+ }
1883
+ if (type.render) {
1884
+ return type.render.displayName || type.render.name || null;
1885
+ }
1886
+ return type.displayName || type.name || null;
1887
+ }
1888
+ return null;
1889
+ }
1890
+ function buildAncestorChain(fiber) {
1891
+ const chain = [];
1892
+ let current = fiber;
1893
+ const maxDepth = 10;
1894
+ while (current && chain.length < maxDepth) {
1895
+ const name = getComponentNameFromFiber(current);
1896
+ if (name) {
1897
+ chain.unshift(name);
1898
+ }
1899
+ current = current.return;
1900
+ }
1901
+ return chain;
1902
+ }
1903
+
1904
+ // src/networkTracker.ts
1905
+ var MAX_BATCH_SIZE = 50;
1906
+ var FLUSH_INTERVAL_MS2 = 500;
1907
+ var MAX_BUFFER_SIZE = 300;
1908
+ var DEDUPE_WINDOW_MS = 5e3;
1909
+ var MAX_ANCESTOR_CHAIN = 3;
1910
+ var NOISE_URL_PATTERNS = [
1911
+ // Analytics & tracking
1912
+ /google-analytics\.com/i,
1913
+ /googletagmanager\.com/i,
1914
+ /facebook\.com\/tr/i,
1915
+ /segment\.io/i,
1916
+ /mixpanel\.com/i,
1917
+ /amplitude\.com/i,
1918
+ /hotjar\.com/i,
1919
+ /fullstory\.com/i,
1920
+ /sentry\.io/i,
1921
+ /bugsnag\.com/i,
1922
+ /datadog/i,
1923
+ /clarity\.ms/i,
1924
+ /plausible\.io/i,
1925
+ // Development tools
1926
+ /webpack-dev-server/i,
1927
+ /__webpack_hmr/i,
1928
+ /\.hot-update\./i,
1929
+ /\.map$/,
1930
+ /sourcemap/i,
1931
+ /__nextjs_original-stack-frame/i,
1932
+ /__nextjs_launch-editor/i,
1933
+ /on-demand-entries-ping/i,
1934
+ // Browser resources
1935
+ /favicon\.ico/i,
1936
+ /robots\.txt/i,
1937
+ /manifest\.json/i,
1938
+ /service-worker/i,
1939
+ /sw\.js/i,
1940
+ // Static assets
1941
+ /\/_next\/static\//i,
1942
+ /\/_next\/image/i,
1943
+ // FloTrace's own WebSocket
1944
+ /127\.0\.0\.1:3457/,
1945
+ // Chrome extensions
1946
+ /chrome-extension:/i,
1947
+ /moz-extension:/i
1948
+ ];
1949
+ var client2 = null;
1950
+ var isInstalled3 = false;
1951
+ var isPrewarmed = false;
1952
+ var buffer = [];
1953
+ var earlyBuffer = [];
1954
+ var flushTimer2 = null;
1955
+ var requestCounter = 0;
1956
+ var requestIndexMap = /* @__PURE__ */ new Map();
1957
+ var earlyRequestIndexMap = /* @__PURE__ */ new Map();
1958
+ var previousFetch = null;
1959
+ var originalXhrOpen = null;
1960
+ var originalXhrSend = null;
1961
+ var originalResponseJson = null;
1962
+ var originalJsonParse = null;
1963
+ var responseToRequestId = /* @__PURE__ */ new WeakMap();
1964
+ var activeXhrRequestId = null;
1965
+ var activeXhrResponseText = null;
1966
+ var dedupeWindow = /* @__PURE__ */ new Map();
1967
+ var fetchDataOrigin = /* @__PURE__ */ new WeakMap();
1968
+ var requestTagTimestamps = /* @__PURE__ */ new Map();
1969
+ var FETCH_ORIGIN_TTL_MS = 3e3;
1970
+ function tagFetchData(obj, requestId, depth = 0) {
1971
+ if (depth > 2 || obj === null || typeof obj !== "object") return;
1972
+ fetchDataOrigin.set(obj, requestId);
1973
+ if (depth === 0) requestTagTimestamps.set(requestId, Date.now());
1974
+ if (Array.isArray(obj)) {
1975
+ for (let i = 0; i < Math.min(obj.length, 50); i++) tagFetchData(obj[i], requestId, depth + 1);
1976
+ } else {
1977
+ for (const val of Object.values(obj)) tagFetchData(val, requestId, depth + 1);
1978
+ }
1979
+ }
1980
+ function hasActiveTags() {
1981
+ return requestTagTimestamps.size > 0;
1982
+ }
1983
+ function findFetchOrigin(obj, depth = 0) {
1984
+ if (depth > 2 || obj === null || typeof obj !== "object") return void 0;
1985
+ const rid = fetchDataOrigin.get(obj);
1986
+ if (rid) {
1987
+ const tagTime = requestTagTimestamps.get(rid);
1988
+ if (tagTime && Date.now() - tagTime <= FETCH_ORIGIN_TTL_MS) return rid;
1989
+ requestTagTimestamps.delete(rid);
1990
+ }
1991
+ if (Array.isArray(obj)) {
1992
+ for (let i = 0; i < Math.min(obj.length, 20); i++) {
1993
+ const found = findFetchOrigin(obj[i], depth + 1);
1994
+ if (found) return found;
1995
+ }
1996
+ } else {
1997
+ for (const val of Object.values(obj)) {
1998
+ const found = findFetchOrigin(val, depth + 1);
1999
+ if (found) return found;
2000
+ }
2001
+ }
2002
+ return void 0;
2003
+ }
2004
+ function installPatches() {
2005
+ patchFetch();
2006
+ patchXhr();
2007
+ patchResponseJson();
2008
+ patchJsonParse();
2009
+ }
2010
+ function prewarmNetworkTracker() {
2011
+ if (isInstalled3 || isPrewarmed) return;
2012
+ isPrewarmed = true;
2013
+ installPatches();
2014
+ }
2015
+ function installNetworkTracker(wsClient) {
2016
+ if (isInstalled3) return;
2017
+ client2 = wsClient;
2018
+ isInstalled3 = true;
2019
+ if (!isPrewarmed) {
2020
+ requestCounter = 0;
2021
+ installPatches();
2022
+ } else {
2023
+ isPrewarmed = false;
2024
+ if (earlyBuffer.length > 0) {
2025
+ buffer = [...earlyBuffer, ...buffer];
2026
+ rebuildRequestIndex();
2027
+ earlyBuffer = [];
2028
+ earlyRequestIndexMap.clear();
2029
+ }
2030
+ }
2031
+ flushTimer2 = setInterval(flushBuffer, FLUSH_INTERVAL_MS2);
2032
+ flushBuffer();
2033
+ }
2034
+ function uninstallNetworkTracker() {
2035
+ if (!isInstalled3 && !isPrewarmed) return;
2036
+ if (previousFetch) {
2037
+ globalThis.fetch = previousFetch;
2038
+ previousFetch = null;
2039
+ }
2040
+ if (originalXhrOpen) {
2041
+ XMLHttpRequest.prototype.open = originalXhrOpen;
2042
+ originalXhrOpen = null;
2043
+ }
2044
+ if (originalXhrSend) {
2045
+ XMLHttpRequest.prototype.send = originalXhrSend;
2046
+ originalXhrSend = null;
2047
+ }
2048
+ if (originalResponseJson) {
2049
+ Response.prototype.json = originalResponseJson;
2050
+ originalResponseJson = null;
2051
+ }
2052
+ if (originalJsonParse) {
2053
+ JSON.parse = originalJsonParse;
2054
+ originalJsonParse = null;
2055
+ }
2056
+ if (flushTimer2) {
2057
+ clearInterval(flushTimer2);
2058
+ flushTimer2 = null;
2059
+ }
2060
+ if (isInstalled3) flushBuffer();
2061
+ buffer = [];
2062
+ earlyBuffer = [];
2063
+ requestIndexMap.clear();
2064
+ earlyRequestIndexMap.clear();
2065
+ dedupeWindow.clear();
2066
+ requestTagTimestamps.clear();
2067
+ activeXhrRequestId = null;
2068
+ activeXhrResponseText = null;
2069
+ client2 = null;
2070
+ isInstalled3 = false;
2071
+ isPrewarmed = false;
2072
+ }
2073
+ function patchFetch() {
2074
+ if (typeof globalThis.fetch !== "function") return;
2075
+ previousFetch = globalThis.fetch;
2076
+ globalThis.fetch = async function trackedFetch(input, init) {
2077
+ const url = extractUrl(input);
2078
+ if (isNoiseUrl(url)) {
2079
+ return previousFetch.call(globalThis, input, init);
2080
+ }
2081
+ const method = (init?.method ?? "GET").toUpperCase();
2082
+ const parsedUrl = parseUrl(url);
2083
+ const entry = createEntry(method, parsedUrl, init);
2084
+ const startTime = performance.now();
2085
+ if (init?.signal) {
2086
+ init.signal.addEventListener("abort", () => {
2087
+ entry.state = "aborted";
2088
+ entry.durationMs = performance.now() - startTime;
2089
+ pushEntry(entry);
2090
+ }, { once: true });
2091
+ }
2092
+ pushEntry({ ...entry });
2093
+ try {
2094
+ const response = await previousFetch.call(globalThis, input, init);
2095
+ if (entry.state !== "aborted") {
2096
+ entry.state = response.ok ? "success" : "error";
2097
+ entry.status = response.status;
2098
+ entry.durationMs = performance.now() - startTime;
2099
+ entry.responseSizeBytes = parseContentLength(response.headers);
2100
+ if (!response.ok) {
2101
+ entry.errorMessage = `${response.status} ${response.statusText}`;
2102
+ }
2103
+ pushEntry(entry);
2104
+ responseToRequestId.set(response, entry.requestId);
2105
+ }
2106
+ return response;
2107
+ } catch (err) {
2108
+ if (entry.state !== "aborted") {
2109
+ entry.state = "error";
2110
+ entry.durationMs = performance.now() - startTime;
2111
+ entry.errorMessage = err instanceof Error ? err.message : String(err);
2112
+ pushEntry(entry);
2113
+ }
2114
+ throw err;
2115
+ }
2116
+ };
2117
+ }
2118
+ function patchXhr() {
2119
+ if (typeof XMLHttpRequest === "undefined") return;
2120
+ originalXhrOpen = XMLHttpRequest.prototype.open;
2121
+ originalXhrSend = XMLHttpRequest.prototype.send;
2122
+ XMLHttpRequest.prototype.open = function(method, url, ...rest) {
2123
+ this.__ftMethod = method.toUpperCase();
2124
+ this.__ftUrl = typeof url === "string" ? url : url.href;
2125
+ const self = this;
2126
+ this.addEventListener("load", function() {
2127
+ const requestId = self.__ftRequestId;
2128
+ if (!requestId) return;
2129
+ if (self.responseType === "json" && self.response !== null && typeof self.response === "object") {
2130
+ try {
2131
+ tagFetchData(self.response, requestId, 0);
2132
+ } catch {
2133
+ }
2134
+ return;
2135
+ }
2136
+ const text = self.responseText;
2137
+ if (text) {
2138
+ activeXhrRequestId = requestId;
2139
+ activeXhrResponseText = text;
2140
+ }
2141
+ });
2142
+ return originalXhrOpen.apply(this, [method, url, ...rest]);
2143
+ };
2144
+ XMLHttpRequest.prototype.send = function(body) {
2145
+ const meta = this;
2146
+ const url = meta.__ftUrl ?? "";
2147
+ if (isNoiseUrl(url)) {
2148
+ return originalXhrSend.call(this, body);
2149
+ }
2150
+ const method = meta.__ftMethod ?? "GET";
2151
+ const parsedUrl = parseUrl(url);
2152
+ const entry = createEntry(method, parsedUrl);
2153
+ const startTime = performance.now();
2154
+ this.__ftRequestId = entry.requestId;
2155
+ pushEntry({ ...entry });
2156
+ this.addEventListener("load", () => {
2157
+ entry.state = this.status >= 400 ? "error" : "success";
2158
+ entry.status = this.status;
2159
+ entry.durationMs = performance.now() - startTime;
2160
+ entry.responseSizeBytes = parseXhrContentLength(this);
2161
+ if (this.status >= 400) {
2162
+ entry.errorMessage = `${this.status} ${this.statusText}`;
2163
+ }
2164
+ pushEntry(entry);
2165
+ });
2166
+ this.addEventListener("error", () => {
2167
+ entry.state = "error";
2168
+ entry.durationMs = performance.now() - startTime;
2169
+ entry.errorMessage = "Network error";
2170
+ pushEntry(entry);
2171
+ });
2172
+ this.addEventListener("abort", () => {
2173
+ entry.state = "aborted";
2174
+ entry.durationMs = performance.now() - startTime;
2175
+ pushEntry(entry);
2176
+ });
2177
+ return originalXhrSend.call(this, body);
2178
+ };
2179
+ }
2180
+ function patchResponseJson() {
2181
+ if (typeof Response === "undefined") return;
2182
+ originalResponseJson = Response.prototype.json;
2183
+ Response.prototype.json = async function() {
2184
+ const data = await originalResponseJson.call(this);
2185
+ const requestId = responseToRequestId.get(this);
2186
+ if (requestId && data !== null && typeof data === "object") {
2187
+ try {
2188
+ tagFetchData(data, requestId, 0);
2189
+ } catch {
2190
+ }
2191
+ }
2192
+ return data;
2193
+ };
2194
+ }
2195
+ function patchJsonParse() {
2196
+ originalJsonParse = JSON.parse;
2197
+ JSON.parse = function(text, reviver) {
2198
+ const result = originalJsonParse.call(JSON, text, reviver);
2199
+ if (activeXhrRequestId !== null && activeXhrResponseText !== null && text === activeXhrResponseText && result !== null && typeof result === "object") {
2200
+ try {
2201
+ tagFetchData(result, activeXhrRequestId, 0);
2202
+ } catch {
2203
+ }
2204
+ activeXhrRequestId = null;
2205
+ activeXhrResponseText = null;
2206
+ }
2207
+ return result;
2208
+ };
2209
+ }
2210
+ function createEntry(method, parsedUrl, init) {
2211
+ const requestId = String(++requestCounter);
2212
+ const dedupeKey = `${method}:${parsedUrl.path}`;
2213
+ const attribution = getAttribution();
2214
+ const isServerAction = hasHeader(init, "Next-Action");
2215
+ const isPrefetch = hasHeader(init, "Next-Router-Prefetch");
2216
+ const now = Date.now();
2217
+ const isDuplicate = checkDuplicate(dedupeKey, now);
2218
+ return {
2219
+ requestId,
2220
+ method,
2221
+ urlPath: parsedUrl.path,
2222
+ urlHost: parsedUrl.host,
2223
+ status: 0,
2224
+ durationMs: null,
2225
+ responseSizeBytes: null,
2226
+ componentName: attribution.componentName,
2227
+ ancestorChain: attribution.ancestorChain,
2228
+ initiatedDuringRender: attribution.duringRender,
2229
+ initiatedInEffect: attribution.inEffect,
2230
+ state: "pending",
2231
+ dedupeKey,
2232
+ isDuplicate: isDuplicate || void 0,
2233
+ isServerAction: isServerAction || void 0,
2234
+ isPrefetch: isPrefetch || void 0,
2235
+ timestamp: now
2236
+ };
2237
+ }
2238
+ function getAttribution() {
2239
+ const fiber = getCurrentRenderingFiber();
2240
+ if (fiber) {
2241
+ const name = getComponentNameFromFiber(fiber);
2242
+ const ancestors = buildAncestorChain(fiber).slice(-MAX_ANCESTOR_CHAIN);
2243
+ return {
2244
+ componentName: name || void 0,
2245
+ ancestorChain: ancestors.length > 0 ? ancestors : void 0,
2246
+ duringRender: true,
2247
+ inEffect: false
2248
+ };
2249
+ }
2250
+ return { duringRender: false, inEffect: false };
2251
+ }
2252
+ function extractUrl(input) {
2253
+ if (typeof input === "string") return input;
2254
+ if (input instanceof URL) return input.href;
2255
+ return input.url;
2256
+ }
2257
+ function parseUrl(url) {
2258
+ try {
2259
+ const u = new URL(url, globalThis.location?.href ?? "http://localhost");
2260
+ return { path: u.pathname, host: u.host };
2261
+ } catch {
2262
+ return { path: url.split("?")[0] ?? url, host: "" };
2263
+ }
2264
+ }
2265
+ var COMBINED_NOISE_PATTERN = new RegExp(
2266
+ NOISE_URL_PATTERNS.map((r) => r.source).join("|"),
2267
+ "i"
2268
+ );
2269
+ function isNoiseUrl(url) {
2270
+ return COMBINED_NOISE_PATTERN.test(url);
2271
+ }
2272
+ function parseIntOrNull(value) {
2273
+ if (!value) return null;
2274
+ const n = parseInt(value, 10);
2275
+ return isNaN(n) ? null : n;
2276
+ }
2277
+ function parseContentLength(headers) {
2278
+ return parseIntOrNull(headers.get("content-length"));
2279
+ }
2280
+ function parseXhrContentLength(xhr) {
2281
+ return parseIntOrNull(xhr.getResponseHeader("content-length"));
2282
+ }
2283
+ function hasHeader(init, name) {
2284
+ if (!init?.headers) return false;
2285
+ if (init.headers instanceof Headers) return init.headers.has(name);
2286
+ if (Array.isArray(init.headers)) return init.headers.some(([k]) => k.toLowerCase() === name.toLowerCase());
2287
+ if (typeof init.headers === "object") {
2288
+ return Object.keys(init.headers).some((k) => k.toLowerCase() === name.toLowerCase());
2289
+ }
2290
+ return false;
2291
+ }
2292
+ function checkDuplicate(dedupeKey, now) {
2293
+ for (const [key, ts] of dedupeWindow) {
2294
+ if (now - ts > DEDUPE_WINDOW_MS) dedupeWindow.delete(key);
2295
+ }
2296
+ const isDup = dedupeWindow.has(dedupeKey);
2297
+ dedupeWindow.set(dedupeKey, now);
2298
+ return isDup;
2299
+ }
2300
+ function upsertAndPrune(entry, buf, idxMap, maxSize) {
2301
+ const existingIdx = idxMap.get(entry.requestId);
2302
+ if (existingIdx !== void 0 && existingIdx < buf.length && buf[existingIdx]?.requestId === entry.requestId) {
2303
+ buf[existingIdx] = entry;
2304
+ return buf;
2305
+ }
2306
+ idxMap.set(entry.requestId, buf.length);
2307
+ buf.push(entry);
2308
+ if (buf.length > maxSize) {
2309
+ const pruned = buf.slice(-maxSize);
2310
+ idxMap.clear();
2311
+ for (let i = 0; i < pruned.length; i++) idxMap.set(pruned[i].requestId, i);
2312
+ return pruned;
2313
+ }
2314
+ return buf;
2315
+ }
2316
+ function pushEntry(entry) {
2317
+ if (client2 === null && isPrewarmed) {
2318
+ earlyBuffer = upsertAndPrune(entry, earlyBuffer, earlyRequestIndexMap, MAX_BUFFER_SIZE);
2319
+ return;
2320
+ }
2321
+ buffer = upsertAndPrune(entry, buffer, requestIndexMap, MAX_BUFFER_SIZE);
2322
+ if (buffer.length >= MAX_BATCH_SIZE) flushBuffer();
2323
+ }
2324
+ function rebuildRequestIndex() {
2325
+ requestIndexMap.clear();
2326
+ for (let i = 0; i < buffer.length; i++) {
2327
+ requestIndexMap.set(buffer[i].requestId, i);
2328
+ }
2329
+ }
2330
+ function flushBuffer() {
2331
+ if (buffer.length === 0 || !client2?.connected) return;
2332
+ client2.send({
2333
+ type: "runtime:networkRequest",
2334
+ requests: [...buffer],
2335
+ timestamp: Date.now()
2336
+ });
2337
+ buffer = [];
2338
+ requestIndexMap.clear();
2339
+ }
2340
+
2341
+ // src/fiberTreeWalker.ts
2342
+ var FIBER_TAGS = {
2343
+ FunctionComponent: 0,
2344
+ ClassComponent: 1,
2345
+ HostRoot: 3,
2346
+ // Root of a host tree (e.g., #root DOM node)
2347
+ HostComponent: 5,
2348
+ // DOM elements (div, span, etc.) - SKIP these
2349
+ HostText: 6,
2350
+ // Text nodes - SKIP these
2351
+ Fragment: 7,
2352
+ // React.Fragment - SKIP but traverse children
2353
+ Mode: 8,
2354
+ // React.StrictMode, ConcurrentMode - SKIP but traverse children
2355
+ ContextConsumer: 9,
2356
+ ContextProvider: 10,
2357
+ ForwardRef: 11,
2358
+ Profiler: 12,
2359
+ // React.Profiler - SKIP but traverse children
2360
+ SuspenseComponent: 13,
2361
+ MemoComponent: 14,
2362
+ SimpleMemoComponent: 15,
2363
+ LazyComponent: 16,
2364
+ OffscreenComponent: 22
2365
+ // React 18 concurrent features - SKIP but traverse children
2366
+ };
2367
+ var USER_COMPONENT_TAGS = /* @__PURE__ */ new Set([
2368
+ FIBER_TAGS.FunctionComponent,
2369
+ FIBER_TAGS.ClassComponent,
2370
+ FIBER_TAGS.ForwardRef,
2371
+ FIBER_TAGS.MemoComponent,
2372
+ FIBER_TAGS.SimpleMemoComponent
2373
+ ]);
2374
+ function isLikelyQueryObserver(obj) {
2375
+ if (obj === null || typeof obj !== "object") return false;
2376
+ const candidate = obj;
2377
+ return typeof candidate.getCurrentResult === "function" && typeof candidate.subscribe === "function";
2378
+ }
2379
+ function getQueryHashFromObserver(observer) {
2380
+ if (observer.options && typeof observer.options === "object") {
2381
+ const opts = observer.options;
2382
+ if (typeof opts.queryHash === "string") return opts.queryHash;
2383
+ }
2384
+ if (observer.currentQuery && typeof observer.currentQuery === "object") {
2385
+ const q = observer.currentQuery;
2386
+ if (typeof q.queryHash === "string") return q.queryHash;
2387
+ }
2388
+ if (typeof observer.queryHash === "string") return observer.queryHash;
2389
+ return null;
2390
+ }
2391
+ function detectQueryObserverHashes(fiber) {
2392
+ let hookState = fiber.memoizedState;
2393
+ if (!hookState) return void 0;
2394
+ const seen = /* @__PURE__ */ new Set();
2395
+ let iterations = 0;
2396
+ while (hookState && iterations < 100) {
2397
+ iterations++;
2398
+ try {
2399
+ const ms = hookState.memoizedState;
2400
+ if (isLikelyQueryObserver(ms)) {
2401
+ const hash = getQueryHashFromObserver(ms);
2402
+ if (hash) seen.add(hash);
2403
+ } else if (ms !== null && typeof ms === "object" && !Array.isArray(ms)) {
2404
+ const ref = ms.current;
2405
+ if (isLikelyQueryObserver(ref)) {
2406
+ const hash = getQueryHashFromObserver(ref);
2407
+ if (hash) seen.add(hash);
2408
+ }
2409
+ }
2410
+ } catch {
2411
+ }
2412
+ hookState = hookState.next;
2413
+ }
2414
+ return seen.size > 0 ? Array.from(seen) : void 0;
2415
+ }
2416
+ function countFiberHooks(fiber) {
2417
+ if (fiber._debugHookTypes) return fiber._debugHookTypes.length;
2418
+ let count = 0;
2419
+ let state = fiber.memoizedState;
2420
+ while (state && count < 100) {
2421
+ count++;
2422
+ state = state.next;
2423
+ }
2424
+ return count;
2425
+ }
2426
+ function hasFiberContextHook(fiber) {
2427
+ if (fiber.dependencies?.firstContext) return true;
2428
+ if (fiber._debugHookTypes?.includes("useContext")) return true;
2429
+ return false;
2430
+ }
2431
+ function detectTransitionPending(fiber) {
2432
+ let state = fiber.memoizedState;
2433
+ let iterations = 0;
2434
+ while (state && iterations < 100) {
2435
+ iterations++;
2436
+ const ms = state.memoizedState;
2437
+ if (Array.isArray(ms) && ms.length === 2 && typeof ms[0] === "boolean" && typeof ms[1] === "function") {
2438
+ if (ms[0] === true) return true;
2439
+ }
2440
+ state = state.next;
2441
+ }
2442
+ return false;
2443
+ }
2444
+ var MAX_TREE_DEPTH = 100;
2445
+ var MAX_CHILDREN_PER_NODE = 300;
2446
+ var throttleTimer = null;
2447
+ var maxWaitTimer = null;
2448
+ var INTERVAL_MS_SMALL = 200;
2449
+ var INTERVAL_MS_MEDIUM = 500;
2450
+ var INTERVAL_MS_LARGE = 1e3;
2451
+ var snapshotIntervalMs = INTERVAL_MS_SMALL;
2452
+ var cachedFiberRoot = null;
2453
+ var isWalking = false;
2454
+ var pendingLocalStateCorrelations = [];
2455
+ var originalOnCommitFiberRoot = null;
2456
+ var isInstalled4 = false;
2457
+ var hookedRendererID = null;
2458
+ var activeStrategy = null;
2459
+ var lastSnapshotSentTime = 0;
2460
+ var DEVTOOLS_STALE_THRESHOLD_MS = 2e3;
2461
+ var debugEnabled = false;
2462
+ try {
2463
+ debugEnabled = !!globalThis.__FLOTRACE_DEBUG__;
2464
+ } catch {
2465
+ }
2466
+ function debugLog(...args) {
2467
+ if (debugEnabled) console.log(...args);
2468
+ }
2469
+ var fiberRefMap = /* @__PURE__ */ new Map();
2470
+ function getComponentName2(fiber) {
2471
+ const type = fiber.type;
2472
+ if (!type) return "Unknown";
2473
+ if (typeof type === "function") {
2474
+ return type.displayName || type.name || "Anonymous";
2475
+ }
2476
+ if (typeof type === "object" && type !== null) {
2477
+ const t = type;
2478
+ if (t.type) {
2479
+ return t.type.displayName || t.type.name || "Memo";
2480
+ }
2481
+ if (t.render) {
2482
+ return t.render.displayName || t.render.name || "ForwardRef";
2483
+ }
2484
+ return t.displayName || t.name || "Unknown";
2485
+ }
2486
+ if (typeof type === "string") {
2487
+ return type;
2488
+ }
2489
+ return "Unknown";
2490
+ }
2491
+ function isUserComponent(fiber) {
2492
+ if (!USER_COMPONENT_TAGS.has(fiber.tag)) return false;
2493
+ const name = getComponentName2(fiber);
2494
+ if (name === "Anonymous" || name === "Unknown" || name === "ForwardRef" || name === "Memo")
2495
+ return false;
2496
+ if (name.startsWith("FloTrace")) return false;
2497
+ if (name.startsWith("@") || name.includes("/")) return false;
2498
+ if (/^[$_][A-Za-z0-9]{0,3}$/.test(name)) return false;
2499
+ if (fiber._debugSource?.fileName?.includes("node_modules")) return false;
2500
+ return true;
2501
+ }
2502
+ var FRAMEWORK_COMPONENT_NAMES = /* @__PURE__ */ new Set([
2503
+ // Next.js App Router internals (Next.js 13–14)
2504
+ "InnerLayoutRouter",
2505
+ "OuterLayoutRouter",
2506
+ "HotReload",
2507
+ "RedirectBoundary",
2508
+ "NotFoundBoundary",
2509
+ "RenderFromTemplateContext",
2510
+ "ScrollAndFocusHandler",
2511
+ "AppRouter",
2512
+ "ServerRoot",
2513
+ "ReactDevOverlay",
2514
+ "PathnameContextProviderAdapter",
2515
+ "MetadataBoundary",
2516
+ "ViewportBoundary",
2517
+ "NotFoundErrorBoundary",
2518
+ "RedirectErrorBoundary",
2519
+ "InnerScrollAndFocusHandler",
2520
+ "GlobalError",
2521
+ // Next.js 15 / React 19 new internals
2522
+ "ViewTransition",
2523
+ // Next.js 15 shared-element transition wrapper
2524
+ "ActionStateContext",
2525
+ // Next.js 15 server action state context provider
2526
+ "RequestCookiesProvider",
2527
+ "DraftModeProvider",
2528
+ // React Router v6 / v7
2529
+ "Routes",
2530
+ "Route",
2531
+ "Router",
2532
+ "BrowserRouter",
2533
+ "HashRouter",
2534
+ "MemoryRouter",
2535
+ "Outlet",
2536
+ "Navigate",
2537
+ "RenderedRoute",
2538
+ "RouterProvider",
2539
+ // React 19 built-in primitives
2540
+ "Activity",
2541
+ // React 19: show/hide subtrees while preserving state (was <Offscreen>)
2542
+ // Common library wrappers
2543
+ "Suspense",
2544
+ "ErrorBoundary",
2545
+ "QueryClientProvider",
2546
+ "PersistGate"
2547
+ ]);
2548
+ var FRAMEWORK_PATH_PATTERNS = [
2549
+ // React core / Next.js
2550
+ /next[\\/]dist/,
2551
+ /react-dom/,
2552
+ /[\\/]scheduler[\\/]/,
2553
+ // React internal scheduler package
2554
+ // Routing
2555
+ /react-router/,
2556
+ // React Router v6
2557
+ /@react-router[\\/]/,
2558
+ // React Router v7 (scoped package)
2559
+ // State management
2560
+ /@tanstack[\\/]/,
2561
+ // TanStack Query / Table / Router / Form / Virtual
2562
+ /react-redux/,
2563
+ /zustand/,
2564
+ /jotai/,
2565
+ /recoil/,
2566
+ // UI component libraries (for when source maps are available)
2567
+ /@fortawesome[\\/]/,
2568
+ // Font Awesome icons
2569
+ /framer-motion/,
2570
+ // Framer Motion (PresenceChild, AnimatePresence, etc.)
2571
+ /sonner/,
2572
+ // Sonner toast
2573
+ /@radix-ui[\\/]/,
2574
+ // Radix UI primitives
2575
+ /@headlessui[\\/]/,
2576
+ // Headless UI
2577
+ /@mui[\\/]/,
2578
+ // Material UI
2579
+ /@chakra-ui[\\/]/,
2580
+ // Chakra UI
2581
+ /react-spring/,
2582
+ // React Spring
2583
+ /react-transition-group/,
2584
+ // React Transition Group
2585
+ /react-aria/,
2586
+ // Adobe React Aria
2587
+ /react-hook-form/,
2588
+ /formik/
2589
+ ];
2590
+ function isFrameworkComponent(fiber, name) {
2591
+ if (FRAMEWORK_COMPONENT_NAMES.has(name)) return true;
2592
+ const filePath = fiber._debugSource?.fileName;
2593
+ if (filePath) {
2594
+ for (const pattern of FRAMEWORK_PATH_PATTERNS) {
2595
+ if (pattern.test(filePath)) return true;
2596
+ }
2597
+ }
2598
+ return false;
2599
+ }
2600
+ var KNOWN_LIBRARY_NAMES = /* @__PURE__ */ new Map([
2601
+ // Font Awesome
2602
+ ["FontAwesomeIcon", "fontawesome"],
2603
+ ["FontAwesomeLayers", "fontawesome"],
2604
+ ["FontAwesomeLayersText", "fontawesome"],
2605
+ // Framer Motion
2606
+ ["AnimatePresence", "framer"],
2607
+ ["LazyMotion", "framer"],
2608
+ ["MotionConfig", "framer"],
2609
+ ["PresenceChild", "framer"],
2610
+ ["LayoutGroupContext", "framer"],
2611
+ // Lottie
2612
+ ["Lottie", "lottie"],
2613
+ ["LottiePlayer", "lottie"],
2614
+ // Heroicons / Lucide exported icons sometimes appear as named functions
2615
+ ["HeroIcon", "heroicons"]
2616
+ ]);
2617
+ function detectLibraryName(fiber, name) {
2618
+ if (name.includes(".")) {
2619
+ return name.split(".")[0].toLowerCase();
2620
+ }
2621
+ if (name.startsWith("__")) {
2622
+ return "internal";
2623
+ }
2624
+ const known = KNOWN_LIBRARY_NAMES.get(name);
2625
+ return known;
2626
+ }
2627
+ function buildNodeId(name, sameNameIndex, parentId) {
2628
+ const segment = `${name}-${sameNameIndex}`;
2629
+ return parentId ? `${parentId}/${segment}` : segment;
2630
+ }
2631
+ function shallowPropsChanged(prev, next) {
2632
+ if (prev === next) return false;
2633
+ if (!prev || !next) return true;
2634
+ const prevKeys = Object.keys(prev);
2635
+ const nextKeys = Object.keys(next);
2636
+ if (prevKeys.length !== nextKeys.length) return true;
2637
+ for (const key of nextKeys) {
2638
+ if (key === "children") continue;
2639
+ if (prev[key] !== next[key]) return true;
2640
+ }
2641
+ return false;
2642
+ }
2643
+ function detectRenderReason(fiber, renderPhase) {
2644
+ if (renderPhase === "mount") return "mount";
2645
+ const prev = fiber.alternate;
2646
+ if (!prev) return "mount";
2647
+ if (shallowPropsChanged(prev.memoizedProps, fiber.memoizedProps)) {
2648
+ return "props-changed";
2649
+ }
2650
+ return "state-or-context";
2651
+ }
2652
+ function scanFiberStateForOrigin(fiber, componentName) {
2653
+ let hook = fiber.memoizedState;
2654
+ let hookIndex = 0;
2655
+ while (hook !== null) {
2656
+ try {
2657
+ const ms = hook.memoizedState;
2658
+ if (ms !== null && typeof ms === "object") {
2659
+ const isEffect = "tag" in ms && "create" in ms;
2660
+ if (!isEffect) {
2661
+ const rid = findFetchOrigin(ms);
2662
+ if (rid) {
2663
+ pendingLocalStateCorrelations.push({ requestId: rid, componentName, hookIndex });
2664
+ } else if (hook.queue !== null) {
2665
+ const lastRendered = hook.queue.lastRenderedState;
2666
+ if (lastRendered !== null && typeof lastRendered === "object") {
2667
+ const rid2 = findFetchOrigin(lastRendered);
2668
+ if (rid2) {
2669
+ pendingLocalStateCorrelations.push({ requestId: rid2, componentName, hookIndex });
2670
+ }
2671
+ }
2672
+ }
2673
+ }
2674
+ }
2675
+ } catch {
2676
+ }
2677
+ hook = hook.next;
2678
+ hookIndex++;
2679
+ }
2680
+ }
2681
+ function walkFiber(fiber, parentId, sharedNameCountMap, depth = 0, inSuspenseFallback = false) {
2682
+ if (!fiber) return [];
2683
+ if (depth >= MAX_TREE_DEPTH) return [];
2684
+ const nodes = [];
2685
+ let current = fiber;
2686
+ const nameCountMap = sharedNameCountMap || /* @__PURE__ */ new Map();
2687
+ while (current) {
2688
+ try {
2689
+ const tag = current.tag;
2690
+ if (isUserComponent(current)) {
2691
+ const name = getComponentName2(current);
2692
+ const nameCount = nameCountMap.get(name) || 0;
2693
+ nameCountMap.set(name, nameCount + 1);
2694
+ const nodeId = buildNodeId(name, nameCount, parentId);
2695
+ fiberRefMap.set(nodeId, current);
2696
+ const renderPhase = current.alternate ? "update" : "mount";
2697
+ const renderReason = detectRenderReason(current, renderPhase);
2698
+ recordTimelineEvent(
2699
+ nodeId,
2700
+ name,
2701
+ renderPhase === "mount" ? "mount" : "render",
2702
+ { reason: renderReason },
2703
+ current.actualDuration
2704
+ );
2705
+ const children = walkFiber(
2706
+ current.child,
2707
+ nodeId,
2708
+ void 0,
2709
+ depth + 1,
2710
+ inSuspenseFallback
2711
+ );
2712
+ const truncatedChildren = children.length > MAX_CHILDREN_PER_NODE ? children.slice(0, MAX_CHILDREN_PER_NODE) : children;
2713
+ const framework = isFrameworkComponent(current, name) || void 0;
2714
+ const queryHashes = detectQueryObserverHashes(current);
2715
+ const isTransitionPending = detectTransitionPending(current) || void 0;
2716
+ const compilerStatus = detectCompilerStatus(current);
2717
+ const isServerComponent = detectServerComponent(current) || void 0;
2718
+ const libraryName = framework ? void 0 : detectLibraryName(current, name);
2719
+ nodes.push({
2720
+ id: nodeId,
2721
+ name,
2722
+ children: truncatedChildren,
2723
+ fiberTag: tag,
2724
+ renderPhase,
2725
+ renderReason,
2726
+ renderDuration: current.actualDuration,
2727
+ filePath: current._debugSource?.fileName,
2728
+ lineNumber: current._debugSource?.lineNumber,
2729
+ isFramework: framework,
2730
+ reactKey: typeof current.key === "string" ? current.key : void 0,
2731
+ queryHashes,
2732
+ hookCount: countFiberHooks(current),
2733
+ hasContextHook: hasFiberContextHook(current) || void 0,
2734
+ isTransitionPending,
2735
+ isSuspenseFallback: inSuspenseFallback || void 0,
2736
+ compilerStatus,
2737
+ isServerComponent,
2738
+ isLibrary: libraryName !== void 0 ? true : void 0,
2739
+ libraryName
2740
+ });
2741
+ if (hasActiveTags() && current.memoizedState !== null) {
2742
+ scanFiberStateForOrigin(current, name);
2743
+ }
2744
+ } else if (tag === FIBER_TAGS.HostText) {
2745
+ } else if (tag === FIBER_TAGS.SuspenseComponent) {
2746
+ const primary = current.child;
2747
+ if (current.memoizedState === null && primary) {
2748
+ const childNodes = walkFiber(
2749
+ primary.child,
2750
+ parentId,
2751
+ nameCountMap,
2752
+ depth,
2753
+ inSuspenseFallback
2754
+ );
2755
+ nodes.push(...childNodes);
2756
+ } else if (primary?.sibling) {
2757
+ const childNodes = walkFiber(
2758
+ primary.sibling,
2759
+ parentId,
2760
+ nameCountMap,
2761
+ depth,
2762
+ true
2763
+ // all nodes in the fallback branch get isSuspenseFallback
2764
+ );
2765
+ nodes.push(...childNodes);
2766
+ } else {
2767
+ debugLog("[FloTrace] SuspenseComponent has no walkable children");
2768
+ }
2769
+ } else if (tag === FIBER_TAGS.OffscreenComponent) {
2770
+ if (current.memoizedState === null) {
2771
+ const childNodes = walkFiber(
2772
+ current.child,
2773
+ parentId,
2774
+ nameCountMap,
2775
+ depth,
2776
+ inSuspenseFallback
2777
+ );
2778
+ nodes.push(...childNodes);
2779
+ } else {
2780
+ debugLog("[FloTrace] Skipping hidden OffscreenComponent subtree");
2781
+ }
2782
+ } else {
2783
+ const childNodes = walkFiber(
2784
+ current.child,
2785
+ parentId,
2786
+ nameCountMap,
2787
+ depth,
2788
+ inSuspenseFallback
2789
+ );
2790
+ nodes.push(...childNodes);
2791
+ }
2792
+ } catch (error) {
2793
+ console.error("[FloTrace] Error processing fiber node, skipping:", error);
2794
+ }
2795
+ current = current.sibling;
2796
+ }
2797
+ return nodes;
2798
+ }
2799
+ function buildTreeFromFiberRoot(root) {
2800
+ const rootFiber = root.current;
2801
+ if (!rootFiber || !rootFiber.child) {
2802
+ console.warn("[FloTrace] No root fiber or no child:", {
2803
+ hasRoot: !!rootFiber,
2804
+ hasChild: !!rootFiber?.child
2805
+ });
2806
+ return null;
2807
+ }
2808
+ fiberRefMap.clear();
2809
+ const topLevelNodes = walkFiber(rootFiber.child, "");
2810
+ debugLog(
2811
+ "[FloTrace] walkFiber found",
2812
+ topLevelNodes.length,
2813
+ "top-level nodes"
2814
+ );
2815
+ if (topLevelNodes.length === 1) {
2816
+ return topLevelNodes[0];
2817
+ }
2818
+ if (topLevelNodes.length > 0) {
2819
+ return {
2820
+ id: "Root",
2821
+ name: "Root",
2822
+ children: topLevelNodes,
2823
+ fiberTag: FIBER_TAGS.HostRoot
2824
+ };
2825
+ }
2826
+ return null;
2827
+ }
2828
+ function findFiberRootFromDOM() {
2829
+ try {
2830
+ if (typeof document === "undefined") return null;
2831
+ const selectors = ["#root", "#__next", "#app", "#__nuxt", "[data-reactroot]"];
2832
+ for (const selector of selectors) {
2833
+ const element = document.querySelector(selector);
2834
+ if (!element) continue;
2835
+ debugLog(
2836
+ `[FloTrace] Trying selector "${selector}" \u2192 found element`,
2837
+ element.tagName,
2838
+ element.id
2839
+ );
2840
+ const reactKeys = Object.keys(element).filter(
2841
+ (k) => k.startsWith("__react") || k.startsWith("_react")
2842
+ );
2843
+ debugLog(`[FloTrace] React keys on element:`, reactKeys);
2844
+ const fiberRoot = getFiberRootFromElement(element);
2845
+ if (fiberRoot) {
2846
+ debugLog("[FloTrace] Found fiber root from selector:", selector);
2847
+ return fiberRoot;
2848
+ }
2849
+ }
2850
+ const allBodyChildren = document.body?.children;
2851
+ if (allBodyChildren) {
2852
+ debugLog(
2853
+ "[FloTrace] Scanning all",
2854
+ allBodyChildren.length,
2855
+ "body children for React root..."
2856
+ );
2857
+ for (const child of Array.from(allBodyChildren)) {
2858
+ const reactKeys = Object.keys(child).filter(
2859
+ (k) => k.startsWith("__react") || k.startsWith("_react")
2860
+ );
2861
+ if (reactKeys.length > 0) {
2862
+ debugLog(
2863
+ "[FloTrace] React keys on",
2864
+ child.tagName,
2865
+ child.id || "(no id)",
2866
+ ":",
2867
+ reactKeys
2868
+ );
2869
+ }
2870
+ const fiberRoot = getFiberRootFromElement(child);
2871
+ if (fiberRoot) {
2872
+ debugLog(
2873
+ "[FloTrace] Found fiber root from body child scan:",
2874
+ child.tagName,
2875
+ child.id || "(no id)"
2876
+ );
2877
+ return fiberRoot;
2878
+ }
2879
+ }
2880
+ }
2881
+ console.warn(
2882
+ "[FloTrace] Could not find React fiber root from any DOM element"
2883
+ );
2884
+ return null;
2885
+ } catch (error) {
2886
+ console.error("[FloTrace] Error finding fiber root from DOM:", error);
2887
+ return null;
2888
+ }
2889
+ }
2890
+ function getFiberRootFromElement(element) {
2891
+ const keys = Object.keys(element);
2892
+ const containerKey = keys.find((k) => k.startsWith("__reactContainer$"));
2893
+ if (containerKey) {
2894
+ const hostRootFiber = element[containerKey];
2895
+ if (hostRootFiber?.stateNode) {
2896
+ return hostRootFiber.stateNode;
2897
+ }
2898
+ }
2899
+ const fiberKey = keys.find(
2900
+ (k) => k.startsWith("__reactFiber$") || k.startsWith("__reactInternalInstance$")
2901
+ );
2902
+ if (fiberKey) {
2903
+ const fiber = element[fiberKey];
2904
+ if (fiber) {
2905
+ let current = fiber;
2906
+ while (current?.return) {
2907
+ current = current.return;
2908
+ }
2909
+ if (current && current.tag === FIBER_TAGS.HostRoot && current.stateNode) {
2910
+ return current.stateNode;
2911
+ }
2912
+ }
2913
+ }
2914
+ const el = element;
2915
+ if (el._reactRootContainer?._internalRoot) {
2916
+ return el._reactRootContainer._internalRoot;
2917
+ }
2918
+ return null;
2919
+ }
2920
+ function adaptSnapshotInterval(nodeCount) {
2921
+ if (nodeCount >= 200) {
2922
+ snapshotIntervalMs = INTERVAL_MS_LARGE;
2923
+ } else if (nodeCount >= 50) {
2924
+ snapshotIntervalMs = INTERVAL_MS_MEDIUM;
2925
+ } else {
2926
+ snapshotIntervalMs = INTERVAL_MS_SMALL;
2927
+ }
2928
+ }
2929
+ function executeSnapshot(root) {
2930
+ if (isWalking) {
2931
+ debugLog("[FloTrace] Skipped snapshot: already walking");
2932
+ return;
2933
+ }
2934
+ isWalking = true;
2935
+ try {
2936
+ const tree = buildTreeFromFiberRoot(root);
2937
+ if (!tree) {
2938
+ console.warn("[FloTrace] buildTreeFromFiberRoot returned null");
2939
+ return;
2940
+ }
2941
+ const nodeCount = fiberRefMap.size;
2942
+ adaptSnapshotInterval(nodeCount);
2943
+ const client4 = getWebSocketClient();
2944
+ if (!client4.connected) {
2945
+ console.warn(
2946
+ "[FloTrace] WebSocket not connected, cannot send tree snapshot"
2947
+ );
2948
+ return;
2949
+ }
2950
+ const currentFlatTree = flattenTree2(tree);
2951
+ const sendFull = previousFlatTree === null || snapshotCounter % FULL_SNAPSHOT_INTERVAL === 0;
2952
+ if (sendFull) {
2953
+ debugLog(
2954
+ "[FloTrace] Sending FULL tree snapshot, root:",
2955
+ tree.name,
2956
+ "nodes:",
2957
+ nodeCount,
2958
+ "seq:",
2959
+ snapshotCounter,
2960
+ "nextInterval:",
2961
+ snapshotIntervalMs + "ms"
2962
+ );
2963
+ client4.sendImmediate({
2964
+ type: "runtime:treeSnapshot",
2965
+ tree,
2966
+ timestamp: Date.now()
2967
+ });
2968
+ lastSnapshotSentTime = Date.now();
2969
+ diffSeq = 0;
2970
+ } else {
2971
+ const diff = computeTreeDiff(previousFlatTree, currentFlatTree);
2972
+ if (diff) {
2973
+ debugLog(
2974
+ "[FloTrace] Sending tree diff, seq:",
2975
+ diffSeq,
2976
+ "added:",
2977
+ diff.added.length,
2978
+ "removed:",
2979
+ diff.removed.length,
2980
+ "updated:",
2981
+ diff.updated.length
2982
+ );
2983
+ client4.sendImmediate({
2984
+ type: "runtime:treeDiff",
2985
+ seq: diffSeq,
2986
+ added: diff.added,
2987
+ removed: diff.removed,
2988
+ updated: diff.updated,
2989
+ timestamp: Date.now()
2990
+ });
2991
+ lastSnapshotSentTime = Date.now();
2992
+ diffSeq++;
2993
+ } else {
2994
+ debugLog("[FloTrace] Tree unchanged, skipping diff");
2995
+ }
2996
+ }
2997
+ previousFlatTree = currentFlatTree;
2998
+ if (pendingLocalStateCorrelations.length > 0) {
2999
+ const now = Date.now();
3000
+ const toSend = pendingLocalStateCorrelations.splice(0);
3001
+ for (const corr of toSend) {
3002
+ try {
3003
+ client4.sendImmediate({
3004
+ type: "runtime:localStateCorrelation",
3005
+ requestId: corr.requestId,
3006
+ componentName: corr.componentName,
3007
+ hookIndex: corr.hookIndex,
3008
+ timestamp: now
3009
+ });
3010
+ } catch {
3011
+ }
3012
+ }
3013
+ }
3014
+ schedulePropDrillingAnalysis(tree, fiberRefMap, client4);
3015
+ scanActionStateChanges(fiberRefMap, client4);
3016
+ maybeEmitNextjsContext(client4);
3017
+ snapshotCounter++;
3018
+ } catch (error) {
3019
+ console.error("[FloTrace] Error walking fiber tree:", error);
3020
+ } finally {
3021
+ isWalking = false;
3022
+ }
3023
+ }
3024
+ function scheduleSnapshot(root) {
3025
+ cachedFiberRoot = root;
3026
+ if (throttleTimer) {
3027
+ clearTimeout(throttleTimer);
3028
+ }
3029
+ throttleTimer = setTimeout(() => {
3030
+ throttleTimer = null;
3031
+ if (maxWaitTimer) {
3032
+ clearTimeout(maxWaitTimer);
3033
+ maxWaitTimer = null;
3034
+ }
3035
+ executeSnapshot(cachedFiberRoot);
3036
+ }, snapshotIntervalMs);
3037
+ if (!maxWaitTimer) {
3038
+ maxWaitTimer = setTimeout(() => {
3039
+ maxWaitTimer = null;
3040
+ if (throttleTimer) {
3041
+ clearTimeout(throttleTimer);
3042
+ throttleTimer = null;
3043
+ }
3044
+ debugLog("[FloTrace] MaxWait forced snapshot (rapid commits detected)");
3045
+ if (cachedFiberRoot) {
3046
+ executeSnapshot(cachedFiberRoot);
3047
+ }
3048
+ }, snapshotIntervalMs * 2);
3049
+ }
3050
+ }
3051
+ var previousFlatTree = null;
3052
+ var diffSeq = 0;
3053
+ var snapshotCounter = 0;
3054
+ var FULL_SNAPSHOT_INTERVAL = 10;
3055
+ function flattenTree2(root, out = /* @__PURE__ */ new Map()) {
3056
+ out.set(root.id, root);
3057
+ for (const child of root.children) {
3058
+ flattenTree2(child, out);
3059
+ }
3060
+ return out;
3061
+ }
3062
+ function getParentId(nodeId) {
3063
+ const lastSlash = nodeId.lastIndexOf("/");
3064
+ return lastSlash === -1 ? "" : nodeId.substring(0, lastSlash);
3065
+ }
3066
+ function computeTreeDiff(prev, curr) {
3067
+ const added = [];
3068
+ const removed = [];
3069
+ const updated = [];
3070
+ for (const [id, currNode] of curr) {
3071
+ const prevNode = prev.get(id);
3072
+ if (!prevNode) {
3073
+ added.push({ ...currNode, children: [], parentId: getParentId(id) });
3074
+ } else {
3075
+ if (prevNode.renderDuration !== currNode.renderDuration || prevNode.renderPhase !== currNode.renderPhase || prevNode.renderReason !== currNode.renderReason) {
3076
+ updated.push({
3077
+ id,
3078
+ renderDuration: currNode.renderDuration,
3079
+ renderPhase: currNode.renderPhase,
3080
+ renderReason: currNode.renderReason
3081
+ });
3082
+ }
3083
+ }
3084
+ }
3085
+ for (const id of prev.keys()) {
3086
+ if (!curr.has(id)) {
3087
+ removed.push(id);
3088
+ }
3089
+ }
3090
+ if (added.length === 0 && removed.length === 0 && updated.length === 0) {
3091
+ return null;
3092
+ }
3093
+ return { added, removed, updated };
3094
+ }
3095
+ function requestTreeSnapshot() {
3096
+ if (!isInstalled4) {
3097
+ return;
3098
+ }
3099
+ if (activeStrategy === "devtools") {
3100
+ const elapsed = Date.now() - lastSnapshotSentTime;
3101
+ if (elapsed < DEVTOOLS_STALE_THRESHOLD_MS) return;
3102
+ debugLog("[FloTrace] DevTools hook stale (" + elapsed + "ms), falling back to DOM snapshot");
3103
+ }
3104
+ const root = findFiberRootFromDOM();
3105
+ if (root) {
3106
+ scheduleSnapshot(root);
3107
+ }
3108
+ }
3109
+ function requestFullSnapshot() {
3110
+ previousFlatTree = null;
3111
+ snapshotCounter = 0;
3112
+ diffSeq = 0;
3113
+ if (cachedFiberRoot) {
3114
+ scheduleSnapshot(cachedFiberRoot);
3115
+ }
3116
+ }
3117
+ function installFiberTreeWalker() {
3118
+ if (isInstalled4) {
3119
+ console.warn("[FloTrace] Fiber tree walker already installed");
3120
+ return () => uninstallFiberTreeWalker();
3121
+ }
3122
+ if (typeof window === "undefined") {
3123
+ console.warn(
3124
+ "[FloTrace] Not in browser environment, cannot install fiber tree walker"
3125
+ );
3126
+ return () => {
3127
+ };
3128
+ }
3129
+ isInstalled4 = true;
3130
+ try {
3131
+ const client4 = getWebSocketClient();
3132
+ installRscPayloadInterceptor(client4);
3133
+ } catch {
3134
+ }
3135
+ const hook = window.__REACT_DEVTOOLS_GLOBAL_HOOK__;
3136
+ if (hook && typeof hook.onCommitFiberRoot === "function") {
3137
+ originalOnCommitFiberRoot = hook.onCommitFiberRoot;
3138
+ hook.onCommitFiberRoot = (rendererID, root, priority) => {
3139
+ if (originalOnCommitFiberRoot) {
3140
+ try {
3141
+ originalOnCommitFiberRoot(rendererID, root, priority);
3142
+ } catch (error) {
3143
+ console.error(
3144
+ "[FloTrace] Error in original onCommitFiberRoot:",
3145
+ error
3146
+ );
3147
+ }
3148
+ }
3149
+ if (hookedRendererID === null) {
3150
+ hookedRendererID = rendererID;
3151
+ }
3152
+ if (rendererID !== hookedRendererID) return;
3153
+ try {
3154
+ const client4 = getWebSocketClient();
3155
+ if (client4.connected) {
3156
+ const triggers = peekTriggers();
3157
+ for (const trigger of triggers) {
3158
+ client4.sendImmediate({ type: "runtime:renderTrigger", trigger });
3159
+ }
3160
+ const cascade = analyzeCascade(root, triggers);
3161
+ if (cascade) {
3162
+ client4.sendImmediate({ type: "runtime:renderCascade", cascade });
3163
+ }
3164
+ wrapFiberDispatchers(root);
3165
+ clearTriggers();
3166
+ }
3167
+ } catch {
3168
+ }
3169
+ scheduleSnapshot(root);
3170
+ };
3171
+ activeStrategy = "devtools";
3172
+ console.log(
3173
+ "[FloTrace] Fiber tree walker installed (DevTools hook strategy)"
3174
+ );
3175
+ setTimeout(() => {
3176
+ try {
3177
+ const root = findFiberRootFromDOM();
3178
+ if (root) {
3179
+ scheduleSnapshot(root);
3180
+ }
3181
+ } catch (error) {
3182
+ console.error("[FloTrace] Error sending initial DevTools snapshot:", error);
3183
+ }
3184
+ }, 100);
3185
+ } else {
3186
+ activeStrategy = "dom";
3187
+ console.log(
3188
+ "[FloTrace] Fiber tree walker installed (DOM fallback strategy)"
3189
+ );
3190
+ setTimeout(() => {
3191
+ try {
3192
+ const root = findFiberRootFromDOM();
3193
+ if (root) {
3194
+ scheduleSnapshot(root);
3195
+ }
3196
+ } catch (error) {
3197
+ console.error("[FloTrace] Error sending initial DOM fallback snapshot:", error);
3198
+ }
3199
+ }, 100);
3200
+ }
3201
+ return () => uninstallFiberTreeWalker();
3202
+ }
3203
+ function getNodeProps(nodeId) {
3204
+ const fiber = fiberRefMap.get(nodeId);
3205
+ if (!fiber || !fiber.memoizedProps) {
3206
+ return null;
3207
+ }
3208
+ try {
3209
+ return serializeProps(fiber.memoizedProps);
3210
+ } catch (error) {
3211
+ console.error(`[FloTrace] Error serializing props for node "${nodeId}":`, error);
3212
+ return null;
3213
+ }
3214
+ }
3215
+ function detectDetailedRenderReason(fiber) {
3216
+ if (!fiber.alternate) return { type: "mount" };
3217
+ const prev = fiber.alternate;
3218
+ if (shallowPropsChanged(prev.memoizedProps, fiber.memoizedProps)) {
3219
+ const changedProps = diffProps(prev.memoizedProps, fiber.memoizedProps);
3220
+ return { type: "props-changed", changedProps };
3221
+ }
3222
+ const changedHookIndices = diffHookStates(prev.memoizedState, fiber.memoizedState);
3223
+ if (changedHookIndices.length > 0) {
3224
+ return { type: "state-changed", changedHookIndices };
3225
+ }
3226
+ const changedContexts = detectContextChanges(fiber);
3227
+ if (changedContexts.length > 0) {
3228
+ return { type: "context-changed", contextNames: changedContexts };
3229
+ }
3230
+ const parentName = fiber.return ? getComponentName2(fiber.return) : void 0;
3231
+ return { type: "parent-render", parentName };
3232
+ }
3233
+ function diffProps(prev, next) {
3234
+ const changes = [];
3235
+ if (!prev || !next) return changes;
3236
+ const allKeys = /* @__PURE__ */ new Set([...Object.keys(prev), ...Object.keys(next)]);
3237
+ for (const key of allKeys) {
3238
+ if (key === "children") continue;
3239
+ if (!Object.is(prev[key], next[key])) {
3240
+ changes.push({
3241
+ key,
3242
+ prev: serializeValue(prev[key], 0, /* @__PURE__ */ new WeakSet()),
3243
+ next: serializeValue(next[key], 0, /* @__PURE__ */ new WeakSet())
3244
+ });
3245
+ }
3246
+ }
3247
+ return changes;
3248
+ }
3249
+ function diffHookStates(prev, next) {
3250
+ const changed = [];
3251
+ let prevHook = prev;
3252
+ let nextHook = next;
3253
+ let index = 0;
3254
+ while (prevHook && nextHook) {
3255
+ if (prevHook.queue !== null || nextHook.queue !== null) {
3256
+ if (!Object.is(prevHook.memoizedState, nextHook.memoizedState)) {
3257
+ changed.push(index);
3258
+ }
3259
+ }
3260
+ prevHook = prevHook.next;
3261
+ nextHook = nextHook.next;
3262
+ index++;
3263
+ }
3264
+ return changed;
3265
+ }
3266
+ function detectContextChanges(fiber) {
3267
+ const changed = [];
3268
+ if (!fiber.dependencies?.firstContext) return changed;
3269
+ let ctx = fiber.dependencies.firstContext;
3270
+ while (ctx) {
3271
+ try {
3272
+ if (!Object.is(ctx.memoizedValue, ctx.context._currentValue)) {
3273
+ const name = ctx.context.displayName || "UnknownContext";
3274
+ changed.push(name);
3275
+ }
3276
+ } catch {
3277
+ }
3278
+ ctx = ctx.next;
3279
+ }
3280
+ return changed;
3281
+ }
3282
+ function getDetailedRenderReason(nodeId) {
3283
+ const fiber = fiberRefMap.get(nodeId);
3284
+ if (!fiber) return null;
3285
+ try {
3286
+ return detectDetailedRenderReason(fiber);
3287
+ } catch (error) {
3288
+ console.error(`[FloTrace] Error detecting render reason for "${nodeId}":`, error);
3289
+ return null;
3290
+ }
3291
+ }
3292
+ function getNodeHooks(nodeId) {
3293
+ const fiber = fiberRefMap.get(nodeId);
3294
+ if (!fiber) return null;
3295
+ try {
3296
+ return inspectHooks(fiber);
3297
+ } catch (error) {
3298
+ console.error(`[FloTrace] Error inspecting hooks for node "${nodeId}":`, error);
3299
+ return null;
3300
+ }
3301
+ }
3302
+ function getNodeEffects(nodeId) {
3303
+ const fiber = fiberRefMap.get(nodeId);
3304
+ if (!fiber) return null;
3305
+ try {
3306
+ return inspectEffects(fiber);
3307
+ } catch (error) {
3308
+ console.error(`[FloTrace] Error inspecting effects for node "${nodeId}":`, error);
3309
+ return null;
3310
+ }
3311
+ }
3312
+ function getFiberRefMap() {
3313
+ return fiberRefMap;
3314
+ }
3315
+ function uninstallFiberTreeWalker() {
3316
+ if (!isInstalled4) return;
3317
+ if (throttleTimer) {
3318
+ clearTimeout(throttleTimer);
3319
+ throttleTimer = null;
3320
+ }
3321
+ if (maxWaitTimer) {
3322
+ clearTimeout(maxWaitTimer);
3323
+ maxWaitTimer = null;
3324
+ }
3325
+ cachedFiberRoot = null;
3326
+ if (activeStrategy === "devtools" && typeof window !== "undefined") {
3327
+ const hook = window.__REACT_DEVTOOLS_GLOBAL_HOOK__;
3328
+ if (hook) {
3329
+ if (originalOnCommitFiberRoot) {
3330
+ hook.onCommitFiberRoot = originalOnCommitFiberRoot;
3331
+ } else {
3332
+ delete hook.onCommitFiberRoot;
3333
+ }
3334
+ }
3335
+ }
3336
+ originalOnCommitFiberRoot = null;
3337
+ hookedRendererID = null;
3338
+ activeStrategy = null;
3339
+ fiberRefMap = /* @__PURE__ */ new Map();
3340
+ previousFlatTree = null;
3341
+ snapshotCounter = 0;
3342
+ diffSeq = 0;
3343
+ lastSnapshotSentTime = 0;
3344
+ isInstalled4 = false;
3345
+ try {
3346
+ uninstallRscPayloadInterceptor();
3347
+ } catch {
3348
+ }
3349
+ clearActionStateCache();
3350
+ resetNextjsDetection();
3351
+ console.log("[FloTrace] Fiber tree walker uninstalled");
3352
+ }
3353
+
3354
+ // src/storeUtils.ts
3355
+ function serializeStoreState(state, logPrefix) {
3356
+ const serialized = {};
3357
+ for (const [key, value] of Object.entries(state)) {
3358
+ try {
3359
+ serialized[key] = serializeValue(value);
3360
+ } catch (error) {
3361
+ console.error(`[FloTrace] Error serializing ${logPrefix} key "${key}":`, error);
3362
+ serialized[key] = { __type: "error", value: "Serialization failed" };
3363
+ }
3364
+ }
3365
+ return serialized;
3366
+ }
3367
+ function buildCorrelatedRequests(state, changedKeys) {
3368
+ const byRequestId = /* @__PURE__ */ new Map();
3369
+ for (const key of changedKeys) {
3370
+ try {
3371
+ const rid = findFetchOrigin(state[key]);
3372
+ if (rid) {
3373
+ const keys = byRequestId.get(rid) ?? [];
3374
+ keys.push(key);
3375
+ byRequestId.set(rid, keys);
3376
+ }
3377
+ } catch {
3378
+ }
3379
+ }
3380
+ if (byRequestId.size === 0) return void 0;
3381
+ return Array.from(byRequestId, ([requestId, storeKeys]) => ({ requestId, storeKeys }));
3382
+ }
3383
+
3384
+ // src/zustandTracker.ts
3385
+ var activeUnsubscribers = [];
3386
+ var isInstalled5 = false;
3387
+ var debounceTimers = /* @__PURE__ */ new Map();
3388
+ var DEBOUNCE_MS = 200;
3389
+ function installZustandTracker(stores, client4) {
3390
+ if (isInstalled5) {
3391
+ console.warn("[FloTrace] Zustand tracker already installed, reinstalling");
3392
+ uninstallZustandTracker();
3393
+ }
3394
+ isInstalled5 = true;
3395
+ console.log("[FloTrace] Installing Zustand tracker for stores:", Object.keys(stores));
3396
+ for (const [storeName, store] of Object.entries(stores)) {
3397
+ if (!store || typeof store !== "object" && typeof store !== "function" || typeof store.getState !== "function" || typeof store.subscribe !== "function") {
3398
+ console.warn(
3399
+ `[FloTrace] Skipping "${storeName}" \u2014 not a valid Zustand store (missing getState/subscribe). Ensure you pass Zustand stores like: stores={{ myStore: useMyStore }}`
3400
+ );
3401
+ continue;
3402
+ }
3403
+ try {
3404
+ const initialState = store.getState();
3405
+ sendStoreUpdate(storeName, initialState, Object.keys(initialState), client4);
3406
+ const unsubscribe = store.subscribe((newState, prevState) => {
3407
+ try {
3408
+ scheduleStoreUpdate(storeName, prevState, newState, client4);
3409
+ } catch (error) {
3410
+ console.error(`[FloTrace] Error in Zustand subscribe callback for "${storeName}":`, error);
3411
+ }
3412
+ });
3413
+ activeUnsubscribers.push(unsubscribe);
3414
+ } catch (error) {
3415
+ console.error(`[FloTrace] Failed to install tracker for Zustand store "${storeName}":`, error);
3416
+ }
3417
+ }
3418
+ }
3419
+ function uninstallZustandTracker() {
3420
+ if (!isInstalled5) return;
3421
+ for (const timer of debounceTimers.values()) {
3422
+ clearTimeout(timer);
3423
+ }
3424
+ debounceTimers.clear();
3425
+ for (const unsubscribe of activeUnsubscribers) {
3426
+ try {
3427
+ unsubscribe();
3428
+ } catch (error) {
3429
+ console.error("[FloTrace] Error unsubscribing from Zustand store:", error);
3430
+ }
3431
+ }
3432
+ activeUnsubscribers = [];
3433
+ isInstalled5 = false;
3434
+ console.log("[FloTrace] Zustand tracker uninstalled");
3435
+ }
3436
+ function scheduleStoreUpdate(storeName, prevState, newState, client4) {
3437
+ let changedKeys;
3438
+ try {
3439
+ changedKeys = getChangedKeys(prevState, newState);
3440
+ } catch (error) {
3441
+ console.error(`[FloTrace] Error diffing Zustand state for "${storeName}":`, error);
3442
+ return;
3443
+ }
3444
+ if (changedKeys.length === 0) return;
3445
+ const existing = debounceTimers.get(storeName);
3446
+ if (existing) clearTimeout(existing);
3447
+ debounceTimers.set(storeName, setTimeout(() => {
3448
+ debounceTimers.delete(storeName);
3449
+ sendStoreUpdate(storeName, newState, changedKeys, client4);
3450
+ }, DEBOUNCE_MS));
3451
+ }
3452
+ function sendStoreUpdate(storeName, state, changedKeys, client4) {
3453
+ try {
3454
+ if (!client4.connected) return;
3455
+ client4.sendImmediate({
3456
+ type: "runtime:zustand",
3457
+ storeName,
3458
+ state: serializeStoreState(state, `Zustand "${storeName}"`),
3459
+ changedKeys,
3460
+ correlatedRequests: buildCorrelatedRequests(state, changedKeys),
3461
+ timestamp: Date.now()
3462
+ });
3463
+ } catch (error) {
3464
+ console.error(`[FloTrace] Error sending Zustand update for "${storeName}":`, error);
3465
+ }
3466
+ }
3467
+
3468
+ // src/reduxTracker.ts
3469
+ var activeUnsubscribe = null;
3470
+ var isInstalled6 = false;
3471
+ var debounceTimer = null;
3472
+ var previousState = null;
3473
+ var DEBOUNCE_MS2 = 200;
3474
+ function isReduxStore(obj) {
3475
+ return typeof obj === "object" && obj !== null && typeof obj.getState === "function" && typeof obj.subscribe === "function" && typeof obj.dispatch === "function";
3476
+ }
3477
+ function installReduxTracker(store, client4) {
3478
+ if (isInstalled6) {
3479
+ console.warn("[FloTrace] Redux tracker already installed, reinstalling");
3480
+ uninstallReduxTracker();
3481
+ }
3482
+ isInstalled6 = true;
3483
+ console.log("[FloTrace] Installing Redux tracker");
3484
+ try {
3485
+ const initialState = store.getState();
3486
+ previousState = initialState;
3487
+ sendReduxUpdate(initialState, Object.keys(initialState), client4);
3488
+ activeUnsubscribe = store.subscribe(() => {
3489
+ try {
3490
+ const newState = store.getState();
3491
+ scheduleReduxUpdate(newState, client4);
3492
+ } catch (error) {
3493
+ console.error("[FloTrace] Error in Redux subscribe callback:", error);
3494
+ }
3495
+ });
3496
+ } catch (error) {
3497
+ console.error("[FloTrace] Failed to install Redux tracker:", error);
3498
+ isInstalled6 = false;
3499
+ }
3500
+ }
3501
+ function uninstallReduxTracker() {
3502
+ if (!isInstalled6) return;
3503
+ if (debounceTimer) {
3504
+ clearTimeout(debounceTimer);
3505
+ debounceTimer = null;
3506
+ }
3507
+ if (activeUnsubscribe) {
3508
+ try {
3509
+ activeUnsubscribe();
3510
+ } catch (error) {
3511
+ console.error("[FloTrace] Error unsubscribing from Redux store:", error);
3512
+ }
3513
+ activeUnsubscribe = null;
3514
+ }
3515
+ previousState = null;
3516
+ isInstalled6 = false;
3517
+ console.log("[FloTrace] Redux tracker uninstalled");
3518
+ }
3519
+ function scheduleReduxUpdate(newState, client4) {
3520
+ let changedKeys;
3521
+ try {
3522
+ changedKeys = getChangedKeys(previousState ?? {}, newState);
3523
+ } catch (error) {
3524
+ console.error("[FloTrace] Error diffing Redux state:", error);
3525
+ return;
3526
+ }
3527
+ if (changedKeys.length === 0) return;
3528
+ previousState = newState;
3529
+ if (debounceTimer) clearTimeout(debounceTimer);
3530
+ debounceTimer = setTimeout(() => {
3531
+ debounceTimer = null;
3532
+ sendReduxUpdate(newState, changedKeys, client4);
3533
+ }, DEBOUNCE_MS2);
3534
+ }
3535
+ function sendReduxUpdate(state, changedKeys, client4) {
3536
+ try {
3537
+ if (!client4.connected) return;
3538
+ client4.sendImmediate({
3539
+ type: "runtime:redux",
3540
+ state: serializeStoreState(state, "Redux"),
3541
+ changedKeys,
3542
+ correlatedRequests: buildCorrelatedRequests(state, changedKeys),
3543
+ timestamp: Date.now()
3544
+ });
3545
+ } catch (error) {
3546
+ console.error("[FloTrace] Error sending Redux update:", error);
3547
+ }
3548
+ }
3549
+
3550
+ // src/tanstackQueryTracker.ts
3551
+ var isInstalled7 = false;
3552
+ var queryUnsubscribe = null;
3553
+ var mutationUnsubscribe = null;
3554
+ var debounceTimer2 = null;
3555
+ var DEBOUNCE_MS3 = 300;
3556
+ var MAX_EVENTS_PER_QUERY = 50;
3557
+ var queryTracking = /* @__PURE__ */ new Map();
3558
+ var CORRELATION_WINDOW_MS = 500;
3559
+ var MAX_COMPLETED_CORRELATIONS = 20;
3560
+ var correlationCounter = 0;
3561
+ var pendingCorrelations = /* @__PURE__ */ new Map();
3562
+ var completedCorrelations = [];
3563
+ var mutationPrevStatus = /* @__PURE__ */ new Map();
3564
+ var mutationCorrelationMap = /* @__PURE__ */ new Map();
3565
+ function isTanStackQueryClient(obj) {
3566
+ if (!obj || typeof obj !== "object") return false;
3567
+ const candidate = obj;
3568
+ return typeof candidate.getQueryCache === "function" && typeof candidate.getMutationCache === "function";
3569
+ }
3570
+ function installTanStackQueryTracker(queryClient, client4) {
3571
+ if (isInstalled7) {
3572
+ console.warn("[FloTrace] TanStack Query tracker already installed, reinstalling");
3573
+ uninstallTanStackQueryTracker();
3574
+ }
3575
+ isInstalled7 = true;
3576
+ console.log("[FloTrace] Installing TanStack Query tracker");
3577
+ try {
3578
+ const queryCache = queryClient.getQueryCache();
3579
+ const mutationCache = queryClient.getMutationCache();
3580
+ for (const query of queryCache.getAll()) {
3581
+ if (!queryTracking.has(query.queryHash)) {
3582
+ initQueryTracking(query);
3583
+ }
3584
+ }
3585
+ for (const mutation of mutationCache.getAll()) {
3586
+ mutationPrevStatus.set(mutation.mutationId, mutation.state.status);
3587
+ }
3588
+ sendSnapshot(queryCache, mutationCache, client4);
3589
+ queryUnsubscribe = queryCache.subscribe((event) => {
3590
+ try {
3591
+ if (event.type === "added" || event.type === "removed" || event.type === "updated") {
3592
+ if (event.query) {
3593
+ updateQueryTracking(event.query, event.type);
3594
+ }
3595
+ scheduleSnapshot2(queryCache, mutationCache, client4);
3596
+ }
3597
+ } catch (error) {
3598
+ console.error("[FloTrace] Error in TanStack Query cache subscribe callback:", error);
3599
+ }
3600
+ });
3601
+ mutationUnsubscribe = mutationCache.subscribe((event) => {
3602
+ try {
3603
+ if (event.mutation) {
3604
+ updateMutationTracking(event.mutation, queryCache, mutationCache, client4);
3605
+ }
3606
+ scheduleSnapshot2(queryCache, mutationCache, client4);
3607
+ } catch (error) {
3608
+ console.error("[FloTrace] Error in TanStack Mutation cache subscribe callback:", error);
3609
+ }
3610
+ });
3611
+ } catch (error) {
3612
+ console.error("[FloTrace] Failed to install TanStack Query tracker:", error);
3613
+ isInstalled7 = false;
3614
+ }
3615
+ }
3616
+ function uninstallTanStackQueryTracker() {
3617
+ if (!isInstalled7) return;
3618
+ if (debounceTimer2) {
3619
+ clearTimeout(debounceTimer2);
3620
+ debounceTimer2 = null;
3621
+ }
3622
+ if (queryUnsubscribe) {
3623
+ try {
3624
+ queryUnsubscribe();
3625
+ } catch (e) {
3626
+ console.error("[FloTrace] Error unsubscribing from QueryCache:", e);
3627
+ }
3628
+ queryUnsubscribe = null;
3629
+ }
3630
+ if (mutationUnsubscribe) {
3631
+ try {
3632
+ mutationUnsubscribe();
3633
+ } catch (e) {
3634
+ console.error("[FloTrace] Error unsubscribing from MutationCache:", e);
3635
+ }
3636
+ mutationUnsubscribe = null;
3637
+ }
3638
+ for (const pending of pendingCorrelations.values()) {
3639
+ clearTimeout(pending.timeoutId);
3640
+ }
3641
+ pendingCorrelations.clear();
3642
+ isInstalled7 = false;
3643
+ console.log("[FloTrace] TanStack Query tracker uninstalled");
3644
+ }
3645
+ function computeDataHash(data) {
3646
+ if (data === null || data === void 0) return "__null__";
3647
+ try {
3648
+ return JSON.stringify(data);
3649
+ } catch {
3650
+ return "__unhashable__";
3651
+ }
3652
+ }
3653
+ function initQueryTracking(query) {
3654
+ const state = {
3655
+ lastDataHash: computeDataHash(query.state.data),
3656
+ lastDataUpdatedAt: query.state.dataUpdatedAt,
3657
+ prevStatus: query.state.status,
3658
+ prevFetchStatus: query.state.fetchStatus,
3659
+ totalFetchCount: 0,
3660
+ wastedRefetchCount: 0,
3661
+ events: []
3662
+ };
3663
+ queryTracking.set(query.queryHash, state);
3664
+ return state;
3665
+ }
3666
+ function updateQueryTracking(query, eventType) {
3667
+ let tracking = queryTracking.get(query.queryHash);
3668
+ if (eventType === "removed") {
3669
+ queryTracking.delete(query.queryHash);
3670
+ return;
3671
+ }
3672
+ if (!tracking) {
3673
+ tracking = initQueryTracking(query);
3674
+ }
3675
+ const currentStatus = query.state.status;
3676
+ const currentFetchStatus = query.state.fetchStatus;
3677
+ const statusChanged = tracking.prevStatus !== currentStatus;
3678
+ const fetchStatusChanged = tracking.prevFetchStatus !== currentFetchStatus;
3679
+ if (statusChanged || fetchStatusChanged) {
3680
+ const currentDataHash = computeDataHash(query.state.data);
3681
+ const dataChanged = currentDataHash !== tracking.lastDataHash;
3682
+ const event = {
3683
+ timestamp: Date.now(),
3684
+ fromStatus: tracking.prevStatus,
3685
+ toStatus: currentStatus,
3686
+ fromFetchStatus: tracking.prevFetchStatus,
3687
+ toFetchStatus: currentFetchStatus,
3688
+ dataChanged
3689
+ };
3690
+ tracking.events.push(event);
3691
+ if (tracking.events.length > MAX_EVENTS_PER_QUERY) {
3692
+ tracking.events.shift();
3693
+ }
3694
+ if (tracking.prevFetchStatus === "fetching" && currentFetchStatus === "idle" && currentStatus === "success") {
3695
+ tracking.totalFetchCount++;
3696
+ if (!dataChanged) {
3697
+ tracking.wastedRefetchCount++;
3698
+ }
3699
+ tracking.lastDataHash = currentDataHash;
3700
+ tracking.lastDataUpdatedAt = query.state.dataUpdatedAt;
3701
+ if (query.state.data !== null && query.state.data !== void 0) {
3702
+ const rid = findFetchOrigin(query.state.data);
3703
+ if (rid) tracking.pendingCorrelationId = rid;
3704
+ }
3705
+ }
3706
+ if (tracking.prevFetchStatus === "idle" && currentFetchStatus === "fetching") {
3707
+ const now = Date.now();
3708
+ for (const pending of pendingCorrelations.values()) {
3709
+ if (pending.idleQueryHashes.has(query.queryHash)) {
3710
+ pending.affectedQueries.set(query.queryHash, {
3711
+ fetchStartedAt: now,
3712
+ queryKey: query.queryKey
3713
+ });
3714
+ }
3715
+ }
3716
+ }
3717
+ tracking.prevStatus = currentStatus;
3718
+ tracking.prevFetchStatus = currentFetchStatus;
3719
+ }
3720
+ }
3721
+ function openCorrelationWindow(mutation, queryCache, mutationCache, client4) {
3722
+ const correlationId = `corr-${++correlationCounter}`;
3723
+ const now = Date.now();
3724
+ const idleQueryHashes = /* @__PURE__ */ new Set();
3725
+ for (const query of queryCache.getAll()) {
3726
+ if (query.state.fetchStatus === "idle") {
3727
+ idleQueryHashes.add(query.queryHash);
3728
+ }
3729
+ }
3730
+ const timeoutId = setTimeout(() => {
3731
+ resolveCorrelation(correlationId, queryCache, mutationCache, client4);
3732
+ }, CORRELATION_WINDOW_MS);
3733
+ pendingCorrelations.set(correlationId, {
3734
+ correlationId,
3735
+ mutationId: mutation.mutationId,
3736
+ mutationKey: mutation.options.mutationKey,
3737
+ completedAt: now,
3738
+ idleQueryHashes,
3739
+ affectedQueries: /* @__PURE__ */ new Map(),
3740
+ timeoutId
3741
+ });
3742
+ mutationCorrelationMap.set(mutation.mutationId, correlationId);
3743
+ }
3744
+ function resolveCorrelation(correlationId, queryCache, mutationCache, client4) {
3745
+ const pending = pendingCorrelations.get(correlationId);
3746
+ if (!pending) return;
3747
+ pendingCorrelations.delete(correlationId);
3748
+ if (pending.affectedQueries.size === 0) return;
3749
+ const affectedQueries = [];
3750
+ for (const [queryHash, info] of pending.affectedQueries) {
3751
+ const tracking = queryTracking.get(queryHash);
3752
+ let queryKeySerialized;
3753
+ try {
3754
+ queryKeySerialized = serializeValue(info.queryKey);
3755
+ } catch {
3756
+ queryKeySerialized = "[serialization failed]";
3757
+ }
3758
+ affectedQueries.push({
3759
+ queryHash,
3760
+ queryKey: queryKeySerialized,
3761
+ fetchStartedAt: info.fetchStartedAt,
3762
+ latencyMs: info.fetchStartedAt - pending.completedAt,
3763
+ // dataChanged is resolved from the latest tracking state if the fetch completed
3764
+ dataChanged: tracking?.events.length ? tracking.events[tracking.events.length - 1].dataChanged : void 0
3765
+ });
3766
+ }
3767
+ let mutationKeySerialized;
3768
+ if (pending.mutationKey) {
3769
+ try {
3770
+ mutationKeySerialized = serializeValue(pending.mutationKey);
3771
+ } catch {
3772
+ mutationKeySerialized = "[serialization failed]";
3773
+ }
3774
+ }
3775
+ const correlation = {
3776
+ correlationId,
3777
+ mutationId: pending.mutationId,
3778
+ mutationKey: mutationKeySerialized,
3779
+ mutationCompletedAt: pending.completedAt,
3780
+ affectedQueries,
3781
+ resolvedAt: Date.now()
3782
+ };
3783
+ completedCorrelations.push(correlation);
3784
+ if (completedCorrelations.length > MAX_COMPLETED_CORRELATIONS) {
3785
+ completedCorrelations = completedCorrelations.slice(-MAX_COMPLETED_CORRELATIONS);
3786
+ }
3787
+ scheduleSnapshot2(queryCache, mutationCache, client4);
3788
+ }
3789
+ function updateMutationTracking(mutation, queryCache, mutationCache, client4) {
3790
+ const currentStatus = mutation.state.status;
3791
+ const prevStatus = mutationPrevStatus.get(mutation.mutationId);
3792
+ mutationPrevStatus.set(mutation.mutationId, currentStatus);
3793
+ if (prevStatus && prevStatus !== "success" && currentStatus === "success") {
3794
+ openCorrelationWindow(mutation, queryCache, mutationCache, client4);
3795
+ }
3796
+ }
3797
+ function scheduleSnapshot2(queryCache, mutationCache, client4) {
3798
+ if (debounceTimer2) clearTimeout(debounceTimer2);
3799
+ debounceTimer2 = setTimeout(() => {
3800
+ debounceTimer2 = null;
3801
+ sendSnapshot(queryCache, mutationCache, client4);
3802
+ }, DEBOUNCE_MS3);
3803
+ }
3804
+ function serializeQueryData(data) {
3805
+ if (data === null || data === void 0) return null;
3806
+ try {
3807
+ return serializeValue(data);
3808
+ } catch {
3809
+ return { __type: "truncated", originalType: typeof data };
3810
+ }
3811
+ }
3812
+ function extractErrorMessage(error) {
3813
+ try {
3814
+ return error instanceof Error ? error.message : String(error);
3815
+ } catch {
3816
+ return "Unknown error";
3817
+ }
3818
+ }
3819
+ function serializeQuery(query) {
3820
+ let queryKeySerialized;
3821
+ try {
3822
+ queryKeySerialized = serializeValue(query.queryKey);
3823
+ } catch {
3824
+ queryKeySerialized = "[serialization failed]";
3825
+ }
3826
+ const errorMessage = query.state.error ? extractErrorMessage(query.state.error) : void 0;
3827
+ const tracking = queryTracking.get(query.queryHash);
3828
+ const correlatedRequestId = tracking?.pendingCorrelationId;
3829
+ if (correlatedRequestId && tracking) {
3830
+ tracking.pendingCorrelationId = void 0;
3831
+ }
3832
+ return {
3833
+ queryKey: queryKeySerialized,
3834
+ queryHash: query.queryHash,
3835
+ status: query.state.status,
3836
+ fetchStatus: query.state.fetchStatus,
3837
+ dataUpdatedAt: query.state.dataUpdatedAt,
3838
+ errorUpdatedAt: query.state.errorUpdatedAt,
3839
+ isInvalidated: query.state.isInvalidated,
3840
+ isStale: safeCall(() => query.isStale(), false),
3841
+ isActive: safeCall(() => query.isActive(), false),
3842
+ isDisabled: safeCall(() => query.isDisabled(), false),
3843
+ failureCount: query.state.fetchFailureCount,
3844
+ errorMessage,
3845
+ observerCount: safeCall(() => query.getObserversCount(), 0),
3846
+ staleTime: query.options.staleTime,
3847
+ gcTime: query.options.gcTime,
3848
+ // Phase 1: additional config for health analysis
3849
+ refetchInterval: query.options.refetchInterval,
3850
+ refetchOnWindowFocus: query.options.refetchOnWindowFocus,
3851
+ refetchOnMount: query.options.refetchOnMount,
3852
+ refetchOnReconnect: query.options.refetchOnReconnect,
3853
+ networkMode: query.options.networkMode,
3854
+ enabled: query.options.enabled,
3855
+ retry: query.options.retry,
3856
+ dataShape: serializeQueryData(query.state.data),
3857
+ // Phase 2: wasted refetch tracking
3858
+ wastedRefetchCount: tracking?.wastedRefetchCount,
3859
+ totalFetchCount: tracking?.totalFetchCount,
3860
+ // Phase 3: query timeline
3861
+ events: tracking?.events.length ? [...tracking.events] : void 0,
3862
+ correlatedRequestId
3863
+ };
3864
+ }
3865
+ function serializeMutation(mutation) {
3866
+ const errorMessage = mutation.state.error ? extractErrorMessage(mutation.state.error) : void 0;
3867
+ let mutationKey;
3868
+ if (mutation.options.mutationKey) {
3869
+ try {
3870
+ mutationKey = serializeValue(mutation.options.mutationKey);
3871
+ } catch {
3872
+ mutationKey = "[serialization failed]";
3873
+ }
3874
+ }
3875
+ return {
3876
+ mutationId: mutation.mutationId,
3877
+ status: mutation.state.status,
3878
+ isPaused: mutation.state.isPaused,
3879
+ submittedAt: mutation.state.submittedAt,
3880
+ failureCount: mutation.state.failureCount,
3881
+ errorMessage,
3882
+ mutationKey,
3883
+ scope: mutation.options.scope?.id,
3884
+ lastCorrelationId: mutationCorrelationMap.get(mutation.mutationId)
3885
+ };
3886
+ }
3887
+ function sendSnapshot(queryCache, mutationCache, client4) {
3888
+ try {
3889
+ if (!client4.connected) return;
3890
+ const queries = [];
3891
+ for (const query of queryCache.getAll()) {
3892
+ try {
3893
+ queries.push(serializeQuery(query));
3894
+ } catch (error) {
3895
+ console.error(`[FloTrace] Error serializing query "${query.queryHash}":`, error);
3896
+ }
3897
+ }
3898
+ const mutations = [];
3899
+ const activeMutationIds = /* @__PURE__ */ new Set();
3900
+ for (const mutation of mutationCache.getAll()) {
3901
+ try {
3902
+ activeMutationIds.add(mutation.mutationId);
3903
+ mutations.push(serializeMutation(mutation));
3904
+ } catch (error) {
3905
+ console.error(`[FloTrace] Error serializing mutation ${mutation.mutationId}:`, error);
3906
+ }
3907
+ }
3908
+ for (const id of mutationPrevStatus.keys()) {
3909
+ if (!activeMutationIds.has(id)) {
3910
+ mutationPrevStatus.delete(id);
3911
+ mutationCorrelationMap.delete(id);
3912
+ }
3913
+ }
3914
+ const correlations = completedCorrelations.length > 0 ? [...completedCorrelations] : void 0;
3915
+ if (correlations) {
3916
+ completedCorrelations = [];
3917
+ }
3918
+ client4.sendImmediate({
3919
+ type: "runtime:tanstackQuery",
3920
+ queries,
3921
+ mutations,
3922
+ correlations,
3923
+ timestamp: Date.now()
3924
+ });
3925
+ } catch (error) {
3926
+ console.error("[FloTrace] Error sending TanStack Query snapshot:", error);
3927
+ }
3928
+ }
3929
+ function safeCall(fn, fallback) {
3930
+ try {
3931
+ return fn();
3932
+ } catch {
3933
+ return fallback;
3934
+ }
3935
+ }
3936
+
3937
+ // src/routerTracker.ts
3938
+ var isInstalled8 = false;
3939
+ var debounceTimer3 = null;
3940
+ var client3 = null;
3941
+ var originalPushState = null;
3942
+ var originalReplaceState = null;
3943
+ var popstateHandler = null;
3944
+ var DEBOUNCE_MS4 = 200;
3945
+ function installRouterTracker(wsClient) {
3946
+ if (isInstalled8) {
3947
+ console.warn("[FloTrace] Router tracker already installed, reinstalling");
3948
+ uninstallRouterTracker();
3949
+ }
3950
+ if (typeof window === "undefined" || typeof history === "undefined") {
3951
+ console.warn("[FloTrace] Router tracker requires a browser environment");
3952
+ return;
3953
+ }
3954
+ console.log("[FloTrace] Installing router tracker");
3955
+ try {
3956
+ isInstalled8 = true;
3957
+ client3 = wsClient;
3958
+ originalPushState = history.pushState.bind(history);
3959
+ originalReplaceState = history.replaceState.bind(history);
3960
+ history.pushState = function(data, unused, url) {
3961
+ originalPushState(data, unused, url);
3962
+ try {
3963
+ scheduleRouterUpdate();
3964
+ } catch (error) {
3965
+ console.error("[FloTrace] Error in pushState handler:", error);
3966
+ }
3967
+ };
3968
+ history.replaceState = function(data, unused, url) {
3969
+ originalReplaceState(data, unused, url);
3970
+ try {
3971
+ scheduleRouterUpdate();
3972
+ } catch (error) {
3973
+ console.error("[FloTrace] Error in replaceState handler:", error);
3974
+ }
3975
+ };
3976
+ popstateHandler = () => {
3977
+ try {
3978
+ scheduleRouterUpdate();
3979
+ } catch (error) {
3980
+ console.error("[FloTrace] Error in popstate handler:", error);
3981
+ }
3982
+ };
3983
+ window.addEventListener("popstate", popstateHandler);
3984
+ sendRouterUpdate();
3985
+ } catch (error) {
3986
+ console.error("[FloTrace] Failed to install router tracker:", error);
3987
+ try {
3988
+ uninstallRouterTracker();
3989
+ } catch (_) {
3990
+ }
3991
+ }
3992
+ }
3993
+ function uninstallRouterTracker() {
3994
+ if (!isInstalled8) return;
3995
+ if (debounceTimer3) {
3996
+ clearTimeout(debounceTimer3);
3997
+ debounceTimer3 = null;
3998
+ }
3999
+ try {
4000
+ if (originalPushState) {
4001
+ history.pushState = originalPushState;
4002
+ originalPushState = null;
4003
+ }
4004
+ } catch (error) {
4005
+ console.error("[FloTrace] Error restoring pushState:", error);
4006
+ }
4007
+ try {
4008
+ if (originalReplaceState) {
4009
+ history.replaceState = originalReplaceState;
4010
+ originalReplaceState = null;
4011
+ }
4012
+ } catch (error) {
4013
+ console.error("[FloTrace] Error restoring replaceState:", error);
4014
+ }
4015
+ try {
4016
+ if (popstateHandler) {
4017
+ window.removeEventListener("popstate", popstateHandler);
4018
+ popstateHandler = null;
4019
+ }
4020
+ } catch (error) {
4021
+ console.error("[FloTrace] Error removing popstate listener:", error);
4022
+ }
4023
+ client3 = null;
4024
+ isInstalled8 = false;
4025
+ console.log("[FloTrace] Router tracker uninstalled");
4026
+ }
4027
+ function scheduleRouterUpdate() {
4028
+ if (debounceTimer3) clearTimeout(debounceTimer3);
4029
+ debounceTimer3 = setTimeout(() => {
4030
+ debounceTimer3 = null;
4031
+ sendRouterUpdate();
4032
+ }, DEBOUNCE_MS4);
4033
+ }
4034
+ function sendRouterUpdate() {
4035
+ try {
4036
+ if (!client3?.connected) return;
4037
+ const pathname = window.location.pathname;
4038
+ const searchParams = {};
4039
+ const urlSearchParams = new URLSearchParams(window.location.search);
4040
+ for (const [key, value] of urlSearchParams.entries()) {
4041
+ searchParams[key] = value;
4042
+ }
4043
+ client3.sendImmediate({
4044
+ type: "runtime:router",
4045
+ pathname,
4046
+ // Matched route params (e.g., :id) are not available from the History API.
4047
+ // Future enhancement: extract from React Router's fiber context.
4048
+ params: {},
4049
+ searchParams,
4050
+ timestamp: Date.now()
4051
+ });
4052
+ } catch (error) {
4053
+ console.error("[FloTrace] Error sending router update:", error);
4054
+ }
4055
+ }
4056
+
4057
+ // src/FloTraceProvider.tsx
4058
+ var import_jsx_runtime = require("react/jsx-runtime");
4059
+ var pendingCleanupTimer = null;
4060
+ function safeTrackerOp(name, op) {
4061
+ try {
4062
+ op();
4063
+ } catch (error) {
4064
+ console.error(`[FloTrace] ${name}:`, error);
4065
+ }
4066
+ }
4067
+ var FloTraceContext = (0, import_react.createContext)(null);
4068
+ function useFloTrace() {
4069
+ return (0, import_react.useContext)(FloTraceContext);
4070
+ }
4071
+ function FloTraceProvider({ children, config = {}, stores, reduxStore, queryClient }) {
4072
+ const mergedConfig = { ...DEFAULT_CONFIG, ...config };
4073
+ const [connected, setConnected] = import_react.default.useState(false);
4074
+ const trackingOptionsRef = (0, import_react.useRef)({});
4075
+ const storesRef = (0, import_react.useRef)(stores);
4076
+ storesRef.current = stores;
4077
+ const reduxStoreRef = (0, import_react.useRef)(reduxStore);
4078
+ reduxStoreRef.current = reduxStore;
4079
+ const queryClientRef = (0, import_react.useRef)(queryClient);
4080
+ queryClientRef.current = queryClient;
4081
+ if (mergedConfig.enabled && typeof window !== "undefined") {
4082
+ getWebSocketClient(mergedConfig);
4083
+ installFiberTreeWalker();
4084
+ prewarmNetworkTracker();
4085
+ }
4086
+ (0, import_react.useEffect)(() => {
4087
+ if (!mergedConfig.enabled) {
4088
+ return;
4089
+ }
4090
+ if (pendingCleanupTimer) {
4091
+ clearTimeout(pendingCleanupTimer);
4092
+ pendingCleanupTimer = null;
4093
+ }
4094
+ const client4 = getWebSocketClient();
4095
+ const unsubConnection = client4.onConnectionChange((isConnected) => {
4096
+ setConnected(isConnected);
4097
+ if (isConnected) {
4098
+ requestFullSnapshot();
4099
+ }
4100
+ });
4101
+ const unsubMessage = client4.onMessage((message) => {
4102
+ try {
4103
+ switch (message.type) {
4104
+ case "ext:ping":
4105
+ client4.sendImmediate({ type: "runtime:ready", appName: mergedConfig.appName });
4106
+ break;
4107
+ case "ext:startTracking":
4108
+ trackingOptionsRef.current = message.options || {};
4109
+ if (message.options?.trackZustand && storesRef.current && Object.keys(storesRef.current).length > 0) {
4110
+ safeTrackerOp("Zustand install", () => installZustandTracker(storesRef.current, client4));
4111
+ }
4112
+ if (message.options?.trackRedux && reduxStoreRef.current) {
4113
+ safeTrackerOp("Redux install", () => installReduxTracker(reduxStoreRef.current, client4));
4114
+ }
4115
+ if (message.options?.trackTanstackQuery && queryClientRef.current) {
4116
+ safeTrackerOp("TanStack Query install", () => installTanStackQueryTracker(queryClientRef.current, client4));
4117
+ }
4118
+ if (message.options?.trackRouter) {
4119
+ safeTrackerOp("Router install", () => installRouterTracker(client4));
4120
+ }
4121
+ if (message.options?.trackNetwork) {
4122
+ safeTrackerOp("Network install", () => installNetworkTracker(client4));
4123
+ }
4124
+ safeTrackerOp("Timeline install", () => installTimelineTracker(client4));
4125
+ console.log("[FloTrace] Tracking started with options:", message.options);
4126
+ break;
4127
+ case "ext:stopTracking":
4128
+ trackingOptionsRef.current = {};
4129
+ safeTrackerOp("Zustand uninstall", uninstallZustandTracker);
4130
+ safeTrackerOp("Redux uninstall", uninstallReduxTracker);
4131
+ safeTrackerOp("TanStack Query uninstall", uninstallTanStackQueryTracker);
4132
+ safeTrackerOp("Router uninstall", uninstallRouterTracker);
4133
+ safeTrackerOp("Timeline uninstall", uninstallTimelineTracker);
4134
+ safeTrackerOp("Network uninstall", uninstallNetworkTracker);
4135
+ console.log("[FloTrace] Tracking stopped");
4136
+ break;
4137
+ case "ext:startTreeTracking":
4138
+ installFiberTreeWalker();
4139
+ break;
4140
+ case "ext:stopTreeTracking":
4141
+ uninstallFiberTreeWalker();
4142
+ console.log("[FloTrace] Tree tracking stopped");
4143
+ break;
4144
+ case "ext:requestNodeProps": {
4145
+ const nodeId = message.nodeId;
4146
+ if (nodeId) {
4147
+ const props = getNodeProps(nodeId);
4148
+ client4.sendImmediate({
4149
+ type: "runtime:nodeProps",
4150
+ nodeId,
4151
+ props: props || {},
4152
+ timestamp: Date.now()
4153
+ });
4154
+ }
4155
+ break;
4156
+ }
4157
+ case "ext:requestNodeHooks": {
4158
+ const hookNodeId = message.nodeId;
4159
+ if (hookNodeId) {
4160
+ const hooks = getNodeHooks(hookNodeId);
4161
+ client4.sendImmediate({
4162
+ type: "runtime:nodeHooks",
4163
+ nodeId: hookNodeId,
4164
+ hooks: hooks || [],
4165
+ timestamp: Date.now()
4166
+ });
4167
+ }
4168
+ break;
4169
+ }
4170
+ case "ext:requestNodeEffects": {
4171
+ const effectNodeId = message.nodeId;
4172
+ if (effectNodeId) {
4173
+ const effects = getNodeEffects(effectNodeId);
4174
+ client4.sendImmediate({
4175
+ type: "runtime:nodeEffects",
4176
+ nodeId: effectNodeId,
4177
+ effects: effects || [],
4178
+ timestamp: Date.now()
4179
+ });
4180
+ }
4181
+ break;
4182
+ }
4183
+ case "ext:requestDetailedRenderReason": {
4184
+ const reasonNodeId = message.nodeId;
4185
+ if (reasonNodeId) {
4186
+ const reason = getDetailedRenderReason(reasonNodeId);
4187
+ if (reason) {
4188
+ client4.sendImmediate({
4189
+ type: "runtime:detailedRenderReason",
4190
+ nodeId: reasonNodeId,
4191
+ reason,
4192
+ timestamp: Date.now()
4193
+ });
4194
+ }
4195
+ }
4196
+ break;
4197
+ }
4198
+ case "ext:requestFullSnapshot":
4199
+ requestFullSnapshot();
4200
+ console.log("[FloTrace] Full snapshot requested by extension");
4201
+ break;
4202
+ case "ext:requestTimeline": {
4203
+ const timelineNodeId = message.nodeId;
4204
+ if (timelineNodeId) {
4205
+ const events = getTimeline(timelineNodeId);
4206
+ const componentName = timelineNodeId.split("/").pop()?.replace(/-\d+$/, "") ?? "Unknown";
4207
+ for (const event of events) {
4208
+ client4.sendImmediate({
4209
+ type: "runtime:timelineEvent",
4210
+ nodeId: timelineNodeId,
4211
+ componentName,
4212
+ event
4213
+ });
4214
+ }
4215
+ }
4216
+ break;
4217
+ }
4218
+ case "ext:startNetworkCapture":
4219
+ safeTrackerOp("Network capture start", () => installNetworkTracker(client4));
4220
+ break;
4221
+ case "ext:stopNetworkCapture":
4222
+ safeTrackerOp("Network capture stop", uninstallNetworkTracker);
4223
+ break;
4224
+ // --- Individual tracker start/stop (sidebar panel show/hide) ---
4225
+ case "ext:startReduxTracking":
4226
+ if (reduxStoreRef.current) {
4227
+ safeTrackerOp("Redux install", () => installReduxTracker(reduxStoreRef.current, client4));
4228
+ }
4229
+ break;
4230
+ case "ext:stopReduxTracking":
4231
+ safeTrackerOp("Redux uninstall", uninstallReduxTracker);
4232
+ break;
4233
+ case "ext:startRouterTracking":
4234
+ safeTrackerOp("Router install", () => installRouterTracker(client4));
4235
+ break;
4236
+ case "ext:stopRouterTracking":
4237
+ safeTrackerOp("Router uninstall", uninstallRouterTracker);
4238
+ break;
4239
+ case "ext:startZustandTracking":
4240
+ if (storesRef.current && Object.keys(storesRef.current).length > 0) {
4241
+ safeTrackerOp("Zustand install", () => installZustandTracker(
4242
+ storesRef.current,
4243
+ client4
4244
+ ));
4245
+ }
4246
+ break;
4247
+ case "ext:stopZustandTracking":
4248
+ safeTrackerOp("Zustand uninstall", uninstallZustandTracker);
4249
+ break;
4250
+ case "ext:startTanstackTracking":
4251
+ if (queryClientRef.current) {
4252
+ safeTrackerOp("TanStack Query install", () => installTanStackQueryTracker(queryClientRef.current, client4));
4253
+ }
4254
+ break;
4255
+ case "ext:stopTanstackTracking":
4256
+ safeTrackerOp("TanStack Query uninstall", uninstallTanStackQueryTracker);
4257
+ break;
4258
+ case "ext:requestState":
4259
+ break;
4260
+ }
4261
+ } catch (error) {
4262
+ console.error(`[FloTrace] Error handling message type "${message.type}":`, error);
4263
+ }
4264
+ });
4265
+ client4.connect();
4266
+ return () => {
4267
+ unsubConnection();
4268
+ unsubMessage();
4269
+ pendingCleanupTimer = setTimeout(() => {
4270
+ pendingCleanupTimer = null;
4271
+ safeTrackerOp("cleanup fiberTreeWalker", uninstallFiberTreeWalker);
4272
+ safeTrackerOp("cleanup zustandTracker", uninstallZustandTracker);
4273
+ safeTrackerOp("cleanup reduxTracker", uninstallReduxTracker);
4274
+ safeTrackerOp("cleanup tanstackQueryTracker", uninstallTanStackQueryTracker);
4275
+ safeTrackerOp("cleanup routerTracker", uninstallRouterTracker);
4276
+ safeTrackerOp("cleanup timelineTracker", uninstallTimelineTracker);
4277
+ safeTrackerOp("cleanup networkTracker", uninstallNetworkTracker);
4278
+ safeTrackerOp("cleanup websocketClient", disposeWebSocketClient);
4279
+ }, 100);
4280
+ };
4281
+ }, [mergedConfig.enabled, mergedConfig.port, mergedConfig.appName]);
4282
+ const onRenderCallback = (id, phase, actualDuration, baseDuration, startTime, commitTime) => {
4283
+ try {
4284
+ if (!mergedConfig.enabled) {
4285
+ return;
4286
+ }
4287
+ const client4 = getWebSocketClient();
4288
+ if (!client4.connected) {
4289
+ return;
4290
+ }
4291
+ const normalizedPhase = phase === "nested-update" ? "update" : phase;
4292
+ client4.send({
4293
+ type: "runtime:render",
4294
+ componentName: id,
4295
+ phase: normalizedPhase,
4296
+ actualDuration,
4297
+ baseDuration,
4298
+ timestamp: commitTime
4299
+ });
4300
+ requestTreeSnapshot();
4301
+ } catch (error) {
4302
+ console.error("[FloTrace] Error in Profiler callback:", error);
4303
+ }
4304
+ };
4305
+ const contextValue = {
4306
+ connected,
4307
+ enabled: mergedConfig.enabled,
4308
+ config: mergedConfig
4309
+ };
4310
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(FloTraceContext.Provider, { value: contextValue, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react.Profiler, { id: "FloTrace-Root", onRender: onRenderCallback, children }) });
4311
+ }
4312
+ function withFloTrace(Component, displayName) {
4313
+ const name = displayName || Component.displayName || Component.name || "Unknown";
4314
+ const WrappedComponent = (props) => {
4315
+ const floTrace = useFloTrace();
4316
+ const onRender = (id, phase, actualDuration, baseDuration, startTime, commitTime) => {
4317
+ try {
4318
+ if (!floTrace?.enabled) {
4319
+ return;
4320
+ }
4321
+ const client4 = getWebSocketClient();
4322
+ if (!client4.connected) {
4323
+ return;
4324
+ }
4325
+ const normalizedPhase = phase === "nested-update" ? "update" : phase;
4326
+ client4.send({
4327
+ type: "runtime:render",
4328
+ componentName: id,
4329
+ phase: normalizedPhase,
4330
+ actualDuration,
4331
+ baseDuration,
4332
+ timestamp: commitTime
4333
+ });
4334
+ if (floTrace.config.includeProps) {
4335
+ client4.send({
4336
+ type: "runtime:props",
4337
+ componentName: id,
4338
+ props: serializeProps(props),
4339
+ timestamp: commitTime
4340
+ });
4341
+ }
4342
+ } catch (error) {
4343
+ console.error("[FloTrace] Error in withFloTrace render callback:", error);
4344
+ }
4345
+ };
4346
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react.Profiler, { id: name, onRender, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Component, { ...props }) });
4347
+ };
4348
+ WrappedComponent.displayName = `FloTrace(${name})`;
4349
+ return WrappedComponent;
4350
+ }
4351
+ function useTrackProps(componentName, props) {
4352
+ const floTrace = useFloTrace();
4353
+ const prevPropsRef = (0, import_react.useRef)();
4354
+ (0, import_react.useEffect)(() => {
4355
+ try {
4356
+ if (!floTrace?.enabled || !floTrace.config.includeProps) {
4357
+ return;
4358
+ }
4359
+ const client4 = getWebSocketClient();
4360
+ if (!client4.connected) {
4361
+ return;
4362
+ }
4363
+ const changedKeys = getChangedKeys(prevPropsRef.current, props);
4364
+ if (changedKeys.length > 0) {
4365
+ client4.send({
4366
+ type: "runtime:props",
4367
+ componentName,
4368
+ props: serializeProps(props),
4369
+ changedKeys,
4370
+ timestamp: Date.now()
4371
+ });
4372
+ }
4373
+ } catch (error) {
4374
+ console.error("[FloTrace] Error in useTrackProps:", error);
4375
+ } finally {
4376
+ prevPropsRef.current = { ...props };
4377
+ }
4378
+ }, [componentName, props, floTrace?.enabled, floTrace?.config.includeProps]);
4379
+ }
4380
+ // Annotate the CommonJS export names for ESM import in node:
4381
+ 0 && (module.exports = {
4382
+ DEFAULT_CONFIG,
4383
+ FloTraceProvider,
4384
+ FloTraceWebSocketClient,
4385
+ disposeWebSocketClient,
4386
+ getDetailedRenderReason,
4387
+ getFiberRefMap,
4388
+ getNodeEffects,
4389
+ getNodeHooks,
4390
+ getTimeline,
4391
+ getWebSocketClient,
4392
+ inspectEffects,
4393
+ inspectHooks,
4394
+ installFiberTreeWalker,
4395
+ installNetworkTracker,
4396
+ installReduxTracker,
4397
+ installRouterTracker,
4398
+ installTanStackQueryTracker,
4399
+ installTimelineTracker,
4400
+ installZustandTracker,
4401
+ isReduxStore,
4402
+ isTanStackQueryClient,
4403
+ recordTimelineEvent,
4404
+ requestTreeSnapshot,
4405
+ serializeProps,
4406
+ serializeValue,
4407
+ uninstallFiberTreeWalker,
4408
+ uninstallNetworkTracker,
4409
+ uninstallReduxTracker,
4410
+ uninstallRouterTracker,
4411
+ uninstallTanStackQueryTracker,
4412
+ uninstallTimelineTracker,
4413
+ uninstallZustandTracker,
4414
+ useFloTrace,
4415
+ useTrackProps,
4416
+ withFloTrace
4417
+ });