@clipy/cli 0.15.0 → 0.16.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 +53 -3
- package/dist/cdpClient.js +277 -0
- package/dist/cdpDiagnostics.js +644 -0
- package/dist/chromeExtensionCapture.js +197 -56
- package/dist/chromeForClipy.js +588 -111
- package/dist/index.js +1187 -125
- package/dist/linuxScreen.js +655 -0
- package/dist/macBridge.js +11 -1
- package/dist/processProbe.js +265 -0
- package/dist/skill.js +55 -21
- package/package.json +4 -4
|
@@ -0,0 +1,644 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Browser bug evidence for recordings Clipy drives itself (`clipy session`
|
|
3
|
+
* with the headless web source): the same v2 browser-diagnostics sidecar the
|
|
4
|
+
* Chrome extension uploads, built from Playwright's page events instead of a
|
|
5
|
+
* page-world script. This is parity with `jam record --cdp`: an agent's
|
|
6
|
+
* verification run carries console errors, failed requests and socket
|
|
7
|
+
* activity alongside the video, readable through the same Evidence tab, AREC
|
|
8
|
+
* section and `get_browser_diagnostics` tool.
|
|
9
|
+
*
|
|
10
|
+
* Source is `cdp`: the browser reported it, page code did not get a say in
|
|
11
|
+
* what was recorded (page-authored text inside it is still untrusted).
|
|
12
|
+
*
|
|
13
|
+
* Privacy: the default tier never reads headers or bodies. With
|
|
14
|
+
* `--network-detail`, cookie and authorization headers are dropped here,
|
|
15
|
+
* before anything leaves the machine, and the server redacts headers, bodies
|
|
16
|
+
* and messages again at ingest exactly as it does for the extension.
|
|
17
|
+
*/
|
|
18
|
+
/** Runs in the page. A string, because the CLI builds without DOM types. */
|
|
19
|
+
const ENVIRONMENT_PROBE = `(() => {
|
|
20
|
+
const c = navigator.connection || {};
|
|
21
|
+
return {
|
|
22
|
+
page_url: location.href,
|
|
23
|
+
platform: navigator.platform || null,
|
|
24
|
+
language: navigator.language || null,
|
|
25
|
+
viewport_width: innerWidth,
|
|
26
|
+
viewport_height: innerHeight,
|
|
27
|
+
device_pixel_ratio: devicePixelRatio || null,
|
|
28
|
+
timezone_offset_minutes: new Date().getTimezoneOffset(),
|
|
29
|
+
user_agent: navigator.userAgent,
|
|
30
|
+
screen_width: screen.width,
|
|
31
|
+
screen_height: screen.height,
|
|
32
|
+
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone || null,
|
|
33
|
+
connection_type: c.effectiveType || null,
|
|
34
|
+
downlink_mbps: typeof c.downlink === "number" ? c.downlink : null,
|
|
35
|
+
rtt_ms: typeof c.rtt === "number" ? c.rtt : null,
|
|
36
|
+
};
|
|
37
|
+
})()`;
|
|
38
|
+
const MAX_EVENTS = 2_000;
|
|
39
|
+
const MAX_BODY_BYTES = 1024 * 1024;
|
|
40
|
+
const MAX_BODY_CHARS = 16_384;
|
|
41
|
+
const MAX_REQUEST_BODY_CHARS = 8_192;
|
|
42
|
+
const MAX_FRAME_CHARS = 2_048;
|
|
43
|
+
const MAX_FRAMES_PER_SOCKET = 200;
|
|
44
|
+
/** Never leave the machine, whatever the policy. */
|
|
45
|
+
const WITHHELD_HEADERS = new Set([
|
|
46
|
+
"authorization",
|
|
47
|
+
"proxy-authorization",
|
|
48
|
+
"cookie",
|
|
49
|
+
"set-cookie",
|
|
50
|
+
"x-api-key",
|
|
51
|
+
"x-auth-token",
|
|
52
|
+
"x-csrf-token",
|
|
53
|
+
"x-xsrf-token",
|
|
54
|
+
]);
|
|
55
|
+
const DEFAULT_EXCLUDED_ORIGINS = [
|
|
56
|
+
"accounts.google.com",
|
|
57
|
+
"securetoken.googleapis.com",
|
|
58
|
+
"identitytoolkit.googleapis.com",
|
|
59
|
+
"login.microsoftonline.com",
|
|
60
|
+
"login.live.com",
|
|
61
|
+
"*.okta.com",
|
|
62
|
+
"*.auth0.com",
|
|
63
|
+
"*.onelogin.com",
|
|
64
|
+
"*.duosecurity.com",
|
|
65
|
+
"appleid.apple.com",
|
|
66
|
+
];
|
|
67
|
+
const CONSOLE_LEVEL = {
|
|
68
|
+
error: { level: "error" },
|
|
69
|
+
warning: { level: "warn" },
|
|
70
|
+
info: { level: "info" },
|
|
71
|
+
log: { level: "log" },
|
|
72
|
+
debug: { level: "debug" },
|
|
73
|
+
trace: { level: "log", method: "trace" },
|
|
74
|
+
table: { level: "log", method: "table" },
|
|
75
|
+
dir: { level: "log", method: "dir" },
|
|
76
|
+
dirxml: { level: "log", method: "dir" },
|
|
77
|
+
count: { level: "log", method: "count" },
|
|
78
|
+
assert: { level: "error", method: "assert" },
|
|
79
|
+
};
|
|
80
|
+
function excludedHost(url) {
|
|
81
|
+
let host;
|
|
82
|
+
try {
|
|
83
|
+
host = new URL(url.replace(/^ws/i, "http")).hostname.toLowerCase();
|
|
84
|
+
}
|
|
85
|
+
catch {
|
|
86
|
+
return false;
|
|
87
|
+
}
|
|
88
|
+
return DEFAULT_EXCLUDED_ORIGINS.some((pattern) => pattern.startsWith("*.") ? host === pattern.slice(2) || host.endsWith(pattern.slice(1)) : host === pattern);
|
|
89
|
+
}
|
|
90
|
+
function withheldHeaders(headers) {
|
|
91
|
+
if (!headers)
|
|
92
|
+
return undefined;
|
|
93
|
+
const out = {};
|
|
94
|
+
for (const [name, value] of Object.entries(headers)) {
|
|
95
|
+
const key = name.toLowerCase();
|
|
96
|
+
if (key.startsWith(":"))
|
|
97
|
+
continue; // HTTP/2 pseudo-headers
|
|
98
|
+
out[key] = WITHHELD_HEADERS.has(key) ? "[redacted]" : value;
|
|
99
|
+
}
|
|
100
|
+
return Object.keys(out).length ? out : undefined;
|
|
101
|
+
}
|
|
102
|
+
function isTextual(mime) {
|
|
103
|
+
return (!mime ||
|
|
104
|
+
/^text\//.test(mime) ||
|
|
105
|
+
/(json|xml|javascript|ecmascript|graphql|x-www-form-urlencoded|csv|yaml|html)/.test(mime));
|
|
106
|
+
}
|
|
107
|
+
function graphqlOf(url, body) {
|
|
108
|
+
try {
|
|
109
|
+
let candidate = null;
|
|
110
|
+
if (body && /^\s*[{[]/.test(body) && body.length < 512 * 1024)
|
|
111
|
+
candidate = JSON.parse(body);
|
|
112
|
+
else if (/[?&]query=/.test(url)) {
|
|
113
|
+
const params = new URL(url).searchParams;
|
|
114
|
+
candidate = { query: params.get("query"), operationName: params.get("operationName") };
|
|
115
|
+
}
|
|
116
|
+
const first = (Array.isArray(candidate) ? candidate[0] : candidate);
|
|
117
|
+
if (!first || typeof first !== "object")
|
|
118
|
+
return null;
|
|
119
|
+
const hasQuery = typeof first.query === "string";
|
|
120
|
+
if (!hasQuery && !first.extensions?.persistedQuery)
|
|
121
|
+
return null;
|
|
122
|
+
const declared = hasQuery ? /^\s*(query|mutation|subscription)\b\s*([A-Za-z_][A-Za-z0-9_]*)?/.exec(first.query) : null;
|
|
123
|
+
const operation = (typeof first.operationName === "string" && first.operationName) || declared?.[2];
|
|
124
|
+
return {
|
|
125
|
+
...(operation ? { operation } : {}),
|
|
126
|
+
...(declared?.[1] ? { operation_type: declared[1] } : {}),
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
catch {
|
|
130
|
+
return null;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
function graphqlErrors(text) {
|
|
134
|
+
try {
|
|
135
|
+
const parsed = JSON.parse(text);
|
|
136
|
+
let errors = 0;
|
|
137
|
+
let first;
|
|
138
|
+
for (const item of Array.isArray(parsed) ? parsed : [parsed]) {
|
|
139
|
+
const list = item?.errors;
|
|
140
|
+
if (Array.isArray(list) && list.length) {
|
|
141
|
+
errors += list.length;
|
|
142
|
+
const message = list[0]?.message;
|
|
143
|
+
first ??= typeof message === "string" ? message.slice(0, 500) : undefined;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
return { errors, ...(first ? { first_error: first } : {}) };
|
|
147
|
+
}
|
|
148
|
+
catch {
|
|
149
|
+
return null;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
function span(a, b) {
|
|
153
|
+
return a >= 0 && b >= a ? Math.round(b - a) : undefined;
|
|
154
|
+
}
|
|
155
|
+
/** The server's sidecar limits (lib/browserDiagnostics.ts), with headroom for
|
|
156
|
+
* the redaction markers its normalizer may add. */
|
|
157
|
+
const SIDECAR_BUDGET_BYTES = Math.floor(2 * 1024 * 1024 * 0.9);
|
|
158
|
+
const SIDECAR_FULL_DETAIL_BUDGET_BYTES = Math.floor(6 * 1024 * 1024 * 0.9);
|
|
159
|
+
/** Same order as the extension's trim: bodies and socket frames of successful
|
|
160
|
+
* traffic first, then all of them, then the oldest events. A request without
|
|
161
|
+
* its body is still evidence; an over-budget sidecar is rejected outright. */
|
|
162
|
+
export function trimToBudget(sidecar) {
|
|
163
|
+
const budget = sidecar.policy.networkDetail === "full" ? SIDECAR_FULL_DETAIL_BUDGET_BYTES : SIDECAR_BUDGET_BYTES;
|
|
164
|
+
const sizeOf = (value) => Buffer.byteLength(JSON.stringify(value));
|
|
165
|
+
if (sizeOf(sidecar) <= budget)
|
|
166
|
+
return sidecar;
|
|
167
|
+
const events = sidecar.events.slice();
|
|
168
|
+
let trimmed = { ...sidecar, events };
|
|
169
|
+
for (const keepFailures of [true, false]) {
|
|
170
|
+
for (let index = 0; index < events.length; index++) {
|
|
171
|
+
const event = events[index];
|
|
172
|
+
const failed = event.outcome !== undefined && event.outcome !== "success";
|
|
173
|
+
if (event.kind === "network" && (event.request_body !== undefined || event.response_body !== undefined)) {
|
|
174
|
+
if (keepFailures && failed)
|
|
175
|
+
continue;
|
|
176
|
+
const { request_body, response_body, ...rest } = event;
|
|
177
|
+
events[index] = {
|
|
178
|
+
...rest,
|
|
179
|
+
body_omitted: {
|
|
180
|
+
...(request_body !== undefined ? { request: "too_large" } : {}),
|
|
181
|
+
...(response_body !== undefined ? { response: "too_large" } : {}),
|
|
182
|
+
},
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
else if (event.kind === "stream" && event.data !== undefined && (!keepFailures || event.action === "message")) {
|
|
186
|
+
const { data: _data, ...rest } = event;
|
|
187
|
+
events[index] = rest;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
trimmed = { ...sidecar, events: events.slice() };
|
|
191
|
+
if (sizeOf(trimmed) <= budget)
|
|
192
|
+
return trimmed;
|
|
193
|
+
}
|
|
194
|
+
while (trimmed.events.length > 0 && sizeOf(trimmed) > budget) {
|
|
195
|
+
const drop = Math.max(1, Math.ceil(trimmed.events.length / 10));
|
|
196
|
+
trimmed = { ...trimmed, events: trimmed.events.slice(drop), dropped_events: trimmed.dropped_events + drop };
|
|
197
|
+
}
|
|
198
|
+
return trimmed;
|
|
199
|
+
}
|
|
200
|
+
export function attachCdpDiagnostics(page, opts) {
|
|
201
|
+
const events = [];
|
|
202
|
+
let dropped = 0;
|
|
203
|
+
let environment = null;
|
|
204
|
+
let firstNavigation = true;
|
|
205
|
+
// While the top-level page is an excluded site (a sign-in provider), nothing
|
|
206
|
+
// is recorded at all: its console, errors and requests to other hosts carry
|
|
207
|
+
// no page origin the server could filter them by afterwards.
|
|
208
|
+
let pageExcluded = (() => {
|
|
209
|
+
try {
|
|
210
|
+
const url = page.url?.() ?? "";
|
|
211
|
+
return /^https?:/i.test(url) && excludedHost(url);
|
|
212
|
+
}
|
|
213
|
+
catch {
|
|
214
|
+
return false;
|
|
215
|
+
}
|
|
216
|
+
})();
|
|
217
|
+
let socketCounter = 0;
|
|
218
|
+
const pending = [];
|
|
219
|
+
const all = opts.level === "all";
|
|
220
|
+
// `startedOnAllowedPage`: a request decides by the page that started it,
|
|
221
|
+
// not by the page that is current when it finishes.
|
|
222
|
+
const push = (event, atMs = Date.now(), startedOnAllowedPage = false) => {
|
|
223
|
+
if (pageExcluded && !startedOnAllowedPage)
|
|
224
|
+
return;
|
|
225
|
+
if (events.length >= MAX_EVENTS) {
|
|
226
|
+
dropped++;
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
// Anything before the recording's t=0 (the first page load can land just
|
|
230
|
+
// before it) is pinned to 0 rather than given an epoch-sized offset.
|
|
231
|
+
const start = opts.recordStart();
|
|
232
|
+
events.push({ ...event, time_ms: start > 0 ? Math.max(0, atMs - start) : 0 });
|
|
233
|
+
};
|
|
234
|
+
const guard = (fn) => {
|
|
235
|
+
try {
|
|
236
|
+
const result = fn();
|
|
237
|
+
if (result instanceof Promise)
|
|
238
|
+
pending.push(result.catch(() => undefined));
|
|
239
|
+
}
|
|
240
|
+
catch {
|
|
241
|
+
// Evidence capture must never take the recording down.
|
|
242
|
+
}
|
|
243
|
+
};
|
|
244
|
+
if (opts.level === "off")
|
|
245
|
+
return { sidecar: () => null, ready: Promise.resolve(), settle: async () => undefined };
|
|
246
|
+
page.on("console", ((msg) => guard(() => {
|
|
247
|
+
const mapped = CONSOLE_LEVEL[msg.type()] ?? { level: "log" };
|
|
248
|
+
if (!all && mapped.level !== "error" && mapped.level !== "warn")
|
|
249
|
+
return;
|
|
250
|
+
const location = msg.location?.();
|
|
251
|
+
const where = location?.url ? `at ${location.url}:${(location.lineNumber ?? 0) + 1}:${(location.columnNumber ?? 0) + 1}` : undefined;
|
|
252
|
+
push({
|
|
253
|
+
kind: "console",
|
|
254
|
+
level: mapped.level,
|
|
255
|
+
message: msg.text() || "(empty)",
|
|
256
|
+
...(mapped.method ? { method: mapped.method } : {}),
|
|
257
|
+
...(where && (mapped.level === "error" || mapped.level === "warn" || mapped.method === "trace") ? { stack: where } : {}),
|
|
258
|
+
});
|
|
259
|
+
})));
|
|
260
|
+
page.on("pageerror", ((error) => guard(() => {
|
|
261
|
+
push({ kind: "error", message: `${error.name}: ${error.message}`, ...(error.stack ? { stack: error.stack } : {}) });
|
|
262
|
+
})));
|
|
263
|
+
page.on("framenavigated", ((frame) => guard(() => {
|
|
264
|
+
if (frame.parentFrame() !== null)
|
|
265
|
+
return;
|
|
266
|
+
const url = frame.url();
|
|
267
|
+
pageExcluded = /^https?:/i.test(url) && excludedHost(url);
|
|
268
|
+
if (!/^https?:/i.test(url) || pageExcluded)
|
|
269
|
+
return;
|
|
270
|
+
push({ kind: "navigation", navigation: firstNavigation ? "initial" : "push_state", url });
|
|
271
|
+
if (firstNavigation) {
|
|
272
|
+
firstNavigation = false;
|
|
273
|
+
pending.push(page
|
|
274
|
+
.evaluate(ENVIRONMENT_PROBE)
|
|
275
|
+
.then((env) => {
|
|
276
|
+
const ua = String(env.user_agent ?? "");
|
|
277
|
+
const chrome = /(?:HeadlessChrome|Chrome)\/([\d.]+)/.exec(ua);
|
|
278
|
+
environment = {
|
|
279
|
+
...env,
|
|
280
|
+
browser_name: chrome ? (ua.includes("HeadlessChrome") ? "Chrome (headless)" : "Chrome") : null,
|
|
281
|
+
browser_version: chrome?.[1] ?? null,
|
|
282
|
+
os_name: process.platform === "darwin" ? "macOS" : process.platform === "win32" ? "Windows" : "Linux",
|
|
283
|
+
};
|
|
284
|
+
})
|
|
285
|
+
.catch(() => undefined));
|
|
286
|
+
}
|
|
287
|
+
})));
|
|
288
|
+
// A document loaded into the tab's main frame (not an iframe's).
|
|
289
|
+
const isTopLevelDocument = (request) => {
|
|
290
|
+
if (request.resourceType() !== "document")
|
|
291
|
+
return false;
|
|
292
|
+
try {
|
|
293
|
+
const frame = request.frame?.();
|
|
294
|
+
return !!frame && frame.parentFrame() === null;
|
|
295
|
+
}
|
|
296
|
+
catch {
|
|
297
|
+
return false;
|
|
298
|
+
}
|
|
299
|
+
};
|
|
300
|
+
// Whether the top-level page was an excluded site when each request began.
|
|
301
|
+
const startedExcluded = new WeakMap();
|
|
302
|
+
page.on("request", ((request) => guard(() => void startedExcluded.set(request, pageExcluded))));
|
|
303
|
+
const onRequestDone = (request, failed) => guard(async () => {
|
|
304
|
+
const finishedAt = Date.now();
|
|
305
|
+
const url = request.url();
|
|
306
|
+
if (!/^https?:/i.test(url) || excludedHost(url))
|
|
307
|
+
return;
|
|
308
|
+
const type = request.resourceType();
|
|
309
|
+
if (type === "websocket")
|
|
310
|
+
return;
|
|
311
|
+
// A request started on an excluded page is never read, even if it
|
|
312
|
+
// finishes after the tab has moved on; one started on an allowed page
|
|
313
|
+
// is kept even if it finishes after the tab reached an excluded one.
|
|
314
|
+
// A top-level navigation is judged by its own address (checked above):
|
|
315
|
+
// it is the tab leaving the excluded page. A frame's document is part of
|
|
316
|
+
// the page that holds it, so it keeps that page's exclusion.
|
|
317
|
+
const begunExcluded = isTopLevelDocument(request) ? false : startedExcluded.get(request) ?? pageExcluded;
|
|
318
|
+
if (begunExcluded)
|
|
319
|
+
return;
|
|
320
|
+
// A failed request can still have a response: Chrome reports a 404
|
|
321
|
+
// script as net::ERR_ABORTED after the 404 arrived. The status wins.
|
|
322
|
+
const response = await request.response().catch(() => null);
|
|
323
|
+
const status = response ? response.status() : null;
|
|
324
|
+
const timing = request.timing();
|
|
325
|
+
const duration = timing.responseEnd >= 0 ? timing.responseEnd : Math.max(0, finishedAt - timing.startTime);
|
|
326
|
+
const transport = type === "fetch" || type === "xhr" ? type : type === "document" ? "document" : "resource";
|
|
327
|
+
// Metadata mode never materializes what the page submitted. An address
|
|
328
|
+
// naming GraphQL still marks the request as one, without an operation
|
|
329
|
+
// name, so its reply is checked for errors.
|
|
330
|
+
const postData = opts.networkDetail ? request.postData() : null;
|
|
331
|
+
const graphql = transport === "fetch" || transport === "xhr"
|
|
332
|
+
? graphqlOf(url, postData) ?? (/graphql/i.test(url) ? {} : null)
|
|
333
|
+
: null;
|
|
334
|
+
const failure = request.failure();
|
|
335
|
+
const aborted = failed && /ERR_ABORTED/.test(failure?.errorText ?? "");
|
|
336
|
+
let outcome = status !== null && status >= 400
|
|
337
|
+
? "http_error"
|
|
338
|
+
: failed
|
|
339
|
+
? aborted
|
|
340
|
+
? "aborted"
|
|
341
|
+
: "network_error"
|
|
342
|
+
: "success";
|
|
343
|
+
// The header map is full-detail evidence. Metadata reads only the two
|
|
344
|
+
// values it needs: the content type it reports, and the length that
|
|
345
|
+
// keeps an oversized body from being read.
|
|
346
|
+
const headerOf = async (name) => {
|
|
347
|
+
if (!response)
|
|
348
|
+
return undefined;
|
|
349
|
+
if (response.headerValue)
|
|
350
|
+
return (await response.headerValue(name).catch(() => null)) ?? undefined;
|
|
351
|
+
return opts.networkDetail ? response.headers()[name] : undefined;
|
|
352
|
+
};
|
|
353
|
+
const contentType = await headerOf("content-type");
|
|
354
|
+
const contentLength = await headerOf("content-length");
|
|
355
|
+
const mime = (contentType ?? "").split(";")[0].trim().toLowerCase() || null;
|
|
356
|
+
const readBody = response &&
|
|
357
|
+
status !== null &&
|
|
358
|
+
!(status >= 300 && status < 400) &&
|
|
359
|
+
isTextual(mime) &&
|
|
360
|
+
mime !== "text/event-stream" &&
|
|
361
|
+
// Failures-only capture never reads a successful body for its own
|
|
362
|
+
// sake; only the GraphQL check may look at one.
|
|
363
|
+
((opts.networkDetail && (all || outcome !== "success")) || (graphql && /json/.test(mime ?? "json")));
|
|
364
|
+
let bodyText;
|
|
365
|
+
let bodySize;
|
|
366
|
+
let bodyOmitted;
|
|
367
|
+
// response.body() buffers the whole payload, so it is only called once
|
|
368
|
+
// the size is known to fit: the declared length, or else the size the
|
|
369
|
+
// browser received. A body whose size cannot be known is not read.
|
|
370
|
+
let knownSize = contentLength !== undefined && Number.isFinite(Number(contentLength)) ? Number(contentLength) : undefined;
|
|
371
|
+
if (readBody && knownSize === undefined) {
|
|
372
|
+
const sizes = await request.sizes?.().catch(() => null);
|
|
373
|
+
if (sizes && Number.isFinite(sizes.responseBodySize) && sizes.responseBodySize >= 0)
|
|
374
|
+
knownSize = sizes.responseBodySize;
|
|
375
|
+
}
|
|
376
|
+
if (readBody && knownSize === undefined) {
|
|
377
|
+
bodyOmitted = "unreadable";
|
|
378
|
+
if (graphql && !all && outcome === "success")
|
|
379
|
+
dropped++;
|
|
380
|
+
}
|
|
381
|
+
else if (readBody && knownSize !== undefined && knownSize > MAX_BODY_BYTES) {
|
|
382
|
+
// Never materialize a body larger than the cap just to cut it.
|
|
383
|
+
bodySize = knownSize;
|
|
384
|
+
bodyOmitted = "too_large";
|
|
385
|
+
// A GraphQL reply too large to check for errors[] would pass as a
|
|
386
|
+
// success and vanish under failures-only capture: a capture gap.
|
|
387
|
+
if (graphql && !all && outcome === "success")
|
|
388
|
+
dropped++;
|
|
389
|
+
}
|
|
390
|
+
else if (readBody) {
|
|
391
|
+
const body = await response.body().catch(() => null);
|
|
392
|
+
if (body) {
|
|
393
|
+
bodySize = body.length;
|
|
394
|
+
bodyText = body.subarray(0, MAX_BODY_BYTES).toString("utf8");
|
|
395
|
+
}
|
|
396
|
+
else {
|
|
397
|
+
bodyOmitted = "unreadable";
|
|
398
|
+
// The GraphQL check could not run: a gap, not a silent success.
|
|
399
|
+
if (graphql && !all && outcome === "success")
|
|
400
|
+
dropped++;
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
let graphqlSummary = graphql;
|
|
404
|
+
if (graphql && bodyText) {
|
|
405
|
+
const errors = graphqlErrors(bodyText);
|
|
406
|
+
if (errors && errors.errors > 0) {
|
|
407
|
+
graphqlSummary = { ...graphql, ...errors };
|
|
408
|
+
if (outcome === "success")
|
|
409
|
+
outcome = "graphql_error";
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
if (!all && outcome === "success")
|
|
413
|
+
return;
|
|
414
|
+
const detail = {};
|
|
415
|
+
if (opts.networkDetail) {
|
|
416
|
+
detail.full_url = url;
|
|
417
|
+
const requestHeaders = withheldHeaders(await request.allHeaders?.().catch(() => undefined));
|
|
418
|
+
const responseHeaders = withheldHeaders(response ? await (response.allHeaders?.() ?? Promise.resolve(response.headers())).catch(() => response.headers()) : undefined);
|
|
419
|
+
if (requestHeaders)
|
|
420
|
+
detail.request_headers = requestHeaders;
|
|
421
|
+
if (responseHeaders)
|
|
422
|
+
detail.response_headers = responseHeaders;
|
|
423
|
+
if (postData)
|
|
424
|
+
detail.request_body = postData.slice(0, MAX_REQUEST_BODY_CHARS * 4);
|
|
425
|
+
if (bodyText)
|
|
426
|
+
detail.response_body = bodyText.slice(0, MAX_BODY_CHARS * 4);
|
|
427
|
+
else if (bodyOmitted)
|
|
428
|
+
detail.body_omitted = { response: bodyOmitted };
|
|
429
|
+
else if (response && !isTextual(mime))
|
|
430
|
+
detail.body_omitted = { response: "binary" };
|
|
431
|
+
else if (mime === "text/event-stream")
|
|
432
|
+
detail.body_omitted = { response: "streaming" };
|
|
433
|
+
}
|
|
434
|
+
push({
|
|
435
|
+
kind: "network",
|
|
436
|
+
transport,
|
|
437
|
+
method: request.method(),
|
|
438
|
+
url,
|
|
439
|
+
status,
|
|
440
|
+
duration_ms: Math.max(0, Math.round(duration)),
|
|
441
|
+
outcome,
|
|
442
|
+
...(failure && !aborted && status === null ? { error: failure.errorText } : {}),
|
|
443
|
+
...(transport === "resource" || transport === "document" ? { resource_type: type } : {}),
|
|
444
|
+
...(mime ? { response_type: mime } : {}),
|
|
445
|
+
...(bodySize !== undefined ? { response_size: bodySize } : {}),
|
|
446
|
+
...(postData ? { request_body_size: Buffer.byteLength(postData) } : {}),
|
|
447
|
+
...(graphqlSummary && Object.keys(graphqlSummary).length ? { graphql: graphqlSummary } : {}),
|
|
448
|
+
timing: {
|
|
449
|
+
...(span(timing.domainLookupStart, timing.domainLookupEnd) ? { dns_ms: span(timing.domainLookupStart, timing.domainLookupEnd) } : {}),
|
|
450
|
+
...(span(timing.connectStart, timing.connectEnd) ? { connect_ms: span(timing.connectStart, timing.connectEnd) } : {}),
|
|
451
|
+
...(span(timing.requestStart, timing.responseStart) !== undefined ? { ttfb_ms: span(timing.requestStart, timing.responseStart) } : {}),
|
|
452
|
+
...(span(timing.responseStart, timing.responseEnd) !== undefined ? { download_ms: span(timing.responseStart, timing.responseEnd) } : {}),
|
|
453
|
+
},
|
|
454
|
+
...detail,
|
|
455
|
+
}, finishedAt, true);
|
|
456
|
+
});
|
|
457
|
+
page.on("requestfinished", ((request) => onRequestDone(request, false)));
|
|
458
|
+
page.on("requestfailed", ((request) => onRequestDone(request, true)));
|
|
459
|
+
const eventSources = new Map();
|
|
460
|
+
let sseCounter = 0;
|
|
461
|
+
const sseClose = (state, extra = {}) => ({
|
|
462
|
+
kind: "stream",
|
|
463
|
+
protocol: "eventsource",
|
|
464
|
+
connection: state.connection,
|
|
465
|
+
action: "close",
|
|
466
|
+
url: state.url,
|
|
467
|
+
messages_received: state.messages_received,
|
|
468
|
+
bytes_received: state.bytes_received,
|
|
469
|
+
...extra,
|
|
470
|
+
});
|
|
471
|
+
const ready = (async () => {
|
|
472
|
+
const context = page.context?.();
|
|
473
|
+
if (!context?.newCDPSession)
|
|
474
|
+
return;
|
|
475
|
+
const session = await context.newCDPSession(page);
|
|
476
|
+
session.on("Network.requestWillBeSent", ((p) => guard(() => {
|
|
477
|
+
const url = p.request?.url;
|
|
478
|
+
if (p.type !== "EventSource" || !url || excludedHost(url) || pageExcluded)
|
|
479
|
+
return;
|
|
480
|
+
const state = { connection: `sse-${++sseCounter}`, url, messages_received: 0, bytes_received: 0, frames: 0 };
|
|
481
|
+
eventSources.set(p.requestId, state);
|
|
482
|
+
if (all)
|
|
483
|
+
push({ kind: "stream", protocol: "eventsource", connection: state.connection, action: "open", url });
|
|
484
|
+
})));
|
|
485
|
+
session.on("Network.eventSourceMessageReceived", ((p) => guard(() => {
|
|
486
|
+
const state = eventSources.get(p.requestId);
|
|
487
|
+
if (!state)
|
|
488
|
+
return;
|
|
489
|
+
const data = String(p.data ?? "");
|
|
490
|
+
const size = Buffer.byteLength(data);
|
|
491
|
+
state.messages_received++;
|
|
492
|
+
state.bytes_received += size;
|
|
493
|
+
if (!opts.networkDetail)
|
|
494
|
+
return;
|
|
495
|
+
if (state.frames >= MAX_FRAMES_PER_SOCKET) {
|
|
496
|
+
dropped++;
|
|
497
|
+
return;
|
|
498
|
+
}
|
|
499
|
+
state.frames++;
|
|
500
|
+
push({
|
|
501
|
+
kind: "stream",
|
|
502
|
+
protocol: "eventsource",
|
|
503
|
+
connection: state.connection,
|
|
504
|
+
action: "message",
|
|
505
|
+
direction: "received",
|
|
506
|
+
url: state.url,
|
|
507
|
+
size,
|
|
508
|
+
data: data.slice(0, MAX_FRAME_CHARS * 2),
|
|
509
|
+
});
|
|
510
|
+
})));
|
|
511
|
+
session.on("Network.loadingFailed", ((p) => guard(() => {
|
|
512
|
+
const state = eventSources.get(p.requestId);
|
|
513
|
+
if (!state)
|
|
514
|
+
return;
|
|
515
|
+
eventSources.delete(p.requestId);
|
|
516
|
+
// The page calling close() cancels the request; that is not a failure.
|
|
517
|
+
if (!p.canceled) {
|
|
518
|
+
// Totals ride on the error too: failures-only capture keeps this
|
|
519
|
+
// row and drops the close.
|
|
520
|
+
push({
|
|
521
|
+
kind: "stream",
|
|
522
|
+
protocol: "eventsource",
|
|
523
|
+
connection: state.connection,
|
|
524
|
+
action: "error",
|
|
525
|
+
url: state.url,
|
|
526
|
+
reason: String(p.errorText ?? "stream failed").slice(0, 300),
|
|
527
|
+
messages_received: state.messages_received,
|
|
528
|
+
bytes_received: state.bytes_received,
|
|
529
|
+
});
|
|
530
|
+
}
|
|
531
|
+
push(sseClose(state));
|
|
532
|
+
})));
|
|
533
|
+
session.on("Network.loadingFinished", ((p) => guard(() => {
|
|
534
|
+
const state = eventSources.get(p.requestId);
|
|
535
|
+
if (!state)
|
|
536
|
+
return;
|
|
537
|
+
eventSources.delete(p.requestId);
|
|
538
|
+
push(sseClose(state));
|
|
539
|
+
})));
|
|
540
|
+
await session.send("Network.enable");
|
|
541
|
+
})().catch(() => undefined);
|
|
542
|
+
// WebSockets still open at the snapshot get their totals there too.
|
|
543
|
+
const openSockets = new Map();
|
|
544
|
+
page.on("websocket", ((socket) => guard(() => {
|
|
545
|
+
const url = socket.url();
|
|
546
|
+
if (excludedHost(url) || pageExcluded)
|
|
547
|
+
return;
|
|
548
|
+
const connection = `ws-${++socketCounter}`;
|
|
549
|
+
const totals = { messages_sent: 0, messages_received: 0, bytes_sent: 0, bytes_received: 0 };
|
|
550
|
+
let frames = 0;
|
|
551
|
+
openSockets.set(connection, { url, totals });
|
|
552
|
+
if (all)
|
|
553
|
+
push({ kind: "stream", protocol: "websocket", connection, action: "open", url });
|
|
554
|
+
const frame = (direction) => ((data) => guard(() => {
|
|
555
|
+
const size = typeof data.payload === "string" ? Buffer.byteLength(data.payload) : data.payload.length;
|
|
556
|
+
if (direction === "sent") {
|
|
557
|
+
totals.messages_sent++;
|
|
558
|
+
totals.bytes_sent += size;
|
|
559
|
+
}
|
|
560
|
+
else {
|
|
561
|
+
totals.messages_received++;
|
|
562
|
+
totals.bytes_received += size;
|
|
563
|
+
}
|
|
564
|
+
if (!opts.networkDetail)
|
|
565
|
+
return;
|
|
566
|
+
if (frames >= MAX_FRAMES_PER_SOCKET) {
|
|
567
|
+
dropped++;
|
|
568
|
+
return;
|
|
569
|
+
}
|
|
570
|
+
frames++;
|
|
571
|
+
push({
|
|
572
|
+
kind: "stream",
|
|
573
|
+
protocol: "websocket",
|
|
574
|
+
connection,
|
|
575
|
+
action: "message",
|
|
576
|
+
url,
|
|
577
|
+
direction,
|
|
578
|
+
size,
|
|
579
|
+
data: typeof data.payload === "string" ? data.payload.slice(0, MAX_FRAME_CHARS * 2) : `[binary ${size} bytes]`,
|
|
580
|
+
});
|
|
581
|
+
}));
|
|
582
|
+
socket.on("framesent", frame("sent"));
|
|
583
|
+
socket.on("framereceived", frame("received"));
|
|
584
|
+
socket.on("socketerror", ((error) =>
|
|
585
|
+
// Totals ride on the error: failures-only capture keeps it and drops
|
|
586
|
+
// the code-less close Playwright reports after it.
|
|
587
|
+
guard(() => push({ kind: "stream", protocol: "websocket", connection, action: "error", url, reason: String(error).slice(0, 300), ...totals }))));
|
|
588
|
+
socket.on("close", (() => guard(() => {
|
|
589
|
+
openSockets.delete(connection);
|
|
590
|
+
push({ kind: "stream", protocol: "websocket", connection, action: "close", url, ...totals });
|
|
591
|
+
})));
|
|
592
|
+
})));
|
|
593
|
+
return {
|
|
594
|
+
sidecar() {
|
|
595
|
+
if (events.length === 0 && environment === null)
|
|
596
|
+
return null;
|
|
597
|
+
// Streams still open now: their totals, stamped with the stop time so
|
|
598
|
+
// the connection's duration runs to the end of the recording, within
|
|
599
|
+
// the event cap (the rest count as dropped below).
|
|
600
|
+
const start = opts.recordStart();
|
|
601
|
+
const stoppedAt = start > 0 ? Math.max(0, Date.now() - start) : 0;
|
|
602
|
+
const stillOpen = "still open when the recording stopped";
|
|
603
|
+
// Only full capture keeps a healthy connection; failures-only capture
|
|
604
|
+
// drops it at ingest like a successful request, so it takes no slot.
|
|
605
|
+
// A failed one already reported its totals on the error row.
|
|
606
|
+
const open = !all ? [] : [
|
|
607
|
+
...[...eventSources.values()].map((state) => sseClose(state, { reason: stillOpen })),
|
|
608
|
+
...[...openSockets.entries()].map(([connection, socket]) => ({
|
|
609
|
+
kind: "stream",
|
|
610
|
+
protocol: "websocket",
|
|
611
|
+
connection,
|
|
612
|
+
action: "close",
|
|
613
|
+
url: socket.url,
|
|
614
|
+
reason: stillOpen,
|
|
615
|
+
...socket.totals,
|
|
616
|
+
})),
|
|
617
|
+
];
|
|
618
|
+
const room = Math.max(0, MAX_EVENTS - events.length);
|
|
619
|
+
return trimToBudget({
|
|
620
|
+
schema_version: 2,
|
|
621
|
+
source: "cdp",
|
|
622
|
+
policy: {
|
|
623
|
+
console: all ? "all" : "errors",
|
|
624
|
+
network: all ? "all" : "failures",
|
|
625
|
+
navigation: true,
|
|
626
|
+
urls: "route",
|
|
627
|
+
text: "standard",
|
|
628
|
+
excludedOrigins: DEFAULT_EXCLUDED_ORIGINS,
|
|
629
|
+
networkDetail: opts.networkDetail ? "full" : "off",
|
|
630
|
+
// Playwright drives the clicks; they are already the agent's marks.
|
|
631
|
+
actions: false,
|
|
632
|
+
},
|
|
633
|
+
environment,
|
|
634
|
+
events: [...events, ...open.slice(0, room).map((row) => ({ ...row, time_ms: stoppedAt }))].sort((a, b) => a.time_ms - b.time_ms),
|
|
635
|
+
dropped_events: dropped + Math.max(0, open.length - room),
|
|
636
|
+
});
|
|
637
|
+
},
|
|
638
|
+
ready,
|
|
639
|
+
async settle() {
|
|
640
|
+
while (pending.length)
|
|
641
|
+
await Promise.all(pending.splice(0));
|
|
642
|
+
},
|
|
643
|
+
};
|
|
644
|
+
}
|