mcp-browser-dev-tools 0.2.2 → 0.4.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/README.md +30 -15
- package/package.json +9 -2
- package/src/action-changes.mjs +340 -0
- package/src/browser-adapter.mjs +48 -4
- package/src/cdp-client.mjs +1219 -44
- package/src/config.mjs +10 -0
- package/src/firefox-bidi-client.mjs +767 -47
- package/src/json-schema.mjs +14 -1
- package/src/mcp-server.mjs +59 -8
- package/src/network-control.mjs +156 -0
- package/src/page-context.mjs +306 -2
- package/src/page-script.mjs +1175 -13
- package/src/run-steps.mjs +75 -23
- package/src/run-tabs.mjs +11 -16
- package/src/screenshot-output.mjs +92 -1
- package/src/session-events.mjs +57 -0
- package/src/tool-schemas.mjs +88 -83
- package/src/tool-sets.mjs +73 -0
- package/src/tools/action-tools.mjs +217 -77
- package/src/tools/browser-tools.mjs +12 -19
- package/src/tools/inspection-tools.mjs +88 -54
- package/src/tools/more-tools.mjs +108 -0
- package/src/tools/performance-tools.mjs +183 -0
- package/src/tools/state-tools.mjs +62 -16
- package/src/upload-files.mjs +57 -0
- package/src/video-output.mjs +401 -0
|
@@ -80,7 +80,7 @@ export function stateTools(server) {
|
|
|
80
80
|
definition: {
|
|
81
81
|
name: "get_page_state",
|
|
82
82
|
description:
|
|
83
|
-
"
|
|
83
|
+
"URL, title, ready state, viewport, and scroll position.",
|
|
84
84
|
inputSchema: sessionSchema({}, []),
|
|
85
85
|
},
|
|
86
86
|
handler: async (args) =>
|
|
@@ -93,7 +93,7 @@ export function stateTools(server) {
|
|
|
93
93
|
definition: {
|
|
94
94
|
name: "compare_page_state",
|
|
95
95
|
description:
|
|
96
|
-
"Compare
|
|
96
|
+
"Compare page state across two sessions, for cross-browser checks.",
|
|
97
97
|
inputSchema: compareSessionsSchema({}, []),
|
|
98
98
|
},
|
|
99
99
|
handler: async (args) => {
|
|
@@ -133,8 +133,7 @@ export function stateTools(server) {
|
|
|
133
133
|
{
|
|
134
134
|
definition: {
|
|
135
135
|
name: "compare_selector",
|
|
136
|
-
description:
|
|
137
|
-
"Compare a selector across two attached sessions using a bounded element summary.",
|
|
136
|
+
description: "Compare one element across two sessions.",
|
|
138
137
|
inputSchema: compareSessionsSchema(
|
|
139
138
|
{
|
|
140
139
|
selector: selectorProperty(),
|
|
@@ -189,9 +188,8 @@ export function stateTools(server) {
|
|
|
189
188
|
{
|
|
190
189
|
definition: {
|
|
191
190
|
name: "wait_for",
|
|
192
|
-
description:
|
|
193
|
-
|
|
194
|
-
: "Wait until every given condition holds: selector state, its text (textEquals, textIncludes, textExcludes), url, urlIncludes, or readyState; or give anyOf to end on the first of several. Polls until they hold or timeoutMs passes, then fails with the last observed state. Selector checks scroll the element into view.",
|
|
191
|
+
description:
|
|
192
|
+
"Wait until every given condition holds, or the first of anyOf; at timeoutMs it fails with the last observed state. Selector checks scroll the element into view.",
|
|
195
193
|
inputSchema: waitForInputSchema({
|
|
196
194
|
expression: server.config.enableEvaluate,
|
|
197
195
|
}),
|
|
@@ -221,21 +219,70 @@ export function stateTools(server) {
|
|
|
221
219
|
{
|
|
222
220
|
definition: {
|
|
223
221
|
name: "get_cookies",
|
|
224
|
-
description:
|
|
225
|
-
"Read bounded page-visible cookies for the attached session.",
|
|
222
|
+
description: "Page-visible cookies.",
|
|
226
223
|
inputSchema: sessionSchema({}, []),
|
|
227
224
|
},
|
|
228
225
|
handler: async (args) =>
|
|
229
226
|
server.browserAdapter.getCookies(args.sessionId),
|
|
230
227
|
},
|
|
231
228
|
],
|
|
229
|
+
[
|
|
230
|
+
"set_network",
|
|
231
|
+
{
|
|
232
|
+
definition: {
|
|
233
|
+
name: "set_network",
|
|
234
|
+
description:
|
|
235
|
+
"Block or mock requests by URL glob (* any run, ? one character), add request headers, or emulate offline and slow networks (throttling Chromium only). A call replaces the fields it gives; reset clears all. Returns the rules with their hits.",
|
|
236
|
+
inputSchema: sessionSchema(
|
|
237
|
+
{
|
|
238
|
+
rules: {
|
|
239
|
+
type: "array",
|
|
240
|
+
maxItems: 50,
|
|
241
|
+
items: {
|
|
242
|
+
type: "object",
|
|
243
|
+
properties: {
|
|
244
|
+
url: { type: "string", description: "e.g. *://*/api/ads*" },
|
|
245
|
+
action: { type: "string", enum: ["block", "mock"] },
|
|
246
|
+
status: { type: "integer", minimum: 100, maximum: 599 },
|
|
247
|
+
contentType: { type: "string" },
|
|
248
|
+
body: { type: "string" },
|
|
249
|
+
headers: {
|
|
250
|
+
type: "object",
|
|
251
|
+
additionalProperties: { type: "string" },
|
|
252
|
+
},
|
|
253
|
+
},
|
|
254
|
+
required: ["url", "action"],
|
|
255
|
+
additionalProperties: false,
|
|
256
|
+
},
|
|
257
|
+
description:
|
|
258
|
+
"First match wins; [] clears. Mock status defaults to 200.",
|
|
259
|
+
},
|
|
260
|
+
headers: {
|
|
261
|
+
type: "object",
|
|
262
|
+
additionalProperties: { type: "string" },
|
|
263
|
+
description: "Extra request headers; {} clears.",
|
|
264
|
+
},
|
|
265
|
+
offline: { type: "boolean" },
|
|
266
|
+
latencyMs: { type: "integer", minimum: 0 },
|
|
267
|
+
downloadKbps: { type: "number", exclusiveMinimum: 0 },
|
|
268
|
+
uploadKbps: { type: "number", exclusiveMinimum: 0 },
|
|
269
|
+
reset: { type: "boolean" },
|
|
270
|
+
},
|
|
271
|
+
[],
|
|
272
|
+
),
|
|
273
|
+
},
|
|
274
|
+
handler: async (args) => {
|
|
275
|
+
const { sessionId, ...options } = args;
|
|
276
|
+
return server.browserAdapter.setNetwork(sessionId, options);
|
|
277
|
+
},
|
|
278
|
+
},
|
|
279
|
+
],
|
|
232
280
|
[
|
|
233
281
|
"get_storage",
|
|
234
282
|
{
|
|
235
283
|
definition: {
|
|
236
284
|
name: "get_storage",
|
|
237
|
-
description:
|
|
238
|
-
"Read bounded localStorage and sessionStorage entries for the attached session.",
|
|
285
|
+
description: "localStorage and sessionStorage entries.",
|
|
239
286
|
inputSchema: storageInputSchema(),
|
|
240
287
|
},
|
|
241
288
|
handler: async (args) => {
|
|
@@ -259,7 +306,7 @@ export function stateTools(server) {
|
|
|
259
306
|
definition: {
|
|
260
307
|
name: "capture_debug_report",
|
|
261
308
|
description:
|
|
262
|
-
"
|
|
309
|
+
"One bundle: page state, cookie and storage summary, recent console and network, and a screenshot.",
|
|
263
310
|
inputSchema: captureDebugReportInputSchema(
|
|
264
311
|
server.config.browserFamily,
|
|
265
312
|
),
|
|
@@ -279,7 +326,7 @@ export function stateTools(server) {
|
|
|
279
326
|
definition: {
|
|
280
327
|
name: "capture_session_snapshot",
|
|
281
328
|
description:
|
|
282
|
-
"
|
|
329
|
+
"Save page state, cookies, and web storage for restore_session_snapshot on the same origin.",
|
|
283
330
|
inputSchema: sessionSchema({}, []),
|
|
284
331
|
},
|
|
285
332
|
handler: async (args) =>
|
|
@@ -292,7 +339,7 @@ export function stateTools(server) {
|
|
|
292
339
|
definition: {
|
|
293
340
|
name: "restore_session_snapshot",
|
|
294
341
|
description:
|
|
295
|
-
"Restore
|
|
342
|
+
"Restore page-visible cookies and web storage from capture_session_snapshot, on the current origin.",
|
|
296
343
|
inputSchema: restoreSessionSnapshotInputSchema(),
|
|
297
344
|
},
|
|
298
345
|
validate: (args) => {
|
|
@@ -313,8 +360,7 @@ export function stateTools(server) {
|
|
|
313
360
|
{
|
|
314
361
|
definition: {
|
|
315
362
|
name: "get_har",
|
|
316
|
-
description:
|
|
317
|
-
"Export a bounded HAR-like summary from buffered network activity for an attached session.",
|
|
363
|
+
description: "Buffered network activity as a HAR-like summary.",
|
|
318
364
|
inputSchema: sessionWithLimitSchema(),
|
|
319
365
|
},
|
|
320
366
|
handler: async (args) =>
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { realpath, stat } from "node:fs/promises";
|
|
2
|
+
import { tmpdir } from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
|
|
5
|
+
// upload_file hands local files to a web page, so it reads only from the
|
|
6
|
+
// directories the user would expect: the server's working directory
|
|
7
|
+
// (usually the project), the system temp directory, and those listed in
|
|
8
|
+
// MCP_BROWSER_UPLOAD_DIRS. Paths are compared after resolving symlinks, so
|
|
9
|
+
// a link inside an allowed directory cannot reach outside it. The boundary
|
|
10
|
+
// is against an agent a page has talked into uploading private files; it
|
|
11
|
+
// does not stop a process that can write to the allowed directories (it
|
|
12
|
+
// could swap a file for a link after the check), since such a process can
|
|
13
|
+
// read those files itself.
|
|
14
|
+
export async function allowedUploadDirs(config) {
|
|
15
|
+
const dirs = [process.cwd(), tmpdir(), ...(config.uploadDirs ?? [])];
|
|
16
|
+
const resolved = await Promise.all(
|
|
17
|
+
dirs.map((dir) => realpath(dir).catch(() => null)),
|
|
18
|
+
);
|
|
19
|
+
return Array.from(new Set(resolved.filter(Boolean)));
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function inside(dir, file) {
|
|
23
|
+
const relative = path.relative(dir, file);
|
|
24
|
+
return (
|
|
25
|
+
relative !== "" &&
|
|
26
|
+
relative !== ".." &&
|
|
27
|
+
!relative.startsWith(`..${path.sep}`) &&
|
|
28
|
+
!path.isAbsolute(relative)
|
|
29
|
+
);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// The real paths of the files to upload; throws for a path that is not
|
|
33
|
+
// absolute, not a regular file, or outside the allowed directories.
|
|
34
|
+
export async function resolveUploadPaths(paths, allowedDirs) {
|
|
35
|
+
const resolved = [];
|
|
36
|
+
for (const file of paths) {
|
|
37
|
+
if (!path.isAbsolute(file)) {
|
|
38
|
+
throw new Error(`Upload path must be absolute: ${file}`);
|
|
39
|
+
}
|
|
40
|
+
let real;
|
|
41
|
+
try {
|
|
42
|
+
real = await realpath(file);
|
|
43
|
+
} catch {
|
|
44
|
+
throw new Error(`No file at ${file}`);
|
|
45
|
+
}
|
|
46
|
+
if (!(await stat(real)).isFile()) {
|
|
47
|
+
throw new Error(`Not a regular file: ${file}`);
|
|
48
|
+
}
|
|
49
|
+
if (!allowedDirs.some((dir) => inside(dir, real))) {
|
|
50
|
+
throw new Error(
|
|
51
|
+
`${file} is outside the directories upload_file may read (the server's working directory, the temp directory, and MCP_BROWSER_UPLOAD_DIRS): ${allowedDirs.join(", ")}`,
|
|
52
|
+
);
|
|
53
|
+
}
|
|
54
|
+
resolved.push(real);
|
|
55
|
+
}
|
|
56
|
+
return resolved;
|
|
57
|
+
}
|
|
@@ -0,0 +1,401 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import {
|
|
4
|
+
access,
|
|
5
|
+
chmod,
|
|
6
|
+
constants,
|
|
7
|
+
link,
|
|
8
|
+
lstat,
|
|
9
|
+
mkdir,
|
|
10
|
+
mkdtemp,
|
|
11
|
+
open,
|
|
12
|
+
realpath,
|
|
13
|
+
rename,
|
|
14
|
+
rm,
|
|
15
|
+
unlink,
|
|
16
|
+
writeFile,
|
|
17
|
+
} from "node:fs/promises";
|
|
18
|
+
import { createReadStream } from "node:fs";
|
|
19
|
+
import { tmpdir } from "node:os";
|
|
20
|
+
import path from "node:path";
|
|
21
|
+
import { pipeline } from "node:stream/promises";
|
|
22
|
+
|
|
23
|
+
import { SCREENSHOT_FILE_MODE } from "./screenshot-output.mjs";
|
|
24
|
+
|
|
25
|
+
// How long an encode may run before it is given up and the frames kept.
|
|
26
|
+
const ENCODE_TIMEOUT_MS = 10 * 60_000;
|
|
27
|
+
const STDERR_KEEP = 4096;
|
|
28
|
+
|
|
29
|
+
// Each frame lasts until the next one, and the last until the capture
|
|
30
|
+
// stopped, so a page that repaints rarely plays at its real pace. A frame
|
|
31
|
+
// that is not later than the one before it (a duplicate timestamp, or one
|
|
32
|
+
// delivered out of order) is left out, so every duration is positive. The
|
|
33
|
+
// last frame is listed again half a frame before the end: ffmpeg ends a
|
|
34
|
+
// stream one estimated interval after its last frame, and drops a frame at
|
|
35
|
+
// or past -t, so the copy holds the picture while -t sets the length.
|
|
36
|
+
export function frameDurations(frames, stoppedAt, fps) {
|
|
37
|
+
const kept = [];
|
|
38
|
+
for (const frame of frames) {
|
|
39
|
+
if (kept.length === 0 || frame.timestamp > kept.at(-1).timestamp) {
|
|
40
|
+
kept.push(frame);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return kept.map((frame, index) => {
|
|
44
|
+
const next = kept[index + 1];
|
|
45
|
+
const until = next ? next.timestamp : stoppedAt - 0.5 / fps;
|
|
46
|
+
return {
|
|
47
|
+
file: frame.file,
|
|
48
|
+
duration: Math.max(
|
|
49
|
+
0.001,
|
|
50
|
+
Math.round((until - frame.timestamp) * 1000) / 1000,
|
|
51
|
+
),
|
|
52
|
+
};
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// The concat demuxer's script. File names are relative to the script, so
|
|
57
|
+
// no path needs quoting. Each JPEG is read with a 1 ms timebase (the
|
|
58
|
+
// default, 1/25 s, would round every frame time to 40 ms), which needs
|
|
59
|
+
// -safe 0; the script and the frames are in the recording's own directory.
|
|
60
|
+
export function concatList(entries) {
|
|
61
|
+
const lines = ["ffconcat version 1.0"];
|
|
62
|
+
for (const entry of entries) {
|
|
63
|
+
lines.push(
|
|
64
|
+
`file ${entry.file}`,
|
|
65
|
+
"option framerate 1000",
|
|
66
|
+
`duration ${entry.duration.toFixed(3)}`,
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
if (entries.length > 0) {
|
|
70
|
+
lines.push(`file ${entries.at(-1).file}`, "option framerate 1000");
|
|
71
|
+
}
|
|
72
|
+
return `${lines.join("\n")}\n`;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function evenSize(size) {
|
|
76
|
+
return {
|
|
77
|
+
width: Math.max(2, Math.floor(size.width / 2) * 2),
|
|
78
|
+
height: Math.max(2, Math.floor(size.height / 2) * 2),
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// H.264 at a constant frame rate for exactly the capture's length, scaled
|
|
83
|
+
// to the recording's even size and to limited-range yuv420p (JPEG frames
|
|
84
|
+
// are full range) so players and browsers open it, with the index first.
|
|
85
|
+
export function ffmpegArgs({
|
|
86
|
+
listPath,
|
|
87
|
+
fps,
|
|
88
|
+
width,
|
|
89
|
+
height,
|
|
90
|
+
durationS,
|
|
91
|
+
outputPath,
|
|
92
|
+
}) {
|
|
93
|
+
return [
|
|
94
|
+
"-hide_banner",
|
|
95
|
+
"-loglevel",
|
|
96
|
+
"error",
|
|
97
|
+
"-nostdin",
|
|
98
|
+
"-y",
|
|
99
|
+
"-safe",
|
|
100
|
+
"0",
|
|
101
|
+
"-f",
|
|
102
|
+
"concat",
|
|
103
|
+
"-i",
|
|
104
|
+
listPath,
|
|
105
|
+
"-fps_mode",
|
|
106
|
+
"cfr",
|
|
107
|
+
"-r",
|
|
108
|
+
String(fps),
|
|
109
|
+
"-vf",
|
|
110
|
+
`scale=${width}:${height}:in_range=full:out_range=limited,setsar=1,format=yuv420p`,
|
|
111
|
+
"-t",
|
|
112
|
+
durationS.toFixed(3),
|
|
113
|
+
"-c:v",
|
|
114
|
+
"libx264",
|
|
115
|
+
"-preset",
|
|
116
|
+
"veryfast",
|
|
117
|
+
"-crf",
|
|
118
|
+
"23",
|
|
119
|
+
"-pix_fmt",
|
|
120
|
+
"yuv420p",
|
|
121
|
+
"-movflags",
|
|
122
|
+
"+faststart",
|
|
123
|
+
outputPath,
|
|
124
|
+
];
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function shellQuote(value) {
|
|
128
|
+
return /^[\w./:=+@%,-]+$/.test(value)
|
|
129
|
+
? value
|
|
130
|
+
: `'${value.replaceAll("'", `'\\''`)}'`;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export function formatCommand(command, args) {
|
|
134
|
+
return [command, ...args].map(shellQuote).join(" ");
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
async function isExecutable(file) {
|
|
138
|
+
return access(file, constants.X_OK).then(
|
|
139
|
+
() => true,
|
|
140
|
+
() => false,
|
|
141
|
+
);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// MCP_BROWSER_FFMPEG, else the first ffmpeg on PATH, else null.
|
|
145
|
+
export async function findFfmpeg(config = {}, env = process.env) {
|
|
146
|
+
if (config.ffmpegPath) {
|
|
147
|
+
return (await isExecutable(config.ffmpegPath)) ? config.ffmpegPath : null;
|
|
148
|
+
}
|
|
149
|
+
const names =
|
|
150
|
+
process.platform === "win32" ? ["ffmpeg.exe", "ffmpeg"] : ["ffmpeg"];
|
|
151
|
+
for (const dir of (env.PATH ?? "").split(path.delimiter).filter(Boolean)) {
|
|
152
|
+
for (const name of names) {
|
|
153
|
+
const candidate = path.join(dir, name);
|
|
154
|
+
if (await isExecutable(candidate)) {
|
|
155
|
+
return candidate;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
return null;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const encoders = new Set();
|
|
163
|
+
let exitHookInstalled = false;
|
|
164
|
+
|
|
165
|
+
// An encoder still running when the server exits is killed with it.
|
|
166
|
+
function trackEncoder(child) {
|
|
167
|
+
encoders.add(child);
|
|
168
|
+
child.once("exit", () => encoders.delete(child));
|
|
169
|
+
if (!exitHookInstalled) {
|
|
170
|
+
exitHookInstalled = true;
|
|
171
|
+
process.once("exit", () => {
|
|
172
|
+
for (const encoder of encoders) {
|
|
173
|
+
encoder.kill("SIGKILL");
|
|
174
|
+
}
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
export function runFfmpeg(command, args, { spawnFn = spawn } = {}) {
|
|
180
|
+
return new Promise((resolve) => {
|
|
181
|
+
let stderr = "";
|
|
182
|
+
let child;
|
|
183
|
+
try {
|
|
184
|
+
child = spawnFn(command, args, { stdio: ["ignore", "ignore", "pipe"] });
|
|
185
|
+
} catch (error) {
|
|
186
|
+
resolve({ ok: false, error: error.message });
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
trackEncoder(child);
|
|
190
|
+
const timer = setTimeout(() => {
|
|
191
|
+
child.kill("SIGKILL");
|
|
192
|
+
stderr += `\nffmpeg was stopped after ${ENCODE_TIMEOUT_MS / 60_000} minutes`;
|
|
193
|
+
}, ENCODE_TIMEOUT_MS);
|
|
194
|
+
child.stderr?.on("data", (chunk) => {
|
|
195
|
+
stderr = (stderr + chunk.toString()).slice(-STDERR_KEEP);
|
|
196
|
+
});
|
|
197
|
+
child.once("error", (error) => {
|
|
198
|
+
clearTimeout(timer);
|
|
199
|
+
resolve({ ok: false, error: error.message });
|
|
200
|
+
});
|
|
201
|
+
child.once("exit", (code, signal) => {
|
|
202
|
+
clearTimeout(timer);
|
|
203
|
+
if (code === 0) {
|
|
204
|
+
resolve({ ok: true });
|
|
205
|
+
} else {
|
|
206
|
+
resolve({
|
|
207
|
+
ok: false,
|
|
208
|
+
error: `ffmpeg exited with ${signal ?? code}${stderr.trim() ? `: ${stderr.trim()}` : ""}`,
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
});
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// Checked before the capture stops, so a bad path does not cost the frames.
|
|
216
|
+
export async function checkVideoPath(args) {
|
|
217
|
+
if (args.path === undefined) {
|
|
218
|
+
return;
|
|
219
|
+
}
|
|
220
|
+
if (!path.isAbsolute(args.path) || !args.path.endsWith(".mp4")) {
|
|
221
|
+
throw new Error("record_video path must be absolute and end in .mp4");
|
|
222
|
+
}
|
|
223
|
+
if (!args.overwrite) {
|
|
224
|
+
const exists = await lstat(args.path).then(
|
|
225
|
+
() => true,
|
|
226
|
+
() => false,
|
|
227
|
+
);
|
|
228
|
+
if (exists) {
|
|
229
|
+
throw new Error(
|
|
230
|
+
`${args.path} already exists; pass overwrite: true to replace it`,
|
|
231
|
+
);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
// Moves the encoded file, private already, into place like a screenshot:
|
|
237
|
+
// never over an existing file unless asked, and never through a symlink
|
|
238
|
+
// (link and rename replace a link at the path rather than following it).
|
|
239
|
+
// Across volumes the file is copied into one opened exclusively instead.
|
|
240
|
+
async function placeVideo(encoded, filePath, overwrite) {
|
|
241
|
+
await mkdir(path.dirname(filePath), { recursive: true });
|
|
242
|
+
try {
|
|
243
|
+
if (overwrite) {
|
|
244
|
+
await rename(encoded, filePath);
|
|
245
|
+
} else {
|
|
246
|
+
await link(encoded, filePath);
|
|
247
|
+
await unlink(encoded);
|
|
248
|
+
}
|
|
249
|
+
return;
|
|
250
|
+
} catch (error) {
|
|
251
|
+
if (error.code === "EEXIST") {
|
|
252
|
+
throw new Error(
|
|
253
|
+
`${filePath} already exists; pass overwrite: true to replace it`,
|
|
254
|
+
{ cause: error },
|
|
255
|
+
);
|
|
256
|
+
}
|
|
257
|
+
// Another volume, or a filesystem without hard links: copy instead.
|
|
258
|
+
if (!["EXDEV", "EPERM", "ENOTSUP", "EOPNOTSUPP"].includes(error.code)) {
|
|
259
|
+
throw error;
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
const target = overwrite ? `${filePath}.${randomUUID()}.tmp` : filePath;
|
|
263
|
+
let handle;
|
|
264
|
+
try {
|
|
265
|
+
handle = await open(target, "wx", SCREENSHOT_FILE_MODE);
|
|
266
|
+
} catch (error) {
|
|
267
|
+
if (error.code === "EEXIST") {
|
|
268
|
+
throw new Error(
|
|
269
|
+
`${filePath} already exists; pass overwrite: true to replace it`,
|
|
270
|
+
{ cause: error },
|
|
271
|
+
);
|
|
272
|
+
}
|
|
273
|
+
throw error;
|
|
274
|
+
}
|
|
275
|
+
try {
|
|
276
|
+
await pipeline(createReadStream(encoded), handle.createWriteStream());
|
|
277
|
+
if (overwrite) {
|
|
278
|
+
await rename(target, filePath);
|
|
279
|
+
}
|
|
280
|
+
} catch (error) {
|
|
281
|
+
await rm(target, { force: true });
|
|
282
|
+
throw error;
|
|
283
|
+
}
|
|
284
|
+
await unlink(encoded);
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
// Both sides are resolved through symlinks (the destination by its nearest
|
|
288
|
+
// existing ancestor), so an alias such as /private/var for /var is caught.
|
|
289
|
+
async function isInside(dir, filePath) {
|
|
290
|
+
const realDir = await realpath(dir);
|
|
291
|
+
let ancestor = path.resolve(filePath);
|
|
292
|
+
let rest = "";
|
|
293
|
+
while (true) {
|
|
294
|
+
try {
|
|
295
|
+
ancestor = await realpath(ancestor);
|
|
296
|
+
break;
|
|
297
|
+
} catch {
|
|
298
|
+
rest = path.join(path.basename(ancestor), rest);
|
|
299
|
+
const parent = path.dirname(ancestor);
|
|
300
|
+
if (parent === ancestor) {
|
|
301
|
+
break;
|
|
302
|
+
}
|
|
303
|
+
ancestor = parent;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
const relative = path.relative(realDir, path.join(ancestor, rest));
|
|
307
|
+
return (
|
|
308
|
+
relative === "" ||
|
|
309
|
+
(!relative.startsWith("..") && !path.isAbsolute(relative))
|
|
310
|
+
);
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
async function tempVideoPath() {
|
|
314
|
+
const dir = await mkdtemp(path.join(tmpdir(), "mcp-browser-dev-tools-"));
|
|
315
|
+
return path.join(dir, "video.mp4");
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
// Encodes a capture ({ dir, frames, startedAt, stoppedAt, fps, width,
|
|
319
|
+
// height, warnings }) to MP4. Without ffmpeg, or when it fails, the frames
|
|
320
|
+
// stay in their directory and the result says so and gives the command.
|
|
321
|
+
export async function encodeVideo(capture, args, config, { spawnFn } = {}) {
|
|
322
|
+
const entries = frameDurations(
|
|
323
|
+
capture.frames,
|
|
324
|
+
capture.stoppedAt,
|
|
325
|
+
capture.fps,
|
|
326
|
+
);
|
|
327
|
+
const { width, height } = evenSize(capture);
|
|
328
|
+
const listPath = path.join(capture.dir, "frames.ffconcat");
|
|
329
|
+
await writeFile(listPath, concatList(entries), {
|
|
330
|
+
mode: SCREENSHOT_FILE_MODE,
|
|
331
|
+
});
|
|
332
|
+
const encoded = path.join(capture.dir, "video.mp4");
|
|
333
|
+
const durationS = Math.max(0, capture.stoppedAt - capture.startedAt);
|
|
334
|
+
const ffmpegArguments = ffmpegArgs({
|
|
335
|
+
listPath,
|
|
336
|
+
fps: capture.fps,
|
|
337
|
+
width,
|
|
338
|
+
height,
|
|
339
|
+
durationS,
|
|
340
|
+
outputPath: encoded,
|
|
341
|
+
});
|
|
342
|
+
const summary = {
|
|
343
|
+
durationMs: Math.round(durationS * 1000),
|
|
344
|
+
frames: entries.length,
|
|
345
|
+
width,
|
|
346
|
+
height,
|
|
347
|
+
...(capture.warnings?.length ? { warnings: capture.warnings } : {}),
|
|
348
|
+
};
|
|
349
|
+
const kept = (error) => ({
|
|
350
|
+
...summary,
|
|
351
|
+
framesDir: capture.dir,
|
|
352
|
+
ffmpegCommand: formatCommand(
|
|
353
|
+
config.ffmpegPath || "ffmpeg",
|
|
354
|
+
ffmpegArguments,
|
|
355
|
+
),
|
|
356
|
+
error,
|
|
357
|
+
});
|
|
358
|
+
|
|
359
|
+
const ffmpeg = await findFfmpeg(config);
|
|
360
|
+
if (!ffmpeg) {
|
|
361
|
+
return kept(
|
|
362
|
+
config.ffmpegPath
|
|
363
|
+
? `${config.ffmpegPath} (MCP_BROWSER_FFMPEG) is not an executable; the frames are kept in framesDir and ffmpegCommand encodes them`
|
|
364
|
+
: "ffmpeg was not found on PATH (set MCP_BROWSER_FFMPEG to its path); the frames are kept in framesDir and ffmpegCommand encodes them",
|
|
365
|
+
);
|
|
366
|
+
}
|
|
367
|
+
const run = await runFfmpeg(ffmpeg, ffmpegArguments, { spawnFn });
|
|
368
|
+
if (!run.ok) {
|
|
369
|
+
await rm(encoded, { force: true });
|
|
370
|
+
return kept(
|
|
371
|
+
`${run.error}; the frames are kept in framesDir and ffmpegCommand encodes them`,
|
|
372
|
+
);
|
|
373
|
+
}
|
|
374
|
+
await chmod(encoded, SCREENSHOT_FILE_MODE);
|
|
375
|
+
|
|
376
|
+
let placed;
|
|
377
|
+
let error;
|
|
378
|
+
if (args.path === undefined) {
|
|
379
|
+
placed = await tempVideoPath();
|
|
380
|
+
await placeVideo(encoded, placed, false);
|
|
381
|
+
} else {
|
|
382
|
+
try {
|
|
383
|
+
// The frame directory is deleted below, so a video placed in it
|
|
384
|
+
// would go with it.
|
|
385
|
+
if (await isInside(capture.dir, args.path)) {
|
|
386
|
+
throw new Error(
|
|
387
|
+
"the path is inside the frame directory, which is deleted after encoding",
|
|
388
|
+
);
|
|
389
|
+
}
|
|
390
|
+
await placeVideo(encoded, args.path, args.overwrite);
|
|
391
|
+
placed = args.path;
|
|
392
|
+
} catch (placeError) {
|
|
393
|
+
// The video is not lost: it goes to a temp file instead.
|
|
394
|
+
placed = await tempVideoPath();
|
|
395
|
+
await placeVideo(encoded, placed, false);
|
|
396
|
+
error = `Could not write ${args.path} (${placeError.message}); the video was saved to a temp file instead`;
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
await rm(capture.dir, { recursive: true, force: true });
|
|
400
|
+
return { path: placed, ...summary, ...(error ? { error } : {}) };
|
|
401
|
+
}
|