@reticlehq/react 2.12.0 → 2.13.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.
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Find the app's state stores WITHOUT the app registering them.
3
+ *
4
+ * `registerStore` is the highest-value line in a Reticle install and the one most likely never to be
5
+ * written: `init` can only offer a commented suggestion, because the argument it would need
6
+ * (which client, which store instance) is knowable only by reading the source. Measured on real
7
+ * apps, that suggestion mostly stays a comment — the install reports every step green,
8
+ * `hasCapabilities` stays false, and `reticle_state` is empty forever. The agent doing the install
9
+ * then spends a handful of turns being told to go finish the file, which is most of what makes
10
+ * onboarding long.
11
+ *
12
+ * The observation that removes the whole step: every context-based state library already hands its
13
+ * store to React as a prop. `<Provider store>` renders `ReactReduxContext.Provider value={{store}}`,
14
+ * `<QueryClientProvider client>` renders `QueryClientContext.Provider value={client}`. So the store
15
+ * is sitting in the fiber tree under `memoizedProps.value`, and one walk finds it.
16
+ *
17
+ * WHAT THIS CANNOT FIND, deliberately: module-scope stores (Zustand, Valtio, MobX singletons, Jotai
18
+ * atoms). They are never passed through a provider, so nothing in the tree points at them and only
19
+ * the app can hand them over. Those still need `registerStore`, and the capability report must keep
20
+ * saying so — an auto-discovery that quietly covered 60% of apps while reading as though it covered
21
+ * all of them would be a worse failure than the manual step it replaced.
22
+ *
23
+ * A store the app registered itself ALWAYS wins. This never overwrites a name that is already taken.
24
+ */
25
+ import { type StoreLike } from '@reticlehq/browser';
26
+ /** Names for the libraries we can recognise by shape rather than by import. */
27
+ export declare const AUTO_STORE_KEY: {
28
+ readonly REDUX: "redux";
29
+ readonly QUERY: "query";
30
+ /** Anything store-shaped behind an anonymous context. */
31
+ readonly STORE: "store";
32
+ };
33
+ export interface DiscoveredStore {
34
+ key: string;
35
+ store: StoreLike;
36
+ /**
37
+ * The object the store was built FROM — the Redux store, the QueryClient.
38
+ *
39
+ * Carried separately from `store` because for an adapter-wrapped library the two are different
40
+ * objects, and the source is the only one that can answer "has the app already registered this?".
41
+ */
42
+ source: object;
43
+ }
44
+ /**
45
+ * Decide whether one context value is a store, and what to call it.
46
+ *
47
+ * Ordered most-specific first: react-redux nests the store under `.store` and would otherwise fall
48
+ * through to the generic branch under whatever its context is called this major version.
49
+ */
50
+ export declare function classifyProviderValue(value: unknown, displayName: string | undefined): DiscoveredStore | null;
51
+ /**
52
+ * Every store-shaped context value in the mounted tree, in mount order.
53
+ *
54
+ * Iterative rather than recursive: a deep tree is ordinary in a real app, and a stack overflow
55
+ * inside instrumentation would take the host app's render with it.
56
+ */
57
+ export declare function discoverStores(doc: Document): DiscoveredStore[];
58
+ /** Test seam: forget what was discovered so a fresh tree can be walked. */
59
+ export declare function resetAutoStores(): void;
60
+ /**
61
+ * Register everything discovered that is not already spoken for, and return the new names.
62
+ *
63
+ * Safe to call on every commit: it re-walks (providers can mount late) but only registers sources
64
+ * nothing has claimed, so the steady state is a walk and no writes.
65
+ */
66
+ export declare function autoRegisterStores(doc: Document): string[];
@@ -0,0 +1,237 @@
1
+ /**
2
+ * Find the app's state stores WITHOUT the app registering them.
3
+ *
4
+ * `registerStore` is the highest-value line in a Reticle install and the one most likely never to be
5
+ * written: `init` can only offer a commented suggestion, because the argument it would need
6
+ * (which client, which store instance) is knowable only by reading the source. Measured on real
7
+ * apps, that suggestion mostly stays a comment — the install reports every step green,
8
+ * `hasCapabilities` stays false, and `reticle_state` is empty forever. The agent doing the install
9
+ * then spends a handful of turns being told to go finish the file, which is most of what makes
10
+ * onboarding long.
11
+ *
12
+ * The observation that removes the whole step: every context-based state library already hands its
13
+ * store to React as a prop. `<Provider store>` renders `ReactReduxContext.Provider value={{store}}`,
14
+ * `<QueryClientProvider client>` renders `QueryClientContext.Provider value={client}`. So the store
15
+ * is sitting in the fiber tree under `memoizedProps.value`, and one walk finds it.
16
+ *
17
+ * WHAT THIS CANNOT FIND, deliberately: module-scope stores (Zustand, Valtio, MobX singletons, Jotai
18
+ * atoms). They are never passed through a provider, so nothing in the tree points at them and only
19
+ * the app can hand them over. Those still need `registerStore`, and the capability report must keep
20
+ * saying so — an auto-discovery that quietly covered 60% of apps while reading as though it covered
21
+ * all of them would be a worse failure than the manual step it replaced.
22
+ *
23
+ * A store the app registered itself ALWAYS wins. This never overwrites a name that is already taken.
24
+ */
25
+ import { registerStore, sourceOwner, storeNames, tanstackQueryStore, unregisterStore, } from '@reticlehq/browser';
26
+ /** Names for the libraries we can recognise by shape rather than by import. */
27
+ export const AUTO_STORE_KEY = {
28
+ REDUX: 'redux',
29
+ QUERY: 'query',
30
+ /** Anything store-shaped behind an anonymous context. */
31
+ STORE: 'store',
32
+ };
33
+ /** React stamps its fiber on host nodes under a key with a per-copy suffix. */
34
+ const FIBER_PREFIXES = ['__reactFiber$', '__reactInternalInstance$'];
35
+ /** How many elements to look at before concluding this is not a React page. A root is near the top. */
36
+ const MAX_HOST_SCAN = 200;
37
+ /** Fibers visited in one walk. A cap, not a budget — real trees finish far inside it. */
38
+ const MAX_FIBER_NODES = 20000;
39
+ /** React 18 renders a provider whose `type` carries this; React 19 uses the context object itself. */
40
+ const PROVIDER_TYPE = Symbol.for('react.provider');
41
+ const CONTEXT_TYPE = Symbol.for('react.context');
42
+ function isStoreLike(value) {
43
+ if (null === value)
44
+ return false;
45
+ if ('object' !== typeof value && 'function' !== typeof value)
46
+ return false;
47
+ const candidate = value;
48
+ return 'function' === typeof candidate.getState && 'function' === typeof candidate.subscribe;
49
+ }
50
+ /** A TanStack QueryClient, identified by the one method the adapter needs. */
51
+ function isQueryClient(value) {
52
+ if (null === value || 'object' !== typeof value)
53
+ return false;
54
+ return 'function' === typeof value.getQueryCache;
55
+ }
56
+ /**
57
+ * Turn a context display name into a store key.
58
+ *
59
+ * Lowercased and stripped to word characters because the key is typed by an agent into
60
+ * `reticle_state({ store })`, and `ReactRedux.Provider` is not a thing anyone will type correctly.
61
+ */
62
+ function keyFromName(name) {
63
+ if ('string' !== typeof name)
64
+ return undefined;
65
+ const cleaned = name.toLowerCase().replace(/[^a-z0-9]/g, '');
66
+ return cleaned.length > 0 ? cleaned : undefined;
67
+ }
68
+ /**
69
+ * Decide whether one context value is a store, and what to call it.
70
+ *
71
+ * Ordered most-specific first: react-redux nests the store under `.store` and would otherwise fall
72
+ * through to the generic branch under whatever its context is called this major version.
73
+ */
74
+ export function classifyProviderValue(value, displayName) {
75
+ if (null === value || undefined === value)
76
+ return null;
77
+ const nested = value.store;
78
+ if (isStoreLike(nested))
79
+ return { key: AUTO_STORE_KEY.REDUX, store: nested, source: nested };
80
+ if (isQueryClient(value)) {
81
+ return {
82
+ key: AUTO_STORE_KEY.QUERY,
83
+ // The adapter already exists and carries what a bare `getState` would lose — staleness and
84
+ // fetch status, which is the whole reason a cache read beats a DOM read.
85
+ store: tanstackQueryStore(value),
86
+ source: value,
87
+ };
88
+ }
89
+ if (isStoreLike(value)) {
90
+ return { key: keyFromName(displayName) ?? AUTO_STORE_KEY.STORE, store: value, source: value };
91
+ }
92
+ return null;
93
+ }
94
+ /** The context a provider fiber renders, across the versions that spell it differently. */
95
+ function providerContext(type) {
96
+ if (null === type || 'object' !== typeof type)
97
+ return null;
98
+ const marker = type.$$typeof;
99
+ if (PROVIDER_TYPE === marker) {
100
+ const inner = type._context;
101
+ return inner ?? type;
102
+ }
103
+ if (CONTEXT_TYPE === marker)
104
+ return type;
105
+ return null;
106
+ }
107
+ /** The topmost fiber reachable from one node — the tree we then walk downward. */
108
+ function topOf(fiber) {
109
+ let current = fiber;
110
+ for (let i = 0; i < MAX_FIBER_NODES; i += 1) {
111
+ const parent = current.return;
112
+ if (null === parent || undefined === parent)
113
+ return current;
114
+ current = parent;
115
+ }
116
+ return current;
117
+ }
118
+ /** Any fiber React has stamped on the document, as the entry point into the tree. */
119
+ function findFiber(doc) {
120
+ const elements = doc.querySelectorAll('*');
121
+ const limit = Math.min(elements.length, MAX_HOST_SCAN);
122
+ for (let i = 0; i < limit; i += 1) {
123
+ const node = elements[i];
124
+ if (undefined === node)
125
+ continue;
126
+ for (const key of Object.keys(node)) {
127
+ if (FIBER_PREFIXES.some((prefix) => key.startsWith(prefix))) {
128
+ const fiber = node[key];
129
+ if (null !== fiber && 'object' === typeof fiber)
130
+ return fiber;
131
+ }
132
+ }
133
+ }
134
+ return null;
135
+ }
136
+ /**
137
+ * Every store-shaped context value in the mounted tree, in mount order.
138
+ *
139
+ * Iterative rather than recursive: a deep tree is ordinary in a real app, and a stack overflow
140
+ * inside instrumentation would take the host app's render with it.
141
+ */
142
+ export function discoverStores(doc) {
143
+ const entry = findFiber(doc);
144
+ if (null === entry)
145
+ return [];
146
+ const found = [];
147
+ const used = new Set();
148
+ try {
149
+ const stack = [topOf(entry)];
150
+ let visited = 0;
151
+ while (stack.length > 0 && visited < MAX_FIBER_NODES) {
152
+ const fiber = stack.pop();
153
+ if (undefined === fiber || null === fiber)
154
+ continue;
155
+ visited += 1;
156
+ const context = providerContext(fiber.type);
157
+ if (null !== context) {
158
+ const props = fiber.memoizedProps;
159
+ const value = null !== props && 'object' === typeof props ? props.value : null;
160
+ const store = classifyProviderValue(value, context.displayName);
161
+ if (null !== store) {
162
+ // Two providers of the same shape are ordinary — a nested QueryClient, two Redux stores in
163
+ // a micro-frontend. Both are worth reading, so the second gets a suffixed key rather than
164
+ // silently replacing the first.
165
+ let key = store.key;
166
+ for (let n = 2; used.has(key); n += 1)
167
+ key = `${store.key}${String(n)}`;
168
+ used.add(key);
169
+ found.push({ key, store: store.store, source: store.source });
170
+ }
171
+ }
172
+ const sibling = fiber.sibling;
173
+ if (null !== sibling && undefined !== sibling)
174
+ stack.push(sibling);
175
+ const child = fiber.child;
176
+ if (null !== child && undefined !== child)
177
+ stack.push(child);
178
+ }
179
+ }
180
+ catch {
181
+ // A fiber shape we have not seen must never break the host app. Whatever was found still counts.
182
+ }
183
+ return found;
184
+ }
185
+ /** What this module registered: our key → the source object we registered it for. */
186
+ let registered = new Map();
187
+ /** Test seam: forget what was discovered so a fresh tree can be walked. */
188
+ export function resetAutoStores() {
189
+ registered = new Map();
190
+ }
191
+ /**
192
+ * Give up a name we claimed for a store the app has since registered itself.
193
+ *
194
+ * The order of the two is a genuine race: the app registers inside `connect()`, discovery runs on a
195
+ * React commit, and which lands first depends on the app. Handling only the app-first order would
196
+ * leave the other one shipping the exact duplicate this exists to prevent — one cache under two
197
+ * names, differing only by which of them the reader happens to try.
198
+ */
199
+ function releaseSupersededNames() {
200
+ for (const [key, source] of [...registered]) {
201
+ const owner = sourceOwner(source);
202
+ if (owner !== undefined && owner !== key) {
203
+ unregisterStore(key);
204
+ registered.delete(key);
205
+ }
206
+ }
207
+ }
208
+ /**
209
+ * Register everything discovered that is not already spoken for, and return the new names.
210
+ *
211
+ * Safe to call on every commit: it re-walks (providers can mount late) but only registers sources
212
+ * nothing has claimed, so the steady state is a walk and no writes.
213
+ */
214
+ export function autoRegisterStores(doc) {
215
+ releaseSupersededNames();
216
+ const taken = new Set(storeNames());
217
+ const added = [];
218
+ for (const { key, store, source } of discoverStores(doc)) {
219
+ // The SOURCE, not the name and not the read value. bench-app registers `queries` from
220
+ // `tanstackQueryStore(client)`; discovery finds the same `client` and, keying on the name alone,
221
+ // added `query` beside it — one cache listed twice in every state read. Comparing read values
222
+ // cannot catch it either, because that adapter builds a fresh snapshot on every `getState`.
223
+ if (sourceOwner(source) !== undefined)
224
+ continue;
225
+ if (taken.has(key) || registered.has(key))
226
+ continue;
227
+ try {
228
+ registerStore(key, store);
229
+ }
230
+ catch {
231
+ continue; // a store whose getState throws on registration is not worth taking the app down for
232
+ }
233
+ registered.set(key, source);
234
+ added.push(key);
235
+ }
236
+ return added;
237
+ }
@@ -20,6 +20,7 @@ import { 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
22
  import { createCommitAggregator } from './commit-aggregator.js';
23
+ import { autoRegisterStores } from './auto-stores.js';
23
24
  const HOOK_KEY = '__REACT_DEVTOOLS_GLOBAL_HOOK__';
24
25
  const RENDER_STORE = RETICLE_RENDERS_STORE;
25
26
  // Fire the hydration-complete signal (once, on the first commit) via the SDK instance if it is present.
@@ -45,11 +46,37 @@ const commitStream = createCommitAggregator({
45
46
  },
46
47
  flush: (n) => reticleInstance()?.renderCommit?.(n),
47
48
  });
