@reticlehq/react 3.10.11 → 3.11.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.
@@ -36,6 +36,13 @@ interface DiscoveredStore {
36
36
  */
37
37
  source: object;
38
38
  }
39
+ interface FiberNode {
40
+ return?: FiberNode | null;
41
+ child?: FiberNode | null;
42
+ sibling?: FiberNode | null;
43
+ type?: unknown;
44
+ memoizedProps?: unknown;
45
+ }
39
46
  /**
40
47
  * Decide whether one context value is a store, and what to call it.
41
48
  *
@@ -43,6 +50,10 @@ interface DiscoveredStore {
43
50
  * through to the generic branch under whatever its context is called this major version.
44
51
  */
45
52
  export declare function classifyProviderValue(value: unknown, displayName: string | undefined): DiscoveredStore | null;
53
+ /** The topmost fiber reachable from one node — the tree we then walk downward. */
54
+ export declare function topOf(fiber: FiberNode): FiberNode;
55
+ /** Any fiber React has stamped on the document, as the entry point into the tree. */
56
+ export declare function findFiber(doc: Document): FiberNode | null;
46
57
  /**
47
58
  * Every store-shaped context value in the mounted tree, in mount order.
48
59
  *
@@ -35,17 +35,20 @@ const MAX_FIBER_NODES = 20000;
35
35
  const PROVIDER_TYPE = Symbol.for('react.provider');
36
36
  const CONTEXT_TYPE = Symbol.for('react.context');
37
37
  function isStoreLike(value) {
38
- if (null === value)
38
+ if (null === value) {
39
39
  return false;
40
- if ('object' !== typeof value && 'function' !== typeof value)
40
+ }
41
+ if ('object' !== typeof value && 'function' !== typeof value) {
41
42
  return false;
43
+ }
42
44
  const candidate = value;
43
45
  return 'function' === typeof candidate.getState && 'function' === typeof candidate.subscribe;
44
46
  }
45
47
  /** A TanStack QueryClient, identified by the one method the adapter needs. */
46
48
  function isQueryClient(value) {
47
- if (null === value || 'object' !== typeof value)
49
+ if (null === value || 'object' !== typeof value) {
48
50
  return false;
51
+ }
49
52
  return 'function' === typeof value.getQueryCache;
50
53
  }
51
54
  /**
@@ -55,8 +58,9 @@ function isQueryClient(value) {
55
58
  * `reticle_state({ store })`, and `ReactRedux.Provider` is not a thing anyone will type correctly.
56
59
  */
57
60
  function keyFromName(name) {
58
- if ('string' !== typeof name)
61
+ if ('string' !== typeof name) {
59
62
  return undefined;
63
+ }
60
64
  const cleaned = name.toLowerCase().replace(/[^a-z0-9]/g, '');
61
65
  return cleaned.length > 0 ? cleaned : undefined;
62
66
  }
