@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.
@@ -0,0 +1,434 @@
1
+ /**
2
+ * `wkgeo template verify` —— 起本地服务 → Chrome 截图 → 与 `design/` 比对。
3
+ *
4
+ * ## 口径与门禁(老板 2026-10-30 定)
5
+ * * 桌面 1440×900 与移动 375×812 **两组都必须 ≥ `--threshold`(默认 0.95)**,否则 exit 1 并给差异图路径;
6
+ * * 比对**不另写算法**:直接 spawn `tools/render-compare/compare.mjs`(task-45 产物),读它产出的
7
+ * `report.json`。工具不存在时 **exit 2** 报「等 task-45」——这是派单写死的约定;
8
+ * * 另出 **动画清单**:`design/*-t0.png` 与 `*-t1500.png` 两帧逐像素差,聚类成区域后按面积排序。
9
+ * 实测 qibukuai.com 首屏两帧完全一致(虚拟时间不推进 CSS 动画、首屏无时间型运动),
10
+ * 这时清单就是空数组,报告里写 clear 的 note,**不编造动画**。
11
+ */
12
+
13
+ import fs from 'node:fs';
14
+ import fsp from 'node:fs/promises';
15
+ import path from 'node:path';
16
+ import { spawn } from 'node:child_process';
17
+ import { fileURLToPath } from 'node:url';
18
+
19
+ import { CliError, EXIT } from './errors.mjs';
20
+ import { VIEWPORTS, readPngSize, resolveChrome, measureAnimationGeom } from './template-capture.mjs';
21
+ import { readAnimationManifest, extractAnimationsFromDir, anchorsOf, reconcileAnimations } from './template-anim.mjs';
22
+ import { resolveBaseDir } from './template-gen.mjs';
23
+
24
+ const HERE = path.dirname(fileURLToPath(import.meta.url));
25
+
26
+ /** 找 task-45 的比对工具:显式 --compare > 环境变量 > cwd 往上 > 本文件往上 */
27
+ export function findCompareScript({ explicit = null, cwd = process.cwd(), env = process.env } = {}) {
28
+ const ok = (p) => p && fs.existsSync(p) && fs.statSync(p).isFile();
29
+ // 显式指定(--compare / WKGEO_COMPARE)却不存在时**不再猜**:否则用户以为跑的是自己指定的工具
30
+ if (explicit) return ok(explicit) ? path.resolve(explicit) : null;
31
+ if (env.WKGEO_COMPARE) return ok(env.WKGEO_COMPARE) ? path.resolve(env.WKGEO_COMPARE) : null;
32
+ for (const start of [cwd, HERE]) {
33
+ let dir = path.resolve(start);
34
+ for (let i = 0; i < 8; i++) {
35
+ const cand = path.join(dir, 'tools', 'render-compare', 'compare.mjs');
36
+ if (ok(cand)) return cand;
37
+ const parent = path.dirname(dir);
38
+ if (parent === dir) break;
39
+ dir = parent;
40
+ }
41
+ }
42
+ return null;
43
+ }
44
+
45
+ export const COMPARE_MISSING_MESSAGE =
46
+ '找不到像素比对工具 `tools/render-compare/compare.mjs`(task-45 产物)。\n' +
47
+ ' 这里不另写一套比对——请先等 task-45 落地,或用 `--compare <path>` 指定同契约的脚本。';
48
+
49
+ function runNode(args, { cwd, timeoutMs = 180000 } = {}) {
50
+ return new Promise((resolve) => {
51
+ const child = spawn(process.execPath, args, { cwd, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
52
+ let stdout = '';
53
+ let stderr = '';
54
+ const timer = setTimeout(() => {
55
+ try {
56
+ child.kill();
57
+ } catch {
58
+ /* ignore */
59
+ }
60
+ }, timeoutMs);
61
+ child.stdout.on('data', (d) => (stdout += d.toString('utf8')));
62
+ child.stderr.on('data', (d) => (stderr += d.toString('utf8')));
63
+ child.on('error', (e) => {
64
+ clearTimeout(timer);
65
+ resolve({ code: -1, stdout, stderr: stderr + String(e.message) });
66
+ });
67
+ child.on('close', (code) => {
68
+ clearTimeout(timer);
69
+ resolve({ code, stdout, stderr });
70
+ });
71
+ });
72
+ }
73
+
74
+ /**
75
+ * 两帧差异 → 动画区域清单。
76
+ * 用 16px 网格聚合:格子内变化像素 ≥ 12% 记"热格",热格做 8 邻域连通聚类,输出包围盒。
77
+ * 这样输出的是一块块"在动的地方",而不是 3 万个散点。
78
+ */
79
+ export function detectAnimationRegions(fileT0, fileT1500, { tolerance = 12, cell = 16, hotRatio = 0.12 } = {}) {
80
+ let png;
81
+ try {
82
+ png = requireCompareLib();
83
+ } catch (e) {
84
+ return { ok: false, reason: String(e.message || e) };
85
+ }
86
+ let a;
87
+ let b;
88
+ try {
89
+ a = png.decodePng(fs.readFileSync(fileT0));
90
+ b = png.decodePng(fs.readFileSync(fileT1500));
91
+ } catch (e) {
92
+ return { ok: false, reason: `帧解码失败:${e.message}` };
93
+ }
94
+ if (a.width !== b.width || a.height !== b.height) return { ok: false, reason: '两帧尺寸不一致' };
95
+ const px = png.comparePixels(a, b, { tolerance });
96
+ const { width, height } = a;
97
+ const cols = Math.ceil(width / cell);
98
+ const rows = Math.ceil(height / cell);
99
+ const hot = new Uint8Array(cols * rows);
100
+ const changed = new Int32Array(cols * rows);
101
+ let mismatch = 0;
102
+ for (let y = 0; y < height; y++) {
103
+ for (let x = 0; x < width; x++) {
104
+ const i = (y * width + x) * 4;
105
+ // comparePixels 的 diff 是**可视化 RGBA**:不一致像素涂红 (255,0,0,255),
106
+ // 一致像素涂灰度(值可能 >0)→ 只能按"红"判差异,不能按 >0 判。
107
+ if (px.diff[i] === 255 && px.diff[i + 1] === 0 && px.diff[i + 2] === 0) {
108
+ mismatch++;
109
+ changed[Math.floor(y / cell) * cols + Math.floor(x / cell)]++;
110
+ }
111
+ }
112
+ }
113
+ for (let r = 0; r < rows; r++) {
114
+ for (let c = 0; c < cols; c++) {
115
+ const area = cell * cell;
116
+ if (changed[r * cols + c] >= Math.max(3, area * hotRatio)) hot[r * cols + c] = 1;
117
+ }
118
+ }
119
+ const seen = new Uint8Array(cols * rows);
120
+ const regions = [];
121
+ const stack = [];
122
+ for (let r = 0; r < rows; r++) {
123
+ for (let c = 0; c < cols; c++) {
124
+ const idx = r * cols + c;
125
+ if (!hot[idx] || seen[idx]) continue;
126
+ stack.push(idx);
127
+ seen[idx] = 1;
128
+ let minC = c;
129
+ let maxC = c;
130
+ let minR = r;
131
+ let maxR = r;
132
+ let cells = 0;
133
+ while (stack.length) {
134
+ const cur = stack.pop();
135
+ const cr = Math.floor(cur / cols);
136
+ const cc = cur % cols;
137
+ cells++;
138
+ if (cc < minC) minC = cc;
139
+ if (cc > maxC) maxC = cc;
140
+ if (cr < minR) minR = cr;
141
+ if (cr > maxR) maxR = cr;
142
+ for (let dr = -1; dr <= 1; dr++) {
143
+ for (let dc = -1; dc <= 1; dc++) {
144
+ const nr = cr + dr;
145
+ const nc = cc + dc;
146
+ if (nr < 0 || nc < 0 || nr >= rows || nc >= cols) continue;
147
+ const ni = nr * cols + nc;
148
+ if (hot[ni] && !seen[ni]) {
149
+ seen[ni] = 1;
150
+ stack.push(ni);
151
+ }
152
+ }
153
+ }
154
+ }
155
+ regions.push({
156
+ x: minC * cell,
157
+ y: minR * cell,
158
+ w: Math.min(width, (maxC + 1) * cell) - minC * cell,
159
+ h: Math.min(height, (maxR + 1) * cell) - minR * cell,
160
+ cells,
161
+ });
162
+ }
163
+ }
164
+ regions.sort((p, q) => q.w * q.h - p.w * p.h);
165
+ return {
166
+ ok: true,
167
+ width,
168
+ height,
169
+ mismatch,
170
+ ratio: px.ratio,
171
+ changedRatio: mismatch / (width * height),
172
+ regions: regions.slice(0, 20).map((r) => ({
173
+ ...r,
174
+ label: `区域 ${r.x},${r.y} ${r.w}×${r.h}`,
175
+ })),
176
+ };
177
+ }
178
+
179
+ /** png/compare 两个库由 verify 命令动态 import 后注入(cli 单独分发时不强依赖 tools/) */
180
+ let _lib = null;
181
+ function requireCompareLib() {
182
+ if (_lib) return _lib;
183
+ throw new Error('比对库未加载(先调用 loadCompareLib(compareScript))');
184
+ }
185
+
186
+ /** verify 命令启动时注入(动态 import 得到模块对象) */
187
+ export function setCompareLib(lib) {
188
+ _lib = lib;
189
+ }
190
+
191
+ export async function loadCompareLib(scriptPath) {
192
+ const dir = path.dirname(scriptPath);
193
+ const png = await import(`file://${path.join(dir, 'lib', 'png.mjs')}`.replace(/\\/g, '/'));
194
+ const cmp = await import(`file://${path.join(dir, 'lib', 'compare.mjs')}`.replace(/\\/g, '/'));
195
+ const lib = { decodePng: png.decodePng, comparePixels: cmp.comparePixels };
196
+ setCompareLib(lib);
197
+ return lib;
198
+ }
199
+
200
+ function fmtPct(n) {
201
+ return `${(Number(n) * 100).toFixed(2)}%`;
202
+ }
203
+
204
+ /**
205
+ * 跑 verify。
206
+ * @returns {Promise<{pass:boolean,threshold:number,viewports:Array,animations:Array,note:string,compare:string,outDir:string}>}
207
+ */
208
+ export async function verifyTemplate({
209
+ dir,
210
+ designDir = null,
211
+ page = '/pages/index.html',
212
+ threshold = 0.95,
213
+ tolerance = 12,
214
+ outDir = null,
215
+ chromeExe = null,
216
+ compareScript = null,
217
+ onProgress = null,
218
+ timeoutMs = 180000,
219
+ animCheck = true,
220
+ }) {
221
+ const say = (s) => onProgress && onProgress(s);
222
+ const templateDir = path.resolve(dir);
223
+ if (!fs.existsSync(path.join(templateDir, 'template.json'))) {
224
+ throw new CliError(`不是模板目录(没有 template.json):${templateDir}`, { code: 'ENOTEMPLATE' });
225
+ }
226
+ const design = path.resolve(designDir || path.join(templateDir, 'design'));
227
+ const script = findCompareScript({ explicit: compareScript });
228
+ if (!script) throw new CliError(COMPARE_MISSING_MESSAGE, { kind: 'env', code: 'ECOMPARE', exitCode: EXIT.USAGE });
229
+
230
+ const chrome = resolveChrome(chromeExe);
231
+ const baseDir = resolveBaseDir(null, {});
232
+ if (!baseDir) say('提示:没找到 templates/_base(不影响比对)');
233
+
234
+ const out =
235
+ outDir ||
236
+ path.join(process.cwd(), '.wkgeo-verify', path.basename(templateDir) + '-' + new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19));
237
+ await fsp.mkdir(out, { recursive: true });
238
+
239
+ const results = [];
240
+ for (const vp of VIEWPORTS) {
241
+ const designFile = path.join(design, `${vp.name}.png`);
242
+ if (!fs.existsSync(designFile)) {
243
+ throw new CliError(
244
+ `design/ 里缺少 ${vp.name}.png,没法比。\n 目录:${design}\n 先跑:wkgeo template capture --dir <模板目录>(或重新 init --from-url)`,
245
+ { kind: 'verify', code: 'ENODESIGN', exitCode: EXIT.ERROR }
246
+ );
247
+ }
248
+ const caseOut = path.join(out, vp.name);
249
+ say(`比对 ${vp.name}(${vp.width}×${vp.height})…`);
250
+ const args = [
251
+ script,
252
+ '--design',
253
+ designFile,
254
+ '--dir',
255
+ templateDir,
256
+ '--page',
257
+ page,
258
+ '--viewport',
259
+ `${vp.width}x${vp.height}`,
260
+ '--threshold',
261
+ String(threshold),
262
+ '--tolerance',
263
+ String(tolerance),
264
+ '--out',
265
+ caseOut,
266
+ '--chrome',
267
+ chrome,
268
+ ];
269
+ const run = await runNode(args, { timeoutMs });
270
+ const reportPath = path.join(caseOut, 'report.json');
271
+ let report = null;
272
+ try {
273
+ report = JSON.parse(await fsp.readFile(reportPath, 'utf8'));
274
+ } catch {
275
+ /* 下面统一按失败处理 */
276
+ }
277
+ if (!report) {
278
+ throw new CliError(
279
+ `compare.mjs 没有产出 report.json(退出码 ${run.code})。\n 命令:node ${args.join(' ')}\n 输出:${(run.stderr || run.stdout).trim().slice(0, 800) || '(空)'}`,
280
+ { kind: 'verify', code: 'ECOMPAREFAIL', exitCode: run.code === 2 ? EXIT.USAGE : EXIT.ERROR }
281
+ );
282
+ }
283
+ const vpReport = (report.viewports || [])[0] || {};
284
+ results.push({
285
+ name: vp.name,
286
+ width: vp.width,
287
+ height: vp.height,
288
+ design: designFile,
289
+ ratio: Number(vpReport.ratio || 0),
290
+ mismatch: Number(vpReport.mismatch || 0),
291
+ total: Number(vpReport.total || 0),
292
+ pass: !!vpReport.pass && Number(vpReport.ratio || 0) >= threshold,
293
+ diffPath: vpReport.diffPath ? path.resolve(caseOut, path.basename(vpReport.diffPath)) : path.join(caseOut, `diff-${vp.width}x${vp.height}.png`),
294
+ renderPath: path.join(caseOut, `render-${vp.width}x${vp.height}.png`),
295
+ reportPath,
296
+ compareExit: run.code,
297
+ });
298
+ say(` ${vp.name} 一致率 ${fmtPct(vpReport.ratio || 0)}${vpReport.pass ? '(达标)' : '(不达标)'}`);
299
+ }
300
+
301
+ // ---- 动画清单(两帧) ----
302
+ const animations = [];
303
+ const notes = [];
304
+ try {
305
+ await loadCompareLib(script);
306
+ } catch (e) {
307
+ notes.push(`动画清单跳过:${e.message}`);
308
+ }
309
+ for (const vp of VIEWPORTS) {
310
+ const t0 = path.join(design, `${vp.name}-t0.png`);
311
+ const t15 = path.join(design, `${vp.name}-t1500.png`);
312
+ if (!fs.existsSync(t0) || !fs.existsSync(t15)) {
313
+ notes.push(`${vp.name} 没有 t0/t1500 帧(只做了主帧比对)`);
314
+ continue;
315
+ }
316
+ const r = detectAnimationRegions(t0, t15, { tolerance });
317
+ if (!r.ok) {
318
+ notes.push(`${vp.name} 动画检测失败:${r.reason}`);
319
+ continue;
320
+ }
321
+ animations.push({ viewport: vp.name, width: r.width, height: r.height, mismatch: r.mismatch, ratio: r.ratio, changedRatio: r.changedRatio, regions: r.regions });
322
+ }
323
+ const totalRegions = animations.reduce((n, a) => n + a.regions.length, 0);
324
+ const note = totalRegions
325
+ ? `动画区域 ${totalRegions} 处(t0 与 t1500 两帧不同的位置,按面积排序)`
326
+ : 't0 与 t1500 两帧逐像素一致:首屏没有时间型动画(或动画只由滚动/交互触发),动画清单为空';
327
+
328
+ // ---- 动画对账:期望(design/animations.json)vs 实测(模板渲染页 t0/t1500 像素差区域) ----
329
+ let reconcile = null;
330
+ const rendered = [];
331
+ if (animCheck) {
332
+ try {
333
+ let manifest = readAnimationManifest(design) || readAnimationManifest(templateDir);
334
+ if (!manifest) {
335
+ const ex = await extractAnimationsFromDir({ dir: templateDir, page });
336
+ manifest = ex.manifest;
337
+ notes.push(
338
+ `没有 design/animations.json,现场从模板源码抽了一份(${manifest.counts.total} 处);跑 \`wkgeo template anim --dir <目录>\` 可把它固定下来`
339
+ );
340
+ }
341
+ const probe = anchorsOf(manifest);
342
+ say(`动画对账:清单 ${manifest.counts.total} 处(首屏预期 ${manifest.counts.expectInWindow} 处),在模板渲染页上量 t0/t1500…`);
343
+ const measured = await measureAnimationGeom({
344
+ dir: templateDir,
345
+ page,
346
+ viewports: VIEWPORTS,
347
+ chromeExe: chrome,
348
+ probe,
349
+ outDir: path.join(out, 'anim'),
350
+ timeoutMs,
351
+ });
352
+ for (const vp of VIEWPORTS) {
353
+ const f = measured.frames[vp.name];
354
+ const r = detectAnimationRegions(f.t0, f.t1500, { tolerance });
355
+ if (!r.ok) {
356
+ notes.push(`${vp.name} 渲染页动画检测失败:${r.reason}`);
357
+ continue;
358
+ }
359
+ rendered.push({
360
+ viewport: vp.name,
361
+ width: r.width,
362
+ height: r.height,
363
+ mismatch: r.mismatch,
364
+ ratio: r.ratio,
365
+ changedRatio: r.changedRatio,
366
+ regions: r.regions,
367
+ t0: f.t0,
368
+ t1500: f.t1500,
369
+ });
370
+ }
371
+ reconcile = reconcileAnimations({ manifest, geom: measured.geom, animations: rendered });
372
+ say(` ${reconcile.note}`);
373
+ } catch (e) {
374
+ notes.push(`动画对账跳过:${e && e.message ? e.message : e}`);
375
+ reconcile = null;
376
+ }
377
+ }
378
+
379
+ const pass = results.every((r) => r.pass);
380
+ const payload = {
381
+ pass,
382
+ threshold,
383
+ tolerance,
384
+ dir: templateDir,
385
+ design,
386
+ page,
387
+ compare: script,
388
+ outDir: out,
389
+ viewports: results,
390
+ animations,
391
+ animationNote: note,
392
+ rendered,
393
+ reconcile,
394
+ animCheck,
395
+ notes,
396
+ };
397
+
398
+ if (!pass) {
399
+ const failed = results.filter((r) => !r.pass);
400
+ const lines = failed
401
+ .map((r) => ` - ${r.name}: ${fmtPct(r.ratio)} < ${fmtPct(threshold)}(差异图 ${r.diffPath})`)
402
+ .join('\n');
403
+ const err = new CliError(`一致率不达标(门禁 ${fmtPct(threshold)}):\n${lines}`, {
404
+ kind: 'verify',
405
+ code: 'EVERIFY',
406
+ exitCode: EXIT.ERROR,
407
+ raw: payload,
408
+ hint: '看差异图定位改了哪儿;design/ 与 pages/ 必须出自同一份抓取',
409
+ });
410
+ err.payload = payload;
411
+ // `--json` 里也要能给结构化结果(error.details),不然脚本只能去解析中文文案
412
+ err.details = { animCheck, reconcile, viewports: results.map((r) => ({ name: r.name, ratio: r.ratio, pass: r.pass, diffPath: r.diffPath })) };
413
+ throw err;
414
+ }
415
+
416
+ if (reconcile && !reconcile.ok) {
417
+ const lines = [];
418
+ for (const m of reconcile.missing) lines.push(` 缺失 ${m.id}(${m.kind} · ${m.selector})→ ${m.reason}`);
419
+ for (const x of reconcile.extra) lines.push(` 多余 ${x.viewport} ${x.region} → 清单里没有任何动画能解释这块运动`);
420
+ const err = new CliError(`动画对账不通过:缺失 ${reconcile.missing.length} 处 / 多余 ${reconcile.extra.length} 处\n${lines.join('\n')}`, {
421
+ kind: 'verify',
422
+ code: 'EANIM',
423
+ exitCode: EXIT.ERROR,
424
+ raw: payload,
425
+ hint: '缺失 = 清单声明了却没动(CSS 被删/被覆盖);多余 = 有运动没写进 design/animations.json(先跑 `wkgeo template anim --dir <目录>`)',
426
+ });
427
+ err.payload = payload;
428
+ err.details = { animCheck, reconcile, animations: rendered, viewports: results.map((r) => ({ name: r.name, ratio: r.ratio, pass: r.pass })) };
429
+ throw err;
430
+ }
431
+ return payload;
432
+ }
433
+
434
+ export { VIEWPORTS, readPngSize, EXIT };