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