chrome-devtools-mcp 1.9.0 → 1.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/src/BrowserManager.js +401 -0
- package/build/src/McpContext.js +5 -5
- package/build/src/McpPage.js +107 -3
- package/build/src/McpResponse.js +68 -3
- package/build/src/ToolHandler.js +172 -118
- package/build/src/bin/chrome-devtools-mcp-main.js +11 -6
- package/build/src/bin/chrome-devtools.js +6 -12
- package/build/src/collectors/PageCollector.js +66 -3
- package/build/src/config/browser-options.js +2 -0
- package/build/src/config/category-options.js +13 -4
- package/build/src/config/cli-commands.js +26 -0
- package/build/src/config/cli-options.js +32 -0
- package/build/src/config/mcp-options.js +40 -1
- package/build/src/devtools/DevToolsCommentBridge.js +91 -0
- package/build/src/formatters/CommentFormatter.js +82 -0
- package/build/src/formatters/CssFormatter.js +812 -0
- package/build/src/index.js +53 -72
- package/build/src/processors/ChunkedTraceParser.js +361 -0
- package/build/src/processors/PerformanceTrace.js +60 -13
- package/build/src/telemetry/ClearcutLogger.js +91 -34
- package/build/src/telemetry/metricsRegistry.js +3 -0
- package/build/src/telemetry/persistence.js +17 -7
- package/build/src/telemetry/transformation.js +53 -4
- package/build/src/telemetry/types.js +1 -0
- package/build/src/third_party/THIRD_PARTY_NOTICES +685 -131
- package/build/src/third_party/bundled-packages.json +6 -3
- package/build/src/third_party/devtools-formatter-worker.js +136 -5
- package/build/src/third_party/devtools-heap-snapshot-worker.js +567 -6
- package/build/src/third_party/index.js +54945 -35497
- package/build/src/third_party/issue-descriptions/webInstallManifestMissingId.md +3 -0
- package/build/src/third_party/issue-descriptions/webInstallManifestMissingNameOrShortName.md +3 -0
- package/build/src/third_party/issue-descriptions/webInstallManifestParsingOrNetworkError.md +3 -0
- package/build/src/third_party/issue-descriptions/webInstallNoManifest.md +3 -0
- package/build/src/third_party/issue-descriptions/webInstallStartUrlInvalid.md +3 -0
- package/build/src/tools/ToolDefinition.js +13 -21
- package/build/src/tools/comments.js +169 -0
- package/build/src/tools/console.js +3 -3
- package/build/src/tools/css.js +45 -0
- package/build/src/tools/emulation.js +5 -5
- package/build/src/tools/extensions.js +10 -10
- package/build/src/tools/input.js +159 -87
- package/build/src/tools/lighthouse.js +18 -7
- package/build/src/tools/memory.js +26 -26
- package/build/src/tools/network.js +4 -4
- package/build/src/tools/pages.js +14 -14
- package/build/src/tools/performance.js +6 -6
- package/build/src/tools/pwa.js +8 -8
- package/build/src/tools/screencast.js +4 -4
- package/build/src/tools/screenshot.js +2 -2
- package/build/src/tools/script.js +7 -7
- package/build/src/tools/slim/tools.js +5 -5
- package/build/src/tools/snapshot.js +4 -4
- package/build/src/tools/thirdPartyDeveloper.js +4 -4
- package/build/src/tools/tools.js +6 -9
- package/build/src/tools/webmcp.js +4 -4
- package/build/src/types.js +4 -1
- package/build/src/utils/WaitForHelper.js +14 -8
- package/build/src/utils/logger.js +7 -6
- package/build/src/version.js +1 -1
- package/package.json +8 -5
- package/skills/chrome-devtools/SKILL.md +2 -1
- package/skills/chrome-devtools-cli/SKILL.md +2 -0
- package/build/src/browser.js +0 -233
- package/build/src/third_party/issue-descriptions/cookieExcludeBlockedWithinRelatedWebsiteSet.md +0 -4
package/build/src/index.js
CHANGED
|
@@ -5,12 +5,12 @@
|
|
|
5
5
|
*/
|
|
6
6
|
import path from 'node:path';
|
|
7
7
|
import { pathToFileURL } from 'node:url';
|
|
8
|
-
import {
|
|
8
|
+
import { BrowserManager } from './BrowserManager.js';
|
|
9
9
|
import { loadIssueDescriptions } from './devtools/issueDescriptions.js';
|
|
10
10
|
import { McpContext } from './McpContext.js';
|
|
11
11
|
import { ClearcutLogger } from './telemetry/ClearcutLogger.js';
|
|
12
12
|
import { FilePersistence } from './telemetry/persistence.js';
|
|
13
|
-
import { McpServer as SdkMcpServer,
|
|
13
|
+
import { McpServer as SdkMcpServer, Mutex, puppeteer, } from './third_party/index.js';
|
|
14
14
|
import { ToolHandler } from './ToolHandler.js';
|
|
15
15
|
import { createTools } from './tools/tools.js';
|
|
16
16
|
import { logger } from './utils/logger.js';
|
|
@@ -28,7 +28,7 @@ const ROOTS_REQUEST_TIMEOUT = 5_000;
|
|
|
28
28
|
export class McpServer {
|
|
29
29
|
server;
|
|
30
30
|
#serverArgs;
|
|
31
|
-
#
|
|
31
|
+
#browserManager;
|
|
32
32
|
#context;
|
|
33
33
|
/**
|
|
34
34
|
* Client roots stay valid across browser reconnects and only the client can
|
|
@@ -37,9 +37,9 @@ export class McpServer {
|
|
|
37
37
|
*/
|
|
38
38
|
#lastClientRoots;
|
|
39
39
|
#toolMutex = new Mutex();
|
|
40
|
-
constructor(serverArgs, options
|
|
40
|
+
constructor(serverArgs, options) {
|
|
41
41
|
this.#serverArgs = serverArgs;
|
|
42
|
-
this.#
|
|
42
|
+
this.#browserManager = options.browserManager;
|
|
43
43
|
if (this.#serverArgs.usageStatistics) {
|
|
44
44
|
ClearcutLogger.initialize({
|
|
45
45
|
persistence: new FilePersistence(),
|
|
@@ -55,7 +55,7 @@ export class McpServer {
|
|
|
55
55
|
title: 'Chrome DevTools MCP server',
|
|
56
56
|
version: VERSION,
|
|
57
57
|
}, { capabilities: { logging: {} } });
|
|
58
|
-
this.server.server.setRequestHandler(
|
|
58
|
+
this.server.server.setRequestHandler('logging/setLevel', () => {
|
|
59
59
|
return {};
|
|
60
60
|
});
|
|
61
61
|
this.server.server.oninitialized = () => {
|
|
@@ -65,7 +65,7 @@ export class McpServer {
|
|
|
65
65
|
}
|
|
66
66
|
if (this.server.server.getClientCapabilities()?.roots) {
|
|
67
67
|
void this.#updateRoots();
|
|
68
|
-
this.server.server.setNotificationHandler(
|
|
68
|
+
this.server.server.setNotificationHandler('notifications/roots/list_changed', () => {
|
|
69
69
|
void this.#updateRoots();
|
|
70
70
|
});
|
|
71
71
|
}
|
|
@@ -85,19 +85,29 @@ export class McpServer {
|
|
|
85
85
|
* Closes the MCP connection and disposes internal context/listeners.
|
|
86
86
|
*/
|
|
87
87
|
async close() {
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
88
|
+
try {
|
|
89
|
+
this.#context?.dispose();
|
|
90
|
+
}
|
|
91
|
+
catch (err) {
|
|
92
|
+
logger?.('Failed to dispose context', err);
|
|
93
|
+
}
|
|
94
|
+
finally {
|
|
95
|
+
this.#context = undefined;
|
|
96
|
+
}
|
|
97
|
+
await Promise.allSettled([
|
|
98
|
+
this.#browserManager.close(),
|
|
99
|
+
this.server.close(),
|
|
100
|
+
]);
|
|
91
101
|
}
|
|
92
102
|
[Symbol.dispose]() {
|
|
93
|
-
this.close().catch(
|
|
94
|
-
|
|
103
|
+
this.close().catch(err => {
|
|
104
|
+
logger?.('Failed to dispose McpServer', err);
|
|
95
105
|
});
|
|
96
106
|
}
|
|
97
107
|
async [Symbol.asyncDispose]() {
|
|
98
108
|
await this.close();
|
|
99
109
|
}
|
|
100
|
-
static async from(serverArgs, options
|
|
110
|
+
static async from(serverArgs, options) {
|
|
101
111
|
const server = new McpServer(serverArgs, options);
|
|
102
112
|
await server.#init();
|
|
103
113
|
return server;
|
|
@@ -113,7 +123,7 @@ export class McpServer {
|
|
|
113
123
|
const configuredRoots = (this.#serverArgs.allowUnrestrictedPaths
|
|
114
124
|
? []
|
|
115
125
|
: (this.#serverArgs.filesystemRoot ?? [])).map(root => {
|
|
116
|
-
const rootPath = path.resolve(
|
|
126
|
+
const rootPath = path.resolve(root);
|
|
117
127
|
return {
|
|
118
128
|
uri: pathToFileURL(rootPath).href,
|
|
119
129
|
name: path.basename(rootPath) || rootPath,
|
|
@@ -134,8 +144,8 @@ export class McpServer {
|
|
|
134
144
|
return;
|
|
135
145
|
}
|
|
136
146
|
try {
|
|
137
|
-
const
|
|
138
|
-
this.#lastClientRoots =
|
|
147
|
+
const result = await this.server.server.request({ method: 'roots/list' }, timeout === undefined ? undefined : { timeout });
|
|
148
|
+
this.#lastClientRoots = result.roots;
|
|
139
149
|
this.#context?.setRoots(this.#combinedRoots());
|
|
140
150
|
}
|
|
141
151
|
catch (e) {
|
|
@@ -143,63 +153,30 @@ export class McpServer {
|
|
|
143
153
|
}
|
|
144
154
|
}
|
|
145
155
|
async #getContext() {
|
|
146
|
-
const
|
|
147
|
-
const ignoreDefaultChromeArgs = (this.#serverArgs.ignoreDefaultChromeArg ?? []).map(String);
|
|
148
|
-
if (this.#serverArgs.proxyServer) {
|
|
149
|
-
chromeArgs.push(`--proxy-server=${this.#serverArgs.proxyServer}`);
|
|
150
|
-
}
|
|
151
|
-
const devtools = this.#serverArgs.experimentalDevtools ?? false;
|
|
152
|
-
const blocklist = this.#serverArgs.blockedUrlPattern
|
|
153
|
-
? this.#serverArgs.blockedUrlPattern.map(String)
|
|
154
|
-
: undefined;
|
|
155
|
-
const allowlist = this.#serverArgs.allowedUrlPattern
|
|
156
|
-
? this.#serverArgs.allowedUrlPattern.map(String)
|
|
157
|
-
: undefined;
|
|
158
|
-
const channel = this.#serverArgs.channel;
|
|
159
|
-
const browser = this.#serverArgs.browserUrl ||
|
|
160
|
-
this.#serverArgs.wsEndpoint ||
|
|
161
|
-
this.#serverArgs.autoConnect
|
|
162
|
-
? await ensureBrowserConnected({
|
|
163
|
-
browserURL: this.#serverArgs.browserUrl,
|
|
164
|
-
wsEndpoint: this.#serverArgs.wsEndpoint,
|
|
165
|
-
wsHeaders: this.#serverArgs.wsHeaders,
|
|
166
|
-
// Important: only pass channel, if autoConnect is true.
|
|
167
|
-
channel: this.#serverArgs.autoConnect ? channel : undefined,
|
|
168
|
-
userDataDir: this.#serverArgs.userDataDir,
|
|
169
|
-
devtools,
|
|
170
|
-
blocklist,
|
|
171
|
-
allowlist,
|
|
172
|
-
})
|
|
173
|
-
: await ensureBrowserLaunched({
|
|
174
|
-
headless: this.#serverArgs.headless,
|
|
175
|
-
executablePath: this.#serverArgs.executablePath,
|
|
176
|
-
channel,
|
|
177
|
-
isolated: this.#serverArgs.isolated ?? false,
|
|
178
|
-
userDataDir: this.#serverArgs.userDataDir,
|
|
179
|
-
logFile: this.#options.logFile,
|
|
180
|
-
viewport: this.#serverArgs.viewport,
|
|
181
|
-
chromeArgs,
|
|
182
|
-
ignoreDefaultChromeArgs,
|
|
183
|
-
acceptInsecureCerts: this.#serverArgs.acceptInsecureCerts,
|
|
184
|
-
devtools,
|
|
185
|
-
enableExtensions: this.#serverArgs.categoryExtensions,
|
|
186
|
-
viaCli: this.#serverArgs.viaCli,
|
|
187
|
-
blocklist,
|
|
188
|
-
allowlist,
|
|
189
|
-
});
|
|
156
|
+
const browser = await this.#browserManager.ensureBrowser();
|
|
190
157
|
if (this.#context?.browser !== browser) {
|
|
191
158
|
this.#context?.dispose();
|
|
192
159
|
this.#context = await McpContext.from(browser, logger, {
|
|
193
|
-
experimentalDevToolsDebugging:
|
|
160
|
+
experimentalDevToolsDebugging: this.#serverArgs.experimentalDevtools ?? false,
|
|
194
161
|
experimentalIncludeAllPages: this.#serverArgs.experimentalIncludeAllPages,
|
|
195
162
|
performanceCrux: this.#serverArgs.performanceCrux,
|
|
196
163
|
sourceMaps: this.#serverArgs.sourceMaps,
|
|
197
|
-
|
|
198
|
-
blocklist:
|
|
164
|
+
allowlist: this.#serverArgs.allowedUrlPattern,
|
|
165
|
+
blocklist: this.#serverArgs.blockedUrlPattern,
|
|
199
166
|
allowUnrestrictedPaths: this.#serverArgs.allowUnrestrictedPaths,
|
|
200
167
|
// Surfaces a one-time note in the next response after a reconnect.
|
|
201
168
|
reconnected: this.#context !== undefined,
|
|
202
169
|
categoryExtensions: this.#serverArgs.categoryExtensions,
|
|
170
|
+
onNotification: (message) => {
|
|
171
|
+
void this.server
|
|
172
|
+
.sendLoggingMessage({
|
|
173
|
+
level: 'info',
|
|
174
|
+
data: message,
|
|
175
|
+
})
|
|
176
|
+
.catch(e => {
|
|
177
|
+
logger?.('Failed to send MCP notification', e);
|
|
178
|
+
});
|
|
179
|
+
},
|
|
203
180
|
});
|
|
204
181
|
this.#context.setRoots(this.#combinedRoots());
|
|
205
182
|
if (this.#lastClientRoots === undefined) {
|
|
@@ -217,16 +194,14 @@ export class McpServer {
|
|
|
217
194
|
}
|
|
218
195
|
#registerTool(tool) {
|
|
219
196
|
const toolHandler = new ToolHandler(tool, this.#serverArgs, () => this.#getContext(), this.#toolMutex);
|
|
220
|
-
|
|
221
|
-
return;
|
|
222
|
-
}
|
|
223
|
-
this.server.registerTool(tool.name, {
|
|
197
|
+
const registeredTool = this.server.registerTool(tool.name, {
|
|
224
198
|
description: tool.description,
|
|
225
199
|
inputSchema: toolHandler.registeredInputSchema,
|
|
226
200
|
annotations: tool.annotations,
|
|
227
|
-
},
|
|
228
|
-
|
|
229
|
-
|
|
201
|
+
}, toolHandler.handle);
|
|
202
|
+
if (toolHandler.disabled) {
|
|
203
|
+
registeredTool.disable();
|
|
204
|
+
}
|
|
230
205
|
}
|
|
231
206
|
}
|
|
232
207
|
/**
|
|
@@ -236,8 +211,14 @@ export class McpServer {
|
|
|
236
211
|
* consumers and integrations rely on `createMcpServer()`. For new code,
|
|
237
212
|
* prefer using `McpServer.from(serverArgs, options)`.
|
|
238
213
|
*/
|
|
239
|
-
export async function createMcpServer(serverArgs, options
|
|
240
|
-
const
|
|
214
|
+
export async function createMcpServer(serverArgs, options) {
|
|
215
|
+
const browserManager = new BrowserManager(serverArgs, {
|
|
216
|
+
logFile: options.logFile,
|
|
217
|
+
});
|
|
218
|
+
const server = await McpServer.from(serverArgs, {
|
|
219
|
+
browserManager,
|
|
220
|
+
...options,
|
|
221
|
+
});
|
|
241
222
|
return { server: server.server };
|
|
242
223
|
}
|
|
243
224
|
export const logDisclaimers = (args) => {
|
|
@@ -0,0 +1,361 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Google LLC
|
|
4
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
5
|
+
*/
|
|
6
|
+
const DEFAULT_EVENTS_PER_BATCH = 10_000;
|
|
7
|
+
const DEFAULT_MAX_BATCH_BYTES = 32 * 1024 * 1024;
|
|
8
|
+
// ASCII character byte constants used by the state machine.
|
|
9
|
+
// All values are strictly less than 0x80 (standard ASCII).
|
|
10
|
+
// In UTF-8 encoding, multi-byte code units only contain bytes from 0x80 through 0xFF.
|
|
11
|
+
// Therefore, scanning for these byte values will never match bytes inside multi-byte characters.
|
|
12
|
+
const BYTE_QUOTE = 0x22;
|
|
13
|
+
const BYTE_BACKSLASH = 0x5c;
|
|
14
|
+
const BYTE_OPEN_BRACE = 0x7b;
|
|
15
|
+
const BYTE_CLOSE_BRACE = 0x7d;
|
|
16
|
+
const BYTE_OPEN_BRACKET = 0x5b;
|
|
17
|
+
const BYTE_CLOSE_BRACKET = 0x5d;
|
|
18
|
+
const BYTE_COLON = 0x3a;
|
|
19
|
+
const BYTE_COMMA = 0x2c;
|
|
20
|
+
/**
|
|
21
|
+
* Advances past any RFC 8259 JSON whitespace bytes.
|
|
22
|
+
*
|
|
23
|
+
* @param buffer - The trace byte buffer to inspect.
|
|
24
|
+
* @param start - The buffer index where scanning begins.
|
|
25
|
+
* @returns The index of the first non-whitespace byte, or the buffer length if the buffer ends.
|
|
26
|
+
*/
|
|
27
|
+
function skipWhitespace(buffer, start) {
|
|
28
|
+
let i = start;
|
|
29
|
+
while (i < buffer.length) {
|
|
30
|
+
const byte = buffer[i];
|
|
31
|
+
if (byte !== 0x20 && byte !== 0x09 && byte !== 0x0a && byte !== 0x0d) {
|
|
32
|
+
break;
|
|
33
|
+
}
|
|
34
|
+
i++;
|
|
35
|
+
}
|
|
36
|
+
return i;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Scans past a JSON string starting at the opening quotation mark.
|
|
40
|
+
*
|
|
41
|
+
* @param buffer - The trace byte buffer to scan.
|
|
42
|
+
* @param startQuotePos - The buffer index of the opening quotation mark.
|
|
43
|
+
* @returns The index immediately following the closing quotation mark.
|
|
44
|
+
* @throws {SyntaxError} If the string is unterminated before the end of the buffer.
|
|
45
|
+
*/
|
|
46
|
+
function skipString(buffer, startQuotePos) {
|
|
47
|
+
let pos = startQuotePos + 1;
|
|
48
|
+
while (pos < buffer.length) {
|
|
49
|
+
const byte = buffer[pos];
|
|
50
|
+
if (byte === BYTE_BACKSLASH) {
|
|
51
|
+
if (pos + 1 >= buffer.length) {
|
|
52
|
+
throw new SyntaxError('Unterminated string in JSON');
|
|
53
|
+
}
|
|
54
|
+
pos += 2;
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
57
|
+
if (byte === BYTE_QUOTE) {
|
|
58
|
+
return pos + 1;
|
|
59
|
+
}
|
|
60
|
+
pos++;
|
|
61
|
+
}
|
|
62
|
+
throw new SyntaxError('Unterminated string in JSON');
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Scans past a complete JSON value starting at the specified buffer position.
|
|
66
|
+
* Skips strings, compound objects, arrays, and primitive values without parsing them into memory.
|
|
67
|
+
*
|
|
68
|
+
* @param buffer - The trace byte buffer to scan.
|
|
69
|
+
* @param startPos - The buffer index where the value begins.
|
|
70
|
+
* @returns The index immediately following the skipped JSON value.
|
|
71
|
+
* @throws {SyntaxError} If the value contains unbalanced delimiters, unterminated strings, or empty primitive tokens.
|
|
72
|
+
*/
|
|
73
|
+
function skipValue(buffer, startPos) {
|
|
74
|
+
let pos = skipWhitespace(buffer, startPos);
|
|
75
|
+
if (pos >= buffer.length) {
|
|
76
|
+
return pos;
|
|
77
|
+
}
|
|
78
|
+
const firstByte = buffer[pos];
|
|
79
|
+
if (firstByte === BYTE_QUOTE) {
|
|
80
|
+
return skipString(buffer, pos);
|
|
81
|
+
}
|
|
82
|
+
if (firstByte === BYTE_OPEN_BRACE || firstByte === BYTE_OPEN_BRACKET) {
|
|
83
|
+
const delimiterStack = [];
|
|
84
|
+
delimiterStack.push(firstByte === BYTE_OPEN_BRACE ? BYTE_CLOSE_BRACE : BYTE_CLOSE_BRACKET);
|
|
85
|
+
pos++;
|
|
86
|
+
while (pos < buffer.length) {
|
|
87
|
+
const byte = buffer[pos];
|
|
88
|
+
if (byte === BYTE_QUOTE) {
|
|
89
|
+
pos = skipString(buffer, pos);
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
if (byte === BYTE_OPEN_BRACE) {
|
|
93
|
+
delimiterStack.push(BYTE_CLOSE_BRACE);
|
|
94
|
+
}
|
|
95
|
+
else if (byte === BYTE_OPEN_BRACKET) {
|
|
96
|
+
delimiterStack.push(BYTE_CLOSE_BRACKET);
|
|
97
|
+
}
|
|
98
|
+
else if (byte === BYTE_CLOSE_BRACE || byte === BYTE_CLOSE_BRACKET) {
|
|
99
|
+
const expected = delimiterStack.pop();
|
|
100
|
+
if (expected !== byte) {
|
|
101
|
+
throw new SyntaxError('Unexpected delimiter in JSON');
|
|
102
|
+
}
|
|
103
|
+
if (delimiterStack.length === 0) {
|
|
104
|
+
pos++;
|
|
105
|
+
return pos;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
pos++;
|
|
109
|
+
}
|
|
110
|
+
throw new SyntaxError('Unexpected end of JSON input');
|
|
111
|
+
}
|
|
112
|
+
const valStart = pos;
|
|
113
|
+
while (pos < buffer.length) {
|
|
114
|
+
const byte = buffer[pos];
|
|
115
|
+
if (byte === BYTE_COMMA ||
|
|
116
|
+
byte === BYTE_CLOSE_BRACE ||
|
|
117
|
+
byte === BYTE_CLOSE_BRACKET ||
|
|
118
|
+
byte === 0x20 ||
|
|
119
|
+
byte === 0x09 ||
|
|
120
|
+
byte === 0x0a ||
|
|
121
|
+
byte === 0x0d) {
|
|
122
|
+
break;
|
|
123
|
+
}
|
|
124
|
+
pos++;
|
|
125
|
+
}
|
|
126
|
+
if (pos === valStart) {
|
|
127
|
+
throw new SyntaxError('Expected JSON value');
|
|
128
|
+
}
|
|
129
|
+
return pos;
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Scans trace events from a JSON array in bounded batches to limit memory consumption.
|
|
133
|
+
*
|
|
134
|
+
* @param buffer - The raw byte buffer containing the events array.
|
|
135
|
+
* @param startPos - The index immediately after the opening array bracket.
|
|
136
|
+
* @param config - Configuration settings controlling batch sizes and text decoding.
|
|
137
|
+
* @returns An object containing the parsed events and the ending buffer position.
|
|
138
|
+
* @throws {SyntaxError} If the event array contains malformed JSON, unbalanced delimiters, or unexpected tokens.
|
|
139
|
+
*/
|
|
140
|
+
function parseEventsArray(buffer, startPos, config) {
|
|
141
|
+
const events = [];
|
|
142
|
+
let batchStart = -1;
|
|
143
|
+
let lastEventEnd = -1;
|
|
144
|
+
let batchEventCount = 0;
|
|
145
|
+
let depth = 0;
|
|
146
|
+
let i = startPos;
|
|
147
|
+
let closed = false;
|
|
148
|
+
let state = 'expect_element_or_end';
|
|
149
|
+
const flushBatch = () => {
|
|
150
|
+
if (batchStart !== -1 && lastEventEnd > batchStart) {
|
|
151
|
+
// Slicing between batchStart and lastEventEnd is safe for UTF-8 decoding.
|
|
152
|
+
// Both boundaries are ASCII structural braces ({ and }) that align with code unit boundaries.
|
|
153
|
+
const slice = buffer.subarray(batchStart, lastEventEnd);
|
|
154
|
+
const chunkText = config.decoder.decode(slice);
|
|
155
|
+
// Wrapping comma-delimited event objects in brackets creates a valid JSON array for the parser.
|
|
156
|
+
const parsed = JSON.parse(`[${chunkText}]`);
|
|
157
|
+
// Append items iteratively to avoid exceeding V8 call stack size limits on large batches.
|
|
158
|
+
for (const event of parsed) {
|
|
159
|
+
events.push(event);
|
|
160
|
+
}
|
|
161
|
+
batchStart = -1;
|
|
162
|
+
batchEventCount = 0;
|
|
163
|
+
}
|
|
164
|
+
};
|
|
165
|
+
while (i < buffer.length) {
|
|
166
|
+
const byte = buffer[i];
|
|
167
|
+
if (depth > 0) {
|
|
168
|
+
if (byte === BYTE_QUOTE) {
|
|
169
|
+
i = skipString(buffer, i);
|
|
170
|
+
continue;
|
|
171
|
+
}
|
|
172
|
+
if (byte === BYTE_OPEN_BRACE) {
|
|
173
|
+
depth++;
|
|
174
|
+
i++;
|
|
175
|
+
continue;
|
|
176
|
+
}
|
|
177
|
+
if (byte === BYTE_CLOSE_BRACE) {
|
|
178
|
+
depth--;
|
|
179
|
+
if (depth === 0) {
|
|
180
|
+
lastEventEnd = i + 1;
|
|
181
|
+
batchEventCount++;
|
|
182
|
+
state = 'expect_comma_or_end';
|
|
183
|
+
// Check thresholds after recording the completed event.
|
|
184
|
+
// Checking batchEventCount after incrementing ensures batches cap at exactly eventsPerBatch.
|
|
185
|
+
// Individual events are atomic JSON objects and cannot be split mid-event; when an event
|
|
186
|
+
// pushes currentBatchBytes over maxBatchBytes, the completed event is flushed immediately.
|
|
187
|
+
const currentBatchBytes = lastEventEnd - batchStart;
|
|
188
|
+
if (batchEventCount >= config.eventsPerBatch ||
|
|
189
|
+
currentBatchBytes >= config.maxBatchBytes) {
|
|
190
|
+
flushBatch();
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
i++;
|
|
194
|
+
continue;
|
|
195
|
+
}
|
|
196
|
+
i++;
|
|
197
|
+
continue;
|
|
198
|
+
}
|
|
199
|
+
// When depth is 0, scan top-level array delimiter and separator tokens.
|
|
200
|
+
if (byte === 0x20 || byte === 0x09 || byte === 0x0a || byte === 0x0d) {
|
|
201
|
+
i++;
|
|
202
|
+
continue;
|
|
203
|
+
}
|
|
204
|
+
if (byte === BYTE_OPEN_BRACE) {
|
|
205
|
+
if (state !== 'expect_element_or_end' && state !== 'expect_element') {
|
|
206
|
+
throw new SyntaxError('Expected "," or "]" in JSON array');
|
|
207
|
+
}
|
|
208
|
+
depth = 1;
|
|
209
|
+
if (batchStart === -1) {
|
|
210
|
+
batchStart = i;
|
|
211
|
+
}
|
|
212
|
+
i++;
|
|
213
|
+
continue;
|
|
214
|
+
}
|
|
215
|
+
if (byte === BYTE_COMMA) {
|
|
216
|
+
if (state !== 'expect_comma_or_end') {
|
|
217
|
+
throw new SyntaxError('Unexpected token "," in JSON array');
|
|
218
|
+
}
|
|
219
|
+
state = 'expect_element';
|
|
220
|
+
i++;
|
|
221
|
+
continue;
|
|
222
|
+
}
|
|
223
|
+
if (byte === BYTE_CLOSE_BRACKET) {
|
|
224
|
+
if (state === 'expect_element') {
|
|
225
|
+
throw new SyntaxError('Unexpected token "]" in JSON array');
|
|
226
|
+
}
|
|
227
|
+
closed = true;
|
|
228
|
+
i++;
|
|
229
|
+
break;
|
|
230
|
+
}
|
|
231
|
+
if (byte === BYTE_CLOSE_BRACE) {
|
|
232
|
+
throw new SyntaxError('Unexpected token "}" in JSON');
|
|
233
|
+
}
|
|
234
|
+
throw new SyntaxError('Unexpected token in JSON array');
|
|
235
|
+
}
|
|
236
|
+
if (!closed || depth !== 0) {
|
|
237
|
+
throw new SyntaxError('Unexpected end of JSON input');
|
|
238
|
+
}
|
|
239
|
+
flushBatch();
|
|
240
|
+
return { events, endPos: i };
|
|
241
|
+
}
|
|
242
|
+
/**
|
|
243
|
+
* Parses Chrome DevTools trace events and metadata from a raw byte buffer.
|
|
244
|
+
* Supports both root array format ([...]) and object container format ({"traceEvents": [...]}).
|
|
245
|
+
* Parses events in chunks to prevent V8 string length and memory exhaustion errors.
|
|
246
|
+
*
|
|
247
|
+
* @param buffer - The raw trace buffer to parse.
|
|
248
|
+
* @param options - Optional configuration settings for batch processing.
|
|
249
|
+
* @returns A {@link ParsedTraceBuffer} containing parsed trace events and optional file metadata, or an object with an empty events array if the buffer is empty or contains only whitespace.
|
|
250
|
+
* @throws {Error} If the buffer contains non-whitespace data that does not begin with a valid JSON array or object.
|
|
251
|
+
* @throws {SyntaxError} If the underlying JSON syntax within batches or metadata is invalid.
|
|
252
|
+
*/
|
|
253
|
+
export function parseTraceEventsFromBuffer(buffer, options = {}) {
|
|
254
|
+
const eventsPerBatch = typeof options.eventsPerBatch === 'number' &&
|
|
255
|
+
Number.isFinite(options.eventsPerBatch) &&
|
|
256
|
+
options.eventsPerBatch > 0
|
|
257
|
+
? options.eventsPerBatch
|
|
258
|
+
: DEFAULT_EVENTS_PER_BATCH;
|
|
259
|
+
const maxBatchBytes = typeof options.maxBatchBytes === 'number' &&
|
|
260
|
+
Number.isFinite(options.maxBatchBytes) &&
|
|
261
|
+
options.maxBatchBytes > 0
|
|
262
|
+
? options.maxBatchBytes
|
|
263
|
+
: DEFAULT_MAX_BATCH_BYTES;
|
|
264
|
+
const decoder = new TextDecoder();
|
|
265
|
+
const config = {
|
|
266
|
+
eventsPerBatch,
|
|
267
|
+
maxBatchBytes,
|
|
268
|
+
decoder,
|
|
269
|
+
};
|
|
270
|
+
let pos = skipWhitespace(buffer, 0);
|
|
271
|
+
if (pos >= buffer.length) {
|
|
272
|
+
return { events: [] };
|
|
273
|
+
}
|
|
274
|
+
const firstByte = buffer[pos];
|
|
275
|
+
if (firstByte === BYTE_OPEN_BRACKET) {
|
|
276
|
+
const { events, endPos } = parseEventsArray(buffer, pos + 1, config);
|
|
277
|
+
const trailingPos = skipWhitespace(buffer, endPos);
|
|
278
|
+
if (trailingPos < buffer.length) {
|
|
279
|
+
throw new SyntaxError('Unexpected non-whitespace character after JSON');
|
|
280
|
+
}
|
|
281
|
+
return { events };
|
|
282
|
+
}
|
|
283
|
+
if (firstByte === BYTE_OPEN_BRACE) {
|
|
284
|
+
pos++;
|
|
285
|
+
let events = [];
|
|
286
|
+
let metadata;
|
|
287
|
+
let closed = false;
|
|
288
|
+
let expectComma = false;
|
|
289
|
+
while (pos < buffer.length) {
|
|
290
|
+
pos = skipWhitespace(buffer, pos);
|
|
291
|
+
if (pos >= buffer.length) {
|
|
292
|
+
break;
|
|
293
|
+
}
|
|
294
|
+
if (buffer[pos] === BYTE_CLOSE_BRACE) {
|
|
295
|
+
closed = true;
|
|
296
|
+
pos++;
|
|
297
|
+
break;
|
|
298
|
+
}
|
|
299
|
+
if (expectComma) {
|
|
300
|
+
if (buffer[pos] !== BYTE_COMMA) {
|
|
301
|
+
throw new SyntaxError('Expected "," or "}" after property value in JSON');
|
|
302
|
+
}
|
|
303
|
+
pos++;
|
|
304
|
+
pos = skipWhitespace(buffer, pos);
|
|
305
|
+
}
|
|
306
|
+
if (pos >= buffer.length) {
|
|
307
|
+
break;
|
|
308
|
+
}
|
|
309
|
+
if (buffer[pos] !== BYTE_QUOTE) {
|
|
310
|
+
throw new SyntaxError('Expected property name or "}" in JSON');
|
|
311
|
+
}
|
|
312
|
+
const keyStart = pos;
|
|
313
|
+
pos = skipString(buffer, pos);
|
|
314
|
+
const keyJson = decoder.decode(buffer.subarray(keyStart, pos));
|
|
315
|
+
const parsedKey = JSON.parse(keyJson);
|
|
316
|
+
if (typeof parsedKey !== 'string') {
|
|
317
|
+
throw new SyntaxError('Expected property name in JSON');
|
|
318
|
+
}
|
|
319
|
+
const key = parsedKey;
|
|
320
|
+
pos = skipWhitespace(buffer, pos);
|
|
321
|
+
if (pos >= buffer.length || buffer[pos] !== BYTE_COLON) {
|
|
322
|
+
throw new SyntaxError('Expected ":" after property name in JSON');
|
|
323
|
+
}
|
|
324
|
+
pos++;
|
|
325
|
+
pos = skipWhitespace(buffer, pos);
|
|
326
|
+
if (key === 'traceEvents') {
|
|
327
|
+
if (pos >= buffer.length || buffer[pos] !== BYTE_OPEN_BRACKET) {
|
|
328
|
+
throw new SyntaxError('Expected "[" for "traceEvents" in JSON');
|
|
329
|
+
}
|
|
330
|
+
const arrayResult = parseEventsArray(buffer, pos + 1, config);
|
|
331
|
+
events = arrayResult.events;
|
|
332
|
+
pos = arrayResult.endPos;
|
|
333
|
+
}
|
|
334
|
+
else if (key === 'metadata') {
|
|
335
|
+
if (pos >= buffer.length || buffer[pos] !== BYTE_OPEN_BRACE) {
|
|
336
|
+
throw new SyntaxError('Expected "{" for "metadata" in JSON');
|
|
337
|
+
}
|
|
338
|
+
const metaStart = pos;
|
|
339
|
+
pos = skipValue(buffer, pos);
|
|
340
|
+
const metaSlice = buffer.subarray(metaStart, pos);
|
|
341
|
+
const metaText = decoder.decode(metaSlice);
|
|
342
|
+
const parsedMetadata = JSON.parse(metaText);
|
|
343
|
+
metadata = parsedMetadata;
|
|
344
|
+
}
|
|
345
|
+
else {
|
|
346
|
+
pos = skipValue(buffer, pos);
|
|
347
|
+
}
|
|
348
|
+
expectComma = true;
|
|
349
|
+
}
|
|
350
|
+
if (!closed) {
|
|
351
|
+
throw new SyntaxError('Unexpected end of JSON input');
|
|
352
|
+
}
|
|
353
|
+
const trailingPos = skipWhitespace(buffer, pos);
|
|
354
|
+
if (trailingPos < buffer.length) {
|
|
355
|
+
throw new SyntaxError('Unexpected non-whitespace character after JSON');
|
|
356
|
+
}
|
|
357
|
+
return { events, metadata };
|
|
358
|
+
}
|
|
359
|
+
throw new Error('Invalid trace buffer: expected JSON object or array.');
|
|
360
|
+
}
|
|
361
|
+
//# sourceMappingURL=ChunkedTraceParser.js.map
|