@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.
@@ -1,123 +0,0 @@
1
- /**
2
- * consoleFilter — port of DevTools `panels/console/ConsoleFilter.ts` plus the
3
- * `TextUtils.FilterParser` text-filter grammar.
4
- *
5
- * - Level mask: 4 levels (verbose/info/warning/error); "Default" = all but verbose.
6
- * - Text filter: space-separated tokens, AND-combined. Each token may be a plain
7
- * substring, a `/regex/`, or `key:value` (url/source/context), and a leading
8
- * `-` negates it. Our captured entries have no url/source/context fields, so
9
- * keyed tokens degrade to a substring test against the rendered message.
10
- */
11
-
12
- import type { ConsoleLevel, ConsoleLogEntry } from "../store/consoleLogStore";
13
-
14
- export type LevelsMask = Record<ConsoleLevel, boolean>;
15
-
16
- export const ALL_LEVELS: LevelsMask = {
17
- verbose: true,
18
- info: true,
19
- warning: true,
20
- error: true,
21
- };
22
-
23
- /** "Default levels": everything except Verbose. */
24
- export const DEFAULT_LEVELS: LevelsMask = { ...ALL_LEVELS, verbose: false };
25
-
26
- export interface ParsedFilter {
27
- key?: string;
28
- text?: string;
29
- regex?: RegExp;
30
- negative: boolean;
31
- }
32
-
33
- const KEY_VALUE_RE = /^([\w-]+):(.+)$/;
34
- const REGEXP_RE = /^\/(.+)\/$/;
35
-
36
- /** Parse a filter query string into AND-combined parsed filters. */
37
- export function parseFilterQuery(query: string): ParsedFilter[] {
38
- const filters: ParsedFilter[] = [];
39
- for (const rawToken of query.split(/\s+/)) {
40
- if (!rawToken) continue;
41
- let token = rawToken;
42
- let negative = false;
43
- if (token.startsWith("-") && token.length > 1) {
44
- negative = true;
45
- token = token.slice(1);
46
- }
47
-
48
- const kv = token.match(KEY_VALUE_RE);
49
- if (kv) {
50
- filters.push({ key: kv[1].toLowerCase(), text: kv[2], negative });
51
- continue;
52
- }
53
- const rx = token.match(REGEXP_RE);
54
- if (rx) {
55
- try {
56
- filters.push({ regex: new RegExp(rx[1], "im"), negative });
57
- continue;
58
- } catch {
59
- // Invalid regex falls back to literal text (DevTools does the same).
60
- }
61
- }
62
- filters.push({ text: token, negative });
63
- }
64
- return filters;
65
- }
66
-
67
- /** Does the entry's rendered text contain `text` (case-insensitive)? */
68
- function textMatches(entry: ConsoleLogEntry, text: string): boolean {
69
- return entry.message.toLowerCase().includes(text.toLowerCase());
70
- }
71
-
72
- /** Apply the parsed text filters (all must pass). */
73
- function applyFilters(entry: ConsoleLogEntry, parsed: ParsedFilter[]): boolean {
74
- for (const filter of parsed) {
75
- if (filter.regex) {
76
- if (filter.regex.test(entry.message) === filter.negative) return false;
77
- } else if (filter.text) {
78
- // Keyed tokens (url:/source:/context:) degrade to a substring test since
79
- // captured RN logs carry no such fields.
80
- if (textMatches(entry, filter.text) === filter.negative) return false;
81
- }
82
- }
83
- return true;
84
- }
85
-
86
- /** DevTools ConsoleFilter.shouldBeVisible, adapted to our entry model. */
87
- export function shouldBeVisible(
88
- entry: ConsoleLogEntry,
89
- levelsMask: LevelsMask,
90
- parsed: ParsedFilter[]
91
- ): boolean {
92
- // Group-end markers are control rows, never filtered out (handled by the view).
93
- if (entry.method === "groupEnd") return true;
94
- if (!levelsMask[entry.level]) return false;
95
- return applyFilters(entry, parsed);
96
- }
97
-
98
- // ─── Level menu summary text (DevTools updateLevelMenuButtonText) ────────────
99
-
100
- const LEVEL_LABEL: Record<ConsoleLevel, string> = {
101
- verbose: "Verbose",
102
- info: "Info",
103
- warning: "Warnings",
104
- error: "Errors",
105
- };
106
-
107
- const LEVEL_ORDER: ConsoleLevel[] = ["verbose", "info", "warning", "error"];
108
-
109
- function masksEqual(a: LevelsMask, b: LevelsMask): boolean {
110
- return LEVEL_ORDER.every((l) => a[l] === b[l]);
111
- }
112
-
113
- /** The summary shown on the level menu button. */
114
- export function levelMenuSummary(mask: LevelsMask): string {
115
- if (masksEqual(mask, ALL_LEVELS)) return "All levels";
116
- if (masksEqual(mask, DEFAULT_LEVELS)) return "Default levels";
117
- const enabled = LEVEL_ORDER.filter((l) => mask[l]);
118
- if (enabled.length === 0) return "Hide all";
119
- if (enabled.length === 1) return `${LEVEL_LABEL[enabled[0]]} only`;
120
- return "Custom levels";
121
- }
122
-
123
- export { LEVEL_LABEL, LEVEL_ORDER };
@@ -1,314 +0,0 @@
1
- /**
2
- * consoleFormat — port of DevTools `panels/console/ConsoleFormat.ts`.
3
- *
4
- * Implements the WHATWG console Formatter: %s/%d/%i/%f/%o/%O/%c/%_ substitutions
5
- * plus ANSI SGR (\x1B[…m) styling. Where DevTools works over V8 RemoteObjects we
6
- * work over raw JS values; the substitution/ANSI logic is otherwise 1:1.
7
- *
8
- * Output is a flat list of tokens the row renderer consumes:
9
- * - { type: 'string', value, style? } — text, optionally styled by %c / ANSI
10
- * - { type: 'value', value, mode } — an object/array substitution (%o/%O)
11
- * or a trailing non-string argument
12
- */
13
-
14
- import type { TextStyle } from "react-native";
15
- import { ansiColors } from "./theme";
16
-
17
- export type FormatToken =
18
- | { type: "string"; value: string; style?: TextStyle }
19
- | { type: "value"; value: unknown; mode: "optimal" | "generic" };
20
-
21
- // VGA color palette (matches DevTools ANSI_COLORS / ANSI_BRIGHT_COLORS).
22
- const ANSI_COLORS = ["black", "red", "green", "yellow", "blue", "magenta", "cyan", "gray"];
23
- const ANSI_BRIGHT_COLORS = [
24
- "darkgray",
25
- "lightred",
26
- "lightgreen",
27
- "lightyellow",
28
- "lightblue",
29
- "lightmagenta",
30
- "lightcyan",
31
- "white",
32
- ];
33
-
34
- /** A console arg's `description` (string form) — DevTools uses RemoteObject.description. */
35
- function description(arg: unknown): string {
36
- if (typeof arg === "string") return arg;
37
- if (arg === undefined) return "undefined";
38
- if (arg === null) return "null";
39
- if (typeof arg === "number" || typeof arg === "boolean" || typeof arg === "bigint") {
40
- return String(arg);
41
- }
42
- if (arg instanceof Error) return arg.stack ?? `${arg.name}: ${arg.message}`;
43
- if (typeof arg === "function") return `ƒ ${arg.name || "(anonymous)"}`;
44
- try {
45
- return JSON.stringify(arg);
46
- } catch {
47
- return String(arg);
48
- }
49
- }
50
-
51
- // \x1B is the ANSI escape (ESC) — intentional, for parsing color codes.
52
- // eslint-disable-next-line no-control-regex
53
- const FORMAT_RE = /%([%_Oocsdfi])|\x1B\[([\d;]*)m/;
54
-
55
- /** Does the first arg actually need the substitution engine? */
56
- function hasFormatting(fmt: string): boolean {
57
- return FORMAT_RE.test(fmt);
58
- }
59
-
60
- /** Convert a CSS declaration string (from %c or ANSI) into an RN TextStyle. */
61
- function cssToTextStyle(css: string): TextStyle | undefined {
62
- const style: TextStyle = {};
63
- let any = false;
64
- for (const decl of css.split(";")) {
65
- const idx = decl.indexOf(":");
66
- if (idx === -1) continue;
67
- const prop = decl.slice(0, idx).trim().toLowerCase();
68
- let value = decl.slice(idx + 1).trim();
69
- if (!value) continue;
70
- // Resolve DevTools ANSI color vars to concrete hex.
71
- const varMatch = value.match(/var\(--console-color-([a-z]+)\)/);
72
- if (varMatch) value = ansiColors[varMatch[1]] ?? value;
73
-
74
- switch (prop) {
75
- case "color":
76
- style.color = value;
77
- any = true;
78
- break;
79
- case "background-color":
80
- case "background":
81
- style.backgroundColor = value;
82
- any = true;
83
- break;
84
- case "font-weight":
85
- style.fontWeight = value === "lighter" ? "300" : (value as TextStyle["fontWeight"]);
86
- any = true;
87
- break;
88
- case "font-style":
89
- if (value === "italic") {
90
- style.fontStyle = "italic";
91
- any = true;
92
- }
93
- break;
94
- case "font-size": {
95
- const n = parseFloat(value);
96
- if (!Number.isNaN(n)) {
97
- style.fontSize = n;
98
- any = true;
99
- }
100
- break;
101
- }
102
- case "text-decoration":
103
- case "text-decoration-line":
104
- if (value.includes("underline") && value.includes("line-through")) {
105
- style.textDecorationLine = "underline line-through";
106
- } else if (value.includes("underline")) {
107
- style.textDecorationLine = "underline";
108
- } else if (value.includes("line-through")) {
109
- style.textDecorationLine = "line-through";
110
- }
111
- any = true;
112
- break;
113
- default:
114
- break;
115
- }
116
- }
117
- return any ? style : undefined;
118
- }
119
-
120
- /** Apply one ANSI SGR sequence to the running style map (DevTools algorithm). */
121
- function applyAnsi(codes: number[], currentStyle: Map<string, string>): void {
122
- const addTextDecoration = (value: string) => {
123
- const td = currentStyle.get("text-decoration") ?? "";
124
- if (!td.includes(value)) currentStyle.set("text-decoration", `${td} ${value}`);
125
- };
126
- const removeTextDecoration = (value: string) => {
127
- const td = currentStyle.get("text-decoration")?.replace(` ${value}`, "");
128
- if (td) currentStyle.set("text-decoration", td);
129
- else currentStyle.delete("text-decoration");
130
- };
131
-
132
- while (codes.length) {
133
- const code = codes.shift() as number;
134
- switch (code) {
135
- case 0:
136
- currentStyle.clear();
137
- break;
138
- case 1:
139
- currentStyle.set("font-weight", "bold");
140
- break;
141
- case 2:
142
- currentStyle.set("font-weight", "lighter");
143
- break;
144
- case 3:
145
- currentStyle.set("font-style", "italic");
146
- break;
147
- case 4:
148
- addTextDecoration("underline");
149
- break;
150
- case 9:
151
- addTextDecoration("line-through");
152
- break;
153
- case 22:
154
- currentStyle.delete("font-weight");
155
- break;
156
- case 23:
157
- currentStyle.delete("font-style");
158
- break;
159
- case 24:
160
- removeTextDecoration("underline");
161
- break;
162
- case 29:
163
- removeTextDecoration("line-through");
164
- break;
165
- case 38:
166
- case 48:
167
- if (codes.shift() === 2) {
168
- const r = codes.shift() ?? 0;
169
- const g = codes.shift() ?? 0;
170
- const b = codes.shift() ?? 0;
171
- currentStyle.set(code === 38 ? "color" : "background-color", `rgb(${r},${g},${b})`);
172
- }
173
- break;
174
- case 39:
175
- case 49:
176
- currentStyle.delete(code === 39 ? "color" : "background-color");
177
- break;
178
- default: {
179
- const color = ANSI_COLORS[code - 30] ?? ANSI_BRIGHT_COLORS[code - 90];
180
- if (color !== undefined) {
181
- currentStyle.set("color", `var(--console-color-${color})`);
182
- } else {
183
- const bg = ANSI_COLORS[code - 40] ?? ANSI_BRIGHT_COLORS[code - 100];
184
- if (bg !== undefined) currentStyle.set("background-color", `var(--console-color-${bg})`);
185
- }
186
- break;
187
- }
188
- }
189
- }
190
- }
191
-
192
- /** Run the substitution engine over a format string + its args. */
193
- function formatWithSubstitutions(fmtIn: string, args: unknown[]): {
194
- tokens: FormatToken[];
195
- rest: unknown[];
196
- } {
197
- let fmt = fmtIn;
198
- const tokens: FormatToken[] = [];
199
- const currentStyle = new Map<string, string>();
200
- let cssStyle: TextStyle | undefined;
201
-
202
- const pushString = (value: string) => {
203
- if (!value) return;
204
- const last = tokens[tokens.length - 1];
205
- if (last && last.type === "string" && styleEq(last.style, cssStyle)) {
206
- last.value += value;
207
- return;
208
- }
209
- tokens.push({ type: "string", value, style: cssStyle });
210
- };
211
-
212
- let argIndex = 0;
213
- for (let match = FORMAT_RE.exec(fmt); match !== null; match = FORMAT_RE.exec(fmt)) {
214
- pushString(match.input.substring(0, match.index));
215
- let substitution: number | string | undefined;
216
- const specifier = match[1];
217
- switch (specifier) {
218
- case "%":
219
- pushString("%");
220
- substitution = "";
221
- break;
222
- case "s":
223
- if (argIndex < args.length) substitution = description(args[argIndex++]);
224
- break;
225
- case "c":
226
- if (argIndex < args.length) {
227
- cssStyle = cssToTextStyle(description(args[argIndex++]));
228
- substitution = "";
229
- }
230
- break;
231
- case "o":
232
- case "O":
233
- if (argIndex < args.length) {
234
- tokens.push({
235
- type: "value",
236
- value: args[argIndex++],
237
- mode: specifier === "O" ? "generic" : "optimal",
238
- });
239
- substitution = "";
240
- }
241
- break;
242
- case "_":
243
- if (argIndex < args.length) {
244
- argIndex++;
245
- substitution = "";
246
- }
247
- break;
248
- case "d":
249
- case "f":
250
- case "i": {
251
- if (argIndex < args.length) {
252
- const v = args[argIndex++];
253
- let n = typeof v !== "number" ? NaN : v;
254
- if (specifier !== "f") n = Math.floor(n);
255
- substitution = n;
256
- }
257
- break;
258
- }
259
- case undefined: {
260
- const codes = (match[2] || "0").split(";").map((c) => (c ? parseInt(c, 10) : 0));
261
- applyAnsi(codes, currentStyle);
262
- const css = [...currentStyle.entries()]
263
- .map(([k, val]) => `${k}:${val.trimStart()}`)
264
- .join(";");
265
- cssStyle = cssToTextStyle(css);
266
- substitution = "";
267
- break;
268
- }
269
- }
270
- if (substitution === undefined) {
271
- pushString(match[0]);
272
- substitution = "";
273
- }
274
- fmt = substitution + match.input.substring(match.index + match[0].length);
275
- }
276
- pushString(fmt);
277
- return { tokens, rest: args.slice(argIndex) };
278
- }
279
-
280
- function styleEq(a?: TextStyle, b?: TextStyle): boolean {
281
- if (a === b) return true;
282
- if (!a || !b) return false;
283
- return JSON.stringify(a) === JSON.stringify(b);
284
- }
285
-
286
- /**
287
- * Format a console call's arguments into renderable tokens, mirroring how the
288
- * DevTools console renders a message: if the first arg is a format string it
289
- * drives substitution, then any leftover args are appended (space-separated).
290
- */
291
- export function formatConsoleMessage(args: unknown[]): FormatToken[] {
292
- if (args.length === 0) return [];
293
-
294
- let tokens: FormatToken[] = [];
295
- let rest = args;
296
-
297
- if (typeof args[0] === "string" && hasFormatting(args[0])) {
298
- const result = formatWithSubstitutions(args[0], args.slice(1));
299
- tokens = result.tokens;
300
- rest = result.rest;
301
- }
302
-
303
- // Append remaining args (the common case: console.log("x", obj, 1)).
304
- for (const arg of rest) {
305
- if (tokens.length > 0) tokens.push({ type: "string", value: " " });
306
- if (typeof arg === "string") {
307
- tokens.push({ type: "string", value: arg });
308
- } else {
309
- tokens.push({ type: "value", value: arg, mode: "optimal" });
310
- }
311
- }
312
-
313
- return tokens;
314
- }
@@ -1,190 +0,0 @@
1
- /**
2
- * origin — attributes a console call to *where it came from*, and provides the
3
- * lnav-style colored connecting bracket helpers.
4
- *
5
- * Three independent signals (captured in the store at log time):
6
- * - **component** — nearest owning React component (React.captureOwnerStack,
7
- * dev only; null outside render / in async callbacks)
8
- * - **function** — the enclosing function of the call site (JS stack)
9
- * - **callSite** — the exact `file:line` of the call site (JS stack)
10
- *
11
- * The view groups consecutive same-source rows and draws a colored bracket
12
- * gutter (┌ │ └ ─) exactly like lnav's per-file gutter.
13
- */
14
-
15
- export type GroupDimension = "component" | "callsite" | "function" | "off";
16
-
17
- export interface LogOrigin {
18
- component?: string;
19
- functionName?: string;
20
- callSite?: string;
21
- file?: string;
22
- line?: number;
23
- }
24
-
25
- /**
26
- * Our own capture frames, matched by FUNCTION NAME. This is the primary filter:
27
- * in a Metro/Hermes bundle every frame shares one bundle URL, so filename
28
- * filtering can't distinguish them — and that URL often contains `node_modules`
29
- * (e.g. expo-router/entry.bundle), which would wrongly reject *every* frame.
30
- * The first frame after these is the real caller (framework internals sit
31
- * deeper in the stack, after the app frame).
32
- */
33
- const INTERNAL_FUNC =
34
- /^(buoyConsoleProxy|record|cleanStack|captureOwnerStack|formatArgs|formatArg)$/;
35
-
36
- /** Narrow filename guard — only our own module (used when stacks carry real
37
- * file paths, e.g. on web/V8 rather than a single Hermes bundle). */
38
- const INTERNAL_FILE = /consoleLogStore/;
39
-
40
- function isInternalFrame(frame: RawFrame): boolean {
41
- if (frame.func && INTERNAL_FUNC.test(frame.func.replace(/^Object\./, ""))) {
42
- return true;
43
- }
44
- return Boolean(frame.file && INTERNAL_FILE.test(frame.file));
45
- }
46
-
47
- interface RawFrame {
48
- func?: string;
49
- file?: string;
50
- line?: number;
51
- }
52
-
53
- /** Parse a V8 or Hermes stack string into frames. */
54
- function parseFrames(stack: string): RawFrame[] {
55
- const frames: RawFrame[] = [];
56
- for (const raw of stack.split("\n")) {
57
- const line = raw.trim();
58
- if (!line || line === "Error") continue;
59
- // V8: "at func (file:line:col)"
60
- let m = line.match(/^at\s+(.+?)\s+\((.+?):(\d+):(\d+)\)$/);
61
- if (m) {
62
- frames.push({ func: m[1], file: m[2], line: Number(m[3]) });
63
- continue;
64
- }
65
- // V8: "at file:line:col"
66
- m = line.match(/^at\s+(.+?):(\d+):(\d+)$/);
67
- if (m) {
68
- frames.push({ file: m[1], line: Number(m[2]) });
69
- continue;
70
- }
71
- // Hermes: "func@file:line:col"
72
- m = line.match(/^(.*?)@(.+?):(\d+):(\d+)$/);
73
- if (m) {
74
- frames.push({ func: m[1] || undefined, file: m[2], line: Number(m[3]) });
75
- continue;
76
- }
77
- }
78
- return frames;
79
- }
80
-
81
- function basename(file?: string): string | undefined {
82
- if (!file) return undefined;
83
- const noQuery = file.split("?")[0];
84
- return noQuery.split("/").pop() || noQuery;
85
- }
86
-
87
- function cleanFunctionName(func?: string): string | undefined {
88
- if (!func) return undefined;
89
- const f = func.replace(/^Object\./, "").trim();
90
- if (!f || f === "<anonymous>" || f === "anonymous") return undefined;
91
- return f;
92
- }
93
-
94
- /** First component name from a React owner stack (nearest owner). */
95
- function firstComponent(ownerStack?: string): string | undefined {
96
- if (!ownerStack) return undefined;
97
- for (const raw of ownerStack.split("\n")) {
98
- const m = raw.trim().match(/^at\s+([A-Za-z_$][\w$]*)/);
99
- if (m) return m[1];
100
- }
101
- return undefined;
102
- }
103
-
104
- /** Derive the origin of a log from its captured JS stack + React owner stack. */
105
- export function parseOrigin(stack?: string, ownerStack?: string): LogOrigin | undefined {
106
- const component = firstComponent(ownerStack);
107
-
108
- let appFrame: RawFrame | undefined;
109
- if (stack) {
110
- const frames = parseFrames(stack);
111
- appFrame = frames.find((f) => !isInternalFrame(f));
112
- }
113
-
114
- const functionName = cleanFunctionName(appFrame?.func);
115
- const file = basename(appFrame?.file);
116
- const line = appFrame?.line;
117
- const callSite = file && line != null ? `${file}:${line}` : undefined;
118
-
119
- if (!component && !functionName && !callSite) return undefined;
120
- return { component, functionName, callSite, file, line };
121
- }
122
-
123
- // ─── Grouping by dimension ───────────────────────────────────────────────────
124
-
125
- /**
126
- * Stable key used to group consecutive rows (null = ungrouped).
127
- *
128
- * Each dimension falls back to the next-best signal so a row is never lumped
129
- * into a single catch-all bucket: a handler-fired log (no React owner) still
130
- * differentiates by its function / call site under "Component".
131
- */
132
- export function sourceKey(origin: LogOrigin | undefined, dim: GroupDimension): string | null {
133
- if (dim === "off" || !origin) return dim === "off" ? null : "—unknown—";
134
- if (dim === "component") {
135
- return origin.component ?? origin.functionName ?? origin.callSite ?? "—unknown—";
136
- }
137
- if (dim === "function") {
138
- return origin.functionName ?? origin.callSite ?? origin.component ?? "—anonymous—";
139
- }
140
- return origin.callSite ?? origin.functionName ?? "—unknown—";
141
- }
142
-
143
- /** Human label shown next to the row. */
144
- export function sourceLabel(origin: LogOrigin | undefined, dim: GroupDimension): string {
145
- if (!origin) return "(unknown)";
146
- if (dim === "component") {
147
- if (origin.component) return origin.component;
148
- if (origin.functionName) return `ƒ ${origin.functionName}`;
149
- return origin.callSite ?? "(unknown)";
150
- }
151
- if (dim === "function") {
152
- if (origin.functionName) return origin.functionName;
153
- return origin.callSite ?? "(anonymous)";
154
- }
155
- if (dim === "callsite") {
156
- if (origin.functionName && origin.callSite) return `${origin.functionName} · ${origin.callSite}`;
157
- return origin.callSite ?? (origin.functionName ? `ƒ ${origin.functionName}` : "(unknown)");
158
- }
159
- return "";
160
- }
161
-
162
- // ─── Color + bracket ─────────────────────────────────────────────────────────
163
-
164
- function hashString(s: string): number {
165
- let h = 0;
166
- for (let i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) | 0;
167
- return Math.abs(h);
168
- }
169
-
170
- /** Stable, readable color for a source key (bright enough for a dark surface). */
171
- export function colorForKey(key: string): string {
172
- const hue = hashString(key) % 360;
173
- return `hsl(${hue}, 70%, 66%)`;
174
- }
175
-
176
- export type Bracket = "top" | "mid" | "bottom" | "single";
177
-
178
- /** lnav gutter glyph: ┌ run-start · │ run-middle · └ run-end · ─ single. */
179
- export function bracketGlyph(bracket: Bracket): string {
180
- switch (bracket) {
181
- case "top":
182
- return "┌";
183
- case "bottom":
184
- return "└";
185
- case "single":
186
- return "─";
187
- default:
188
- return "│";
189
- }
190
- }