deictic 0.8.1 → 0.9.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.
Files changed (103) hide show
  1. package/API.md +71 -17
  2. package/README.md +1 -1
  3. package/dist/annotations/client.js +1 -1
  4. package/dist/cli.js +1 -1
  5. package/dist/cli.js.map +1 -1
  6. package/dist/client/index.d.ts +13 -13
  7. package/dist/client/index.d.ts.map +1 -1
  8. package/dist/client/index.js +11 -7
  9. package/dist/client/index.js.map +1 -1
  10. package/dist/react/client.d.ts +19 -0
  11. package/dist/react/client.d.ts.map +1 -0
  12. package/dist/react/client.js +504 -0
  13. package/dist/react/client.js.map +1 -0
  14. package/dist/react/index.d.ts +2 -0
  15. package/dist/react/index.js +1 -0
  16. package/dist/recommended/index.d.ts +15 -7
  17. package/dist/recommended/index.d.ts.map +1 -1
  18. package/dist/recommended/index.js +1 -1
  19. package/dist/recordings/client.d.ts.map +1 -1
  20. package/dist/recordings/client.js +48 -5
  21. package/dist/recordings/client.js.map +1 -1
  22. package/dist/screenshots/client.d.ts +9 -1
  23. package/dist/screenshots/client.d.ts.map +1 -1
  24. package/dist/screenshots/rrweb.d.ts +0 -6
  25. package/dist/screenshots/rrweb.d.ts.map +1 -1
  26. package/dist/screenshots/rrweb.js +46 -12
  27. package/dist/screenshots/rrweb.js.map +1 -1
  28. package/dist/shared/board.js +1 -1
  29. package/dist/shared/client.js +44 -2
  30. package/dist/shared/client.js.map +1 -1
  31. package/dist/shared/dom.js +7 -1
  32. package/dist/shared/dom.js.map +1 -1
  33. package/dist/shared/drawer.js +1 -1
  34. package/dist/shared/endpoints.js +1 -1
  35. package/dist/shared/index.d.ts +6 -0
  36. package/dist/shared/index.d.ts.map +1 -1
  37. package/dist/shared/index10.d.ts +70 -0
  38. package/dist/shared/index10.d.ts.map +1 -0
  39. package/dist/shared/index3.d.ts +11 -0
  40. package/dist/shared/index3.d.ts.map +1 -1
  41. package/dist/shared/index7.d.ts +92 -312
  42. package/dist/shared/index7.d.ts.map +1 -1
  43. package/dist/shared/index8.d.ts +324 -47
  44. package/dist/shared/index8.d.ts.map +1 -1
  45. package/dist/shared/index9.d.ts +45 -63
  46. package/dist/shared/index9.d.ts.map +1 -1
  47. package/dist/shared/init.js +15 -11
  48. package/dist/shared/init.js.map +1 -1
  49. package/dist/shared/marks.js +7 -1
  50. package/dist/shared/marks.js.map +1 -1
  51. package/dist/shared/package.js +3 -1
  52. package/dist/shared/packages.js +1 -1
  53. package/dist/shared/playwright.js +39 -1
  54. package/dist/shared/playwright.js.map +1 -1
  55. package/dist/shared/react.js +25 -0
  56. package/dist/shared/react.js.map +1 -0
  57. package/dist/shared/recommended.js +6 -3
  58. package/dist/shared/recommended.js.map +1 -1
  59. package/dist/shared/recording.js +80 -3
  60. package/dist/shared/recording.js.map +1 -1
  61. package/dist/shared/recordings.js +30 -2
  62. package/dist/shared/recordings.js.map +1 -1
  63. package/dist/shared/screenshots.js.map +1 -1
  64. package/dist/shared/src.js.map +1 -1
  65. package/dist/shared/task.js +1 -0
  66. package/dist/shared/task.js.map +1 -1
  67. package/dist/shared/tasks.js +11 -0
  68. package/dist/shared/tasks.js.map +1 -1
  69. package/dist/tailwind/client.d.ts +1 -1
  70. package/dist/tailwind/index.d.ts +1 -1
  71. package/dist/tasks/client.d.ts +1 -1
  72. package/dist/tasks/client.js +45 -19
  73. package/dist/tasks/client.js.map +1 -1
  74. package/dist/tasks/index.d.ts +1 -1
  75. package/dist/voice/client.d.ts +1 -1
  76. package/dist/voice/client.js +1 -1
  77. package/dist/voice/index.d.ts +1 -1
  78. package/package.json +25 -1
  79. package/src/cli/bun.ts +2 -2
  80. package/src/cli/init.ts +14 -9
  81. package/src/cli/recording.ts +90 -4
  82. package/src/cli/task.ts +4 -0
  83. package/src/cli.ts +13 -6
  84. package/src/client/dom.ts +14 -0
  85. package/src/client/index.ts +21 -14
  86. package/src/index.ts +6 -0
  87. package/src/plugins/react/client.ts +162 -0
  88. package/src/plugins/react/index.ts +130 -0
  89. package/src/plugins/react/renders.ts +219 -0
  90. package/src/plugins/react/serialize.ts +139 -0
  91. package/src/plugins/react/timeline.ts +143 -0
  92. package/src/plugins/recommended/index.ts +17 -5
  93. package/src/plugins/recordings/client.ts +64 -4
  94. package/src/plugins/recordings/marks.ts +7 -0
  95. package/src/plugins/recordings/replay.ts +30 -2
  96. package/src/plugins/screenshots/client.ts +42 -2
  97. package/src/plugins/screenshots/index.ts +11 -0
  98. package/src/plugins/screenshots/playwright.ts +65 -1
  99. package/src/plugins/screenshots/rrweb.ts +55 -28
  100. package/src/plugins/screenshots/states.ts +26 -0
  101. package/src/plugins/tasks/client.ts +41 -6
  102. package/src/plugins/tasks/composer.ts +24 -7
  103. package/src/plugins/tasks/index.ts +16 -2