@@ -67,11 +71,13 @@ function keyFromName(name) {
67
71
  * through to the generic branch under whatever its context is called this major version.
68
72
  */
69
73
  export function classifyProviderValue(value, displayName) {
70
- if (null === value || undefined === value)
74
+ if (null === value || undefined === value) {
71
75
  return null;
76
+ }
72
77
  const nested = value.store;
73
- if (isStoreLike(nested))
78
+ if (isStoreLike(nested)) {
74
79
  return { key: AUTO_STORE_KEY.REDUX, store: nested, source: nested };
80
+ }
75
81
  if (isQueryClient(value)) {
76
82
  return {
77
83
  key: AUTO_STORE_KEY.QUERY,
@@ -88,41 +94,46 @@ export function classifyProviderValue(value, displayName) {
88
94
  }
89
95
  /** The context a provider fiber renders, across the versions that spell it differently. */
90
96
  function providerContext(type) {
91
- if (null === type || 'object' !== typeof type)
97
+ if (null === type || 'object' !== typeof type) {
92
98
  return null;
99
+ }
93
100
  const marker = type.$$typeof;
94
101
  if (PROVIDER_TYPE === marker) {
95
102
  const inner = type._context;
96
103
  return inner ?? type;
97
104
  }
98
- if (CONTEXT_TYPE === marker)
105
+ if (CONTEXT_TYPE === marker) {
99
106
  return type;
107
+ }
100
108
  return null;
101
109
  }
102
110
  /** The topmost fiber reachable from one node — the tree we then walk downward. */
103
- function topOf(fiber) {
111
+ export function topOf(fiber) {
104
112
  let current = fiber;
105
113
  for (let i = 0; i < MAX_FIBER_NODES; i += 1) {
106
114
  const parent = current.return;
107
- if (null === parent || undefined === parent)
115
+ if (null === parent || undefined === parent) {
108
116
  return current;
117
+ }
109
118
  current = parent;
110
119
  }
111
120
  return current;
112
121
  }
113
122
  /** Any fiber React has stamped on the document, as the entry point into the tree. */
114
- function findFiber(doc) {
123
+ export function findFiber(doc) {
115
124
  const elements = doc.querySelectorAll('*');
116
125
  const limit = Math.min(elements.length, MAX_HOST_SCAN);
117
126
  for (let i = 0; i < limit; i += 1) {
118
127
  const node = elements[i];
119
- if (undefined === node)
128
+ if (undefined === node) {
120
129
  continue;
130
+ }
121
131
  for (const key of Object.keys(node)) {
122
132
  if (FIBER_PREFIXES.some((prefix) => key.startsWith(prefix))) {
123
133
  const fiber = node[key];
124
- if (null !== fiber && 'object' === typeof fiber)
134
+ if (null !== fiber && 'object' === typeof fiber) {
125
135
  return fiber;
136
+ }
126
137
  }
127
138
  }
128
139
  }
@@ -136,8 +147,9 @@ function findFiber(doc) {
136
147
  */
137
148
  export function discoverStores(doc) {
138
149
  const entry = findFiber(doc);
139
- if (null === entry)
150
+ if (null === entry) {
140
151
  return [];
152
+ }
141
153
  const found = [];
142
154
  const used = new Set();
143
155
  try {
@@ -145,8 +157,9 @@ export function discoverStores(doc) {
145
157
  let visited = 0;
146
158
  while (stack.length > 0 && visited < MAX_FIBER_NODES) {
147
159
  const fiber = stack.pop();
148
- if (undefined === fiber || null === fiber)
160
+ if (undefined === fiber || null === fiber) {
149
161
  continue;
162
+ }
150
163
  visited += 1;
151
164
  const context = providerContext(fiber.type);
152
165
  if (null !== context) {
@@ -158,18 +171,21 @@ export function discoverStores(doc) {
158
171
  // a micro-frontend. Both are worth reading, so the second gets a suffixed key rather than
159
172
  // silently replacing the first.
160
173
  let key = store.key;
161
- for (let n = 2; used.has(key); n += 1)
174
+ for (let n = 2; used.has(key); n += 1) {
162
175
  key = `${store.key}${String(n)}`;
176
+ }
163
177
  used.add(key);
164
178
  found.push({ key, store: store.store, source: store.source });
165
179
  }
166
180
  }
167
181
  const sibling = fiber.sibling;
168
- if (null !== sibling && undefined !== sibling)
182
+ if (null !== sibling && undefined !== sibling) {
169
183
  stack.push(sibling);
184
+ }
170
185
  const child = fiber.child;
171
- if (null !== child && undefined !== child)
186
+ if (null !== child && undefined !== child) {
172
187
  stack.push(child);
188
+ }
173
189
  }
174
190
  }
175
191
  catch {
@@ -215,14 +231,16 @@ export function autoRegisterStores(doc) {
215
231
  // `tanstackQueryStore(client)`; discovery finds the same `client` and, keying on the name alone,
216
232
  // added `query` beside it — one cache listed twice in every state read. Comparing read values
217
233
  // cannot catch it either, because that adapter builds a fresh snapshot on every `getState`.
218
- if (sourceOwner(source) !== undefined)
234
+ if (sourceOwner(source) !== undefined) {
219
235
  continue;
236
+ }
220
237
  // A name we registered ourselves for a DIFFERENT source is stale: HMR re-ran the module that
221
238
  // creates the store, so the page now holds a new instance under the same name. Replace it —
222
239
  // registerStore swaps the getter and subscription — instead of reading the old instance forever.
223
240
  const replacesOurs = registered.has(key) && registered.get(key) !== source;
224
- if (!replacesOurs && (taken.has(key) || registered.has(key)))
241
+ if (!replacesOurs && (taken.has(key) || registered.has(key))) {
225
242
  continue;
243
+ }
226
244
  try {
227
245
  registerStore(key, store);
228
246
  }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Has React hydrated every server-rendered part of the page? Read from React's own fibers (#1654).
3
+ *
4
+ * The first commit is not the answer. Next commits the shell, and a Suspense boundary under it can
5
+ * hydrate seconds later. Until then the boundary's server-rendered button has no handler, so a click
6
+ * on it does nothing. React keeps such a boundary in the tree as a "dehydrated" fiber, so a walk of
7
+ * the committed tree can say which part still waits.
8
+ *
9
+ * A read that cannot be sure says UNKNOWN, never DONE. A wrong DONE sends replay into a page without
10
+ * handlers, which is the defect this exists for.
11
+ *
12
+ * HOST-SAFE: nothing here throws into the app. A fiber shape this module does not know gives UNKNOWN.
13
+ */
14
+ import { HydrationState } from '@reticlehq/core';
15
+ /**
16
+ * The most fibers one read visits, over all roots. A cap so that a strange fiber graph cannot hang
17
+ * the app. It is ten times the store-discovery walk, because here a walk cut short cannot answer.
18
+ */
19
+ export declare const MAX_HYDRATION_WALK = 200000;
20
+ /**
21
+ * The hydration state of the React trees on `doc`.
22
+ *
23
+ * @param known FiberRoots the commit hook named. They count wherever their container is on the
24
+ * page, so a root the page scan does not reach is still read.
25
+ */
26
+ export declare function readHydrationState(doc: Document, known?: Iterable<unknown>): HydrationState;
@@ -0,0 +1,180 @@
1
+ /**
2
+ * Has React hydrated every server-rendered part of the page? Read from React's own fibers (#1654).
3
+ *
4
+ * The first commit is not the answer. Next commits the shell, and a Suspense boundary under it can
5
+ * hydrate seconds later. Until then the boundary's server-rendered button has no handler, so a click
6
+ * on it does nothing. React keeps such a boundary in the tree as a "dehydrated" fiber, so a walk of
7
+ * the committed tree can say which part still waits.
8
+ *
9
+ * A read that cannot be sure says UNKNOWN, never DONE. A wrong DONE sends replay into a page without
10
+ * handlers, which is the defect this exists for.
11
+ *
12
+ * HOST-SAFE: nothing here throws into the app. A fiber shape this module does not know gives UNKNOWN.
13
+ */
14
+ import { HydrationState } from '@reticlehq/core';
15
+ import { findFiber, topOf } from './auto-stores.js';
16
+ /** React's fiber tags that this module reads (react-reconciler `ReactWorkTags`). */
17
+ const FiberTag = {
18
+ HOST_ROOT: 3,
19
+ SUSPENSE: 13,
20
+ DEHYDRATED_FRAGMENT: 18,
21
+ ACTIVITY: 31,
22
+ };
23
+ /** The fields of React's internals that this module reads. */
24
+ const FiberField = {
25
+ /** `FiberRoot.current`: the HostRoot fiber of the committed tree. */
26
+ CURRENT: 'current',
27
+ /** `FiberRoot.containerInfo`: the node the root renders into. Only a FiberRoot has it. */
28
+ CONTAINER_INFO: 'containerInfo',
29
+ /** `Fiber.stateNode`: for a HostRoot fiber, its FiberRoot. */
30
+ STATE_NODE: 'stateNode',
31
+ /** `Fiber.memoizedState`: the committed state of a root or a boundary. */
32
+ MEMOIZED_STATE: 'memoizedState',
33
+ /** `SuspenseState.dehydrated` and `ActivityState.dehydrated`: server HTML not hydrated yet. */
34
+ DEHYDRATED: 'dehydrated',
35
+ /** `RootState.isDehydrated`: a `hydrateRoot` root before its first commit. */
36
+ IS_DEHYDRATED: 'isDehydrated',
37
+ TAG: 'tag',
38
+ CHILD: 'child',
39
+ SIBLING: 'sibling',
40
+ };
41
+ /** React marks the node it renders into (for Next, the document) with its HostRoot fiber. */
42
+ const CONTAINER_PREFIX = '__reactContainer$';
43
+ /** How many elements to look at for a root container. A root is near the top of most pages. */
44
+ const MAX_CONTAINER_SCAN = 200;
45
+ /**
46
+ * The most fibers one read visits, over all roots. A cap so that a strange fiber graph cannot hang
47
+ * the app. It is ten times the store-discovery walk, because here a walk cut short cannot answer.
48
+ */
49
+ export const MAX_HYDRATION_WALK = 200_000;
50
+ function fieldOf(value, key) {
51
+ return null !== value && 'object' === typeof value
52
+ ? value[key]
53
+ : undefined;
54
+ }
55
+ function isObject(value) {
56
+ return null !== value && 'object' === typeof value;
57
+ }
58
+ /** The FiberRoot of a value: a FiberRoot itself, or any fiber of its tree. */
59
+ function fiberRootOf(value) {
60
+ if (!isObject(value)) {
61
+ return null;
62
+ }
63
+ if (isObject(fieldOf(value, FiberField.CURRENT)) &&
64
+ undefined !== fieldOf(value, FiberField.CONTAINER_INFO)) {
65
+ return value;
66
+ }
67
+ const top = topOf(value);
68
+ if (FiberTag.HOST_ROOT !== fieldOf(top, FiberField.TAG)) {
69
+ return null;
70
+ }
71
+ const root = fieldOf(top, FiberField.STATE_NODE);
72
+ return isObject(root) && isObject(fieldOf(root, FiberField.CURRENT)) ? root : null;
73
+ }
74
+ function containerFiber(node) {
75
+ if (!isObject(node)) {
76
+ return null;
77
+ }
78
+ for (const key of Object.keys(node)) {
79
+ if (key.startsWith(CONTAINER_PREFIX)) {
80
+ return node[key];
81
+ }
82
+ }
83
+ return null;
84
+ }
85
+ /**
86
+ * The React roots that `doc` shows: every root container among the document and its first elements.
87
+ * When none is there, the root of the first element that carries a fiber.
88
+ */
89
+ function rootsOnPage(doc) {
90
+ const nodes = [doc];
91
+ const elements = doc.querySelectorAll('*');
92
+ for (let i = 0; i < Math.min(elements.length, MAX_CONTAINER_SCAN); i += 1) {
93
+ nodes.push(elements[i]);
94
+ }
95
+ const roots = [];
96
+ for (const node of nodes) {
97
+ const root = fiberRootOf(containerFiber(node));
98
+ if (null !== root) {
99
+ roots.push(root);
100
+ }
101
+ }
102
+ if (0 === roots.length) {
103
+ const root = fiberRootOf(findFiber(doc));
104
+ if (null !== root) {
105
+ roots.push(root);
106
+ }
107
+ }
108
+ return roots;
109
+ }
110
+ function isDehydrated(fiber) {
111
+ const tag = fieldOf(fiber, FiberField.TAG);
112
+ if (FiberTag.DEHYDRATED_FRAGMENT === tag) {
113
+ return true;
114
+ }
115
+ if (FiberTag.SUSPENSE !== tag && FiberTag.ACTIVITY !== tag) {
116
+ return false;
117
+ }
118
+ const dehydrated = fieldOf(fieldOf(fiber, FiberField.MEMOIZED_STATE), FiberField.DEHYDRATED);
119
+ return null !== dehydrated && undefined !== dehydrated;
120
+ }
121
+ /** Walk the committed tree of one root, down to the first dehydrated part. */
122
+ function readRoot(root, budget) {
123
+ const current = fieldOf(root, FiberField.CURRENT);
124
+ if (true === fieldOf(fieldOf(current, FiberField.MEMOIZED_STATE), FiberField.IS_DEHYDRATED)) {
125
+ return { state: HydrationState.PENDING, left: budget };
126
+ }
127
+ const stack = [current];
128
+ let left = budget;
129
+ while (stack.length > 0) {
130
+ if (0 === left) {
131
+ return { state: HydrationState.UNKNOWN, left };
132
+ }
133
+ const fiber = stack.pop();
134
+ left -= 1;
135
+ if (isDehydrated(fiber)) {
136
+ return { state: HydrationState.PENDING, left };
137
+ }
138
+ for (const next of [fieldOf(fiber, FiberField.SIBLING), fieldOf(fiber, FiberField.CHILD)]) {
139
+ if (isObject(next)) {
140
+ stack.push(next);
141
+ }
142
+ }
143
+ }
144
+ return { state: HydrationState.DONE, left };
145
+ }
146
+ /**
147
+ * The hydration state of the React trees on `doc`.
148
+ *
149
+ * @param known FiberRoots the commit hook named. They count wherever their container is on the
150
+ * page, so a root the page scan does not reach is still read.
151
+ */
152
+ export function readHydrationState(doc, known = []) {
153
+ try {
154
+ const roots = new Set();
155
+ for (const value of [...known, ...rootsOnPage(doc)]) {
156
+ const root = fiberRootOf(value);
157
+ if (null !== root) {
158
+ roots.add(root);
159
+ }
160
+ }
161
+ if (0 === roots.size) {
162
+ return HydrationState.NONE;
163
+ }
164
+ let left = MAX_HYDRATION_WALK;
165
+ let unsure = false;
166
+ for (const root of roots) {
167
+ const walk = readRoot(root, left);
168
+ if (HydrationState.PENDING === walk.state) {
169
+ return HydrationState.PENDING;
170
+ }
171
+ unsure = unsure || HydrationState.UNKNOWN === walk.state;
172
+ left = walk.left;
173
+ }
174
+ return unsure ? HydrationState.UNKNOWN : HydrationState.DONE;
175
+ }
176
+ catch {
177
+ // A fiber shape this module does not know. Say so; never claim DONE on it.
178
+ return HydrationState.UNKNOWN;
179
+ }
180
+ }
@@ -1,16 +1,35 @@
1
1
  /**
2
2
  * React hydration detection — a science-backed differentiator. The published literature says no agent
3
3
  * framework can detect hydration completion from OUTSIDE the page: pre-hydration clicks are silent no-ops,
4
- * and only an in-app SDK knows when handlers attached. React's FIRST commit (via the DevTools commit hook)
5
- * is the hydration/initial-mount boundary — so the first commit is "handlers attached". We emit a
6
- * `reticle:hydration-complete` signal exactly once, letting the agent wait for interactivity instead of
7
- * clicking into the void. Pure tracker; the commit hook drives it, the SDK emits the signal.
4
+ * and only an in-app SDK knows when handlers attached. We emit a `reticle:hydration-complete` signal
5
+ * exactly once, letting the agent wait for interactivity instead of clicking into the void. Pure
6
+ * tracker; the commit hook drives it, the SDK emits the signal.
7
+ *
8
+ * With a page read, the signal fires on the first commit after which the read says DONE, or at
9
+ * install when React hydrated the page before the adapter loaded (#1654). Next installs the adapter in
10
+ * a `useEffect`, after the shell committed: a signal that waited for the next commit never came on a
11
+ * quiet page, and one that fired on any commit came before a slow Suspense boundary had handlers.
12
+ * NONE, PENDING and UNKNOWN all hold the signal back: none of them says that the page is hydrated.
8
13
  */
9
- /** The signal fired once React has committed its first render (handlers attached). */
14
+ import { HydrationState } from '@reticlehq/core';
15
+ /** The signal fired once React has hydrated the page (handlers attached). */
10
16
  export declare const HYDRATION_COMPLETE_SIGNAL = "reticle:hydration-complete";
17
+ /** Reads the page's hydration state. `roots` are the FiberRoots that commits named so far. */
18
+ export type HydrationRead = (roots: readonly unknown[]) => HydrationState;
11
19
  export interface HydrationTracker {
12
- /** Call on every React commit; fires `onHydrated` exactly once, on the first. */
13
- onCommit(): void;
20
+ /**
21
+ * Call on every React commit, with the FiberRoot that committed when the hook gives one. Fires
22
+ * `onHydrated` once, when the page is hydrated.
23
+ */
24
+ onCommit(root?: unknown): void;
25
+ /** Call once at install. Fires `onHydrated` when React already hydrated the whole page. */
26
+ onInstall(): void;
14
27
  isHydrated(): boolean;
28
+ /** DONE once hydrated. Before that, what the page read says now (NONE with no read). */
29
+ state(): HydrationState;
15
30
  }
16
- export declare function createHydrationTracker(onHydrated: () => void): HydrationTracker;
31
+ /**
32
+ * @param read The page's hydration state. Without one, the tracker cannot read the page: it fires on
33
+ * the first commit, as it did before #1654, and `onInstall` does nothing.
34
+ */
35
+ export declare function createHydrationTracker(onHydrated: () => void, read?: HydrationRead): HydrationTracker;
package/dist/hydration.js CHANGED
@@ -1,23 +1,75 @@
1
1
  /**
2
2
  * React hydration detection — a science-backed differentiator. The published literature says no agent
3
3
  * framework can detect hydration completion from OUTSIDE the page: pre-hydration clicks are silent no-ops,
4
- * and only an in-app SDK knows when handlers attached. React's FIRST commit (via the DevTools commit hook)
5
- * is the hydration/initial-mount boundary — so the first commit is "handlers attached". We emit a
6
- * `reticle:hydration-complete` signal exactly once, letting the agent wait for interactivity instead of
7
- * clicking into the void. Pure tracker; the commit hook drives it, the SDK emits the signal.
4
+ * and only an in-app SDK knows when handlers attached. We emit a `reticle:hydration-complete` signal
5
+ * exactly once, letting the agent wait for interactivity instead of clicking into the void. Pure
6
+ * tracker; the commit hook drives it, the SDK emits the signal.
7
+ *
8
+ * With a page read, the signal fires on the first commit after which the read says DONE, or at
9
+ * install when React hydrated the page before the adapter loaded (#1654). Next installs the adapter in
10
+ * a `useEffect`, after the shell committed: a signal that waited for the next commit never came on a
11
+ * quiet page, and one that fired on any commit came before a slow Suspense boundary had handlers.
12
+ * NONE, PENDING and UNKNOWN all hold the signal back: none of them says that the page is hydrated.
8
13
  */
9
- import { RETICLE_HYDRATION_SIGNAL } from '@reticlehq/core';
10
- /** The signal fired once React has committed its first render (handlers attached). */
14
+ import { HydrationState, RETICLE_HYDRATION_SIGNAL } from '@reticlehq/core';
15
+ /** The signal fired once React has hydrated the page (handlers attached). */
11
16
  export const HYDRATION_COMPLETE_SIGNAL = RETICLE_HYDRATION_SIGNAL;
12
- export function createHydrationTracker(onHydrated) {
17
+ /**
18
+ * @param read The page's hydration state. Without one, the tracker cannot read the page: it fires on
19
+ * the first commit, as it did before #1654, and `onInstall` does nothing.
20
+ */
21
+ export function createHydrationTracker(onHydrated, read) {
13
22
  let hydrated = false;
23
+ /*
24
+ * Set when a read could not reach the end of the tree (too large, or a shape this adapter does not
25
+ * know). Such a page stays so, and a walk of up to `MAX_HYDRATION_WALK` fibers on each of its
26
+ * commits would cost the app for nothing. So the tracker stops reading, and says UNKNOWN.
27
+ */
28
+ let unreadable = false;
29
+ const roots = [];
30
+ const settle = () => {
31
+ if (hydrated || unreadable) {
32
+ return;
33
+ }
34
+ if (read !== undefined) {
35
+ const now = read(roots);
36
+ unreadable = HydrationState.UNKNOWN === now;
37
+ if (unreadable) {
38
+ roots.length = 0;
39
+ }
40
+ if (HydrationState.DONE !== now) {
41
+ return;
42
+ }
43
+ }
44
+ roots.length = 0;
45
+ hydrated = true;
46
+ onHydrated();
47
+ };
14
48
  return {
15
- onCommit() {
16
- if (hydrated)
49
+ onCommit: (root) => {
50
+ // Once the answer is fixed, no root is read again, so none is kept.
51
+ if (hydrated || unreadable) {
17
52
  return;
18
- hydrated = true;
19
- onHydrated();
53
+ }
54
+ if (null !== root && 'object' === typeof root && !roots.includes(root)) {
55
+ roots.push(root);
56
+ }
57
+ settle();
58
+ },
59
+ onInstall: () => {
60
+ if (read !== undefined) {
61
+ settle();
62
+ }
20
63
  },
21
64
  isHydrated: () => hydrated,
65
+ state: () => {
66
+ if (hydrated) {
67
+ return HydrationState.DONE;
68
+ }
69
+ if (unreadable) {
70
+ return HydrationState.UNKNOWN;
71
+ }
72
+ return read === undefined ? HydrationState.NONE : read(roots);
73
+ },
22
74
  };
23
75
  }
package/dist/index.d.ts CHANGED
@@ -61,7 +61,7 @@ export interface InstallOptions {
61
61
  */
62
62
  export declare function install(options?: InstallOptions): void;
63
63
  export { installRenderMeter, resetRenderMeter, getRenderStats, type RenderStats, } from './render-meter.js';
64
- export { HYDRATION_COMPLETE_SIGNAL, createHydrationTracker, type HydrationTracker, } from './hydration.js';
64
+ export { HYDRATION_COMPLETE_SIGNAL, createHydrationTracker, type HydrationRead, type HydrationTracker, } from './hydration.js';
65
65
  export { buildErrorBoundaryData, reticleOnCaughtError, type ErrorBoundaryData, } from './error-boundary.js';
66
66
  export { buildHydrationErrorData, isHydrationMismatch, reticleOnRecoverableError, type HydrationErrorData, } from './hydration-error.js';
67
67
  export { createCommitAggregator, type CommitAggregator } from './commit-aggregator.js';
package/dist/index.js CHANGED
@@ -30,11 +30,13 @@ function toPosix(path) {
30
30
  */
31
31
  export function relativeToRoot(file) {
32
32
  const root = globalThis[RETICLE_ROOT_GLOBAL];
33
- if (typeof root !== 'string' || 0 === root.length)
33
+ if (typeof root !== 'string' || 0 === root.length) {
34
34
  return file;
35
+ }
35
36
  const normalizedRoot = toPosix(root).replace(/\/+$/, '');
36
- if (0 === normalizedRoot.length)
37
+ if (0 === normalizedRoot.length) {
37
38
  return file;
39
+ }
38
40
  const normalizedFile = toPosix(file);
39
41
  const prefix = `${normalizedRoot}/`;
40
42
  const matches = normalizedFile.startsWith(prefix) ||
@@ -77,8 +79,9 @@ function isFrameworkNoise(name) {
77
79
  */
78
80
  function currentFiber(fiber) {
79
81
  const alternate = fiber.alternate;
80
- if (alternate === undefined || null === alternate)
82
+ if (alternate === undefined || null === alternate) {
81
83
  return fiber;
84
+ }
82
85
  let top = fiber;
83
86
  let depth = 0;
84
87
  while (top.return !== null && depth < MAX_DEPTH) {
@@ -86,28 +89,33 @@ function currentFiber(fiber) {
86
89
  depth += 1;
87
90
  }
88
91
  const fiberRoot = top.stateNode;
89
- if (typeof fiberRoot !== 'object' || null === fiberRoot)
92
+ if (typeof fiberRoot !== 'object' || null === fiberRoot) {
90
93
  return fiber;
94
+ }
91
95
  const committed = fiberRoot.current;
92
- if (typeof committed !== 'object' || null === committed)
96
+ if (typeof committed !== 'object' || null === committed) {
93
97
  return fiber;
98
+ }
94
99
  return committed === top ? fiber : alternate;
95
100
  }
96
101
  function getFiber(el) {
97
102
  const key = Object.keys(el).find((k) => FIBER_PREFIXES.some((p) => k.startsWith(p)));
98
- if (key === undefined)
103
+ if (key === undefined) {
99
104
  return null;
105
+ }
100
106
  const value = el[key];
101
- if (value === undefined || null === value)
107
+ if (value === undefined || null === value) {
102
108
  return null;
109
+ }
103
110
  return currentFiber(value);
104
111
  }
105
112
  /** Display name of a component type (function, forwardRef/memo object, or host string). */
106
113
  function componentName(type) {
107
114
  if ('function' === typeof type) {
108
115
  const fn = type;
109
- if (fn.displayName !== undefined && fn.displayName.length > 0)
116
+ if (fn.displayName !== undefined && fn.displayName.length > 0) {
110
117
  return fn.displayName;
118
+ }
111
119
  return fn.name !== undefined && fn.name.length > 0 ? fn.name : null;
112
120
  }
113
121
  if ('object' === typeof type && type !== null) {
@@ -128,8 +136,9 @@ export function identify(el) {
128
136
  const name = componentName(fiber.elementType ?? fiber.type);
129
137
  if (name !== null && rawStack[rawStack.length - 1] !== name) {
130
138
  rawStack.push(name);
131
- if (!isFrameworkNoise(name) && stack[stack.length - 1] !== name)
139
+ if (!isFrameworkNoise(name) && stack[stack.length - 1] !== name) {
132
140
  stack.push(name);
141
+ }
133
142
  }
134
143
  // `identify()` is on the ACT path as well as the inspect path, so one null fiber anywhere in
135
144
  // this walk takes out reticle_act / reticle_act_and_wait / reticle_inspect for the whole app —
@@ -140,8 +149,9 @@ export function identify(el) {
140
149
  if (source === undefined && debugSource !== undefined && debugSource !== null) {
141
150
  source = { file: relativeToRoot(debugSource.fileName), line: debugSource.lineNumber };
142
151
  const column = debugSource.columnNumber;
143
- if (column !== undefined && column !== null)
152
+ if (column !== undefined && column !== null) {
144
153
  source.column = column;
154
+ }
145
155
  }
146
156
  fiber = fiber.return;
147
157
  }
@@ -152,24 +162,29 @@ export function identify(el) {
152
162
  }
153
163
  // Prefer the de-noised stack; fall back to the nearest raw name if filtering left nothing.
154
164
  const componentStack = stack.length > 0 ? stack : rawStack.slice(0, 1);
155
- if (0 === componentStack.length && source === undefined)
165
+ if (0 === componentStack.length && source === undefined) {
156
166
  return null;
167
+ }
157
168
  const info = { componentStack };
158
- if (source !== undefined)
169
+ if (source !== undefined) {
159
170
  info.source = source;
171
+ }
160
172
  return info;
161
173
  }
162
174
  function sourceFromAttribute(el) {
163
175
  const stamped = el.closest(`[${DATA_RETICLE_SOURCE_ATTR}]`);
164
176
  const raw = stamped?.getAttribute(DATA_RETICLE_SOURCE_ATTR);
165
- if (null === raw || raw === undefined)
177
+ if (null === raw || raw === undefined) {
166
178
  return undefined;
179
+ }
167
180
  const match = /^(.*):(\d+):(\d+)$/.exec(raw);
168
- if (null === match)
181
+ if (null === match) {
169
182
  return undefined;
183
+ }
170
184
  const [, file, line, column] = match;
171
- if (file === undefined || line === undefined || column === undefined)
185
+ if (file === undefined || line === undefined || column === undefined) {
172
186
  return undefined;
187
+ }
173
188
  return { file, line: Number(line), column: Number(column) };
174
189
  }
175
190
  /** Find the nearest function-component fiber above a host node. */
@@ -178,8 +193,9 @@ function nearestComponentFiber(el) {
178
193
  let depth = 0;
179
194
  while (fiber !== null && depth < MAX_DEPTH) {
180
195
  depth += 1;
181
- if ('function' === typeof fiber.type || 'function' === typeof fiber.elementType)
196
+ if ('function' === typeof fiber.type || 'function' === typeof fiber.elementType) {
182
197
  return fiber;
198
+ }
183
199
  fiber = fiber.return;
184
200
  }
185
201
  return null;
@@ -191,20 +207,26 @@ function nearestComponentFiber(el) {
191
207
  * serializing those un-guarded can cause hangs. Never throws.
192
208
  */
193
209
  function safeValue(value, depth, seen) {
194
- if (null === value)
210
+ if (null === value) {
195
211
  return null;
212
+ }
196
213
  const t = typeof value;
197
- if ('string' === t || 'number' === t || 'boolean' === t)
214
+ if ('string' === t || 'number' === t || 'boolean' === t) {
198
215
  return value;
199
- if ('undefined' === t || 'function' === t || 'symbol' === t || 'bigint' === t)
216
+ }
217
+ if ('undefined' === t || 'function' === t || 'symbol' === t || 'bigint' === t) {
200
218
  return null;
201
- if (typeof Node !== 'undefined' && value instanceof Node)
219
+ }
220
+ if (typeof Node !== 'undefined' && value instanceof Node) {
202
221
  return DOM_NODE_MARKER;
203
- if (depth >= MAX_SERIALIZE_DEPTH)
222
+ }
223
+ if (depth >= MAX_SERIALIZE_DEPTH) {
204
224
  return null;
225
+ }
205
226
  const obj = value;
206
- if (seen.has(obj))
227
+ if (seen.has(obj)) {
207
228
  return null;
229
+ }
208
230
  seen.add(obj);
209
231
  if (Array.isArray(value)) {
210
232
  const out = value.slice(0, MAX_SERIALIZE_ITEMS).map((v) => safeValue(v, depth + 1, seen));
@@ -247,8 +269,9 @@ export function readState(el) {
247
269
  while ('object' === typeof hook && i < MAX_HOOKS) {
248
270
  hooks.push(safeValue(hook.memoizedState, 0, seen));
249
271
  const next = hook.next;
250
- if (null === next || typeof next !== 'object')
272
+ if (null === next || typeof next !== 'object') {
251
273
  break;
274
+ }
252
275
  hook = next;
253
276
  i += 1;
254
277
  }
@@ -272,8 +295,9 @@ const HOVER_HANDLER_KEYS = [
272
295
  export function hasHoverHandlers(el) {
273
296
  const fiber = getFiber(el);
274
297
  const props = fiber?.memoizedProps;
275
- if (typeof props !== 'object' || null === props)
298
+ if (typeof props !== 'object' || null === props) {
276
299
  return false;
300
+ }
277
301
  const p = props;
278
302
  return HOVER_HANDLER_KEYS.some((k) => 'function' === typeof p[k]);
279
303
  }
@@ -289,8 +313,9 @@ let installed = false;
289
313
  * silence, indistinguishable from an idle page.
290
314
  */
291
315
  export function install(options) {
292
- if (installed)
316
+ if (installed) {
293
317
  return;
318
+ }
294
319
  installed = true;
295
320
  registerAdapter({ name: 'react', identify, readState, hasHoverHandlers });
296
321
  installRenderMeter({ discoverStores: false !== options?.discoverStores });
@@ -1,7 +1,32 @@
1
+ /**
2
+ * React render meter — counts commits the way React DevTools does, via the global
3
+ * `__REACT_DEVTOOLS_GLOBAL_HOOK__.onCommitFiberRoot` callback (one call per committed render). This is
4
+ * the Reticle-only perf signal: Playwright/DevTools-MCP cannot observe a single React render, so a page
5
+ * that is thrashing (committing many times a second) while the DOM stays visually identical — a
6
+ * wasted-render storm — looks idle to them. Reticle sees the commit rate.
7
+ *
8
+ * Exposed as a registered store (`__reticle_renders`) so it reads through the normal `reticle_state` path —
9
+ * no new wire surface. Total commits is the robust, version-tolerant signal; we deliberately do NOT
10
+ * attribute per-component (React clears the per-fiber work flags during commit, before this fires, so
11
+ * a post-commit walk can't reliably tell which component re-rendered without the profiler build).
12
+ *
13
+ * HOST-SAFE BY CONSTRUCTION: everything is wrapped in try/catch and React itself guards its calls to
14
+ * the devtools hook in try/catch, so a fault here can never break the host app's rendering. If a real
15
+ * React DevTools hook is already present we AUGMENT it (call the original too); otherwise we install a
16
+ * complete minimal hook. MUST be installed before `react-dom` initializes (React reads the hook at
17
+ * renderer-inject time) — import this as the first side-effect in the app entry, before React.
18
+ */
19
+ import { HydrationState } from '@reticlehq/core';
1
20
  /** The render stats surfaced via the `__reticle_renders` store (read with reticle_state). */
2
21
  export interface RenderStats {
3
22
  /** Total React commits observed since install (monotonic; diff over a window for a rate). */
4
23
  commits: number;
24
+ /**
25
+ * Whether React hydrated every server-rendered part of the page (`RenderStatsField.HYDRATION`).
26
+ * `done` stays once reached. Before that, each read looks at the page again. Replay waits while it
27
+ * is `pending`, because a click on a part that is not hydrated does nothing (#1654).
28
+ */
29
+ hydration: HydrationState;
5
30
  }
6
31
  export declare function getRenderStats(): RenderStats;
7
32
  /** Reset the commit counter — call before a measured window so the count is window-scoped. */
@@ -16,20 +16,28 @@
16
16
  * complete minimal hook. MUST be installed before `react-dom` initializes (React reads the hook at
17
17
  * renderer-inject time) — import this as the first side-effect in the app entry, before React.
18
18
  */
19
- import { RETICLE_RENDER_PREHOOK, RETICLE_RENDERS_STORE } from '@reticlehq/core';
19
+ import { HydrationState, RETICLE_RENDER_PREHOOK, RETICLE_RENDERS_STORE } from '@reticlehq/core';
20
20
  import { registerStore } from '@reticlehq/browser';
21
21
  import { HYDRATION_COMPLETE_SIGNAL, createHydrationTracker } from './hydration.js';
22
+ import { readHydrationState } from './hydration-state.js';
22
23
  import { createCommitAggregator } from './commit-aggregator.js';
23
24
  import { autoRegisterStores } from './auto-stores.js';
24
25
  const HOOK_KEY = '__REACT_DEVTOOLS_GLOBAL_HOOK__';
26
+ /** Where the FiberRoot is in the arguments of `onCommitFiberRoot(rendererID, root, ...)`. */
27
+ const COMMIT_ROOT_ARG = 1;
25
28
  const RENDER_STORE = RETICLE_RENDERS_STORE;
26
- // Fire the hydration-complete signal (once, on the first commit) via the SDK instance if it is present.
27
- // Structural access avoids importing the whole Reticle type into this tooling module.
28
- const hydration = createHydrationTracker(() => {
29
- const instance = globalThis
30
- .__reticleInstance;
31
- instance?.signal?.(HYDRATION_COMPLETE_SIGNAL);
32
- });
29
+ // Fire the hydration-complete signal (once, when no server-rendered part waits) via the SDK instance if
30
+ // it is present. Structural access avoids importing the whole Reticle type into this tooling module.
31
+ function createPageHydration() {
32
+ return createHydrationTracker(() => {
33
+ const instance = globalThis
34
+ .__reticleInstance;
35
+ instance?.signal?.(HYDRATION_COMPLETE_SIGNAL);
36
+ },
37
+ // No document (a server import) has no React tree to wait for.
38
+ (roots) => 'undefined' === typeof document ? HydrationState.NONE : readHydrationState(document, roots));
39
+ }
40
+ let hydration = createPageHydration();
33
41
  // Access the SDK instance structurally (avoids importing the whole Reticle type into this tooling module).
34
42
  function reticleInstance() {
35
43
  return globalThis
@@ -39,10 +47,12 @@ function reticleInstance() {
39
47
  // storm is one event of magnitude N, never a per-render flood. requestAnimationFrame when available.
40
48
  const commitStream = createCommitAggregator({
41
49
  schedule: (fn) => {
42
- if ('function' === typeof requestAnimationFrame)
50
+ if ('function' === typeof requestAnimationFrame) {
43
51
  requestAnimationFrame(() => fn());
44
- else
52
+ }
53
+ else {
45
54
  setTimeout(fn, 16);
55
+ }
46
56
  },
47
57
  flush: (n) => reticleInstance()?.renderCommit?.(n),
48
58
  });
@@ -63,10 +73,14 @@ const DISCOVERY_COMMITS = 10;
63
73
  */
64
74
  let discoveryAttempts = 0;
65
75
  let shouldDiscover = true;
66
- /** One React commit: bump the counter, fire hydration on the first, and feed the throttled stream. */
67
- function onReactCommit() {
76
+ /**
77
+ * One React commit: bump the counter, check hydration, and feed the throttled stream. React calls the
78
+ * hook as `onCommitFiberRoot(rendererID, root, ...)`; the root is how hydration finds a tree that the
79
+ * page scan does not reach.
80
+ */
81
+ function onReactCommit(...args) {
68
82
  commits += 1;
69
- hydration.onCommit();
83
+ hydration.onCommit(args[COMMIT_ROOT_ARG]);
70
84
  commitStream.onCommit();
71
85
  if (shouldDiscover && discoveryAttempts < DISCOVERY_COMMITS && 'undefined' !== typeof document) {
72
86
  discoveryAttempts += 1;
@@ -88,15 +102,16 @@ let commits = 0;
88
102
  * rest of this layer refuses to make.
89
103
  */
90
104
  function seedCommits(prior) {
91
- if (Number.isFinite(prior) && prior > commits)
105
+ if (Number.isFinite(prior) && prior > commits) {
92
106
  commits = prior;
107
+ }
93
108
  }
94
109
  let installed = false;
95
110
  function noop() {
96
111
  /* React calls these; a no-op keeps a freshly-installed hook complete. */
97
112
  }
98
113
  export function getRenderStats() {
99
- return { commits };
114
+ return { commits, hydration: hydration.state() };
100
115
  }
101
116
  /** Reset the commit counter — call before a measured window so the count is window-scoped. */
102
117
  export function resetRenderMeter() {
@@ -105,6 +120,7 @@ export function resetRenderMeter() {
105
120
  /** Reset internal state for test isolation. */
106
121
  export function resetRenderMeterForTest() {
107
122
  installed = false;
123
+ hydration = createPageHydration();
108
124
  shouldDiscover = true;
109
125
  discoveryAttempts = 0;
110
126
  commits = 0;
@@ -114,8 +130,9 @@ export function resetRenderMeterForTest() {
114
130
  * never throws. Call BEFORE react-dom loads.
115
131
  */
116
132
  export function installRenderMeter(options) {
117
- if (installed)
133
+ if (installed) {
118
134
  return;
135
+ }
119
136
  installed = true;
120
137
  if (false === options?.discoverStores) {
121
138
  shouldDiscover = false;
@@ -133,6 +150,7 @@ export function installRenderMeter(options) {
133
150
  seedCommits(pre.commits);
134
151
  pre.sinks.push(onReactCommit);
135
152
  registerStore(RENDER_STORE, () => getRenderStats());
153
+ hydration.onInstall();
136
154
  return;
137
155
  }
138
156
  const existing = root[HOOK_KEY];
@@ -152,7 +170,7 @@ export function installRenderMeter(options) {
152
170
  ? existing.onCommitFiberRoot.bind(existing)
153
171
  : undefined;
154
172
  existing.onCommitFiberRoot = (...args) => {
155
- onReactCommit();
173
+ onReactCommit(...args);
156
174
  if (original !== undefined) {
157
175
  try {
158
176
  original(...args);
@@ -164,6 +182,8 @@ export function installRenderMeter(options) {
164
182
  };
165
183
  }
166
184
  registerStore(RENDER_STORE, () => getRenderStats());
185
+ // React may have hydrated the page before this ran, and no commit may come after it.
186
+ hydration.onInstall();
167
187
  }
168
188
  catch {
169
189
  /* never break the host app */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@reticlehq/react",
3
- "version": "3.10.11",
3
+ "version": "3.11.0",
4
4
  "description": "Reticle React adapter — maps a DOM ref to its component stack and source file via the fiber tree.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -17,8 +17,8 @@
17
17
  "./package.json": "./package.json"
18
18
  },
19
19
  "dependencies": {
20
- "@reticlehq/browser": "3.10.11",
21
- "@reticlehq/core": "3.10.11"
20
+ "@reticlehq/browser": "3.11.0",
21
+ "@reticlehq/core": "3.11.0"
22
22
  },
23
23
  "peerDependencies": {
24
24
  "react": ">=18"