49
+ /**
50
+ * How many commits to keep looking for providers over.
51
+ *
52
+ * Discovery has to happen AFTER a commit — at install time the tree is empty and there is nothing to
53
+ * find — and it cannot be a one-shot on the first commit either, because a provider can mount late
54
+ * (a lazy route, a QueryClient created in an effect). A handful of attempts covers both without
55
+ * turning a walk of the whole fiber tree into a per-commit cost for the life of the session.
56
+ */
57
+ const DISCOVERY_COMMITS = 10;
58
+ /**
59
+ * Counted separately from `commits`, which is seeded from the pre-hook's total and reset by
60
+ * `resetRenderMeter`. Either would have decided how many discovery attempts we get on grounds that
61
+ * have nothing to do with discovery — a page that had already committed 50 times before `install()`
62
+ * ran would have got none at all.
63
+ */
64
+ let discoveryAttempts = 0;
48
65
  /** One React commit: bump the counter, fire hydration on the first, and feed the throttled stream. */
49
66
  function onReactCommit() {
50
67
  commits += 1;
51
68
  hydration.onCommit();
52
69
  commitStream.onCommit();
70
+ if (discoveryAttempts < DISCOVERY_COMMITS && 'undefined' !== typeof document) {
71
+ discoveryAttempts += 1;
72
+ // Never allowed to break a render: this runs inside React's own commit callback.
73
+ try {
74
+ autoRegisterStores(document);
75
+ }
76
+ catch {
77
+ /* discovery is a bonus, not a contract */
78
+ }
79
+ }
53
80
  }
54
81
  let commits = 0;
55
82
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@reticlehq/react",
3
- "version": "2.12.0",
3
+ "version": "2.13.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/core": "2.12.0",
21
- "@reticlehq/browser": "2.12.0"
20
+ "@reticlehq/browser": "2.13.0",
21
+ "@reticlehq/core": "2.13.0"
22
22
  },
23
23
  "peerDependencies": {
24
24
  "react": ">=18"