Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

probes.ts

190 lines8.3 KB

1// Scripts client-metrics.ts runs inside the page. They are strings because they run in
2// Chromium, not Node; the shapes they return are decoded with the schemas below.
3import * as Schema from "effect/Schema";
4​
5import type { Renders } from "./report.ts";
6​
7/**
8 * Installed before the app loads (`--renders`): a minimal DevTools hook makes production React
9 * report commits. Only fibers React rendered are counted: a bailed-out subtree keeps
10 * `child === alternate.child`, and PerformedWork (flag 1) is cleared whenever a fiber is cloned.
11 */
12export const RENDER_PROBE = `(() => {
13 const hook = (window.__REACT_DEVTOOLS_GLOBAL_HOOK__ ??= {
14 supportsFiber: true,
15 renderers: new Map(),
16 inject(renderer) { const id = this.renderers.size + 1; this.renderers.set(id, renderer); return id; },
17 onCommitFiberRoot() {},
18 onCommitFiberUnmount() {},
19 onPostCommitFiberRoot() {},
20 onScheduleFiberRoot() {},
21 checkDCE() {},
22 isDisabled: false,
23 });
24 const COMPONENT_TAGS = new Set([0, 1, 11, 14, 15]);
25 const nameOf = (fiber) => {
26 const type = fiber.type;
27 if (!type || typeof type === "string") return null;
28 const inner = type.type ?? type.render ?? type;
29 return (type.displayName || inner.displayName || inner.name || "").replace(/^(Forget\\(|Memo\\()+|\\)+$/g, "") || null;
30 };
31 const isEffect = (value) => value && typeof value === "object" && "create" in value && "deps" in value && "tag" in value;
32 // Only state, reducer and store hooks have a queue; memo, callback and ref slots move because something upstream did.
33 const changedStateSlot = (previous, next) => {
34 let a = previous.memoizedState, b = next.memoizedState;
35 for (let slot = 0; a && b && slot < 800; slot++, a = a.next, b = b.next) {
36 if (b.queue !== null && !isEffect(b.memoizedState) && !Object.is(a.memoizedState, b.memoizedState)) return slot;
37 }
38 return -1;
39 };
40 const diff = (a, b, path, out, depth) => {
41 if (Object.is(a, b) || out.length > 20) return;
42 if (depth > 4 || !a || !b || typeof a !== "object" || typeof b !== "object") {
43 out.push(path + (b && typeof b === "object" ? "(object)" : "=" + String(b).slice(0, 40)));
44 return;
45 }
46 if (a instanceof Map && b instanceof Map) {
47 for (const key of new Set([...a.keys(), ...b.keys()])) {
48 const at = path + "<" + String(key).slice(0, 20) + ">";
49 if (!b.has(key)) out.push(at + "(deleted)");
50 else diff(a.get(key), b.get(key), at, out, depth + 1);
51 }
52 return;
53 }
54 let any = false;
55 for (const key of new Set([...Object.keys(a), ...Object.keys(b)])) {
56 if (!Object.is(a[key], b[key])) { any = true; diff(a[key], b[key], path + "." + key, out, depth + 1); }
57 }
58 if (!any) out.push(path + "(identity only)");
59 };
60 const state = { on: false, commits: 0, counts: new Map(), causes: new Map(), slotNames: [], slots: [] };
61 const bump = (map, key) => map.set(key, (map.get(key) ?? 0) + 1);
62 const visit = (first, parentName) => {
63 for (let node = first; node; node = node.sibling) {
64 const previous = node.alternate;
65 const name = COMPONENT_TAGS.has(node.tag) ? (nameOf(node) ?? "(anonymous)") : null;
66 const rendered = name !== null && (node.flags & 1) === 1;
67 if (rendered) {
68 bump(state.counts, name);
69 let cause;
70 if (!previous) cause = "mount";
71 else {
72 const slot = changedStateSlot(previous, node);
73 if (slot >= 0) cause = "state#" + slot;
74 else if (previous.memoizedProps !== node.memoizedProps) {
75 const props = node.memoizedProps ?? {};
76 const keys = Object.keys(props).filter((key) => !Object.is(previous.memoizedProps?.[key], props[key]));
77 cause = keys.length ? "props:" + keys.slice(0, 4).join(",") : "parent-same-props<-" + parentName;
78 } else cause = "context";
79 if (state.slotNames.includes(name)) {
80 let a = previous.memoizedState, b = node.memoizedState;
81 for (let slot = 0; a && b && slot < 600; slot++, a = a.next, b = b.next) {
82 if (Object.is(a.memoizedState, b.memoizedState) || isEffect(b.memoizedState)) continue;
83 const out = [];
84 diff(a.memoizedState, b.memoizedState, "#" + slot, out, 0);
85 if (state.slots.length < 200) state.slots.push(name + " " + out.join(" "));
86 }
87 }
88 }
89 bump(state.causes, name + " " + cause);
90 }
91 const skipped = previous !== null && node.child === previous.child && !rendered;
92 if (node.child && !skipped) visit(node.child, rendered ? name : parentName);
93 }
94 };
95 const original = hook.onCommitFiberRoot.bind(hook);
96 hook.onCommitFiberRoot = function (id, root, ...rest) {
97 if (state.on) {
98 state.commits += 1;
99 visit(root.current.child, "root");
100 }
101 return original(id, root, ...rest);
102 };
103 const sortedCounts = (map, limit) =>
104 [...map].sort((a, b) => b[1] - a[1]).slice(0, limit).map(([name, count]) => ({ name, count }));
105 window.__clientMetricsRenders = {
106 start(slotNames) {
107 Object.assign(state, { on: true, commits: 0, counts: new Map(), causes: new Map(), slotNames: slotNames ?? [], slots: [] });
108 },
109 stop() {
110 state.on = false;
111 let renders = 0;
112 for (const count of state.counts.values()) renders += count;
113 return { commits: state.commits, renders, top: sortedCounts(state.counts, 40), causes: sortedCounts(state.causes, 400), slots: state.slots };
114 },
115 };
116})()`;
117​
118const Count = Schema.Struct({ name: Schema.String, count: Schema.Number });
119export const ProbeReading = Schema.Struct({
120 commits: Schema.Number,
121 renders: Schema.Number,
122 top: Schema.Array(Count),
123 causes: Schema.Array(Count),
124 slots: Schema.Array(Schema.String),
125});
126export type ProbeReading = typeof ProbeReading.Type;
127​
128/** What the result file keeps of a probe reading; the full one goes to the artifacts. */
129export const rendersOf = (reading: ProbeReading, keep = 12): Renders => ({
130 commits: reading.commits,
131 renders: reading.renders,
132 top: reading.top.slice(0, keep),
133 causes: reading.causes.slice(0, keep),
134});
135​
136/**
137 * The open right-panel surface's DOM: node counts, and the path down its largest children with
138 * the tags that dominate, to say what makes a panel heavy.
139 */
140export const DOM_CENSUS = `(() => {
141 const all = document.getElementsByTagName("*").length;
142 const panel = document.querySelector("[data-right-panel-surface-content]");
143 if (!panel) return { documentNodes: all, panelNodes: 0, svg: 0, svgChildren: 0, buttons: 0, codeTokens: 0, tags: [], path: [] };
144 const size = (element) => element.getElementsByTagName("*").length + 1;
145 const describe = (element) => {
146 const data = [...element.attributes].filter((attribute) => attribute.name.startsWith("data-")).slice(0, 3).map((attribute) => "[" + attribute.name + "]").join("");
147 const classes = (element.getAttribute("class") ?? "").split(" ").filter(Boolean).slice(0, 3).map((name) => "." + name).join("");
148 return element.tagName.toLowerCase() + data + classes;
149 };
150 const path = [];
151 let cursor = panel;
152 for (let depth = 0; depth < 8; depth++) {
153 const children = [...cursor.children].map((child) => [child, size(child)]).sort((a, b) => b[1] - a[1]);
154 path.push({ node: describe(cursor), nodes: size(cursor), children: children.slice(0, 6).map(([child, nodes]) => ({ node: describe(child), nodes })) });
155 if (children.length === 0) break;
156 cursor = children[0][0];
157 }
158 const tags = new Map();
159 for (const element of panel.getElementsByTagName("*")) {
160 const tag = element.tagName.toLowerCase();
161 tags.set(tag, (tags.get(tag) ?? 0) + 1);
162 }
163 return {
164 documentNodes: all,
165 panelNodes: size(panel),
166 svg: panel.querySelectorAll("svg").length,
167 svgChildren: panel.querySelectorAll("svg *").length,
168 buttons: panel.querySelectorAll("button").length,
169 codeTokens: panel.querySelectorAll("pre *").length,
170 tags: [...tags].sort((a, b) => b[1] - a[1]).slice(0, 14).map(([tag, count]) => ({ name: tag, count })),
171 path,
172 };
173})()`;
174​
175export const Census = Schema.Struct({
176 documentNodes: Schema.Number,
177 panelNodes: Schema.Number,
178 svg: Schema.Number,
179 svgChildren: Schema.Number,
180 buttons: Schema.Number,
181 codeTokens: Schema.Number,
182 tags: Schema.Array(Count),
183 path: Schema.Array(
184 Schema.Struct({
185 node: Schema.String,
186 nodes: Schema.Number,
187 children: Schema.Array(Schema.Struct({ node: Schema.String, nodes: Schema.Number })),
188 }),
189 ),
190});