@buoy-gg/console 7.0.29 → 7.0.30
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.
- package/package.json +5 -6
- package/src/components/ConsoleIcon.tsx +0 -9
- package/src/components/ConsoleLogList.tsx +0 -135
- package/src/components/ConsoleModal.tsx +0 -48
- package/src/components/ConsoleRoot.tsx +0 -25
- package/src/devtools/ConsoleBody.tsx +0 -228
- package/src/devtools/ConsoleHeader.tsx +0 -149
- package/src/devtools/ConsoleMessageRow.tsx +0 -388
- package/src/devtools/ConsoleValue.tsx +0 -265
- package/src/devtools/ConsoleView.tsx +0 -43
- package/src/devtools/consoleFilter.ts +0 -123
- package/src/devtools/consoleFormat.ts +0 -314
- package/src/devtools/origin.ts +0 -190
- package/src/devtools/theme.ts +0 -148
- package/src/devtools/useConsoleController.ts +0 -104
- package/src/devtools/useConsoleMessages.ts +0 -337
- package/src/hooks/useConsoleLogs.ts +0 -26
- package/src/index.tsx +0 -70
- package/src/preset.tsx +0 -67
- package/src/store/__tests__/consoleSyncAdapter.test.ts +0 -156
- package/src/store/consoleLogStore.ts +0 -721
- package/src/store/sanitize.ts +0 -83
- package/src/sync/consoleSyncAdapter.ts +0 -115
|
@@ -1,721 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* consoleLogStore
|
|
3
|
-
*
|
|
4
|
-
* Intercepts the global `console` methods and keeps a bounded ring buffer of
|
|
5
|
-
* captured entries, modeled after Chrome DevTools' ConsoleMessage. Direct
|
|
6
|
-
* console patching is the capture path (works identically on Expo, RN CLI, and
|
|
7
|
-
* web). The DevTools-style view layer (filtering, formatting, grouping) is built
|
|
8
|
-
* on top of these raw entries.
|
|
9
|
-
*
|
|
10
|
-
* By default the buffer is in-memory only, so a JS reload starts fresh — just
|
|
11
|
-
* like the Metro/Chrome console. A "Preserve log" toggle persists the buffer to
|
|
12
|
-
* storage and restores it on the next launch (Chrome's "Preserve log").
|
|
13
|
-
*/
|
|
14
|
-
|
|
15
|
-
import * as React from "react";
|
|
16
|
-
import { persistentStorage } from "@buoy-gg/shared-ui";
|
|
17
|
-
import { sanitizeArgs } from "./sanitize";
|
|
18
|
-
import { parseOrigin, type LogOrigin } from "../devtools/origin";
|
|
19
|
-
|
|
20
|
-
/** The console method that produced an entry. */
|
|
21
|
-
export type ConsoleMethod =
|
|
22
|
-
| "log"
|
|
23
|
-
| "info"
|
|
24
|
-
| "warn"
|
|
25
|
-
| "error"
|
|
26
|
-
| "debug"
|
|
27
|
-
| "trace"
|
|
28
|
-
| "dir"
|
|
29
|
-
| "table"
|
|
30
|
-
| "assert"
|
|
31
|
-
| "group"
|
|
32
|
-
| "groupCollapsed"
|
|
33
|
-
| "groupEnd";
|
|
34
|
-
|
|
35
|
-
/** DevTools log levels (Protocol.Log.LogEntryLevel). */
|
|
36
|
-
export type ConsoleLevel = "verbose" | "info" | "warning" | "error";
|
|
37
|
-
|
|
38
|
-
export interface ConsoleLogEntry {
|
|
39
|
-
/** Monotonic id, unique per captured entry. */
|
|
40
|
-
id: number;
|
|
41
|
-
/** The console method that produced this entry. */
|
|
42
|
-
method: ConsoleMethod;
|
|
43
|
-
/** DevTools level, derived from the method. */
|
|
44
|
-
level: ConsoleLevel;
|
|
45
|
-
/** The raw arguments passed to the console method. */
|
|
46
|
-
args: unknown[];
|
|
47
|
-
/** Pre-rendered single-line text (used for filtering + the simple list). */
|
|
48
|
-
message: string;
|
|
49
|
-
/** Capture time in ms since epoch. */
|
|
50
|
-
timestamp: number;
|
|
51
|
-
/** Captured JS stack (error/warn/trace only), newest frame first. */
|
|
52
|
-
stack?: string;
|
|
53
|
-
/** Where the log came from (component / function / call site). */
|
|
54
|
-
origin?: LogOrigin;
|
|
55
|
-
/**
|
|
56
|
-
* True when this entry came from React Native's global error handler (an
|
|
57
|
-
* uncaught — usually fatal — JS error), not from a `console.*` call. The
|
|
58
|
-
* message carries a matching `[FATAL]` / `[UNCAUGHT]` prefix.
|
|
59
|
-
*/
|
|
60
|
-
fatal?: boolean;
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
/** Methods we intercept, in the order we install them. */
|
|
64
|
-
const METHODS: ConsoleMethod[] = [
|
|
65
|
-
"log",
|
|
66
|
-
"info",
|
|
67
|
-
"warn",
|
|
68
|
-
"error",
|
|
69
|
-
"debug",
|
|
70
|
-
"trace",
|
|
71
|
-
"dir",
|
|
72
|
-
"table",
|
|
73
|
-
"assert",
|
|
74
|
-
"group",
|
|
75
|
-
"groupCollapsed",
|
|
76
|
-
"groupEnd",
|
|
77
|
-
];
|
|
78
|
-
|
|
79
|
-
/** Methods whose call site we capture a stack for. */
|
|
80
|
-
const STACK_METHODS = new Set<ConsoleMethod>(["error", "warn", "trace", "assert"]);
|
|
81
|
-
|
|
82
|
-
/** method → DevTools level. */
|
|
83
|
-
const METHOD_LEVEL: Record<ConsoleMethod, ConsoleLevel> = {
|
|
84
|
-
error: "error",
|
|
85
|
-
assert: "error",
|
|
86
|
-
warn: "warning",
|
|
87
|
-
debug: "verbose",
|
|
88
|
-
log: "info",
|
|
89
|
-
info: "info",
|
|
90
|
-
trace: "info",
|
|
91
|
-
dir: "info",
|
|
92
|
-
table: "info",
|
|
93
|
-
group: "info",
|
|
94
|
-
groupCollapsed: "info",
|
|
95
|
-
groupEnd: "info",
|
|
96
|
-
};
|
|
97
|
-
|
|
98
|
-
/** Max entries retained before the oldest are dropped. */
|
|
99
|
-
const MAX_ENTRIES = 1000;
|
|
100
|
-
|
|
101
|
-
type Listener = () => void;
|
|
102
|
-
|
|
103
|
-
let entries: ConsoleLogEntry[] = [];
|
|
104
|
-
let nextId = 1;
|
|
105
|
-
let installed = false;
|
|
106
|
-
let fatalInstalled = false;
|
|
107
|
-
/**
|
|
108
|
-
* Raised by an explicit `uninstallConsoleCapture()`. The fatal-error hook can't
|
|
109
|
-
* be safely unwound once chained (another library may have chained on top of
|
|
110
|
-
* ours since), so an explicit user OFF mutes fatal recording instead.
|
|
111
|
-
*/
|
|
112
|
-
let captureDisabledByUser = false;
|
|
113
|
-
|
|
114
|
-
const listeners = new Set<Listener>();
|
|
115
|
-
const clearListeners = new Set<Listener>();
|
|
116
|
-
|
|
117
|
-
/** Saved originals so we can restore on uninstall and still print through. */
|
|
118
|
-
const originals: Partial<Record<ConsoleMethod, (...args: unknown[]) => void>> = {};
|
|
119
|
-
|
|
120
|
-
// Frame-coalesced emit: console traffic is inherently bursty (loops,
|
|
121
|
-
// per-frame logs), and uncoalesced each entry was its own React commit —
|
|
122
|
-
// the console tool measured 41 JS FPS / 84% CPU / 7 jank during a bench
|
|
123
|
-
// dwell (tool-bench 2026-07-06) largely from its own live churn.
|
|
124
|
-
let emitScheduled = false;
|
|
125
|
-
function emit(): void {
|
|
126
|
-
if (emitScheduled) return;
|
|
127
|
-
emitScheduled = true;
|
|
128
|
-
requestAnimationFrame(() => {
|
|
129
|
-
emitScheduled = false;
|
|
130
|
-
for (const listener of listeners) listener();
|
|
131
|
-
});
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
/** Best-effort, single-line serialization of a single console argument. */
|
|
135
|
-
function formatArg(arg: unknown): string {
|
|
136
|
-
if (typeof arg === "string") return arg;
|
|
137
|
-
if (arg instanceof Error) return arg.stack ?? `${arg.name}: ${arg.message}`;
|
|
138
|
-
if (arg === undefined) return "undefined";
|
|
139
|
-
if (arg === null) return "null";
|
|
140
|
-
if (typeof arg === "function") return `ƒ ${arg.name || "(anonymous)"}`;
|
|
141
|
-
try {
|
|
142
|
-
return JSON.stringify(arg);
|
|
143
|
-
} catch {
|
|
144
|
-
return String(arg);
|
|
145
|
-
}
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
function formatArgs(args: unknown[]): string {
|
|
149
|
-
return args.map(formatArg).join(" ");
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
/** Drop the "Error" header + the interceptor's own frames from a raw stack. */
|
|
153
|
-
function cleanStack(raw?: string): string | undefined {
|
|
154
|
-
if (!raw) return undefined;
|
|
155
|
-
return raw.split("\n").slice(3).join("\n") || undefined;
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
/** Nearest owning React component stack (dev only; empty off-render). */
|
|
159
|
-
function captureOwnerStack(): string | undefined {
|
|
160
|
-
try {
|
|
161
|
-
const fn = (React as unknown as { captureOwnerStack?: () => string | null })
|
|
162
|
-
.captureOwnerStack;
|
|
163
|
-
return typeof fn === "function" ? fn() ?? undefined : undefined;
|
|
164
|
-
} catch {
|
|
165
|
-
return undefined;
|
|
166
|
-
}
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
/**
|
|
170
|
-
* An error React Native decorated on its way through ExceptionsManager: a
|
|
171
|
-
* render/lifecycle crash carrying the component stack. `isComponentError` is
|
|
172
|
-
* set by RN's `getExtendedError`, so this identifies a REAL crash rather than
|
|
173
|
-
* an ordinary `console.error("...")` call.
|
|
174
|
-
*/
|
|
175
|
-
type ComponentError = Error & {
|
|
176
|
-
componentStack?: string;
|
|
177
|
-
isComponentError?: boolean;
|
|
178
|
-
};
|
|
179
|
-
|
|
180
|
-
/** Frames to keep from a component stack — the crash site plus its context. */
|
|
181
|
-
const COMPONENT_STACK_FRAMES = 8;
|
|
182
|
-
|
|
183
|
-
/**
|
|
184
|
-
* Squeeze a React component stack down to the part a human (or an agent
|
|
185
|
-
* reading this over a wire) actually uses: the component names nearest the
|
|
186
|
-
* crash.
|
|
187
|
-
*
|
|
188
|
-
* Raw component stacks in a Metro dev bundle append the full bundle URL with
|
|
189
|
-
* every query param to EVERY frame — one crash is ~15 KB of near-identical
|
|
190
|
-
* `http://192.168.x.x:8830/…&transform.routerRoot=src/app…` noise wrapped
|
|
191
|
-
* around the handful of names that matter. The complete error, componentStack
|
|
192
|
-
* included, is still on the entry's `args` for anyone who wants it.
|
|
193
|
-
*/
|
|
194
|
-
function compactComponentStack(stack: string): string {
|
|
195
|
-
const frames = stack
|
|
196
|
-
.split("\n")
|
|
197
|
-
.map((line) => line.trim())
|
|
198
|
-
.filter(Boolean)
|
|
199
|
-
// Drop the "(url)" tail; keep a "Name(./file.tsx)" hint when RN provides one.
|
|
200
|
-
.map((line) => line.replace(/\s*\((?:https?:|\/).*$/, ""));
|
|
201
|
-
const shown = frames.slice(0, COMPONENT_STACK_FRAMES);
|
|
202
|
-
const rest = frames.length - shown.length;
|
|
203
|
-
return (
|
|
204
|
-
shown.map((f) => ` ${f}`).join("\n") +
|
|
205
|
-
(rest > 0 ? `\n …+${rest} more frames` : "")
|
|
206
|
-
);
|
|
207
|
-
}
|
|
208
|
-
function asComponentError(arg: unknown): ComponentError | null {
|
|
209
|
-
if (!(arg instanceof Error)) return null;
|
|
210
|
-
const e = arg as ComponentError;
|
|
211
|
-
return e.isComponentError || typeof e.componentStack === "string" ? e : null;
|
|
212
|
-
}
|
|
213
|
-
|
|
214
|
-
function record(method: ConsoleMethod, args: unknown[]): void {
|
|
215
|
-
// Capture the call site for every log so we can attribute its origin.
|
|
216
|
-
const rawStack = new Error().stack;
|
|
217
|
-
const origin = parseOrigin(rawStack, captureOwnerStack());
|
|
218
|
-
|
|
219
|
-
// React Native funnels an uncaught render error back through console.error
|
|
220
|
-
// (ExceptionsManager.reportException) so console monkey-patches still see it.
|
|
221
|
-
// That arrives as an ordinary error row, which badly under-sells it: the app
|
|
222
|
-
// is dead. Promote it to a tagged [FATAL] entry carrying the component stack.
|
|
223
|
-
const crash = method === "error" ? asComponentError(args[0]) : null;
|
|
224
|
-
if (crash) {
|
|
225
|
-
// Tagged [RENDER ERROR], not [FATAL]: React reports an error an
|
|
226
|
-
// ErrorBoundary CAUGHT and recovered from through this same path, with the
|
|
227
|
-
// same componentStack, and nothing here distinguishes the two. Claiming a
|
|
228
|
-
// healthy app "most likely CRASHED" is worse than under-claiming — the
|
|
229
|
-
// component stack, which is the useful part, is reported either way.
|
|
230
|
-
const headline = fatalKey(crash.name, crash.message);
|
|
231
|
-
const located = crash.componentStack
|
|
232
|
-
? `\n\nThis error is located at:\n${compactComponentStack(crash.componentStack)}`
|
|
233
|
-
: "";
|
|
234
|
-
pushFatal(
|
|
235
|
-
{
|
|
236
|
-
id: nextId++,
|
|
237
|
-
method: "error",
|
|
238
|
-
level: "error",
|
|
239
|
-
args: ["[RENDER ERROR]", crash],
|
|
240
|
-
message: `[RENDER ERROR] ${headline}${located}`,
|
|
241
|
-
timestamp: Date.now(),
|
|
242
|
-
stack: crash.stack,
|
|
243
|
-
origin,
|
|
244
|
-
},
|
|
245
|
-
isDuplicateFatal(`[RENDER ERROR] ${headline}`)
|
|
246
|
-
);
|
|
247
|
-
return;
|
|
248
|
-
}
|
|
249
|
-
|
|
250
|
-
const entry: ConsoleLogEntry = {
|
|
251
|
-
id: nextId++,
|
|
252
|
-
method,
|
|
253
|
-
level: METHOD_LEVEL[method],
|
|
254
|
-
args,
|
|
255
|
-
message: formatArgs(args),
|
|
256
|
-
timestamp: Date.now(),
|
|
257
|
-
stack: STACK_METHODS.has(method) ? cleanStack(rawStack) : undefined,
|
|
258
|
-
origin,
|
|
259
|
-
};
|
|
260
|
-
entries =
|
|
261
|
-
entries.length >= MAX_ENTRIES
|
|
262
|
-
? [...entries.slice(entries.length - MAX_ENTRIES + 1), entry]
|
|
263
|
-
: [...entries, entry];
|
|
264
|
-
emit();
|
|
265
|
-
scheduleSave();
|
|
266
|
-
// Errors are the entries most likely to be the last thing an app ever logs,
|
|
267
|
-
// so they get pushed to any dashboard immediately instead of waiting on the
|
|
268
|
-
// throttle that a dying tree will never run. Rate-limited; ordinary logs
|
|
269
|
-
// still ride the normal throttled path.
|
|
270
|
-
if (entry.level === "error") flushConsoleSyncNow();
|
|
271
|
-
}
|
|
272
|
-
|
|
273
|
-
/** Minimal shape of React Native's global `ErrorUtils`. */
|
|
274
|
-
interface RNErrorUtils {
|
|
275
|
-
getGlobalHandler?: () =>
|
|
276
|
-
| ((error: unknown, isFatal?: boolean) => void)
|
|
277
|
-
| undefined;
|
|
278
|
-
setGlobalHandler?: (
|
|
279
|
-
handler: (error: unknown, isFatal?: boolean) => void
|
|
280
|
-
) => void;
|
|
281
|
-
}
|
|
282
|
-
|
|
283
|
-
/**
|
|
284
|
-
* Two independent seams report the same crash on some setups (the C++ handler
|
|
285
|
-
* can also feed `console.error`). Suppress a repeat of the same headline within
|
|
286
|
-
* this window so a crash reads as ONE entry.
|
|
287
|
-
*/
|
|
288
|
-
const FATAL_DEDUPE_MS = 2000;
|
|
289
|
-
let lastFatalKey = "";
|
|
290
|
-
let lastFatalAt = 0;
|
|
291
|
-
|
|
292
|
-
/**
|
|
293
|
-
* Normalize a crash headline so the same error reported through two different
|
|
294
|
-
* seams produces the same key. React Native often sets `error.message` to the
|
|
295
|
-
* ALREADY-prefixed string ("TypeError: x is not a function"), so one path
|
|
296
|
-
* builds "TypeError: TypeError: x…" and the other "TypeError: x…" — which
|
|
297
|
-
* defeats the de-duplication entirely.
|
|
298
|
-
*/
|
|
299
|
-
function fatalKey(name: string | undefined, message: string): string {
|
|
300
|
-
const body = message.trim();
|
|
301
|
-
if (name && body.startsWith(`${name}: `)) return body;
|
|
302
|
-
return name ? `${name}: ${body}` : body;
|
|
303
|
-
}
|
|
304
|
-
|
|
305
|
-
/**
|
|
306
|
-
* Has this crash already been recorded moments ago?
|
|
307
|
-
*
|
|
308
|
-
* Only ever used to suppress a duplicate PUSH to the dashboard — never to drop
|
|
309
|
-
* an entry. Two different components crashing with the same message inside the
|
|
310
|
-
* window are two crashes, and a tool whose pitch is "the app's last words"
|
|
311
|
-
* must not silently throw one away.
|
|
312
|
-
*/
|
|
313
|
-
function isDuplicateFatal(key: string): boolean {
|
|
314
|
-
const now = Date.now();
|
|
315
|
-
if (key === lastFatalKey && now - lastFatalAt < FATAL_DEDUPE_MS) return true;
|
|
316
|
-
lastFatalKey = key;
|
|
317
|
-
lastFatalAt = now;
|
|
318
|
-
return false;
|
|
319
|
-
}
|
|
320
|
-
|
|
321
|
-
/**
|
|
322
|
-
* The device sync bridge's "push this tool NOW" escape hatch
|
|
323
|
-
* (@buoy-gg/external-sync `crashFlush`). Reached through the global rather than
|
|
324
|
-
* an import because console deliberately has no dependency on external-sync.
|
|
325
|
-
*/
|
|
326
|
-
let lastFlushAt = 0;
|
|
327
|
-
/** Floor between opportunistic flushes, so an error storm can't flood the socket. */
|
|
328
|
-
const FLUSH_MIN_INTERVAL_MS = 150;
|
|
329
|
-
const flushConsoleSyncNow = (force = false): void => {
|
|
330
|
-
const now = Date.now();
|
|
331
|
-
// A fatal is the app's last word — it always goes out, rate limit or not.
|
|
332
|
-
if (!force && now - lastFlushAt < FLUSH_MIN_INTERVAL_MS) return;
|
|
333
|
-
lastFlushAt = now;
|
|
334
|
-
try {
|
|
335
|
-
const set = (globalThis as { __buoyFlushToolSync?: Set<(toolId: string) => void> })
|
|
336
|
-
.__buoyFlushToolSync;
|
|
337
|
-
if (!set) return;
|
|
338
|
-
for (const flush of set) flush("console");
|
|
339
|
-
} catch {
|
|
340
|
-
// Best-effort: a crash path must never crash.
|
|
341
|
-
}
|
|
342
|
-
};
|
|
343
|
-
|
|
344
|
-
/**
|
|
345
|
-
* Append a pre-built fatal entry to the ring buffer, then push it to any
|
|
346
|
-
* connected dashboard IMMEDIATELY.
|
|
347
|
-
*
|
|
348
|
-
* A fatal render error unmounts the React tree microseconds later, taking the
|
|
349
|
-
* sync bridge — and the normal 200 ms throttled snapshot — with it. Flushing
|
|
350
|
-
* synchronously here is what makes a crashed app's last words readable from
|
|
351
|
-
* the desktop app and the MCP server instead of the app just going silent.
|
|
352
|
-
*/
|
|
353
|
-
function pushFatal(entry: ConsoleLogEntry, duplicate = false): void {
|
|
354
|
-
entries =
|
|
355
|
-
entries.length >= MAX_ENTRIES
|
|
356
|
-
? [...entries.slice(entries.length - MAX_ENTRIES + 1), entry]
|
|
357
|
-
: [...entries, entry];
|
|
358
|
-
emit();
|
|
359
|
-
scheduleSave();
|
|
360
|
-
// A repeat within the dedupe window is still RECORDED (two crashes are two
|
|
361
|
-
// crashes); it just doesn't earn another forced push to the dashboard.
|
|
362
|
-
if (!duplicate) flushConsoleSyncNow(true);
|
|
363
|
-
}
|
|
364
|
-
|
|
365
|
-
/** Record an uncaught JS error from the global handler as an error entry. */
|
|
366
|
-
function recordFatalError(error: unknown, isFatal?: boolean): void {
|
|
367
|
-
const err = error instanceof Error ? error : undefined;
|
|
368
|
-
// RN passes isFatal:false for non-fatal uncaught errors (e.g. errors thrown
|
|
369
|
-
// in event handlers on some setups); anything else is treated as fatal.
|
|
370
|
-
const label = isFatal === false ? "[UNCAUGHT]" : "[FATAL]";
|
|
371
|
-
const headline = err ? fatalKey(err.name, err.message) : formatArg(error);
|
|
372
|
-
const duplicate = isDuplicateFatal(`${label} ${headline}`);
|
|
373
|
-
// The label leads the args (not just the pre-rendered message): the
|
|
374
|
-
// DevTools-style row renders from args, so this is what makes the tag
|
|
375
|
-
// visible in the UI — exactly like `console.error("[FATAL]", err)`.
|
|
376
|
-
pushFatal(
|
|
377
|
-
{
|
|
378
|
-
id: nextId++,
|
|
379
|
-
method: "error",
|
|
380
|
-
level: "error",
|
|
381
|
-
args: [label, error],
|
|
382
|
-
message: `${label} ${headline}`,
|
|
383
|
-
timestamp: Date.now(),
|
|
384
|
-
// The error's OWN stack — the crash site, not this handler's call site.
|
|
385
|
-
stack: err?.stack,
|
|
386
|
-
fatal: true,
|
|
387
|
-
},
|
|
388
|
-
duplicate
|
|
389
|
-
);
|
|
390
|
-
}
|
|
391
|
-
|
|
392
|
-
/**
|
|
393
|
-
* The exception payload React Native's C++ error handler hands to listeners
|
|
394
|
-
* registered via `global.RN$registerExceptionListener` (JsErrorHandler.cpp).
|
|
395
|
-
*/
|
|
396
|
-
interface NativeExceptionData {
|
|
397
|
-
message?: string;
|
|
398
|
-
originalMessage?: string | null;
|
|
399
|
-
name?: string | null;
|
|
400
|
-
componentStack?: string | null;
|
|
401
|
-
stack?: Array<{
|
|
402
|
-
file?: string;
|
|
403
|
-
methodName?: string;
|
|
404
|
-
lineNumber?: number;
|
|
405
|
-
column?: number;
|
|
406
|
-
}>;
|
|
407
|
-
id?: number;
|
|
408
|
-
isFatal?: boolean;
|
|
409
|
-
isComponentError?: boolean;
|
|
410
|
-
extraData?: { rawStack?: string } & Record<string, unknown>;
|
|
411
|
-
/** Suppresses RN's own redbox. We never call it — we only observe. */
|
|
412
|
-
preventDefault?: () => unknown;
|
|
413
|
-
}
|
|
414
|
-
|
|
415
|
-
/** Render the C++ handler's parsed frames back into a normal stack string. */
|
|
416
|
-
function formatNativeStack(data: NativeExceptionData): string | undefined {
|
|
417
|
-
const raw = data.extraData?.rawStack;
|
|
418
|
-
if (typeof raw === "string" && raw.length > 0) return raw;
|
|
419
|
-
if (!Array.isArray(data.stack) || data.stack.length === 0) return undefined;
|
|
420
|
-
return data.stack
|
|
421
|
-
.map((f) => {
|
|
422
|
-
const where =
|
|
423
|
-
f.lineNumber != null ? `${f.file ?? "?"}:${f.lineNumber}:${f.column ?? 0}` : f.file ?? "?";
|
|
424
|
-
return ` at ${f.methodName || "<anonymous>"} (${where})`;
|
|
425
|
-
})
|
|
426
|
-
.join("\n");
|
|
427
|
-
}
|
|
428
|
-
|
|
429
|
-
/** Record a crash reported by React Native's native (C++) error handler. */
|
|
430
|
-
function recordNativeException(data: NativeExceptionData): void {
|
|
431
|
-
const label = data.isFatal === false ? "[UNCAUGHT]" : "[FATAL]";
|
|
432
|
-
const headline = fatalKey(data.name ?? undefined, data.originalMessage ?? data.message ?? "Unknown error");
|
|
433
|
-
const duplicate = isDuplicateFatal(`${label} ${headline}`);
|
|
434
|
-
// The component stack is the single most useful line for "which component
|
|
435
|
-
// crashed" — RN puts it in the redbox, so put it in the console entry too.
|
|
436
|
-
const componentStack =
|
|
437
|
-
typeof data.componentStack === "string" && data.componentStack.trim()
|
|
438
|
-
? `\n\nThis error is located at:\n${compactComponentStack(data.componentStack)}`
|
|
439
|
-
: "";
|
|
440
|
-
const message = `${label} ${headline}${componentStack}`;
|
|
441
|
-
pushFatal(
|
|
442
|
-
{
|
|
443
|
-
id: nextId++,
|
|
444
|
-
method: "error",
|
|
445
|
-
level: "error",
|
|
446
|
-
args: [label, headline, ...(componentStack ? [componentStack.trim()] : [])],
|
|
447
|
-
message,
|
|
448
|
-
timestamp: Date.now(),
|
|
449
|
-
stack: formatNativeStack(data),
|
|
450
|
-
fatal: true,
|
|
451
|
-
},
|
|
452
|
-
duplicate
|
|
453
|
-
);
|
|
454
|
-
}
|
|
455
|
-
|
|
456
|
-
/**
|
|
457
|
-
* Register with React Native's native (C++) exception handler — the seam a
|
|
458
|
-
* RENDER crash actually travels through on the New Architecture.
|
|
459
|
-
*
|
|
460
|
-
* React 19 routes an uncaught render error to `onUncaughtError` →
|
|
461
|
-
* `ExceptionsManager.handleException`, which NEVER reaches
|
|
462
|
-
* `ErrorUtils.setGlobalHandler`. Where it goes from there depends on the build:
|
|
463
|
-
*
|
|
464
|
-
* - `useAlwaysAvailableJSErrorHandling` on: the C++ handler
|
|
465
|
-
* (`global.RN$handleException`) reports it and JS sees nothing — this
|
|
466
|
-
* listener is the only seam.
|
|
467
|
-
* - otherwise: JS `reportException` re-feeds `console.error(e)` "so any methods
|
|
468
|
-
* monkey patched on top of console.error are called", which the console patch
|
|
469
|
-
* catches and promotes to `[FATAL]` (see `record`).
|
|
470
|
-
*
|
|
471
|
-
* Both are covered, and a crash reported through both de-duplicates to one
|
|
472
|
-
* entry. `RN$registerExceptionListener` keeps a LIST of listeners (LogBox
|
|
473
|
-
* registers one too), so this is purely additive. We never call the payload's
|
|
474
|
-
* `preventDefault()`: suppressing RN's own redbox is not our call to make.
|
|
475
|
-
*/
|
|
476
|
-
function installNativeExceptionCapture(): boolean {
|
|
477
|
-
const register = (
|
|
478
|
-
globalThis as {
|
|
479
|
-
RN$registerExceptionListener?: (
|
|
480
|
-
listener: (data: NativeExceptionData) => void
|
|
481
|
-
) => void;
|
|
482
|
-
}
|
|
483
|
-
).RN$registerExceptionListener;
|
|
484
|
-
if (typeof register !== "function") return false;
|
|
485
|
-
register((data) => {
|
|
486
|
-
try {
|
|
487
|
-
if (!captureDisabledByUser) recordNativeException(data);
|
|
488
|
-
} catch {
|
|
489
|
-
// Capture must never interfere with error reporting.
|
|
490
|
-
}
|
|
491
|
-
});
|
|
492
|
-
return true;
|
|
493
|
-
}
|
|
494
|
-
|
|
495
|
-
/**
|
|
496
|
-
* Hook React Native's error paths so FATAL/uncaught JS errors land in the
|
|
497
|
-
* console store: the classic `ErrorUtils.setGlobalHandler` (old architecture,
|
|
498
|
-
* native-module callbacks, promise rejections) AND the native C++ exception
|
|
499
|
-
* listener (New Architecture render crashes — see
|
|
500
|
-
* {@link installNativeExceptionCapture}). Both feed the same de-duplicated
|
|
501
|
-
* `[FATAL]` entry, so a crash reported through both seams shows up once.
|
|
502
|
-
*
|
|
503
|
-
* - Chains the previous handler (LogBox/redbox still fire; nothing swallowed).
|
|
504
|
-
* - Idempotent, and a silent no-op off React Native (neither global present) —
|
|
505
|
-
* which also keeps it inert on the desktop dashboard / web mirrors.
|
|
506
|
-
* - Recording respects an explicit `uninstallConsoleCapture()` (user OFF), but
|
|
507
|
-
* the hooks themselves stay chained — they can't be safely removed.
|
|
508
|
-
*/
|
|
509
|
-
export function installFatalErrorCapture(): void {
|
|
510
|
-
if (fatalInstalled) return;
|
|
511
|
-
// Latch only once a seam is actually attached. Setting the flag up front
|
|
512
|
-
// means an install that runs before `InitializeCore` has published
|
|
513
|
-
// `ErrorUtils` would latch anyway and never retry — silently losing promise
|
|
514
|
-
// rejections and native-callback errors, which travel ONLY that seam.
|
|
515
|
-
const nativeInstalled = installNativeExceptionCapture();
|
|
516
|
-
const errorUtils = (globalThis as { ErrorUtils?: RNErrorUtils }).ErrorUtils;
|
|
517
|
-
if (typeof errorUtils?.setGlobalHandler !== "function") {
|
|
518
|
-
fatalInstalled = nativeInstalled;
|
|
519
|
-
return;
|
|
520
|
-
}
|
|
521
|
-
fatalInstalled = true;
|
|
522
|
-
const previous =
|
|
523
|
-
typeof errorUtils.getGlobalHandler === "function"
|
|
524
|
-
? errorUtils.getGlobalHandler()
|
|
525
|
-
: undefined;
|
|
526
|
-
errorUtils.setGlobalHandler((error: unknown, isFatal?: boolean) => {
|
|
527
|
-
try {
|
|
528
|
-
if (!captureDisabledByUser) recordFatalError(error, isFatal);
|
|
529
|
-
} catch {
|
|
530
|
-
// Capture must never interfere with error reporting.
|
|
531
|
-
}
|
|
532
|
-
if (typeof previous === "function") previous(error, isFatal);
|
|
533
|
-
});
|
|
534
|
-
}
|
|
535
|
-
|
|
536
|
-
/**
|
|
537
|
-
* Patch the global console methods. Idempotent — safe to call more than once.
|
|
538
|
-
* Each patched method still forwards to the original so normal logging keeps
|
|
539
|
-
* working (Metro terminal, Chrome, native logcat/Xcode).
|
|
540
|
-
*
|
|
541
|
-
* Also installs the fatal-error hook (see `installFatalErrorCapture`) so every
|
|
542
|
-
* install path captures crashes, not just `console.*` calls.
|
|
543
|
-
*/
|
|
544
|
-
export function installConsoleCapture(): void {
|
|
545
|
-
captureDisabledByUser = false;
|
|
546
|
-
installFatalErrorCapture();
|
|
547
|
-
if (installed) return;
|
|
548
|
-
installed = true;
|
|
549
|
-
|
|
550
|
-
for (const method of METHODS) {
|
|
551
|
-
const original = console[method] as ((...args: unknown[]) => void) | undefined;
|
|
552
|
-
if (typeof original !== "function") continue;
|
|
553
|
-
originals[method] = original;
|
|
554
|
-
// Named so origin parsing can identify (and skip) this frame by function
|
|
555
|
-
// name — in a Metro bundle every frame shares one bundle URL, so filename
|
|
556
|
-
// filtering can't distinguish our wrapper from the real caller.
|
|
557
|
-
console[method] = function buoyConsoleProxy(...args: unknown[]) {
|
|
558
|
-
record(method, args);
|
|
559
|
-
original.apply(console, args);
|
|
560
|
-
};
|
|
561
|
-
}
|
|
562
|
-
}
|
|
563
|
-
|
|
564
|
-
/** Restore the original console methods. Also mutes fatal-error recording
|
|
565
|
-
* (the hook itself stays chained — see `installFatalErrorCapture`). */
|
|
566
|
-
export function uninstallConsoleCapture(): void {
|
|
567
|
-
captureDisabledByUser = true;
|
|
568
|
-
if (!installed) return;
|
|
569
|
-
installed = false;
|
|
570
|
-
for (const method of METHODS) {
|
|
571
|
-
const original = originals[method];
|
|
572
|
-
if (original) console[method] = original;
|
|
573
|
-
delete originals[method];
|
|
574
|
-
}
|
|
575
|
-
}
|
|
576
|
-
|
|
577
|
-
/** Subscribe to changes. Returns an unsubscribe function. */
|
|
578
|
-
export function subscribe(listener: Listener): () => void {
|
|
579
|
-
listeners.add(listener);
|
|
580
|
-
return () => {
|
|
581
|
-
listeners.delete(listener);
|
|
582
|
-
};
|
|
583
|
-
}
|
|
584
|
-
|
|
585
|
-
/** Current snapshot (stable reference between mutations for useSyncExternalStore). */
|
|
586
|
-
export function getEntries(): ConsoleLogEntry[] {
|
|
587
|
-
return entries;
|
|
588
|
-
}
|
|
589
|
-
|
|
590
|
-
/** Clear all captured entries. Fires onClear listeners (e.g. to forward the
|
|
591
|
-
* clear to a remote device when running in mirror mode). */
|
|
592
|
-
export function clearEntries(): void {
|
|
593
|
-
for (const listener of clearListeners) listener();
|
|
594
|
-
void clearSavedBuffer();
|
|
595
|
-
if (entries.length === 0) return;
|
|
596
|
-
entries = [];
|
|
597
|
-
emit();
|
|
598
|
-
}
|
|
599
|
-
|
|
600
|
-
// ─── Remote-mirror mode (desktop dashboard) ──────────────────────────────────
|
|
601
|
-
// The desktop imports this same store but, instead of patching its own console,
|
|
602
|
-
// drives it from device snapshots via replaceEntries(). Capture is never
|
|
603
|
-
// installed there, so local and remote modes never mix.
|
|
604
|
-
|
|
605
|
-
/** Replace the whole entry list from a remote snapshot. */
|
|
606
|
-
export function replaceEntries(next: ConsoleLogEntry[]): void {
|
|
607
|
-
entries = next.length > MAX_ENTRIES ? next.slice(next.length - MAX_ENTRIES) : next;
|
|
608
|
-
emit();
|
|
609
|
-
}
|
|
610
|
-
|
|
611
|
-
/** Register a listener fired when clearEntries() is called. Returns an
|
|
612
|
-
* unsubscribe function. Used by the dashboard to forward clears to the device. */
|
|
613
|
-
export function onClear(listener: Listener): () => void {
|
|
614
|
-
clearListeners.add(listener);
|
|
615
|
-
return () => {
|
|
616
|
-
clearListeners.delete(listener);
|
|
617
|
-
};
|
|
618
|
-
}
|
|
619
|
-
|
|
620
|
-
// ─── Preserve log (persist across reload) ────────────────────────────────────
|
|
621
|
-
// Default OFF: the buffer is in-memory only, so a reload starts fresh. When ON,
|
|
622
|
-
// the buffer is saved to storage (debounced) and restored on the next launch.
|
|
623
|
-
|
|
624
|
-
const PRESERVE_KEY = "@react_buoy_console_preserve";
|
|
625
|
-
const BUFFER_KEY = "@react_buoy_console_buffer";
|
|
626
|
-
const SAVE_DEBOUNCE_MS = 600;
|
|
627
|
-
|
|
628
|
-
let preserveLog = false;
|
|
629
|
-
let persistenceReady = false;
|
|
630
|
-
const preserveListeners = new Set<Listener>();
|
|
631
|
-
let saveTimer: ReturnType<typeof setTimeout> | null = null;
|
|
632
|
-
|
|
633
|
-
function emitPreserve(): void {
|
|
634
|
-
for (const listener of preserveListeners) listener();
|
|
635
|
-
}
|
|
636
|
-
|
|
637
|
-
function scheduleSave(): void {
|
|
638
|
-
if (!preserveLog) return;
|
|
639
|
-
if (saveTimer) clearTimeout(saveTimer);
|
|
640
|
-
saveTimer = setTimeout(saveBuffer, SAVE_DEBOUNCE_MS);
|
|
641
|
-
}
|
|
642
|
-
|
|
643
|
-
async function saveBuffer(): Promise<void> {
|
|
644
|
-
saveTimer = null;
|
|
645
|
-
if (!preserveLog) return;
|
|
646
|
-
try {
|
|
647
|
-
const serializable = entries.map((entry) => ({
|
|
648
|
-
...entry,
|
|
649
|
-
args: sanitizeArgs(entry.args),
|
|
650
|
-
}));
|
|
651
|
-
await persistentStorage.setItem(BUFFER_KEY, JSON.stringify(serializable));
|
|
652
|
-
} catch {
|
|
653
|
-
// Storage unavailable — preserve is best-effort.
|
|
654
|
-
}
|
|
655
|
-
}
|
|
656
|
-
|
|
657
|
-
async function clearSavedBuffer(): Promise<void> {
|
|
658
|
-
try {
|
|
659
|
-
await persistentStorage.removeItem(BUFFER_KEY);
|
|
660
|
-
} catch {
|
|
661
|
-
// ignore
|
|
662
|
-
}
|
|
663
|
-
}
|
|
664
|
-
|
|
665
|
-
/**
|
|
666
|
-
* Load the persisted preserve-log flag and, if enabled, restore the saved
|
|
667
|
-
* buffer. If disabled, drop any saved buffer so the session starts fresh.
|
|
668
|
-
* Idempotent — safe to call from ConsoleRoot on every mount.
|
|
669
|
-
*/
|
|
670
|
-
export async function initConsolePersistence(): Promise<void> {
|
|
671
|
-
if (persistenceReady) return;
|
|
672
|
-
persistenceReady = true;
|
|
673
|
-
try {
|
|
674
|
-
preserveLog = (await persistentStorage.getItem(PRESERVE_KEY)) === "true";
|
|
675
|
-
} catch {
|
|
676
|
-
preserveLog = false;
|
|
677
|
-
}
|
|
678
|
-
emitPreserve();
|
|
679
|
-
|
|
680
|
-
if (!preserveLog) {
|
|
681
|
-
await clearSavedBuffer();
|
|
682
|
-
return;
|
|
683
|
-
}
|
|
684
|
-
try {
|
|
685
|
-
const raw = await persistentStorage.getItem(BUFFER_KEY);
|
|
686
|
-
if (raw) {
|
|
687
|
-
const saved = JSON.parse(raw) as ConsoleLogEntry[];
|
|
688
|
-
if (Array.isArray(saved) && saved.length) {
|
|
689
|
-
// Prepend restored entries before anything captured this session.
|
|
690
|
-
entries = [...saved, ...entries].slice(-MAX_ENTRIES);
|
|
691
|
-
nextId = Math.max(nextId, ...saved.map((e) => e.id + 1));
|
|
692
|
-
emit();
|
|
693
|
-
}
|
|
694
|
-
}
|
|
695
|
-
} catch {
|
|
696
|
-
// Corrupt/absent buffer — ignore.
|
|
697
|
-
}
|
|
698
|
-
}
|
|
699
|
-
|
|
700
|
-
/** Whether logs persist across reload. */
|
|
701
|
-
export function getPreserveLog(): boolean {
|
|
702
|
-
return preserveLog;
|
|
703
|
-
}
|
|
704
|
-
|
|
705
|
-
/** Toggle preserve-log. Persists the flag; saves or drops the buffer. */
|
|
706
|
-
export function setPreserveLog(next: boolean): void {
|
|
707
|
-
if (preserveLog === next) return;
|
|
708
|
-
preserveLog = next;
|
|
709
|
-
emitPreserve();
|
|
710
|
-
persistentStorage.setItem(PRESERVE_KEY, String(next)).catch(() => {});
|
|
711
|
-
if (next) saveBuffer();
|
|
712
|
-
else clearSavedBuffer();
|
|
713
|
-
}
|
|
714
|
-
|
|
715
|
-
/** Subscribe to preserve-log changes. Returns an unsubscribe function. */
|
|
716
|
-
export function subscribePreserveLog(listener: Listener): () => void {
|
|
717
|
-
preserveListeners.add(listener);
|
|
718
|
-
return () => {
|
|
719
|
-
preserveListeners.delete(listener);
|
|
720
|
-
};
|
|
721
|
-
}
|