@open-take/runtime 0.5.3 → 0.6.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/dist/cdp-capture-DfJeA-uY.js +4697 -0
- package/dist/cdp-capture-DfJeA-uY.js.map +1 -0
- package/dist/cdp-capture-ryEVA9lz.js +3 -0
- package/dist/index.d.ts +965 -84
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3503 -232
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
- package/dist/cdp-capture-MBg9nQy3.js +0 -2370
- package/dist/cdp-capture-MBg9nQy3.js.map +0 -1
- package/dist/cdp-capture-gux1GPRE.js +0 -3
|
@@ -0,0 +1,4697 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, readlinkSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
|
3
|
+
import { homedir, tmpdir } from "node:os";
|
|
4
|
+
import { basename, dirname, extname, join, relative, resolve, sep } from "node:path";
|
|
5
|
+
import { CLIP_CLEAR_CSS, componentProbeExpression, mjpegMatroska, partDomExpression, pictureClip, readStateIndex, resolveFfmpeg, resolveFfprobe } from "@open-take/compositor";
|
|
6
|
+
import { spawn } from "node:child_process";
|
|
7
|
+
import { once } from "node:events";
|
|
8
|
+
import { createRequire } from "node:module";
|
|
9
|
+
import { createHash } from "node:crypto";
|
|
10
|
+
import { pathToFileURL } from "node:url";
|
|
11
|
+
|
|
12
|
+
//#region src/cdp.ts
|
|
13
|
+
const sleep$4 = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
14
|
+
const require = createRequire(import.meta.url);
|
|
15
|
+
const CHROME_CACHE = join(homedir(), ".open-take", "browsers");
|
|
16
|
+
const BUILDID_FILE = join(homedir(), ".open-take", "chrome-build.json");
|
|
17
|
+
function resolveChrome(explicit) {
|
|
18
|
+
const candidates = [];
|
|
19
|
+
if (explicit) candidates.push(explicit);
|
|
20
|
+
if (process.env.OPEN_TAKE_CHROME) candidates.push(process.env.OPEN_TAKE_CHROME);
|
|
21
|
+
if (existsSync(BUILDID_FILE)) try {
|
|
22
|
+
const exe = computeChromePathSync(JSON.parse(readFileSync(BUILDID_FILE, "utf8")).buildId);
|
|
23
|
+
if (exe) candidates.push(exe);
|
|
24
|
+
} catch {}
|
|
25
|
+
const abBrowsers = join(homedir(), ".agent-browser", "browsers");
|
|
26
|
+
if (existsSync(abBrowsers)) for (const d of readdirSync(abBrowsers).filter((n) => n.startsWith("chrome-")).sort().reverse()) candidates.push(join(abBrowsers, d, "Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing"), join(abBrowsers, d, "chrome-linux64", "chrome"), join(abBrowsers, d, "chrome"));
|
|
27
|
+
return candidates.find((c) => c && existsSync(c)) ?? null;
|
|
28
|
+
}
|
|
29
|
+
function computeChromePathSync(buildId) {
|
|
30
|
+
try {
|
|
31
|
+
const { computeExecutablePath, Browser } = require("@puppeteer/browsers");
|
|
32
|
+
return computeExecutablePath({
|
|
33
|
+
browser: Browser.CHROME,
|
|
34
|
+
buildId,
|
|
35
|
+
cacheDir: CHROME_CACHE
|
|
36
|
+
});
|
|
37
|
+
} catch {
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
async function ensureChrome(explicit) {
|
|
42
|
+
const found = resolveChrome(explicit);
|
|
43
|
+
if (found) return found;
|
|
44
|
+
try {
|
|
45
|
+
const { install, resolveBuildId, detectBrowserPlatform, computeExecutablePath, Browser } = await import("@puppeteer/browsers");
|
|
46
|
+
const platform = detectBrowserPlatform();
|
|
47
|
+
if (!platform) throw new Error("unsupported platform");
|
|
48
|
+
const buildId = await resolveBuildId(Browser.CHROME, platform, "stable");
|
|
49
|
+
const exe = computeExecutablePath({
|
|
50
|
+
browser: Browser.CHROME,
|
|
51
|
+
buildId,
|
|
52
|
+
cacheDir: CHROME_CACHE
|
|
53
|
+
});
|
|
54
|
+
if (!existsSync(exe)) {
|
|
55
|
+
mkdirSync(CHROME_CACHE, { recursive: true });
|
|
56
|
+
process.stderr.write(`open-take: downloading Chrome for Testing (${buildId}, one-time) → ${CHROME_CACHE}\n`);
|
|
57
|
+
let lastPct = -1;
|
|
58
|
+
await install({
|
|
59
|
+
browser: Browser.CHROME,
|
|
60
|
+
buildId,
|
|
61
|
+
cacheDir: CHROME_CACHE,
|
|
62
|
+
downloadProgressCallback: (downloaded, total) => {
|
|
63
|
+
if (!total) return;
|
|
64
|
+
const pct = Math.floor(downloaded / total * 100);
|
|
65
|
+
if (pct >= lastPct + 10 || pct === 100) {
|
|
66
|
+
lastPct = pct;
|
|
67
|
+
process.stderr.write(`open-take: …Chrome download ${pct}%\n`);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
});
|
|
71
|
+
process.stderr.write("open-take: Chrome ready.\n");
|
|
72
|
+
}
|
|
73
|
+
mkdirSync(dirname(BUILDID_FILE), { recursive: true });
|
|
74
|
+
writeFileSync(BUILDID_FILE, JSON.stringify({ buildId }));
|
|
75
|
+
return exe;
|
|
76
|
+
} catch (e) {
|
|
77
|
+
throw new Error(`open-take: no Chrome found and auto-download failed (${e.message}). Install Chrome/Chromium, or set OPEN_TAKE_CHROME to a Chrome binary.`);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
/** How long a request waits for Chrome's answer before it is given up. Most
|
|
81
|
+
* commands answer in milliseconds; a page whose renderer is stuck (or a
|
|
82
|
+
* Chrome that went quiet) never answers at all, and without a bound the take
|
|
83
|
+
* waits forever with Chrome idle — seen in 2 of 6 multi-screen shoots. */
|
|
84
|
+
const CDP_TIMEOUT_MS = 3e4;
|
|
85
|
+
/** The budget of the commands that legitimately take long on a big page —
|
|
86
|
+
* a full screenshot, an MHTML snapshot, a navigation that has to commit, a
|
|
87
|
+
* response body, and any evaluate that awaits the page's own promise. */
|
|
88
|
+
const CDP_SLOW_TIMEOUT_MS = 12e4;
|
|
89
|
+
const SLOW_METHODS = new Set([
|
|
90
|
+
"Page.captureScreenshot",
|
|
91
|
+
"Page.captureSnapshot",
|
|
92
|
+
"Page.printToPDF",
|
|
93
|
+
"Page.navigate",
|
|
94
|
+
"Page.reload",
|
|
95
|
+
"Network.getResponseBody",
|
|
96
|
+
"Target.createTarget"
|
|
97
|
+
]);
|
|
98
|
+
/** OPEN_TAKE_CDP_TIMEOUT_MS (a very slow machine, a test): the ordinary
|
|
99
|
+
* budget; slow commands get 4× it */
|
|
100
|
+
function envBudget() {
|
|
101
|
+
const v = Number(process.env.OPEN_TAKE_CDP_TIMEOUT_MS);
|
|
102
|
+
return Number.isFinite(v) && v > 0 ? v : void 0;
|
|
103
|
+
}
|
|
104
|
+
/** The default budget of one request: `base` (the connection's own, else
|
|
105
|
+
* OPEN_TAKE_CDP_TIMEOUT_MS, else CDP_TIMEOUT_MS) — or, for the slow
|
|
106
|
+
* commands and promise-awaiting evaluates, 4× it (CDP_SLOW_TIMEOUT_MS by
|
|
107
|
+
* default). */
|
|
108
|
+
function cdpTimeoutFor(method, params, base) {
|
|
109
|
+
const b = base ?? envBudget() ?? CDP_TIMEOUT_MS;
|
|
110
|
+
const slow = SLOW_METHODS.has(method) || (method === "Runtime.evaluate" || method === "Runtime.callFunctionOn") && params.awaitPromise === true;
|
|
111
|
+
return slow ? b * (CDP_SLOW_TIMEOUT_MS / CDP_TIMEOUT_MS) : b;
|
|
112
|
+
}
|
|
113
|
+
/** A request Chrome did not answer: it timed out, or the connection closed /
|
|
114
|
+
* the page crashed while it waited. `reason` tells which. */
|
|
115
|
+
var CdpError = class extends Error {
|
|
116
|
+
constructor(message, method, reason) {
|
|
117
|
+
super(message);
|
|
118
|
+
this.method = method;
|
|
119
|
+
this.reason = reason;
|
|
120
|
+
this.name = "CdpError";
|
|
121
|
+
}
|
|
122
|
+
};
|
|
123
|
+
/** true for a request that got no answer (timeout, closed, crashed) — the
|
|
124
|
+
* page behind it may be stuck; a protocol error answer is not one */
|
|
125
|
+
const isCdpStall = (e) => e instanceof CdpError;
|
|
126
|
+
var CDP = class CDP {
|
|
127
|
+
ws;
|
|
128
|
+
id = 0;
|
|
129
|
+
pending = new Map();
|
|
130
|
+
handlers = new Map();
|
|
131
|
+
/** why the connection is gone, once it is — later sends fail at once */
|
|
132
|
+
closedWhy = null;
|
|
133
|
+
timeoutMs;
|
|
134
|
+
constructor(ws, timeoutMs) {
|
|
135
|
+
this.ws = ws;
|
|
136
|
+
this.timeoutMs = timeoutMs;
|
|
137
|
+
ws.addEventListener("message", (ev) => {
|
|
138
|
+
let msg;
|
|
139
|
+
try {
|
|
140
|
+
msg = JSON.parse(ev.data);
|
|
141
|
+
} catch {
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
if (msg.id != null) {
|
|
145
|
+
const p = this.pending.get(msg.id);
|
|
146
|
+
if (!p) return;
|
|
147
|
+
this.pending.delete(msg.id);
|
|
148
|
+
clearTimeout(p.timer);
|
|
149
|
+
if (msg.error) p.reject(new Error(JSON.stringify(msg.error)));
|
|
150
|
+
else p.resolve(msg.result);
|
|
151
|
+
} else if (msg.method) {
|
|
152
|
+
if (msg.method === "Inspector.targetCrashed") this.failAll("crashed", "the page crashed (its renderer died)");
|
|
153
|
+
else if (msg.method === "Inspector.detached") this.gone(`the page detached (${msg.params?.reason ?? "no reason given"})`);
|
|
154
|
+
this.handlers.get(msg.method)?.(msg.params);
|
|
155
|
+
}
|
|
156
|
+
});
|
|
157
|
+
ws.addEventListener("close", () => this.gone("the DevTools connection closed"));
|
|
158
|
+
ws.addEventListener("error", () => this.gone("the DevTools connection failed"));
|
|
159
|
+
}
|
|
160
|
+
/** Open a session on `wsUrl`. `timeoutMs` replaces the per-request default
|
|
161
|
+
* base (see cdpTimeoutFor; slow commands get 4× it). */
|
|
162
|
+
static connect(wsUrl, opts = {}) {
|
|
163
|
+
return new Promise((resolve$1, reject) => {
|
|
164
|
+
const ws = new WebSocket(wsUrl);
|
|
165
|
+
const timer = setTimeout(() => {
|
|
166
|
+
reject(new Error(`CDP connect failed: ${wsUrl} did not open within 15 s`));
|
|
167
|
+
try {
|
|
168
|
+
ws.close();
|
|
169
|
+
} catch {}
|
|
170
|
+
}, 15e3);
|
|
171
|
+
timer.unref?.();
|
|
172
|
+
ws.addEventListener("open", () => {
|
|
173
|
+
clearTimeout(timer);
|
|
174
|
+
resolve$1(new CDP(ws, opts.timeoutMs));
|
|
175
|
+
});
|
|
176
|
+
ws.addEventListener("error", () => {
|
|
177
|
+
clearTimeout(timer);
|
|
178
|
+
reject(new Error(`CDP connect failed: ${wsUrl}`));
|
|
179
|
+
});
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
/** Send one command. Rejects with a CdpError if no answer arrives within its
|
|
183
|
+
* budget (`opts.timeoutMs`, else cdpTimeoutFor), or the connection closes /
|
|
184
|
+
* the page crashes first — it never waits forever. */
|
|
185
|
+
send(method, params = {}, opts = {}) {
|
|
186
|
+
if (this.closedWhy != null) return Promise.reject(new CdpError(`CDP ${method}: ${this.closedWhy}`, method, "closed"));
|
|
187
|
+
const id = ++this.id;
|
|
188
|
+
const budget = opts.timeoutMs ?? cdpTimeoutFor(method, params, this.timeoutMs);
|
|
189
|
+
return new Promise((resolve$1, reject) => {
|
|
190
|
+
const p = {
|
|
191
|
+
method,
|
|
192
|
+
resolve: (value) => resolve$1(value),
|
|
193
|
+
reject
|
|
194
|
+
};
|
|
195
|
+
if (budget > 0 && Number.isFinite(budget)) {
|
|
196
|
+
p.timer = setTimeout(() => {
|
|
197
|
+
if (!this.pending.delete(id)) return;
|
|
198
|
+
reject(new CdpError(`CDP ${method}: no answer within ${Math.round(budget / 100) / 10} s — the page (or Chrome) is not responding`, method, "timeout"));
|
|
199
|
+
}, budget);
|
|
200
|
+
p.timer.unref?.();
|
|
201
|
+
}
|
|
202
|
+
this.pending.set(id, p);
|
|
203
|
+
try {
|
|
204
|
+
this.ws.send(JSON.stringify({
|
|
205
|
+
id,
|
|
206
|
+
method,
|
|
207
|
+
params
|
|
208
|
+
}));
|
|
209
|
+
} catch (e) {
|
|
210
|
+
this.pending.delete(id);
|
|
211
|
+
clearTimeout(p.timer);
|
|
212
|
+
reject(new CdpError(`CDP ${method}: could not send (${e.message})`, method, "closed"));
|
|
213
|
+
}
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
on(method, fn) {
|
|
217
|
+
this.handlers.set(method, (params) => fn(params));
|
|
218
|
+
}
|
|
219
|
+
/** requests still waiting for an answer */
|
|
220
|
+
get waiting() {
|
|
221
|
+
return this.pending.size;
|
|
222
|
+
}
|
|
223
|
+
/** whether the connection is gone (closed, failed) */
|
|
224
|
+
get closed() {
|
|
225
|
+
return this.closedWhy != null;
|
|
226
|
+
}
|
|
227
|
+
close() {
|
|
228
|
+
this.gone("the DevTools connection was closed");
|
|
229
|
+
try {
|
|
230
|
+
this.ws.close();
|
|
231
|
+
} catch {}
|
|
232
|
+
}
|
|
233
|
+
gone(why) {
|
|
234
|
+
if (this.closedWhy == null) this.closedWhy = why;
|
|
235
|
+
this.failAll("closed", this.closedWhy);
|
|
236
|
+
}
|
|
237
|
+
failAll(reason, why) {
|
|
238
|
+
const all = [...this.pending.values()];
|
|
239
|
+
this.pending.clear();
|
|
240
|
+
for (const p of all) {
|
|
241
|
+
clearTimeout(p.timer);
|
|
242
|
+
p.reject(new CdpError(`CDP ${p.method}: ${why}`, p.method, reason));
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
};
|
|
246
|
+
/** Launch headless Chrome, return a CDP session bound to its page target. */
|
|
247
|
+
async function launchBrowser(opts) {
|
|
248
|
+
const chrome = await ensureChrome(opts.chromePath);
|
|
249
|
+
const ephemeral = !opts.userDataDir;
|
|
250
|
+
if (opts.userDataDir) mkdirSync(opts.userDataDir, { recursive: true });
|
|
251
|
+
const userDir = opts.userDataDir ?? mkdtempSync(join(tmpdir(), "open-take-cdp-"));
|
|
252
|
+
if (!ephemeral) rmSync(join(userDir, "DevToolsActivePort"), { force: true });
|
|
253
|
+
if (!ephemeral) {
|
|
254
|
+
const holder = singletonHolderPid(userDir);
|
|
255
|
+
if (holder != null && pidAlive(holder)) throw new Error(`profile in use: a Chrome (pid ${holder}) is already running on ${userDir} — quit it first (e.g. the \`open-take auth\` window)`);
|
|
256
|
+
for (const f of [
|
|
257
|
+
"SingletonLock",
|
|
258
|
+
"SingletonCookie",
|
|
259
|
+
"SingletonSocket"
|
|
260
|
+
]) rmSync(join(userDir, f), { force: true });
|
|
261
|
+
}
|
|
262
|
+
const dsf = opts.deviceScaleFactor ?? 1;
|
|
263
|
+
const proc = spawn(chrome, [
|
|
264
|
+
"--remote-debugging-port=0",
|
|
265
|
+
`--user-data-dir=${userDir}`,
|
|
266
|
+
`--window-size=${opts.width},${opts.height}`,
|
|
267
|
+
...dsf !== 1 ? [`--force-device-scale-factor=${dsf}`] : [],
|
|
268
|
+
...opts.headless === false ? [] : ["--headless=new"],
|
|
269
|
+
"--no-sandbox",
|
|
270
|
+
"--password-store=basic",
|
|
271
|
+
"--use-mock-keychain",
|
|
272
|
+
"--no-first-run",
|
|
273
|
+
"--no-default-browser-check",
|
|
274
|
+
"--hide-scrollbars",
|
|
275
|
+
"--disable-extensions",
|
|
276
|
+
"--disable-background-networking",
|
|
277
|
+
"--disable-features=Translate,AcceptCHFrame,MediaRouter,OptimizationHints",
|
|
278
|
+
"--mute-audio",
|
|
279
|
+
"--disable-audio-output",
|
|
280
|
+
"about:blank"
|
|
281
|
+
], { stdio: [
|
|
282
|
+
"ignore",
|
|
283
|
+
"ignore",
|
|
284
|
+
"pipe"
|
|
285
|
+
] });
|
|
286
|
+
let stderr = "";
|
|
287
|
+
proc.stderr?.on("data", (d) => {
|
|
288
|
+
stderr += d;
|
|
289
|
+
});
|
|
290
|
+
const close = async () => {
|
|
291
|
+
const exitWithin = (ms) => new Promise((res) => {
|
|
292
|
+
if (proc.exitCode != null) return res(true);
|
|
293
|
+
const tm = setTimeout(() => res(false), ms);
|
|
294
|
+
proc.once("exit", () => {
|
|
295
|
+
clearTimeout(tm);
|
|
296
|
+
res(true);
|
|
297
|
+
});
|
|
298
|
+
});
|
|
299
|
+
try {
|
|
300
|
+
if (!ephemeral) {
|
|
301
|
+
proc.kill("SIGTERM");
|
|
302
|
+
if (!await exitWithin(4e3)) proc.kill("SIGKILL");
|
|
303
|
+
} else proc.kill("SIGKILL");
|
|
304
|
+
} catch {}
|
|
305
|
+
await exitWithin(2e3);
|
|
306
|
+
if (ephemeral) try {
|
|
307
|
+
rmSync(userDir, {
|
|
308
|
+
recursive: true,
|
|
309
|
+
force: true,
|
|
310
|
+
maxRetries: 12,
|
|
311
|
+
retryDelay: 250
|
|
312
|
+
});
|
|
313
|
+
} catch (e) {
|
|
314
|
+
console.error(`open-take: could not remove Chrome's temporary profile ${userDir} (${e.message}) — safe to delete by hand`);
|
|
315
|
+
}
|
|
316
|
+
};
|
|
317
|
+
try {
|
|
318
|
+
const port = await readDevtoolsPort(userDir, proc);
|
|
319
|
+
const target = await pageTargetWs(port);
|
|
320
|
+
const cdp = await CDP.connect(target.wsUrl);
|
|
321
|
+
return {
|
|
322
|
+
cdp,
|
|
323
|
+
targetId: target.id,
|
|
324
|
+
port,
|
|
325
|
+
close
|
|
326
|
+
};
|
|
327
|
+
} catch (e) {
|
|
328
|
+
await close();
|
|
329
|
+
throw new Error(`open-take(hi-fps): browser launch failed: ${e.message}\n${stderr.slice(-600)}`);
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
function singletonHolderPid(userDir) {
|
|
333
|
+
try {
|
|
334
|
+
const target = readlinkSync(join(userDir, "SingletonLock"));
|
|
335
|
+
const pid = Number(target.split("-").pop());
|
|
336
|
+
return Number.isFinite(pid) && pid > 0 ? pid : null;
|
|
337
|
+
} catch {
|
|
338
|
+
return null;
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
function pidAlive(pid) {
|
|
342
|
+
try {
|
|
343
|
+
process.kill(pid, 0);
|
|
344
|
+
return true;
|
|
345
|
+
} catch {
|
|
346
|
+
return false;
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
const DEVTOOLS_PORT_WAIT_MS = 3e4;
|
|
350
|
+
async function readDevtoolsPort(userDir, proc) {
|
|
351
|
+
const file = join(userDir, "DevToolsActivePort");
|
|
352
|
+
for (let i = 0; i < DEVTOOLS_PORT_WAIT_MS / 50; i++) {
|
|
353
|
+
if (proc.exitCode != null) throw new Error(`chrome exited early (${proc.exitCode})`);
|
|
354
|
+
if (existsSync(file)) {
|
|
355
|
+
const line = readFileSync(file, "utf8").split("\n")[0]?.trim();
|
|
356
|
+
const port = Number(line);
|
|
357
|
+
if (Number.isFinite(port) && port > 0) return port;
|
|
358
|
+
}
|
|
359
|
+
await sleep$4(50);
|
|
360
|
+
}
|
|
361
|
+
throw new Error(`timed out waiting for DevToolsActivePort (${DEVTOOLS_PORT_WAIT_MS / 1e3}s)`);
|
|
362
|
+
}
|
|
363
|
+
async function pageTargetWs(port) {
|
|
364
|
+
for (let i = 0; i < 60; i++) {
|
|
365
|
+
try {
|
|
366
|
+
const list = await (await fetch(`http://localhost:${port}/json`)).json();
|
|
367
|
+
const page = list.find((t) => t.type === "page");
|
|
368
|
+
if (page?.webSocketDebuggerUrl) return {
|
|
369
|
+
wsUrl: page.webSocketDebuggerUrl,
|
|
370
|
+
id: page.id
|
|
371
|
+
};
|
|
372
|
+
} catch {}
|
|
373
|
+
await sleep$4(100);
|
|
374
|
+
}
|
|
375
|
+
throw new Error("no page target appeared");
|
|
376
|
+
}
|
|
377
|
+
async function fitViewport(cdp, targetId, vw, vh) {
|
|
378
|
+
const readInner = async () => {
|
|
379
|
+
const r = await cdp.send("Runtime.evaluate", {
|
|
380
|
+
expression: "JSON.stringify([window.innerWidth, window.innerHeight])",
|
|
381
|
+
returnByValue: true
|
|
382
|
+
});
|
|
383
|
+
const v = JSON.parse(r.result?.value ?? "[0,0]");
|
|
384
|
+
return [Number(v[0]), Number(v[1])];
|
|
385
|
+
};
|
|
386
|
+
let win = null;
|
|
387
|
+
try {
|
|
388
|
+
win = await cdp.send("Browser.getWindowForTarget", { targetId });
|
|
389
|
+
} catch {
|
|
390
|
+
return readInner();
|
|
391
|
+
}
|
|
392
|
+
if (!win?.windowId) return readInner();
|
|
393
|
+
let { width, height } = win.bounds;
|
|
394
|
+
let inner = await readInner();
|
|
395
|
+
for (let i = 0; i < 4; i++) {
|
|
396
|
+
const dw = vw - inner[0];
|
|
397
|
+
const dh = vh - inner[1];
|
|
398
|
+
if (Math.abs(dw) <= 1 && Math.abs(dh) <= 1) break;
|
|
399
|
+
width += dw;
|
|
400
|
+
height += dh;
|
|
401
|
+
await cdp.send("Browser.setWindowBounds", {
|
|
402
|
+
windowId: win.windowId,
|
|
403
|
+
bounds: {
|
|
404
|
+
width,
|
|
405
|
+
height
|
|
406
|
+
}
|
|
407
|
+
});
|
|
408
|
+
await sleep$4(120);
|
|
409
|
+
inner = await readInner();
|
|
410
|
+
}
|
|
411
|
+
return inner;
|
|
412
|
+
}
|
|
413
|
+
function captureCadence(frames) {
|
|
414
|
+
const ordered = [...frames].sort((a, b) => a.offMs - b.offMs);
|
|
415
|
+
const intervals = ordered.slice(1).map((frame, i) => frame.offMs - ordered[i].offMs).sort((a, b) => a - b);
|
|
416
|
+
const rounded = (n) => Math.round(n * 1e3) / 1e3;
|
|
417
|
+
const sources = new Set(frames.map((frame) => frame.timestampSource ?? "arrival"));
|
|
418
|
+
return {
|
|
419
|
+
frameCount: frames.length,
|
|
420
|
+
timestampSource: sources.size > 1 ? "mixed" : sources.has("frame-swap") ? "frame-swap" : "arrival",
|
|
421
|
+
frameOffsetsMs: ordered.map((frame) => rounded(frame.offMs)),
|
|
422
|
+
arrivalOffsetsMs: ordered.map((frame) => rounded(frame.arrivalMs ?? frame.offMs)),
|
|
423
|
+
medianIntervalMs: rounded(intervals[Math.floor(intervals.length / 2)] ?? 0),
|
|
424
|
+
p95IntervalMs: rounded(intervals[Math.max(0, Math.ceil(intervals.length * .95) - 1)] ?? 0),
|
|
425
|
+
maxIntervalMs: rounded(intervals.at(-1) ?? 0),
|
|
426
|
+
maxArrivalDelayMs: rounded(frames.reduce((max, frame) => Math.max(max, (frame.arrivalMs ?? frame.offMs) - frame.offMs), 0)),
|
|
427
|
+
outOfOrderFrames: frames.filter((frame, i) => i > 0 && frame.offMs < frames[i - 1].offMs).length,
|
|
428
|
+
note: "Delivered-frame timing, not unique image content or a smoothness score. Static pages may send no frames; inspect image changes within active action windows. Encoded fps is separate."
|
|
429
|
+
};
|
|
430
|
+
}
|
|
431
|
+
const HOLE_GAP_MS = 40;
|
|
432
|
+
const HOLE_MOVE_PX = 16;
|
|
433
|
+
function easedPoint(path, u, ease) {
|
|
434
|
+
const c = Math.max(0, Math.min(1, u));
|
|
435
|
+
const k = ease === "linear" ? c : c * c * c * (c * (c * 6 - 15) + 10);
|
|
436
|
+
if (path.length === 1) return path[0];
|
|
437
|
+
const seg = path.slice(1).map((q, i) => Math.hypot(q.x - path[i].x, q.y - path[i].y));
|
|
438
|
+
let left = k * seg.reduce((t, d) => t + d, 0);
|
|
439
|
+
for (let i = 0; i < seg.length; i++) {
|
|
440
|
+
if (left <= seg[i] || i === seg.length - 1) {
|
|
441
|
+
const f = seg[i] > 0 ? left / seg[i] : 0;
|
|
442
|
+
return {
|
|
443
|
+
x: path[i].x + (path[i + 1].x - path[i].x) * f,
|
|
444
|
+
y: path[i].y + (path[i + 1].y - path[i].y) * f
|
|
445
|
+
};
|
|
446
|
+
}
|
|
447
|
+
left -= seg[i];
|
|
448
|
+
}
|
|
449
|
+
return path[path.length - 1];
|
|
450
|
+
}
|
|
451
|
+
function dragCadence(events, frameOffsetsMs, arrivalOffsetsMs) {
|
|
452
|
+
const out = [];
|
|
453
|
+
events.forEach((e, event) => {
|
|
454
|
+
if (e.kind !== "drag" || !e.durationMs || e.durationMs < 200) return;
|
|
455
|
+
const start = e.tMs;
|
|
456
|
+
const dur = e.durationMs;
|
|
457
|
+
const end = start + dur;
|
|
458
|
+
const inside = frameOffsetsMs.filter((t) => t >= start && t <= end).sort((a, b) => a - b);
|
|
459
|
+
const marks = [
|
|
460
|
+
start,
|
|
461
|
+
...inside,
|
|
462
|
+
end
|
|
463
|
+
];
|
|
464
|
+
const maxGapMs = Math.max(...marks.slice(1).map((t, i) => t - marks[i]));
|
|
465
|
+
const path = e.path?.length ? e.path : e.x != null && e.y != null && e.to ? [{
|
|
466
|
+
x: e.x,
|
|
467
|
+
y: e.y
|
|
468
|
+
}, e.to] : null;
|
|
469
|
+
let holes = 0;
|
|
470
|
+
let worstHole;
|
|
471
|
+
if (path) {
|
|
472
|
+
const ease = e.ease === "linear" ? "linear" : "smooth";
|
|
473
|
+
const at = (t) => easedPoint(path, (t - start) / dur, ease);
|
|
474
|
+
for (let i = 1; i < inside.length; i++) {
|
|
475
|
+
const gapMs = inside[i] - inside[i - 1];
|
|
476
|
+
if (gapMs <= HOLE_GAP_MS) continue;
|
|
477
|
+
const p = at(inside[i - 1]);
|
|
478
|
+
const q = at(inside[i]);
|
|
479
|
+
const movedPx = Math.hypot(q.x - p.x, q.y - p.y);
|
|
480
|
+
if (movedPx < HOLE_MOVE_PX) continue;
|
|
481
|
+
holes++;
|
|
482
|
+
if (!worstHole || movedPx > worstHole.movedPx) worstHole = {
|
|
483
|
+
atMs: Math.round(inside[i - 1]),
|
|
484
|
+
gapMs: Math.round(gapMs),
|
|
485
|
+
movedPx: Math.round(movedPx)
|
|
486
|
+
};
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
let deliveryMs;
|
|
490
|
+
if (arrivalOffsetsMs && arrivalOffsetsMs.length === frameOffsetsMs.length) {
|
|
491
|
+
const delays = frameOffsetsMs.map((t, i) => t >= start && t <= end ? arrivalOffsetsMs[i] - t : null).filter((d) => d != null).sort((a, b) => a - b);
|
|
492
|
+
if (delays.length) deliveryMs = Math.round(delays[Math.floor(delays.length / 2)]);
|
|
493
|
+
}
|
|
494
|
+
out.push({
|
|
495
|
+
event,
|
|
496
|
+
tMs: start,
|
|
497
|
+
durationMs: dur,
|
|
498
|
+
frames: inside.length,
|
|
499
|
+
perSecond: Math.round(inside.length / dur * 1e4) / 10,
|
|
500
|
+
maxGapMs: Math.round(maxGapMs),
|
|
501
|
+
holes,
|
|
502
|
+
...worstHole ? { worstHole } : {},
|
|
503
|
+
...deliveryMs != null ? { deliveryMs } : {}
|
|
504
|
+
});
|
|
505
|
+
});
|
|
506
|
+
return out;
|
|
507
|
+
}
|
|
508
|
+
var Screencast = class {
|
|
509
|
+
cdp;
|
|
510
|
+
dir;
|
|
511
|
+
t0 = 0;
|
|
512
|
+
n = 0;
|
|
513
|
+
lastArrivalAt = 0;
|
|
514
|
+
frames = [];
|
|
515
|
+
get idleForMs() {
|
|
516
|
+
return Date.now() - this.lastArrivalAt;
|
|
517
|
+
}
|
|
518
|
+
constructor(cdp, dir) {
|
|
519
|
+
this.cdp = cdp;
|
|
520
|
+
this.dir = dir;
|
|
521
|
+
}
|
|
522
|
+
/** Begin capture. `t0` (Date.now) anchors every frame + event onto one clock. */
|
|
523
|
+
async start(t0, opts) {
|
|
524
|
+
this.t0 = t0;
|
|
525
|
+
this.lastArrivalAt = t0;
|
|
526
|
+
this.cdp.on("Page.screencastFrame", (p) => {
|
|
527
|
+
const arrived = Date.now();
|
|
528
|
+
this.lastArrivalAt = arrived;
|
|
529
|
+
const swap = p.metadata?.timestamp;
|
|
530
|
+
const hasSwap = typeof swap === "number" && Number.isFinite(swap);
|
|
531
|
+
const off = Math.max(0, hasSwap ? swap * 1e3 - this.t0 : arrived - this.t0);
|
|
532
|
+
const file = join(this.dir, `f-${String(this.n++).padStart(5, "0")}.jpg`);
|
|
533
|
+
this.cdp.send("Page.screencastFrameAck", { sessionId: p.sessionId }).catch(() => {});
|
|
534
|
+
writeFileSync(file, Buffer.from(p.data, "base64"));
|
|
535
|
+
this.frames.push({
|
|
536
|
+
file,
|
|
537
|
+
offMs: off,
|
|
538
|
+
arrivalMs: arrived - this.t0,
|
|
539
|
+
timestampSource: hasSwap ? "frame-swap" : "arrival"
|
|
540
|
+
});
|
|
541
|
+
});
|
|
542
|
+
await this.cdp.send("Page.startScreencast", {
|
|
543
|
+
format: "jpeg",
|
|
544
|
+
quality: opts.quality ?? 90,
|
|
545
|
+
maxWidth: opts.maxWidth,
|
|
546
|
+
maxHeight: opts.maxHeight,
|
|
547
|
+
everyNthFrame: 1
|
|
548
|
+
});
|
|
549
|
+
}
|
|
550
|
+
async stop() {
|
|
551
|
+
await this.cdp.send("Page.stopScreencast").catch(() => {});
|
|
552
|
+
}
|
|
553
|
+
};
|
|
554
|
+
/** Refresh idle surfaces without interrupting pages already producing frames.
|
|
555
|
+
* Never queue another expensive screenshot behind a slow/in-flight request. */
|
|
556
|
+
async function pumpIdleRaster(cdp, screencast, active, paused) {
|
|
557
|
+
let pending = false;
|
|
558
|
+
while (active()) {
|
|
559
|
+
if (!paused() && !pending && screencast.idleForMs >= 200) {
|
|
560
|
+
pending = true;
|
|
561
|
+
cdp.send("Page.captureScreenshot", {
|
|
562
|
+
format: "jpeg",
|
|
563
|
+
quality: 1
|
|
564
|
+
}).catch(() => {}).finally(() => {
|
|
565
|
+
pending = false;
|
|
566
|
+
});
|
|
567
|
+
}
|
|
568
|
+
await sleep$4(45);
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
/** Where each frame sits on the video's clock, in whole milliseconds. The
|
|
572
|
+
* first frame is pulled back to 0 so the video timeline starts where event
|
|
573
|
+
* timestamps do; later frames keep their observed offset, nudged forward by
|
|
574
|
+
* 1 ms when two swaps round onto the same millisecond so no frame vanishes
|
|
575
|
+
* under its neighbour. The last frame is repeated at the end time (at least
|
|
576
|
+
* one frame period after it was shown) to give it a duration. */
|
|
577
|
+
function frameTimeline(frames, endMs, fps) {
|
|
578
|
+
const ordered = [...frames].sort((a, b) => a.offMs - b.offMs);
|
|
579
|
+
const timeline = [];
|
|
580
|
+
let tMs = 0;
|
|
581
|
+
for (let i = 0; i < ordered.length; i++) {
|
|
582
|
+
if (i > 0) tMs = Math.max(tMs + 1, Math.round(ordered[i].offMs));
|
|
583
|
+
timeline.push({
|
|
584
|
+
file: ordered[i].file,
|
|
585
|
+
tMs
|
|
586
|
+
});
|
|
587
|
+
}
|
|
588
|
+
const last = ordered[ordered.length - 1];
|
|
589
|
+
timeline.push({
|
|
590
|
+
file: last.file,
|
|
591
|
+
tMs: Math.max(tMs + 1, Math.round(endMs), Math.round(last.offMs + 1e3 / fps))
|
|
592
|
+
});
|
|
593
|
+
return timeline;
|
|
594
|
+
}
|
|
595
|
+
async function encodeFrames(frames, endMs, outPath, fps, ffmpegBin) {
|
|
596
|
+
if (frames.length === 0) throw new Error("open-take(hi-fps): no frames captured");
|
|
597
|
+
const timeline = frameTimeline(frames, endMs, fps);
|
|
598
|
+
const bin = ffmpegBin ?? await resolveFfmpeg();
|
|
599
|
+
const isWebm = /\.webm$/i.test(outPath);
|
|
600
|
+
const codec = isWebm ? [
|
|
601
|
+
"-c:v",
|
|
602
|
+
"libvpx-vp9",
|
|
603
|
+
"-b:v",
|
|
604
|
+
"0",
|
|
605
|
+
"-crf",
|
|
606
|
+
"28",
|
|
607
|
+
"-deadline",
|
|
608
|
+
"good",
|
|
609
|
+
"-cpu-used",
|
|
610
|
+
"4"
|
|
611
|
+
] : [
|
|
612
|
+
"-c:v",
|
|
613
|
+
"libx264",
|
|
614
|
+
"-preset",
|
|
615
|
+
"veryfast",
|
|
616
|
+
"-crf",
|
|
617
|
+
"18"
|
|
618
|
+
];
|
|
619
|
+
const colorConvert = isWebm ? "" : ":in_range=full:in_color_matrix=bt601:out_range=tv:out_color_matrix=bt709:flags=bicubic+accurate_rnd+full_chroma_int";
|
|
620
|
+
const colorLabel = isWebm ? "" : ",setparams=range=tv:colorspace=bt709:color_primaries=bt709:color_trc=iec61966-2-1";
|
|
621
|
+
return new Promise((resolve$1, reject) => {
|
|
622
|
+
const args = [
|
|
623
|
+
"-y",
|
|
624
|
+
"-loglevel",
|
|
625
|
+
"error",
|
|
626
|
+
"-f",
|
|
627
|
+
"matroska",
|
|
628
|
+
"-i",
|
|
629
|
+
"pipe:0",
|
|
630
|
+
"-fps_mode",
|
|
631
|
+
"cfr",
|
|
632
|
+
"-r",
|
|
633
|
+
String(fps),
|
|
634
|
+
"-vf",
|
|
635
|
+
`scale=trunc(iw/2)*2:trunc(ih/2)*2${colorConvert},format=yuv420p${colorLabel}`,
|
|
636
|
+
...codec,
|
|
637
|
+
outPath
|
|
638
|
+
];
|
|
639
|
+
const c = spawn(bin, args, { stdio: [
|
|
640
|
+
"pipe",
|
|
641
|
+
"ignore",
|
|
642
|
+
"pipe"
|
|
643
|
+
] });
|
|
644
|
+
let err = "";
|
|
645
|
+
let feedErr;
|
|
646
|
+
c.stderr.on("data", (d) => {
|
|
647
|
+
err += d;
|
|
648
|
+
});
|
|
649
|
+
c.on("error", reject);
|
|
650
|
+
c.on("close", (code) => {
|
|
651
|
+
if (code !== 0 && code !== null) reject(new Error(`ffmpeg encode exited ${code}: ${err.slice(-800)}`));
|
|
652
|
+
else if (feedErr) reject(feedErr);
|
|
653
|
+
else if (code === 0) resolve$1();
|
|
654
|
+
else reject(new Error(`ffmpeg encode killed: ${err.slice(-800)}`));
|
|
655
|
+
});
|
|
656
|
+
c.stdin.on("error", () => {});
|
|
657
|
+
feedStdin(c.stdin, mjpegMatroska(timeline)).then(() => c.stdin.end(), (e) => {
|
|
658
|
+
feedErr = e;
|
|
659
|
+
c.kill("SIGKILL");
|
|
660
|
+
});
|
|
661
|
+
});
|
|
662
|
+
}
|
|
663
|
+
/** Write chunks respecting backpressure. The pipe dying underneath us (ffmpeg
|
|
664
|
+
* exited) simply ends the feed — the process exit explains itself; only the
|
|
665
|
+
* source throwing (a frame that cannot be read) rejects. */
|
|
666
|
+
async function feedStdin(stdin, chunks) {
|
|
667
|
+
for await (const chunk of chunks) {
|
|
668
|
+
if (stdin.destroyed || stdin.writableEnded) return;
|
|
669
|
+
try {
|
|
670
|
+
if (!stdin.write(chunk)) await once(stdin, "drain");
|
|
671
|
+
} catch {
|
|
672
|
+
return;
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
/** A throwaway temp dir for the screencast's per-frame JPEGs. */
|
|
677
|
+
const makeFrameDir = () => mkdtempSync(join(tmpdir(), "open-take-frames-"));
|
|
678
|
+
/** Poll `ready` every few milliseconds until it is true or `timeoutMs` has passed.
|
|
679
|
+
* Resolves true when the condition was met, false on timeout. Used to pace work
|
|
680
|
+
* by something the page did (a painted frame) instead of by a blind timer. */
|
|
681
|
+
async function waitUntil(ready, timeoutMs, stepMs = 4) {
|
|
682
|
+
const deadline = Date.now() + timeoutMs;
|
|
683
|
+
while (!ready()) {
|
|
684
|
+
if (Date.now() >= deadline) return false;
|
|
685
|
+
await new Promise((r) => setTimeout(r, stepMs));
|
|
686
|
+
}
|
|
687
|
+
return true;
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
//#endregion
|
|
691
|
+
//#region src/capture.ts
|
|
692
|
+
const sleep$3 = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
693
|
+
function findBox(o) {
|
|
694
|
+
if (!o || typeof o !== "object") return null;
|
|
695
|
+
const r = o;
|
|
696
|
+
if (typeof r.x === "number" && typeof r.y === "number" && (typeof r.width === "number" || typeof r.w === "number")) return {
|
|
697
|
+
x: r.x,
|
|
698
|
+
y: r.y,
|
|
699
|
+
w: r.width ?? r.w,
|
|
700
|
+
h: r.height ?? r.h
|
|
701
|
+
};
|
|
702
|
+
for (const k of Object.keys(r)) {
|
|
703
|
+
const hit = findBox(r[k]);
|
|
704
|
+
if (hit) return hit;
|
|
705
|
+
}
|
|
706
|
+
return null;
|
|
707
|
+
}
|
|
708
|
+
function deepParse(s) {
|
|
709
|
+
let cur = s;
|
|
710
|
+
for (let i = 0; i < 5 && typeof cur === "string"; i++) try {
|
|
711
|
+
cur = JSON.parse(cur);
|
|
712
|
+
} catch {
|
|
713
|
+
break;
|
|
714
|
+
}
|
|
715
|
+
return cur;
|
|
716
|
+
}
|
|
717
|
+
function evalValue(raw) {
|
|
718
|
+
let top;
|
|
719
|
+
try {
|
|
720
|
+
top = JSON.parse(raw);
|
|
721
|
+
} catch {
|
|
722
|
+
return deepParse(raw);
|
|
723
|
+
}
|
|
724
|
+
if (top && typeof top === "object") {
|
|
725
|
+
const o = top;
|
|
726
|
+
const data = o.data;
|
|
727
|
+
if (data && "result" in data) return deepParse(data.result);
|
|
728
|
+
for (const k of [
|
|
729
|
+
"result",
|
|
730
|
+
"output",
|
|
731
|
+
"stdout",
|
|
732
|
+
"value"
|
|
733
|
+
]) if (k in o) return deepParse(o[k]);
|
|
734
|
+
}
|
|
735
|
+
return deepParse(top);
|
|
736
|
+
}
|
|
737
|
+
const NAME_JS = "function names(e){var raw=[e.getAttribute('aria-label'),e.textContent,e.getAttribute('title'),e.getAttribute('alt'),e.getAttribute('placeholder')];var out=[];for(var i=0;i<raw.length;i++){var s=(raw[i]||'').replace(/\\s+/g,' ').trim();if(s&&out.indexOf(s)===-1)out.push(s);}return out;}function dispName(e){var a=[e.getAttribute('aria-label'),e.textContent,e.getAttribute('title'),e.getAttribute('alt')];for(var i=0;i<a.length;i++){var s=(a[i]||'').replace(/\\s+/g,' ').trim();if(s)return s;}return '';}function pick(els,t){var i,n,j;for(i=0;i<els.length;i++){if(names(els[i]).indexOf(t)!==-1)return els[i];}for(i=0;i<els.length;i++){n=names(els[i]);for(j=0;j<n.length;j++){if(n[j].indexOf(t)!==-1)return els[i];}}return null;}";
|
|
738
|
+
const HITTABLE_JS = "function hittable(m,r){var cx=Math.round(r.x+r.width/2),cy=Math.round(r.y+r.height/2);if(!(r.width>0&&r.height>0&&document.elementFromPoint))return null;var hit=document.elementFromPoint(cx,cy);var ok=!!hit&&(hit===m||(m.contains&&m.contains(hit)));if(!ok&&document.elementsFromPoint){var top=document.elementsFromPoint(cx,cy)[0];ok=!!top&&(top===m||(m.contains&&m.contains(top)));}return ok?{cx:cx,cy:cy}:null;}";
|
|
739
|
+
const UNREACHABLE_JS = "function unreachable(m){var z=m.getBoundingClientRect();if(!z.width||!z.height)return 'it has no size — not shown yet (display:none?)';function d(e){var s=e.tagName.toLowerCase();if(e.id)s+='#'+e.id;var c=typeof e.className==='string'?e.className.trim().split(/\\s+/).slice(0,2).join('.'):'';if(c)s+='.'+c;var t=(e.textContent||'').replace(/\\s+/g,' ').trim().slice(0,40);return t?s+' \"'+t+'\"':s;}var x=m.closest('details:not([open])');if(x){var sm=x.querySelector('summary');if(!sm||!sm.contains(m)){var st=sm?(sm.textContent||'').replace(/\\s+/g,' ').trim().slice(0,40):'';return 'it is inside a closed <details> — open it first: click its summary'+(st?' \"'+st+'\"':'');}}var r=m.getBoundingClientRect(),top=document.elementsFromPoint?document.elementsFromPoint(r.x+r.width/2,r.y+r.height/2)[0]:null;if(!top)return 'its centre is outside the page';if(top.contains(m))return 'its centre reaches only its container ('+d(top)+'), so something there hides it';return 'its centre is covered by '+d(top);}";
|
|
740
|
+
const CLICK_TAIL_JS = `if(m.tagName==='SELECT')return 'SELECTINERT';` + HITTABLE_JS + "var r=m.getBoundingClientRect();if(r.top<0||r.bottom>window.innerHeight){m.scrollIntoView({block:'center',behavior:'instant'});r=m.getBoundingClientRect();}var b={x:Math.round(r.x),y:Math.round(r.y),w:Math.round(r.width),h:Math.round(r.height)};var p=hittable(m,r);if(p){b.cx=p.cx;b.cy=p.cy;return JSON.stringify(b);}m.click();return JSON.stringify(b);";
|
|
741
|
+
const CLICK_CANDIDATES = "button,a,[role=button],[role=link],[role=menuitem],input[type=submit],input[type=button]";
|
|
742
|
+
/** Clicked by text only when nothing in CLICK_CANDIDATES carries the name, so
|
|
743
|
+
* nothing that resolved before resolves differently: a <label> wrapping a
|
|
744
|
+
* checkbox or a radio — clicking it toggles its control, and its text is
|
|
745
|
+
* the only name such a control has ("I agree to the terms"). */
|
|
746
|
+
const CLICK_FALLBACK_CANDIDATES = "label:has(input[type=checkbox]),label:has(input[type=radio])";
|
|
747
|
+
const FIELD_CANDIDATES = "input,textarea,[contenteditable],[contenteditable=true],[role=textbox],[role=searchbox]";
|
|
748
|
+
const BOX_CANDIDATES = "button,a,[role=button],[role=link],[role=menuitem],[aria-label],[title],img[alt],li,[draggable=true]";
|
|
749
|
+
const SCROLL_CANDIDATES = "button,a,[role=button],[role=link],[role=heading],[aria-label],[title],h1,h2,h3,li,section,p";
|
|
750
|
+
function clickByTextJs(text) {
|
|
751
|
+
const t = JSON.stringify(text);
|
|
752
|
+
return `(function(){var t=${t};var els=Array.prototype.slice.call(document.querySelectorAll('${CLICK_CANDIDATES}'));` + NAME_JS + `var m=pick(els,t)||pick(Array.prototype.slice.call(document.querySelectorAll('${CLICK_FALLBACK_CANDIDATES}')),t);if(!m)return 'NOTFOUND';` + CLICK_TAIL_JS + `})()`;
|
|
753
|
+
}
|
|
754
|
+
function clickBySelectorJs(selector) {
|
|
755
|
+
const s = JSON.stringify(selector);
|
|
756
|
+
return `(function(){var m=document.querySelector(${s});if(!m)return 'NOTFOUND';` + CLICK_TAIL_JS + `})()`;
|
|
757
|
+
}
|
|
758
|
+
const FOCUS_STATE_JS = "function deepActive(){var a=document.activeElement;while(a&&a.shadowRoot&&a.shadowRoot.activeElement){a=a.shadowRoot.activeElement;}return a;}function editable(a){if(!a)return false;if(a.isContentEditable)return true;return typeof a.value==='string'&&!a.readOnly&&!a.disabled;}function withinTarget(a){var n=a;while(n){if(n===m||(m.contains&&m.contains(n)))return true;var rn=n.getRootNode?n.getRootNode():null;n=n.parentElement||((rn&&rn.host)?rn.host:null);}return false;}var ae=deepActive();var ok=!!ae&&(ae!==document.body||m===document.body)&&editable(ae)&&(withinTarget(ae)||(ae.isContentEditable&&ae.contains&&ae.contains(m)));";
|
|
759
|
+
const FOCUS_TAIL_JS = HITTABLE_JS + UNREACHABLE_JS + "var r=m.getBoundingClientRect();if(r.top<0||r.bottom>window.innerHeight){m.scrollIntoView({block:'center',behavior:'instant'});r=m.getBoundingClientRect();}var b={x:Math.round(r.x),y:Math.round(r.y),w:Math.round(r.width),h:Math.round(r.height)};m.focus();m.click();m.focus();" + FOCUS_STATE_JS + "b.f=ok?1:0;if(!ok){b.hit=hittable(m,m.getBoundingClientRect())?1:0;if(!b.hit)b.why=unreachable(m);}return JSON.stringify(b);";
|
|
760
|
+
function focusFieldByTextJs(text) {
|
|
761
|
+
const t = JSON.stringify(text);
|
|
762
|
+
return `(function(){var t=${t};var els=Array.prototype.slice.call(document.querySelectorAll('${FIELD_CANDIDATES}'));` + NAME_JS + "var m=pick(els,t);if(!m)return 'NOTFOUND';" + FOCUS_TAIL_JS + `})()`;
|
|
763
|
+
}
|
|
764
|
+
function focusSelectorJs(selector) {
|
|
765
|
+
const s = JSON.stringify(selector);
|
|
766
|
+
return `(function(){var m=document.querySelector(${s});if(!m)return 'NOTFOUND';` + FOCUS_TAIL_JS + `})()`;
|
|
767
|
+
}
|
|
768
|
+
function verifyFocusJs(target) {
|
|
769
|
+
if (!target.text && !target.selector) return `'0'`;
|
|
770
|
+
const resolve$1 = target.text ? `var els=Array.prototype.slice.call(document.querySelectorAll('${FIELD_CANDIDATES}'));` + NAME_JS + `var m=pick(els,${JSON.stringify(target.text)});` : `var m=document.querySelector(${JSON.stringify(target.selector ?? "")});`;
|
|
771
|
+
return `(function(){${resolve$1}if(!m)return '0';` + FOCUS_STATE_JS + "if(ok)return '1';return (!!ae&&ae!==document.body&&editable(ae))?'1':'0';})()";
|
|
772
|
+
}
|
|
773
|
+
function selectAllInFocusedJs() {
|
|
774
|
+
return "(function(){var el=document.activeElement;if(!el)return 'NOFOCUS';if(typeof el.select==='function'&&typeof el.value==='string'){el.select();return 'SEL';}if(el.isContentEditable){var r=document.createRange();r.selectNodeContents(el);var s=window.getSelection();s.removeAllRanges();s.addRange(r);return 'SEL';}return 'NOSEL';})()";
|
|
775
|
+
}
|
|
776
|
+
function boxSelectorJs(selector) {
|
|
777
|
+
const s = JSON.stringify(selector);
|
|
778
|
+
return `(function(){var m=document.querySelector(${s});if(!m)return 'NOTFOUND';var r=m.getBoundingClientRect();if(r.top<0||r.bottom>window.innerHeight){m.scrollIntoView({block:'center'});r=m.getBoundingClientRect();}return JSON.stringify({x:Math.round(r.x),y:Math.round(r.y),w:Math.round(r.width),h:Math.round(r.height)});})()`;
|
|
779
|
+
}
|
|
780
|
+
function boxByTextJs(text) {
|
|
781
|
+
const t = JSON.stringify(text);
|
|
782
|
+
return `(function(){var t=${t};var els=Array.prototype.slice.call(document.querySelectorAll('${BOX_CANDIDATES}'));` + NAME_JS + "var m=pick(els,t);if(!m)return 'NOTFOUND';var r=m.getBoundingClientRect();if(r.top<0||r.bottom>window.innerHeight){m.scrollIntoView({block:'center'});r=m.getBoundingClientRect();}return JSON.stringify({x:Math.round(r.x),y:Math.round(r.y),w:Math.round(r.width),h:Math.round(r.height)});})()";
|
|
783
|
+
}
|
|
784
|
+
const CLOSEST_ANCHOR_JS = "var a=m.closest('a[href]')||m.querySelector('a[href]');if(!a||!a.href)return 'NOTFOUND';return a.href;";
|
|
785
|
+
function hrefSelectorJs(selector) {
|
|
786
|
+
const s = JSON.stringify(selector);
|
|
787
|
+
return `(function(){var m=document.querySelector(${s});if(!m)return 'NOTFOUND';${CLOSEST_ANCHOR_JS}})()`;
|
|
788
|
+
}
|
|
789
|
+
function hrefByTextJs(text) {
|
|
790
|
+
const t = JSON.stringify(text);
|
|
791
|
+
return `(function(){var t=${t};var els=Array.prototype.slice.call(document.querySelectorAll('a,button,[role=link],[role=button],[aria-label],[title]'));` + NAME_JS + `var m=pick(els,t);if(!m)return 'NOTFOUND';${CLOSEST_ANCHOR_JS}})()`;
|
|
792
|
+
}
|
|
793
|
+
function scrollDeltaSelectorJs(selector) {
|
|
794
|
+
const s = JSON.stringify(selector);
|
|
795
|
+
return `(function(){var m=document.querySelector(${s});if(!m)return 'NOTFOUND';var r=m.getBoundingClientRect();return JSON.stringify({dy:Math.round(r.top+r.height/2-window.innerHeight/2)});})()`;
|
|
796
|
+
}
|
|
797
|
+
function scrollDeltaByTextJs(text) {
|
|
798
|
+
const t = JSON.stringify(text);
|
|
799
|
+
return `(function(){var t=${t};var els=Array.prototype.slice.call(document.querySelectorAll('${SCROLL_CANDIDATES}'));` + NAME_JS + "var m=pick(els,t);if(!m)return 'NOTFOUND';var r=m.getBoundingClientRect();return JSON.stringify({dy:Math.round(r.top+r.height/2-window.innerHeight/2)});})()";
|
|
800
|
+
}
|
|
801
|
+
function sampleAlong(pts, u) {
|
|
802
|
+
if (pts.length === 1) return pts[0];
|
|
803
|
+
const seg = [];
|
|
804
|
+
let total = 0;
|
|
805
|
+
for (let i = 0; i < pts.length - 1; i++) {
|
|
806
|
+
const d = Math.hypot(pts[i + 1].x - pts[i].x, pts[i + 1].y - pts[i].y);
|
|
807
|
+
seg.push(d);
|
|
808
|
+
total += d;
|
|
809
|
+
}
|
|
810
|
+
if (total === 0) return pts[0];
|
|
811
|
+
let target = u * total;
|
|
812
|
+
for (let i = 0; i < seg.length; i++) {
|
|
813
|
+
if (target <= seg[i] || i === seg.length - 1) {
|
|
814
|
+
const f = seg[i] > 0 ? target / seg[i] : 0;
|
|
815
|
+
return {
|
|
816
|
+
x: pts[i].x + (pts[i + 1].x - pts[i].x) * f,
|
|
817
|
+
y: pts[i].y + (pts[i + 1].y - pts[i].y) * f
|
|
818
|
+
};
|
|
819
|
+
}
|
|
820
|
+
target -= seg[i];
|
|
821
|
+
}
|
|
822
|
+
return pts[pts.length - 1];
|
|
823
|
+
}
|
|
824
|
+
async function ffprobe(path) {
|
|
825
|
+
const bin = await resolveFfprobe().catch(() => null);
|
|
826
|
+
if (!bin) return {};
|
|
827
|
+
return new Promise((res) => {
|
|
828
|
+
const c = spawn(bin, [
|
|
829
|
+
"-v",
|
|
830
|
+
"error",
|
|
831
|
+
"-select_streams",
|
|
832
|
+
"v:0",
|
|
833
|
+
"-show_entries",
|
|
834
|
+
"stream=width,height,r_frame_rate,duration",
|
|
835
|
+
"-show_entries",
|
|
836
|
+
"format=duration",
|
|
837
|
+
"-of",
|
|
838
|
+
"json",
|
|
839
|
+
path
|
|
840
|
+
], { stdio: [
|
|
841
|
+
"ignore",
|
|
842
|
+
"pipe",
|
|
843
|
+
"ignore"
|
|
844
|
+
] });
|
|
845
|
+
let out = "";
|
|
846
|
+
c.stdout.on("data", (d) => {
|
|
847
|
+
out += d;
|
|
848
|
+
});
|
|
849
|
+
c.on("close", () => {
|
|
850
|
+
try {
|
|
851
|
+
const j = JSON.parse(out);
|
|
852
|
+
const s = j.streams?.[0] ?? {};
|
|
853
|
+
res({
|
|
854
|
+
width: s.width,
|
|
855
|
+
height: s.height,
|
|
856
|
+
fps: s.r_frame_rate,
|
|
857
|
+
durationS: Number(s.duration ?? j.format?.duration ?? 0)
|
|
858
|
+
});
|
|
859
|
+
} catch {
|
|
860
|
+
res({});
|
|
861
|
+
}
|
|
862
|
+
});
|
|
863
|
+
});
|
|
864
|
+
}
|
|
865
|
+
/** Drive `plan` against the live app over CDP, return the ground-truth log. */
|
|
866
|
+
async function captureTake(plan, opts) {
|
|
867
|
+
const { captureTakeCDP: captureTakeCDP$1 } = await import("./cdp-capture-ryEVA9lz.js");
|
|
868
|
+
return captureTakeCDP$1(plan, {
|
|
869
|
+
...opts,
|
|
870
|
+
fps: opts.fps ?? 60
|
|
871
|
+
});
|
|
872
|
+
}
|
|
873
|
+
function listInteractiveJs() {
|
|
874
|
+
return `(function(){` + NAME_JS + "var sel='button,a,[role=button],[role=link],[role=menuitem],[role=tab],[role=switch],[role=checkbox],input,select,textarea';var els=Array.prototype.slice.call(document.querySelectorAll(sel));var vw=window.innerWidth,vh=window.innerHeight;var out=[];var seen={};for(var i=0;i<els.length;i++){var e=els[i];var n=dispName(e);var ph=e.getAttribute('placeholder');var r=e.getBoundingClientRect();if(r.width<6||r.height<6)continue;if(!n&&!ph)continue;var label=n||('['+(ph||e.tagName.toLowerCase())+']');var key=label+'@'+Math.round(r.x)+','+Math.round(r.y);if(seen[key])continue;seen[key]=1;var iv=r.top<vh&&r.bottom>0&&r.left<vw&&r.right>0;out.push({name:label,tag:e.tagName.toLowerCase(),role:e.getAttribute('role')||null,href:e.getAttribute('href')||null,inView:iv,x:Math.round(r.x),y:Math.round(r.y),w:Math.round(r.width),h:Math.round(r.height)});}out.sort(function(a,b){return (b.inView?1:0)-(a.inView?1:0);});return JSON.stringify(out.slice(0,60));})()";
|
|
875
|
+
}
|
|
876
|
+
/** Open `url`, return its interactive elements (accessible name + bbox) —
|
|
877
|
+
* what an agent uses to choose a demo flow. Pure CDP, same as capture, so
|
|
878
|
+
* the reported coordinate space matches what capture will drive against. */
|
|
879
|
+
async function inspectPage(url, opts = {}) {
|
|
880
|
+
const vw = opts.viewport?.width ?? 1920;
|
|
881
|
+
const vh = opts.viewport?.height ?? 1080;
|
|
882
|
+
const browser = await launchBrowser({
|
|
883
|
+
width: vw,
|
|
884
|
+
height: vh,
|
|
885
|
+
chromePath: opts.chromePath,
|
|
886
|
+
...opts.userDataDir ? { userDataDir: opts.userDataDir } : {},
|
|
887
|
+
...opts.headless === false ? { headless: false } : {}
|
|
888
|
+
});
|
|
889
|
+
try {
|
|
890
|
+
const { cdp } = browser;
|
|
891
|
+
await cdp.send("Page.enable");
|
|
892
|
+
await cdp.send("Runtime.enable");
|
|
893
|
+
const inner = await fitViewport(cdp, browser.targetId, vw, vh);
|
|
894
|
+
const nav = await cdp.send("Page.navigate", { url });
|
|
895
|
+
if (nav.errorText) throw new Error(`inspectPage: ${url} did not answer (${nav.errorText}) — is the app running?`);
|
|
896
|
+
await sleep$3(opts.warmupMs ?? 1500);
|
|
897
|
+
const evalRaw = async (expr) => {
|
|
898
|
+
const r = await cdp.send("Runtime.evaluate", {
|
|
899
|
+
expression: expr,
|
|
900
|
+
returnByValue: true
|
|
901
|
+
});
|
|
902
|
+
return String(r.result?.value ?? "");
|
|
903
|
+
};
|
|
904
|
+
let elements = [];
|
|
905
|
+
try {
|
|
906
|
+
const v = evalValue(await evalRaw(listInteractiveJs()));
|
|
907
|
+
if (Array.isArray(v)) elements = v;
|
|
908
|
+
} catch {}
|
|
909
|
+
const title = await evalRaw("document.title").catch(() => "");
|
|
910
|
+
const finalUrl = await evalRaw("location.href").catch(() => "") || url;
|
|
911
|
+
return {
|
|
912
|
+
url,
|
|
913
|
+
finalUrl,
|
|
914
|
+
title,
|
|
915
|
+
viewport: {
|
|
916
|
+
w: inner[0],
|
|
917
|
+
h: inner[1]
|
|
918
|
+
},
|
|
919
|
+
elements
|
|
920
|
+
};
|
|
921
|
+
} finally {
|
|
922
|
+
await browser.close();
|
|
923
|
+
}
|
|
924
|
+
}
|
|
925
|
+
function selectOptionJs(target, value) {
|
|
926
|
+
const sel = JSON.stringify(target.selector ?? "");
|
|
927
|
+
const name = JSON.stringify(target.text ?? "");
|
|
928
|
+
const v = JSON.stringify(value);
|
|
929
|
+
return `(function(){var s=${sel},n=${name},want=${v};var m=null;if(s){m=document.querySelector(s);}else if(n){var els=Array.prototype.slice.call(document.querySelectorAll('select'));m=els.find(function(e){var a=(e.getAttribute('aria-label')||'').trim();if(a===n)return true;var id=e.id;if(id){var l=document.querySelector('label[for="'+id+'"]');if(l&&(l.textContent||'').trim().indexOf(n)>=0)return true;}var p=e.closest('label');if(p&&(p.textContent||'').trim().indexOf(n)>=0)return true;return false;})||null;}if(!m)return 'NOTFOUND';if(m.tagName!=='SELECT')return 'NOTASELECT';var opts=Array.prototype.slice.call(m.options);var norm=function(x){return (x||'').replace(/\\s+/g,'').trim();};var o=opts.find(function(x){return x.value===want;})||opts.find(function(x){return norm(x.textContent)===norm(want);})||opts.find(function(x){return norm(x.textContent).indexOf(norm(want))>=0;});if(!o)return 'NOOPTION';var r=m.getBoundingClientRect();if(r.top<0||r.bottom>window.innerHeight){m.scrollIntoView({block:'center'});r=m.getBoundingClientRect();}m.focus();m.value=o.value;m.dispatchEvent(new Event('input',{bubbles:true}));m.dispatchEvent(new Event('change',{bubbles:true}));var b={x:Math.round(r.x),y:Math.round(r.y),w:Math.round(r.width),h:Math.round(r.height)};return JSON.stringify(b);})()`;
|
|
930
|
+
}
|
|
931
|
+
|
|
932
|
+
//#endregion
|
|
933
|
+
//#region src/tool.ts
|
|
934
|
+
function runBuffer(bin, args) {
|
|
935
|
+
return new Promise((ok, fail) => {
|
|
936
|
+
const p = spawn(bin, args, { stdio: [
|
|
937
|
+
"ignore",
|
|
938
|
+
"pipe",
|
|
939
|
+
"pipe"
|
|
940
|
+
] });
|
|
941
|
+
const chunks = [];
|
|
942
|
+
let err = "";
|
|
943
|
+
p.stdout.on("data", (d) => chunks.push(d));
|
|
944
|
+
p.stderr.on("data", (d) => {
|
|
945
|
+
err = (err + d.toString()).slice(-2e3);
|
|
946
|
+
});
|
|
947
|
+
p.on("error", fail);
|
|
948
|
+
p.on("close", (code) => code === 0 ? ok(Buffer.concat(chunks)) : fail(new Error(`${bin} exited ${code}: ${err.trim().slice(-400)}`)));
|
|
949
|
+
});
|
|
950
|
+
}
|
|
951
|
+
|
|
952
|
+
//#endregion
|
|
953
|
+
//#region src/dom-state.ts
|
|
954
|
+
const sleep$2 = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
955
|
+
/** Hard cap on the element index — a page past it is a data table, not a UI. */
|
|
956
|
+
const DOM_STATE_MAX_ELEMENTS = 3e3;
|
|
957
|
+
/** A state whose re-render reaches this PSNR against the live screenshot is
|
|
958
|
+
* trusted; below it the film uses the video. */
|
|
959
|
+
const DOM_STATE_PSNR_OK = 30;
|
|
960
|
+
/** Runs in the live page (Runtime.evaluate, returnByValue) and returns the
|
|
961
|
+
* probe as a JSON string. Reads only: no attribute, style or node is touched
|
|
962
|
+
* — the app is being filmed and must behave exactly as without states. */
|
|
963
|
+
const DOM_STATE_PROBE_JS = `(() => {
|
|
964
|
+
try {
|
|
965
|
+
const vw = innerWidth, vh = innerHeight, dpr = devicePixelRatio || 1;
|
|
966
|
+
const CAP = ${DOM_STATE_MAX_ELEMENTS};
|
|
967
|
+
// never listed (invisible by nature) — but they DO count as siblings when they survive serialization
|
|
968
|
+
const SKIP = { script: 1, style: 1, link: 1, meta: 1, noscript: 1, head: 1, title: 1, template: 1 };
|
|
969
|
+
// what Chrome's MHTML serializer drops: these never count as siblings (see the module header)
|
|
970
|
+
const survives = (el) => {
|
|
971
|
+
const t = el.localName;
|
|
972
|
+
if (t === "script" || t === "noscript") return false;
|
|
973
|
+
if (el.hasAttribute("hidden")) return false;
|
|
974
|
+
if (t === "input" && (el.getAttribute("type") || "").toLowerCase() === "hidden") return false;
|
|
975
|
+
return true;
|
|
976
|
+
};
|
|
977
|
+
// containers never take their name from content (a page-sized div would name itself after the page)
|
|
978
|
+
const CONTAINER = { div: 1, section: 1, article: 1, main: 1, nav: 1, header: 1, footer: 1, aside: 1, form: 1, ul: 1, ol: 1, table: 1, tbody: 1, thead: 1, tfoot: 1, tr: 1, fieldset: 1, dialog: 1, body: 1, html: 1, figure: 1, details: 1, menu: 1, dl: 1 };
|
|
979
|
+
const HEADING = { h1: 1, h2: 1, h3: 1, h4: 1, h5: 1, h6: 1 };
|
|
980
|
+
const INTERACTIVE_ROLE = { button: 1, link: 1, tab: 1, menuitem: 1, checkbox: 1, switch: 1, radio: 1, option: 1, combobox: 1, textbox: 1, searchbox: 1, slider: 1, spinbutton: 1, menuitemcheckbox: 1, menuitemradio: 1 };
|
|
981
|
+
const collapse = (s) => (s || "").replace(/\\s+/g, " ").trim().slice(0, 80);
|
|
982
|
+
const ownText = (el) => { let s = ""; for (const n of el.childNodes) if (n.nodeType === 3) s += n.data; return collapse(s); };
|
|
983
|
+
const implicitRole = (el) => {
|
|
984
|
+
const t = el.localName;
|
|
985
|
+
switch (t) {
|
|
986
|
+
case "a": case "area": return el.hasAttribute("href") ? "link" : null;
|
|
987
|
+
case "button": case "summary": return "button";
|
|
988
|
+
case "input": {
|
|
989
|
+
const ty = (el.getAttribute("type") || "text").toLowerCase();
|
|
990
|
+
if (ty === "checkbox") return "checkbox";
|
|
991
|
+
if (ty === "radio") return "radio";
|
|
992
|
+
if (ty === "range") return "slider";
|
|
993
|
+
if (ty === "number") return "spinbutton";
|
|
994
|
+
if (ty === "search") return "searchbox";
|
|
995
|
+
if (ty === "button" || ty === "submit" || ty === "reset" || ty === "image") return "button";
|
|
996
|
+
return "textbox";
|
|
997
|
+
}
|
|
998
|
+
case "select": return el.multiple || el.size > 1 ? "listbox" : "combobox";
|
|
999
|
+
case "textarea": return "textbox";
|
|
1000
|
+
case "img": case "svg": return "img";
|
|
1001
|
+
case "ul": case "ol": case "menu": return "list";
|
|
1002
|
+
case "li": return "listitem";
|
|
1003
|
+
case "nav": return "navigation";
|
|
1004
|
+
case "main": return "main";
|
|
1005
|
+
case "header": return "banner";
|
|
1006
|
+
case "footer": return "contentinfo";
|
|
1007
|
+
case "aside": return "complementary";
|
|
1008
|
+
case "form": return "form";
|
|
1009
|
+
case "table": return "table";
|
|
1010
|
+
case "tr": return "row";
|
|
1011
|
+
case "td": return "cell";
|
|
1012
|
+
case "th": return "columnheader";
|
|
1013
|
+
case "dialog": return "dialog";
|
|
1014
|
+
case "option": return "option";
|
|
1015
|
+
case "progress": return "progressbar";
|
|
1016
|
+
case "hr": return "separator";
|
|
1017
|
+
case "article": return "article";
|
|
1018
|
+
case "fieldset": case "details": return "group";
|
|
1019
|
+
case "output": return "status";
|
|
1020
|
+
case "section": return el.hasAttribute("aria-label") || el.hasAttribute("aria-labelledby") ? "region" : null;
|
|
1021
|
+
default: return HEADING[t] ? "heading" : null;
|
|
1022
|
+
}
|
|
1023
|
+
};
|
|
1024
|
+
const isInteractive = (el, role) => {
|
|
1025
|
+
const t = el.localName;
|
|
1026
|
+
if (t === "a" || t === "button" || t === "input" || t === "select" || t === "textarea" || t === "summary") return true;
|
|
1027
|
+
if (role && INTERACTIVE_ROLE[role]) return true;
|
|
1028
|
+
const ce = el.getAttribute("contenteditable");
|
|
1029
|
+
if (ce != null && ce !== "false") return true;
|
|
1030
|
+
const ti = el.getAttribute("tabindex");
|
|
1031
|
+
if (ti != null && Number(ti) >= 0) return true;
|
|
1032
|
+
return false;
|
|
1033
|
+
};
|
|
1034
|
+
const nameOf = (el, interactive) => {
|
|
1035
|
+
const al = el.getAttribute("aria-label"); if (al && al.trim()) return collapse(al);
|
|
1036
|
+
const lb = el.getAttribute("aria-labelledby");
|
|
1037
|
+
if (lb) { let s = ""; for (const id of lb.split(/\\s+/)) { const r = document.getElementById(id); if (r) s += " " + r.textContent; } if (s.trim()) return collapse(s); }
|
|
1038
|
+
const alt = el.getAttribute("alt"); if (alt && alt.trim()) return collapse(alt);
|
|
1039
|
+
const ti = el.getAttribute("title"); if (ti && ti.trim()) return collapse(ti);
|
|
1040
|
+
const ph = el.getAttribute("placeholder"); if (ph && ph.trim()) return collapse(ph);
|
|
1041
|
+
if (el.labels && el.labels.length) { const s = collapse(el.labels[0].textContent); if (s) return s; }
|
|
1042
|
+
if (el.localName === "input") {
|
|
1043
|
+
const ty = (el.getAttribute("type") || "").toLowerCase();
|
|
1044
|
+
if (ty === "submit" || ty === "button" || ty === "reset") { const v = el.getAttribute("value"); if (v) return collapse(v); }
|
|
1045
|
+
}
|
|
1046
|
+
if (el.localName === "select") { const o = el.selectedOptions && el.selectedOptions[0]; return o ? collapse(o.textContent) : ""; }
|
|
1047
|
+
if (interactive || !CONTAINER[el.localName]) { const s = collapse(el.textContent); if (s) return s; }
|
|
1048
|
+
return "";
|
|
1049
|
+
};
|
|
1050
|
+
const elements = [], scrolled = [], inputs = [], canvases = [], videos = [];
|
|
1051
|
+
// a copy that came out empty (a WebGL canvas that does not keep its
|
|
1052
|
+
// drawing buffer reads back transparent): one colour over 16×16 samples
|
|
1053
|
+
const blankImage = (img) => {
|
|
1054
|
+
try {
|
|
1055
|
+
const c = document.createElement("canvas"); c.width = 16; c.height = 16;
|
|
1056
|
+
const x = c.getContext("2d", { willReadFrequently: true }); x.drawImage(img, 0, 0, 16, 16);
|
|
1057
|
+
const d = x.getImageData(0, 0, 16, 16).data;
|
|
1058
|
+
for (let i = 4; i < d.length; i += 4)
|
|
1059
|
+
if (d[i] !== d[0] || d[i + 1] !== d[1] || d[i + 2] !== d[2] || d[i + 3] !== d[3]) return false;
|
|
1060
|
+
return true;
|
|
1061
|
+
} catch (e) { return false; }
|
|
1062
|
+
};
|
|
1063
|
+
const custom = new Map();
|
|
1064
|
+
const idOf = new Map();
|
|
1065
|
+
let count = 0;
|
|
1066
|
+
const visit = (el, path) => {
|
|
1067
|
+
const t = el.localName;
|
|
1068
|
+
if (t === "head") return; // nothing visible lives there
|
|
1069
|
+
if (t.indexOf("-") > 0 && customElements.get(t)) custom.set(t, "");
|
|
1070
|
+
const isAttr = el.getAttribute("is");
|
|
1071
|
+
if (isAttr && customElements.get(isAttr)) custom.set(isAttr, t);
|
|
1072
|
+
if (!SKIP[t]) {
|
|
1073
|
+
const cs = getComputedStyle(el);
|
|
1074
|
+
if (cs.display === "none") return; // no boxes below either
|
|
1075
|
+
if (parseFloat(cs.opacity) === 0) return; // subtree invisible
|
|
1076
|
+
const r = el.getBoundingClientRect();
|
|
1077
|
+
// checkVisibility: content skipped by content-visibility (a closed
|
|
1078
|
+
// <details>' rows keep boxes but are not drawn) is not on screen
|
|
1079
|
+
const drawn = typeof el.checkVisibility !== "function" || el.checkVisibility();
|
|
1080
|
+
const onScreen = drawn && cs.visibility === "visible" && r.width > 0 && r.height > 0 && r.right > 0 && r.bottom > 0 && r.left < vw && r.top < vh;
|
|
1081
|
+
if (count < CAP && onScreen) {
|
|
1082
|
+
const role = (el.getAttribute("role") || "").trim().split(/\\s+/)[0] || implicitRole(el);
|
|
1083
|
+
const interactive = isInteractive(el, role);
|
|
1084
|
+
const id = "e" + count++;
|
|
1085
|
+
const item = { id, path, tag: t };
|
|
1086
|
+
if (role) item.role = role;
|
|
1087
|
+
const name = nameOf(el, interactive); if (name) item.name = name;
|
|
1088
|
+
const text = ownText(el); if (text) item.text = text;
|
|
1089
|
+
item.box = [Math.round(r.left), Math.round(r.top), Math.round(r.width), Math.round(r.height)];
|
|
1090
|
+
if (cs.position === "fixed" || cs.position === "sticky") item.fixed = true;
|
|
1091
|
+
if (interactive) item.interactive = true;
|
|
1092
|
+
elements.push(item);
|
|
1093
|
+
idOf.set(el, id);
|
|
1094
|
+
}
|
|
1095
|
+
if ((el.scrollTop || el.scrollLeft) && el !== document.scrollingElement && el !== document.body)
|
|
1096
|
+
scrolled.push({ path, top: el.scrollTop, left: el.scrollLeft });
|
|
1097
|
+
if (t === "input") {
|
|
1098
|
+
const ty = (el.getAttribute("type") || "text").toLowerCase();
|
|
1099
|
+
if (ty === "checkbox" || ty === "radio") inputs.push({ path, checked: !!el.checked });
|
|
1100
|
+
else if (ty !== "file") inputs.push({ path, value: ty === "password" ? "x".repeat(el.value.length) : el.value });
|
|
1101
|
+
} else if (t === "textarea") inputs.push({ path, value: el.value });
|
|
1102
|
+
else if (t === "select") {
|
|
1103
|
+
const selected = [];
|
|
1104
|
+
for (let i = 0; i < el.options.length; i++) if (el.options[i].selected) selected.push(i);
|
|
1105
|
+
inputs.push({ path, selected });
|
|
1106
|
+
}
|
|
1107
|
+
// pixels are copied only for what is on screen, at the size it is
|
|
1108
|
+
// shown (× the pixel ratio): encoding runs on the app's main thread,
|
|
1109
|
+
// and a hidden 4K <video> behind a canvas stage cost a 5.7 s freeze
|
|
1110
|
+
else if (t === "canvas") {
|
|
1111
|
+
if (onScreen && el.width > 0 && el.height > 0) {
|
|
1112
|
+
try {
|
|
1113
|
+
const w = Math.min(el.width, Math.ceil(r.width * dpr)), h = Math.min(el.height, Math.ceil(r.height * dpr));
|
|
1114
|
+
let src = el;
|
|
1115
|
+
if (w < el.width || h < el.height) { src = document.createElement("canvas"); src.width = w; src.height = h; src.getContext("2d").drawImage(el, 0, 0, w, h); }
|
|
1116
|
+
canvases.push({ path, dataUrl: src.toDataURL("image/png"), box: [r.left, r.top, r.width, r.height], blank: blankImage(src) });
|
|
1117
|
+
} catch (e) {}
|
|
1118
|
+
}
|
|
1119
|
+
} else if (t === "video") {
|
|
1120
|
+
try {
|
|
1121
|
+
if (onScreen && el.videoWidth > 0 && el.videoHeight > 0) {
|
|
1122
|
+
const c = document.createElement("canvas");
|
|
1123
|
+
c.width = Math.min(el.videoWidth, Math.ceil(r.width * dpr)); c.height = Math.min(el.videoHeight, Math.ceil(r.height * dpr));
|
|
1124
|
+
c.getContext("2d").drawImage(el, 0, 0, c.width, c.height);
|
|
1125
|
+
// a frame of video is opaque: JPEG encodes it an order of magnitude faster than PNG
|
|
1126
|
+
videos.push({ path, dataUrl: c.toDataURL("image/jpeg", 0.92), box: [r.left, r.top, r.width, r.height], blank: blankImage(c) });
|
|
1127
|
+
}
|
|
1128
|
+
} catch (e) {}
|
|
1129
|
+
}
|
|
1130
|
+
}
|
|
1131
|
+
if (t === "svg") return; // internals are never targets; keeps icon-heavy pages under the cap
|
|
1132
|
+
let i = 0;
|
|
1133
|
+
for (const c of el.children) { if (!survives(c)) continue; visit(c, path.concat(i)); i++; }
|
|
1134
|
+
};
|
|
1135
|
+
visit(document.documentElement, []);
|
|
1136
|
+
|
|
1137
|
+
// layers: from <body> descend through single big-child wrappers; a container
|
|
1138
|
+
// covering > 50% of the viewport is split into its big in-view children;
|
|
1139
|
+
// fixed/sticky and higher z-index sort on top
|
|
1140
|
+
const areaOf = (el) => { const r = el.getBoundingClientRect(); return Math.max(0, r.width) * Math.max(0, r.height); };
|
|
1141
|
+
const big = (el) => !SKIP[el.localName] && survives(el) && areaOf(el) >= 0.03 * vw * vh && getComputedStyle(el).display !== "none";
|
|
1142
|
+
const bigKids = (n) => Array.from(n.children).filter(big);
|
|
1143
|
+
const inView = (el) => { const r = el.getBoundingClientRect(); return r.top < vh && r.bottom > 0 && r.left < vw && r.right > 0; };
|
|
1144
|
+
let node = document.body, guard = 0;
|
|
1145
|
+
while (node && bigKids(node).length === 1 && guard++ < 8) node = bigKids(node)[0];
|
|
1146
|
+
const split = (k, depth) => {
|
|
1147
|
+
const cs = getComputedStyle(k);
|
|
1148
|
+
if (depth > 4 || cs.position === "fixed" || cs.position === "sticky" || areaOf(k) <= 0.5 * vw * vh) return [k];
|
|
1149
|
+
const sub = bigKids(k).filter(inView);
|
|
1150
|
+
if (sub.length >= 2) return sub;
|
|
1151
|
+
if (sub.length === 1) return split(sub[0], depth + 1);
|
|
1152
|
+
return [k];
|
|
1153
|
+
};
|
|
1154
|
+
const score = (el) => { const cs = getComputedStyle(el); return (cs.position === "fixed" || cs.position === "sticky" ? 1000 : 0) + (Number(cs.zIndex) || 0); };
|
|
1155
|
+
const kids = node ? bigKids(node).flatMap((k) => split(k, 0)).filter(inView) : [];
|
|
1156
|
+
const layers = [];
|
|
1157
|
+
for (const { el } of kids.map((el, i) => ({ el, i, s: score(el) })).sort((a, b) => a.s - b.s || a.i - b.i)) {
|
|
1158
|
+
const id = idOf.get(el);
|
|
1159
|
+
if (id && layers.length < 8) layers.push(id);
|
|
1160
|
+
}
|
|
1161
|
+
|
|
1162
|
+
// animated: the CURRENT computed value of every property an animation or
|
|
1163
|
+
// transition drives — the saved page runs no animations (animation: none),
|
|
1164
|
+
// so without this a finished "fadeIn forwards" would show its base style
|
|
1165
|
+
const pathOf = (el) => {
|
|
1166
|
+
const p = [];
|
|
1167
|
+
let n = el;
|
|
1168
|
+
while (n !== document.documentElement) {
|
|
1169
|
+
const par = n.parentElement;
|
|
1170
|
+
if (!par || !survives(n)) return null; // detached, hidden, or inside a shadow root
|
|
1171
|
+
let i = 0;
|
|
1172
|
+
for (const c of par.children) { if (c === n) break; if (survives(c)) i++; }
|
|
1173
|
+
p.push(i);
|
|
1174
|
+
n = par;
|
|
1175
|
+
}
|
|
1176
|
+
return p.reverse();
|
|
1177
|
+
};
|
|
1178
|
+
const animated = [];
|
|
1179
|
+
try {
|
|
1180
|
+
const byEl = new Map();
|
|
1181
|
+
for (const a of document.getAnimations()) {
|
|
1182
|
+
const ef = a.effect;
|
|
1183
|
+
if (!ef || typeof ef.getKeyframes !== "function") continue;
|
|
1184
|
+
const target = ef.target;
|
|
1185
|
+
if (!(target instanceof Element) || ef.pseudoElement) continue;
|
|
1186
|
+
let styles = byEl.get(target);
|
|
1187
|
+
if (!styles) { styles = {}; byEl.set(target, styles); }
|
|
1188
|
+
const cs = getComputedStyle(target);
|
|
1189
|
+
for (const kf of ef.getKeyframes()) for (const k in kf) {
|
|
1190
|
+
if (k === "offset" || k === "easing" || k === "composite" || k === "computedOffset") continue;
|
|
1191
|
+
const prop = k === "cssFloat" ? "float" : k === "cssOffset" ? "offset" : k.startsWith("--") ? k : k.replace(/[A-Z]/g, (m) => "-" + m.toLowerCase());
|
|
1192
|
+
styles[prop] = cs.getPropertyValue(prop);
|
|
1193
|
+
}
|
|
1194
|
+
}
|
|
1195
|
+
for (const [el, styles] of byEl) {
|
|
1196
|
+
const path = pathOf(el);
|
|
1197
|
+
if (path && Object.keys(styles).length) animated.push({ path, styles });
|
|
1198
|
+
}
|
|
1199
|
+
} catch (e) {}
|
|
1200
|
+
|
|
1201
|
+
const active = document.activeElement;
|
|
1202
|
+
const focus = active && active !== document.body && active !== document.documentElement ? pathOf(active) : null;
|
|
1203
|
+
return JSON.stringify({
|
|
1204
|
+
url: location.href,
|
|
1205
|
+
title: document.title,
|
|
1206
|
+
viewport: { w: vw, h: vh, dpr: devicePixelRatio },
|
|
1207
|
+
scroll: { x: Math.round(scrollX), y: Math.round(scrollY) },
|
|
1208
|
+
elements, layers, scrolled, inputs, canvases, videos, animated,
|
|
1209
|
+
custom: Array.from(custom, ([name, ext]) => (ext ? { name, extends: ext } : { name })),
|
|
1210
|
+
...(focus ? { focus } : {}),
|
|
1211
|
+
});
|
|
1212
|
+
} catch (e) {
|
|
1213
|
+
return JSON.stringify({ error: String(e && e.message || e) });
|
|
1214
|
+
}
|
|
1215
|
+
})()`;
|
|
1216
|
+
function parseHeaders(text) {
|
|
1217
|
+
const headers = {};
|
|
1218
|
+
const lines = text.replace(/\r?\n[ \t]+/g, " ").split(/\r?\n/);
|
|
1219
|
+
for (const line of lines) {
|
|
1220
|
+
const c = line.indexOf(":");
|
|
1221
|
+
if (c <= 0) continue;
|
|
1222
|
+
headers[line.slice(0, c).trim().toLowerCase()] = line.slice(c + 1).trim();
|
|
1223
|
+
}
|
|
1224
|
+
return headers;
|
|
1225
|
+
}
|
|
1226
|
+
/** quoted-printable → bytes (soft line breaks removed, `=XX` decoded) */
|
|
1227
|
+
function decodeQuotedPrintable(text) {
|
|
1228
|
+
const out = [];
|
|
1229
|
+
for (let i = 0; i < text.length; i++) {
|
|
1230
|
+
const ch = text.charCodeAt(i);
|
|
1231
|
+
if (ch === 61) {
|
|
1232
|
+
const a = text[i + 1];
|
|
1233
|
+
const b = text[i + 2];
|
|
1234
|
+
if (a === "\r" && b === "\n") {
|
|
1235
|
+
i += 2;
|
|
1236
|
+
continue;
|
|
1237
|
+
}
|
|
1238
|
+
if (a === "\n") {
|
|
1239
|
+
i += 1;
|
|
1240
|
+
continue;
|
|
1241
|
+
}
|
|
1242
|
+
if (a != null && b != null && /^[0-9A-Fa-f]{2}$/.test(a + b)) {
|
|
1243
|
+
out.push(parseInt(a + b, 16));
|
|
1244
|
+
i += 2;
|
|
1245
|
+
continue;
|
|
1246
|
+
}
|
|
1247
|
+
}
|
|
1248
|
+
out.push(ch & 255);
|
|
1249
|
+
}
|
|
1250
|
+
return Buffer.from(out);
|
|
1251
|
+
}
|
|
1252
|
+
/** Parse a multipart/related MHTML file (what `Page.captureSnapshot` returns). */
|
|
1253
|
+
function parseMhtml(raw) {
|
|
1254
|
+
const text = typeof raw === "string" ? raw : raw.toString("latin1");
|
|
1255
|
+
const headEnd = text.search(/\r?\n\r?\n/);
|
|
1256
|
+
if (headEnd < 0) throw new Error("mhtml: no header block");
|
|
1257
|
+
const headers = parseHeaders(text.slice(0, headEnd));
|
|
1258
|
+
const ct = headers["content-type"] ?? "";
|
|
1259
|
+
const bm = /boundary="([^"]+)"|boundary=([^;\s]+)/i.exec(ct);
|
|
1260
|
+
const boundary = bm?.[1] ?? bm?.[2];
|
|
1261
|
+
if (!boundary) throw new Error("mhtml: no multipart boundary");
|
|
1262
|
+
const parts = [];
|
|
1263
|
+
const delimiter = `--${boundary}`;
|
|
1264
|
+
const chunks = text.split(new RegExp(`(?:^|\\r?\\n)${delimiter.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`));
|
|
1265
|
+
for (const chunk of chunks.slice(1)) {
|
|
1266
|
+
if (chunk.startsWith("--")) break;
|
|
1267
|
+
const body0 = chunk.search(/\r?\n\r?\n/);
|
|
1268
|
+
if (body0 < 0) continue;
|
|
1269
|
+
const h = parseHeaders(chunk.slice(0, body0));
|
|
1270
|
+
const bodyText = chunk.slice(body0).replace(/^\r?\n\r?\n/, "");
|
|
1271
|
+
const encoding = (h["content-transfer-encoding"] ?? "binary").toLowerCase();
|
|
1272
|
+
let body;
|
|
1273
|
+
if (encoding === "quoted-printable") body = decodeQuotedPrintable(bodyText);
|
|
1274
|
+
else if (encoding === "base64") body = Buffer.from(bodyText.replace(/\s+/g, ""), "base64");
|
|
1275
|
+
else body = Buffer.from(bodyText, "latin1");
|
|
1276
|
+
const idRaw = h["content-id"];
|
|
1277
|
+
parts.push({
|
|
1278
|
+
contentType: (h["content-type"] ?? "application/octet-stream").split(";")[0].trim().toLowerCase(),
|
|
1279
|
+
...h["content-location"] ? { location: h["content-location"] } : {},
|
|
1280
|
+
...idRaw ? { id: idRaw.replace(/^<|>$/g, "") } : {},
|
|
1281
|
+
body
|
|
1282
|
+
});
|
|
1283
|
+
}
|
|
1284
|
+
return parts;
|
|
1285
|
+
}
|
|
1286
|
+
const EXT_BY_TYPE = {
|
|
1287
|
+
"text/html": "html",
|
|
1288
|
+
"text/css": "css",
|
|
1289
|
+
"image/png": "png",
|
|
1290
|
+
"image/jpeg": "jpg",
|
|
1291
|
+
"image/gif": "gif",
|
|
1292
|
+
"image/webp": "webp",
|
|
1293
|
+
"image/avif": "avif",
|
|
1294
|
+
"image/svg+xml": "svg",
|
|
1295
|
+
"image/x-icon": "ico",
|
|
1296
|
+
"image/vnd.microsoft.icon": "ico",
|
|
1297
|
+
"image/bmp": "bmp",
|
|
1298
|
+
"font/woff2": "woff2",
|
|
1299
|
+
"application/font-woff2": "woff2",
|
|
1300
|
+
"font/woff": "woff",
|
|
1301
|
+
"application/font-woff": "woff",
|
|
1302
|
+
"font/ttf": "ttf",
|
|
1303
|
+
"application/x-font-ttf": "ttf",
|
|
1304
|
+
"font/otf": "otf",
|
|
1305
|
+
"font/collection": "ttc",
|
|
1306
|
+
"application/x-font-opentype": "otf",
|
|
1307
|
+
"video/mp4": "mp4",
|
|
1308
|
+
"video/webm": "webm",
|
|
1309
|
+
"audio/mpeg": "mp3",
|
|
1310
|
+
"application/pdf": "pdf",
|
|
1311
|
+
"text/javascript": "js",
|
|
1312
|
+
"application/javascript": "js",
|
|
1313
|
+
"application/json": "json"
|
|
1314
|
+
};
|
|
1315
|
+
function extFor(part) {
|
|
1316
|
+
const byType = EXT_BY_TYPE[part.contentType];
|
|
1317
|
+
if (byType) return byType;
|
|
1318
|
+
if (part.location && !part.location.startsWith("cid:")) try {
|
|
1319
|
+
const e = extname(new URL(part.location).pathname).slice(1).toLowerCase();
|
|
1320
|
+
if (/^[a-z0-9]{1,5}$/.test(e)) return e;
|
|
1321
|
+
} catch {}
|
|
1322
|
+
return "bin";
|
|
1323
|
+
}
|
|
1324
|
+
const stripFragment = (u) => u.replace(/#.*$/, "");
|
|
1325
|
+
/** The freeze rule: the saved page runs no animation or transition (each
|
|
1326
|
+
* animated property's live value is re-applied by the restore script) and
|
|
1327
|
+
* shows no caret. Appended at the END of <head>. */
|
|
1328
|
+
const DOM_STATE_FREEZE_CSS = "*,*::before,*::after{animation:none!important;transition:none!important;caret-color:transparent!important}";
|
|
1329
|
+
const FREEZE_STYLE = `<style data-ot-freeze>${DOM_STATE_FREEZE_CSS}</style>`;
|
|
1330
|
+
/** What every `<script>` becomes: same element, same index, no behaviour. */
|
|
1331
|
+
const INERT_SCRIPT = "<script type=\"application/x-open-take-inert\"></script>";
|
|
1332
|
+
const ENTITY = {
|
|
1333
|
+
amp: "&",
|
|
1334
|
+
lt: "<",
|
|
1335
|
+
gt: ">",
|
|
1336
|
+
quot: "\"",
|
|
1337
|
+
apos: "'",
|
|
1338
|
+
nbsp: "\xA0"
|
|
1339
|
+
};
|
|
1340
|
+
const decodeEntities = (s) => s.replace(/&(#x[0-9a-fA-F]+|#\d+|[a-zA-Z]+);/g, (m, e) => {
|
|
1341
|
+
if (e[0] === "#") {
|
|
1342
|
+
const code = e[1] === "x" || e[1] === "X" ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10);
|
|
1343
|
+
return Number.isFinite(code) ? String.fromCodePoint(code) : m;
|
|
1344
|
+
}
|
|
1345
|
+
return ENTITY[e.toLowerCase()] ?? m;
|
|
1346
|
+
});
|
|
1347
|
+
const encodeAttr = (s) => s.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<");
|
|
1348
|
+
/** Parse the attributes of one start tag from `pos` (just after the tag
|
|
1349
|
+
* name) to its `>`. Chrome's serializer emits well-formed, double-quoted
|
|
1350
|
+
* markup; unquoted and single-quoted values are handled for safety. */
|
|
1351
|
+
function parseTag(html, pos) {
|
|
1352
|
+
const attrs = [];
|
|
1353
|
+
let i = pos;
|
|
1354
|
+
const n = html.length;
|
|
1355
|
+
let selfClosing = false;
|
|
1356
|
+
while (i < n) {
|
|
1357
|
+
while (i < n && /\s/.test(html[i])) i++;
|
|
1358
|
+
if (i >= n) break;
|
|
1359
|
+
const c = html[i];
|
|
1360
|
+
if (c === ">") return {
|
|
1361
|
+
attrs,
|
|
1362
|
+
end: i + 1,
|
|
1363
|
+
selfClosing
|
|
1364
|
+
};
|
|
1365
|
+
if (c === "/") {
|
|
1366
|
+
if (html[i + 1] === ">") {
|
|
1367
|
+
selfClosing = true;
|
|
1368
|
+
return {
|
|
1369
|
+
attrs,
|
|
1370
|
+
end: i + 2,
|
|
1371
|
+
selfClosing
|
|
1372
|
+
};
|
|
1373
|
+
}
|
|
1374
|
+
i++;
|
|
1375
|
+
continue;
|
|
1376
|
+
}
|
|
1377
|
+
const start = i;
|
|
1378
|
+
while (i < n && !/[\s=>/]/.test(html[i])) i++;
|
|
1379
|
+
if (i === start) {
|
|
1380
|
+
i++;
|
|
1381
|
+
continue;
|
|
1382
|
+
}
|
|
1383
|
+
const name = html.slice(start, i);
|
|
1384
|
+
let j = i;
|
|
1385
|
+
while (j < n && /\s/.test(html[j])) j++;
|
|
1386
|
+
let value = null;
|
|
1387
|
+
if (html[j] === "=") {
|
|
1388
|
+
j++;
|
|
1389
|
+
while (j < n && /\s/.test(html[j])) j++;
|
|
1390
|
+
const q = html[j];
|
|
1391
|
+
if (q === "\"" || q === "'") {
|
|
1392
|
+
const close = html.indexOf(q, j + 1);
|
|
1393
|
+
const stop = close < 0 ? n : close;
|
|
1394
|
+
value = html.slice(j + 1, stop);
|
|
1395
|
+
j = stop + 1;
|
|
1396
|
+
} else {
|
|
1397
|
+
const vs = j;
|
|
1398
|
+
while (j < n && !/[\s>]/.test(html[j])) j++;
|
|
1399
|
+
value = html.slice(vs, j);
|
|
1400
|
+
}
|
|
1401
|
+
i = j;
|
|
1402
|
+
}
|
|
1403
|
+
attrs.push({
|
|
1404
|
+
name,
|
|
1405
|
+
lower: name.toLowerCase(),
|
|
1406
|
+
value,
|
|
1407
|
+
raw: html.slice(start, i)
|
|
1408
|
+
});
|
|
1409
|
+
}
|
|
1410
|
+
return {
|
|
1411
|
+
attrs,
|
|
1412
|
+
end: n,
|
|
1413
|
+
selfClosing
|
|
1414
|
+
};
|
|
1415
|
+
}
|
|
1416
|
+
/** Rewrite `url(…)` and `@import "…"` references in CSS text. `resolve`
|
|
1417
|
+
* returns the local reference, or null to leave the original as is. */
|
|
1418
|
+
function rewriteCss(css, resolve$1) {
|
|
1419
|
+
const url = (ref, quote) => {
|
|
1420
|
+
const r = resolve$1(ref);
|
|
1421
|
+
return r == null ? null : `url(${quote}${r}${quote})`;
|
|
1422
|
+
};
|
|
1423
|
+
return css.replace(/url\(\s*(?:"([^"]*)"|'([^']*)'|([^)\s"']*))\s*\)/g, (m, d, s, b) => {
|
|
1424
|
+
const ref = d ?? s ?? b ?? "";
|
|
1425
|
+
if (!ref) return m;
|
|
1426
|
+
return url(ref, d != null ? "\"" : s != null ? "'" : "") ?? m;
|
|
1427
|
+
}).replace(/@import\s+(?:"([^"]*)"|'([^']*)')/g, (m, d, s) => {
|
|
1428
|
+
const ref = d ?? s ?? "";
|
|
1429
|
+
const r = ref ? resolve$1(ref) : null;
|
|
1430
|
+
return r == null ? m : `@import ${d != null ? "\"" : "'"}${r}${d != null ? "\"" : "'"}`;
|
|
1431
|
+
});
|
|
1432
|
+
}
|
|
1433
|
+
/** Parse a `srcset` value into candidates (url + descriptor), the way the
|
|
1434
|
+
* HTML spec does: a URL runs to the next whitespace (so a data URL keeps
|
|
1435
|
+
* its commas), trailing commas end the candidate, otherwise the descriptor
|
|
1436
|
+
* runs to the next comma. */
|
|
1437
|
+
function parseSrcset(value) {
|
|
1438
|
+
const out = [];
|
|
1439
|
+
const n = value.length;
|
|
1440
|
+
let i = 0;
|
|
1441
|
+
while (i < n) {
|
|
1442
|
+
while (i < n && /[\s,]/.test(value[i])) i++;
|
|
1443
|
+
if (i >= n) break;
|
|
1444
|
+
const start = i;
|
|
1445
|
+
while (i < n && !/\s/.test(value[i])) i++;
|
|
1446
|
+
let url = value.slice(start, i);
|
|
1447
|
+
let descriptor = "";
|
|
1448
|
+
if (url.endsWith(",")) url = url.replace(/,+$/, "");
|
|
1449
|
+
else {
|
|
1450
|
+
while (i < n && /\s/.test(value[i])) i++;
|
|
1451
|
+
const ds = i;
|
|
1452
|
+
while (i < n && value[i] !== ",") i++;
|
|
1453
|
+
descriptor = value.slice(ds, i).trim();
|
|
1454
|
+
}
|
|
1455
|
+
if (url) out.push({
|
|
1456
|
+
url,
|
|
1457
|
+
descriptor
|
|
1458
|
+
});
|
|
1459
|
+
}
|
|
1460
|
+
return out;
|
|
1461
|
+
}
|
|
1462
|
+
/** `rel` tokens whose href names a resource the state may hold */
|
|
1463
|
+
const RESOURCE_RELS = new Set([
|
|
1464
|
+
"stylesheet",
|
|
1465
|
+
"icon",
|
|
1466
|
+
"preload",
|
|
1467
|
+
"modulepreload",
|
|
1468
|
+
"prefetch",
|
|
1469
|
+
"apple-touch-icon",
|
|
1470
|
+
"mask-icon",
|
|
1471
|
+
"manifest",
|
|
1472
|
+
"shortcut"
|
|
1473
|
+
]);
|
|
1474
|
+
/** What a reference the snapshot did not carry becomes: it loads nothing. */
|
|
1475
|
+
const OFFLINE_REF = "about:blank";
|
|
1476
|
+
const URL_ATTRS = {
|
|
1477
|
+
img: new Set(["src"]),
|
|
1478
|
+
source: new Set(["src"]),
|
|
1479
|
+
video: new Set(["src", "poster"]),
|
|
1480
|
+
audio: new Set(["src"]),
|
|
1481
|
+
track: new Set(["src"]),
|
|
1482
|
+
embed: new Set(["src"]),
|
|
1483
|
+
iframe: new Set(["src"]),
|
|
1484
|
+
frame: new Set(["src"]),
|
|
1485
|
+
input: new Set(["src"]),
|
|
1486
|
+
object: new Set(["data"]),
|
|
1487
|
+
image: new Set(["href", "xlink:href"]),
|
|
1488
|
+
use: new Set(["href", "xlink:href"]),
|
|
1489
|
+
feimage: new Set(["href", "xlink:href"]),
|
|
1490
|
+
body: new Set(["background"]),
|
|
1491
|
+
table: new Set(["background"]),
|
|
1492
|
+
td: new Set(["background"])
|
|
1493
|
+
};
|
|
1494
|
+
/** Rewrite one HTML document: scripts inert in place, `on*` gone, refresh /
|
|
1495
|
+
* CSP metas neutralised, `<base href>` dropped, legacy shadow templates made
|
|
1496
|
+
* declarative, every resource reference resolved to the local asset. Only
|
|
1497
|
+
* attributes change — no element is added or removed before an existing
|
|
1498
|
+
* one, so child indices survive. */
|
|
1499
|
+
function rewriteHtml(html, ctx) {
|
|
1500
|
+
let base = ctx.docUrl;
|
|
1501
|
+
const bm = /<base\s[^>]*?href\s*=\s*"([^"]*)"/i.exec(html);
|
|
1502
|
+
if (bm?.[1]) try {
|
|
1503
|
+
base = new URL(decodeEntities(bm[1]), ctx.docUrl).href;
|
|
1504
|
+
} catch {}
|
|
1505
|
+
const resolve$1 = (ref) => ctx.resolve(ref, base);
|
|
1506
|
+
const out = [];
|
|
1507
|
+
const n = html.length;
|
|
1508
|
+
let i = 0;
|
|
1509
|
+
while (i < n) {
|
|
1510
|
+
const lt = html.indexOf("<", i);
|
|
1511
|
+
if (lt < 0) {
|
|
1512
|
+
out.push(html.slice(i));
|
|
1513
|
+
break;
|
|
1514
|
+
}
|
|
1515
|
+
out.push(html.slice(i, lt));
|
|
1516
|
+
const next = html[lt + 1];
|
|
1517
|
+
if (html.startsWith("<!--", lt)) {
|
|
1518
|
+
const end$1 = html.indexOf("-->", lt + 4);
|
|
1519
|
+
const e = end$1 < 0 ? n : end$1 + 3;
|
|
1520
|
+
out.push(html.slice(lt, e));
|
|
1521
|
+
i = e;
|
|
1522
|
+
continue;
|
|
1523
|
+
}
|
|
1524
|
+
if (next === "!" || next === "?" || next === "/") {
|
|
1525
|
+
const end$1 = html.indexOf(">", lt);
|
|
1526
|
+
const e = end$1 < 0 ? n : end$1 + 1;
|
|
1527
|
+
out.push(html.slice(lt, e));
|
|
1528
|
+
i = e;
|
|
1529
|
+
continue;
|
|
1530
|
+
}
|
|
1531
|
+
if (next == null || !/[a-zA-Z]/.test(next)) {
|
|
1532
|
+
out.push("<");
|
|
1533
|
+
i = lt + 1;
|
|
1534
|
+
continue;
|
|
1535
|
+
}
|
|
1536
|
+
let j = lt + 1;
|
|
1537
|
+
while (j < n && !/[\s/>]/.test(html[j])) j++;
|
|
1538
|
+
const tagName = html.slice(lt + 1, j);
|
|
1539
|
+
const tag = tagName.toLowerCase();
|
|
1540
|
+
const { attrs, end, selfClosing } = parseTag(html, j);
|
|
1541
|
+
if (tag === "script") {
|
|
1542
|
+
const close = /<\/script\s*>/gi;
|
|
1543
|
+
close.lastIndex = end;
|
|
1544
|
+
const m = close.exec(html);
|
|
1545
|
+
out.push(INERT_SCRIPT);
|
|
1546
|
+
i = m ? m.index + m[0].length : n;
|
|
1547
|
+
continue;
|
|
1548
|
+
}
|
|
1549
|
+
let changed = false;
|
|
1550
|
+
const kept = [];
|
|
1551
|
+
const relTokens = tag === "link" ? new Set((attrs.find((a) => a.lower === "rel")?.value ?? "").toLowerCase().split(/\s+/).filter(Boolean)) : null;
|
|
1552
|
+
const wantsRel = relTokens ? [...relTokens].some((r) => RESOURCE_RELS.has(r)) : false;
|
|
1553
|
+
for (const a of attrs) {
|
|
1554
|
+
if (a.lower.startsWith("on")) {
|
|
1555
|
+
changed = true;
|
|
1556
|
+
continue;
|
|
1557
|
+
}
|
|
1558
|
+
if (tag === "base" && a.lower === "href") {
|
|
1559
|
+
changed = true;
|
|
1560
|
+
continue;
|
|
1561
|
+
}
|
|
1562
|
+
if (a.lower === "crossorigin" || a.lower === "integrity") {
|
|
1563
|
+
changed = true;
|
|
1564
|
+
continue;
|
|
1565
|
+
}
|
|
1566
|
+
if (tag === "meta" && a.lower === "http-equiv" && a.value != null) {
|
|
1567
|
+
const v = a.value.trim().toLowerCase();
|
|
1568
|
+
if (v === "refresh" || v === "content-security-policy") {
|
|
1569
|
+
const name = "data-ot-stripped-http-equiv";
|
|
1570
|
+
kept.push({
|
|
1571
|
+
...a,
|
|
1572
|
+
name,
|
|
1573
|
+
lower: name,
|
|
1574
|
+
raw: `${name}="${a.value}"`
|
|
1575
|
+
});
|
|
1576
|
+
changed = true;
|
|
1577
|
+
continue;
|
|
1578
|
+
}
|
|
1579
|
+
}
|
|
1580
|
+
if (tag === "template" && a.lower === "shadowmode") {
|
|
1581
|
+
const name = "shadowrootmode";
|
|
1582
|
+
kept.push({
|
|
1583
|
+
...a,
|
|
1584
|
+
name,
|
|
1585
|
+
lower: name,
|
|
1586
|
+
raw: a.value == null ? name : `${name}="${a.value}"`
|
|
1587
|
+
});
|
|
1588
|
+
changed = true;
|
|
1589
|
+
continue;
|
|
1590
|
+
}
|
|
1591
|
+
if (a.value == null) {
|
|
1592
|
+
kept.push(a);
|
|
1593
|
+
continue;
|
|
1594
|
+
}
|
|
1595
|
+
const value = decodeEntities(a.value);
|
|
1596
|
+
let rewritten = null;
|
|
1597
|
+
if (a.lower === "style") {
|
|
1598
|
+
const css = rewriteCss(value, resolve$1);
|
|
1599
|
+
if (css !== value) rewritten = css;
|
|
1600
|
+
} else if (a.lower === "srcset" && (tag === "img" || tag === "source")) {
|
|
1601
|
+
const local = parseSrcset(value).map((c) => ({
|
|
1602
|
+
...c,
|
|
1603
|
+
url: resolve$1(c.url)
|
|
1604
|
+
})).filter((c) => c.url != null && c.url !== OFFLINE_REF);
|
|
1605
|
+
if (local.length === 0) {
|
|
1606
|
+
changed = true;
|
|
1607
|
+
continue;
|
|
1608
|
+
}
|
|
1609
|
+
rewritten = local.map((c) => c.descriptor ? `${c.url} ${c.descriptor}` : c.url).join(", ");
|
|
1610
|
+
} else if (/^cid:/i.test(value) || URL_ATTRS[tag]?.has(a.lower) || tag === "link" && a.lower === "href" && wantsRel) rewritten = resolve$1(value);
|
|
1611
|
+
if (rewritten != null && rewritten !== value) {
|
|
1612
|
+
kept.push({
|
|
1613
|
+
...a,
|
|
1614
|
+
value: rewritten,
|
|
1615
|
+
raw: `${a.name}="${encodeAttr(rewritten)}"`
|
|
1616
|
+
});
|
|
1617
|
+
changed = true;
|
|
1618
|
+
} else kept.push(a);
|
|
1619
|
+
}
|
|
1620
|
+
if (changed) out.push(`<${tagName}${kept.map((a) => ` ${a.raw}`).join("")}${selfClosing ? " /" : ""}>`);
|
|
1621
|
+
else out.push(html.slice(lt, end));
|
|
1622
|
+
i = end;
|
|
1623
|
+
if (tag === "style") {
|
|
1624
|
+
const close = /<\/style\s*>/gi;
|
|
1625
|
+
close.lastIndex = end;
|
|
1626
|
+
const m = close.exec(html);
|
|
1627
|
+
const stop = m ? m.index : n;
|
|
1628
|
+
out.push(rewriteCss(html.slice(end, stop), resolve$1));
|
|
1629
|
+
i = stop;
|
|
1630
|
+
}
|
|
1631
|
+
}
|
|
1632
|
+
return out.join("");
|
|
1633
|
+
}
|
|
1634
|
+
/** The restore script: what markup cannot carry, re-applied when the saved
|
|
1635
|
+
* page loads. Plain JS, the only script that runs; the probe data rides
|
|
1636
|
+
* inline as JSON. Sets `document.documentElement.dataset.otReady = "1"`
|
|
1637
|
+
* once fonts and images are in (bounded — a hung image never blocks it). */
|
|
1638
|
+
function buildRestoreScript(probe) {
|
|
1639
|
+
const data = {
|
|
1640
|
+
scroll: probe.scroll,
|
|
1641
|
+
scrolled: probe.scrolled,
|
|
1642
|
+
inputs: probe.inputs,
|
|
1643
|
+
canvases: probe.canvases,
|
|
1644
|
+
videos: probe.videos,
|
|
1645
|
+
animated: probe.animated,
|
|
1646
|
+
custom: probe.custom,
|
|
1647
|
+
focus: probe.focus ?? null,
|
|
1648
|
+
elements: probe.elements.map((e) => ({
|
|
1649
|
+
id: e.id,
|
|
1650
|
+
path: e.path,
|
|
1651
|
+
tag: e.tag
|
|
1652
|
+
}))
|
|
1653
|
+
};
|
|
1654
|
+
const json = JSON.stringify(data).replace(/</g, "\\u003c").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
|
|
1655
|
+
return `<script data-ot-restore>(function(){
|
|
1656
|
+
var P=${json};
|
|
1657
|
+
var doc=document;
|
|
1658
|
+
function resolve(path){var n=doc.documentElement;for(var i=0;i<path.length;i++){n=n.children[path[i]];if(!n)return null;}return n;}
|
|
1659
|
+
function paint(el,url){return new Promise(function(res){try{var ctx=el.getContext("2d");if(!ctx)return res();var im=new Image();im.onload=function(){try{ctx.clearRect(0,0,el.width,el.height);ctx.drawImage(im,0,0,el.width,el.height);}catch(e){}res();};im.onerror=function(){res();};im.src=url;}catch(e){res();}});}
|
|
1660
|
+
function run(){
|
|
1661
|
+
var misses=0,i,j,el,waits=[];
|
|
1662
|
+
for(i=0;i<P.custom.length;i++){var c=P.custom[i];try{if(!customElements.get(c.name)){if(c.extends){var Base=doc.createElement(c.extends).constructor;customElements.define(c.name,class extends Base{},{extends:c.extends});}else customElements.define(c.name,class extends HTMLElement{});}}catch(e){}}
|
|
1663
|
+
for(i=0;i<P.elements.length;i++){var e=P.elements[i];el=resolve(e.path);if(el&&el.localName===e.tag)el.setAttribute("data-ot-id",e.id);else misses++;}
|
|
1664
|
+
for(i=0;i<P.inputs.length;i++){var x=P.inputs[i];el=resolve(x.path);if(!el)continue;try{if("checked" in x)el.checked=x.checked;if(x.selected)for(var o=0;o<el.options.length;o++)el.options[o].selected=x.selected.indexOf(o)>=0;if("value" in x)el.value=x.value;}catch(e){}}
|
|
1665
|
+
for(i=0;i<P.canvases.length;i++){var cv=P.canvases[i];el=resolve(cv.path);if(!el||el.localName!=="canvas")continue;waits.push(paint(el,cv.dataUrl));}
|
|
1666
|
+
for(i=0;i<P.videos.length;i++){var vd=P.videos[i];el=resolve(vd.path);if(!el||el.localName!=="video")continue;try{el.removeAttribute("autoplay");el.removeAttribute("src");var ss=el.querySelectorAll("source");for(j=0;j<ss.length;j++)ss[j].remove();el.setAttribute("preload","none");el.setAttribute("poster",vd.dataUrl);el.load();}catch(e){}}
|
|
1667
|
+
for(i=0;i<P.animated.length;i++){var an=P.animated[i];el=resolve(an.path);if(!el)continue;for(var k in an.styles){try{el.style.setProperty(k,an.styles[k],"important");}catch(e){}}}
|
|
1668
|
+
var lazy=doc.querySelectorAll("img[loading=lazy]");for(i=0;i<lazy.length;i++)lazy[i].loading="eager";
|
|
1669
|
+
try{var sheet=new CSSStyleSheet();sheet.replaceSync(${JSON.stringify(DOM_STATE_FREEZE_CSS)});var all=doc.querySelectorAll("*");for(i=0;i<all.length;i++){var sr=all[i].shadowRoot;if(sr)sr.adoptedStyleSheets=sr.adoptedStyleSheets.concat([sheet]);}}catch(e){}
|
|
1670
|
+
function applyScroll(){try{window.scrollTo({left:P.scroll.x,top:P.scroll.y,behavior:"instant"});}catch(e){window.scrollTo(P.scroll.x,P.scroll.y);}for(var s=0;s<P.scrolled.length;s++){var sc=P.scrolled[s];var se=resolve(sc.path);if(!se)continue;try{se.scrollTo({left:sc.left,top:sc.top,behavior:"instant"});}catch(e){se.scrollTop=sc.top;se.scrollLeft=sc.left;}}}
|
|
1671
|
+
void doc.body.getBoundingClientRect();
|
|
1672
|
+
if(P.focus){el=resolve(P.focus);if(el){try{el.focus({preventScroll:true});}catch(e){}}}
|
|
1673
|
+
applyScroll();
|
|
1674
|
+
try{waits.push(doc.fonts.ready);}catch(e){}
|
|
1675
|
+
var imgs=doc.images;for(i=0;i<imgs.length;i++){try{if(typeof imgs[i].decode==="function")waits.push(imgs[i].decode().catch(function(){}));}catch(e){}}
|
|
1676
|
+
var done=false;
|
|
1677
|
+
function finish(){if(done)return;done=true;applyScroll();doc.documentElement.setAttribute("data-ot-misses",String(misses));doc.documentElement.setAttribute("data-ot-ready","1");}
|
|
1678
|
+
Promise.all(waits).then(finish,finish);
|
|
1679
|
+
setTimeout(finish,6000);
|
|
1680
|
+
}
|
|
1681
|
+
if(doc.readyState==="loading")doc.addEventListener("DOMContentLoaded",run);else run();
|
|
1682
|
+
})();</script>`;
|
|
1683
|
+
}
|
|
1684
|
+
/**
|
|
1685
|
+
* MHTML → state.html. Every part but the document goes to `assetsDir` as
|
|
1686
|
+
* `<sha1>.<ext>` (deduped across states); references are rewritten to
|
|
1687
|
+
* `../assets/<file>`. Sub-frame documents become `.html` assets, converted
|
|
1688
|
+
* the same way (best effort — no restore script for them).
|
|
1689
|
+
*/
|
|
1690
|
+
function convertMhtml(raw, probe, opts) {
|
|
1691
|
+
const parts = parseMhtml(raw);
|
|
1692
|
+
const doc = parts.find((p) => p.contentType === "text/html");
|
|
1693
|
+
if (!doc) throw new Error("mhtml: no text/html part");
|
|
1694
|
+
mkdirSync(opts.assetsDir, { recursive: true });
|
|
1695
|
+
const byLocation = new Map();
|
|
1696
|
+
const byCid = new Map();
|
|
1697
|
+
for (const p of parts) {
|
|
1698
|
+
if (p === doc) continue;
|
|
1699
|
+
if (p.id) byCid.set(p.id, p);
|
|
1700
|
+
if (p.location) if (/^cid:/i.test(p.location)) byCid.set(p.location.slice(4), p);
|
|
1701
|
+
else byLocation.set(stripFragment(p.location), p);
|
|
1702
|
+
}
|
|
1703
|
+
for (const p of opts.extra ?? []) {
|
|
1704
|
+
if (!p.location || /^cid:/i.test(p.location)) continue;
|
|
1705
|
+
const at = stripFragment(p.location);
|
|
1706
|
+
if (!byLocation.has(at)) byLocation.set(at, p);
|
|
1707
|
+
}
|
|
1708
|
+
const assets = new Set();
|
|
1709
|
+
const emitted = new Map();
|
|
1710
|
+
const inProgress = new Set();
|
|
1711
|
+
let unresolved = 0;
|
|
1712
|
+
const write = (bytes, ext) => {
|
|
1713
|
+
const name = `${createHash("sha1").update(bytes).digest("hex")}.${ext}`;
|
|
1714
|
+
const file = join(opts.assetsDir, name);
|
|
1715
|
+
if (!existsSync(file)) writeFileSync(file, bytes);
|
|
1716
|
+
assets.add(name);
|
|
1717
|
+
return `../assets/${name}`;
|
|
1718
|
+
};
|
|
1719
|
+
const lookup = (ref, base) => {
|
|
1720
|
+
if (/^cid:/i.test(ref)) return byCid.get(ref.slice(4)) ?? null;
|
|
1721
|
+
if (/^(data|blob|about|javascript|mailto|tel):/i.test(ref) || ref.startsWith("#")) return null;
|
|
1722
|
+
try {
|
|
1723
|
+
const abs = stripFragment(new URL(ref, base).href);
|
|
1724
|
+
return byLocation.get(abs) ?? null;
|
|
1725
|
+
} catch {
|
|
1726
|
+
return null;
|
|
1727
|
+
}
|
|
1728
|
+
};
|
|
1729
|
+
/** the local reference for a part, converting it on first use */
|
|
1730
|
+
const emit = (part) => {
|
|
1731
|
+
if (emitted.has(part)) return emitted.get(part) ?? null;
|
|
1732
|
+
if (inProgress.has(part)) return null;
|
|
1733
|
+
inProgress.add(part);
|
|
1734
|
+
let ref;
|
|
1735
|
+
try {
|
|
1736
|
+
const partBase = part.location && !/^cid:/i.test(part.location) ? part.location : doc.location ?? "about:blank";
|
|
1737
|
+
if (part.contentType === "text/css") {
|
|
1738
|
+
const css = rewriteCss(part.body.toString("utf8"), (r) => resolveRef(r, partBase));
|
|
1739
|
+
ref = write(Buffer.from(css, "utf8"), "css");
|
|
1740
|
+
} else if (part.contentType === "text/html") {
|
|
1741
|
+
const html$1 = rewriteHtml(part.body.toString("utf8"), {
|
|
1742
|
+
resolve: resolveRef,
|
|
1743
|
+
docUrl: partBase
|
|
1744
|
+
});
|
|
1745
|
+
ref = write(Buffer.from(withFreeze(html$1), "utf8"), "html");
|
|
1746
|
+
} else ref = write(part.body, extFor(part));
|
|
1747
|
+
} finally {
|
|
1748
|
+
inProgress.delete(part);
|
|
1749
|
+
}
|
|
1750
|
+
emitted.set(part, ref);
|
|
1751
|
+
return ref;
|
|
1752
|
+
};
|
|
1753
|
+
const resolveRef = (ref, base) => {
|
|
1754
|
+
if (ref.startsWith("#")) return null;
|
|
1755
|
+
const part = lookup(ref, base);
|
|
1756
|
+
if (part) {
|
|
1757
|
+
const local = emit(part);
|
|
1758
|
+
const place = /#.*$/.exec(ref)?.[0];
|
|
1759
|
+
return local && place ? local + place : local;
|
|
1760
|
+
}
|
|
1761
|
+
if (/^cid:/i.test(ref)) {
|
|
1762
|
+
unresolved++;
|
|
1763
|
+
return OFFLINE_REF;
|
|
1764
|
+
}
|
|
1765
|
+
try {
|
|
1766
|
+
const u = new URL(ref, base);
|
|
1767
|
+
if (u.protocol === "http:" || u.protocol === "https:") {
|
|
1768
|
+
unresolved++;
|
|
1769
|
+
return OFFLINE_REF;
|
|
1770
|
+
}
|
|
1771
|
+
} catch {}
|
|
1772
|
+
return null;
|
|
1773
|
+
};
|
|
1774
|
+
const docUrl = doc.location && !/^cid:/i.test(doc.location) ? doc.location : probe.url;
|
|
1775
|
+
let html = rewriteHtml(doc.body.toString("utf8"), {
|
|
1776
|
+
resolve: resolveRef,
|
|
1777
|
+
docUrl
|
|
1778
|
+
});
|
|
1779
|
+
html = withFreeze(html);
|
|
1780
|
+
const htmlClose = html.search(/<\/html\s*>\s*$/i);
|
|
1781
|
+
const restore = buildRestoreScript(probe);
|
|
1782
|
+
html = htmlClose >= 0 ? `${html.slice(0, htmlClose)}${restore}\n${html.slice(htmlClose)}` : `${html}${restore}\n`;
|
|
1783
|
+
return {
|
|
1784
|
+
html,
|
|
1785
|
+
assets: [...assets],
|
|
1786
|
+
unresolved
|
|
1787
|
+
};
|
|
1788
|
+
}
|
|
1789
|
+
/** the freeze style at the END of <head> (or before <body>, or first) */
|
|
1790
|
+
function withFreeze(html) {
|
|
1791
|
+
const headClose = /<\/head\s*>/i.exec(html);
|
|
1792
|
+
if (headClose) return `${html.slice(0, headClose.index)}${FREEZE_STYLE}${html.slice(headClose.index)}`;
|
|
1793
|
+
const body = /<body[\s>]/i.exec(html);
|
|
1794
|
+
if (body) return `${html.slice(0, body.index)}${FREEZE_STYLE}${html.slice(body.index)}`;
|
|
1795
|
+
return `${FREEZE_STYLE}${html}`;
|
|
1796
|
+
}
|
|
1797
|
+
/** The most font bytes one take saves (all states together) — a CJK face cut
|
|
1798
|
+
* into ~100 unicode-range subsets is ~5–10 MB; faces the page loaded go
|
|
1799
|
+
* first, so what falls past the cap is a subset nothing on screen used. */
|
|
1800
|
+
const FONT_BUDGET_BYTES = 48 * 1024 * 1024;
|
|
1801
|
+
/** One file larger than this is not saved (a whole CJK family in one file is
|
|
1802
|
+
* under it). */
|
|
1803
|
+
const FONT_FILE_MAX_BYTES = 12 * 1024 * 1024;
|
|
1804
|
+
const CSS_URL = /url\(\s*(?:"([^"]*)"|'([^']*)'|([^)\s"']*))\s*\)/g;
|
|
1805
|
+
/** The file each @font-face rule in the snapshot's stylesheets (linked,
|
|
1806
|
+
* inline, sub-frame) names — the first http(s) `url()` of its `src`, the one
|
|
1807
|
+
* Chrome tries first — absolute, in order, once each. */
|
|
1808
|
+
function fontFaceSources(parts, docUrl) {
|
|
1809
|
+
const out = new Set();
|
|
1810
|
+
const doc = parts.find((p) => p.contentType === "text/html");
|
|
1811
|
+
const docBase = doc?.location && !/^cid:/i.test(doc.location) ? doc.location : docUrl;
|
|
1812
|
+
for (const p of parts) {
|
|
1813
|
+
if (p.contentType !== "text/css" && p.contentType !== "text/html") continue;
|
|
1814
|
+
const base = p.location && !/^cid:/i.test(p.location) ? p.location : docBase;
|
|
1815
|
+
for (const face of p.body.toString("utf8").matchAll(/@font-face\s*\{([^}]*)\}/gi)) {
|
|
1816
|
+
const src = /(?:^|[;\s])src\s*:([^;]*)/i.exec(face[1])?.[1];
|
|
1817
|
+
if (!src) continue;
|
|
1818
|
+
for (const m of src.matchAll(CSS_URL)) {
|
|
1819
|
+
const ref = m[1] ?? m[2] ?? m[3] ?? "";
|
|
1820
|
+
try {
|
|
1821
|
+
const u = new URL(ref, base);
|
|
1822
|
+
if (u.protocol !== "http:" && u.protocol !== "https:") continue;
|
|
1823
|
+
out.add(stripFragment(u.href));
|
|
1824
|
+
break;
|
|
1825
|
+
} catch {}
|
|
1826
|
+
}
|
|
1827
|
+
}
|
|
1828
|
+
}
|
|
1829
|
+
return [...out];
|
|
1830
|
+
}
|
|
1831
|
+
/** a font file's media type from its first bytes, or null when it is not one
|
|
1832
|
+
* (an app that answers every path with its HTML shell) */
|
|
1833
|
+
function fontType(bytes) {
|
|
1834
|
+
const sig = bytes.subarray(0, 4).toString("latin1");
|
|
1835
|
+
if (sig === "wOF2") return "font/woff2";
|
|
1836
|
+
if (sig === "wOFF") return "font/woff";
|
|
1837
|
+
if (sig === "OTTO") return "font/otf";
|
|
1838
|
+
if (sig === "true" || sig === "\0\0\0") return "font/ttf";
|
|
1839
|
+
if (sig === "ttcf") return "font/collection";
|
|
1840
|
+
return null;
|
|
1841
|
+
}
|
|
1842
|
+
/**
|
|
1843
|
+
* Fetch font files through the recorded page (`Network.loadNetworkResource`
|
|
1844
|
+
* on its main frame: its cookies and referrer, nothing run in the page), at
|
|
1845
|
+
* most `concurrency` at a time, in the order given, until the cap in `state`
|
|
1846
|
+
* runs out. Results land in `state.done`; a URL already there is skipped.
|
|
1847
|
+
*/
|
|
1848
|
+
async function fetchFontFiles(cdp, urls, state, opts = {}) {
|
|
1849
|
+
const todo = urls.filter((u) => !state.done.has(u));
|
|
1850
|
+
if (!todo.length) return;
|
|
1851
|
+
let frameId;
|
|
1852
|
+
try {
|
|
1853
|
+
const tree = await cdp.send("Page.getFrameTree");
|
|
1854
|
+
frameId = tree.frameTree.frame.id;
|
|
1855
|
+
} catch (e) {
|
|
1856
|
+
for (const u of todo) state.done.set(u, `no page to fetch through (${e.message})`);
|
|
1857
|
+
return;
|
|
1858
|
+
}
|
|
1859
|
+
const one = async (url) => {
|
|
1860
|
+
if (state.left <= 0) return "over the cap";
|
|
1861
|
+
const r = await cdp.send("Network.loadNetworkResource", {
|
|
1862
|
+
frameId,
|
|
1863
|
+
url,
|
|
1864
|
+
options: {
|
|
1865
|
+
disableCache: false,
|
|
1866
|
+
includeCredentials: true
|
|
1867
|
+
}
|
|
1868
|
+
});
|
|
1869
|
+
const { stream } = r.resource;
|
|
1870
|
+
try {
|
|
1871
|
+
const status = r.resource.httpStatusCode ?? 0;
|
|
1872
|
+
if (!r.resource.success || status < 200 || status > 299) return r.resource.netErrorName ?? `HTTP ${status}`;
|
|
1873
|
+
if (!stream) return "no body";
|
|
1874
|
+
const chunks = [];
|
|
1875
|
+
let n = 0;
|
|
1876
|
+
for (;;) {
|
|
1877
|
+
const c = await cdp.send("IO.read", {
|
|
1878
|
+
handle: stream,
|
|
1879
|
+
size: 1 << 20
|
|
1880
|
+
});
|
|
1881
|
+
const b = Buffer.from(c.data, c.base64Encoded ? "base64" : "latin1");
|
|
1882
|
+
chunks.push(b);
|
|
1883
|
+
n += b.length;
|
|
1884
|
+
if (n > FONT_FILE_MAX_BYTES) return `larger than ${FONT_FILE_MAX_BYTES >> 20} MB`;
|
|
1885
|
+
if (n > state.left) return "over the cap";
|
|
1886
|
+
if (c.eof) break;
|
|
1887
|
+
}
|
|
1888
|
+
const body = Buffer.concat(chunks);
|
|
1889
|
+
const contentType = fontType(body);
|
|
1890
|
+
if (!contentType) return "not a font file";
|
|
1891
|
+
state.left -= body.length;
|
|
1892
|
+
return {
|
|
1893
|
+
contentType,
|
|
1894
|
+
location: url,
|
|
1895
|
+
body
|
|
1896
|
+
};
|
|
1897
|
+
} finally {
|
|
1898
|
+
if (stream) await cdp.send("IO.close", { handle: stream }).catch(() => {});
|
|
1899
|
+
}
|
|
1900
|
+
};
|
|
1901
|
+
let next = 0;
|
|
1902
|
+
const worker = async () => {
|
|
1903
|
+
while (next < todo.length) {
|
|
1904
|
+
const url = todo[next++];
|
|
1905
|
+
let got;
|
|
1906
|
+
try {
|
|
1907
|
+
got = await one(url);
|
|
1908
|
+
} catch (e) {
|
|
1909
|
+
got = e.message;
|
|
1910
|
+
}
|
|
1911
|
+
state.done.set(url, got);
|
|
1912
|
+
}
|
|
1913
|
+
};
|
|
1914
|
+
await Promise.all(Array.from({ length: Math.max(1, opts.concurrency ?? 6) }, worker));
|
|
1915
|
+
}
|
|
1916
|
+
/** The web-font files the states' snapshots name and do not carry, fetched
|
|
1917
|
+
* once for the whole take — the faces the page loaded first (any state),
|
|
1918
|
+
* then the rest — as parts `convertMhtml` resolves like its own. */
|
|
1919
|
+
async function fetchStateFonts(cdp, states, warn) {
|
|
1920
|
+
const loaded = new Set(states.flatMap((s) => (s.loadedFonts ?? []).map(stripFragment)));
|
|
1921
|
+
const wanted = [];
|
|
1922
|
+
for (const raw of states) try {
|
|
1923
|
+
const parts$1 = parseMhtml(await readFile(join(raw.dir, "page.mhtml"), "latin1"));
|
|
1924
|
+
const carried = new Set(parts$1.flatMap((p) => p.location ? [stripFragment(p.location)] : []));
|
|
1925
|
+
for (const u of fontFaceSources(parts$1, raw.probe.url)) if (!carried.has(u) && !wanted.includes(u)) wanted.push(u);
|
|
1926
|
+
} catch {}
|
|
1927
|
+
if (!wanted.length) return [];
|
|
1928
|
+
const order = [...wanted.filter((u) => loaded.has(u)), ...wanted.filter((u) => !loaded.has(u))];
|
|
1929
|
+
const state = {
|
|
1930
|
+
done: new Map(),
|
|
1931
|
+
left: FONT_BUDGET_BYTES
|
|
1932
|
+
};
|
|
1933
|
+
const t0 = Date.now();
|
|
1934
|
+
await fetchFontFiles(cdp, order, state);
|
|
1935
|
+
const parts = order.flatMap((u) => {
|
|
1936
|
+
const p = state.done.get(u);
|
|
1937
|
+
return p && typeof p !== "string" ? [p] : [];
|
|
1938
|
+
});
|
|
1939
|
+
const bytes = parts.reduce((s, p) => s + p.body.length, 0);
|
|
1940
|
+
const why = new Map();
|
|
1941
|
+
for (const v of state.done.values()) if (typeof v === "string") why.set(v, (why.get(v) ?? 0) + 1);
|
|
1942
|
+
warn(`dom-state: ${parts.length} of ${order.length} web-font file(s) the snapshot left out saved (${(bytes / 1048576).toFixed(1)} MB, ${Date.now() - t0} ms)${why.size ? ` — not saved: ${[...why].slice(0, 4).map(([w, n]) => `${n} ${w}`).join("; ")}` : ""}`);
|
|
1943
|
+
return parts;
|
|
1944
|
+
}
|
|
1945
|
+
/** PSNR (dB, capped at 99 for identical images) and the fraction of pixels
|
|
1946
|
+
* differing by more than 8 on any channel, over two rgb24 buffers — pixels
|
|
1947
|
+
* inside `mask` boxes (what moves on its own: canvases, videos) left out. */
|
|
1948
|
+
function comparePixels(a, b, mask) {
|
|
1949
|
+
const n = Math.min(a.length, b.length) - Math.min(a.length, b.length) % 3;
|
|
1950
|
+
if (n === 0) return {
|
|
1951
|
+
psnr: 0,
|
|
1952
|
+
diffFrac: 1
|
|
1953
|
+
};
|
|
1954
|
+
const masked = mask?.boxes.length ? maskBits(mask, n / 3) : null;
|
|
1955
|
+
let se = 0;
|
|
1956
|
+
let diff = 0;
|
|
1957
|
+
let counted = 0;
|
|
1958
|
+
for (let i = 0; i < n; i += 3) {
|
|
1959
|
+
if (masked?.[i / 3]) continue;
|
|
1960
|
+
counted++;
|
|
1961
|
+
const d0 = a[i] - b[i];
|
|
1962
|
+
const d1 = a[i + 1] - b[i + 1];
|
|
1963
|
+
const d2 = a[i + 2] - b[i + 2];
|
|
1964
|
+
se += d0 * d0 + d1 * d1 + d2 * d2;
|
|
1965
|
+
if (Math.abs(d0) > 8 || Math.abs(d1) > 8 || Math.abs(d2) > 8) diff++;
|
|
1966
|
+
}
|
|
1967
|
+
if (counted === 0) return {
|
|
1968
|
+
psnr: 99,
|
|
1969
|
+
diffFrac: 0
|
|
1970
|
+
};
|
|
1971
|
+
const mse = se / (counted * 3);
|
|
1972
|
+
const psnr = mse === 0 ? 99 : Math.min(99, 10 * Math.log10(255 * 255 / mse));
|
|
1973
|
+
return {
|
|
1974
|
+
psnr: Math.round(psnr * 100) / 100,
|
|
1975
|
+
diffFrac: Math.round(diff / counted * 1e4) / 1e4
|
|
1976
|
+
};
|
|
1977
|
+
}
|
|
1978
|
+
function maskBits(mask, pixels) {
|
|
1979
|
+
const bits = new Uint8Array(pixels);
|
|
1980
|
+
const w = mask.width;
|
|
1981
|
+
const h = Math.floor(pixels / w);
|
|
1982
|
+
for (const [bx, by, bw, bh] of mask.boxes) {
|
|
1983
|
+
const x0 = Math.max(0, Math.floor(bx));
|
|
1984
|
+
const y0 = Math.max(0, Math.floor(by));
|
|
1985
|
+
const x1 = Math.min(w, Math.ceil(bx + bw));
|
|
1986
|
+
const y1 = Math.min(h, Math.ceil(by + bh));
|
|
1987
|
+
for (let y = y0; y < y1; y++) bits.fill(1, y * w + x0, Math.max(y * w + x0, y * w + x1));
|
|
1988
|
+
}
|
|
1989
|
+
return bits;
|
|
1990
|
+
}
|
|
1991
|
+
/** width/height from a PNG's IHDR */
|
|
1992
|
+
function pngSize(png) {
|
|
1993
|
+
if (png.length < 24 || png.readUInt32BE(12) !== 1229472850) throw new Error("not a PNG");
|
|
1994
|
+
return {
|
|
1995
|
+
w: png.readUInt32BE(16),
|
|
1996
|
+
h: png.readUInt32BE(20)
|
|
1997
|
+
};
|
|
1998
|
+
}
|
|
1999
|
+
/** Decode an image file to raw rgb24 at `w`×`h` through ffmpeg. */
|
|
2000
|
+
function decodeRgb(ffmpeg, file, w, h, flags = "neighbor") {
|
|
2001
|
+
return runBuffer(ffmpeg, [
|
|
2002
|
+
"-v",
|
|
2003
|
+
"error",
|
|
2004
|
+
"-i",
|
|
2005
|
+
file,
|
|
2006
|
+
"-vf",
|
|
2007
|
+
`scale=${w}:${h}:flags=${flags}`,
|
|
2008
|
+
"-f",
|
|
2009
|
+
"rawvideo",
|
|
2010
|
+
"-pix_fmt",
|
|
2011
|
+
"rgb24",
|
|
2012
|
+
"-"
|
|
2013
|
+
]).then((buf) => {
|
|
2014
|
+
if (buf.length !== w * h * 3) throw new Error(`ffmpeg decoded ${file} to ${buf.length} bytes, not ${w}×${h} rgb`);
|
|
2015
|
+
return new Uint8Array(buf);
|
|
2016
|
+
});
|
|
2017
|
+
}
|
|
2018
|
+
/** `box` (CSS px) of a PNG as a PNG data URL, clamped to the image. */
|
|
2019
|
+
async function cropPng(ffmpeg, png, box) {
|
|
2020
|
+
const { w, h } = pngSize(await readFile(png));
|
|
2021
|
+
const x = Math.max(0, Math.floor(box[0]));
|
|
2022
|
+
const y = Math.max(0, Math.floor(box[1]));
|
|
2023
|
+
const cw = Math.min(w - x, Math.ceil(box[0] + box[2]) - x);
|
|
2024
|
+
const ch = Math.min(h - y, Math.ceil(box[1] + box[3]) - y);
|
|
2025
|
+
if (cw < 1 || ch < 1) throw new Error("the box is off the image");
|
|
2026
|
+
const out = await runBuffer(ffmpeg, [
|
|
2027
|
+
"-v",
|
|
2028
|
+
"error",
|
|
2029
|
+
"-i",
|
|
2030
|
+
png,
|
|
2031
|
+
"-vf",
|
|
2032
|
+
`crop=${cw}:${ch}:${x}:${y}`,
|
|
2033
|
+
"-f",
|
|
2034
|
+
"image2pipe",
|
|
2035
|
+
"-vcodec",
|
|
2036
|
+
"png",
|
|
2037
|
+
"-"
|
|
2038
|
+
]);
|
|
2039
|
+
return `data:image/png;base64,${out.toString("base64")}`;
|
|
2040
|
+
}
|
|
2041
|
+
/** Compare a state's re-render against the live reference, both PNG files. */
|
|
2042
|
+
async function measureFidelity(ffmpeg, livePng, statePng, moving = []) {
|
|
2043
|
+
const { w, h } = pngSize(await readFile(livePng));
|
|
2044
|
+
const [a, b] = await Promise.all([decodeRgb(ffmpeg, livePng, w, h), decodeRgb(ffmpeg, statePng, w, h)]);
|
|
2045
|
+
const { psnr, diffFrac } = comparePixels(a, b, {
|
|
2046
|
+
width: w,
|
|
2047
|
+
boxes: moving
|
|
2048
|
+
});
|
|
2049
|
+
return {
|
|
2050
|
+
psnr,
|
|
2051
|
+
diffFrac,
|
|
2052
|
+
ok: psnr >= DOM_STATE_PSNR_OK
|
|
2053
|
+
};
|
|
2054
|
+
}
|
|
2055
|
+
/** The element whose box best matches `box` (IoU ≥ 0.5), or undefined. */
|
|
2056
|
+
function matchTarget(box, elements) {
|
|
2057
|
+
let best;
|
|
2058
|
+
let bestIou = .5;
|
|
2059
|
+
const area = Math.max(0, box.w) * Math.max(0, box.h);
|
|
2060
|
+
for (const e of elements) {
|
|
2061
|
+
const [x, y, w, h] = e.box;
|
|
2062
|
+
const ix = Math.max(0, Math.min(box.x + box.w, x + w) - Math.max(box.x, x));
|
|
2063
|
+
const iy = Math.max(0, Math.min(box.y + box.h, y + h) - Math.max(box.y, y));
|
|
2064
|
+
const inter = ix * iy;
|
|
2065
|
+
if (inter <= 0) continue;
|
|
2066
|
+
const iou = inter / (area + w * h - inter);
|
|
2067
|
+
if (iou > bestIou) {
|
|
2068
|
+
bestIou = iou;
|
|
2069
|
+
best = e.id;
|
|
2070
|
+
}
|
|
2071
|
+
}
|
|
2072
|
+
return best;
|
|
2073
|
+
}
|
|
2074
|
+
/** Visible canvases and videos (CSS px): content that moves on its own — a
|
|
2075
|
+
* spinning WebGL globe, a looping clip — which a still can only freeze. And
|
|
2076
|
+
* the focused text field, whose caret blinks on its own (every half second:
|
|
2077
|
+
* two shots 150 ms apart straddled a blink about one time in three). */
|
|
2078
|
+
const LIVING_JS = `(() => {
|
|
2079
|
+
const out = [];
|
|
2080
|
+
const f = document.activeElement;
|
|
2081
|
+
if (f && (f.isContentEditable || /^(input|textarea|select)$/i.test(f.tagName))) {
|
|
2082
|
+
const r = f.getBoundingClientRect();
|
|
2083
|
+
if (r.width > 0 && r.height > 0) out.push([r.left, r.top, r.width, r.height]);
|
|
2084
|
+
}
|
|
2085
|
+
for (const el of document.querySelectorAll("canvas,video")) {
|
|
2086
|
+
const r = el.getBoundingClientRect();
|
|
2087
|
+
if (r.width < 2 || r.height < 2 || r.right <= 0 || r.bottom <= 0 || r.left >= innerWidth || r.top >= innerHeight) continue;
|
|
2088
|
+
const cs = getComputedStyle(el);
|
|
2089
|
+
if (cs.visibility === "hidden" || Number(cs.opacity) === 0) continue;
|
|
2090
|
+
out.push([r.left, r.top, r.width, r.height]);
|
|
2091
|
+
}
|
|
2092
|
+
return out;
|
|
2093
|
+
})()`;
|
|
2094
|
+
/** Is the page visually still? Two screenshots 150 ms apart. They are taken at
|
|
2095
|
+
* the page's own scale: a scaled capture re-rasters the page and is not
|
|
2096
|
+
* repeatable (a still page gave two different 1/8-scale images in 12 shots;
|
|
2097
|
+
* native-scale shots were identical), so identical bytes mean nothing moved.
|
|
2098
|
+
* When they differ and the page has content that moves on its own — visible
|
|
2099
|
+
* canvases and videos, the focused field's caret — both are decoded small
|
|
2100
|
+
* and compared outside those boxes. The settle probe hears a page WORKING —
|
|
2101
|
+
* timers, requests, mutations — which a loaded machine stretches past its
|
|
2102
|
+
* budget even when nothing on screen moves; only moving pixels make a moment
|
|
2103
|
+
* unfit for a still. */
|
|
2104
|
+
async function visuallyStill(cdp, vw, vh) {
|
|
2105
|
+
const living = await cdp.send("Runtime.evaluate", {
|
|
2106
|
+
expression: LIVING_JS,
|
|
2107
|
+
returnByValue: true
|
|
2108
|
+
}).then((r) => r.result?.value ?? []).catch(() => []);
|
|
2109
|
+
const shot = async () => Buffer.from((await cdp.send("Page.captureScreenshot", {
|
|
2110
|
+
format: "jpeg",
|
|
2111
|
+
quality: 80,
|
|
2112
|
+
optimizeForSpeed: true
|
|
2113
|
+
})).data, "base64");
|
|
2114
|
+
const a = await shot();
|
|
2115
|
+
await sleep$2(150);
|
|
2116
|
+
const b = await shot();
|
|
2117
|
+
if (a.equals(b)) return true;
|
|
2118
|
+
if (!living.length) return false;
|
|
2119
|
+
const w = Math.max(1, Math.round(vw / 4));
|
|
2120
|
+
const h = Math.max(1, Math.round(vh / 4));
|
|
2121
|
+
const [sa, sb] = await decodeSmall(await resolveFfmpeg(), [a, b], w, h);
|
|
2122
|
+
return stillOutside(sa, sb, living, vw, 2);
|
|
2123
|
+
}
|
|
2124
|
+
/** JPEG screenshots → w×h rgb24 (area-averaged), one ffmpeg run each. */
|
|
2125
|
+
async function decodeSmall(ffmpeg, jpegs, w, h) {
|
|
2126
|
+
const dir = await mkdtemp(join(tmpdir(), "open-take-still-"));
|
|
2127
|
+
try {
|
|
2128
|
+
const files = await Promise.all(jpegs.map(async (j, i) => {
|
|
2129
|
+
const f = join(dir, `${i}.jpg`);
|
|
2130
|
+
await writeFile(f, j);
|
|
2131
|
+
return f;
|
|
2132
|
+
}));
|
|
2133
|
+
const frames = await Promise.all(files.map((f) => decodeRgb(ffmpeg, f, w, h, "area")));
|
|
2134
|
+
return frames.map((data) => ({
|
|
2135
|
+
w,
|
|
2136
|
+
h,
|
|
2137
|
+
ch: 3,
|
|
2138
|
+
data
|
|
2139
|
+
}));
|
|
2140
|
+
} finally {
|
|
2141
|
+
await rm(dir, {
|
|
2142
|
+
recursive: true,
|
|
2143
|
+
force: true
|
|
2144
|
+
});
|
|
2145
|
+
}
|
|
2146
|
+
}
|
|
2147
|
+
/** Pixels of the small image that may change without the page moving, and by
|
|
2148
|
+
* how much a channel must change to count. */
|
|
2149
|
+
const STILL_TOLERANCE = {
|
|
2150
|
+
pixels: 2,
|
|
2151
|
+
level: 12
|
|
2152
|
+
};
|
|
2153
|
+
/** Two decoded screenshots of a `vw`-wide viewport show the same page outside
|
|
2154
|
+
* the CSS-px `boxes` (grown by a screenshot pixel for antialiased edges). */
|
|
2155
|
+
function stillOutside(a, b, boxes, vw, margin) {
|
|
2156
|
+
if (a.w !== b.w || a.h !== b.h || a.ch !== b.ch) return false;
|
|
2157
|
+
const k = a.w / vw;
|
|
2158
|
+
const masked = maskBits({
|
|
2159
|
+
width: a.w,
|
|
2160
|
+
boxes: boxes.map(([x, y, w, h]) => [
|
|
2161
|
+
x * k - margin,
|
|
2162
|
+
y * k - margin,
|
|
2163
|
+
w * k + 2 * margin,
|
|
2164
|
+
h * k + 2 * margin
|
|
2165
|
+
])
|
|
2166
|
+
}, a.w * a.h);
|
|
2167
|
+
let moved = 0;
|
|
2168
|
+
for (let i = 0; i < a.w * a.h; i++) {
|
|
2169
|
+
if (masked[i]) continue;
|
|
2170
|
+
for (let c = 0; c < a.ch; c++) if (Math.abs(a.data[i * a.ch + c] - b.data[i * a.ch + c]) > STILL_TOLERANCE.level) {
|
|
2171
|
+
if (++moved > STILL_TOLERANCE.pixels) return false;
|
|
2172
|
+
break;
|
|
2173
|
+
}
|
|
2174
|
+
}
|
|
2175
|
+
return true;
|
|
2176
|
+
}
|
|
2177
|
+
/** One settled moment: probe, reference screenshot, MHTML — raw files into
|
|
2178
|
+
* `<statesDir>/<id>/` (`probe.json`, `live.png`, `page.mhtml`). Read-only on
|
|
2179
|
+
* the page. Throws on a CDP failure; the caller decides whether a missing
|
|
2180
|
+
* state matters (it never fails a take). */
|
|
2181
|
+
async function captureDomState(cdp, args) {
|
|
2182
|
+
const t0 = Date.now();
|
|
2183
|
+
const dir = join(args.statesDir, args.id);
|
|
2184
|
+
mkdirSync(dir, { recursive: true });
|
|
2185
|
+
const at = await cdp.send("Page.getLayoutMetrics").then((m) => ({
|
|
2186
|
+
x: m.cssVisualViewport?.pageX ?? 0,
|
|
2187
|
+
y: m.cssVisualViewport?.pageY ?? 0
|
|
2188
|
+
})).catch(() => ({
|
|
2189
|
+
x: 0,
|
|
2190
|
+
y: 0
|
|
2191
|
+
}));
|
|
2192
|
+
const [r, shot] = await Promise.all([cdp.send("Runtime.evaluate", {
|
|
2193
|
+
expression: DOM_STATE_PROBE_JS,
|
|
2194
|
+
returnByValue: true
|
|
2195
|
+
}).then((x) => ({ value: x.result?.value })), cdp.send("Page.captureScreenshot", {
|
|
2196
|
+
format: "png",
|
|
2197
|
+
clip: {
|
|
2198
|
+
x: at.x,
|
|
2199
|
+
y: at.y,
|
|
2200
|
+
width: args.vw,
|
|
2201
|
+
height: args.vh,
|
|
2202
|
+
scale: 1 / Math.max(1, args.dpr)
|
|
2203
|
+
}
|
|
2204
|
+
}).then((s) => ({ data: s.data }))]);
|
|
2205
|
+
const v = r.value;
|
|
2206
|
+
if (typeof v !== "string") throw new Error("dom-state probe returned nothing");
|
|
2207
|
+
const probe = JSON.parse(v);
|
|
2208
|
+
if (probe.error) throw new Error(`dom-state probe failed in page: ${probe.error}`);
|
|
2209
|
+
const snap = await cdp.send("Page.captureSnapshot", { format: "mhtml" });
|
|
2210
|
+
const loadedFonts = await cdp.send("Runtime.evaluate", {
|
|
2211
|
+
expression: `performance.getEntriesByType("resource").filter(function(e){return /\\.(woff2?|ttf|otf|ttc)(?:[?#]|$)/i.test(e.name)}).map(function(e){return e.name})`,
|
|
2212
|
+
returnByValue: true
|
|
2213
|
+
}).then((x) => Array.isArray(x.result?.value) ? x.result.value.filter((u) => typeof u === "string") : []).catch(() => []);
|
|
2214
|
+
writeFileSync(join(dir, "live.png"), Buffer.from(shot.data, "base64"));
|
|
2215
|
+
writeFileSync(join(dir, "page.mhtml"), snap.data, "utf8");
|
|
2216
|
+
writeFileSync(join(dir, "probe.json"), v, "utf8");
|
|
2217
|
+
return {
|
|
2218
|
+
id: args.id,
|
|
2219
|
+
tMs: args.tMs,
|
|
2220
|
+
...args.step != null ? { step: args.step } : {},
|
|
2221
|
+
dir,
|
|
2222
|
+
probe,
|
|
2223
|
+
...loadedFonts.length ? { loadedFonts } : {},
|
|
2224
|
+
ms: Date.now() - t0
|
|
2225
|
+
};
|
|
2226
|
+
}
|
|
2227
|
+
/** `states/<id>/index.json` from a raw capture (fidelity filled in later) */
|
|
2228
|
+
function buildIndex(raw) {
|
|
2229
|
+
return {
|
|
2230
|
+
version: 1,
|
|
2231
|
+
id: raw.id,
|
|
2232
|
+
url: raw.probe.url,
|
|
2233
|
+
title: raw.probe.title,
|
|
2234
|
+
tMs: raw.tMs,
|
|
2235
|
+
...raw.step != null ? { step: raw.step } : {},
|
|
2236
|
+
viewport: raw.probe.viewport,
|
|
2237
|
+
scroll: raw.probe.scroll,
|
|
2238
|
+
elements: raw.probe.elements,
|
|
2239
|
+
layers: raw.probe.layers
|
|
2240
|
+
};
|
|
2241
|
+
}
|
|
2242
|
+
/**
|
|
2243
|
+
* Convert every raw state to `state.html` + `index.json`, drop the raw
|
|
2244
|
+
* MHTML/probe, then re-open each state in a second page of the SAME browser
|
|
2245
|
+
* (viewport-sized, deviceScaleFactor 1) and score it against `live.png`.
|
|
2246
|
+
* Returns the items for the capture log. A state that fails conversion or
|
|
2247
|
+
* the check stays on disk with `fidelity.ok: false`; nothing here throws
|
|
2248
|
+
* past a single state.
|
|
2249
|
+
*/
|
|
2250
|
+
async function finalizeDomStates(args) {
|
|
2251
|
+
const warn = (l) => console.error(l);
|
|
2252
|
+
const assetsDir = join(args.statesDir, "assets");
|
|
2253
|
+
const items = [];
|
|
2254
|
+
const converted = [];
|
|
2255
|
+
let ffmpeg;
|
|
2256
|
+
try {
|
|
2257
|
+
ffmpeg = await resolveFfmpeg();
|
|
2258
|
+
} catch (e) {
|
|
2259
|
+
warn(`dom-state: no ffmpeg for the fidelity check (${e.message})`);
|
|
2260
|
+
}
|
|
2261
|
+
let fonts = [];
|
|
2262
|
+
try {
|
|
2263
|
+
fonts = await fetchStateFonts(args.browser.cdp, args.states, warn);
|
|
2264
|
+
} catch (e) {
|
|
2265
|
+
warn(`dom-state: the page's web fonts were not fetched (${e.message})`);
|
|
2266
|
+
}
|
|
2267
|
+
for (const raw of args.states) {
|
|
2268
|
+
const index = buildIndex(raw);
|
|
2269
|
+
if (ffmpeg) for (const cv of raw.probe.canvases) {
|
|
2270
|
+
if (!cv.blank || !cv.box) continue;
|
|
2271
|
+
try {
|
|
2272
|
+
cv.dataUrl = await cropPng(ffmpeg, join(raw.dir, "live.png"), cv.box);
|
|
2273
|
+
cv.blank = false;
|
|
2274
|
+
warn(`dom-state ${raw.id}: a canvas read back empty — filled from the screenshot taken with it`);
|
|
2275
|
+
} catch (e) {
|
|
2276
|
+
warn(`dom-state ${raw.id}: an empty canvas could not be filled (${e.message})`);
|
|
2277
|
+
}
|
|
2278
|
+
}
|
|
2279
|
+
try {
|
|
2280
|
+
const mhtml = await readFile(join(raw.dir, "page.mhtml"), "latin1");
|
|
2281
|
+
const { html, unresolved } = convertMhtml(mhtml, raw.probe, {
|
|
2282
|
+
assetsDir,
|
|
2283
|
+
extra: fonts
|
|
2284
|
+
});
|
|
2285
|
+
await writeFile(join(raw.dir, "state.html"), html, "utf8");
|
|
2286
|
+
if (unresolved) warn(`dom-state ${raw.id}: ${unresolved} reference(s) not in the snapshot cut off (the page never loaded them, or loaded them after the snapshot)`);
|
|
2287
|
+
converted.push({
|
|
2288
|
+
raw,
|
|
2289
|
+
index
|
|
2290
|
+
});
|
|
2291
|
+
} catch (e) {
|
|
2292
|
+
warn(`dom-state ${raw.id}: conversion failed (${e.message}) — the film will use the video here`);
|
|
2293
|
+
index.fidelity = {
|
|
2294
|
+
psnr: 0,
|
|
2295
|
+
diffFrac: 1,
|
|
2296
|
+
ok: false
|
|
2297
|
+
};
|
|
2298
|
+
}
|
|
2299
|
+
await writeFile(join(raw.dir, "index.json"), JSON.stringify(index, null, 2));
|
|
2300
|
+
await rm(join(raw.dir, "page.mhtml"), { force: true });
|
|
2301
|
+
await rm(join(raw.dir, "probe.json"), { force: true });
|
|
2302
|
+
}
|
|
2303
|
+
if (converted.length) {
|
|
2304
|
+
let page = null;
|
|
2305
|
+
let noPage = false;
|
|
2306
|
+
let stallsInARow = 0;
|
|
2307
|
+
const openPage = async () => {
|
|
2308
|
+
if (page || noPage || !ffmpeg) return;
|
|
2309
|
+
try {
|
|
2310
|
+
page = await openFidelityPage(args.browser, args.vw, args.vh);
|
|
2311
|
+
} catch (e) {
|
|
2312
|
+
noPage = true;
|
|
2313
|
+
warn(`dom-state: could not open a page for the fidelity check (${e.message})`);
|
|
2314
|
+
}
|
|
2315
|
+
};
|
|
2316
|
+
const dropPage = async (id, e) => {
|
|
2317
|
+
if (!page || !isCdpStall(e)) return;
|
|
2318
|
+
warn(`dom-state ${id}: the check's page stopped answering — the next state gets a new one`);
|
|
2319
|
+
await closeFidelityPage(args.browser, page);
|
|
2320
|
+
page = null;
|
|
2321
|
+
if (++stallsInARow >= 2) {
|
|
2322
|
+
noPage = true;
|
|
2323
|
+
warn("dom-state: two checks in a row stopped answering — the remaining states are not checked");
|
|
2324
|
+
}
|
|
2325
|
+
};
|
|
2326
|
+
for (const { raw, index } of converted) {
|
|
2327
|
+
const stallsBefore = stallsInARow;
|
|
2328
|
+
let fidelity = {
|
|
2329
|
+
psnr: 0,
|
|
2330
|
+
diffFrac: 1,
|
|
2331
|
+
ok: false
|
|
2332
|
+
};
|
|
2333
|
+
await openPage();
|
|
2334
|
+
if (page && ffmpeg) {
|
|
2335
|
+
const statePng = join(raw.dir, "render.png");
|
|
2336
|
+
try {
|
|
2337
|
+
const shot = await renderState(page.cdp, join(raw.dir, "state.html"), args.vw, args.vh);
|
|
2338
|
+
await writeFile(statePng, shot.png);
|
|
2339
|
+
if (args.parts !== false) await measureParts(page.cdp, {
|
|
2340
|
+
dir: raw.dir,
|
|
2341
|
+
index,
|
|
2342
|
+
assetsDir
|
|
2343
|
+
}).catch(async (e) => {
|
|
2344
|
+
warn(`dom-state ${raw.id}: parts not measured (${e.message})`);
|
|
2345
|
+
await dropPage(raw.id, e);
|
|
2346
|
+
});
|
|
2347
|
+
const moving = [...raw.probe.canvases, ...raw.probe.videos].filter((m) => m.box && !m.blank).map((m) => m.box);
|
|
2348
|
+
fidelity = await measureFidelity(ffmpeg, join(raw.dir, "live.png"), statePng, moving);
|
|
2349
|
+
if (args.afterRender) await args.afterRender(page.cdp, raw).catch(async (e) => {
|
|
2350
|
+
warn(`dom-state ${raw.id}: ${e.message}`);
|
|
2351
|
+
await dropPage(raw.id, e);
|
|
2352
|
+
});
|
|
2353
|
+
if (shot.misses) warn(`dom-state ${raw.id}: ${shot.misses} element path(s) did not resolve in state.html`);
|
|
2354
|
+
} catch (e) {
|
|
2355
|
+
warn(`dom-state ${raw.id}: fidelity check failed (${e.message})`);
|
|
2356
|
+
await dropPage(raw.id, e);
|
|
2357
|
+
} finally {
|
|
2358
|
+
await rm(statePng, { force: true });
|
|
2359
|
+
}
|
|
2360
|
+
}
|
|
2361
|
+
if (page && stallsInARow === stallsBefore) stallsInARow = 0;
|
|
2362
|
+
index.fidelity = fidelity;
|
|
2363
|
+
await writeFile(join(raw.dir, "index.json"), JSON.stringify(index, null, 2));
|
|
2364
|
+
}
|
|
2365
|
+
if (page) await closeFidelityPage(args.browser, page);
|
|
2366
|
+
}
|
|
2367
|
+
for (const raw of args.states) {
|
|
2368
|
+
const index = converted.find((c) => c.raw === raw)?.index;
|
|
2369
|
+
items.push({
|
|
2370
|
+
id: raw.id,
|
|
2371
|
+
tMs: raw.tMs,
|
|
2372
|
+
...raw.step != null ? { step: raw.step } : {},
|
|
2373
|
+
...index?.fidelity ? { fidelity: index.fidelity } : { fidelity: {
|
|
2374
|
+
psnr: 0,
|
|
2375
|
+
diffFrac: 1,
|
|
2376
|
+
ok: false
|
|
2377
|
+
} }
|
|
2378
|
+
});
|
|
2379
|
+
}
|
|
2380
|
+
return items;
|
|
2381
|
+
}
|
|
2382
|
+
/** close a page openFidelityPage opened (never throws, never waits long:
|
|
2383
|
+
* its target may be the one that stopped answering) */
|
|
2384
|
+
async function closeFidelityPage(browser, page) {
|
|
2385
|
+
page.cdp.close();
|
|
2386
|
+
await browser.cdp.send("Target.closeTarget", { targetId: page.targetId }, { timeoutMs: 5e3 }).catch(() => {});
|
|
2387
|
+
}
|
|
2388
|
+
/** a second page target in the same Chrome, emulated at vw×vh @1× */
|
|
2389
|
+
async function openFidelityPage(browser, vw, vh) {
|
|
2390
|
+
const { targetId } = await browser.cdp.send("Target.createTarget", { url: "about:blank" });
|
|
2391
|
+
let cdp;
|
|
2392
|
+
try {
|
|
2393
|
+
cdp = await CDP.connect(`ws://127.0.0.1:${browser.port}/devtools/page/${targetId}`);
|
|
2394
|
+
await setUpFidelityPage(cdp, vw, vh);
|
|
2395
|
+
} catch (e) {
|
|
2396
|
+
cdp?.close();
|
|
2397
|
+
await browser.cdp.send("Target.closeTarget", { targetId }, { timeoutMs: 5e3 }).catch(() => {});
|
|
2398
|
+
throw e;
|
|
2399
|
+
}
|
|
2400
|
+
return {
|
|
2401
|
+
cdp,
|
|
2402
|
+
targetId
|
|
2403
|
+
};
|
|
2404
|
+
}
|
|
2405
|
+
async function setUpFidelityPage(cdp, vw, vh) {
|
|
2406
|
+
await cdp.send("Page.enable");
|
|
2407
|
+
await cdp.send("Runtime.enable");
|
|
2408
|
+
await cdp.send("Emulation.setDeviceMetricsOverride", {
|
|
2409
|
+
width: vw,
|
|
2410
|
+
height: vh,
|
|
2411
|
+
deviceScaleFactor: 1,
|
|
2412
|
+
mobile: false
|
|
2413
|
+
});
|
|
2414
|
+
await cdp.send("Network.enable");
|
|
2415
|
+
await cdp.send("Network.setBlockedURLs", { urls: [
|
|
2416
|
+
"http://*",
|
|
2417
|
+
"https://*",
|
|
2418
|
+
"ws://*",
|
|
2419
|
+
"wss://*"
|
|
2420
|
+
] });
|
|
2421
|
+
}
|
|
2422
|
+
/** Open a state.html (file://), wait for the restore script's ready flag, screenshot at 1×. */
|
|
2423
|
+
async function renderState(cdp, stateHtml, vw, vh) {
|
|
2424
|
+
let timer;
|
|
2425
|
+
const loaded = new Promise((res) => {
|
|
2426
|
+
cdp.on("Page.loadEventFired", () => res());
|
|
2427
|
+
timer = setTimeout(res, 15e3);
|
|
2428
|
+
});
|
|
2429
|
+
try {
|
|
2430
|
+
await cdp.send("Page.navigate", { url: pathToFileURL(stateHtml).href });
|
|
2431
|
+
await loaded;
|
|
2432
|
+
} finally {
|
|
2433
|
+
clearTimeout(timer);
|
|
2434
|
+
}
|
|
2435
|
+
const deadline = Date.now() + 1e4;
|
|
2436
|
+
let misses = 0;
|
|
2437
|
+
for (;;) {
|
|
2438
|
+
const r = await cdp.send("Runtime.evaluate", {
|
|
2439
|
+
expression: "document.documentElement.dataset.otReady === \"1\" ? (document.documentElement.dataset.otMisses || \"0\") : \"\"",
|
|
2440
|
+
returnByValue: true
|
|
2441
|
+
});
|
|
2442
|
+
const v = r.result?.value;
|
|
2443
|
+
if (v) {
|
|
2444
|
+
misses = Number(v) || 0;
|
|
2445
|
+
break;
|
|
2446
|
+
}
|
|
2447
|
+
if (Date.now() > deadline) throw new Error("state.html never reported ready");
|
|
2448
|
+
await sleep$2(50);
|
|
2449
|
+
}
|
|
2450
|
+
await sleep$2(60);
|
|
2451
|
+
const at = await cdp.send("Page.getLayoutMetrics").then((m) => ({
|
|
2452
|
+
x: m.cssVisualViewport?.pageX ?? 0,
|
|
2453
|
+
y: m.cssVisualViewport?.pageY ?? 0
|
|
2454
|
+
})).catch(() => ({
|
|
2455
|
+
x: 0,
|
|
2456
|
+
y: 0
|
|
2457
|
+
}));
|
|
2458
|
+
const shot = await cdp.send("Page.captureScreenshot", {
|
|
2459
|
+
format: "png",
|
|
2460
|
+
clip: {
|
|
2461
|
+
x: at.x,
|
|
2462
|
+
y: at.y,
|
|
2463
|
+
width: vw,
|
|
2464
|
+
height: vh,
|
|
2465
|
+
scale: 1
|
|
2466
|
+
}
|
|
2467
|
+
});
|
|
2468
|
+
return {
|
|
2469
|
+
png: Buffer.from(shot.data, "base64"),
|
|
2470
|
+
misses
|
|
2471
|
+
};
|
|
2472
|
+
}
|
|
2473
|
+
/** Most pictures taken per state (each is one clipped screenshot, ~40–80 ms). */
|
|
2474
|
+
const PARTS_MAX_PICTURES = 60;
|
|
2475
|
+
/**
|
|
2476
|
+
* Measure the parts of the saved state open in `cdp` (state.html, ready —
|
|
2477
|
+
* renderState has run) with the compositor's component probe, take a crisp
|
|
2478
|
+
* picture of each kept part (its ink or box ± pad, 3×, the rest of the page
|
|
2479
|
+
* hidden and see-through — what lift(…, { around: "clear" }) shows), and
|
|
2480
|
+
* write `<dir>/parts.json`. Pictures are content-named files in `assetsDir`
|
|
2481
|
+
* (shared with the state's other files), referenced relative to `dir`. The
|
|
2482
|
+
* page's look is put back afterwards (the background override persists
|
|
2483
|
+
* across navigations in this target).
|
|
2484
|
+
*/
|
|
2485
|
+
async function measureParts(cdp, opts) {
|
|
2486
|
+
const r = await cdp.send("Runtime.evaluate", {
|
|
2487
|
+
expression: componentProbeExpression(opts.index, opts.minArea != null ? { minArea: opts.minArea } : {}),
|
|
2488
|
+
returnByValue: true
|
|
2489
|
+
});
|
|
2490
|
+
const raw = r.result?.value;
|
|
2491
|
+
if (typeof raw !== "string") throw new Error(`the component probe returned nothing (${r.exceptionDetails?.text ?? "?"})`);
|
|
2492
|
+
const res = JSON.parse(raw);
|
|
2493
|
+
if ("error" in res) throw new Error(`the component probe failed: ${res.error}`);
|
|
2494
|
+
const file = {
|
|
2495
|
+
version: 1,
|
|
2496
|
+
state: opts.index.id,
|
|
2497
|
+
viewport: res.viewport,
|
|
2498
|
+
scroll: res.scroll,
|
|
2499
|
+
medianTextPx: res.medianTextPx,
|
|
2500
|
+
parts: res.parts,
|
|
2501
|
+
skipped: res.skipped,
|
|
2502
|
+
ms: { measure: res.ms }
|
|
2503
|
+
};
|
|
2504
|
+
if (opts.dom !== false && file.parts.length) await keepPartDom(cdp, opts.dir, file);
|
|
2505
|
+
if (opts.pictures !== false && file.parts.length) {
|
|
2506
|
+
const t0 = Date.now();
|
|
2507
|
+
mkdirSync(opts.assetsDir, { recursive: true });
|
|
2508
|
+
const evaluate = (expression) => cdp.send("Runtime.evaluate", {
|
|
2509
|
+
expression,
|
|
2510
|
+
returnByValue: true
|
|
2511
|
+
});
|
|
2512
|
+
await cdp.send("Emulation.setDefaultBackgroundColorOverride", { color: {
|
|
2513
|
+
r: 0,
|
|
2514
|
+
g: 0,
|
|
2515
|
+
b: 0,
|
|
2516
|
+
a: 0
|
|
2517
|
+
} });
|
|
2518
|
+
let stalled = false;
|
|
2519
|
+
try {
|
|
2520
|
+
await evaluate(`(() => { const st = document.createElement("style"); st.setAttribute("data-ot-clip-css", ""); st.textContent = ${JSON.stringify(CLIP_CLEAR_CSS)}; document.head.appendChild(st); })()`);
|
|
2521
|
+
const at = await cdp.send("Page.getLayoutMetrics").then((m) => ({
|
|
2522
|
+
x: m.cssVisualViewport?.pageX ?? 0,
|
|
2523
|
+
y: m.cssVisualViewport?.pageY ?? 0
|
|
2524
|
+
})).catch(() => ({
|
|
2525
|
+
x: 0,
|
|
2526
|
+
y: 0
|
|
2527
|
+
}));
|
|
2528
|
+
let taken = 0;
|
|
2529
|
+
for (const part of file.parts) {
|
|
2530
|
+
const win = pictureClip(part, file.viewport);
|
|
2531
|
+
if (!win) {
|
|
2532
|
+
part.noPicture = "nothing of it inside the screen";
|
|
2533
|
+
continue;
|
|
2534
|
+
}
|
|
2535
|
+
if (taken >= PARTS_MAX_PICTURES) {
|
|
2536
|
+
part.noPicture = `not taken: ${PARTS_MAX_PICTURES} pictures already taken in this state`;
|
|
2537
|
+
continue;
|
|
2538
|
+
}
|
|
2539
|
+
const sel = JSON.stringify(`[data-ot-id="${part.el}"]`);
|
|
2540
|
+
await evaluate(`document.querySelector(${sel})?.setAttribute("data-ot-clip", "")`);
|
|
2541
|
+
try {
|
|
2542
|
+
const [x, y, w, h] = win.clip;
|
|
2543
|
+
const shot = await cdp.send("Page.captureScreenshot", {
|
|
2544
|
+
format: "png",
|
|
2545
|
+
clip: {
|
|
2546
|
+
x: x + at.x,
|
|
2547
|
+
y: y + at.y,
|
|
2548
|
+
width: w,
|
|
2549
|
+
height: h,
|
|
2550
|
+
scale: win.scale
|
|
2551
|
+
}
|
|
2552
|
+
});
|
|
2553
|
+
const png = Buffer.from(shot.data, "base64");
|
|
2554
|
+
const name = `${createHash("sha1").update(png).digest("hex")}.png`;
|
|
2555
|
+
const path = join(opts.assetsDir, name);
|
|
2556
|
+
if (!existsSync(path)) writeFileSync(path, png);
|
|
2557
|
+
part.picture = relative(opts.dir, path).split(sep).join("/");
|
|
2558
|
+
part.clip = win.clip;
|
|
2559
|
+
part.clipScale = win.scale;
|
|
2560
|
+
taken++;
|
|
2561
|
+
} catch (e) {
|
|
2562
|
+
if (isCdpStall(e)) {
|
|
2563
|
+
stalled = true;
|
|
2564
|
+
throw e;
|
|
2565
|
+
}
|
|
2566
|
+
part.noPicture = `the screenshot failed (${e.message})`;
|
|
2567
|
+
} finally {
|
|
2568
|
+
if (!stalled) await evaluate(`document.querySelector(${sel})?.removeAttribute("data-ot-clip")`);
|
|
2569
|
+
}
|
|
2570
|
+
}
|
|
2571
|
+
} catch (e) {
|
|
2572
|
+
if (isCdpStall(e)) stalled = true;
|
|
2573
|
+
throw e;
|
|
2574
|
+
} finally {
|
|
2575
|
+
if (!stalled) {
|
|
2576
|
+
await evaluate("document.querySelector(\"style[data-ot-clip-css]\")?.remove()").catch(() => {});
|
|
2577
|
+
await cdp.send("Emulation.setDefaultBackgroundColorOverride", {}).catch(() => {});
|
|
2578
|
+
}
|
|
2579
|
+
}
|
|
2580
|
+
file.ms.pictures = Date.now() - t0;
|
|
2581
|
+
}
|
|
2582
|
+
await writeFile(join(opts.dir, "parts.json"), `${JSON.stringify(file, null, 2)}\n`);
|
|
2583
|
+
return file;
|
|
2584
|
+
}
|
|
2585
|
+
/**
|
|
2586
|
+
* Each measured part's elements with their computed styles inlined, its
|
|
2587
|
+
* fonts' families and its natural size — what `parts/<state>-<el>-<kind>.html`
|
|
2588
|
+
* is written from (compositor part-files.ts) — as `<dir>/parts-dom.json`.
|
|
2589
|
+
* One that cannot be read is a line, never a failure of the parts; a page
|
|
2590
|
+
* that stops answering is passed on (the caller drops it).
|
|
2591
|
+
*/
|
|
2592
|
+
async function keepPartDom(cdp, dir, parts) {
|
|
2593
|
+
const path = join(dir, "parts-dom.json");
|
|
2594
|
+
try {
|
|
2595
|
+
const r = await cdp.send("Runtime.evaluate", {
|
|
2596
|
+
expression: partDomExpression(parts.parts.map((p) => p.el)),
|
|
2597
|
+
returnByValue: true
|
|
2598
|
+
}, { timeoutMs: 3e4 });
|
|
2599
|
+
const raw = r.result?.value;
|
|
2600
|
+
if (typeof raw !== "string") throw new Error(`the page returned nothing (${r.exceptionDetails?.text ?? "?"})`);
|
|
2601
|
+
const res = JSON.parse(raw);
|
|
2602
|
+
if ("error" in res) throw new Error(res.error.split("\n")[0]);
|
|
2603
|
+
const file = {
|
|
2604
|
+
version: 1,
|
|
2605
|
+
state: parts.state,
|
|
2606
|
+
...res
|
|
2607
|
+
};
|
|
2608
|
+
await writeFile(path, `${JSON.stringify(file)}\n`);
|
|
2609
|
+
} catch (e) {
|
|
2610
|
+
if (isCdpStall(e)) throw e;
|
|
2611
|
+
await rm(path, { force: true });
|
|
2612
|
+
console.error(`dom-state ${parts.state}: parts not kept as files (${e.message})`);
|
|
2613
|
+
}
|
|
2614
|
+
}
|
|
2615
|
+
/**
|
|
2616
|
+
* Measure the parts of saved states that already exist (each a folder with
|
|
2617
|
+
* state.html + index.json) — for states saved before parts.json, which
|
|
2618
|
+
* `open-take components` meets. One page in `browser`, emulated at each
|
|
2619
|
+
* state's own viewport @1×, network blocked, as the fidelity check opens
|
|
2620
|
+
* them. A state that cannot be measured is a line in `failed`.
|
|
2621
|
+
*/
|
|
2622
|
+
async function measureStateDirs(args) {
|
|
2623
|
+
const measured = [];
|
|
2624
|
+
const failed = [];
|
|
2625
|
+
let page = null;
|
|
2626
|
+
try {
|
|
2627
|
+
for (const dir of args.dirs) {
|
|
2628
|
+
const index = readStateIndex(dir);
|
|
2629
|
+
if (typeof index === "string") {
|
|
2630
|
+
failed.push({
|
|
2631
|
+
dir,
|
|
2632
|
+
why: index
|
|
2633
|
+
});
|
|
2634
|
+
continue;
|
|
2635
|
+
}
|
|
2636
|
+
const { w, h } = index.viewport;
|
|
2637
|
+
try {
|
|
2638
|
+
if (!page) page = await openFidelityPage(args.browser, w, h);
|
|
2639
|
+
else await page.cdp.send("Emulation.setDeviceMetricsOverride", {
|
|
2640
|
+
width: w,
|
|
2641
|
+
height: h,
|
|
2642
|
+
deviceScaleFactor: 1,
|
|
2643
|
+
mobile: false
|
|
2644
|
+
});
|
|
2645
|
+
await renderState(page.cdp, join(dir, "state.html"), w, h);
|
|
2646
|
+
const parts = await measureParts(page.cdp, {
|
|
2647
|
+
dir,
|
|
2648
|
+
index,
|
|
2649
|
+
assetsDir: join(dir, "..", "assets"),
|
|
2650
|
+
...args.pictures != null ? { pictures: args.pictures } : {},
|
|
2651
|
+
...args.minArea != null ? { minArea: args.minArea } : {}
|
|
2652
|
+
});
|
|
2653
|
+
measured.push({
|
|
2654
|
+
dir,
|
|
2655
|
+
parts
|
|
2656
|
+
});
|
|
2657
|
+
} catch (e) {
|
|
2658
|
+
failed.push({
|
|
2659
|
+
dir,
|
|
2660
|
+
why: e.message
|
|
2661
|
+
});
|
|
2662
|
+
if (page && isCdpStall(e)) {
|
|
2663
|
+
await closeFidelityPage(args.browser, page);
|
|
2664
|
+
page = null;
|
|
2665
|
+
}
|
|
2666
|
+
}
|
|
2667
|
+
}
|
|
2668
|
+
} finally {
|
|
2669
|
+
if (page) await closeFidelityPage(args.browser, page);
|
|
2670
|
+
}
|
|
2671
|
+
return {
|
|
2672
|
+
measured,
|
|
2673
|
+
failed
|
|
2674
|
+
};
|
|
2675
|
+
}
|
|
2676
|
+
/** One stderr line: what the states cost the take and how they scored. */
|
|
2677
|
+
function summarizeDomStates(states, items) {
|
|
2678
|
+
const moving = items.filter((i) => i.moving).map((i) => i.id);
|
|
2679
|
+
if (!states.length) return moving.length ? `captureTakeCDP: DOM states — none saved: the page was still moving at ${moving.join(", ")} (use the recording)` : "captureTakeCDP: DOM states — none captured";
|
|
2680
|
+
const total = states.reduce((s, r) => s + r.ms, 0);
|
|
2681
|
+
const each = states.map((r) => `${r.id} ${r.ms}ms`).join(", ");
|
|
2682
|
+
const scored = items.filter((i) => i.fidelity);
|
|
2683
|
+
const ok = scored.filter((i) => i.fidelity.ok).length;
|
|
2684
|
+
const worst = scored.reduce((w, i) => !w || i.fidelity.psnr < w.fidelity.psnr ? i : w, null);
|
|
2685
|
+
return `captureTakeCDP: DOM states — ${states.length} captured, +${(total / 1e3).toFixed(1)}s on the take (${each}); ` + (moving.length ? `${moving.join(", ")} not saved — the page was still moving there (use the recording); ` : "") + `fidelity ${ok}/${scored.length} ok` + (worst ? ` (lowest ${worst.id}: psnr ${worst.fidelity.psnr.toFixed(1)}, ${(worst.fidelity.diffFrac * 100).toFixed(1)}% px differ)` : "");
|
|
2686
|
+
}
|
|
2687
|
+
|
|
2688
|
+
//#endregion
|
|
2689
|
+
//#region src/nav.ts
|
|
2690
|
+
/**
|
|
2691
|
+
* Resolve a navigate step to one absolute URL, or null when it cannot be.
|
|
2692
|
+
*
|
|
2693
|
+
* Precedence is `href` > `url` > `current`: a destination READ FROM THE PAGE
|
|
2694
|
+
* beats one written in the plan, because it is the one that reflects what the
|
|
2695
|
+
* app just did. `current` last means `{ query }` on its own is "reload this
|
|
2696
|
+
* same page with these params" rather than an error.
|
|
2697
|
+
*/
|
|
2698
|
+
function resolveNavigateUrl(t) {
|
|
2699
|
+
const base = safeUrl(t.current);
|
|
2700
|
+
const raw = t.href || t.url || t.current;
|
|
2701
|
+
if (!raw) return null;
|
|
2702
|
+
const dest = safeUrl(raw, base);
|
|
2703
|
+
if (!dest) return null;
|
|
2704
|
+
for (const [k, v] of Object.entries(t.query ?? {})) dest.searchParams.set(k, v);
|
|
2705
|
+
return dest.toString();
|
|
2706
|
+
}
|
|
2707
|
+
function safeUrl(raw, base) {
|
|
2708
|
+
try {
|
|
2709
|
+
return new URL(raw, base);
|
|
2710
|
+
} catch {
|
|
2711
|
+
return void 0;
|
|
2712
|
+
}
|
|
2713
|
+
}
|
|
2714
|
+
|
|
2715
|
+
//#endregion
|
|
2716
|
+
//#region src/precheck.ts
|
|
2717
|
+
/** Thrown by the capture when error-severity findings refuse the shoot.
|
|
2718
|
+
* Carries the FULL structured findings (warns included) so the CLI can emit
|
|
2719
|
+
* the machine-readable defects block and exit 2 like every other gate
|
|
2720
|
+
* verdict — the message is only the human rendering of the same facts, and
|
|
2721
|
+
* flattening the findings into it is how the measured values used to get
|
|
2722
|
+
* lost on the way to the repair loop. */
|
|
2723
|
+
var PrecheckRefusal = class extends Error {
|
|
2724
|
+
issues;
|
|
2725
|
+
constructor(message, issues) {
|
|
2726
|
+
super(message);
|
|
2727
|
+
this.name = "PrecheckRefusal";
|
|
2728
|
+
this.issues = issues;
|
|
2729
|
+
}
|
|
2730
|
+
};
|
|
2731
|
+
const FIELD_ORDER = {
|
|
2732
|
+
click: ["text", "selector"],
|
|
2733
|
+
type: ["text", "selector"],
|
|
2734
|
+
look: ["text", "selector"],
|
|
2735
|
+
hover: ["text", "selector"],
|
|
2736
|
+
press: ["text", "selector"],
|
|
2737
|
+
select: ["selector", "text"],
|
|
2738
|
+
scroll: ["toSelector", "toText"],
|
|
2739
|
+
drag: ["selector", "text"]
|
|
2740
|
+
};
|
|
2741
|
+
const DRAG_TO_ORDER = ["toSelector", "toText"];
|
|
2742
|
+
const MUTATING = new Set([
|
|
2743
|
+
"click",
|
|
2744
|
+
"type",
|
|
2745
|
+
"press",
|
|
2746
|
+
"select",
|
|
2747
|
+
"drag",
|
|
2748
|
+
"dropFiles",
|
|
2749
|
+
"navigate",
|
|
2750
|
+
"hover",
|
|
2751
|
+
"scroll"
|
|
2752
|
+
]);
|
|
2753
|
+
/** Every named target in the plan, in step order, tagged cold/late. */
|
|
2754
|
+
function planTargets(steps) {
|
|
2755
|
+
const out = [];
|
|
2756
|
+
let cold = true;
|
|
2757
|
+
for (let i = 0; i < steps.length; i++) {
|
|
2758
|
+
const s = steps[i];
|
|
2759
|
+
const action = String(s.action ?? "");
|
|
2760
|
+
const has = (f) => typeof s[f] === "string" && s[f];
|
|
2761
|
+
/** the first field of this group the step actually carries */
|
|
2762
|
+
const winner = (order$1) => order$1.find(has);
|
|
2763
|
+
const order = FIELD_ORDER[action];
|
|
2764
|
+
const dragTo = action === "drag" && s.to ? null : winner(DRAG_TO_ORDER);
|
|
2765
|
+
const primary = action === "drag" && s.from ? null : winner(order ?? []);
|
|
2766
|
+
const isUsed = (field) => !order || field === primary || field === dragTo;
|
|
2767
|
+
const add = (field, kind, revealOnly) => {
|
|
2768
|
+
const v = s[field];
|
|
2769
|
+
if (typeof v === "string" && v) out.push({
|
|
2770
|
+
step: i,
|
|
2771
|
+
action,
|
|
2772
|
+
field,
|
|
2773
|
+
kind,
|
|
2774
|
+
value: v,
|
|
2775
|
+
cold: cold && !revealOnly,
|
|
2776
|
+
used: isUsed(field),
|
|
2777
|
+
...revealOnly ? { revealOnly } : {}
|
|
2778
|
+
});
|
|
2779
|
+
};
|
|
2780
|
+
switch (action) {
|
|
2781
|
+
case "click":
|
|
2782
|
+
case "hover":
|
|
2783
|
+
case "look":
|
|
2784
|
+
case "type":
|
|
2785
|
+
case "select":
|
|
2786
|
+
add("selector", "selector");
|
|
2787
|
+
add("text", "text");
|
|
2788
|
+
break;
|
|
2789
|
+
case "press":
|
|
2790
|
+
add("selector", "selector", true);
|
|
2791
|
+
add("text", "text", true);
|
|
2792
|
+
break;
|
|
2793
|
+
case "scroll":
|
|
2794
|
+
add("toSelector", "selector");
|
|
2795
|
+
add("toText", "text");
|
|
2796
|
+
break;
|
|
2797
|
+
case "drag": {
|
|
2798
|
+
const hasPath = Array.isArray(s.path) && s.path.length > 0;
|
|
2799
|
+
if (!hasPath) {
|
|
2800
|
+
add("selector", "selector");
|
|
2801
|
+
add("text", "text");
|
|
2802
|
+
add("toSelector", "selector");
|
|
2803
|
+
add("toText", "text");
|
|
2804
|
+
}
|
|
2805
|
+
break;
|
|
2806
|
+
}
|
|
2807
|
+
case "navigate": {
|
|
2808
|
+
const hf = s.hrefFrom;
|
|
2809
|
+
const hfField = hf?.selector ? "selector" : hf?.text ? "text" : null;
|
|
2810
|
+
for (const [sub, kind] of [["selector", "selector"], ["text", "text"]]) {
|
|
2811
|
+
const v = hf?.[sub];
|
|
2812
|
+
if (typeof v === "string" && v) out.push({
|
|
2813
|
+
step: i,
|
|
2814
|
+
action,
|
|
2815
|
+
field: `hrefFrom.${sub}`,
|
|
2816
|
+
kind,
|
|
2817
|
+
value: v,
|
|
2818
|
+
cold,
|
|
2819
|
+
used: sub === hfField
|
|
2820
|
+
});
|
|
2821
|
+
}
|
|
2822
|
+
break;
|
|
2823
|
+
}
|
|
2824
|
+
default: break;
|
|
2825
|
+
}
|
|
2826
|
+
if (MUTATING.has(action)) cold = false;
|
|
2827
|
+
}
|
|
2828
|
+
return out;
|
|
2829
|
+
}
|
|
2830
|
+
/** The candidate set the ENGINE's by-text locator queries for this action —
|
|
2831
|
+
* imported from capture.ts so the probe and the real resolver cannot drift. */
|
|
2832
|
+
function textCandidates(action) {
|
|
2833
|
+
switch (action) {
|
|
2834
|
+
case "type": return FIELD_CANDIDATES;
|
|
2835
|
+
case "click": return CLICK_CANDIDATES;
|
|
2836
|
+
case "scroll": return SCROLL_CANDIDATES;
|
|
2837
|
+
case "navigate": return "a,button,[role=link],[role=button],[aria-label],[title]";
|
|
2838
|
+
default: return BOX_CANDIDATES;
|
|
2839
|
+
}
|
|
2840
|
+
}
|
|
2841
|
+
/** One page eval: resolve a target and DESCRIBE the outcome (no side effects). */
|
|
2842
|
+
function probeJs(kind, value, action) {
|
|
2843
|
+
const v = JSON.stringify(value);
|
|
2844
|
+
const desc = "function desc(m){if(!m)return null;var r=m.getBoundingClientRect();return {tag:m.tagName,w:Math.round(r.width),h:Math.round(r.height),x:Math.round(r.x),y:Math.round(r.y),inMain:!!m.closest('main')};}";
|
|
2845
|
+
if (kind === "selector") return `(function(){${desc}var all;try{all=Array.prototype.slice.call(document.querySelectorAll(${v}));}catch(e){return JSON.stringify({err:String(e.message||e)});}return JSON.stringify({count:all.length,first:desc(all[0]||null)});})()`;
|
|
2846
|
+
if (action === "select") return `(function(){${desc}var n=${v};var els=Array.prototype.slice.call(document.querySelectorAll('select'));var hits=els.filter(function(e){var a=(e.getAttribute('aria-label')||'').trim();if(a===n)return true;var id=e.id;if(id){var l=document.querySelector('label[for="'+id+'"]');if(l&&(l.textContent||'').trim().indexOf(n)>=0)return true;}var p=e.closest('label');if(p&&(p.textContent||'').trim().indexOf(n)>=0)return true;return false;});return JSON.stringify({count:hits.length?1:0,exact:hits.length,first:desc(hits[0]||null)});})()`;
|
|
2847
|
+
const set = textCandidates(action);
|
|
2848
|
+
return `(function(){${desc}${NAME_JS}var els=Array.prototype.slice.call(document.querySelectorAll('${set}'));var m=pick(els,${v});` + (action === "click" ? `if(!m){var fb=Array.prototype.slice.call(document.querySelectorAll('${CLICK_FALLBACK_CANDIDATES}'));m=pick(fb,${v});if(m)els=fb;}` : "") + `var exact=0;for(var i=0;i<els.length;i++){if(names(els[i]).indexOf(${v})!==-1)exact++;}var how=m?(names(m).indexOf(${v})!==-1?'exact':'substring'):'none';var share=how==='exact'?1:0,pn=null;if(m&&how==='substring'){var mn=names(m);for(var k=0;k<mn.length;k++){if(mn[k].indexOf(${v})!==-1&&(pn===null||mn[k].length<pn.length))pn=mn[k];}if(pn)share=${v}.length/pn.length;}function nm(e){var n=names(e),k;for(k=0;k<n.length;k++){if(n[k]===${v})return 'exact';}if(${v}.length>6){for(k=0;k<n.length;k++){if(n[k].length>6&&(n[k].indexOf(${v})!==-1||${v}.indexOf(n[k])!==-1))return 'contains';}}return null;}var inM=[],same=false,am=document.querySelectorAll('main *'),vwA=window.innerWidth*window.innerHeight;for(var i=0;i<am.length;i++){var e=am[i],mk=nm(e);if(!mk)continue;if(m&&e===m){if(mk==='exact')same=true;continue;}if(m&&(m.contains(e)||e.contains(m))){same=true;continue;}var d=desc(e);if(d.w<3||d.h<3)continue;if(mk==='contains'&&d.w*d.h>vwA*0.25)continue;d.match=mk;inM.push(d);}inM.sort(function(a,b){if(a.match!==b.match)return a.match==='exact'?-1:1;return a.w*a.h-b.w*b.h;});return JSON.stringify({count:m?1:0,exact:exact,first:desc(m),how:how,pickNameShare:Math.round(share*100)/100,pickName:pn?pn.slice(0,60):null,pickIsNamed:same,mainMatches:inM.slice(0,4)});})()`;
|
|
2849
|
+
}
|
|
2850
|
+
/** C3.5 parse-intent mismatch: the pick and the same-named in-main element
|
|
2851
|
+
* disagree by more than a step's worth of geometry. Validated against the 36
|
|
2852
|
+
* plans of the X5 corpus (23 poisoned targets). A pick that covers most of
|
|
2853
|
+
* its own label (share >= 0.5) is the named control, abbreviated — for that
|
|
2854
|
+
* shape only an EXACT in-main duplicate is evidence of anything; body copy
|
|
2855
|
+
* merely mentioning the phrase is how landing pages talk about their own
|
|
2856
|
+
* buttons. */
|
|
2857
|
+
const FAR_PX = 150;
|
|
2858
|
+
const ABBREVIATION_SHARE = .5;
|
|
2859
|
+
function parseIntentMismatch(p) {
|
|
2860
|
+
const pick = p.first;
|
|
2861
|
+
if (!pick || typeof pick.x !== "number" || typeof pick.y !== "number") return null;
|
|
2862
|
+
if (p.pickIsNamed) return null;
|
|
2863
|
+
let matches = (p.mainMatches ?? []).filter((m) => typeof m.x === "number" && typeof m.y === "number");
|
|
2864
|
+
if ((p.pickNameShare ?? 0) >= ABBREVIATION_SHARE) matches = matches.filter((m) => m.match === "exact");
|
|
2865
|
+
if (!matches.length) return null;
|
|
2866
|
+
const cx = pick.x + pick.w / 2;
|
|
2867
|
+
const cy = pick.y + pick.h / 2;
|
|
2868
|
+
for (const m of matches) if (Math.abs(m.x + m.w / 2 - cx) <= 5 && Math.abs(m.y + m.h / 2 - cy) <= 5) return null;
|
|
2869
|
+
const intended = matches[0];
|
|
2870
|
+
const far = Math.abs(intended.x + intended.w / 2 - cx) > FAR_PX || Math.abs(intended.y + intended.h / 2 - cy) > FAR_PX;
|
|
2871
|
+
return !pick.inMain || far ? {
|
|
2872
|
+
pick,
|
|
2873
|
+
intended
|
|
2874
|
+
} : null;
|
|
2875
|
+
}
|
|
2876
|
+
/** Resolve every plan target through `evalJson` (a Runtime.evaluate wrapper)
|
|
2877
|
+
* and grade the outcomes. Cold-prefix misses get ONE retry after `retryMs` —
|
|
2878
|
+
* a hydration-slow page may mount its controls a beat after load. */
|
|
2879
|
+
async function precheckPlan(steps, evalJson, opts) {
|
|
2880
|
+
const sleep$5 = opts?.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
2881
|
+
const targets = planTargets(steps).filter((t) => t.used);
|
|
2882
|
+
const probes = new Map();
|
|
2883
|
+
const probe = async (t) => await evalJson(probeJs(t.kind, t.value, t.action)) ?? {};
|
|
2884
|
+
for (const t of targets) probes.set(t, await probe(t));
|
|
2885
|
+
const misses = targets.filter((t) => !probes.get(t)?.err && !probes.get(t)?.count);
|
|
2886
|
+
if (misses.length) {
|
|
2887
|
+
await sleep$5(opts?.retryMs ?? 1500);
|
|
2888
|
+
for (const t of misses) probes.set(t, await probe(t));
|
|
2889
|
+
}
|
|
2890
|
+
const issues = [];
|
|
2891
|
+
const lateMisses = [];
|
|
2892
|
+
for (const t of targets) {
|
|
2893
|
+
const p = probes.get(t) ?? {};
|
|
2894
|
+
const path = `steps[${t.step}].${t.field}`;
|
|
2895
|
+
const name = `${t.action} ${JSON.stringify(t.value)}`;
|
|
2896
|
+
if (p.err) {
|
|
2897
|
+
issues.push({
|
|
2898
|
+
severity: "error",
|
|
2899
|
+
path,
|
|
2900
|
+
message: `${name}: invalid selector — the page rejected it (${p.err})`,
|
|
2901
|
+
fix: "fix the selector syntax; the capture would skip every use of it"
|
|
2902
|
+
});
|
|
2903
|
+
continue;
|
|
2904
|
+
}
|
|
2905
|
+
if (!p.count) {
|
|
2906
|
+
if (t.revealOnly) continue;
|
|
2907
|
+
if (t.cold) issues.push({
|
|
2908
|
+
severity: "error",
|
|
2909
|
+
path,
|
|
2910
|
+
message: `${name}: target not found in the page as loaded — this step runs before anything has changed the page, so it is CERTAIN to be skipped. Refusing in seconds what would fail after the full capture.`,
|
|
2911
|
+
fix: "point it at an element that exists at load (`open-take inspect <url>` lists them), or move it after the step that reveals it"
|
|
2912
|
+
});
|
|
2913
|
+
else lateMisses.push(t);
|
|
2914
|
+
continue;
|
|
2915
|
+
}
|
|
2916
|
+
if (t.kind === "text" && !t.revealOnly) {
|
|
2917
|
+
const mm = parseIntentMismatch(p);
|
|
2918
|
+
if (mm) {
|
|
2919
|
+
const certain = t.cold && p.how === "substring" && !mm.pick.inMain && (p.pickNameShare ?? 0) < ABBREVIATION_SHARE;
|
|
2920
|
+
issues.push({
|
|
2921
|
+
severity: certain ? "error" : "warn",
|
|
2922
|
+
path,
|
|
2923
|
+
message: `${name}: resolves to the WRONG element. The by-text lookup for ${t.action} searches only its candidate set and ${p.how === "substring" ? "substring-" : ""}matched a ${mm.pick.w}x${mm.pick.h} ${mm.pick.tag.toLowerCase()} at (${mm.pick.x},${mm.pick.y})${mm.pick.inMain ? "" : " OUTSIDE <main>"}${p.pickName ? ` (its actual name: ${JSON.stringify(p.pickName)})` : ""}, while the element named ${JSON.stringify(t.value.slice(0, 40))} is a ${mm.intended.tag.toLowerCase()} at (${mm.intended.x},${mm.intended.y}) inside <main>. The step would land on the impostor.`,
|
|
2924
|
+
fix: `target the in-main ${mm.intended.tag.toLowerCase()} with a CSS selector scoped to \`main\` (\`open-take inspect <url>\` lists one), or name a real control instead`
|
|
2925
|
+
});
|
|
2926
|
+
continue;
|
|
2927
|
+
}
|
|
2928
|
+
}
|
|
2929
|
+
if (t.kind === "selector" && (p.count ?? 0) > 1) {
|
|
2930
|
+
const z = p.first && (p.first.w === 0 || p.first.h === 0) ? " — and the first match is ZERO-SIZE" : "";
|
|
2931
|
+
issues.push({
|
|
2932
|
+
severity: "warn",
|
|
2933
|
+
path,
|
|
2934
|
+
message: `${name}: matches ${p.count} nodes; the engine takes the FIRST in document order${z}. A sidebar thumbnail or an off-screen clone outranking the real element is exactly how a whole take dies.`,
|
|
2935
|
+
fix: "qualify the selector until it matches once (e.g. scope it to `main`)"
|
|
2936
|
+
});
|
|
2937
|
+
continue;
|
|
2938
|
+
}
|
|
2939
|
+
if (t.kind === "text" && (p.exact ?? 0) > 1) {
|
|
2940
|
+
issues.push({
|
|
2941
|
+
severity: "warn",
|
|
2942
|
+
path,
|
|
2943
|
+
message: `${name}: ${p.exact} elements carry this exact accessible name; the engine takes the first in document order`,
|
|
2944
|
+
fix: "use a more specific name, or a CSS selector scoped to the intended region"
|
|
2945
|
+
});
|
|
2946
|
+
continue;
|
|
2947
|
+
}
|
|
2948
|
+
if (p.first && (p.first.w === 0 || p.first.h === 0)) issues.push({
|
|
2949
|
+
severity: "warn",
|
|
2950
|
+
path,
|
|
2951
|
+
message: t.cold ? `${name}: resolves to a zero-size element — the cursor has nowhere real to land` : `${name}: has no size in the page as loaded (hidden until an earlier step shows it?) — fine if one does; if none does, the step lands on nothing`
|
|
2952
|
+
});
|
|
2953
|
+
}
|
|
2954
|
+
if (lateMisses.length) issues.push({
|
|
2955
|
+
severity: "warn",
|
|
2956
|
+
path: "steps",
|
|
2957
|
+
message: `${lateMisses.length} target${lateMisses.length === 1 ? " is" : "s are"} not in the initial DOM (${lateMisses.map((t) => `steps[${t.step}] ${JSON.stringify(t.value)}`).join(", ")}) — fine if earlier steps reveal them; any that never appears is SKIPPED at capture time (and the run exits non-zero)`
|
|
2958
|
+
});
|
|
2959
|
+
return issues;
|
|
2960
|
+
}
|
|
2961
|
+
|
|
2962
|
+
//#endregion
|
|
2963
|
+
//#region src/product-audio.ts
|
|
2964
|
+
/** the CDP binding the page posts blocks through */
|
|
2965
|
+
const PRODUCT_AUDIO_BINDING = "__openTakeProductAudio";
|
|
2966
|
+
/** Saved fetched sound files: per file and in total. Larger ones are only listed. */
|
|
2967
|
+
const MAX_SAVED_FILE_BYTES = 8 * 1024 * 1024;
|
|
2968
|
+
const MAX_SAVED_TOTAL_BYTES = 48 * 1024 * 1024;
|
|
2969
|
+
const MAX_LISTED_FILES = 200;
|
|
2970
|
+
const AUDIO_EXT = /\.(mp3|wav|wave|ogg|oga|opus|m4a|aac|flac|weba|caf|aif|aiff)(?:$|[?#])/i;
|
|
2971
|
+
const PRODUCT_AUDIO_INIT_JS = `(() => {
|
|
2972
|
+
if (window.__openTakeAudioTap || typeof AudioNode === "undefined") return;
|
|
2973
|
+
window.__openTakeAudioTap = true;
|
|
2974
|
+
var NAME = ${JSON.stringify(PRODUCT_AUDIO_BINDING)};
|
|
2975
|
+
var post = function (s) { try { var f = window[NAME]; if (typeof f === "function") f(s); } catch (e) {} };
|
|
2976
|
+
var connect = AudioNode.prototype.connect;
|
|
2977
|
+
var disconnect = AudioNode.prototype.disconnect;
|
|
2978
|
+
var taps = new WeakMap();
|
|
2979
|
+
var nextId = 0;
|
|
2980
|
+
var DOC = Math.random().toString(36).slice(2, 10);
|
|
2981
|
+
var toB64 = function (f32) {
|
|
2982
|
+
var u8 = new Uint8Array(f32.buffer), s = "";
|
|
2983
|
+
for (var i = 0; i < u8.length; i += 0x8000) s += String.fromCharCode.apply(null, u8.subarray(i, i + 0x8000));
|
|
2984
|
+
return btoa(s);
|
|
2985
|
+
};
|
|
2986
|
+
// Wall-clock ms at which the page's audio graph PRODUCED context time t:
|
|
2987
|
+
// the output timestamp pairs a context time with the moment it leaves the
|
|
2988
|
+
// speakers, and the output device's own latency (outputLatency) is taken
|
|
2989
|
+
// back off — that delay belongs to the capturing browser (its fake output,
|
|
2990
|
+
// see launchBrowser, reports ~16 ms), not to the product, and a film's own
|
|
2991
|
+
// playback adds its own. Right after a context starts it reports
|
|
2992
|
+
// contextTime 0 (not yet paired): then "now" plus the base latency.
|
|
2993
|
+
var producedAt = function (ctx, t) {
|
|
2994
|
+
var o = null;
|
|
2995
|
+
try { o = ctx.getOutputTimestamp(); } catch (e) {}
|
|
2996
|
+
if (o && o.contextTime > 0 && o.performanceTime > 0)
|
|
2997
|
+
return performance.timeOrigin + o.performanceTime + (t - o.contextTime - (ctx.outputLatency || 0)) * 1000;
|
|
2998
|
+
return performance.timeOrigin + performance.now() + (t - ctx.currentTime + (ctx.baseLatency || 0)) * 1000;
|
|
2999
|
+
};
|
|
3000
|
+
var tapFor = function (ctx, kind) {
|
|
3001
|
+
if (taps.has(ctx)) return taps.get(ctx);
|
|
3002
|
+
var t = null;
|
|
3003
|
+
try {
|
|
3004
|
+
if (typeof AudioContext !== "undefined" && ctx instanceof AudioContext) {
|
|
3005
|
+
var bus = ctx.createGain();
|
|
3006
|
+
var sp = ctx.createScriptProcessor(4096, 2, 2);
|
|
3007
|
+
connect.call(bus, sp);
|
|
3008
|
+
connect.call(sp, ctx.destination);
|
|
3009
|
+
var id = DOC + "." + ++nextId;
|
|
3010
|
+
post("S " + id + " " + ctx.sampleRate + " " + kind + " " + (ctx.baseLatency || 0));
|
|
3011
|
+
var next = -1;
|
|
3012
|
+
sp.onaudioprocess = function (e) {
|
|
3013
|
+
try {
|
|
3014
|
+
// a buffer the main thread was too busy to take is skipped, and
|
|
3015
|
+
// its sound is lost to the tap (the page itself still played it)
|
|
3016
|
+
var span = e.inputBuffer.length / ctx.sampleRate;
|
|
3017
|
+
if (next >= 0 && e.playbackTime - next > span / 2)
|
|
3018
|
+
post("G " + id + " " + producedAt(ctx, next - 2 * span).toFixed(3) + " " + ((e.playbackTime - next) * 1000).toFixed(0));
|
|
3019
|
+
next = e.playbackTime + span;
|
|
3020
|
+
var ob = e.outputBuffer;
|
|
3021
|
+
for (var c = 0; c < ob.numberOfChannels; c++) ob.getChannelData(c).fill(0);
|
|
3022
|
+
var ib = e.inputBuffer, n = ib.length;
|
|
3023
|
+
var L = ib.getChannelData(0), R = ib.numberOfChannels > 1 ? ib.getChannelData(1) : L;
|
|
3024
|
+
var peak = 0;
|
|
3025
|
+
for (var i = 0; i < n; i++) { var a = L[i] < 0 ? -L[i] : L[i], b = R[i] < 0 ? -R[i] : R[i]; if (a > peak) peak = a; if (b > peak) peak = b; }
|
|
3026
|
+
if (peak < 1e-5) return;
|
|
3027
|
+
var f = new Float32Array(n * 2);
|
|
3028
|
+
for (var j = 0; j < n; j++) { f[2 * j] = L[j]; f[2 * j + 1] = R[j]; }
|
|
3029
|
+
// a ScriptProcessor hands over its input two buffers before the
|
|
3030
|
+
// playbackTime it reports (Chrome double-buffers it): the block's
|
|
3031
|
+
// audio is the graph's output at playbackTime - 2 * n / rate. The
|
|
3032
|
+
// block's frame on the context's own sample clock goes along, so
|
|
3033
|
+
// the runtime can lay consecutive blocks sample-exactly end to end
|
|
3034
|
+
// (the wall-clock estimate jitters by a few samples per block).
|
|
3035
|
+
var at = e.playbackTime - (2 * n) / ctx.sampleRate;
|
|
3036
|
+
post("B " + id + " " + producedAt(ctx, at).toFixed(3) + " " + ((ctx.outputLatency || 0) * 1000).toFixed(1) + " " + Math.round(at * ctx.sampleRate) + " " + toB64(f));
|
|
3037
|
+
} catch (err) {}
|
|
3038
|
+
};
|
|
3039
|
+
t = { bus: bus, sp: sp };
|
|
3040
|
+
}
|
|
3041
|
+
} catch (e) { t = null; }
|
|
3042
|
+
taps.set(ctx, t);
|
|
3043
|
+
return t;
|
|
3044
|
+
};
|
|
3045
|
+
AudioNode.prototype.connect = function (dest) {
|
|
3046
|
+
var r = connect.apply(this, arguments);
|
|
3047
|
+
try {
|
|
3048
|
+
if (dest instanceof AudioDestinationNode) {
|
|
3049
|
+
var t = tapFor(this.context, "webaudio");
|
|
3050
|
+
if (t && t.bus !== this) connect.call(this, t.bus, arguments.length > 1 ? arguments[1] : 0);
|
|
3051
|
+
}
|
|
3052
|
+
} catch (e) {}
|
|
3053
|
+
return r;
|
|
3054
|
+
};
|
|
3055
|
+
AudioNode.prototype.disconnect = function (dest) {
|
|
3056
|
+
var r = disconnect.apply(this, arguments);
|
|
3057
|
+
try {
|
|
3058
|
+
if (dest instanceof AudioDestinationNode) {
|
|
3059
|
+
var t = taps.get(this.context);
|
|
3060
|
+
if (t) { try { arguments.length > 1 ? disconnect.call(this, t.bus, arguments[1]) : disconnect.call(this, t.bus); } catch (e) {} }
|
|
3061
|
+
}
|
|
3062
|
+
} catch (e) {}
|
|
3063
|
+
return r;
|
|
3064
|
+
};
|
|
3065
|
+
// <audio>/<video>: captureStream() leaves the element's own output alone —
|
|
3066
|
+
// but it also ignores the element's muted/volume, so each element's tap goes
|
|
3067
|
+
// through a gain that follows them (a muted hero video stays unheard). An
|
|
3068
|
+
// element the page routes into its own graph (createMediaElementSource) is
|
|
3069
|
+
// already heard at that graph's speakers, so its stream tap is silenced.
|
|
3070
|
+
var mediaCtx = null;
|
|
3071
|
+
var tappedMedia = new WeakSet();
|
|
3072
|
+
var routed = new WeakSet();
|
|
3073
|
+
var mediaGains = new WeakMap();
|
|
3074
|
+
var follow = function (el) {
|
|
3075
|
+
var g = mediaGains.get(el);
|
|
3076
|
+
if (g) { try { g.gain.value = routed.has(el) || el.muted ? 0 : el.volume; } catch (e) {} }
|
|
3077
|
+
};
|
|
3078
|
+
if (typeof AudioContext !== "undefined" && AudioContext.prototype.createMediaElementSource) {
|
|
3079
|
+
var cmes = AudioContext.prototype.createMediaElementSource;
|
|
3080
|
+
AudioContext.prototype.createMediaElementSource = function (el) {
|
|
3081
|
+
var r = cmes.apply(this, arguments);
|
|
3082
|
+
try { routed.add(el); follow(el); } catch (e) {}
|
|
3083
|
+
return r;
|
|
3084
|
+
};
|
|
3085
|
+
}
|
|
3086
|
+
var tapMedia = function (el) {
|
|
3087
|
+
if (!el || tappedMedia.has(el) || routed.has(el) || typeof el.captureStream !== "function") return;
|
|
3088
|
+
tappedMedia.add(el);
|
|
3089
|
+
var stream;
|
|
3090
|
+
try { stream = el.captureStream(); } catch (e) { return; }
|
|
3091
|
+
var attached = false;
|
|
3092
|
+
var attach = function () {
|
|
3093
|
+
try {
|
|
3094
|
+
if (attached || !stream.getAudioTracks().length) return;
|
|
3095
|
+
attached = true;
|
|
3096
|
+
stream.getVideoTracks().forEach(function (v) { try { v.stop(); } catch (e) {} });
|
|
3097
|
+
if (!mediaCtx) mediaCtx = new AudioContext();
|
|
3098
|
+
if (mediaCtx.state === "suspended") mediaCtx.resume().catch(function () {});
|
|
3099
|
+
var t = tapFor(mediaCtx, "media");
|
|
3100
|
+
if (!t) return;
|
|
3101
|
+
var g = mediaCtx.createGain();
|
|
3102
|
+
mediaGains.set(el, g);
|
|
3103
|
+
follow(el);
|
|
3104
|
+
el.addEventListener("volumechange", function () { follow(el); });
|
|
3105
|
+
connect.call(mediaCtx.createMediaStreamSource(stream), g);
|
|
3106
|
+
connect.call(g, t.bus);
|
|
3107
|
+
} catch (e) {}
|
|
3108
|
+
};
|
|
3109
|
+
attach();
|
|
3110
|
+
try { stream.addEventListener("addtrack", attach); } catch (e) {}
|
|
3111
|
+
};
|
|
3112
|
+
var play = HTMLMediaElement.prototype.play;
|
|
3113
|
+
HTMLMediaElement.prototype.play = function () {
|
|
3114
|
+
var r = play.apply(this, arguments);
|
|
3115
|
+
try { tapMedia(this); } catch (e) {}
|
|
3116
|
+
return r;
|
|
3117
|
+
};
|
|
3118
|
+
// autoplay (and any play the wrapper above did not see) still fires "play"
|
|
3119
|
+
try { window.addEventListener("play", function (e) { try { if (e.target instanceof HTMLMediaElement) tapMedia(e.target); } catch (x) {} }, true); } catch (e) {}
|
|
3120
|
+
})();`;
|
|
3121
|
+
/** Start listening on the capture page. Call BEFORE the first navigation so
|
|
3122
|
+
* the init script runs ahead of the page's own scripts. Never throws: a
|
|
3123
|
+
* failure to install returns a recorder that reports why. */
|
|
3124
|
+
async function startProductAudio(cdp) {
|
|
3125
|
+
const notes = [];
|
|
3126
|
+
const sources = new Map();
|
|
3127
|
+
const blocks = [];
|
|
3128
|
+
const lost = [];
|
|
3129
|
+
let listening = true;
|
|
3130
|
+
let installed = false;
|
|
3131
|
+
try {
|
|
3132
|
+
await cdp.send("Runtime.addBinding", { name: PRODUCT_AUDIO_BINDING });
|
|
3133
|
+
cdp.on("Runtime.bindingCalled", (p) => {
|
|
3134
|
+
if (!listening || p.name !== PRODUCT_AUDIO_BINDING) return;
|
|
3135
|
+
const s = p.payload;
|
|
3136
|
+
const parts = s.split(" ", 6);
|
|
3137
|
+
if (parts[0] === "S") sources.set(parts[1], {
|
|
3138
|
+
id: parts[1],
|
|
3139
|
+
sampleRate: Number(parts[2]),
|
|
3140
|
+
kind: parts[3] === "media" ? "media" : "webaudio",
|
|
3141
|
+
baseLatencyMs: round1(Number(parts[4]) * 1e3),
|
|
3142
|
+
outputLatencyMs: 0
|
|
3143
|
+
});
|
|
3144
|
+
else if (parts[0] === "G") lost.push({
|
|
3145
|
+
producedMs: Number(parts[2]),
|
|
3146
|
+
ms: Number(parts[3])
|
|
3147
|
+
});
|
|
3148
|
+
else if (parts[0] === "B") {
|
|
3149
|
+
const src = parts[1];
|
|
3150
|
+
const source = sources.get(src);
|
|
3151
|
+
if (source) source.outputLatencyMs = Math.max(source.outputLatencyMs, round1(Number(parts[3])));
|
|
3152
|
+
let at = 0;
|
|
3153
|
+
for (let k = 0; k < 5; k++) at = s.indexOf(" ", at) + 1;
|
|
3154
|
+
const buf = Buffer.from(s.slice(at), "base64");
|
|
3155
|
+
const samples = new Float32Array(Math.floor(buf.length / 8) * 2);
|
|
3156
|
+
for (let k = 0; k < samples.length; k++) samples[k] = buf.readFloatLE(k * 4);
|
|
3157
|
+
const ctxFrame = Number(parts[4]);
|
|
3158
|
+
blocks.push({
|
|
3159
|
+
src,
|
|
3160
|
+
producedMs: Number(parts[2]),
|
|
3161
|
+
...Number.isFinite(ctxFrame) ? { ctxFrame } : {},
|
|
3162
|
+
samples
|
|
3163
|
+
});
|
|
3164
|
+
}
|
|
3165
|
+
});
|
|
3166
|
+
await cdp.send("Page.addScriptToEvaluateOnNewDocument", { source: PRODUCT_AUDIO_INIT_JS });
|
|
3167
|
+
installed = true;
|
|
3168
|
+
} catch (e) {
|
|
3169
|
+
notes.push(`product audio tap not installed (${e.message})`);
|
|
3170
|
+
}
|
|
3171
|
+
const responses = new Map();
|
|
3172
|
+
const finished = new Set();
|
|
3173
|
+
try {
|
|
3174
|
+
await cdp.send("Network.enable", {});
|
|
3175
|
+
cdp.on("Network.responseReceived", (p) => {
|
|
3176
|
+
if (!listening || responses.size >= MAX_LISTED_FILES) return;
|
|
3177
|
+
const { url, mimeType = "", status } = p.response;
|
|
3178
|
+
if (!/^https?:|^file:/i.test(url)) return;
|
|
3179
|
+
if (!/^audio\//i.test(mimeType) && !AUDIO_EXT.test(url)) return;
|
|
3180
|
+
responses.set(p.requestId, {
|
|
3181
|
+
url,
|
|
3182
|
+
mimeType,
|
|
3183
|
+
status
|
|
3184
|
+
});
|
|
3185
|
+
});
|
|
3186
|
+
cdp.on("Network.loadingFinished", (p) => {
|
|
3187
|
+
const r = responses.get(p.requestId);
|
|
3188
|
+
if (!r) return;
|
|
3189
|
+
if (p.encodedDataLength != null) r.bytes = Math.round(p.encodedDataLength);
|
|
3190
|
+
finished.add(p.requestId);
|
|
3191
|
+
});
|
|
3192
|
+
} catch (e) {
|
|
3193
|
+
notes.push(`fetched sound files not listed (${e.message})`);
|
|
3194
|
+
}
|
|
3195
|
+
return { async finish({ t0, endMs, dir }) {
|
|
3196
|
+
listening = false;
|
|
3197
|
+
try {
|
|
3198
|
+
const files = await saveFetched(cdp, responses, finished, dir, notes);
|
|
3199
|
+
let audio = null;
|
|
3200
|
+
const gaps = lost.map((g) => ({
|
|
3201
|
+
at: Math.round(g.producedMs - t0),
|
|
3202
|
+
ms: g.ms
|
|
3203
|
+
})).filter((g) => Number.isFinite(g.at) && g.at < endMs && g.at + g.ms > 0);
|
|
3204
|
+
if (blocks.length && gaps.length) notes.push(`the tap missed ${Math.round(gaps.reduce((a, g) => a + g.ms, 0))} ms of the page's audio while its main thread was busy (any sound there is missing from product-audio.wav; the page itself played it) — at ${gaps.slice(0, 8).map((g) => `${g.at}+${g.ms} ms`).join(", ")}${gaps.length > 8 ? ", …" : ""}`);
|
|
3205
|
+
if (installed && blocks.length) try {
|
|
3206
|
+
audio = writeMix(blocks, sources, t0, endMs, join(dir, "product-audio.wav"));
|
|
3207
|
+
} catch (e) {
|
|
3208
|
+
notes.push(`product audio not written (${e.message})`);
|
|
3209
|
+
}
|
|
3210
|
+
if (!audio && !files.length && !notes.length) return null;
|
|
3211
|
+
const report = {
|
|
3212
|
+
audio,
|
|
3213
|
+
files,
|
|
3214
|
+
notes
|
|
3215
|
+
};
|
|
3216
|
+
writeFileSync(join(dir, "product-sound.json"), `${JSON.stringify(report, null, 2)}\n`);
|
|
3217
|
+
return report;
|
|
3218
|
+
} catch (e) {
|
|
3219
|
+
console.error(`product audio: nothing written (${e.message})`);
|
|
3220
|
+
return null;
|
|
3221
|
+
}
|
|
3222
|
+
} };
|
|
3223
|
+
}
|
|
3224
|
+
const round1 = (n) => Number.isFinite(n) ? Math.round(n * 10) / 10 : 0;
|
|
3225
|
+
async function saveFetched(cdp, responses, finished, dir, notes) {
|
|
3226
|
+
const out = [];
|
|
3227
|
+
const used = new Set();
|
|
3228
|
+
const seen = new Set();
|
|
3229
|
+
let total = 0;
|
|
3230
|
+
let timedOut = false;
|
|
3231
|
+
const deadline = Date.now() + 5e3;
|
|
3232
|
+
for (const [id, r] of responses) {
|
|
3233
|
+
if (seen.has(r.url)) continue;
|
|
3234
|
+
seen.add(r.url);
|
|
3235
|
+
let body = null;
|
|
3236
|
+
if (finished.has(id) && r.status === 200 && (r.bytes ?? 0) <= MAX_SAVED_FILE_BYTES) if (Date.now() > deadline) timedOut = true;
|
|
3237
|
+
else body = await Promise.race([cdp.send("Network.getResponseBody", { requestId: id }).then((b) => Buffer.from(b.body, b.base64Encoded ? "base64" : "utf8")).catch(() => null), new Promise((r$1) => setTimeout(() => r$1(null), Math.max(0, deadline - Date.now())).unref())]);
|
|
3238
|
+
if (body?.length && total + body.length <= MAX_SAVED_TOTAL_BYTES) {
|
|
3239
|
+
const name = uniqueName(r.url, used);
|
|
3240
|
+
mkdirSync(join(dir, "product-sounds"), { recursive: true });
|
|
3241
|
+
writeFileSync(join(dir, "product-sounds", name), body);
|
|
3242
|
+
total += body.length;
|
|
3243
|
+
out.push({
|
|
3244
|
+
...r,
|
|
3245
|
+
bytes: r.bytes ?? body.length,
|
|
3246
|
+
saved: `product-sounds/${name}`
|
|
3247
|
+
});
|
|
3248
|
+
} else out.push(r);
|
|
3249
|
+
}
|
|
3250
|
+
if (timedOut) notes.push("some fetched sound files are listed but not saved (ran out of time reading them)");
|
|
3251
|
+
return out;
|
|
3252
|
+
}
|
|
3253
|
+
/** `https://x/sounds/click/1.wav?v=3` → `sounds-click-1.wav` (deduped). */
|
|
3254
|
+
function uniqueName(url, used) {
|
|
3255
|
+
let path;
|
|
3256
|
+
try {
|
|
3257
|
+
path = decodeURIComponent(new URL(url).pathname);
|
|
3258
|
+
} catch {
|
|
3259
|
+
path = url;
|
|
3260
|
+
}
|
|
3261
|
+
const segs = path.split("/").filter(Boolean).slice(-3);
|
|
3262
|
+
let name = (segs.join("-") || "sound").replace(/[^A-Za-z0-9._-]+/g, "_").slice(-120);
|
|
3263
|
+
if (!/\.[A-Za-z0-9]{2,5}$/.test(name)) name += ".audio";
|
|
3264
|
+
let candidate = name;
|
|
3265
|
+
for (let i = 2; used.has(candidate.toLowerCase()); i++) {
|
|
3266
|
+
const dot = name.lastIndexOf(".");
|
|
3267
|
+
candidate = `${name.slice(0, dot)}-${i}${name.slice(dot)}`;
|
|
3268
|
+
}
|
|
3269
|
+
used.add(candidate.toLowerCase());
|
|
3270
|
+
return basename(candidate);
|
|
3271
|
+
}
|
|
3272
|
+
/** Mix the blocks onto the capture timeline and write a float WAV. Exported
|
|
3273
|
+
* for the unit test; `producedMs` and `t0` share one wall clock (the page's
|
|
3274
|
+
* performance.timeOrigin and the runtime's Date.now are both epoch ms on the
|
|
3275
|
+
* same machine). */
|
|
3276
|
+
function mixBlocks(blocks, sources, t0, endMs) {
|
|
3277
|
+
const weight = new Map();
|
|
3278
|
+
for (const b of blocks) {
|
|
3279
|
+
const sr = sources.get(b.src)?.sampleRate ?? 48e3;
|
|
3280
|
+
weight.set(sr, (weight.get(sr) ?? 0) + b.samples.length);
|
|
3281
|
+
}
|
|
3282
|
+
const sampleRate = [...weight.entries()].sort((a, b) => b[1] - a[1])[0]?.[0] ?? 48e3;
|
|
3283
|
+
const frames = Math.max(1, Math.ceil(Math.max(endMs, 0) / 1e3 * sampleRate));
|
|
3284
|
+
const pcm = new Float32Array(frames * 2);
|
|
3285
|
+
const spans = [];
|
|
3286
|
+
const startOf = placeOnSourceClocks(blocks, sources);
|
|
3287
|
+
for (const b of blocks) {
|
|
3288
|
+
const sr = sources.get(b.src)?.sampleRate ?? sampleRate;
|
|
3289
|
+
const n = b.samples.length / 2;
|
|
3290
|
+
const placed = startOf.get(b);
|
|
3291
|
+
if (placed === null) continue;
|
|
3292
|
+
const startMs = (placed ?? b.producedMs) - t0;
|
|
3293
|
+
const durMs = n / sr * 1e3;
|
|
3294
|
+
if (startMs + durMs <= 0 || startMs >= endMs) continue;
|
|
3295
|
+
spans.push([startMs, startMs + durMs]);
|
|
3296
|
+
const ratio = sr / sampleRate;
|
|
3297
|
+
const first = Math.round(startMs / 1e3 * sampleRate);
|
|
3298
|
+
const count = Math.floor(n / ratio);
|
|
3299
|
+
for (let k = 0; k < count; k++) {
|
|
3300
|
+
const o = first + k;
|
|
3301
|
+
if (o < 0) continue;
|
|
3302
|
+
if (o >= frames) break;
|
|
3303
|
+
const x = k * ratio;
|
|
3304
|
+
const i = Math.floor(x);
|
|
3305
|
+
const f = x - i;
|
|
3306
|
+
const j = Math.min(i + 1, n - 1);
|
|
3307
|
+
pcm[2 * o] = pcm[2 * o] + b.samples[2 * i] * (1 - f) + b.samples[2 * j] * f;
|
|
3308
|
+
pcm[2 * o + 1] = pcm[2 * o + 1] + b.samples[2 * i + 1] * (1 - f) + b.samples[2 * j + 1] * f;
|
|
3309
|
+
}
|
|
3310
|
+
}
|
|
3311
|
+
let peak = 0;
|
|
3312
|
+
for (let i = 0; i < pcm.length; i++) peak = Math.max(peak, Math.abs(pcm[i]));
|
|
3313
|
+
spans.sort((a, b) => a[0] - b[0]);
|
|
3314
|
+
const soundAt = [];
|
|
3315
|
+
for (const [a, b] of spans) {
|
|
3316
|
+
const last = soundAt[soundAt.length - 1];
|
|
3317
|
+
if (last && a <= last[1] + 30) last[1] = Math.max(last[1], b);
|
|
3318
|
+
else soundAt.push([a, b]);
|
|
3319
|
+
}
|
|
3320
|
+
return {
|
|
3321
|
+
sampleRate,
|
|
3322
|
+
pcm,
|
|
3323
|
+
soundAt: soundAt.map(([a, b]) => [Math.max(0, Math.round(a)), Math.min(endMs, Math.round(b))]),
|
|
3324
|
+
peak
|
|
3325
|
+
};
|
|
3326
|
+
}
|
|
3327
|
+
/** Wall-clock start of each block that carries its source-clock frame.
|
|
3328
|
+
* Each block's own wall-clock estimate jitters by a few samples, which laid
|
|
3329
|
+
* end to end leaves 1-2 sample overlaps (spikes) and holes (dropouts) at
|
|
3330
|
+
* every ~85 ms boundary. So per source, blocks whose clock offset (wall ms −
|
|
3331
|
+
* source-clock ms) agrees within OFFSET_JUMP_MS form a run that shares ONE
|
|
3332
|
+
* offset — the run's median — and sit sample-exactly on the source's clock;
|
|
3333
|
+
* a larger jump (a suspend/resume, an output restart) starts a new run.
|
|
3334
|
+
* After a main-thread stall Chrome hands over a few buffers stamped with one
|
|
3335
|
+
* stale playbackTime, overlapping the steady chain that follows; a block that
|
|
3336
|
+
* runs into the next one on its own clock is such a stamp and is dropped
|
|
3337
|
+
* (null) rather than summed into a spike. */
|
|
3338
|
+
const OFFSET_JUMP_MS = 10;
|
|
3339
|
+
function placeOnSourceClocks(blocks, sources) {
|
|
3340
|
+
const out = new Map();
|
|
3341
|
+
const bySrc = new Map();
|
|
3342
|
+
for (const b of blocks) {
|
|
3343
|
+
if (b.ctxFrame == null || !sources.get(b.src)) continue;
|
|
3344
|
+
const list = bySrc.get(b.src) ?? [];
|
|
3345
|
+
list.push(b);
|
|
3346
|
+
bySrc.set(b.src, list);
|
|
3347
|
+
}
|
|
3348
|
+
for (const [src, list] of bySrc) {
|
|
3349
|
+
const sr = sources.get(src).sampleRate;
|
|
3350
|
+
list.sort((a, b) => a.ctxFrame - b.ctxFrame);
|
|
3351
|
+
const offset = (b) => b.producedMs - b.ctxFrame / sr * 1e3;
|
|
3352
|
+
let run = [];
|
|
3353
|
+
const close = () => {
|
|
3354
|
+
if (!run.length) return;
|
|
3355
|
+
const offs = run.map(offset).sort((a, b) => a - b);
|
|
3356
|
+
const mid = Math.round(offs[Math.floor(offs.length / 2)] * sr / 1e3);
|
|
3357
|
+
for (const b of run) out.set(b, (mid + b.ctxFrame) / sr * 1e3);
|
|
3358
|
+
run = [];
|
|
3359
|
+
};
|
|
3360
|
+
for (let i = 0; i < list.length; i++) {
|
|
3361
|
+
const b = list[i];
|
|
3362
|
+
const next = list[i + 1];
|
|
3363
|
+
if (next && next.ctxFrame < b.ctxFrame + b.samples.length / 2) {
|
|
3364
|
+
out.set(b, null);
|
|
3365
|
+
continue;
|
|
3366
|
+
}
|
|
3367
|
+
const last = run[run.length - 1];
|
|
3368
|
+
if (last && Math.abs(offset(b) - offset(last)) > OFFSET_JUMP_MS) close();
|
|
3369
|
+
run.push(b);
|
|
3370
|
+
}
|
|
3371
|
+
close();
|
|
3372
|
+
}
|
|
3373
|
+
return out;
|
|
3374
|
+
}
|
|
3375
|
+
function writeMix(blocks, sources, t0, endMs, path) {
|
|
3376
|
+
const mix = mixBlocks(blocks, sources, t0, endMs);
|
|
3377
|
+
writeFileSync(path, floatWav(mix.pcm, mix.sampleRate, 2));
|
|
3378
|
+
return {
|
|
3379
|
+
file: "product-audio.wav",
|
|
3380
|
+
sampleRate: mix.sampleRate,
|
|
3381
|
+
channels: 2,
|
|
3382
|
+
format: "float32",
|
|
3383
|
+
startMs: 0,
|
|
3384
|
+
durationMs: Math.round(endMs),
|
|
3385
|
+
soundAt: mix.soundAt,
|
|
3386
|
+
peakDbfs: mix.peak > 0 ? Math.round(20 * Math.log10(mix.peak) * 10) / 10 : -Infinity,
|
|
3387
|
+
placement: "estimated: each ~85 ms block is placed where the browser's audio clock says the page produced it (AudioContext.getOutputTimestamp, less the output latency the capturing browser reports for its own device — see sources[].outputLatencyMs); sample 0 = capture t0, the zero of every event tMs and of capture.mp4. Blocks of one AudioContext sit sample-exactly end to end on that context's own clock (one clock offset per run, the median of its blocks). The product's own delay between an input and its sound is kept. A context's first sound can come late while the browser starts its audio output.",
|
|
3388
|
+
sources: [...sources.values()].map(({ id: _id,...s }) => s)
|
|
3389
|
+
};
|
|
3390
|
+
}
|
|
3391
|
+
/** IEEE-float WAV (format 3), interleaved. */
|
|
3392
|
+
function floatWav(pcm, sampleRate, channels) {
|
|
3393
|
+
const data = Buffer.from(pcm.buffer, pcm.byteOffset, pcm.byteLength);
|
|
3394
|
+
const h = Buffer.alloc(44);
|
|
3395
|
+
h.write("RIFF", 0);
|
|
3396
|
+
h.writeUInt32LE(36 + data.length, 4);
|
|
3397
|
+
h.write("WAVE", 8);
|
|
3398
|
+
h.write("fmt ", 12);
|
|
3399
|
+
h.writeUInt32LE(16, 16);
|
|
3400
|
+
h.writeUInt16LE(3, 20);
|
|
3401
|
+
h.writeUInt16LE(channels, 22);
|
|
3402
|
+
h.writeUInt32LE(sampleRate, 24);
|
|
3403
|
+
h.writeUInt32LE(sampleRate * channels * 4, 28);
|
|
3404
|
+
h.writeUInt16LE(channels * 4, 32);
|
|
3405
|
+
h.writeUInt16LE(32, 34);
|
|
3406
|
+
h.write("data", 36);
|
|
3407
|
+
h.writeUInt32LE(data.length, 40);
|
|
3408
|
+
return Buffer.concat([h, data]);
|
|
3409
|
+
}
|
|
3410
|
+
|
|
3411
|
+
//#endregion
|
|
3412
|
+
//#region src/settle.ts
|
|
3413
|
+
const sleep$1 = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
3414
|
+
/** Extra time a hold may spend waiting for a busy page, per beat. Generous
|
|
3415
|
+
* enough for a slow round-trip, short enough that a page which NEVER goes
|
|
3416
|
+
* quiet (a live clock, a polling dashboard) costs a bounded, reported amount
|
|
3417
|
+
* rather than stretching the take without explanation. */
|
|
3418
|
+
const DEFAULT_SETTLE_BUDGET_MS = 1200;
|
|
3419
|
+
/** The page must have been still this long to count as settled — one paint
|
|
3420
|
+
* plus slack, so a mutation and the layout it triggers aren't read as two
|
|
3421
|
+
* separate quiet periods. */
|
|
3422
|
+
const QUIET_MS = 120;
|
|
3423
|
+
const POLL_MS = 60;
|
|
3424
|
+
/** A pending setTimeout longer than this is the page's own heartbeat (a poll
|
|
3425
|
+
* loop, a session timer), not this beat finishing. Counting it would make the
|
|
3426
|
+
* page look permanently busy. */
|
|
3427
|
+
const TIMER_MAX_MS = 2e3;
|
|
3428
|
+
/** Grace on a timer's own deadline before it stops counting as pending. Errs
|
|
3429
|
+
* SHORT on purpose: expiring early costs the old behaviour (a beat that may
|
|
3430
|
+
* be captured a touch soon), expiring late costs dead air in the cut on
|
|
3431
|
+
* every remaining beat — a much worse trade. */
|
|
3432
|
+
const TIMER_SLACK_MS = 250;
|
|
3433
|
+
/** A <canvas>/<video> covering this much of the frame makes the probe
|
|
3434
|
+
* effectively blind for that beat: the element never changes size, position
|
|
3435
|
+
* or attributes no matter what is painted inside it, so "the page is done"
|
|
3436
|
+
* is unanswerable. Set low on purpose — a needless note costs a line of
|
|
3437
|
+
* output, a missed one costs an author trusting a quiet run that proved
|
|
3438
|
+
* nothing. */
|
|
3439
|
+
const PAINT_BLIND_FRAC = .2;
|
|
3440
|
+
/** Installed once per document; keeps `t` at the last moment anything moved. */
|
|
3441
|
+
const PROBE_INSTALL_JS = `(() => {
|
|
3442
|
+
if (window.__openTakeActivity) return;
|
|
3443
|
+
const TIMER_MAX = ${TIMER_MAX_MS}, TIMER_SLACK = ${TIMER_SLACK_MS};
|
|
3444
|
+
const A = { t: 0, net: 0, timers: 0 };
|
|
3445
|
+
const touch = () => { A.t = performance.now(); };
|
|
3446
|
+
touch();
|
|
3447
|
+
try {
|
|
3448
|
+
new MutationObserver(touch).observe(document, {
|
|
3449
|
+
subtree: true, childList: true, attributes: true, characterData: true,
|
|
3450
|
+
});
|
|
3451
|
+
} catch (e) {}
|
|
3452
|
+
try {
|
|
3453
|
+
const of = window.fetch;
|
|
3454
|
+
if (typeof of === "function")
|
|
3455
|
+
window.fetch = function () {
|
|
3456
|
+
A.net++; touch();
|
|
3457
|
+
let p;
|
|
3458
|
+
try { p = of.apply(window, arguments); } catch (e) { A.net--; throw e; }
|
|
3459
|
+
return Promise.resolve(p).then(
|
|
3460
|
+
(r) => { A.net--; touch(); return r; },
|
|
3461
|
+
(e) => { A.net--; touch(); throw e; },
|
|
3462
|
+
);
|
|
3463
|
+
};
|
|
3464
|
+
} catch (e) {}
|
|
3465
|
+
try {
|
|
3466
|
+
const os = XMLHttpRequest.prototype.send;
|
|
3467
|
+
if (typeof os === "function")
|
|
3468
|
+
XMLHttpRequest.prototype.send = function () {
|
|
3469
|
+
A.net++; touch();
|
|
3470
|
+
// send() throws on API misuse (send before open, send after abort) and
|
|
3471
|
+
// then NO request exists, so loadend never fires — without this the
|
|
3472
|
+
// increment is permanent and the page reads busy for the rest of the
|
|
3473
|
+
// take. Same guard the fetch branch above already has.
|
|
3474
|
+
try { this.addEventListener("loadend", () => { A.net--; touch(); }); } catch (e) {}
|
|
3475
|
+
try { return os.apply(this, arguments); } catch (e) { A.net--; touch(); throw e; }
|
|
3476
|
+
};
|
|
3477
|
+
} catch (e) {}
|
|
3478
|
+
try {
|
|
3479
|
+
const st = window.setTimeout, ct = window.clearTimeout, ci = window.clearInterval;
|
|
3480
|
+
// id -> the moment it must have fired by. Counting by DEADLINE rather than
|
|
3481
|
+
// by cancellation bookkeeping is what makes this safe: a timer we never see
|
|
3482
|
+
// cancelled (clearInterval on a setTimeout id, an id coerced through a
|
|
3483
|
+
// dataset attribute, any API we did not wrap) simply expires and stops
|
|
3484
|
+
// counting. Chasing every cancellation path would leave one uncounted, and
|
|
3485
|
+
// ONE stuck entry means every remaining beat of the take waits the whole
|
|
3486
|
+
// budget for nothing.
|
|
3487
|
+
const live = new Map();
|
|
3488
|
+
const forget = function (id) { live.delete(Number(id)); };
|
|
3489
|
+
A.pending = function () {
|
|
3490
|
+
const now = performance.now();
|
|
3491
|
+
live.forEach(function (due, id) { if (due <= now) live.delete(id); });
|
|
3492
|
+
A.timers = live.size;
|
|
3493
|
+
return live.size;
|
|
3494
|
+
};
|
|
3495
|
+
window.setTimeout = function (fn, delay) {
|
|
3496
|
+
const d = Number(delay) || 0;
|
|
3497
|
+
// a string body keeps the original semantics (wrapping would stop the
|
|
3498
|
+
// code ever running), and a long delay is a heartbeat, not this beat
|
|
3499
|
+
if (typeof fn !== "function" || d > TIMER_MAX) return st.apply(window, arguments);
|
|
3500
|
+
const rest = Array.prototype.slice.call(arguments, 2);
|
|
3501
|
+
let id;
|
|
3502
|
+
const wrapped = function () {
|
|
3503
|
+
forget(id); touch();
|
|
3504
|
+
return fn.apply(this, arguments);
|
|
3505
|
+
};
|
|
3506
|
+
id = st.apply(window, [wrapped, d].concat(rest));
|
|
3507
|
+
live.set(Number(id), performance.now() + d + TIMER_SLACK);
|
|
3508
|
+
touch();
|
|
3509
|
+
return id;
|
|
3510
|
+
};
|
|
3511
|
+
// Both cancellers, and both coerce their argument the way the platform
|
|
3512
|
+
// does — clearInterval legally cancels a setTimeout (one timer map), and
|
|
3513
|
+
// clearTimeout(String(id)) is what you get back out of a dataset.
|
|
3514
|
+
window.clearTimeout = function (id) { forget(id); return ct.apply(window, arguments); };
|
|
3515
|
+
window.clearInterval = function (id) { forget(id); return ci.apply(window, arguments); };
|
|
3516
|
+
} catch (e) {}
|
|
3517
|
+
window.__openTakeActivity = A;
|
|
3518
|
+
})()`;
|
|
3519
|
+
/** Reads the probe. Returns a JSON string so one Runtime.evaluate round-trip
|
|
3520
|
+
* carries the whole answer (returnByValue on a plain object also works, but
|
|
3521
|
+
* the rest of this package already speaks the JSON-string convention). */
|
|
3522
|
+
const PROBE_READ_JS = `(() => {
|
|
3523
|
+
const A = window.__openTakeActivity;
|
|
3524
|
+
if (!A) return JSON.stringify({ ok: false });
|
|
3525
|
+
let anims = 0;
|
|
3526
|
+
try {
|
|
3527
|
+
for (const a of document.getAnimations()) {
|
|
3528
|
+
if (a.playState !== "running") continue;
|
|
3529
|
+
let it = 1;
|
|
3530
|
+
try { it = a.effect.getTiming().iterations; } catch (e) {}
|
|
3531
|
+
if (it === Infinity) continue; // ambient — never settles, never counted
|
|
3532
|
+
anims++;
|
|
3533
|
+
}
|
|
3534
|
+
} catch (e) {}
|
|
3535
|
+
// The largest <canvas>/<video> as a fraction of the viewport, clipped to it
|
|
3536
|
+
// (an offscreen or scrolled-away surface is not what the viewer is watching).
|
|
3537
|
+
let paint = 0;
|
|
3538
|
+
try {
|
|
3539
|
+
const area = innerWidth * innerHeight;
|
|
3540
|
+
if (area > 0)
|
|
3541
|
+
for (const el of document.querySelectorAll("canvas,video")) {
|
|
3542
|
+
const r = el.getBoundingClientRect();
|
|
3543
|
+
const w = Math.max(0, Math.min(r.right, innerWidth) - Math.max(r.left, 0));
|
|
3544
|
+
const h = Math.max(0, Math.min(r.bottom, innerHeight) - Math.max(r.top, 0));
|
|
3545
|
+
if (w * h > paint * area) paint = (w * h) / area;
|
|
3546
|
+
}
|
|
3547
|
+
} catch (e) {}
|
|
3548
|
+
const timers = typeof A.pending === "function" ? A.pending() : (A.timers | 0);
|
|
3549
|
+
const busy = A.net > 0 || timers > 0 || anims > 0 || document.readyState !== "complete";
|
|
3550
|
+
return JSON.stringify({
|
|
3551
|
+
ok: true,
|
|
3552
|
+
quietMs: busy ? 0 : Math.max(0, performance.now() - A.t),
|
|
3553
|
+
net: A.net,
|
|
3554
|
+
timers,
|
|
3555
|
+
anims,
|
|
3556
|
+
paint,
|
|
3557
|
+
});
|
|
3558
|
+
})()`;
|
|
3559
|
+
/** Install the activity probe for the current document AND every future one
|
|
3560
|
+
* (a plan may navigate mid-take). Never throws — a capture must not fail
|
|
3561
|
+
* because a diagnostic could not be attached. */
|
|
3562
|
+
async function installActivityProbe(cdp) {
|
|
3563
|
+
await cdp.send("Page.addScriptToEvaluateOnNewDocument", { source: PROBE_INSTALL_JS }).catch(() => {});
|
|
3564
|
+
await cdp.send("Runtime.evaluate", { expression: PROBE_INSTALL_JS }).catch(() => {});
|
|
3565
|
+
}
|
|
3566
|
+
async function readProbe(cdp) {
|
|
3567
|
+
try {
|
|
3568
|
+
const r = await cdp.send("Runtime.evaluate", {
|
|
3569
|
+
expression: PROBE_READ_JS,
|
|
3570
|
+
returnByValue: true
|
|
3571
|
+
});
|
|
3572
|
+
const v = r.result?.value;
|
|
3573
|
+
if (typeof v !== "string") return null;
|
|
3574
|
+
const p = JSON.parse(v);
|
|
3575
|
+
if (!p.ok) return null;
|
|
3576
|
+
return {
|
|
3577
|
+
quietMs: p.quietMs ?? 0,
|
|
3578
|
+
net: p.net ?? 0,
|
|
3579
|
+
timers: p.timers ?? 0,
|
|
3580
|
+
anims: p.anims ?? 0,
|
|
3581
|
+
paint: p.paint ?? 0
|
|
3582
|
+
};
|
|
3583
|
+
} catch {
|
|
3584
|
+
return null;
|
|
3585
|
+
}
|
|
3586
|
+
}
|
|
3587
|
+
/**
|
|
3588
|
+
* Hold for `heldMs` (the editorial beat — always run in full), then keep
|
|
3589
|
+
* waiting while the page is still working, up to `budgetMs`.
|
|
3590
|
+
*
|
|
3591
|
+
* `budgetMs <= 0` reduces this to the old fixed sleep exactly — the escape
|
|
3592
|
+
* hatch for a page that never goes quiet (`CaptureOpts.settleBudgetMs: 0`),
|
|
3593
|
+
* and what the unit tests use to pin the legacy timing.
|
|
3594
|
+
*/
|
|
3595
|
+
async function settle(cdp, heldMs, opts = {}) {
|
|
3596
|
+
const budget = opts.budgetMs ?? DEFAULT_SETTLE_BUDGET_MS;
|
|
3597
|
+
await sleep$1(Math.max(0, heldMs));
|
|
3598
|
+
if (!(budget > 0)) return {
|
|
3599
|
+
heldMs,
|
|
3600
|
+
waitedMs: 0,
|
|
3601
|
+
reason: "budget",
|
|
3602
|
+
paintFrac: 0
|
|
3603
|
+
};
|
|
3604
|
+
const t0 = Date.now();
|
|
3605
|
+
let paintFrac = 0;
|
|
3606
|
+
for (;;) {
|
|
3607
|
+
const p = await readProbe(cdp);
|
|
3608
|
+
const waitedMs = Date.now() - t0;
|
|
3609
|
+
if (!p) return {
|
|
3610
|
+
heldMs,
|
|
3611
|
+
waitedMs,
|
|
3612
|
+
reason: "unavailable",
|
|
3613
|
+
paintFrac
|
|
3614
|
+
};
|
|
3615
|
+
paintFrac = Math.max(paintFrac, p.paint);
|
|
3616
|
+
if (p.quietMs >= QUIET_MS) return {
|
|
3617
|
+
heldMs,
|
|
3618
|
+
waitedMs,
|
|
3619
|
+
reason: "idle",
|
|
3620
|
+
paintFrac,
|
|
3621
|
+
quietForMs: p.quietMs
|
|
3622
|
+
};
|
|
3623
|
+
if (waitedMs >= budget) return {
|
|
3624
|
+
heldMs,
|
|
3625
|
+
waitedMs,
|
|
3626
|
+
reason: "budget",
|
|
3627
|
+
paintFrac
|
|
3628
|
+
};
|
|
3629
|
+
await sleep$1(POLL_MS);
|
|
3630
|
+
}
|
|
3631
|
+
}
|
|
3632
|
+
/** How many beats in a row may spend the WHOLE budget without the page ever
|
|
3633
|
+
* settling before the waiting is written off. */
|
|
3634
|
+
const SETTLE_GIVE_UP_STREAK = 2;
|
|
3635
|
+
/**
|
|
3636
|
+
* Budget policy across one take. Some pages never go quiet — a one-second
|
|
3637
|
+
* clock, a poll loop, a streaming widget — and no DOM signal can tell that
|
|
3638
|
+
* apart from real work. So do not try: once a run of beats has each spent the
|
|
3639
|
+
* entire budget with no result, the waiting is provably not helping, and
|
|
3640
|
+
* paying it on every remaining beat would add more dead air than the whole
|
|
3641
|
+
* demo is long. Give up once, loudly, and let the author set settleMs by eye.
|
|
3642
|
+
*/
|
|
3643
|
+
function makeBudgetGovernor(budgetMs, giveUpStreak = SETTLE_GIVE_UP_STREAK) {
|
|
3644
|
+
let budget = budgetMs;
|
|
3645
|
+
let streak = 0;
|
|
3646
|
+
return {
|
|
3647
|
+
get budgetMs() {
|
|
3648
|
+
return budget;
|
|
3649
|
+
},
|
|
3650
|
+
get gaveUp() {
|
|
3651
|
+
return budget <= 0 && budgetMs > 0;
|
|
3652
|
+
},
|
|
3653
|
+
record(reason) {
|
|
3654
|
+
if (reason === "idle") {
|
|
3655
|
+
streak = 0;
|
|
3656
|
+
return false;
|
|
3657
|
+
}
|
|
3658
|
+
if (reason !== "budget" || budget <= 0) return false;
|
|
3659
|
+
if (++streak < giveUpStreak) return false;
|
|
3660
|
+
budget = 0;
|
|
3661
|
+
return true;
|
|
3662
|
+
}
|
|
3663
|
+
};
|
|
3664
|
+
}
|
|
3665
|
+
|
|
3666
|
+
//#endregion
|
|
3667
|
+
//#region src/cdp-capture.ts
|
|
3668
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
3669
|
+
/** Report a settle wait only past this — a couple of polls is the probe
|
|
3670
|
+
* confirming quiet, not the page being slow, and a log full of 60ms notes
|
|
3671
|
+
* would bury the beat that actually needed a second. */
|
|
3672
|
+
const SETTLE_NOTE_MS = 150;
|
|
3673
|
+
const smoother = (u) => {
|
|
3674
|
+
const clamped = Math.max(0, Math.min(1, u));
|
|
3675
|
+
return clamped * clamped * clamped * (clamped * (clamped * 6 - 15) + 10);
|
|
3676
|
+
};
|
|
3677
|
+
async function evalBox(cdp, js) {
|
|
3678
|
+
const r = await cdp.send("Runtime.evaluate", {
|
|
3679
|
+
expression: js,
|
|
3680
|
+
returnByValue: true,
|
|
3681
|
+
awaitPromise: true
|
|
3682
|
+
});
|
|
3683
|
+
const v = r.result?.value;
|
|
3684
|
+
if (v == null || v === "NOTFOUND") return null;
|
|
3685
|
+
return findBox(evalValue(typeof v === "string" ? v : JSON.stringify(v)));
|
|
3686
|
+
}
|
|
3687
|
+
async function evalAny(cdp, js) {
|
|
3688
|
+
const r = await cdp.send("Runtime.evaluate", {
|
|
3689
|
+
expression: js,
|
|
3690
|
+
returnByValue: true,
|
|
3691
|
+
awaitPromise: true
|
|
3692
|
+
});
|
|
3693
|
+
const v = r.result?.value;
|
|
3694
|
+
if (v == null || v === "NOTFOUND") return null;
|
|
3695
|
+
return evalValue(typeof v === "string" ? v : JSON.stringify(v));
|
|
3696
|
+
}
|
|
3697
|
+
async function evalString(cdp, js) {
|
|
3698
|
+
const r = await cdp.send("Runtime.evaluate", {
|
|
3699
|
+
expression: js,
|
|
3700
|
+
returnByValue: true,
|
|
3701
|
+
awaitPromise: true
|
|
3702
|
+
});
|
|
3703
|
+
const v = r.result?.value;
|
|
3704
|
+
return typeof v === "string" && v !== "NOTFOUND" && v !== "" ? v : null;
|
|
3705
|
+
}
|
|
3706
|
+
async function awaitFonts(cdp) {
|
|
3707
|
+
let timer;
|
|
3708
|
+
await Promise.race([cdp.send("Runtime.evaluate", {
|
|
3709
|
+
expression: "document.fonts.ready.then(() => true)",
|
|
3710
|
+
awaitPromise: true,
|
|
3711
|
+
returnByValue: true
|
|
3712
|
+
}).catch(() => {}), new Promise((r) => {
|
|
3713
|
+
timer = setTimeout(r, 3e3);
|
|
3714
|
+
})]);
|
|
3715
|
+
clearTimeout(timer);
|
|
3716
|
+
}
|
|
3717
|
+
const center = (b) => ({
|
|
3718
|
+
x: Math.round(b.x + b.w / 2),
|
|
3719
|
+
y: Math.round(b.y + b.h / 2)
|
|
3720
|
+
});
|
|
3721
|
+
const mouse = (cdp, type, x, y, buttons = 0) => cdp.send("Input.dispatchMouseEvent", {
|
|
3722
|
+
type,
|
|
3723
|
+
x: Math.round(x),
|
|
3724
|
+
y: Math.round(y),
|
|
3725
|
+
button: type === "mouseMoved" ? "none" : "left",
|
|
3726
|
+
buttons,
|
|
3727
|
+
...type === "mouseMoved" ? {} : { clickCount: 1 }
|
|
3728
|
+
});
|
|
3729
|
+
const MOD = {
|
|
3730
|
+
alt: 1,
|
|
3731
|
+
option: 1,
|
|
3732
|
+
ctrl: 2,
|
|
3733
|
+
control: 2,
|
|
3734
|
+
meta: 4,
|
|
3735
|
+
cmd: 4,
|
|
3736
|
+
command: 4,
|
|
3737
|
+
super: 4,
|
|
3738
|
+
win: 4,
|
|
3739
|
+
shift: 8
|
|
3740
|
+
};
|
|
3741
|
+
const NAMED = {
|
|
3742
|
+
enter: {
|
|
3743
|
+
key: "Enter",
|
|
3744
|
+
code: "Enter",
|
|
3745
|
+
vk: 13,
|
|
3746
|
+
text: "\r"
|
|
3747
|
+
},
|
|
3748
|
+
return: {
|
|
3749
|
+
key: "Enter",
|
|
3750
|
+
code: "Enter",
|
|
3751
|
+
vk: 13,
|
|
3752
|
+
text: "\r"
|
|
3753
|
+
},
|
|
3754
|
+
tab: {
|
|
3755
|
+
key: "Tab",
|
|
3756
|
+
code: "Tab",
|
|
3757
|
+
vk: 9
|
|
3758
|
+
},
|
|
3759
|
+
escape: {
|
|
3760
|
+
key: "Escape",
|
|
3761
|
+
code: "Escape",
|
|
3762
|
+
vk: 27
|
|
3763
|
+
},
|
|
3764
|
+
esc: {
|
|
3765
|
+
key: "Escape",
|
|
3766
|
+
code: "Escape",
|
|
3767
|
+
vk: 27
|
|
3768
|
+
},
|
|
3769
|
+
backspace: {
|
|
3770
|
+
key: "Backspace",
|
|
3771
|
+
code: "Backspace",
|
|
3772
|
+
vk: 8
|
|
3773
|
+
},
|
|
3774
|
+
delete: {
|
|
3775
|
+
key: "Delete",
|
|
3776
|
+
code: "Delete",
|
|
3777
|
+
vk: 46
|
|
3778
|
+
},
|
|
3779
|
+
space: {
|
|
3780
|
+
key: " ",
|
|
3781
|
+
code: "Space",
|
|
3782
|
+
vk: 32,
|
|
3783
|
+
text: " "
|
|
3784
|
+
},
|
|
3785
|
+
arrowup: {
|
|
3786
|
+
key: "ArrowUp",
|
|
3787
|
+
code: "ArrowUp",
|
|
3788
|
+
vk: 38
|
|
3789
|
+
},
|
|
3790
|
+
arrowdown: {
|
|
3791
|
+
key: "ArrowDown",
|
|
3792
|
+
code: "ArrowDown",
|
|
3793
|
+
vk: 40
|
|
3794
|
+
},
|
|
3795
|
+
arrowleft: {
|
|
3796
|
+
key: "ArrowLeft",
|
|
3797
|
+
code: "ArrowLeft",
|
|
3798
|
+
vk: 37
|
|
3799
|
+
},
|
|
3800
|
+
arrowright: {
|
|
3801
|
+
key: "ArrowRight",
|
|
3802
|
+
code: "ArrowRight",
|
|
3803
|
+
vk: 39
|
|
3804
|
+
},
|
|
3805
|
+
up: {
|
|
3806
|
+
key: "ArrowUp",
|
|
3807
|
+
code: "ArrowUp",
|
|
3808
|
+
vk: 38
|
|
3809
|
+
},
|
|
3810
|
+
down: {
|
|
3811
|
+
key: "ArrowDown",
|
|
3812
|
+
code: "ArrowDown",
|
|
3813
|
+
vk: 40
|
|
3814
|
+
},
|
|
3815
|
+
left: {
|
|
3816
|
+
key: "ArrowLeft",
|
|
3817
|
+
code: "ArrowLeft",
|
|
3818
|
+
vk: 37
|
|
3819
|
+
},
|
|
3820
|
+
right: {
|
|
3821
|
+
key: "ArrowRight",
|
|
3822
|
+
code: "ArrowRight",
|
|
3823
|
+
vk: 39
|
|
3824
|
+
},
|
|
3825
|
+
home: {
|
|
3826
|
+
key: "Home",
|
|
3827
|
+
code: "Home",
|
|
3828
|
+
vk: 36
|
|
3829
|
+
},
|
|
3830
|
+
end: {
|
|
3831
|
+
key: "End",
|
|
3832
|
+
code: "End",
|
|
3833
|
+
vk: 35
|
|
3834
|
+
},
|
|
3835
|
+
pageup: {
|
|
3836
|
+
key: "PageUp",
|
|
3837
|
+
code: "PageUp",
|
|
3838
|
+
vk: 33
|
|
3839
|
+
},
|
|
3840
|
+
pagedown: {
|
|
3841
|
+
key: "PageDown",
|
|
3842
|
+
code: "PageDown",
|
|
3843
|
+
vk: 34
|
|
3844
|
+
}
|
|
3845
|
+
};
|
|
3846
|
+
const MOD_KEY = {
|
|
3847
|
+
1: {
|
|
3848
|
+
key: "Alt",
|
|
3849
|
+
code: "AltLeft",
|
|
3850
|
+
vk: 18
|
|
3851
|
+
},
|
|
3852
|
+
2: {
|
|
3853
|
+
key: "Control",
|
|
3854
|
+
code: "ControlLeft",
|
|
3855
|
+
vk: 17
|
|
3856
|
+
},
|
|
3857
|
+
4: {
|
|
3858
|
+
key: "Meta",
|
|
3859
|
+
code: "MetaLeft",
|
|
3860
|
+
vk: 91
|
|
3861
|
+
},
|
|
3862
|
+
8: {
|
|
3863
|
+
key: "Shift",
|
|
3864
|
+
code: "ShiftLeft",
|
|
3865
|
+
vk: 16
|
|
3866
|
+
}
|
|
3867
|
+
};
|
|
3868
|
+
function parseChord(keys) {
|
|
3869
|
+
const tokens = keys.split("+").map((t) => t.trim()).filter(Boolean);
|
|
3870
|
+
const main = tokens.pop() ?? "";
|
|
3871
|
+
let mods = 0;
|
|
3872
|
+
for (const t of tokens) mods |= MOD[t.toLowerCase()] ?? 0;
|
|
3873
|
+
const named = NAMED[main.toLowerCase()];
|
|
3874
|
+
let info;
|
|
3875
|
+
if (named) info = named;
|
|
3876
|
+
else {
|
|
3877
|
+
const ch = main;
|
|
3878
|
+
const code = /^[a-z]$/i.test(ch) ? `Key${ch.toUpperCase()}` : /^[0-9]$/.test(ch) ? `Digit${ch}` : "";
|
|
3879
|
+
info = {
|
|
3880
|
+
key: ch,
|
|
3881
|
+
code,
|
|
3882
|
+
vk: ch.toUpperCase().charCodeAt(0) || 0
|
|
3883
|
+
};
|
|
3884
|
+
if (!(mods & 7)) info.text = ch;
|
|
3885
|
+
}
|
|
3886
|
+
return {
|
|
3887
|
+
mods,
|
|
3888
|
+
info
|
|
3889
|
+
};
|
|
3890
|
+
}
|
|
3891
|
+
async function dispatchKey(cdp, type, info, mods) {
|
|
3892
|
+
await cdp.send("Input.dispatchKeyEvent", {
|
|
3893
|
+
type: info.text && type === "keyDown" ? "keyDown" : type,
|
|
3894
|
+
modifiers: mods,
|
|
3895
|
+
key: info.key,
|
|
3896
|
+
code: info.code,
|
|
3897
|
+
windowsVirtualKeyCode: info.vk,
|
|
3898
|
+
nativeVirtualKeyCode: info.vk,
|
|
3899
|
+
...info.text ? { text: info.text } : {}
|
|
3900
|
+
});
|
|
3901
|
+
}
|
|
3902
|
+
async function pressChord(cdp, keys) {
|
|
3903
|
+
const { mods, info } = parseChord(keys);
|
|
3904
|
+
const active = [
|
|
3905
|
+
1,
|
|
3906
|
+
2,
|
|
3907
|
+
4,
|
|
3908
|
+
8
|
|
3909
|
+
].filter((m) => mods & m);
|
|
3910
|
+
for (const m of active) await dispatchKey(cdp, "keyDown", MOD_KEY[m], mods);
|
|
3911
|
+
await dispatchKey(cdp, "keyDown", info, mods);
|
|
3912
|
+
await sleep(40);
|
|
3913
|
+
await dispatchKey(cdp, "keyUp", info, mods);
|
|
3914
|
+
for (const m of active.reverse()) await dispatchKey(cdp, "keyUp", MOD_KEY[m], 0);
|
|
3915
|
+
}
|
|
3916
|
+
/** High-fps twin of captureTake. Drives + records via CDP. */
|
|
3917
|
+
async function captureTakeCDP(plan, opts) {
|
|
3918
|
+
const vw = plan.viewport?.width ?? 1920;
|
|
3919
|
+
const vh = plan.viewport?.height ?? 1080;
|
|
3920
|
+
const fps = Math.min(60, Math.max(24, Math.round(opts.fps ?? 60)));
|
|
3921
|
+
const scale = Math.max(1, opts.captureScale ?? 2);
|
|
3922
|
+
const out = resolve(opts.videoPath);
|
|
3923
|
+
let browser = null;
|
|
3924
|
+
const frameDir = makeFrameDir();
|
|
3925
|
+
try {
|
|
3926
|
+
browser = await launchBrowser({
|
|
3927
|
+
width: vw,
|
|
3928
|
+
height: vh,
|
|
3929
|
+
chromePath: opts.chromePath,
|
|
3930
|
+
deviceScaleFactor: scale,
|
|
3931
|
+
...opts.userDataDir ? { userDataDir: opts.userDataDir } : {},
|
|
3932
|
+
...opts.headless === false ? { headless: false } : {}
|
|
3933
|
+
});
|
|
3934
|
+
const { cdp } = browser;
|
|
3935
|
+
await cdp.send("Page.enable");
|
|
3936
|
+
await cdp.send("Runtime.enable");
|
|
3937
|
+
const productAudio = opts.productAudio === false ? null : await startProductAudio(cdp);
|
|
3938
|
+
let inner = await fitViewport(cdp, browser.targetId, vw, vh);
|
|
3939
|
+
await installActivityProbe(cdp);
|
|
3940
|
+
if (!originAllowed(plan.url)) throw new Error(`captureTakeCDP: plan.url ${plan.url} is outside OPEN_TAKE_ALLOWED_ORIGINS — an unattended run only films the app it was pointed at`);
|
|
3941
|
+
const navError = await navigate(cdp, plan.url);
|
|
3942
|
+
if (navError) throw new Error(`captureTakeCDP: ${plan.url} did not answer (${navError}) — is the app running? Start it (or fix the URL) and re-make; nothing was recorded.`);
|
|
3943
|
+
await installActivityProbe(cdp);
|
|
3944
|
+
await awaitFonts(cdp);
|
|
3945
|
+
inner = await fitViewport(cdp, browser.targetId, vw, vh);
|
|
3946
|
+
const precheck = await precheckPlan(plan.steps, (js) => evalAny(cdp, js));
|
|
3947
|
+
const precheckErrors = precheck.filter((p) => p.severity === "error");
|
|
3948
|
+
if (precheckErrors.length) throw new PrecheckRefusal(`captureTakeCDP: ${precheckErrors.length} plan target(s) failed the pre-capture check — nothing was recorded:\n` + precheckErrors.map((p) => ` ${p.path}: ${p.message}${p.fix ? `\n fix: ${p.fix}` : ""}`).join("\n"), precheck);
|
|
3949
|
+
for (const p of precheck) console.error(`captureTakeCDP precheck [${p.severity}] ${p.path}: ${p.message}`);
|
|
3950
|
+
const screencast = new Screencast(cdp, frameDir);
|
|
3951
|
+
const t0 = Date.now();
|
|
3952
|
+
await screencast.start(t0, {
|
|
3953
|
+
maxWidth: inner[0] * scale,
|
|
3954
|
+
maxHeight: inner[1] * scale,
|
|
3955
|
+
quality: 92
|
|
3956
|
+
});
|
|
3957
|
+
let pumping = true;
|
|
3958
|
+
let pumpPaused = false;
|
|
3959
|
+
const pump = opts.rasterRefresh === "off" ? Promise.resolve() : pumpIdleRaster(cdp, screencast, () => pumping, () => pumpPaused);
|
|
3960
|
+
await sleep(opts.warmupMs ?? 900);
|
|
3961
|
+
const resolvePoint = async (spec) => {
|
|
3962
|
+
if (spec.point) return {
|
|
3963
|
+
x: Math.round(spec.point.x),
|
|
3964
|
+
y: Math.round(spec.point.y)
|
|
3965
|
+
};
|
|
3966
|
+
if (spec.selector) {
|
|
3967
|
+
const b = await evalBox(cdp, boxSelectorJs(spec.selector));
|
|
3968
|
+
return b ? center(b) : null;
|
|
3969
|
+
}
|
|
3970
|
+
if (spec.text) {
|
|
3971
|
+
const b = await evalBox(cdp, boxByTextJs(spec.text));
|
|
3972
|
+
return b ? center(b) : null;
|
|
3973
|
+
}
|
|
3974
|
+
return null;
|
|
3975
|
+
};
|
|
3976
|
+
const events = [];
|
|
3977
|
+
const skipped = [];
|
|
3978
|
+
const settleWaits = [];
|
|
3979
|
+
const governor = makeBudgetGovernor(opts.settleBudgetMs ?? DEFAULT_SETTLE_BUDGET_MS);
|
|
3980
|
+
let paintedFrac = 0;
|
|
3981
|
+
let paintNoted = false;
|
|
3982
|
+
const statesDir = opts.states ? join(dirname(out), "states") : null;
|
|
3983
|
+
const states = [];
|
|
3984
|
+
const movingStates = [];
|
|
3985
|
+
let statesAnnotated = 0;
|
|
3986
|
+
let lastState = null;
|
|
3987
|
+
const captureState = async (step, mayMove) => {
|
|
3988
|
+
if (!statesDir) return;
|
|
3989
|
+
pumpPaused = true;
|
|
3990
|
+
await sleep(60);
|
|
3991
|
+
try {
|
|
3992
|
+
const id = `s${states.length + movingStates.length}`;
|
|
3993
|
+
const tMs = Date.now() - t0;
|
|
3994
|
+
const annotate = (target) => {
|
|
3995
|
+
for (; statesAnnotated < events.length; statesAnnotated++) {
|
|
3996
|
+
const ev = events[statesAnnotated];
|
|
3997
|
+
ev.state = id;
|
|
3998
|
+
const hit = ev.box && target ? matchTarget(ev.box, target.probe.elements) : void 0;
|
|
3999
|
+
if (hit) ev.target = hit;
|
|
4000
|
+
}
|
|
4001
|
+
};
|
|
4002
|
+
if (mayMove && !await visuallyStill(cdp, inner[0], inner[1])) {
|
|
4003
|
+
movingStates.push({
|
|
4004
|
+
id,
|
|
4005
|
+
tMs,
|
|
4006
|
+
...step != null ? { step } : {}
|
|
4007
|
+
});
|
|
4008
|
+
annotate(lastState);
|
|
4009
|
+
return;
|
|
4010
|
+
}
|
|
4011
|
+
const raw = await captureDomState(cdp, {
|
|
4012
|
+
statesDir,
|
|
4013
|
+
id,
|
|
4014
|
+
tMs,
|
|
4015
|
+
...step != null ? { step } : {},
|
|
4016
|
+
vw: inner[0],
|
|
4017
|
+
vh: inner[1],
|
|
4018
|
+
dpr: scale
|
|
4019
|
+
});
|
|
4020
|
+
states.push(raw);
|
|
4021
|
+
annotate(lastState);
|
|
4022
|
+
lastState = raw;
|
|
4023
|
+
} catch (e) {
|
|
4024
|
+
console.error(`captureTakeCDP: DOM state after ${step == null ? "the warmup" : `step ${step}`} not captured (${e.message})`);
|
|
4025
|
+
} finally {
|
|
4026
|
+
pumpPaused = false;
|
|
4027
|
+
}
|
|
4028
|
+
};
|
|
4029
|
+
await captureState(void 0, true);
|
|
4030
|
+
for (let stepIdx = 0; stepIdx < plan.steps.length; stepIdx++) {
|
|
4031
|
+
const step = plan.steps[stepIdx];
|
|
4032
|
+
const firstEvent = events.length;
|
|
4033
|
+
const skip = (action, target, reason) => {
|
|
4034
|
+
skipped.push({
|
|
4035
|
+
step: stepIdx,
|
|
4036
|
+
action,
|
|
4037
|
+
...target ? { target } : {},
|
|
4038
|
+
reason
|
|
4039
|
+
});
|
|
4040
|
+
console.error(`captureTakeCDP: ${action} ${reason}, skipped: ${JSON.stringify(target)}`);
|
|
4041
|
+
};
|
|
4042
|
+
const hold = async (defaultMs) => {
|
|
4043
|
+
const heldMs = ("settleMs" in step ? step.settleMs : void 0) ?? defaultMs;
|
|
4044
|
+
const budgeted = governor.budgetMs > 0;
|
|
4045
|
+
const r = await settle(cdp, heldMs, { budgetMs: governor.budgetMs });
|
|
4046
|
+
paintedFrac = Math.max(paintedFrac, r.paintFrac);
|
|
4047
|
+
if (r.quietForMs != null) {
|
|
4048
|
+
const quietAt = Math.round(Date.now() - t0 - r.quietForMs);
|
|
4049
|
+
for (let i = firstEvent; i < events.length; i++) if (quietAt > events[i].tMs) events[i].settledMs = quietAt;
|
|
4050
|
+
}
|
|
4051
|
+
if (paintedFrac >= PAINT_BLIND_FRAC && !paintNoted) {
|
|
4052
|
+
paintNoted = true;
|
|
4053
|
+
console.error(`captureTakeCDP: a <canvas>/<video> covers ~${Math.round(paintedFrac * 100)}% of the frame — the settle probe reads page STRUCTURE and cannot see what is painted inside one, so on beats whose payoff is drawn there, settleMs is doing the whole job. Set those by eye and check \`frames\`.`);
|
|
4054
|
+
}
|
|
4055
|
+
if (governor.record(r.reason)) console.error("captureTakeCDP: this page never goes quiet (consecutive beats spent the whole settle budget) — settle waiting is OFF for the rest of the take; set each beat's settleMs explicitly instead");
|
|
4056
|
+
await captureState(stepIdx, !budgeted || r.reason === "budget");
|
|
4057
|
+
if (r.waitedMs < SETTLE_NOTE_MS) return;
|
|
4058
|
+
const waitedMs = Math.round(r.waitedMs);
|
|
4059
|
+
settleWaits.push({
|
|
4060
|
+
step: stepIdx,
|
|
4061
|
+
action: step.action,
|
|
4062
|
+
heldMs,
|
|
4063
|
+
waitedMs,
|
|
4064
|
+
reason: r.reason
|
|
4065
|
+
});
|
|
4066
|
+
console.error(`captureTakeCDP: step ${stepIdx} (${step.action}) held ${heldMs}ms, then waited ${waitedMs}ms more for the page to settle (${r.reason})`);
|
|
4067
|
+
};
|
|
4068
|
+
if (step.action === "wait") {
|
|
4069
|
+
await sleep(step.ms);
|
|
4070
|
+
await captureState(stepIdx, true);
|
|
4071
|
+
continue;
|
|
4072
|
+
}
|
|
4073
|
+
if (step.action === "navigate") {
|
|
4074
|
+
const spec = step.hrefFrom;
|
|
4075
|
+
let href = null;
|
|
4076
|
+
if (spec) {
|
|
4077
|
+
const target = spec.text ?? spec.selector;
|
|
4078
|
+
if (!target) {
|
|
4079
|
+
skip("navigate", void 0, "hrefFrom has neither `selector` nor `text`");
|
|
4080
|
+
continue;
|
|
4081
|
+
}
|
|
4082
|
+
href = spec.selector ? await evalString(cdp, hrefSelectorJs(spec.selector)) : await evalString(cdp, hrefByTextJs(spec.text));
|
|
4083
|
+
if (!href) {
|
|
4084
|
+
skip("navigate", target, "no link with an href found");
|
|
4085
|
+
continue;
|
|
4086
|
+
}
|
|
4087
|
+
}
|
|
4088
|
+
const current = await evalString(cdp, "location.href") ?? plan.url;
|
|
4089
|
+
const dest = resolveNavigateUrl({
|
|
4090
|
+
current,
|
|
4091
|
+
url: step.url,
|
|
4092
|
+
href,
|
|
4093
|
+
query: step.query
|
|
4094
|
+
});
|
|
4095
|
+
if (!dest) {
|
|
4096
|
+
skip("navigate", step.url ?? href ?? current, "destination is not a resolvable URL");
|
|
4097
|
+
continue;
|
|
4098
|
+
}
|
|
4099
|
+
if (!originAllowed(dest)) {
|
|
4100
|
+
skip("navigate", dest, "destination is outside OPEN_TAKE_ALLOWED_ORIGINS");
|
|
4101
|
+
continue;
|
|
4102
|
+
}
|
|
4103
|
+
const midNavError = await navigate(cdp, dest);
|
|
4104
|
+
if (midNavError) {
|
|
4105
|
+
skip("navigate", dest, `destination did not answer (${midNavError})`);
|
|
4106
|
+
await navigate(cdp, current);
|
|
4107
|
+
await hold(1200);
|
|
4108
|
+
continue;
|
|
4109
|
+
}
|
|
4110
|
+
await awaitFonts(cdp);
|
|
4111
|
+
await hold(1200);
|
|
4112
|
+
continue;
|
|
4113
|
+
}
|
|
4114
|
+
if (step.action === "type") {
|
|
4115
|
+
const label$1 = step.text ?? step.selector;
|
|
4116
|
+
let tMs$1 = Date.now() - t0;
|
|
4117
|
+
const focusRaw = step.text ? await evalAny(cdp, focusFieldByTextJs(step.text)) : step.selector ? await evalAny(cdp, focusSelectorJs(step.selector)) : null;
|
|
4118
|
+
const box$1 = focusRaw ? findBox(focusRaw) : null;
|
|
4119
|
+
if (!box$1) {
|
|
4120
|
+
skip("type", label$1, "target not found");
|
|
4121
|
+
await hold(600);
|
|
4122
|
+
continue;
|
|
4123
|
+
}
|
|
4124
|
+
let focused = focusRaw.f === 1;
|
|
4125
|
+
if (!focused && focusRaw.hit !== 1) {
|
|
4126
|
+
const why = focusRaw.why;
|
|
4127
|
+
skip("type", label$1, `focus never reached the target — ${typeof why === "string" ? why : "its centre is covered"}, so no click could arm it`);
|
|
4128
|
+
await hold(600);
|
|
4129
|
+
continue;
|
|
4130
|
+
}
|
|
4131
|
+
if (!focused) {
|
|
4132
|
+
const pt$1 = center(box$1);
|
|
4133
|
+
pumpPaused = true;
|
|
4134
|
+
await sleep(160);
|
|
4135
|
+
tMs$1 = Date.now() - t0;
|
|
4136
|
+
mouse(cdp, "mouseMoved", pt$1.x, pt$1.y, 0).catch(() => {});
|
|
4137
|
+
mouse(cdp, "mousePressed", pt$1.x, pt$1.y, 1).catch(() => {});
|
|
4138
|
+
await sleep(60);
|
|
4139
|
+
mouse(cdp, "mouseReleased", pt$1.x, pt$1.y, 0).catch(() => {});
|
|
4140
|
+
await sleep(120);
|
|
4141
|
+
pumpPaused = false;
|
|
4142
|
+
for (let poll = 0; poll < 3 && !focused; poll++) {
|
|
4143
|
+
await sleep(250);
|
|
4144
|
+
focused = await evalString(cdp, verifyFocusJs({
|
|
4145
|
+
text: step.text,
|
|
4146
|
+
selector: step.selector
|
|
4147
|
+
})) === "1";
|
|
4148
|
+
}
|
|
4149
|
+
}
|
|
4150
|
+
if (!focused) {
|
|
4151
|
+
skip("type", label$1, "focus never reached the target — typing would go nowhere");
|
|
4152
|
+
await hold(600);
|
|
4153
|
+
continue;
|
|
4154
|
+
}
|
|
4155
|
+
if (process.env.OPEN_TAKE_CI && await evalString(cdp, credentialFieldProbeJs()) === "secret") {
|
|
4156
|
+
skip("type", label$1, "refusing to type into a credential field (OPEN_TAKE_CI)");
|
|
4157
|
+
await hold(600);
|
|
4158
|
+
continue;
|
|
4159
|
+
}
|
|
4160
|
+
if (step.clear) await evalAny(cdp, selectAllInFocusedJs());
|
|
4161
|
+
const chars = [...step.value];
|
|
4162
|
+
const cjk = chars.filter((c) => /[\u2E80-\u9FFF\uAC00-\uD7AF\uF900-\uFAFF\uFF66-\uFF9F]/.test(c)).length;
|
|
4163
|
+
const auto = Math.min(90, Math.max(28, Math.round(1100 / Math.max(1, chars.length)))) * (cjk * 2 > chars.length ? 1.4 : 1);
|
|
4164
|
+
if (step.perCharMs === 0) await cdp.send("Input.insertText", { text: step.value });
|
|
4165
|
+
else {
|
|
4166
|
+
const perChar = Math.round(step.perCharMs ?? auto);
|
|
4167
|
+
for (const ch of chars) {
|
|
4168
|
+
const painted = screencast.frames.length, sentAt = Date.now();
|
|
4169
|
+
await cdp.send("Input.insertText", { text: ch });
|
|
4170
|
+
await waitUntil(() => screencast.frames.length > painted, Math.max(perChar, 250));
|
|
4171
|
+
const rest = perChar - (Date.now() - sentAt);
|
|
4172
|
+
if (rest > 0) await sleep(rest);
|
|
4173
|
+
}
|
|
4174
|
+
}
|
|
4175
|
+
events.push({
|
|
4176
|
+
kind: "type",
|
|
4177
|
+
...center(box$1),
|
|
4178
|
+
box: box$1,
|
|
4179
|
+
tMs: tMs$1,
|
|
4180
|
+
sel: label$1,
|
|
4181
|
+
note: step.note,
|
|
4182
|
+
...step.caption ? { caption: step.caption } : {},
|
|
4183
|
+
text: step.value,
|
|
4184
|
+
durationMs: Date.now() - t0 - tMs$1,
|
|
4185
|
+
...step.zoom ? { zoom: step.zoom } : {}
|
|
4186
|
+
});
|
|
4187
|
+
await hold(900);
|
|
4188
|
+
continue;
|
|
4189
|
+
}
|
|
4190
|
+
if (step.action === "drag") {
|
|
4191
|
+
const pathPts = (step.path ?? []).map((p) => ({
|
|
4192
|
+
x: Math.round(p.x),
|
|
4193
|
+
y: Math.round(p.y)
|
|
4194
|
+
}));
|
|
4195
|
+
const from = await resolvePoint({
|
|
4196
|
+
point: step.from,
|
|
4197
|
+
selector: step.selector,
|
|
4198
|
+
text: step.text
|
|
4199
|
+
}) ?? pathPts[0] ?? null;
|
|
4200
|
+
const to = await resolvePoint({
|
|
4201
|
+
point: step.to,
|
|
4202
|
+
selector: step.toSelector,
|
|
4203
|
+
text: step.toText
|
|
4204
|
+
}) ?? pathPts[pathPts.length - 1] ?? null;
|
|
4205
|
+
const label$1 = step.note ?? step.text ?? step.selector;
|
|
4206
|
+
if (!from || !to) {
|
|
4207
|
+
skip("drag", label$1, "endpoint not found");
|
|
4208
|
+
await hold(600);
|
|
4209
|
+
continue;
|
|
4210
|
+
}
|
|
4211
|
+
const path = pathPts.length ? pathPts : [from, to];
|
|
4212
|
+
const target = step.durationMs ?? 1200;
|
|
4213
|
+
const dragEase = opts.dragEasing ?? "smooth";
|
|
4214
|
+
const easeParam = dragEase === "smooth" ? smoother : (u) => u;
|
|
4215
|
+
const n = Math.max(12, Math.round(target / 16));
|
|
4216
|
+
pumpPaused = true;
|
|
4217
|
+
await sleep(160);
|
|
4218
|
+
const tDrag = Date.now();
|
|
4219
|
+
const tMs$1 = tDrag - t0;
|
|
4220
|
+
mouse(cdp, "mouseMoved", path[0].x, path[0].y, 0).catch(() => {});
|
|
4221
|
+
mouse(cdp, "mousePressed", path[0].x, path[0].y, 1).catch(() => {});
|
|
4222
|
+
for (let k = 1; k <= n; k++) {
|
|
4223
|
+
const p = sampleAlong(path, easeParam(k / n));
|
|
4224
|
+
mouse(cdp, "mouseMoved", p.x, p.y, 1).catch(() => {});
|
|
4225
|
+
const due = tDrag + target * k / n;
|
|
4226
|
+
const slack = due - Date.now();
|
|
4227
|
+
if (slack > 0) await sleep(slack);
|
|
4228
|
+
}
|
|
4229
|
+
const last = path[path.length - 1];
|
|
4230
|
+
mouse(cdp, "mouseReleased", last.x, last.y, 0).catch(() => {});
|
|
4231
|
+
const drawnMs = Date.now() - tDrag;
|
|
4232
|
+
await sleep(120);
|
|
4233
|
+
pumpPaused = false;
|
|
4234
|
+
events.push({
|
|
4235
|
+
kind: "drag",
|
|
4236
|
+
x: from.x,
|
|
4237
|
+
y: from.y,
|
|
4238
|
+
to,
|
|
4239
|
+
path,
|
|
4240
|
+
tMs: tMs$1,
|
|
4241
|
+
sel: label$1,
|
|
4242
|
+
note: step.note,
|
|
4243
|
+
...step.caption ? { caption: step.caption } : {},
|
|
4244
|
+
durationMs: drawnMs,
|
|
4245
|
+
ease: dragEase,
|
|
4246
|
+
...step.zoom ? { zoom: step.zoom } : {}
|
|
4247
|
+
});
|
|
4248
|
+
await hold(1100);
|
|
4249
|
+
continue;
|
|
4250
|
+
}
|
|
4251
|
+
if (step.action === "dropFiles") {
|
|
4252
|
+
const label$1 = step.note ?? step.paths.map((p) => basename(p)).join(", ");
|
|
4253
|
+
if (!step.paths.length) {
|
|
4254
|
+
skip("dropFiles", label$1, "no files given (empty paths)");
|
|
4255
|
+
await hold(600);
|
|
4256
|
+
continue;
|
|
4257
|
+
}
|
|
4258
|
+
const absPaths = step.paths.map((p) => resolve(p));
|
|
4259
|
+
const missing = absPaths.filter((p) => !existsSync(p));
|
|
4260
|
+
if (missing.length) {
|
|
4261
|
+
skip("dropFiles", label$1, `file not found: ${missing.join(", ")}`);
|
|
4262
|
+
await hold(600);
|
|
4263
|
+
continue;
|
|
4264
|
+
}
|
|
4265
|
+
const files = absPaths.map((p) => {
|
|
4266
|
+
const st = statSync(p);
|
|
4267
|
+
return {
|
|
4268
|
+
name: basename(p),
|
|
4269
|
+
size: st.size
|
|
4270
|
+
};
|
|
4271
|
+
});
|
|
4272
|
+
let to;
|
|
4273
|
+
if (step.to || step.toSelector || step.toText) {
|
|
4274
|
+
const found = await resolvePoint({
|
|
4275
|
+
point: step.to,
|
|
4276
|
+
selector: step.toSelector,
|
|
4277
|
+
text: step.toText
|
|
4278
|
+
});
|
|
4279
|
+
if (!found) {
|
|
4280
|
+
skip("dropFiles", label$1, "drop target not found");
|
|
4281
|
+
await hold(600);
|
|
4282
|
+
continue;
|
|
4283
|
+
}
|
|
4284
|
+
to = found;
|
|
4285
|
+
} else to = {
|
|
4286
|
+
x: Math.round(inner[0] / 2),
|
|
4287
|
+
y: Math.round(inner[1] / 2)
|
|
4288
|
+
};
|
|
4289
|
+
const from = step.from ? {
|
|
4290
|
+
x: Math.round(step.from.x),
|
|
4291
|
+
y: Math.round(step.from.y)
|
|
4292
|
+
} : {
|
|
4293
|
+
x: inner[0] - 28,
|
|
4294
|
+
y: Math.round(inner[1] * .18)
|
|
4295
|
+
};
|
|
4296
|
+
const pathPts = (step.path ?? []).map((p) => ({
|
|
4297
|
+
x: Math.round(p.x),
|
|
4298
|
+
y: Math.round(p.y)
|
|
4299
|
+
}));
|
|
4300
|
+
const path = pathPts.length ? pathPts : [from, to];
|
|
4301
|
+
const target = step.durationMs ?? 1400;
|
|
4302
|
+
const dragEase = opts.dragEasing ?? "smooth";
|
|
4303
|
+
const easeParam = dragEase === "smooth" ? smoother : (u) => u;
|
|
4304
|
+
const data = {
|
|
4305
|
+
items: [],
|
|
4306
|
+
files: absPaths,
|
|
4307
|
+
dragOperationsMask: 1
|
|
4308
|
+
};
|
|
4309
|
+
const dragEvt = (type, p) => cdp.send("Input.dispatchDragEvent", {
|
|
4310
|
+
type,
|
|
4311
|
+
x: Math.round(p.x),
|
|
4312
|
+
y: Math.round(p.y),
|
|
4313
|
+
data
|
|
4314
|
+
});
|
|
4315
|
+
const n = Math.max(12, Math.round(target / 16));
|
|
4316
|
+
pumpPaused = true;
|
|
4317
|
+
await sleep(160);
|
|
4318
|
+
const tCarry = Date.now();
|
|
4319
|
+
const tMs$1 = tCarry - t0;
|
|
4320
|
+
const last = path[path.length - 1];
|
|
4321
|
+
let carriedMs;
|
|
4322
|
+
try {
|
|
4323
|
+
await dragEvt("dragEnter", path[0]);
|
|
4324
|
+
for (let k = 1; k <= n; k++) {
|
|
4325
|
+
const p = sampleAlong(path, easeParam(k / n));
|
|
4326
|
+
dragEvt("dragOver", p).catch(() => {});
|
|
4327
|
+
const due = tCarry + target * k / n;
|
|
4328
|
+
const slack = due - Date.now();
|
|
4329
|
+
if (slack > 0) await sleep(slack);
|
|
4330
|
+
}
|
|
4331
|
+
await dragEvt("dragOver", last).catch(() => {});
|
|
4332
|
+
await dragEvt("drop", last);
|
|
4333
|
+
carriedMs = Date.now() - tCarry;
|
|
4334
|
+
} catch (e) {
|
|
4335
|
+
pumpPaused = false;
|
|
4336
|
+
skip("dropFiles", label$1, `drag dispatch failed: ${e.message}`);
|
|
4337
|
+
await hold(600);
|
|
4338
|
+
continue;
|
|
4339
|
+
}
|
|
4340
|
+
await sleep(120);
|
|
4341
|
+
pumpPaused = false;
|
|
4342
|
+
events.push({
|
|
4343
|
+
kind: "dropFiles",
|
|
4344
|
+
x: path[0].x,
|
|
4345
|
+
y: path[0].y,
|
|
4346
|
+
to: last,
|
|
4347
|
+
path,
|
|
4348
|
+
tMs: tMs$1,
|
|
4349
|
+
sel: label$1,
|
|
4350
|
+
note: step.note,
|
|
4351
|
+
...step.caption ? { caption: step.caption } : {},
|
|
4352
|
+
durationMs: carriedMs,
|
|
4353
|
+
ease: dragEase,
|
|
4354
|
+
files,
|
|
4355
|
+
...step.zoom ? { zoom: step.zoom } : {}
|
|
4356
|
+
});
|
|
4357
|
+
await hold(1600);
|
|
4358
|
+
continue;
|
|
4359
|
+
}
|
|
4360
|
+
if (step.action === "scroll") {
|
|
4361
|
+
const tMs$1 = Date.now() - t0;
|
|
4362
|
+
let dy;
|
|
4363
|
+
if (step.toSelector || step.toText) {
|
|
4364
|
+
const r = await evalAny(cdp, step.toSelector ? scrollDeltaSelectorJs(step.toSelector) : scrollDeltaByTextJs(step.toText));
|
|
4365
|
+
if (r && typeof r.dy === "number") dy = r.dy;
|
|
4366
|
+
else {
|
|
4367
|
+
skip("scroll", step.toText ?? step.toSelector, "target not found");
|
|
4368
|
+
await hold(600);
|
|
4369
|
+
continue;
|
|
4370
|
+
}
|
|
4371
|
+
} else dy = step.dy ?? Math.round(vh * .8);
|
|
4372
|
+
const targetMs = step.durationMs ?? 1e3;
|
|
4373
|
+
const cx = Math.round(inner[0] / 2), cy = Math.round(inner[1] / 2);
|
|
4374
|
+
const start = Number(await evalAny(cdp, "window.scrollY")) || 0;
|
|
4375
|
+
const n = Math.max(12, Math.round(targetMs / 16));
|
|
4376
|
+
const tScroll = Date.now();
|
|
4377
|
+
for (let k = 1; k <= n; k++) {
|
|
4378
|
+
const u = k / n;
|
|
4379
|
+
const want = Math.round(dy * (u * u * u * (u * (u * 6 - 15) + 10)));
|
|
4380
|
+
await cdp.send("Runtime.evaluate", { expression: `window.scrollTo(0, ${start + want})` });
|
|
4381
|
+
const due = tScroll + targetMs * k / n;
|
|
4382
|
+
const slack = due - Date.now();
|
|
4383
|
+
if (slack > 0) await sleep(slack);
|
|
4384
|
+
}
|
|
4385
|
+
events.push({
|
|
4386
|
+
kind: "scroll",
|
|
4387
|
+
x: cx,
|
|
4388
|
+
y: cy,
|
|
4389
|
+
tMs: tMs$1,
|
|
4390
|
+
dy,
|
|
4391
|
+
durationMs: Date.now() - tScroll,
|
|
4392
|
+
note: step.note,
|
|
4393
|
+
...step.caption ? { caption: step.caption } : {}
|
|
4394
|
+
});
|
|
4395
|
+
await hold(800);
|
|
4396
|
+
continue;
|
|
4397
|
+
}
|
|
4398
|
+
if (step.action === "hover") {
|
|
4399
|
+
const label$1 = step.text ?? step.selector;
|
|
4400
|
+
const tMs$1 = Date.now() - t0;
|
|
4401
|
+
const box$1 = step.text ? await evalBox(cdp, boxByTextJs(step.text)) : step.selector ? await evalBox(cdp, boxSelectorJs(step.selector)) : null;
|
|
4402
|
+
if (!box$1) {
|
|
4403
|
+
skip("hover", label$1, "target not found");
|
|
4404
|
+
await hold(600);
|
|
4405
|
+
continue;
|
|
4406
|
+
}
|
|
4407
|
+
const c = center(box$1);
|
|
4408
|
+
const dwell = step.durationMs ?? 1200;
|
|
4409
|
+
await mouse(cdp, "mouseMoved", c.x, c.y, 0);
|
|
4410
|
+
events.push({
|
|
4411
|
+
kind: "hover",
|
|
4412
|
+
...c,
|
|
4413
|
+
box: box$1,
|
|
4414
|
+
tMs: tMs$1,
|
|
4415
|
+
sel: label$1,
|
|
4416
|
+
note: step.note,
|
|
4417
|
+
...step.caption ? { caption: step.caption } : {},
|
|
4418
|
+
durationMs: dwell,
|
|
4419
|
+
...step.zoom ? { zoom: step.zoom } : {}
|
|
4420
|
+
});
|
|
4421
|
+
await sleep(dwell);
|
|
4422
|
+
await hold(900);
|
|
4423
|
+
continue;
|
|
4424
|
+
}
|
|
4425
|
+
if (step.action === "select") {
|
|
4426
|
+
const label$1 = step.text ?? step.selector;
|
|
4427
|
+
const tMs$1 = Date.now() - t0;
|
|
4428
|
+
const r = await cdp.send("Runtime.evaluate", {
|
|
4429
|
+
expression: selectOptionJs({
|
|
4430
|
+
selector: step.selector,
|
|
4431
|
+
text: step.text
|
|
4432
|
+
}, step.value),
|
|
4433
|
+
returnByValue: true,
|
|
4434
|
+
awaitPromise: true
|
|
4435
|
+
});
|
|
4436
|
+
const raw = r.result?.value;
|
|
4437
|
+
const str = typeof raw === "string" ? raw : raw == null ? "NOTFOUND" : JSON.stringify(raw);
|
|
4438
|
+
if (str === "NOTFOUND" || str === "NOTASELECT" || str === "NOOPTION") {
|
|
4439
|
+
skip("select", label$1, str === "NOTASELECT" ? "target is not a <select> (use click for custom dropdowns)" : str === "NOOPTION" ? `no option matching ${JSON.stringify(step.value)}` : "target not found");
|
|
4440
|
+
await hold(600);
|
|
4441
|
+
continue;
|
|
4442
|
+
}
|
|
4443
|
+
const box$1 = findBox(evalValue(str));
|
|
4444
|
+
if (!box$1) {
|
|
4445
|
+
skip("select", label$1, "target not found");
|
|
4446
|
+
await hold(600);
|
|
4447
|
+
continue;
|
|
4448
|
+
}
|
|
4449
|
+
events.push({
|
|
4450
|
+
kind: "click",
|
|
4451
|
+
...center(box$1),
|
|
4452
|
+
box: box$1,
|
|
4453
|
+
tMs: tMs$1,
|
|
4454
|
+
sel: label$1,
|
|
4455
|
+
note: step.note,
|
|
4456
|
+
...step.caption ? { caption: step.caption } : {},
|
|
4457
|
+
...step.zoom ? { zoom: step.zoom } : {}
|
|
4458
|
+
});
|
|
4459
|
+
await hold(1300);
|
|
4460
|
+
continue;
|
|
4461
|
+
}
|
|
4462
|
+
if (step.action === "look") {
|
|
4463
|
+
const label$1 = step.text ?? step.selector;
|
|
4464
|
+
const tMs$1 = Date.now() - t0;
|
|
4465
|
+
const box$1 = step.text ? await evalBox(cdp, boxByTextJs(step.text)) : step.selector ? await evalBox(cdp, boxSelectorJs(step.selector)) : null;
|
|
4466
|
+
if (!box$1) {
|
|
4467
|
+
skip("look", label$1, step.text || step.selector ? "target not found" : "no target given");
|
|
4468
|
+
await hold(600);
|
|
4469
|
+
continue;
|
|
4470
|
+
}
|
|
4471
|
+
const dwell = step.durationMs ?? 1800;
|
|
4472
|
+
events.push({
|
|
4473
|
+
kind: "look",
|
|
4474
|
+
...center(box$1),
|
|
4475
|
+
box: box$1,
|
|
4476
|
+
tMs: tMs$1,
|
|
4477
|
+
sel: label$1,
|
|
4478
|
+
note: step.note,
|
|
4479
|
+
...step.caption ? { caption: step.caption } : {},
|
|
4480
|
+
durationMs: dwell,
|
|
4481
|
+
zoom: step.zoom ?? "always"
|
|
4482
|
+
});
|
|
4483
|
+
await sleep(dwell);
|
|
4484
|
+
await hold(900);
|
|
4485
|
+
continue;
|
|
4486
|
+
}
|
|
4487
|
+
if (step.action === "press") {
|
|
4488
|
+
const tMs$1 = Date.now() - t0;
|
|
4489
|
+
try {
|
|
4490
|
+
await pressChord(cdp, step.keys);
|
|
4491
|
+
} catch (e) {
|
|
4492
|
+
console.error(`captureTakeCDP: press failed for ${JSON.stringify(step.keys)}: ${e.message}`);
|
|
4493
|
+
}
|
|
4494
|
+
const dwell = step.durationMs ?? 1e3;
|
|
4495
|
+
let box$1 = null;
|
|
4496
|
+
if (step.selector || step.text) {
|
|
4497
|
+
await sleep(250);
|
|
4498
|
+
box$1 = step.text ? await evalBox(cdp, boxByTextJs(step.text)) : await evalBox(cdp, boxSelectorJs(step.selector));
|
|
4499
|
+
}
|
|
4500
|
+
const anchor = box$1 ? center(box$1) : {
|
|
4501
|
+
x: Math.round(inner[0] / 2),
|
|
4502
|
+
y: Math.round(inner[1] / 2)
|
|
4503
|
+
};
|
|
4504
|
+
events.push({
|
|
4505
|
+
kind: "press",
|
|
4506
|
+
...anchor,
|
|
4507
|
+
...box$1 ? { box: box$1 } : {},
|
|
4508
|
+
tMs: tMs$1,
|
|
4509
|
+
keys: step.keys,
|
|
4510
|
+
sel: step.text ?? step.selector,
|
|
4511
|
+
note: step.note,
|
|
4512
|
+
...step.caption ? { caption: step.caption } : {},
|
|
4513
|
+
durationMs: dwell,
|
|
4514
|
+
...step.zoom ? { zoom: step.zoom } : {}
|
|
4515
|
+
});
|
|
4516
|
+
await sleep(dwell);
|
|
4517
|
+
await hold(900);
|
|
4518
|
+
continue;
|
|
4519
|
+
}
|
|
4520
|
+
const label = step.text ?? step.selector;
|
|
4521
|
+
let tMs = Date.now() - t0;
|
|
4522
|
+
const clickRaw = step.text ? await evalString(cdp, clickByTextJs(step.text)) : step.selector ? await evalString(cdp, clickBySelectorJs(step.selector)) : null;
|
|
4523
|
+
if (clickRaw === "SELECTINERT") {
|
|
4524
|
+
skip("click", label, "clicking a native <select> does nothing headless (inert, no popup) — use the `select` action");
|
|
4525
|
+
await hold(600);
|
|
4526
|
+
continue;
|
|
4527
|
+
}
|
|
4528
|
+
const parsed = clickRaw ? evalValue(clickRaw) : null;
|
|
4529
|
+
const box = parsed ? findBox(parsed) : null;
|
|
4530
|
+
const pt = parsed && typeof parsed.cx === "number" && typeof parsed.cy === "number" ? {
|
|
4531
|
+
x: parsed.cx,
|
|
4532
|
+
y: parsed.cy
|
|
4533
|
+
} : null;
|
|
4534
|
+
if (box && pt) {
|
|
4535
|
+
pumpPaused = true;
|
|
4536
|
+
await sleep(160);
|
|
4537
|
+
tMs = Date.now() - t0;
|
|
4538
|
+
mouse(cdp, "mouseMoved", pt.x, pt.y, 0).catch(() => {});
|
|
4539
|
+
mouse(cdp, "mousePressed", pt.x, pt.y, 1).catch(() => {});
|
|
4540
|
+
await sleep(60);
|
|
4541
|
+
mouse(cdp, "mouseReleased", pt.x, pt.y, 0).catch(() => {});
|
|
4542
|
+
await sleep(120);
|
|
4543
|
+
pumpPaused = false;
|
|
4544
|
+
}
|
|
4545
|
+
if (box) events.push({
|
|
4546
|
+
kind: "click",
|
|
4547
|
+
...pt ?? center(box),
|
|
4548
|
+
box,
|
|
4549
|
+
tMs,
|
|
4550
|
+
sel: label,
|
|
4551
|
+
note: step.note,
|
|
4552
|
+
...step.caption ? { caption: step.caption } : {},
|
|
4553
|
+
...step.zoom ? { zoom: step.zoom } : {}
|
|
4554
|
+
});
|
|
4555
|
+
else skip("click", label, "target not found");
|
|
4556
|
+
await hold(1300);
|
|
4557
|
+
}
|
|
4558
|
+
const tEndMs = Date.now() - t0;
|
|
4559
|
+
await sleep(400);
|
|
4560
|
+
pumping = false;
|
|
4561
|
+
await pump;
|
|
4562
|
+
await screencast.stop();
|
|
4563
|
+
const encoded = encodeFrames(screencast.frames, tEndMs + 400, out, fps);
|
|
4564
|
+
encoded.catch(() => {});
|
|
4565
|
+
const sound = productAudio ? productAudio.finish({
|
|
4566
|
+
t0,
|
|
4567
|
+
endMs: tEndMs + 400,
|
|
4568
|
+
dir: dirname(out)
|
|
4569
|
+
}) : Promise.resolve(null);
|
|
4570
|
+
let stateItems;
|
|
4571
|
+
if (statesDir && (states.length || movingStates.length)) try {
|
|
4572
|
+
const saved = states.length ? await finalizeDomStates({
|
|
4573
|
+
browser,
|
|
4574
|
+
statesDir,
|
|
4575
|
+
states,
|
|
4576
|
+
vw: inner[0],
|
|
4577
|
+
vh: inner[1],
|
|
4578
|
+
parts: opts.components !== false
|
|
4579
|
+
}) : [];
|
|
4580
|
+
stateItems = [...saved, ...movingStates.map((m) => ({
|
|
4581
|
+
...m,
|
|
4582
|
+
moving: true
|
|
4583
|
+
}))].sort((a, b) => a.tMs - b.tMs);
|
|
4584
|
+
console.error(summarizeDomStates(states, stateItems));
|
|
4585
|
+
} catch (e) {
|
|
4586
|
+
console.error(`captureTakeCDP: DOM states not finalized (${e.message})`);
|
|
4587
|
+
}
|
|
4588
|
+
await encoded;
|
|
4589
|
+
const soundReport = await sound;
|
|
4590
|
+
if (soundReport) console.error(summarizeProductSound(soundReport));
|
|
4591
|
+
const probe = await ffprobe(out);
|
|
4592
|
+
if (probe.width && probe.height) {
|
|
4593
|
+
const videoAspect = probe.width / probe.height;
|
|
4594
|
+
const viewAspect = inner[0] / inner[1];
|
|
4595
|
+
if (Math.abs(videoAspect / viewAspect - 1) > .01) process.stderr.write(`⚠ the browser window resized MID-capture: viewport ${inner[0]}×${inner[1]} but the recording is ${probe.width}×${probe.height} — cursor/zoom coordinates in this take are skewed. Re-run; in a cloud/Xvfb environment give the screen a fixed size at least the requested viewport.\n`);
|
|
4596
|
+
}
|
|
4597
|
+
return {
|
|
4598
|
+
video: {
|
|
4599
|
+
width: probe.width ?? inner[0],
|
|
4600
|
+
height: probe.height ?? inner[1],
|
|
4601
|
+
fps: probe.fps,
|
|
4602
|
+
durationS: probe.durationS
|
|
4603
|
+
},
|
|
4604
|
+
viewport: {
|
|
4605
|
+
w: inner[0],
|
|
4606
|
+
h: inner[1]
|
|
4607
|
+
},
|
|
4608
|
+
start: plan.startCursor ?? {
|
|
4609
|
+
x: Math.round(inner[0] * .25),
|
|
4610
|
+
y: Math.round(inner[1] * .9)
|
|
4611
|
+
},
|
|
4612
|
+
events,
|
|
4613
|
+
tEndMs,
|
|
4614
|
+
captureCadence: {
|
|
4615
|
+
...captureCadence(screencast.frames),
|
|
4616
|
+
rasterRefresh: opts.rasterRefresh ?? "idle"
|
|
4617
|
+
},
|
|
4618
|
+
...skipped.length ? { skipped } : {},
|
|
4619
|
+
...precheck.length ? { precheck } : {},
|
|
4620
|
+
...settleWaits.length ? { settleWaits } : {},
|
|
4621
|
+
...paintedFrac >= PAINT_BLIND_FRAC ? { paintedFrac: Math.round(paintedFrac * 100) / 100 } : {},
|
|
4622
|
+
...stateItems ? { states: {
|
|
4623
|
+
dir: "states",
|
|
4624
|
+
items: stateItems
|
|
4625
|
+
} } : {}
|
|
4626
|
+
};
|
|
4627
|
+
} finally {
|
|
4628
|
+
await browser?.close();
|
|
4629
|
+
rmSync(frameDir, {
|
|
4630
|
+
recursive: true,
|
|
4631
|
+
force: true,
|
|
4632
|
+
maxRetries: 5,
|
|
4633
|
+
retryDelay: 100
|
|
4634
|
+
});
|
|
4635
|
+
}
|
|
4636
|
+
}
|
|
4637
|
+
/** One stderr paragraph on what the product's sound left in the take. */
|
|
4638
|
+
function summarizeProductSound(r) {
|
|
4639
|
+
const lines = [];
|
|
4640
|
+
if (r.audio) lines.push(`product audio: ${r.audio.file} — sound at ${r.audio.soundAt.length} moment(s), peak ${r.audio.peakDbfs} dBFS (placement estimated; see product-sound.json)`);
|
|
4641
|
+
else lines.push("product audio: not detected (the page sent nothing to its speakers)");
|
|
4642
|
+
if (r.files.length) {
|
|
4643
|
+
const saved = r.files.filter((f) => f.saved).length;
|
|
4644
|
+
lines.push(`product sound files: the page fetched ${r.files.length} audio file(s)${saved ? `, ${saved} saved to product-sounds/` : ""}`);
|
|
4645
|
+
}
|
|
4646
|
+
for (const n of r.notes) lines.push(`product audio: ${n}`);
|
|
4647
|
+
return lines.join("\n");
|
|
4648
|
+
}
|
|
4649
|
+
/** CI containment. A plan is agent-written, and the agent reads the very page
|
|
4650
|
+
* it films — a hostile string ON that page can talk its way into a plan step.
|
|
4651
|
+
* When OPEN_TAKE_ALLOWED_ORIGINS is set (comma-separated origins; `open-take
|
|
4652
|
+
* ci` sets it to the app's own origin), any navigation outside the list is a
|
|
4653
|
+
* skipped step, never a request. Unset (the interactive default), everything
|
|
4654
|
+
* is allowed — a human is watching. */
|
|
4655
|
+
function originAllowed(url) {
|
|
4656
|
+
const raw = process.env.OPEN_TAKE_ALLOWED_ORIGINS;
|
|
4657
|
+
if (!raw) return true;
|
|
4658
|
+
try {
|
|
4659
|
+
const origin = new URL(url).origin;
|
|
4660
|
+
return raw.split(",").some((entry) => entry.trim() === origin);
|
|
4661
|
+
} catch {
|
|
4662
|
+
return false;
|
|
4663
|
+
}
|
|
4664
|
+
}
|
|
4665
|
+
/** Runs in-page AFTER focus landed on the type target: names the field
|
|
4666
|
+
* "secret" when it is a password input or smells like a credential field.
|
|
4667
|
+
* Only consulted under OPEN_TAKE_CI — locally the human sees what is typed. */
|
|
4668
|
+
function credentialFieldProbeJs() {
|
|
4669
|
+
return `(() => {
|
|
4670
|
+
const el = document.activeElement;
|
|
4671
|
+
if (!el) return "ok";
|
|
4672
|
+
const type = (el.getAttribute("type") || "").toLowerCase();
|
|
4673
|
+
const smell = [el.getAttribute("name"), el.getAttribute("id"), el.getAttribute("autocomplete"), el.getAttribute("placeholder")]
|
|
4674
|
+
.filter(Boolean).join(" ").toLowerCase();
|
|
4675
|
+
return type === "password" || /passw|secret|api[-_]?key|access[-_]?token/.test(smell) ? "secret" : "ok";
|
|
4676
|
+
})()`;
|
|
4677
|
+
}
|
|
4678
|
+
/** Returns Chrome's `errorText` (e.g. "net::ERR_CONNECTION_REFUSED") when the
|
|
4679
|
+
* navigation never reached a server — the tab is then showing Chrome's own
|
|
4680
|
+
* error page, which fires load events like any document and would otherwise
|
|
4681
|
+
* get filmed as if it were the app. HTTP error PAGES (404/500) carry no
|
|
4682
|
+
* errorText: the app answered, and what it said is what an honest take shows. */
|
|
4683
|
+
async function navigate(cdp, url) {
|
|
4684
|
+
let timer;
|
|
4685
|
+
const loaded = new Promise((res) => {
|
|
4686
|
+
cdp.on("Page.loadEventFired", () => res());
|
|
4687
|
+
timer = setTimeout(res, 8e3);
|
|
4688
|
+
});
|
|
4689
|
+
const nav = await cdp.send("Page.navigate", { url });
|
|
4690
|
+
await loaded;
|
|
4691
|
+
clearTimeout(timer);
|
|
4692
|
+
return nav.errorText || void 0;
|
|
4693
|
+
}
|
|
4694
|
+
|
|
4695
|
+
//#endregion
|
|
4696
|
+
export { BOX_CANDIDATES, CDP, CLICK_CANDIDATES, CLICK_FALLBACK_CANDIDATES, DEFAULT_SETTLE_BUDGET_MS, FIELD_CANDIDATES, HITTABLE_JS, NAME_JS, PrecheckRefusal, UNREACHABLE_JS, awaitFonts, captureDomState, captureTake, captureTakeCDP, closeFidelityPage, dragCadence, ensureChrome, finalizeDomStates, fitViewport, inspectPage, installActivityProbe, isCdpStall, launchBrowser, measureParts, measureStateDirs, navigate, openFidelityPage, originAllowed, planTargets, precheckPlan, pressChord, renderState, resolveChrome, resolveNavigateUrl, runBuffer, selectAllInFocusedJs, settle };
|
|
4697
|
+
//# sourceMappingURL=cdp-capture-DfJeA-uY.js.map
|