-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathruntime-script.js
More file actions
2013 lines (1791 loc) · 66.1 KB
/
runtime-script.js
File metadata and controls
2013 lines (1791 loc) · 66.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
export function runtimeBootstrap() {
if (window.__RDT_CLI_RUNTIME__) {
return;
}
const OBSERVED = "observed";
const INFERRED = "inferred";
const STRUCTURAL_ONLY = "structural-only";
const ACTUAL_DURATION = "actual-duration";
const MIXED = "mixed";
const COMMIT = "commit";
const ENGINE_AUTO = "auto";
const ENGINE_CUSTOM = "custom";
const ENGINE_DEVTOOLS = "devtools";
const NO_REACT_WARNING = "No React fiber roots were detected on the current page";
const NO_SOURCE_WARNING = "_debugSource unavailable for this node in the current build";
const DOCTOR_SOURCE_WARNING = "_debugSource is unavailable for the inspected node in the current build";
const SNAPSHOT_DIFF_LIMITATION = "changed nodes and rerender reasons are inferred from commit snapshot diffs";
const RANKING_FALLBACK_LIMITATION = "duration metrics were unavailable; ranking falls back to changed subtree breadth";
const FLAMEGRAPH_FALLBACK_LIMITATION = "duration metrics were unavailable; flamegraph timings fall back to null values";
const COMMIT_RANKING_WARNING = "Duration metrics were unavailable for this commit; ranking uses changed subtree breadth";
const COMMIT_DETAIL_WARNING = "Duration metrics were unavailable for this commit; subtree ranking uses structural fallbacks";
const COMMIT_FLAMEGRAPH_WARNING = "Duration metrics were unavailable for this commit; flamegraph emphasizes changed subtree structure";
const COMMIT_LIST_WARNING = "Duration metrics were unavailable for this commit; ranked views use structural fallbacks";
const PROFILER_FOLLOWUP_WARNING = "Profiler data is commit-oriented only; use inspect/tree snapshots for follow-up analysis";
const PROFILER_SOURCE_WARNING = "Profiler records component duration metrics when the current React runtime exposes them, but changed-fiber attribution is still inferred from commit snapshots";
const PROFILER_STRUCTURAL_WARNING = "Profiler is commit-oriented only; it does not track changed fibers or component durations";
const INITIAL_MOUNT_WARNING = "Initial mount commits can dominate the first recorded commit after profiler start";
const state = {
nextNodeId: 1,
nextRootId: 1,
fiberIds: new WeakMap(),
roots: new Map(),
renderers: new Map(),
snapshotIndex: new Map(),
snapshotStores: {
[ENGINE_CUSTOM]: {
nextSnapshotId: 1,
latestSnapshotId: null,
maxSnapshots: 5,
snapshots: new Map(),
},
[ENGINE_DEVTOOLS]: {
nextSnapshotId: 1,
latestSnapshotId: null,
maxSnapshots: 5,
snapshots: new Map(),
},
},
profiler: {
active: false,
profileId: null,
enginePreference: ENGINE_AUTO,
selectedEngine: ENGINE_CUSTOM,
startedAt: null,
stoppedAt: null,
events: [],
nextCommitId: 1,
profileIndex: new Map(),
profilesByEngine: {
[ENGINE_CUSTOM]: new Map(),
[ENGINE_DEVTOOLS]: new Map(),
},
maxProfiles: 10,
},
overlay: null,
};
const commonLimitations = {
snapshot: [
"snapshot ids are snapshot-scoped only",
"node identity is not stable across React commits",
],
inspect: [
"hooks are simplified serialized state derived from memoizedState",
"ownerStack is a lightweight owner chain, not a full component stack",
"source depends on _debugSource and may legitimately be unavailable",
],
profiler: [
"nodeCount is live tree size at commit, not changed fiber count",
"commit data does not prove which components rerendered",
],
};
function hasDurationMetrics(measurementMode) {
return measurementMode === ACTUAL_DURATION || measurementMode === MIXED;
}
function getSelectedEngine(preferredEngine) {
return detectDevtoolsCapabilities(preferredEngine).selectedEngine;
}
function getSnapshotStore(engineName) {
return state.snapshotStores[engineName] || state.snapshotStores[ENGINE_CUSTOM];
}
function getProfilerStore(engineName) {
return state.profiler.profilesByEngine[engineName] || state.profiler.profilesByEngine[ENGINE_CUSTOM];
}
function getProfilerLimitations(measurementMode) {
const limitations = commonLimitations.profiler.slice();
if (!hasDurationMetrics(measurementMode)) {
limitations.splice(1, 0, "component durations are not measured");
}
return limitations;
}
function normalizeEnginePreference(value) {
if (value === ENGINE_CUSTOM || value === ENGINE_DEVTOOLS) {
return value;
}
return ENGINE_AUTO;
}
function detectDurationMetricsFromRoots() {
const stack = [];
for (const entry of state.roots.values()) {
const current = entry.root?.current?.child || null;
if (current) {
stack.push(current);
}
}
while (stack.length) {
const fiber = stack.pop();
if (!fiber) {
continue;
}
if (typeof fiber.actualDuration === "number") {
return true;
}
if (fiber.sibling) {
stack.push(fiber.sibling);
}
if (fiber.child) {
stack.push(fiber.child);
}
}
return false;
}
function getRendererVersions() {
const versions = [];
for (const renderer of state.renderers.values()) {
const version = renderer?.version || renderer?.reconcilerVersion || null;
if (version && !versions.includes(String(version))) {
versions.push(String(version));
}
}
return versions;
}
function getHighestRendererMajor(versions) {
const majors = (versions || [])
.map((version) => Number.parseInt(String(version).split(".")[0], 10))
.filter((value) => Number.isInteger(value));
if (!majors.length) {
return null;
}
return Math.max(...majors);
}
function getSourceCapability(details) {
const rendererVersions = getRendererVersions();
const highestRendererMajor = getHighestRendererMajor(rendererVersions);
if (details?.source) {
return {
status: "ok",
mode: "legacy-debug-source",
available: true,
rendererVersions,
reason: "_debugSource is available for the inspected node",
};
}
const react19OrNewer = highestRendererMajor != null && highestRendererMajor >= 19;
return {
status: "partial",
mode: react19OrNewer ? "react19-removed-or-build-stripped" : "build-stripped-or-unavailable",
available: false,
rendererVersions,
reason: react19OrNewer
? "React 19+ commonly omits _debugSource; source reveal is treated as an optional capability only"
: "_debugSource is unavailable in the current build or runtime",
};
}
function detectDevtoolsCapabilities(preferredEngine) {
const hook = window.__REACT_DEVTOOLS_GLOBAL_HOOK__ || null;
const rendererCount = state.renderers.size;
const rendererVersions = getRendererVersions();
const rootCount = Array.from(state.roots.values()).filter((entry) => entry.root?.current?.child).length;
const reactDetected = rootCount > 0;
const durationMetricsAvailable = detectDurationMetricsFromRoots();
const canUseDevtoolsEngine = Boolean(hook) && rendererCount > 0 && rootCount > 0;
const normalizedPreference = normalizeEnginePreference(preferredEngine);
const recommendedEngine = canUseDevtoolsEngine ? ENGINE_DEVTOOLS : ENGINE_CUSTOM;
const selectedEngine = normalizedPreference === ENGINE_AUTO
? recommendedEngine
: (normalizedPreference === ENGINE_DEVTOOLS && canUseDevtoolsEngine ? ENGINE_DEVTOOLS : ENGINE_CUSTOM);
return {
hookPresent: Boolean(hook),
rendererCount,
rendererVersions,
rootCount,
reactDetected,
durationMetricsAvailable,
canUseDevtoolsEngine,
inspectionAvailable: reactDetected,
profilerAvailable: reactDetected,
selectedEngine,
recommendedEngine,
availableEngines: canUseDevtoolsEngine
? [ENGINE_CUSTOM, ENGINE_DEVTOOLS]
: [ENGINE_CUSTOM],
enginePreference: normalizedPreference,
engineFallback: normalizedPreference === ENGINE_DEVTOOLS && selectedEngine !== ENGINE_DEVTOOLS,
engineReasons: canUseDevtoolsEngine
? [
"React renderer roots are available through the DevTools global hook",
durationMetricsAvailable
? "React runtime exposes duration metrics for at least one live fiber"
: "DevTools-aligned engine is available, but duration metrics are not exposed in the current runtime",
]
: [
"Falling back to the custom engine because DevTools-aligned renderer data is not yet available on this page",
],
};
}
function buildEngineMetadata(preferredEngine) {
const capabilities = detectDevtoolsCapabilities(preferredEngine);
return buildResolvedEngineMetadata(capabilities.enginePreference, capabilities.selectedEngine, capabilities);
}
function buildResolvedEngineMetadata(enginePreference, selectedEngine, capabilitiesInput) {
const capabilities = capabilitiesInput || detectDevtoolsCapabilities(enginePreference);
const resolvedEngine = selectedEngine || capabilities.selectedEngine;
return {
enginePreference: normalizeEnginePreference(enginePreference),
engine: resolvedEngine,
selectedEngine: resolvedEngine,
recommendedEngine: capabilities.recommendedEngine,
availableEngines: capabilities.availableEngines,
engineFallback: normalizeEnginePreference(enginePreference) === ENGINE_DEVTOOLS && resolvedEngine !== ENGINE_DEVTOOLS,
engineReasons: capabilities.engineReasons,
inspectionSource: resolvedEngine === ENGINE_DEVTOOLS ? "devtools-aligned-fiber" : "custom-fiber",
measurementSource: resolvedEngine === ENGINE_DEVTOOLS ? "devtools-hook-profiler" : "custom-snapshot-profiler",
snapshotModel: resolvedEngine === ENGINE_DEVTOOLS ? "snapshot-scoped-devtools-aligned" : "snapshot-scoped-custom",
devtoolsCapabilities: {
hookPresent: capabilities.hookPresent,
rendererCount: capabilities.rendererCount,
rootCount: capabilities.rootCount,
durationMetricsAvailable: capabilities.durationMetricsAvailable,
inspectionAvailable: capabilities.inspectionAvailable,
profilerAvailable: capabilities.profilerAvailable,
},
};
}
function createRuntimeError(code, message, details) {
return {
__rdtError: true,
code,
message,
details: details || null,
};
}
const tagNames = {
0: "FunctionComponent",
1: "ClassComponent",
3: "HostRoot",
4: "HostPortal",
5: "HostComponent",
6: "HostText",
7: "Fragment",
8: "Mode",
9: "ContextConsumer",
10: "ContextProvider",
11: "ForwardRef",
12: "Profiler",
13: "SuspenseComponent",
14: "MemoComponent",
15: "SimpleMemoComponent",
16: "LazyComponent",
19: "SuspenseListComponent",
22: "OffscreenComponent",
};
function getFiberId(fiber) {
if (!state.fiberIds.has(fiber)) {
state.fiberIds.set(fiber, "n" + state.nextNodeId++);
}
return state.fiberIds.get(fiber);
}
function getRootState(root) {
let entry = state.roots.get(root);
if (!entry) {
entry = {
rootId: "root-" + state.nextRootId++,
rendererId: null,
root,
};
state.roots.set(root, entry);
}
return entry;
}
function pruneSnapshots(engineName) {
const store = getSnapshotStore(engineName);
while (store.snapshots.size > store.maxSnapshots) {
const oldestSnapshotId = store.snapshots.keys().next().value;
if (!oldestSnapshotId) {
break;
}
store.snapshots.delete(oldestSnapshotId);
state.snapshotIndex.delete(oldestSnapshotId);
if (store.latestSnapshotId === oldestSnapshotId) {
store.latestSnapshotId = store.snapshots.size
? Array.from(store.snapshots.keys()).pop()
: null;
}
}
}
function pruneProfiles(engineName) {
const store = getProfilerStore(engineName);
while (store.size > state.profiler.maxProfiles) {
const oldestProfileId = store.keys().next().value;
if (!oldestProfileId) {
break;
}
store.delete(oldestProfileId);
state.profiler.profileIndex.delete(oldestProfileId);
}
}
function safeSerialize(value, depth = 0, seen) {
if (depth > 3) {
return "[MaxDepth]";
}
if (value == null || typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
return value;
}
if (typeof value === "bigint") {
return String(value);
}
if (typeof value === "function") {
return "[Function]";
}
if (typeof value === "symbol") {
return value.toString();
}
const refs = seen || new WeakSet();
if (typeof value === "object") {
if (refs.has(value)) {
return "[Circular]";
}
refs.add(value);
}
if (Array.isArray(value)) {
return value.slice(0, 20).map((item) => safeSerialize(item, depth + 1, refs));
}
const output = {};
for (const key of Object.keys(value).slice(0, 30)) {
try {
output[key] = safeSerialize(value[key], depth + 1, refs);
} catch (error) {
output[key] = "[Unreadable]";
}
}
return output;
}
function stableStringify(value) {
if (value == null || typeof value !== "object") {
return JSON.stringify(value);
}
if (Array.isArray(value)) {
return "[" + value.map((item) => stableStringify(item)).join(",") + "]";
}
const keys = Object.keys(value).sort();
return "{" + keys.map((key) => JSON.stringify(key) + ":" + stableStringify(value[key])).join(",") + "}";
}
function getTopLevelDiffKeys(previous, next) {
const prev = previous && typeof previous === "object" && !Array.isArray(previous) ? previous : {};
const curr = next && typeof next === "object" && !Array.isArray(next) ? next : {};
const keys = new Set(Object.keys(prev).concat(Object.keys(curr)));
const changed = [];
for (const key of keys) {
if (stableStringify(prev[key]) !== stableStringify(curr[key])) {
changed.push(key);
}
}
return changed;
}
function getChangedHookIndexes(previous, next) {
const prev = Array.isArray(previous) ? previous : [];
const curr = Array.isArray(next) ? next : [];
const length = Math.max(prev.length, curr.length);
const changed = [];
for (let index = 0; index < length; index += 1) {
if (stableStringify(prev[index] || null) !== stableStringify(curr[index] || null)) {
changed.push(index);
}
}
return changed;
}
function getChangedContextNames(previous, next) {
const prev = Array.isArray(previous) ? previous : [];
const curr = Array.isArray(next) ? next : [];
const changed = [];
const length = Math.max(prev.length, curr.length);
for (let index = 0; index < length; index += 1) {
const prevEntry = prev[index] || null;
const currEntry = curr[index] || null;
if (stableStringify(prevEntry) !== stableStringify(currEntry)) {
changed.push(
currEntry?.displayName ||
prevEntry?.displayName ||
"Context",
);
}
}
return changed;
}
function getCommitEvents() {
return state.profiler.events.filter((event) => event.eventType === COMMIT);
}
function getSnapshotLimitations() {
return commonLimitations.snapshot.slice();
}
function getObservedTree(runtimeWarnings, tree, preferredEngine) {
const engineMeta = buildEngineMetadata(preferredEngine);
return {
...engineMeta,
snapshotId: null,
snapshotScoped: true,
identityStableAcrossCommits: false,
observationLevel: OBSERVED,
limitations: getSnapshotLimitations(),
runtimeWarnings,
generatedAt: tree.generatedAt,
reactDetected: tree.reactDetected,
roots: tree.roots,
nodes: tree.nodes,
selectedNodeId: tree.selectedNodeId,
};
}
function getCommitNotFoundError(commitId) {
return createRuntimeError(
"commit-not-found",
"Commit \"" + commitId + "\" is not available in the current profiler buffer.",
{ commitId },
);
}
function getProfileNotFoundError(profileId) {
return createRuntimeError(
"profile-not-found",
"Profile \"" + profileId + "\" is not available in the current profiler history.",
{ profileId },
);
}
function getCommitObservation(measurementMode, warning, extraLimitations) {
return {
observationLevel: measurementMode === ACTUAL_DURATION ? OBSERVED : INFERRED,
limitations: getProfilerLimitations(measurementMode).concat(
measurementMode === ACTUAL_DURATION
? [SNAPSHOT_DIFF_LIMITATION]
: extraLimitations,
),
runtimeWarnings: measurementMode === ACTUAL_DURATION ? [] : [warning],
};
}
function getDisplayName(fiber) {
if (!fiber) {
return null;
}
const type = fiber.elementType || fiber.type;
if (typeof type === "string") {
return type;
}
return type?.displayName || type?.name || fiber._debugInfo?.name || tagNames[fiber.tag] || "Anonymous";
}
function getFiberSource(fiber) {
const source = fiber?._debugSource;
if (!source) {
return null;
}
return {
fileName: source.fileName || null,
lineNumber: source.lineNumber || null,
columnNumber: source.columnNumber || null,
};
}
function getOwnerStack(fiber) {
const stack = [];
let current = fiber?._debugOwner || fiber?.return || null;
while (current && stack.length < 25) {
stack.push({
id: getFiberId(current),
displayName: getDisplayName(current),
});
current = current._debugOwner || current.return || null;
}
return stack;
}
function getHooks(fiber) {
const hooks = [];
let cursor = fiber?.memoizedState || null;
let index = 0;
while (cursor && index < 50) {
hooks.push({
index,
memoizedState: safeSerialize(cursor.memoizedState),
baseState: safeSerialize(cursor.baseState),
hasQueue: Boolean(cursor.queue),
});
cursor = cursor.next;
index += 1;
}
return hooks;
}
function getContextDependencies(fiber) {
const contexts = [];
let cursor = fiber?.dependencies?.firstContext || null;
while (cursor && contexts.length < 20) {
contexts.push({
displayName: cursor.context?.displayName || cursor.context?._context?.displayName || "Context",
value: safeSerialize(cursor.memoizedValue),
});
cursor = cursor.next;
}
return contexts;
}
function getDurationMetrics(fiber) {
const actualDuration = typeof fiber?.actualDuration === "number" ? fiber.actualDuration : null;
const actualStartTime = typeof fiber?.actualStartTime === "number" ? fiber.actualStartTime : null;
const treeBaseDuration = typeof fiber?.treeBaseDuration === "number" ? fiber.treeBaseDuration : null;
return {
actualDuration,
actualStartTime,
treeBaseDuration,
totalTime: actualDuration,
selfTime: actualDuration,
};
}
function findHostDescendant(fiber) {
const stack = [];
if (fiber?.child) {
stack.push(fiber.child);
}
while (stack.length) {
const current = stack.pop();
if (!current) {
continue;
}
if (current.tag === 5 && current.stateNode instanceof Element) {
return current;
}
if (current.sibling) {
stack.push(current.sibling);
}
if (current.child) {
stack.push(current.child);
}
}
return null;
}
function getDomInfo(fiber) {
const hostFiber = fiber?.tag === 5 ? fiber : findHostDescendant(fiber);
const node = hostFiber?.stateNode;
if (!(node instanceof Element)) {
return null;
}
const rect = node.getBoundingClientRect();
return {
tagName: node.tagName.toLowerCase(),
id: node.id || null,
className: node.className || null,
textPreview: node.textContent ? node.textContent.slice(0, 120) : null,
rect: {
x: rect.x,
y: rect.y,
width: rect.width,
height: rect.height,
},
};
}
function buildNodeRecord(fiber, parentId, depth, rootId) {
const id = getFiberId(fiber);
return {
id,
parentId,
rootId,
depth,
tag: fiber.tag,
tagName: tagNames[fiber.tag] || "Unknown",
key: fiber.key == null ? null : String(fiber.key),
displayName: getDisplayName(fiber),
source: getFiberSource(fiber),
dom: getDomInfo(fiber),
};
}
function buildNodeDetails(fiber, node, preferredEngine) {
const engineMeta = buildEngineMetadata(preferredEngine);
return {
...engineMeta,
snapshotId: null,
snapshotScoped: true,
identityStableAcrossCommits: false,
observationLevel: OBSERVED,
limitations: commonLimitations.snapshot.concat(commonLimitations.inspect),
runtimeWarnings: node.source ? [] : [NO_SOURCE_WARNING],
id: node.id,
displayName: node.displayName,
tag: node.tag,
tagName: node.tagName,
key: node.key,
props: safeSerialize(fiber.memoizedProps),
state: safeSerialize(fiber.memoizedState),
hooks: getHooks(fiber),
context: getContextDependencies(fiber),
ownerStack: getOwnerStack(fiber),
source: node.source,
dom: node.dom,
};
}
function traverseFiberTree(fiber, parentId, depth, rootId, output, nodeDetails, nodeMetrics, nodeMeta, parentAnalyzerKey, preferredEngine, engineLabel) {
let current = fiber;
let siblingIndex = 0;
while (current) {
const node = buildNodeRecord(current, parentId, depth, rootId);
const analyzerKey = [
engineLabel,
rootId,
parentAnalyzerKey || "root",
node.displayName || "Anonymous",
node.key || "",
node.tagName,
siblingIndex,
].join("|");
output.push(node);
nodeDetails.set(node.id, buildNodeDetails(current, node, preferredEngine));
nodeMetrics.set(node.id, getDurationMetrics(current));
nodeMeta.set(node.id, {
analyzerKey,
parentAnalyzerKey: parentAnalyzerKey || null,
});
if (current.child) {
traverseFiberTree(current.child, node.id, depth + 1, rootId, output, nodeDetails, nodeMetrics, nodeMeta, analyzerKey, preferredEngine, engineLabel);
}
current = current.sibling;
siblingIndex += 1;
}
}
function finalizeNodeMetrics(nodes, nodeMetrics) {
const childrenById = new Map();
for (const node of nodes) {
if (!childrenById.has(node.id)) {
childrenById.set(node.id, []);
}
if (node.parentId) {
const siblings = childrenById.get(node.parentId) || [];
siblings.push(node.id);
childrenById.set(node.parentId, siblings);
}
}
const nodesByDepth = nodes.slice().sort((left, right) => right.depth - left.depth);
for (const node of nodesByDepth) {
const metrics = nodeMetrics.get(node.id);
if (!metrics || typeof metrics.totalTime !== "number") {
continue;
}
const childIds = childrenById.get(node.id) || [];
const childTotal = childIds.reduce((sum, childId) => {
const childMetrics = nodeMetrics.get(childId);
return sum + (typeof childMetrics?.totalTime === "number" ? childMetrics.totalTime : 0);
}, 0);
metrics.selfTime = Math.max(0, metrics.totalTime - childTotal);
}
}
function collectFiberTree(preferredEngine, engineLabel) {
const roots = [];
const nodes = [];
const nodeDetails = new Map();
const nodeMetrics = new Map();
const nodeMeta = new Map();
for (const entry of state.roots.values()) {
const root = entry.root;
const current = root?.current;
if (!current || !current.child) {
continue;
}
roots.push({
id: entry.rootId,
rendererId: entry.rendererId,
nodeId: getFiberId(current.child),
});
traverseFiberTree(current.child, null, 0, entry.rootId, nodes, nodeDetails, nodeMetrics, nodeMeta, null, preferredEngine, engineLabel);
}
finalizeNodeMetrics(nodes, nodeMetrics);
return {
generatedAt: new Date().toISOString(),
reactDetected: roots.length > 0,
roots,
nodes,
selectedNodeId: null,
nodeDetails,
nodeMetrics,
nodeMeta,
};
}
function collectCustomLiveTree(preferredEngine) {
return collectFiberTree(preferredEngine, ENGINE_CUSTOM);
}
function collectDevtoolsLiveTree(preferredEngine) {
return collectFiberTree(preferredEngine, ENGINE_DEVTOOLS);
}
function collectLiveTree(preferredEngine) {
const selectedEngine = getSelectedEngine(preferredEngine);
if (selectedEngine === ENGINE_DEVTOOLS) {
return collectDevtoolsLiveTree(preferredEngine);
}
return collectCustomLiveTree(preferredEngine);
}
function serializeSnapshot(snapshot, preferredEngine) {
const engineMeta = snapshot.engineMeta || buildEngineMetadata(preferredEngine);
return {
...engineMeta,
snapshotId: snapshot.snapshotId,
snapshotScoped: true,
identityStableAcrossCommits: false,
observationLevel: OBSERVED,
limitations: getSnapshotLimitations(),
runtimeWarnings: [],
generatedAt: snapshot.generatedAt,
reactDetected: snapshot.reactDetected,
roots: snapshot.roots,
nodes: snapshot.nodes,
selectedNodeId: snapshot.selectedNodeId,
};
}
function cacheSnapshot(tree, preferredEngine) {
const selectedEngine = getSelectedEngine(preferredEngine);
const store = getSnapshotStore(selectedEngine);
const snapshotId = "snapshot-" + store.nextSnapshotId++;
const snapshot = {
snapshotId,
generatedAt: tree.generatedAt,
reactDetected: tree.reactDetected,
roots: tree.roots,
nodes: tree.nodes,
selectedNodeId: tree.selectedNodeId,
nodeDetails: new Map(
Array.from(tree.nodeDetails.entries(), ([nodeId, details]) => [
nodeId,
{
...details,
snapshotId,
},
]),
),
nodeMetrics: new Map(Array.from(tree.nodeMetrics.entries(), ([nodeId, metrics]) => [
nodeId,
{
...metrics,
},
])),
nodeMeta: new Map(Array.from(tree.nodeMeta.entries(), ([nodeId, meta]) => [
nodeId,
{
...meta,
},
])),
enginePreference: normalizeEnginePreference(preferredEngine),
selectedEngine,
engineMeta: buildResolvedEngineMetadata(preferredEngine, selectedEngine),
};
store.snapshots.set(snapshot.snapshotId, snapshot);
store.latestSnapshotId = snapshot.snapshotId;
state.snapshotIndex.set(snapshot.snapshotId, selectedEngine);
pruneSnapshots(selectedEngine);
return snapshot;
}
function collectTree(preferredEngine) {
const liveTree = collectLiveTree(preferredEngine);
if (!liveTree.reactDetected) {
return getObservedTree([NO_REACT_WARNING], liveTree, preferredEngine);
}
const snapshot = cacheSnapshot(liveTree, preferredEngine);
return serializeSnapshot(snapshot, preferredEngine);
}
function peekTree(preferredEngine) {
const liveTree = collectLiveTree(preferredEngine);
return getObservedTree(liveTree.reactDetected ? [] : [NO_REACT_WARNING], liveTree, preferredEngine);
}
function resolveSnapshot(snapshotId, createIfMissing = true, preferredEngine) {
if (snapshotId) {
const indexedEngine = state.snapshotIndex.get(snapshotId);
const indexedStore = indexedEngine ? getSnapshotStore(indexedEngine) : null;
return indexedStore?.snapshots.get(snapshotId) || createRuntimeError(
"snapshot-expired",
"Snapshot \"" + snapshotId + "\" is no longer available. Run rdt tree get --session <name> again to collect a fresh snapshot.",
{ snapshotId },
);
}
const selectedEngine = getSelectedEngine(preferredEngine);
const store = getSnapshotStore(selectedEngine);
if (store.latestSnapshotId) {
return store.snapshots.get(store.latestSnapshotId) || null;
}
if (!createIfMissing) {
return null;
}
const snapshot = collectTree(preferredEngine);
if (!snapshot.reactDetected || !snapshot.snapshotId) {
return null;
}
const indexedEngine = state.snapshotIndex.get(snapshot.snapshotId);
const indexedStore = indexedEngine ? getSnapshotStore(indexedEngine) : null;
return indexedStore?.snapshots.get(snapshot.snapshotId) || null;
}
function getProfilerCommit(commitId) {
return state.profiler.events.find((event) => event.eventType === COMMIT && event.commitId === commitId) || null;
}
function inspectNode(nodeId, snapshotId, commitId, preferredEngine) {
if (commitId) {
const commit = getProfilerCommit(commitId);
if (!commit) {
return createRuntimeError(
"commit-not-found",
"Commit \"" + commitId + "\" is not available in the current profiler buffer.",
{ commitId },
);
}
const details = commit.nodeDetailsById[nodeId];
if (!details) {
return null;
}
return {
...(commit.engineMeta || buildResolvedEngineMetadata(
preferredEngine || commit.enginePreference,
commit.selectedEngine || commit.engine,
)),
...details,
commitId,
profiler: commit.nodeAnalysisById[nodeId] || null,
metrics: commit.nodeMetricsById[nodeId] || null,
};
}
const snapshot = resolveSnapshot(snapshotId, true, preferredEngine);
if (snapshot?.__rdtError) {
return snapshot;
}
const details = snapshot?.nodeDetails.get(nodeId);
if (!snapshot || !details) {
return null;
}
return details;
}
function searchNodes(query, snapshotId, preferredEngine) {
const snapshot = resolveSnapshot(snapshotId, true, preferredEngine);
if (snapshot?.__rdtError) {
return snapshot;
}
if (!snapshot) {
return [];
}
const lower = String(query || "").toLowerCase();
return snapshot.nodes.filter((node) => {
return String(node.displayName || "").toLowerCase().includes(lower);
}).map((node) => ({
...node,
snapshotId: snapshot.snapshotId,
engine: snapshot.selectedEngine || buildEngineMetadata(preferredEngine).selectedEngine,
}));
}
function ensureOverlay() {
if (state.overlay && document.body.contains(state.overlay)) {
return state.overlay;
}
const overlay = document.createElement("div");
overlay.setAttribute("data-rdt-cli-overlay", "true");
overlay.style.position = "fixed";
overlay.style.pointerEvents = "none";
overlay.style.zIndex = "2147483647";
overlay.style.border = "2px solid #ff5d00";
overlay.style.background = "rgba(255, 93, 0, 0.12)";
overlay.style.boxSizing = "border-box";
overlay.style.display = "none";
document.documentElement.appendChild(overlay);
state.overlay = overlay;