-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathconsoleFormatter.ts
More file actions
216 lines (190 loc) · 5.98 KB
/
consoleFormatter.ts
File metadata and controls
216 lines (190 loc) · 5.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import type {McpContext} from '../McpContext.js';
import type {DevTools} from '../third_party/index.js';
export interface ConsoleMessageData {
consoleMessageStableId: number;
type?: string;
item?: DevTools.AggregatedIssue;
message?: string;
count?: number;
description?: string;
args?: string[];
stackTrace?: DevTools.StackTrace.StackTrace.StackTrace;
}
// The short format for a console message, based on a previous format.
export function formatConsoleEventShort(msg: ConsoleMessageData): string {
if (msg.type === 'issue') {
return `msgid=${msg.consoleMessageStableId} [${msg.type}] ${msg.message} (count: ${msg.count})`;
}
return `msgid=${msg.consoleMessageStableId} [${msg.type}] ${msg.message} (${msg.args?.length ?? 0} args)`;
}
function getArgs(msg: ConsoleMessageData) {
const args = [...(msg.args ?? [])];
// If there is no text, the first argument serves as text (see formatMessage).
if (!msg.message) {
args.shift();
}
return args;
}
// The verbose format for a console message, including all details.
export function formatConsoleEventVerbose(
msg: ConsoleMessageData,
context?: McpContext,
): string {
const aggregatedIssue = msg.item;
const result = [
`ID: ${msg.consoleMessageStableId}`,
`Message: ${msg.type}> ${aggregatedIssue ? formatIssue(aggregatedIssue, msg.description, context) : msg.message}`,
aggregatedIssue ? undefined : formatArgs(msg),
formatStackTrace(msg.stackTrace),
].filter(line => !!line);
return result.join('\n');
}
function formatArg(arg: unknown) {
return typeof arg === 'object' ? JSON.stringify(arg) : String(arg);
}
function formatArgs(consoleData: ConsoleMessageData): string {
const args = getArgs(consoleData);
if (!args.length) {
return '';
}
const result = ['### Arguments'];
for (const [key, arg] of args.entries()) {
result.push(`Arg #${key}: ${formatArg(arg)}`);
}
return result.join('\n');
}
export function formatIssue(
issue: DevTools.AggregatedIssue,
description?: string,
context?: McpContext,
): string {
const result: string[] = [];
let processedMarkdown = description?.trim();
// Remove heading in order not to conflict with the whole console message response markdown
if (processedMarkdown?.startsWith('# ')) {
processedMarkdown = processedMarkdown.substring(2).trimStart();
}
if (processedMarkdown) {
result.push(processedMarkdown);
}
const links = issue.getDescription()?.links;
if (links && links.length > 0) {
result.push('Learn more:');
for (const link of links) {
result.push(`[${link.linkTitle}](${link.link})`);
}
}
const issues = issue.getAllIssues();
const affectedResources: Array<{
uid?: string;
data?: object;
request?: string | number;
}> = [];
for (const singleIssue of issues) {
const details = singleIssue.details();
if (!details) {
continue;
}
// We send the remaining details as untyped JSON because the DevTools
// frontend code is currently not re-usable.
// eslint-disable-next-line
const data = structuredClone(details) as any;
let uid;
let request: number | string | undefined;
if ('violatingNodeId' in details && details.violatingNodeId && context) {
uid = context.resolveCdpElementId(details.violatingNodeId);
delete data.violatingNodeId;
}
if ('nodeId' in details && details.nodeId && context) {
uid = context.resolveCdpElementId(details.nodeId);
delete data.nodeId;
}
if ('documentNodeId' in details && details.documentNodeId && context) {
uid = context.resolveCdpElementId(details.documentNodeId);
delete data.documentNodeId;
}
if ('request' in details && details.request) {
request = details.request.url;
if (details.request.requestId && context) {
const resolvedId = context.resolveCdpRequestId(
details.request.requestId,
);
if (resolvedId) {
request = resolvedId;
delete data.request.requestId;
}
}
}
// These fields has no use for the MCP client (redundant or irrelevant).
delete data.errorType;
delete data.frameId;
affectedResources.push({
uid,
data: data,
request,
});
}
if (affectedResources.length) {
result.push('### Affected resources');
}
result.push(
...affectedResources.map(item => {
const details = [];
if (item.uid) {
details.push(`uid=${item.uid}`);
}
if (item.request) {
details.push(
(typeof item.request === 'number' ? `reqid=` : 'url=') + item.request,
);
}
if (item.data) {
details.push(`data=${JSON.stringify(item.data)}`);
}
return details.join(' ');
}),
);
if (result.length === 0) {
return 'No affected resources found';
}
return result.join('\n');
}
function formatStackTrace(
stackTrace: DevTools.StackTrace.StackTrace.StackTrace | undefined,
): string {
if (!stackTrace) {
return '';
}
return [
'### Stack trace',
formatFragment(stackTrace.syncFragment),
...stackTrace.asyncFragments.map(formatAsyncFragment),
].join('\n');
}
function formatFragment(
fragment: DevTools.StackTrace.StackTrace.Fragment,
): string {
return fragment.frames.map(formatFrame).join('\n');
}
function formatAsyncFragment(
fragment: DevTools.StackTrace.StackTrace.AsyncFragment,
): string {
const separatorLineLength = 40;
const prefix = `--- ${fragment.description || 'async'} `;
const separator = prefix + '-'.repeat(separatorLineLength - prefix.length);
return separator + '\n' + formatFragment(fragment);
}
function formatFrame(frame: DevTools.StackTrace.StackTrace.Frame): string {
let result = `at ${frame.name ?? '<anonymous>'}`;
if (frame.uiSourceCode) {
result += ` (${frame.uiSourceCode.displayName()}:${frame.line}:${frame.column})`;
} else if (frame.url) {
result += ` (${frame.url}:${frame.line}:${frame.column})`;
}
return result;
}