@wkgeo/cli 1.1.0 → 1.1.1
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/CHANGELOG.md +31 -0
- package/README.md +151 -19
- package/SKILL.md +108 -27
- package/lib/args.mjs +2 -2
- package/lib/asset-role.mjs +68 -0
- package/lib/cms.mjs +2 -2
- package/lib/commands/billing.mjs +56 -10
- package/lib/commands/cms.mjs +49 -13
- package/lib/commands/content.mjs +108 -0
- package/lib/commands/crawl.mjs +219 -0
- package/lib/commands/geo.mjs +1673 -0
- package/lib/commands/index.mjs +640 -541
- package/lib/commands/member.mjs +930 -0
- package/lib/commands/seo.mjs +1386 -0
- package/lib/commands/siteops.mjs +3 -3
- package/lib/commands/sites.mjs +21 -125
- package/lib/commands/template.mjs +1222 -6
- package/lib/config.mjs +16 -13
- package/lib/content-apply.mjs +664 -0
- package/lib/content-check.mjs +887 -0
- package/lib/content-contract.mjs +957 -0
- package/lib/errors.mjs +6 -0
- package/lib/format.mjs +5 -1
- package/lib/manifest-apply.mjs +1499 -0
- package/lib/manifest-schema.json +476 -0
- package/lib/manifest.mjs +1082 -0
- package/lib/oauth-urls.mjs +1 -1
- package/lib/runtime.mjs +5 -1
- package/lib/site-create.mjs +536 -0
- package/lib/template-anim.mjs +1338 -0
- package/lib/template-animation.mjs +232 -0
- package/lib/template-capture.mjs +700 -0
- package/lib/template-gen.mjs +1204 -0
- package/lib/template-pack.mjs +206 -0
- package/lib/template-publish.mjs +733 -0
- package/lib/template-score.mjs +865 -0
- package/lib/template-validate.mjs +368 -0
- package/lib/template-verify.mjs +434 -0
- package/lib/templates-sync.mjs +616 -0
- package/package.json +2 -2
|
@@ -0,0 +1,700 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 模板「载图」——本机 Chrome headless 截图。
|
|
3
|
+
*
|
|
4
|
+
* ## 为什么在这里再写一遍截图(不复用 tools/render-compare)
|
|
5
|
+
* `cli/` 是随 npm 包分发的独立目录,不能 `import '../../tools/...'`(装到别人机器上就没有 tools)。
|
|
6
|
+
* 所以截图逻辑在这里自持一份,但**命令行参数与 tools/render-compare/lib/capture.mjs 逐字一致**
|
|
7
|
+
* (`--headless=new --disable-gpu --hide-scrollbars --force-device-scale-factor=1
|
|
8
|
+
* --window-size=W,H --virtual-time-budget=4000 --screenshot=<out>`)——
|
|
9
|
+
* 只有口径一致,`design/` 里的图才能和 verify 时 compare.mjs 现抓的图逐像素自比。
|
|
10
|
+
*
|
|
11
|
+
* ## 两类帧
|
|
12
|
+
* 1. **主帧**(`desktop-1440.png` / `mobile-375.png`):flag 模式 + `--virtual-time-budget=4000`,
|
|
13
|
+
* 与 compare.mjs 同口径,用于 ≥95% 一致率比对。
|
|
14
|
+
* 2. **动画帧**(`*-t0.png` / `*-t1500.png`):**CDP 真实时间**。
|
|
15
|
+
* 实测 `--virtual-time-budget=100` 与 `=1600` 抓出来逐像素相同(虚拟时间不推进 CSS 动画),
|
|
16
|
+
* 要抓"有没有在动"只能在同一个渲染会话里等真实的时间:加载后 ~120ms 抓一帧、~1500ms 再抓一帧。
|
|
17
|
+
*
|
|
18
|
+
* 截图失败(找不到 Chrome / 超时 / 产出不是 PNG)一律抛 `CaptureError`(exit 1 + 中文原因),
|
|
19
|
+
* 由命令层汇总成"整体失败",不允许产出半套 design/。
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
import fs from 'node:fs';
|
|
23
|
+
import fsp from 'node:fs/promises';
|
|
24
|
+
import http from 'node:http';
|
|
25
|
+
import os from 'node:os';
|
|
26
|
+
import path from 'node:path';
|
|
27
|
+
import { spawn } from 'node:child_process';
|
|
28
|
+
|
|
29
|
+
import { CliError, EXIT } from './errors.mjs';
|
|
30
|
+
import { ensureAnimationManifest, anchorsOf, writeAnimationGeom, ANIM_GEOM_FORMAT } from './template-anim.mjs';
|
|
31
|
+
|
|
32
|
+
/** 默认两个视口:与 compare.mjs 的默认视口同名同尺寸 */
|
|
33
|
+
export const VIEWPORTS = [
|
|
34
|
+
{ name: 'desktop-1440', width: 1440, height: 900 },
|
|
35
|
+
{ name: 'mobile-375', width: 375, height: 812 },
|
|
36
|
+
];
|
|
37
|
+
|
|
38
|
+
/** 截图失败:退出码 1(是"跑了但没成",不是用法错误) */
|
|
39
|
+
export class CaptureError extends CliError {
|
|
40
|
+
constructor(message, opts = {}) {
|
|
41
|
+
super(message, { kind: 'capture', code: opts.code || 'ECAPTURE', exitCode: EXIT.ERROR, ...opts });
|
|
42
|
+
this.name = 'CaptureError';
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
47
|
+
|
|
48
|
+
/** 本机 Chrome 的候选路径(Windows 优先,兼顾 macOS / Linux) */
|
|
49
|
+
export function chromeCandidates(env = process.env) {
|
|
50
|
+
const list = [];
|
|
51
|
+
for (const k of ['WKGEO_CHROME', 'RENDER_COMPARE_CHROME', 'CHROME_PATH']) {
|
|
52
|
+
if (env && env[k]) list.push(String(env[k]));
|
|
53
|
+
}
|
|
54
|
+
if (process.platform === 'win32') {
|
|
55
|
+
const roots = [env['PROGRAMFILES'], env['PROGRAMFILES(X86)'], env['PROGRAMW6432'], env['LOCALAPPDATA']].filter(Boolean);
|
|
56
|
+
for (const r of roots) list.push(path.join(r, 'Google', 'Chrome', 'Application', 'chrome.exe'));
|
|
57
|
+
list.push('C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe');
|
|
58
|
+
list.push('C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe');
|
|
59
|
+
} else if (process.platform === 'darwin') {
|
|
60
|
+
list.push('/Applications/Google Chrome.app/Contents/MacOS/Google Chrome');
|
|
61
|
+
list.push(path.join(os.homedir(), 'Applications/Google Chrome.app/Contents/MacOS/Google Chrome'));
|
|
62
|
+
} else {
|
|
63
|
+
list.push('/usr/bin/google-chrome', '/usr/bin/google-chrome-stable', '/usr/bin/chromium', '/usr/bin/chromium-browser');
|
|
64
|
+
}
|
|
65
|
+
return [...new Set(list)];
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* 定位本机 Chrome:显式 `--chrome` > 环境变量 > 常见安装路径。
|
|
70
|
+
* 找不到就抛 `CaptureError`,并把试过的路径全部列出来(老板能照着装/改)。
|
|
71
|
+
*/
|
|
72
|
+
export function resolveChrome(explicit, env = process.env) {
|
|
73
|
+
const tried = [];
|
|
74
|
+
const check = (p) => {
|
|
75
|
+
if (!p) return null;
|
|
76
|
+
tried.push(p);
|
|
77
|
+
try {
|
|
78
|
+
return fs.statSync(p).isFile() ? p : null;
|
|
79
|
+
} catch {
|
|
80
|
+
return null;
|
|
81
|
+
}
|
|
82
|
+
};
|
|
83
|
+
const hit = check(explicit);
|
|
84
|
+
if (hit) return hit;
|
|
85
|
+
for (const c of chromeCandidates(env)) {
|
|
86
|
+
const found = check(c);
|
|
87
|
+
if (found) return found;
|
|
88
|
+
}
|
|
89
|
+
throw new CaptureError(
|
|
90
|
+
'找不到本机 Chrome,无法截图(载图)。\n' +
|
|
91
|
+
` 试过的路径:\n${tried.map((t) => ` - ${t}`).join('\n')}\n` +
|
|
92
|
+
' 处理:装 Google Chrome,或用 `--chrome "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe"` 指定;\n' +
|
|
93
|
+
' 也可设环境变量 WKGEO_CHROME 指向 chrome.exe。',
|
|
94
|
+
{ code: 'ENOCHROME', hint: '装 Chrome 或 --chrome 指定路径' }
|
|
95
|
+
);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** 读 PNG 宽高(只查 IHDR,不解码像素) */
|
|
99
|
+
export function readPngSize(buf) {
|
|
100
|
+
const sig = [137, 80, 78, 71, 13, 10, 26, 10];
|
|
101
|
+
if (!buf || buf.length < 24) return null;
|
|
102
|
+
for (let i = 0; i < 8; i++) if (buf[i] !== sig[i]) return null;
|
|
103
|
+
if (buf.toString('latin1', 12, 16) !== 'IHDR') return null;
|
|
104
|
+
return { width: buf.readUInt32BE(16), height: buf.readUInt32BE(20) };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
async function statPng(file, want) {
|
|
108
|
+
let buf;
|
|
109
|
+
try {
|
|
110
|
+
buf = await fsp.readFile(file);
|
|
111
|
+
} catch (e) {
|
|
112
|
+
throw new CaptureError(`截图文件没生成:${file}(${e.code || e.message})`);
|
|
113
|
+
}
|
|
114
|
+
const size = readPngSize(buf);
|
|
115
|
+
if (!size) throw new CaptureError(`截图不是有效的 PNG:${file}(${buf.length}B)`);
|
|
116
|
+
const out = { path: file, bytes: buf.length, width: size.width, height: size.height };
|
|
117
|
+
if (want && (size.width !== want.width || size.height !== want.height)) {
|
|
118
|
+
out.warning = `尺寸 ${size.width}×${size.height} 与期望 ${want.width}×${want.height} 不一致`;
|
|
119
|
+
}
|
|
120
|
+
return out;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Windows 下 Chrome 会派生进程,必须整棵树杀 */
|
|
124
|
+
async function killTree(pid) {
|
|
125
|
+
if (!pid) return;
|
|
126
|
+
if (process.platform === 'win32') {
|
|
127
|
+
await new Promise((resolve) => {
|
|
128
|
+
const p = spawn('taskkill', ['/PID', String(pid), '/T', '/F'], { stdio: 'ignore', windowsHide: true });
|
|
129
|
+
p.on('close', resolve);
|
|
130
|
+
p.on('error', resolve);
|
|
131
|
+
});
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
try {
|
|
135
|
+
process.kill(pid, 'SIGKILL');
|
|
136
|
+
} catch {
|
|
137
|
+
/* ignore */
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
async function removeDir(dir) {
|
|
142
|
+
try {
|
|
143
|
+
await fsp.rm(dir, { recursive: true, force: true });
|
|
144
|
+
} catch {
|
|
145
|
+
/* Windows 上偶发占用,留给系统临时目录清理 */
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function baseChromeArgs(profileDir, width, height) {
|
|
150
|
+
return [
|
|
151
|
+
'--headless=new',
|
|
152
|
+
'--disable-gpu',
|
|
153
|
+
'--hide-scrollbars',
|
|
154
|
+
'--force-device-scale-factor=1',
|
|
155
|
+
`--window-size=${width},${height}`,
|
|
156
|
+
'--no-first-run',
|
|
157
|
+
'--no-default-browser-check',
|
|
158
|
+
'--disable-extensions',
|
|
159
|
+
'--disable-background-networking',
|
|
160
|
+
'--disable-sync',
|
|
161
|
+
'--mute-audio',
|
|
162
|
+
`--user-data-dir=${profileDir}`,
|
|
163
|
+
];
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
async function waitStable(file, timeoutMs) {
|
|
167
|
+
const deadline = Date.now() + timeoutMs;
|
|
168
|
+
let last = -1;
|
|
169
|
+
let changedAt = Date.now();
|
|
170
|
+
while (Date.now() < deadline) {
|
|
171
|
+
const st = await fsp.stat(file).catch(() => null);
|
|
172
|
+
if (st && st.size > 0) {
|
|
173
|
+
if (st.size === last) {
|
|
174
|
+
if (Date.now() - changedAt >= 120) return st.size;
|
|
175
|
+
} else {
|
|
176
|
+
last = st.size;
|
|
177
|
+
changedAt = Date.now();
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
await sleep(60);
|
|
181
|
+
}
|
|
182
|
+
const st = await fsp.stat(file).catch(() => null);
|
|
183
|
+
if (st && st.size > 0) return st.size;
|
|
184
|
+
throw new CaptureError(`等待截图写盘超时(${timeoutMs}ms):${file}`, { code: 'ETIMEOUT' });
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* flag 模式截一张(与 compare.mjs 同口径)。`budgetMs` 默认 4000。
|
|
189
|
+
* @returns {Promise<{path:string,bytes:number,width:number,height:number}>}
|
|
190
|
+
*/
|
|
191
|
+
export async function captureShot({ url, width, height, outPath, chromeExe, budgetMs = 4000, timeoutMs = 30000 }) {
|
|
192
|
+
const exe = resolveChrome(chromeExe);
|
|
193
|
+
outPath = path.resolve(outPath);
|
|
194
|
+
await fsp.mkdir(path.dirname(outPath), { recursive: true });
|
|
195
|
+
await fsp.rm(outPath, { force: true });
|
|
196
|
+
const profileDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'wk-tpl-shot-'));
|
|
197
|
+
const args = [...baseChromeArgs(profileDir, width, height), `--virtual-time-budget=${budgetMs}`, `--screenshot=${outPath}`, url];
|
|
198
|
+
|
|
199
|
+
let stderr = '';
|
|
200
|
+
const child = spawn(exe, args, { stdio: ['ignore', 'ignore', 'pipe'], windowsHide: true });
|
|
201
|
+
const timer = setTimeout(() => {
|
|
202
|
+
killTree(child.pid);
|
|
203
|
+
}, timeoutMs + 15000);
|
|
204
|
+
child.stderr.on('data', (d) => {
|
|
205
|
+
if (stderr.length < 20000) stderr += d.toString('utf8');
|
|
206
|
+
});
|
|
207
|
+
const exit = await new Promise((resolve) => {
|
|
208
|
+
child.on('error', (e) => resolve({ error: e.message }));
|
|
209
|
+
child.on('close', (code) => resolve({ code }));
|
|
210
|
+
});
|
|
211
|
+
clearTimeout(timer);
|
|
212
|
+
try {
|
|
213
|
+
if (exit.error) throw new CaptureError(`Chrome 启动失败:${exit.error}(${exe})`, { code: 'ENOCHROME' });
|
|
214
|
+
if (!fs.existsSync(outPath)) {
|
|
215
|
+
throw new CaptureError(
|
|
216
|
+
`Chrome 没有产出截图:${outPath}\n 目标 ${url}(${width}×${height})\n Chrome 输出:${stderr.trim().slice(0, 400) || '(空)'}`,
|
|
217
|
+
{ code: 'ESHOTMISS' }
|
|
218
|
+
);
|
|
219
|
+
}
|
|
220
|
+
await waitStable(outPath, 5000);
|
|
221
|
+
return await statPng(outPath, { width, height });
|
|
222
|
+
} finally {
|
|
223
|
+
await removeDir(profileDir);
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
// ---------------- 极简 CDP 客户端(同一会话抓两帧,用于动画清单) ----------------
|
|
228
|
+
|
|
229
|
+
class Cdp {
|
|
230
|
+
constructor(ws) {
|
|
231
|
+
this.ws = ws;
|
|
232
|
+
this.nextId = 1;
|
|
233
|
+
this.pending = new Map();
|
|
234
|
+
this.listeners = [];
|
|
235
|
+
ws.addEventListener('message', (ev) => {
|
|
236
|
+
let msg;
|
|
237
|
+
try {
|
|
238
|
+
msg = JSON.parse(typeof ev.data === 'string' ? ev.data : ev.data.toString());
|
|
239
|
+
} catch {
|
|
240
|
+
return;
|
|
241
|
+
}
|
|
242
|
+
if (msg.id && this.pending.has(msg.id)) {
|
|
243
|
+
const { resolve, reject } = this.pending.get(msg.id);
|
|
244
|
+
this.pending.delete(msg.id);
|
|
245
|
+
if (msg.error) reject(new CaptureError(`CDP 出错:${msg.error.message || 'unknown'}`));
|
|
246
|
+
else resolve(msg.result);
|
|
247
|
+
} else if (msg.method) {
|
|
248
|
+
for (const fn of this.listeners) fn(msg);
|
|
249
|
+
}
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
send(method, params = {}, sessionId) {
|
|
254
|
+
const id = this.nextId++;
|
|
255
|
+
const payload = { id, method, params };
|
|
256
|
+
if (sessionId) payload.sessionId = sessionId;
|
|
257
|
+
return new Promise((resolve, reject) => {
|
|
258
|
+
this.pending.set(id, { resolve, reject });
|
|
259
|
+
this.ws.send(JSON.stringify(payload));
|
|
260
|
+
setTimeout(() => {
|
|
261
|
+
if (this.pending.has(id)) {
|
|
262
|
+
this.pending.delete(id);
|
|
263
|
+
reject(new CaptureError(`CDP 调用超时:${method}`, { code: 'ETIMEOUT' }));
|
|
264
|
+
}
|
|
265
|
+
}, 30000);
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
on(fn) {
|
|
270
|
+
this.listeners.push(fn);
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
close() {
|
|
274
|
+
try {
|
|
275
|
+
this.ws.close();
|
|
276
|
+
} catch {
|
|
277
|
+
/* ignore */
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
async function launchChromeCdp(chromeExe, width, height) {
|
|
283
|
+
const exe = resolveChrome(chromeExe);
|
|
284
|
+
const profileDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'wk-tpl-cdp-'));
|
|
285
|
+
const port = 42000 + Math.floor(Math.random() * 6000);
|
|
286
|
+
const child = spawn(exe, [...baseChromeArgs(profileDir, width, height), `--remote-debugging-port=${port}`, 'about:blank'], {
|
|
287
|
+
stdio: ['ignore', 'ignore', 'pipe'],
|
|
288
|
+
windowsHide: true,
|
|
289
|
+
});
|
|
290
|
+
let stderr = '';
|
|
291
|
+
child.stderr.on('data', (d) => {
|
|
292
|
+
if (stderr.length < 20000) stderr += d.toString('utf8');
|
|
293
|
+
});
|
|
294
|
+
const deadline = Date.now() + 20000;
|
|
295
|
+
let wsUrl = null;
|
|
296
|
+
while (Date.now() < deadline) {
|
|
297
|
+
try {
|
|
298
|
+
const res = await fetch(`http://127.0.0.1:${port}/json/version`);
|
|
299
|
+
if (res.ok) {
|
|
300
|
+
const j = await res.json();
|
|
301
|
+
if (j.webSocketDebuggerUrl) {
|
|
302
|
+
wsUrl = j.webSocketDebuggerUrl;
|
|
303
|
+
break;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
} catch {
|
|
307
|
+
/* 端口还没起来 */
|
|
308
|
+
}
|
|
309
|
+
await sleep(120);
|
|
310
|
+
}
|
|
311
|
+
if (!wsUrl) {
|
|
312
|
+
await killTree(child.pid);
|
|
313
|
+
await removeDir(profileDir);
|
|
314
|
+
throw new CaptureError(
|
|
315
|
+
`连不上 Chrome 调试端口 ${port}(CDP 不可用)。\n Chrome 输出:${stderr.trim().slice(0, 300) || '(空)'}`,
|
|
316
|
+
{ code: 'ECDP' }
|
|
317
|
+
);
|
|
318
|
+
}
|
|
319
|
+
return { child, wsUrl, profileDir };
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/**
|
|
323
|
+
* 同一个渲染会话抓 t0 / t1500 两帧(真实时间)。
|
|
324
|
+
* t0 = 加载完成后 ~120ms;t1500 = 加载完成后 1500ms(相对同一时刻计时)。
|
|
325
|
+
*
|
|
326
|
+
* `probe`(可选)= 一组 CSS 选择器:两帧各量一次元素矩形与计算样式,
|
|
327
|
+
* 用来把像素差区域**归因**到具体动画(`design/animations.geom.json`)。
|
|
328
|
+
* @returns {Promise<{t0:{...},t1500:{...},probeT0:Array|null,probeT1500:Array|null}>}
|
|
329
|
+
*/
|
|
330
|
+
export async function captureFrames({ url, width, height, outT0, outT1500, chromeExe, settleStartMs = 120, probe = null }) {
|
|
331
|
+
let launched = null;
|
|
332
|
+
let session = null;
|
|
333
|
+
try {
|
|
334
|
+
launched = await launchChromeCdp(chromeExe, width, height);
|
|
335
|
+
const ws = new WebSocket(launched.wsUrl);
|
|
336
|
+
await new Promise((resolve, reject) => {
|
|
337
|
+
ws.addEventListener('open', resolve, { once: true });
|
|
338
|
+
ws.addEventListener('error', () => reject(new CaptureError('CDP WebSocket 连接失败', { code: 'ECDP' })), { once: true });
|
|
339
|
+
setTimeout(() => reject(new CaptureError('CDP WebSocket 连接超时', { code: 'ECDP' })), 15000);
|
|
340
|
+
});
|
|
341
|
+
session = new Cdp(ws);
|
|
342
|
+
const { targetId } = await session.send('Target.createTarget', { url: 'about:blank' });
|
|
343
|
+
const { sessionId } = await session.send('Target.attachToTarget', { targetId, flatten: true });
|
|
344
|
+
const send = (m, p) => session.send(m, p, sessionId);
|
|
345
|
+
|
|
346
|
+
let loaded = false;
|
|
347
|
+
session.on((msg) => {
|
|
348
|
+
if (msg.sessionId === sessionId && msg.method === 'Page.loadEventFired') loaded = true;
|
|
349
|
+
});
|
|
350
|
+
|
|
351
|
+
await send('Page.enable');
|
|
352
|
+
await send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: false });
|
|
353
|
+
const navStart = Date.now();
|
|
354
|
+
await send('Page.navigate', { url });
|
|
355
|
+
while (!loaded && Date.now() - navStart < 25000) await sleep(80);
|
|
356
|
+
if (!loaded) throw new CaptureError(`页面加载超时(25s):${url}`, { code: 'ETIMEOUT' });
|
|
357
|
+
const loadedAt = Date.now();
|
|
358
|
+
|
|
359
|
+
const shoot = async (file) => {
|
|
360
|
+
const { data } = await send('Page.captureScreenshot', { format: 'png' });
|
|
361
|
+
await fsp.mkdir(path.dirname(file), { recursive: true });
|
|
362
|
+
await fsp.writeFile(file, Buffer.from(data, 'base64'));
|
|
363
|
+
return await statPng(file, { width, height });
|
|
364
|
+
};
|
|
365
|
+
|
|
366
|
+
const probeExpr = probe && probe.length ? buildProbeExpression(probe) : null;
|
|
367
|
+
const readProbe = async () => {
|
|
368
|
+
if (!probeExpr) return null;
|
|
369
|
+
try {
|
|
370
|
+
const r = await send('Runtime.evaluate', { expression: probeExpr, returnByValue: true });
|
|
371
|
+
const v = r && r.result ? r.result.value : null;
|
|
372
|
+
if (typeof v === 'string') return JSON.parse(v);
|
|
373
|
+
return v || null;
|
|
374
|
+
} catch {
|
|
375
|
+
return null;
|
|
376
|
+
}
|
|
377
|
+
};
|
|
378
|
+
|
|
379
|
+
const waitTo = async (ms) => {
|
|
380
|
+
const left = loadedAt + ms - Date.now();
|
|
381
|
+
if (left > 0) await sleep(left);
|
|
382
|
+
};
|
|
383
|
+
|
|
384
|
+
await waitTo(settleStartMs);
|
|
385
|
+
const t0 = await shoot(outT0);
|
|
386
|
+
const probeT0 = await readProbe();
|
|
387
|
+
await waitTo(1500);
|
|
388
|
+
const t1500 = await shoot(outT1500);
|
|
389
|
+
const probeT1500 = await readProbe();
|
|
390
|
+
return { t0, t1500, msT0: settleStartMs, msT1500: 1500, probeT0, probeT1500 };
|
|
391
|
+
} finally {
|
|
392
|
+
if (session) session.close();
|
|
393
|
+
if (launched) {
|
|
394
|
+
await killTree(launched.child.pid);
|
|
395
|
+
await removeDir(launched.profileDir);
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
/**
|
|
401
|
+
* 生成在页面里跑的探针表达式:返回 `[{anchor, count, items:[{x,y,w,h,animationName,...}]}]` 的 JSON 字符串。
|
|
402
|
+
* 用 `getBoundingClientRect`(视口坐标)——与截图同坐标系,像素差区域可以直接相交判定。
|
|
403
|
+
*/
|
|
404
|
+
export function buildProbeExpression(selectors) {
|
|
405
|
+
const list = JSON.stringify(selectors);
|
|
406
|
+
return `(() => {
|
|
407
|
+
const sels = ${list};
|
|
408
|
+
const out = [];
|
|
409
|
+
for (const sel of sels) {
|
|
410
|
+
let els = [];
|
|
411
|
+
try { els = Array.prototype.slice.call(document.querySelectorAll(sel), 0, 6); } catch (e) { els = []; }
|
|
412
|
+
out.push({
|
|
413
|
+
anchor: sel,
|
|
414
|
+
count: els.length,
|
|
415
|
+
items: els.map((el) => {
|
|
416
|
+
const r = el.getBoundingClientRect();
|
|
417
|
+
const cs = getComputedStyle(el);
|
|
418
|
+
return {
|
|
419
|
+
x: Math.round(r.x), y: Math.round(r.y), w: Math.round(r.width), h: Math.round(r.height),
|
|
420
|
+
animationName: cs.animationName, animationDuration: cs.animationDuration, animationPlayState: cs.animationPlayState,
|
|
421
|
+
transitionProperty: cs.transitionProperty, transitionDuration: cs.transitionDuration,
|
|
422
|
+
opacity: cs.opacity, transform: cs.transform
|
|
423
|
+
};
|
|
424
|
+
})
|
|
425
|
+
});
|
|
426
|
+
}
|
|
427
|
+
return JSON.stringify(out);
|
|
428
|
+
})()`;
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
/** 把两帧探针结果合成 geom(元素矩形取两帧并集,见 reconcile 的 rectsOf) */
|
|
432
|
+
export function buildAnimationGeom({ url, page, viewport, items0, items1 }) {
|
|
433
|
+
const byAnchor = new Map();
|
|
434
|
+
for (const [phase, list] of [['t0', items0], ['t1500', items1]]) {
|
|
435
|
+
for (const it of list || []) {
|
|
436
|
+
const cur = byAnchor.get(it.anchor) || { anchor: it.anchor, count: 0, t0: [], t1500: [] };
|
|
437
|
+
cur.count = Math.max(cur.count, it.count || 0);
|
|
438
|
+
cur[phase] = it.items || [];
|
|
439
|
+
byAnchor.set(it.anchor, cur);
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
return {
|
|
443
|
+
_format: 'wkgeo-anim-geom@1',
|
|
444
|
+
url,
|
|
445
|
+
page,
|
|
446
|
+
viewport,
|
|
447
|
+
capturedAt: new Date().toISOString(),
|
|
448
|
+
items: [...byAnchor.values()],
|
|
449
|
+
};
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
/** 图片尺寸/存在性速查(不抛错) */
|
|
453
|
+
export function pngInfoSync(file) {
|
|
454
|
+
try {
|
|
455
|
+
const buf = fs.readFileSync(file);
|
|
456
|
+
const size = readPngSize(buf);
|
|
457
|
+
return size ? { ...size, bytes: buf.length, path: file } : null;
|
|
458
|
+
} catch {
|
|
459
|
+
return null;
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
/**
|
|
464
|
+
* 载图主流程:两个视口各一张主帧;`frames` 为真时再各出 t0/t1500。
|
|
465
|
+
* 任何一张失败 → 抛 CaptureError(命令层据此整体 exit 1)。
|
|
466
|
+
*
|
|
467
|
+
* 传了 `templateDir` 就顺带做动画抽样:先从模板源码抽清单写 `design/animations.json`,
|
|
468
|
+
* 再用清单里的锚点当探针,把两帧的元素矩形记进 `design/animations.geom.json`(verify 对账用)。
|
|
469
|
+
*
|
|
470
|
+
* @returns {Promise<{dir:string,chrome:string,url:string,files:Array,viewports:Array,animation:object|null}>}
|
|
471
|
+
*/
|
|
472
|
+
export async function captureDesign({
|
|
473
|
+
url,
|
|
474
|
+
dir,
|
|
475
|
+
viewports = VIEWPORTS,
|
|
476
|
+
frames = true,
|
|
477
|
+
chromeExe,
|
|
478
|
+
timeoutMs = 30000,
|
|
479
|
+
onProgress = null,
|
|
480
|
+
templateDir = null,
|
|
481
|
+
animRefresh = true,
|
|
482
|
+
writeGeom = true,
|
|
483
|
+
page = '/pages/index.html',
|
|
484
|
+
}) {
|
|
485
|
+
const chrome = resolveChrome(chromeExe);
|
|
486
|
+
const designDir = path.resolve(dir);
|
|
487
|
+
await fsp.mkdir(designDir, { recursive: true });
|
|
488
|
+
const files = [];
|
|
489
|
+
const viewportsOut = [];
|
|
490
|
+
const note = (s) => onProgress && onProgress(s);
|
|
491
|
+
|
|
492
|
+
let manifest = null;
|
|
493
|
+
let probe = null;
|
|
494
|
+
const geoms = {};
|
|
495
|
+
if (templateDir) {
|
|
496
|
+
note('抽取模板动画清单 …');
|
|
497
|
+
try {
|
|
498
|
+
manifest = await ensureAnimationManifest({ templateDir, designDir, refresh: animRefresh });
|
|
499
|
+
probe = anchorsOf(manifest);
|
|
500
|
+
note(`动画清单 ${manifest.counts.total} 处(首屏预期 ${manifest.counts.expectInWindow} 处,探针锚点 ${probe.length} 个)`);
|
|
501
|
+
} catch (e) {
|
|
502
|
+
manifest = null;
|
|
503
|
+
note(`动画清单抽取跳过:${e && e.message ? e.message : e}`);
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
for (const vp of viewports) {
|
|
508
|
+
note(`截图 ${vp.name}(${vp.width}×${vp.height})…`);
|
|
509
|
+
const mainPath = path.join(designDir, `${vp.name}.png`);
|
|
510
|
+
const main = await captureShot({ url, width: vp.width, height: vp.height, outPath: mainPath, chromeExe: chrome, budgetMs: 4000, timeoutMs });
|
|
511
|
+
files.push({ ...main, role: 'main', viewport: vp.name });
|
|
512
|
+
|
|
513
|
+
if (frames) {
|
|
514
|
+
note(`截动画帧 ${vp.name} t0 / t1500…`);
|
|
515
|
+
const t0Path = path.join(designDir, `${vp.name}-t0.png`);
|
|
516
|
+
const t15Path = path.join(designDir, `${vp.name}-t1500.png`);
|
|
517
|
+
const pair = await captureFrames({
|
|
518
|
+
url,
|
|
519
|
+
width: vp.width,
|
|
520
|
+
height: vp.height,
|
|
521
|
+
outT0: t0Path,
|
|
522
|
+
outT1500: t15Path,
|
|
523
|
+
chromeExe: chrome,
|
|
524
|
+
probe: probe && probe.length ? probe : null,
|
|
525
|
+
});
|
|
526
|
+
files.push({ ...pair.t0, role: 'frame-t0', viewport: vp.name });
|
|
527
|
+
files.push({ ...pair.t1500, role: 'frame-t1500', viewport: vp.name });
|
|
528
|
+
if (writeGeom && (pair.probeT0 || pair.probeT1500)) {
|
|
529
|
+
geoms[vp.name] = { name: vp.name, width: vp.width, height: vp.height, items: buildAnimationGeom({ url, page, viewport: vp.name, items0: pair.probeT0, items1: pair.probeT1500 }).items };
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
viewportsOut.push({ name: vp.name, width: vp.width, height: vp.height });
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
let geomFile = null;
|
|
536
|
+
if (Object.keys(geoms).length) {
|
|
537
|
+
geomFile = await writeAnimationGeom(designDir, { _format: ANIM_GEOM_FORMAT, url, page, capturedAt: new Date().toISOString(), viewports: geoms });
|
|
538
|
+
note(`动画几何证据 → ${path.basename(geomFile)}(${Object.keys(geoms).length} 个视口)`);
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
return {
|
|
542
|
+
dir: designDir,
|
|
543
|
+
chrome,
|
|
544
|
+
url,
|
|
545
|
+
files,
|
|
546
|
+
viewports: viewportsOut,
|
|
547
|
+
capturedAt: new Date().toISOString(),
|
|
548
|
+
animation: manifest ? { file: path.join(designDir, 'animations.json'), counts: manifest.counts, anchors: probe ? probe.length : 0, geom: geomFile } : null,
|
|
549
|
+
};
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
/**
|
|
553
|
+
* verify 用:在**模板自己的渲染页**上量一遍动画(真实时间 t0/t1500 + 元素矩形)。
|
|
554
|
+
*
|
|
555
|
+
* 为什么不在载图时量:`init --from-url` 的 design/ 拍的是**原站**,元素矩形属于原站;
|
|
556
|
+
* 对账要回答的是"模板这个包里的动画有没有真的动",所以必须在模板渲染结果上量。
|
|
557
|
+
* 产出 `render-t0.png` / `render-t1500.png` 作为证据(`outDir` 给了就留在那儿,否则用临时目录)。
|
|
558
|
+
*
|
|
559
|
+
* @returns {Promise<{url:string,page:string,frames:object,geom:object}>}
|
|
560
|
+
*/
|
|
561
|
+
export async function measureAnimationGeom({ dir, page = '/pages/index.html', viewports = VIEWPORTS, chromeExe, probe = null, outDir = null, timeoutMs = 30000 }) {
|
|
562
|
+
const chrome = resolveChrome(chromeExe);
|
|
563
|
+
const root = path.resolve(dir);
|
|
564
|
+
const server = await startStaticServer(root);
|
|
565
|
+
const url = server.url + String(page).replace(/^\/+/, '');
|
|
566
|
+
const tmpRoot = outDir ? null : path.join(os.tmpdir(), `wkgeo-anim-${process.pid}-${Date.now()}`);
|
|
567
|
+
const frames = {};
|
|
568
|
+
const geoms = {};
|
|
569
|
+
try {
|
|
570
|
+
for (const vp of viewports) {
|
|
571
|
+
const vpDir = outDir ? path.join(outDir, vp.name) : path.join(tmpRoot, vp.name);
|
|
572
|
+
await fsp.mkdir(vpDir, { recursive: true });
|
|
573
|
+
const pair = await captureFrames({
|
|
574
|
+
url,
|
|
575
|
+
width: vp.width,
|
|
576
|
+
height: vp.height,
|
|
577
|
+
outT0: path.join(vpDir, 'render-t0.png'),
|
|
578
|
+
outT1500: path.join(vpDir, 'render-t1500.png'),
|
|
579
|
+
chromeExe: chrome,
|
|
580
|
+
probe: probe && probe.length ? probe : null,
|
|
581
|
+
});
|
|
582
|
+
frames[vp.name] = {
|
|
583
|
+
t0: path.join(vpDir, 'render-t0.png'),
|
|
584
|
+
t1500: path.join(vpDir, 'render-t1500.png'),
|
|
585
|
+
msT0: pair.msT0,
|
|
586
|
+
msT1500: pair.msT1500,
|
|
587
|
+
};
|
|
588
|
+
geoms[vp.name] = {
|
|
589
|
+
name: vp.name,
|
|
590
|
+
width: vp.width,
|
|
591
|
+
height: vp.height,
|
|
592
|
+
items: buildAnimationGeom({ url, page, viewport: vp.name, items0: pair.probeT0, items1: pair.probeT1500 }).items,
|
|
593
|
+
};
|
|
594
|
+
}
|
|
595
|
+
} finally {
|
|
596
|
+
await server.close();
|
|
597
|
+
if (tmpRoot) await removeDir(tmpRoot);
|
|
598
|
+
}
|
|
599
|
+
return {
|
|
600
|
+
url,
|
|
601
|
+
page,
|
|
602
|
+
frames,
|
|
603
|
+
geom: { _format: ANIM_GEOM_FORMAT, url, page, capturedAt: new Date().toISOString(), viewports: geoms },
|
|
604
|
+
};
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
/** 校验 design/ 是否齐(≥2 张主帧;有 t0/t1500 更佳),返回清单与缺失项 */export function inspectDesign(designDir, viewports = VIEWPORTS) {
|
|
608
|
+
const present = [];
|
|
609
|
+
const missing = [];
|
|
610
|
+
for (const vp of viewports) {
|
|
611
|
+
for (const suffix of ['', '-t0', '-t1500']) {
|
|
612
|
+
const name = `${vp.name}${suffix}.png`;
|
|
613
|
+
const full = path.join(designDir, name);
|
|
614
|
+
const info = pngInfoSync(full);
|
|
615
|
+
if (info) present.push({ name, ...info, sizeOk: info.width === vp.width && info.height === vp.height });
|
|
616
|
+
else missing.push(name);
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
return { present, missing };
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
// ---------------- 本地静态服务(preview / 本地截图共用) ----------------
|
|
623
|
+
|
|
624
|
+
const MIME = {
|
|
625
|
+
'.html': 'text/html; charset=utf-8',
|
|
626
|
+
'.htm': 'text/html; charset=utf-8',
|
|
627
|
+
'.css': 'text/css; charset=utf-8',
|
|
628
|
+
'.js': 'text/javascript; charset=utf-8',
|
|
629
|
+
'.mjs': 'text/javascript; charset=utf-8',
|
|
630
|
+
'.json': 'application/json; charset=utf-8',
|
|
631
|
+
'.svg': 'image/svg+xml',
|
|
632
|
+
'.png': 'image/png',
|
|
633
|
+
'.jpg': 'image/jpeg',
|
|
634
|
+
'.jpeg': 'image/jpeg',
|
|
635
|
+
'.webp': 'image/webp',
|
|
636
|
+
'.gif': 'image/gif',
|
|
637
|
+
'.ico': 'image/x-icon',
|
|
638
|
+
'.woff': 'font/woff',
|
|
639
|
+
'.woff2': 'font/woff2',
|
|
640
|
+
'.ttf': 'font/ttf',
|
|
641
|
+
'.txt': 'text/plain; charset=utf-8',
|
|
642
|
+
'.md': 'text/markdown; charset=utf-8',
|
|
643
|
+
'.map': 'application/json; charset=utf-8',
|
|
644
|
+
};
|
|
645
|
+
|
|
646
|
+
/**
|
|
647
|
+
* 起一个只读静态服务(只服务 rootDir 之内的文件,拒绝 .. 越界)。
|
|
648
|
+
* `port` 为 0 时随机端口;`onRequest` 可拿到访问日志(preview 打印用)。
|
|
649
|
+
*/
|
|
650
|
+
export async function startStaticServer(rootDir, { port = 0, onRequest = null } = {}) {
|
|
651
|
+
const root = path.resolve(rootDir);
|
|
652
|
+
const sockets = new Set();
|
|
653
|
+
const server = http.createServer((req, res) => {
|
|
654
|
+
let pathname;
|
|
655
|
+
try {
|
|
656
|
+
pathname = decodeURIComponent(new URL(req.url, 'http://127.0.0.1').pathname);
|
|
657
|
+
} catch {
|
|
658
|
+
res.writeHead(400).end('bad request');
|
|
659
|
+
return;
|
|
660
|
+
}
|
|
661
|
+
let target = path.resolve(root, '.' + pathname);
|
|
662
|
+
if (target !== root && !target.startsWith(root + path.sep)) {
|
|
663
|
+
res.writeHead(403).end('forbidden');
|
|
664
|
+
return;
|
|
665
|
+
}
|
|
666
|
+
let st = fs.statSync(target, { throwIfNoEntry: false });
|
|
667
|
+
if (st && st.isDirectory()) {
|
|
668
|
+
target = path.join(target, 'index.html');
|
|
669
|
+
st = fs.statSync(target, { throwIfNoEntry: false });
|
|
670
|
+
}
|
|
671
|
+
if (!st || !st.isFile()) {
|
|
672
|
+
if (onRequest) onRequest({ path: pathname, status: 404 });
|
|
673
|
+
res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' }).end('404 Not Found');
|
|
674
|
+
return;
|
|
675
|
+
}
|
|
676
|
+
const type = MIME[path.extname(target).toLowerCase()] || 'application/octet-stream';
|
|
677
|
+
if (onRequest) onRequest({ path: pathname, status: 200 });
|
|
678
|
+
res.writeHead(200, { 'content-type': type, 'cache-control': 'no-store', 'content-length': st.size });
|
|
679
|
+
fs.createReadStream(target).pipe(res);
|
|
680
|
+
});
|
|
681
|
+
server.on('connection', (s) => {
|
|
682
|
+
sockets.add(s);
|
|
683
|
+
s.on('close', () => sockets.delete(s));
|
|
684
|
+
});
|
|
685
|
+
await new Promise((resolve, reject) => {
|
|
686
|
+
server.once('error', reject);
|
|
687
|
+
server.listen(port, '127.0.0.1', resolve);
|
|
688
|
+
});
|
|
689
|
+
const realPort = server.address().port;
|
|
690
|
+
return {
|
|
691
|
+
port: realPort,
|
|
692
|
+
url: `http://127.0.0.1:${realPort}/`,
|
|
693
|
+
root,
|
|
694
|
+
close: () =>
|
|
695
|
+
new Promise((resolve) => {
|
|
696
|
+
for (const s of sockets) s.destroy();
|
|
697
|
+
server.close(() => resolve());
|
|
698
|
+
}),
|
|
699
|
+
};
|
|
700
|
+
}
|