@@ -0,0 +1,130 @@
1
+ /**
2
+ * `deictic/react`: what React's DevTools would show of the element a task is about, attached to the task as
3
+ * `react.json`. The component that wrote the element and the ones that wrote it in turn, each with its props, and
4
+ * its state: a class's, or a function's hooks, named as the code names them where the source says (`count`, not
5
+ * `State`). Read with bippy (an optional peer, imported as a task first asks for it) in development only, as React
6
+ * keeps who wrote an element only there. Each says how often it rendered, how long that took and why, as DevTools'
7
+ * profiler would, counted from React's commits. No tab, and nothing in the page of its own: the tasks plugin asks it, and
8
+ * sends what it answers beside the element's HTML, while the panel's HTML snapshot box is ticked.
9
+ *
10
+ * Values are what the page holds, so they're masked as the network plugin's are, by their names (`token`,
11
+ * `password`, `auth`…, and `mask`'s), and cut where they're deep or long.
12
+ */
13
+ import { definePlugin } from '#src/index.ts';
14
+
15
+ export interface ReactOptions {
16
+ /** How many components, out from the one that wrote the element: 4 by default. */
17
+ components?: number;
18
+ /** More names whose values are blanked: a part of the name, in any case. */
19
+ mask?: string[];
20
+ /**
21
+ * Whether hooks are named as the code names them, read off the source and its map (fetched from the dev server, as
22
+ * DevTools does): true by default. Without, each is its kind alone, `State` or `Memo`, in the order they're called.
23
+ */
24
+ names?: boolean;
25
+ /**
26
+ * Whether each component's renders are counted, timed and explained, from React's commits as DevTools' hook hears
27
+ * them: true by default. That hook is React Refresh's, in development; without one there's nothing to count.
28
+ */
29
+ renders?: boolean;
30
+ }
31
+
32
+ /** What JSON holds of a value: anything it can't hold says what it was, in brackets (`[function onClick]`). */
33
+ export type Value = null | boolean | number | string | Value[] | { [key: string]: Value };
34
+
35
+ /** A hook as DevTools lists it. */
36
+ export interface Hook {
37
+ /** Its kind: `State`, `Memo`, `Context`, or a custom hook's name less `use` (`Auth`), whose `hooks` it called. */
38
+ hook: string;
39
+ /** What the code calls it: `const [count, setCount] = useState(0)` is `count`. */
40
+ as?: string;
41
+ value?: Value;
42
+ hooks?: Hook[];
43
+ }
44
+
45
+ /** A component's renders, counted from when the page started deictic, not from its first. */
46
+ export interface Renders {
47
+ count: number;
48
+ /** In the 10 seconds before the task: a loop, or a burst on each keystroke. */
49
+ recent: number;
50
+ /** How long ago it last rendered, in milliseconds. */
51
+ lastAgo: number;
52
+ /** How long its last render took, with what it rendered, in milliseconds: where React times them. */
53
+ lastMs?: number;
54
+ /** Its own part of it. */
55
+ selfMs?: number;
56
+ /** Why it last rendered: `mounted`, `props changed: chosen`, `state changed`, `context changed`, `its parent rendered`. */
57
+ why: string;
58
+ }
59
+
60
+ /** A component that rendered in a recording's commit, once for each time it did in the entry. */
61
+ export interface Rendered {
62
+ name: string;
63
+ /** Where its JSX has the first element it wrote, `src/Plan.tsx:12`, where it wrote one. */
64
+ at?: string;
65
+ /** How many times it rendered in the entry, where that's more than once. */
66
+ count?: number;
67
+ /** How long it took, with what it rendered, in milliseconds, all its renders in the entry together. */
68
+ ms?: number;
69
+ /** Its own part of it. */
70
+ selfMs?: number;
71
+ /** Why it last rendered, as `Renders.why`. */
72
+ why: string;
73
+ }
74
+
75
+ /**
76
+ * A recording's entry of React's commits, `deictic.react` events: commits a frame apart, as one, with the components
77
+ * they rendered, the slowest first. `{ on: boolean }` events say where the recording starts and stops having them.
78
+ */
79
+ export interface Commit {
80
+ /** How many commits it is. */
81
+ commits: number;
82
+ /** How long rendering them took, in milliseconds, where React times it. */
83
+ ms?: number;
84
+ /** Of several, the slowest one's, in milliseconds: one past a frame is what makes a page stutter. */
85
+ slowest?: number;
86
+ /**
87
+ * The rest of a busy second, past ten entries in it: how long it spans, in milliseconds, up to this entry's
88
+ * moment. A page that renders without stop is ten entries and this one a second.
89
+ */
90
+ over?: number;
91
+ /** React's scheduler priority for the last: `immediate` (a click, a key), `user-blocking`, `normal`, `low`, `idle`. */
92
+ priority?: string;
93
+ /** Twenty at most. */
94
+ components: Rendered[];
95
+ /** How many more components rendered than it names. */
96
+ more?: number;
97
+ }
98
+
99
+ /** A component that wrote the element, or wrote one that did. */
100
+ export interface Component {
101
+ name: string;
102
+ /** Where its JSX has the nearest element around this one, `src/Plan.tsx:12`: none for one that only passed it on. */
103
+ at?: string;
104
+ /** A server component: React kept its name, and nothing of it is in the page. */
105
+ server?: true;
106
+ props?: Value;
107
+ /** A class component's state. */
108
+ state?: Value;
109
+ /** A function component's hooks, in the order it calls them, effects left out. */
110
+ hooks?: Hook[];
111
+ renders?: Renders;
112
+ /** Why what's missing is. */
113
+ problem?: string;
114
+ }
115
+
116
+ /** `react.json`: the component that wrote the element first, then the one that wrote it, and on out. */
117
+ export interface Snapshot {
118
+ components: Component[];
119
+ }
120
+
121
+ export function reactState(options: ReactOptions = {}) {
122
+ return definePlugin<never, never>({
123
+ name: 'react',
124
+ client: 'deictic/react/client',
125
+ packages: ['bippy'],
126
+ clientOptions: { ...options },
127
+ });
128
+ }
129
+
130
+ export default reactState;
@@ -0,0 +1,219 @@
1
+ /**
2
+ * How often each component rendered, how long it took and why, as React's DevTools profiler tells it: each commit
3
+ * React hands DevTools' hook (`onCommitFiberRoot`) is walked for the components it rendered. The hook is React
4
+ * Refresh's in development (Vite's, Next's, webpack's and Rspack's), which React found as it loaded, and calls on
5
+ * every commit whoever answers it later: so it's counted from when deictic's page half starts, not from the page's
6
+ * first render.
7
+ */
8
+ import type { Renders } from './index.ts';
9
+
10
+ /** What a fiber holds that this reads: React's own, in development. */
11
+ export interface Fiber {
12
+ tag: number;
13
+ flags?: number;
14
+ alternate: Fiber | null;
15
+ child: Fiber | null;
16
+ sibling: Fiber | null;
17
+ memoizedProps?: unknown;
18
+ memoizedState?: unknown;
19
+ dependencies?: { firstContext?: Dependency | null } | null;
20
+ /** In profiling mode, which React is in where DevTools' hook was there as it loaded: this render, with what's under it. */
21
+ actualDuration?: number;
22
+ /** And its own part of it. */
23
+ selfBaseDuration?: number;
24
+ /** The component, or a host element's tag. */
25
+ type?: unknown;
26
+ /** Who wrote it, in development. */
27
+ _debugOwner?: Fiber | null;
28
+ /** A host element's DOM node. */
29
+ stateNode?: unknown;
30
+ }
31
+
32
+ /** A component that rendered in a commit: its timings as they were then, as the next render overwrites a fiber's. */
33
+ export interface RenderedFiber {
34
+ fiber: Fiber;
35
+ why: string;
36
+ ms?: number;
37
+ selfMs?: number;
38
+ }
39
+
40
+ /** A commit, as it was made: for whoever listens to them (a recording's timeline). */
41
+ export interface Rendering {
42
+ /** The whole commit's render, in milliseconds, where React times it. */
43
+ ms?: number;
44
+ /** React's scheduler priority for it. */
45
+ priority?: number;
46
+ rendered: RenderedFiber[];
47
+ }
48
+
49
+ interface Dependency {
50
+ memoizedValue?: unknown;
51
+ next?: Dependency | null;
52
+ }
53
+
54
+ /** A hook of a function component: React keeps them as a list. */
55
+ interface HookNode {
56
+ memoizedState?: unknown;
57
+ next?: HookNode | null;
58
+ }
59
+
60
+ /** Function, class, `forwardRef` and simple `memo` components: those that render (a `memo` wrapper's is its child). */
61
+ const COMPOSITE = new Set([0, 1, 11, 15]);
62
+ const CLASS = 1;
63
+ /** React's flag for a fiber whose component ran in this render, rather than bailed out. */
64
+ const PERFORMED_WORK = 1;
65
+ /** How many render times are kept per component, for how many were recent. */
66
+ const KEPT = 100;
67
+ /** What's recent: renders this long before a task, a loop or a burst. */
68
+ export const RECENT = 10_000;
69
+ /** How many changed props a reason names. */
70
+ const NAMED = 10;
71
+
72
+ interface Stats {
73
+ count: number;
74
+ at: number[];
75
+ lastMs?: number;
76
+ selfMs?: number;
77
+ why: string;
78
+ }
79
+
80
+ /** A hook's state that's an effect: a new one each render, which says nothing changed. */
81
+ const isEffect = (state: unknown) => typeof state === 'object' && state !== null && 'create' in state && 'tag' in state;
82
+
83
+ /** Why `next` rendered, `prev` being what it was: its props, its state, a context, or its parent rendering it again. */
84
+ export function whyOf(next: Fiber, prev: Fiber | null): string {
85
+ if (prev === null) return 'mounted';
86
+ const reasons: string[] = [];
87
+ if (next.memoizedProps !== prev.memoizedProps) {
88
+ const before = (prev.memoizedProps ?? {}) as Record<string, unknown>;
89
+ const now = (next.memoizedProps ?? {}) as Record<string, unknown>;
90
+ const keys = [...new Set([...Object.keys(before), ...Object.keys(now)])].filter((k) => !Object.is(before[k], now[k]));
91
+ if (keys.length > 0)
92
+ reasons.push(`props changed: ${keys.slice(0, NAMED).join(', ')}${keys.length > NAMED ? ` and ${keys.length - NAMED} more` : ''}`);
93
+ }
94
+ if (stateChanged(next, prev)) reasons.push('state changed');
95
+ if (contextChanged(next, prev)) reasons.push('context changed');
96
+ // Props of a new object with the same values: what a parent passes each time it renders.
97
+ return reasons.length > 0 ? reasons.join('; ') : 'its parent rendered';
98
+ }
99
+
100
+ function stateChanged(next: Fiber, prev: Fiber): boolean {
101
+ if (next.memoizedState === prev.memoizedState) return false;
102
+ if (next.tag === CLASS) return true;
103
+ let a = prev.memoizedState as HookNode | null | undefined;
104
+ let b = next.memoizedState as HookNode | null | undefined;
105
+ for (; a != null && b != null; a = a.next, b = b.next) {
106
+ if (Object.is(a.memoizedState, b.memoizedState) || isEffect(b.memoizedState)) continue;
107
+ return true;
108
+ }
109
+ return false;
110
+ }
111
+
112
+ function contextChanged(next: Fiber, prev: Fiber): boolean {
113
+ let a = prev.dependencies?.firstContext;
114
+ let b = next.dependencies?.firstContext;
115
+ for (; a != null && b != null; a = a.next, b = b.next) if (!Object.is(a.memoizedValue, b.memoizedValue)) return true;
116
+ return false;
117
+ }
118
+
119
+ /** The stats of every component the page rendered since it started being counted, read by its fiber, either of its two. */
120
+ export function renderStats(now: () => number = () => performance.now()) {
121
+ const stats = new WeakMap<Fiber, Stats>();
122
+
123
+ const listeners = new Set<(commit: Rendering) => void>();
124
+
125
+ const record = (fiber: Fiber, prev: Fiber | null): RenderedFiber => {
126
+ const kept = stats.get(fiber) ?? (fiber.alternate === null ? undefined : stats.get(fiber.alternate));
127
+ const entry: Stats = kept ?? { count: 0, at: [], why: '' };
128
+ entry.count++;
129
+ entry.at.push(now());
130
+ if (entry.at.length > KEPT) entry.at.shift();
131
+ entry.why = whyOf(fiber, prev);
132
+ if (typeof fiber.actualDuration === 'number') entry.lastMs = fiber.actualDuration;
133
+ if (typeof fiber.selfBaseDuration === 'number') entry.selfMs = fiber.selfBaseDuration;
134
+ stats.set(fiber, entry);
135
+ if (fiber.alternate !== null) stats.set(fiber.alternate, entry);
136
+ return {
137
+ fiber,
138
+ why: entry.why,
139
+ ...(typeof fiber.actualDuration === 'number' ? { ms: fiber.actualDuration } : {}),
140
+ ...(typeof fiber.selfBaseDuration === 'number' ? { selfMs: fiber.selfBaseDuration } : {}),
141
+ };
142
+ };
143
+
144
+ /** A committed tree, from its root's current fiber: what was rendered in it, and nothing React left as it was. */
145
+ const commit = (root: Fiber, priority?: number) => {
146
+ const rendered: RenderedFiber[] = [];
147
+ const stack: Fiber[] = [];
148
+ for (let child = root.child; child !== null; child = child.sibling) stack.push(child);
149
+ while (stack.length > 0) {
150
+ const fiber = stack.pop()!;
151
+ const prev = fiber.alternate;
152
+ if ((prev === null || ((fiber.flags ?? 0) & PERFORMED_WORK) !== 0) && COMPOSITE.has(fiber.tag)) rendered.push(record(fiber, prev));
153
+ // Children React didn't clone weren't rendered, nor anything under them.
154
+ if (prev !== null && fiber.child === prev.child) continue;
155
+ for (let child = fiber.child; child !== null; child = child.sibling) stack.push(child);
156
+ }
157
+ if (listeners.size === 0) return;
158
+ const made: Rendering = {
159
+ rendered,
160
+ ...(typeof root.actualDuration === 'number' ? { ms: root.actualDuration } : {}),
161
+ ...(priority === undefined ? {} : { priority }),
162
+ };
163
+ for (const listen of listeners) listen(made);
164
+ };
165
+
166
+ /** Hears each commit from now, until what's answered stops it. */
167
+ const subscribe = (listen: (commit: Rendering) => void) => {
168
+ listeners.add(listen);
169
+ return () => void listeners.delete(listen);
170
+ };
171
+
172
+ const read = (fiber: Fiber): Renders | undefined => {
173
+ const entry = stats.get(fiber) ?? (fiber.alternate === null ? undefined : stats.get(fiber.alternate));
174
+ if (entry === undefined) return undefined;
175
+ const at = now();
176
+ const round = (ms: number) => Math.round(ms * 100) / 100;
177
+ return {
178
+ count: entry.count,
179
+ recent: entry.at.filter((t) => at - t <= RECENT).length,
180
+ lastAgo: Math.round(at - entry.at.at(-1)!),
181
+ ...(entry.lastMs === undefined ? {} : { lastMs: round(entry.lastMs) }),
182
+ ...(entry.selfMs === undefined ? {} : { selfMs: round(entry.selfMs) }),
183
+ why: entry.why,
184
+ };
185
+ };
186
+
187
+ return { commit, read, subscribe };
188
+ }
189
+
190
+ /** DevTools' hook, as React calls it. */
191
+ interface Hook {
192
+ onCommitFiberRoot?: (id: number, root: { current: Fiber }, priority?: number, ...rest: unknown[]) => unknown;
193
+ }
194
+
195
+ /**
196
+ * Counts every commit from now on, where the page has DevTools' hook: answers what reads the counts and what hears
197
+ * each commit, or nothing where
198
+ * there's no hook (React then calls nothing, and keeps no timings either). The hook's own handler (React Refresh's,
199
+ * or the DevTools extension's) goes on being called first.
200
+ */
201
+ export function countRenders(target: { __REACT_DEVTOOLS_GLOBAL_HOOK__?: Hook } = globalThis as never) {
202
+ const hook = target.__REACT_DEVTOOLS_GLOBAL_HOOK__;
203
+ if (hook === undefined) return undefined;
204
+ const counts = renderStats();
205
+ let warned = false;
206
+ const before = hook.onCommitFiberRoot;
207
+ hook.onCommitFiberRoot = function (this: unknown, id, root, priority, ...rest) {
208
+ const answer = before?.call(this, id, root, priority, ...rest);
209
+ try {
210
+ counts.commit(root.current, priority);
211
+ } catch (e) {
212
+ // Never the page's render: a fiber of a React this doesn't know. Said once, not on each commit.
213
+ if (!warned) console.warn("deictic: renders aren't counted on this page", e);
214
+ warned = true;
215
+ }
216
+ return answer;
217
+ };
218
+ return { read: counts.read, subscribe: counts.subscribe };
219
+ }
@@ -0,0 +1,139 @@
1
+ /**
2
+ * A component's props, state and hooks as JSON: what a person would see of them in React's DevTools, for an agent
3
+ * to read in a file. Anything JSON can't hold says what it was, in brackets (`[function onClick]`, `[<Button>]`,
4
+ * `[circular]`), and what's too deep or too long is cut where it says so, as a page's values may be its whole store.
5
+ */
6
+ import { MASKED, sensitive } from '#src/plugins/network/mask.ts';
7
+
8
+ import type { Value } from './index.ts';
9
+
10
+ export interface Limits {
11
+ /** How deep into objects and arrays. */
12
+ depth: number;
13
+ /** How many keys of an object, and items of an array, a Map or a Set. */
14
+ items: number;
15
+ /** How long a string, in characters. */
16
+ text: number;
17
+ }
18
+
19
+ export const LIMITS: Limits = { depth: 5, items: 50, text: 1000 };
20
+
21
+ const ELEMENTS = new Set([Symbol.for('react.transitional.element'), Symbol.for('react.element')]);
22
+
23
+ /** A function's or a class's name, or nothing for one with none. */
24
+ const nameOf = (fn: unknown): string | undefined => {
25
+ if (typeof fn !== 'function' && (typeof fn !== 'object' || fn === null)) return undefined;
26
+ const { displayName, name } = fn as { displayName?: unknown; name?: unknown };
27
+ const found = displayName ?? name;
28
+ return typeof found === 'string' && found !== '' ? found : undefined;
29
+ };
30
+
31
+ /** `<Button>` for a React element: its tag, or its component's name through `memo` and `forwardRef`. */
32
+ function elementName(type: unknown): string {
33
+ if (typeof type === 'string') return type;
34
+ let at = type as { render?: unknown; type?: unknown } | null | undefined;
35
+ for (let depth = 0; depth < 4 && at !== null && at !== undefined; depth++) {
36
+ const name = nameOf(at);
37
+ if (name !== undefined) return name;
38
+ at = (at.render ?? at.type) as typeof at;
39
+ }
40
+ return 'Anonymous';
41
+ }
42
+
43
+ const cut = (text: string, limit: number) => (text.length > limit ? `${text.slice(0, limit)}… (${text.length - limit} more)` : text);
44
+
45
+ /** What a value read as, as JSON, its secrets blanked by their names (and `mask`'s, a part of a name in any case). */
46
+ export function serialize(value: unknown, mask: readonly string[] = [], limits: Limits = LIMITS): Value | undefined {
47
+ const above = new Set<object>();
48
+ const walk = (value: unknown, depth: number): Value | undefined => {
49
+ switch (typeof value) {
50
+ case 'undefined':
51
+ return undefined;
52
+ case 'boolean':
53
+ return value;
54
+ case 'number':
55
+ return Number.isFinite(value) ? value : `[${value}]`;
56
+ case 'bigint':
57
+ return `[${value}n]`;
58
+ case 'string':
59
+ return cut(value, limits.text);
60
+ case 'symbol':
61
+ return `[${value.toString()}]`;
62
+ case 'function':
63
+ return `[function${nameOf(value) === undefined ? '' : ` ${nameOf(value)}`}]`;
64
+ case 'object':
65
+ break;
66
+ }
67
+ if (value === null || typeof value !== 'object') return null;
68
+ const object = value as Record<PropertyKey, unknown>;
69
+ if (ELEMENTS.has(object.$$typeof as symbol)) return `[<${elementName(object.type)}>]`;
70
+ // A DOM node, told by its shape: `instanceof Node` is another window's in an iframe.
71
+ if (typeof object.nodeType === 'number' && typeof object.nodeName === 'string') {
72
+ const { nodeType, nodeName } = object as { nodeType: number; nodeName: string };
73
+ return nodeType === 1 ? `[<${nodeName.toLowerCase()}>]` : `[${nodeName}]`;
74
+ }
75
+ if (typeof window !== 'undefined' && value === window) return '[window]';
76
+ if (value instanceof Date) return Number.isNaN(value.getTime()) ? '[Invalid Date]' : value.toISOString();
77
+ if (value instanceof RegExp) return `[${value.toString()}]`;
78
+ if (value instanceof Error) return `[${value.name}: ${cut(value.message, limits.text)}]`;
79
+ if (typeof object.then === 'function') return '[Promise]';
80
+ if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer)
81
+ return `[${nameOf(value.constructor) ?? 'Buffer'}(${value.byteLength} bytes)]`;
82
+ if (above.has(value)) return '[circular]';
83
+ const many = Array.isArray(value) ? value.length : value instanceof Map || value instanceof Set ? value.size : undefined;
84
+ if (depth >= limits.depth) {
85
+ if (Array.isArray(value)) return `[Array(${value.length})]`;
86
+ if (value instanceof Map) return `[Map(${value.size})]`;
87
+ if (value instanceof Set) return `[Set(${value.size})]`;
88
+ return `[${nameOf(value.constructor) ?? 'Object'}]`;
89
+ }
90
+ above.add(value);
91
+ try {
92
+ const items = (entries: Iterable<unknown>, of: (item: unknown) => Value) => {
93
+ const out: Value[] = [];
94
+ for (const item of entries) {
95
+ if (out.length === limits.items) {
96
+ out.push(`[… ${(many ?? 0) - limits.items} more]`);
97
+ break;
98
+ }
99
+ out.push(of(item));
100
+ }
101
+ return out;
102
+ };
103
+ // Undefined, in an array, is a hole JSON writes as null: said, so it isn't read as null.
104
+ const inside = (item: unknown) => walk(item, depth + 1) ?? '[undefined]';
105
+ if (Array.isArray(value)) return items(value, inside);
106
+ if (value instanceof Set) return { [`Set(${value.size})`]: items(value, inside) };
107
+ if (value instanceof Map) {
108
+ const pair = (entry: unknown) => {
109
+ const [key, item] = entry as [unknown, unknown];
110
+ return [inside(key), typeof key === 'string' && sensitive(key, mask) ? MASKED : inside(item)];
111
+ };
112
+ return { [`Map(${value.size})`]: items(value, pair) };
113
+ }
114
+ const out: { [key: string]: Value } = {};
115
+ // A class's instance says which, as DevTools does; a plain object, or one of no prototype, doesn't.
116
+ const proto = Object.getPrototypeOf(value) as object | null;
117
+ const made = proto === null || proto === Object.prototype ? undefined : nameOf(proto.constructor);
118
+ if (made !== undefined) out['@'] = made;
119
+ const keys = Object.keys(value);
120
+ for (const key of keys.slice(0, limits.items)) {
121
+ let item: unknown;
122
+ try {
123
+ item = object[key];
124
+ } catch {
125
+ // A getter that throws.
126
+ out[key] = '[unreadable]';
127
+ continue;
128
+ }
129
+ const read = sensitive(key, mask) ? MASKED : walk(item, depth + 1);
130
+ if (read !== undefined) out[key] = read;
131
+ }
132
+ if (keys.length > limits.items) out['…'] = `${keys.length - limits.items} more keys`;
133
+ return out;
134
+ } finally {
135
+ above.delete(value);
136
+ }
137
+ };
138
+ return walk(value, 0);
139
+ }
@@ -0,0 +1,143 @@
1
+ /**
2
+ * React's commits as a timeline, for a recording: what DevTools' profiler shows of each commit, cut to what reads in
3
+ * a list. Commits a frame apart are one entry (an animation commits each frame), each names the components that
4
+ * rendered in it, the slowest first. Past `RATE` entries in a second, the rest of that second's commits are one entry
5
+ * at its end, which says how long it spans and its slowest commit: a recording is kept as it goes, and a page that
6
+ * renders without stop would fill it. So it's `RATE + 1` entries a second at most, whatever the page does.
7
+ */
8
+ import { componentOf } from '#src/client/component.ts';
9
+
10
+ import type { Commit, Rendered } from './index.ts';
11
+ import type { Fiber, Rendering } from './renders.ts';
12
+
13
+ /** Commits closer than this are one entry, in milliseconds: a frame. */
14
+ export const FRAME = 16;
15
+ /** How many components an entry names, the slowest first. */
16
+ const NAMED = 20;
17
+ /** How many entries a second go in as they come; past that, the rest of the second is one. */
18
+ export const RATE = 10;
19
+ /** The span entries are counted in, in milliseconds. */
20
+ const SECOND = 1000;
21
+ /** How far down a component a host element it wrote is looked for, in fibers. */
22
+ const LOOKED = 200;
23
+
24
+ /** React's scheduler priorities, as `onCommitFiberRoot` is given them. */
25
+ const PRIORITIES: Record<number, string> = { 1: 'immediate', 2: 'user-blocking', 3: 'normal', 4: 'low', 5: 'idle' };
26
+
27
+ /** `src/Plan.tsx:12`: the first host element under `fiber` that it wrote, where the page marks it. */
28
+ function placeOf(fiber: Fiber): string | undefined {
29
+ const its = (by: Fiber | null | undefined) => by != null && (by === fiber || by === fiber.alternate);
30
+ const stack: Fiber[] = fiber.child === null ? [] : [fiber.child];
31
+ for (let looked = 0; stack.length > 0 && looked < LOOKED; looked++) {
32
+ const at = stack.pop()!;
33
+ if (at.sibling !== null) stack.push(at.sibling);
34
+ if (typeof at.type === 'string' && its(at._debugOwner)) {
35
+ const mark = (at.stateNode as Element | null)?.getAttribute?.('data-deictic');
36
+ if (typeof mark === 'string') return mark.replace(/:\d+$/, '');
37
+ }
38
+ if (at.child !== null) stack.push(at.child);
39
+ }
40
+ return undefined;
41
+ }
42
+
43
+ const round = (ms: number) => Math.round(ms * 100) / 100;
44
+
45
+ /** One entry of commits: the components that rendered, each once with how often, the slowest first. */
46
+ export function summarize(commits: Rendering[]): Commit {
47
+ const by = new Map<string, Rendered & { order: number }>();
48
+ for (const { rendered } of commits) {
49
+ for (const { fiber, why, ms, selfMs } of rendered) {
50
+ const name = componentOf(fiber) ?? 'Anonymous';
51
+ const at = placeOf(fiber);
52
+ const key = `${name} ${at ?? ''}`;
53
+ const seen = by.get(key);
54
+ const entry = seen ?? { name, ...(at === undefined ? {} : { at }), count: 0, why, order: by.size };
55
+ entry.count = (entry.count ?? 0) + 1;
56
+ entry.why = why;
57
+ if (ms !== undefined) entry.ms = round((entry.ms ?? 0) + ms);
58
+ if (selfMs !== undefined) entry.selfMs = round((entry.selfMs ?? 0) + selfMs);
59
+ by.set(key, entry);
60
+ }
61
+ }
62
+ // The slowest first, and those alike in the order they rendered.
63
+ const all = [...by.values()].sort((a, b) =>
64
+ (b.selfMs ?? 0) - (a.selfMs ?? 0) !== 0 ? (b.selfMs ?? 0) - (a.selfMs ?? 0) : a.order - b.order,
65
+ );
66
+ const kept = all.slice(0, NAMED);
67
+ const timed = commits.flatMap((c) => (c.ms === undefined ? [] : [c.ms]));
68
+ const ms = timed.length === 0 ? undefined : timed.reduce((sum, n) => sum + n, 0);
69
+ const priority = commits.at(-1)?.priority;
70
+ return {
71
+ commits: commits.length,
72
+ ...(ms === undefined ? {} : { ms: round(ms) }),
73
+ // Of several: what makes a page stutter is one slow commit, not many quick ones.
74
+ ...(commits.length > 1 && timed.length > 0 ? { slowest: round(Math.max(...timed)) } : {}),
75
+ ...(priority === undefined || PRIORITIES[priority] === undefined ? {} : { priority: PRIORITIES[priority] }),
76
+ components: kept.map(({ order: _, count, ...rest }) => ({ ...rest, ...(count !== undefined && count > 1 ? { count } : {}) })),
77
+ ...(all.length > kept.length ? { more: all.length - kept.length } : {}),
78
+ };
79
+ }
80
+
81
+ /**
82
+ * Listens to the commits `subscribe` gives, and answers each frame's as one entry, `RATE` a second, then the rest of
83
+ * that second as one: `emit` hears them, until what's answered stops it (what's waiting goes first).
84
+ */
85
+ export function timeline(
86
+ subscribe: (listen: (commit: Rendering) => void) => () => void,
87
+ emit: (commit: Commit) => void,
88
+ clock: { now: () => number; later: (run: () => void, ms: number) => unknown } = {
89
+ now: () => performance.now(),
90
+ later: (run, ms) => setTimeout(run, ms),
91
+ },
92
+ ): () => void {
93
+ let waiting: Rendering[] = [];
94
+ // The second being counted: when it started, and its entries so far.
95
+ let second = Number.NEGATIVE_INFINITY;
96
+ let inSecond = 0;
97
+ // Its commits past `RATE` entries, and since when.
98
+ let over: Rendering[] = [];
99
+ let overFrom = 0;
100
+ const flushOver = () => {
101
+ if (over.length === 0) return;
102
+ const commits = over;
103
+ over = [];
104
+ emit({ ...summarize(commits), over: Math.round(clock.now() - overFrom) });
105
+ };
106
+ const flush = () => {
107
+ const commits = waiting;
108
+ waiting = [];
109
+ if (commits.length === 0) return;
110
+ const now = clock.now();
111
+ if (now - second >= SECOND) {
112
+ flushOver();
113
+ second = now;
114
+ inSecond = 0;
115
+ }
116
+ if (inSecond < RATE) {
117
+ inSecond++;
118
+ emit(summarize(commits));
119
+ return;
120
+ }
121
+ if (over.length === 0) {
122
+ overFrom = now;
123
+ // At the second's end, unless the next second's first entry has said it by then.
124
+ const counting = second;
125
+ clock.later(
126
+ () => {
127
+ if (second === counting) flushOver();
128
+ },
129
+ second + SECOND - now,
130
+ );
131
+ }
132
+ over.push(...commits);
133
+ };
134
+ const unsubscribe = subscribe((commit) => {
135
+ if (waiting.length === 0) clock.later(flush, FRAME);
136
+ waiting.push(commit);
137
+ });
138
+ return () => {
139
+ unsubscribe();
140
+ flush();
141
+ flushOver();
142
+ };
143
+ }