@whzxc/agent-design-gallery 0.6.0 → 0.8.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.
Files changed (41) hide show
  1. package/README.md +12 -1
  2. package/package.json +1 -1
  3. package/public/app.js +38 -10
  4. package/public/arrangement-worker.js +11 -0
  5. package/public/arrangement.js +49 -0
  6. package/public/assets.js +16 -4
  7. package/public/layout.js +29 -13
  8. package/src/cli-output.mjs +258 -0
  9. package/src/cli.mjs +120 -45
  10. package/src/http.mjs +1 -0
  11. package/src/hub/auth.mjs +2 -1
  12. package/src/hub/proxy.mjs +5 -3
  13. package/src/hub/registry.mjs +57 -23
  14. package/src/hub.mjs +36 -21
  15. package/src/lifecycle.mjs +109 -0
  16. package/src/link.mjs +10 -9
  17. package/src/open.mjs +58 -54
  18. package/src/perf.mjs +12 -0
  19. package/src/server.mjs +78 -41
  20. package/src/service.mjs +115 -94
  21. package/src/toolkit/arch-git.mjs +142 -10
  22. package/src/toolkit/arch-overlay.mjs +1 -1
  23. package/src/toolkit/arch.mjs +62 -58
  24. package/src/toolkit/browser.mjs +38 -12
  25. package/src/toolkit/build-store.mjs +11 -3
  26. package/src/toolkit/build-worker.mjs +4 -1
  27. package/src/toolkit/build.mjs +26 -2
  28. package/src/toolkit/commands.mjs +158 -86
  29. package/src/toolkit/compare.mjs +93 -46
  30. package/src/toolkit/config.mjs +23 -20
  31. package/src/toolkit/diff-inputs.mjs +239 -0
  32. package/src/toolkit/diff-policy.mjs +28 -0
  33. package/src/toolkit/diff.mjs +258 -0
  34. package/src/toolkit/migrate.mjs +42 -30
  35. package/src/toolkit/part-diff.mjs +118 -0
  36. package/src/toolkit/part-snapshot.mjs +264 -0
  37. package/src/toolkit/pixel-diff.mjs +103 -0
  38. package/src/toolkit/project.mjs +45 -33
  39. package/src/toolkit/results.mjs +44 -0
  40. package/src/toolkit/runtime.d.ts +2 -1
  41. package/src/toolkit/tokens.mjs +5 -4
@@ -1,13 +1,16 @@
1
- import { mkdirSync } from 'node:fs';
1
+ import { mkdirSync, readFileSync, existsSync } from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { availableParallelism } from 'node:os';
4
4
  import { buildSource } from './build.mjs';
5
5
  import { selectSources, relative, loadTokens, sourceDirectories, archFiles } from './project.mjs';
6
6
  import { importDirectionViolations } from './asset-rules.mjs';
7
- import { launch, loadFrame } from './browser.mjs';
7
+ import { launch, loadFrame, browserTask } from './browser.mjs';
8
+ import { CliError, classifyError } from '../cli-output.mjs';
9
+ import { commandFailure, cleanup, emptySelection } from './results.mjs';
8
10
  export function inspectFrame(tokenNames) {
9
- const frame = document.querySelector('[data-adg-frame]'), box = frame.getBoundingClientRect(), problems = new Set();
10
- if (frame.children.length !== 1 || [...frame.childNodes].some(n => n.nodeType === 3 && n.textContent.trim())) problems.add('Frame needs exactly one root element');
11
+ const frame = document.querySelector('[data-adg-frame]'), box = frame.getBoundingClientRect(), problems = new Map();
12
+ const add = (code, message) => problems.set(message, {code, message, line:null, column:null});
13
+ if (frame.children.length !== 1 || [...frame.childNodes].some(n => n.nodeType === 3 && n.textContent.trim())) add('FRAME_ROOT_INVALID', 'Frame needs exactly one root element');
11
14
  const sample = document.createElement('i'); document.body.append(sample);
12
15
  const canvas = document.createElement('canvas'); canvas.width = canvas.height = 1;
13
16
  const context = canvas.getContext('2d', { colorSpace: 'srgb', colorType: 'float16', willReadFrequently: true });
@@ -73,16 +76,16 @@ export function inspectFrame(tokenNames) {
73
76
  const lines = [], covers = [];
74
77
  for (const el of [frame, ...frame.querySelectorAll('*')]) {
75
78
  const s = style(el), r = rectFor(el);
76
- if (['STYLE','SCRIPT'].includes(el.tagName.toUpperCase())) problems.add(`Forbidden <${el.tagName.toLowerCase()}> in output`);
77
- for (const attr of el.attributes) if (/^on/i.test(attr.name) || attr.name === 'classname') problems.add(`Forbidden attribute ${attr.name} in output`);
79
+ if (['STYLE','SCRIPT'].includes(el.tagName.toUpperCase())) add('MARKUP_FORBIDDEN', `Forbidden <${el.tagName.toLowerCase()}> in output`);
80
+ for (const attr of el.attributes) if (/^on/i.test(attr.name) || attr.name === 'classname') add('MARKUP_FORBIDDEN', `Forbidden attribute ${attr.name} in output`);
78
81
  if (!el.closest('[data-free]')) {
79
82
  const authored = (el.getAttribute('class') ?? '') + ' ' + (el.getAttribute('style') ?? '');
80
- if ([...authored.matchAll(/(-?(?:\d*\.)?\d+)px\b/g)].some(m => !Number.isInteger(Number(m[1])))) problems.add('Fractional pixel length outside data-free');
81
- for (const [,property] of (el.getAttribute('style') ?? '').matchAll(/(?:^|;)\s*([-\w]+)\s*:/g)) if (!['width','height'].includes(property) && !property.startsWith('--')) problems.add(`Style ${property} outside data-free; use layout classes`);
83
+ if ([...authored.matchAll(/(-?(?:\d*\.)?\d+)px\b/g)].some(m => !Number.isInteger(Number(m[1])))) add('FRACTIONAL_LENGTH', 'Fractional pixel length outside data-free');
84
+ for (const [,property] of (el.getAttribute('style') ?? '').matchAll(/(?:^|;)\s*([-\w]+)\s*:/g)) if (!['width','height'].includes(property) && !property.startsWith('--')) add('STYLE_FORBIDDEN', `Style ${property} outside data-free; use layout classes`);
82
85
  }
83
86
  if (s.display === 'none' || s.visibility === 'hidden' || r.width === 0 || r.height === 0) continue;
84
87
  const visibleBox=clipped(r,el.parentElement);
85
- if (nonempty(visibleBox) && outside(visibleBox)) problems.add('Content overflows the frame');
88
+ if (nonempty(visibleBox) && outside(visibleBox)) add('FRAME_OVERFLOW', 'Content overflows the frame');
86
89
  // A border-box background has the same rounded hit shape as its element.
87
90
  // Other background clips/masks cannot establish rectangular opaque coverage.
88
91
  if (el instanceof HTMLElement && s.backgroundClip==='border-box' && opaqueColor(s.backgroundColor) && opaqueEffects(el)) {
@@ -101,7 +104,7 @@ export function inspectFrame(tokenNames) {
101
104
  const matches = colors.some(color => alpha < 1
102
105
  ? paint.slice(0, 3).every((channel, i) => Math.abs(channel - color[i]) <= 2)
103
106
  : paint.every((channel, i) => channel === color[i]));
104
- if (!matches) problems.add(`Color ${value} matches no token`);
107
+ if (!matches) add('TOKEN_COLOR_MISMATCH', `Color ${value} matches no token`);
105
108
  }
106
109
  }
107
110
  for (const node of el.childNodes) {
@@ -112,9 +115,9 @@ export function inspectFrame(tokenNames) {
112
115
  const label = node.textContent.trim().replace(/\s+/g, ' ');
113
116
  const visible=clipped(rect,el);
114
117
  if (!nonempty(visible)) continue;
115
- if (outside(visible)) problems.add(`Text leaves frame: ${label}`);
118
+ if (outside(visible)) add('TEXT_OUTSIDE_FRAME', `Text leaves frame: ${label}`);
116
119
  if (visible.left < r.left - 1 || visible.right > r.right + 1 ||
117
- (visible.top+visible.bottom)/2 < r.top - 1 || (visible.top+visible.bottom)/2 > r.bottom + 1) problems.add(`Text overflows its box: ${label}`);
120
+ (visible.top+visible.bottom)/2 < r.top - 1 || (visible.top+visible.bottom)/2 > r.bottom + 1) add('TEXT_OVERFLOW', `Text overflows its box: ${label}`);
118
121
  const inFrame=intersect(visible,box);
119
122
  if (nonempty(inFrame)) lines.push({rect:inFrame,label,el});
120
123
  }
@@ -163,7 +166,7 @@ export function inspectFrame(tokenNames) {
163
166
  if (a.el===b.el) continue;
164
167
  const overlap=intersect(a.rect,b.rect);
165
168
  if (overlap.right-overlap.left>1 && overlap.bottom-overlap.top>2 &&
166
- !occluded(a.el,overlap) && !occluded(b.el,overlap)) problems.add(`Text overlaps: ${a.label} / ${b.label}`);
169
+ !occluded(a.el,overlap) && !occluded(b.el,overlap)) add('TEXT_OVERLAP', `Text overlaps: ${a.label} / ${b.label}`);
167
170
  }
168
171
  } finally {
169
172
  for (const [el,authored] of restored) {
@@ -174,100 +177,169 @@ export function inspectFrame(tokenNames) {
174
177
  }
175
178
  for (const [el,authored] of inert) el.setAttribute('inert',authored);
176
179
  }
177
- return [...problems];
180
+ return [...problems.values()];
178
181
  }
179
- export async function check(config, args = [], options = {}, log = console.log, error = console.error) {
180
- const write=!options['read-only'];
181
- const files = selectSources(config,args,{write}), tokens = loadTokens(config), problems = new Set(), graph={};
182
- const arch = files.some(file=>file.endsWith('.mmd')) ? await import('./arch.mjs') : null;
183
- const browser = await launch();
182
+ export async function check(config, args = [], options = {}, log = console.log, error = console.error, { launchBrowser = launch } = {}) {
183
+ const write = !options['read-only'];
184
+ /** @type {import('./results.mjs').CheckData} */
185
+ const data = { project: config.root, readOnly: !write, complete: false, sources: [], summary: { sources: 0, frames: 0, evaluations: 0, problems: 0 }, findings: [] };
186
+ const warnings = [], humanProblems = new Set(), findingKeys = new Set(), graph = {};
187
+ let browser, primary;
188
+ const add = (problem, file, frame = null, theme = null, source = relative(config, file)) => {
189
+ const finding = { ...problem, source, frame, theme };
190
+ const key = JSON.stringify(finding);
191
+ if (!findingKeys.has(key)) { findingKeys.add(key); data.findings.push(finding); }
192
+ humanProblems.add(`${relative(config, file)}: ${frame === null ? '' : `${frame}: ${theme}: `}${problem.message}`);
193
+ data.summary.problems = data.findings.length;
194
+ };
195
+ const failed = cause => {
196
+ const failure = cause instanceof CliError ? cause : new CliError('SOURCE_BUILD_FAILED', cause.message, { cause });
197
+ if (!primary) primary = failure;
198
+ else warnings.push(classifyError(failure).error);
199
+ };
184
200
  try {
185
- const page = await browser.newPage();
201
+ const files = selectSources(config, args, { write });
202
+ data.sources = files.map(file => relative(config, file));
203
+ data.summary.sources = files.length;
204
+ const tokens = files.length ? loadTokens(config) : null;
205
+ const arch = files.some(file => file.endsWith('.mmd')) ? await import('./arch.mjs') : null;
206
+ let page;
186
207
  for (const file of files) {
187
- const architecture=file.endsWith('.mmd');
188
- if(architecture) {
189
- const {readFileSync,existsSync}=await import('node:fs');
190
- const text=readFileSync(file,'utf8'), side=file.replace(/\.mmd$/,'.md');
191
- const metadata=arch.sidecar(existsSync(side)?readFileSync(side,'utf8'):'');
192
- for(const problem of [...arch.inspectArch(text,config.check?.archMaxEdges??30).problems,...metadata.problems,...arch.ownerProblems(config,metadata)]) problems.add(`${relative(config,file)}: ${problem}`);
193
- if([...problems].some(problem=>problem.startsWith(relative(config,file)+':'))) continue;
208
+ const architecture = file.endsWith('.mmd');
209
+ if (architecture) {
210
+ const side = file.replace(/\.mmd$/, '.md');
211
+ const metadata = arch.sidecar(existsSync(side) ? readFileSync(side, 'utf8') : '');
212
+ const validation = arch.inspectArch(readFileSync(file, 'utf8'), config.check?.archMaxEdges ?? 30).problems;
213
+ const sidecarProblems = [...metadata.problems, ...arch.ownerProblems(config, metadata)];
214
+ for (const problem of validation) add(problem, file);
215
+ for (const problem of sidecarProblems) add(problem, file, null, null, relative(config, side));
216
+ if (validation.length || sidecarProblems.length) continue;
194
217
  }
195
218
  let built;
196
- try { built = await buildSource(config,file,{allowLegacy:false,write,browser}); }
197
- catch(e) {
198
- const legacy = e.errors?.find(error => error.detail?.code === 'LEGACY_SVG');
219
+ try {
220
+ // Static architecture rejection is a completed rule evaluation and needs no browser.
221
+ browser ??= await launchBrowser();
222
+ built = await buildSource(config, file, { allowLegacy: false, write, browser });
223
+ } catch (cause) {
224
+ const legacy = cause.errors?.find(item => item.detail?.code === 'LEGACY_SOURCE');
199
225
  if (legacy) throw legacy.detail;
200
- for(const problem of e.message.split('\n')) problems.add(`${relative(config,file)}: ${architecture?'':'-: '}${problem.replace(/\s+/g,' ')}`); continue;
226
+ if (['PLAYWRIGHT_UNAVAILABLE', 'CHROMIUM_UNAVAILABLE', 'BROWSER_FAILED', 'LEGACY_SOURCE'].includes(cause.code)) throw cause;
227
+ failed(cause);
228
+ for (const message of cause.message.split('\n')) humanProblems.add(`${relative(config, file)}: ${architecture ? '' : '-: '}${message.replace(/\s+/g, ' ')}`);
229
+ continue;
201
230
  }
202
- graph[path.relative(config.design,file).split(path.sep).join('/')]={uses:built.imports};
203
- for (const frame of built.frames) for (const theme of ['light','dark']) {
231
+ data.summary.frames += built.frames.length;
232
+ graph[path.relative(config.design, file).split(path.sep).join('/')] = { uses: built.imports };
233
+ for (const frame of built.frames) for (const theme of ['light', 'dark']) {
204
234
  try {
205
- await loadFrame(page,frame,theme);
206
- for (const problem of await page.evaluate(architecture?arch.inspectArchLabels:inspectFrame,architecture?undefined:[...tokens.light.keys()])) problems.add(`${relative(config,file)}: ${frame.name}: ${theme}: ${problem}`);
207
- } catch(e) { problems.add(`${relative(config,file)}: ${frame.name}: ${theme}: ${e.message.replace(/\s+/g,' ')}`); }
235
+ page ??= await browserTask(browser, () => browser.newPage());
236
+ await loadFrame(page, frame, theme);
237
+ const findings = await browserTask(browser, () => page.evaluate(architecture ? arch.inspectArchLabels : inspectFrame, architecture ? undefined : [...tokens.light.keys()]));
238
+ for (const finding of findings) add(finding, file, frame.name, theme);
239
+ data.summary.evaluations++;
240
+ } catch (cause) {
241
+ failed(cause);
242
+ humanProblems.add(`${relative(config, file)}: ${frame.name}: ${theme}: ${cause.message.replace(/\s+/g, ' ')}`);
243
+ }
208
244
  }
209
245
  }
210
- } finally { await browser.close(); }
211
- if (config.check?.importDirection!==false) for (const {source,target,from,to} of importDirectionViolations(graph,sourceDirectories(config))) {
212
- problems.add(`${relative(config,path.join(config.design,source))}: import ${target} violates import direction (${from} -> ${to}); import from the same or a lower layer in sources`);
213
- }
214
- for (const problem of problems) error(problem);
215
- log(`Design check ${problems.size ? 'failed' : 'passed'} for ${files.length} sources${problems.size ? `: ${problems.size} problems` : ''}.`);
216
- return problems.size ? 1 : 0;
246
+ await cleanup(() => browser?.close(), primary);
247
+ browser = null;
248
+ if (config.check?.importDirection !== false) for (const { source, target, from, to } of importDirectionViolations(graph, sourceDirectories(config))) {
249
+ add({ code: 'IMPORT_DIRECTION', message: `import ${target} violates import direction (${from} -> ${to}); import from the same or a lower layer in sources`, line: null, column: null }, path.join(config.design, source));
250
+ }
251
+ for (const problem of humanProblems) error(problem);
252
+ const message = `Design check ${humanProblems.size ? 'failed' : 'passed'} for ${files.length} sources${humanProblems.size ? `: ${humanProblems.size} problems` : ''}.`;
253
+ log(message);
254
+ if (!files.length) emptySelection(warnings);
255
+ if (primary) { primary.humanReported = true; throw primary; }
256
+ data.complete = true;
257
+ if (data.findings.length) throw new CliError('CHECK_FAILED', message, { data, warnings, humanReported: true });
258
+ return { data, warnings };
259
+ } catch (cause) {
260
+ primary = commandFailure(cause, data, warnings);
261
+ throw primary;
262
+ } finally { if (browser) await cleanup(() => browser.close(), primary); }
217
263
  }
218
- export async function render(config, args = [], options = {}) {
219
- const scale = Number(options.scale ?? 2);
220
- if (!(Number.isFinite(scale) && scale > 0)) throw Error('Invalid --scale; use a positive number');
221
- const themeOption = options.theme ?? 'both';
222
- if (!['both', 'light', 'dark'].includes(themeOption)) throw Error('Choose --theme=both, light, or dark.');
223
- if (options['out-dir'] === '') throw Error('Set --out-dir to a directory.');
264
+
265
+ export async function render(config, args = [], options = {}, log = console.log, { launchBrowser = launch } = {}) {
224
266
  const output = options['out-dir'] ? path.resolve(config.root, options['out-dir']) : config.output;
225
- const themes = themeOption === 'both' ? ['light', 'dark'] : [themeOption];
226
- let base,deleted=[],additional=[];
227
- if(options.base!==undefined && (!args.length || args.some(arg=>arg.endsWith('.mmd')))) {
228
- const git=await import('./arch-git.mjs');
229
- base=await git.resolveBase(config,options.base);
230
- additional=await git.baseArchFiles(config,base);
231
- }
232
- const selected=selectSources(config,args,{additional});
233
- const {existsSync}=await import('node:fs');
234
- const currentArchitecture=base?new Set(archFiles(config.arch)):null;
235
- const files=selected.filter(file=>{if(!existsSync(file)||(base&&file.endsWith('.mmd')&&!currentArchitecture.has(file))){deleted.push(relative(config,file));return false;}return true;});
236
- const browser = base && !files.length ? null : await launch();
267
+ /** @type {import('./results.mjs').RenderData} */
268
+ const data = { project: config.root, outputDirectory: output, complete: false, base: null, captures: [], deleted: [] };
269
+ const warnings = [], completed = [], failures = [];
270
+ let browser, primary;
237
271
  try {
272
+ const scale = Number(options.scale ?? 2);
273
+ if (!(Number.isFinite(scale) && scale > 0)) throw new CliError('USAGE_INVALID', 'Invalid --scale; use a positive number');
274
+ const themeOption = options.theme ?? 'both';
275
+ if (!['both', 'light', 'dark'].includes(themeOption)) throw new CliError('USAGE_INVALID', 'Choose --theme=both, light, or dark.');
276
+ if (options['out-dir'] === '') throw new CliError('USAGE_INVALID', 'Set --out-dir to a directory.');
277
+ const themes = themeOption === 'both' ? ['light', 'dark'] : [themeOption];
278
+ let base, additional = [];
279
+ if (options.base !== undefined && (!args.length || args.some(arg => arg.endsWith('.mmd')))) {
280
+ const git = await import('./arch-git.mjs');
281
+ base = await git.resolveBase(config, options.base);
282
+ additional = await git.baseArchFiles(config, base);
283
+ data.base = { rev: base.rev, sha: base.sha };
284
+ } else if (options.base !== undefined) warnings.push({ code: 'USAGE_INVALID', message: '--base applies only to architecture sources.', next: [] });
285
+ const selected = selectSources(config, args, { additional });
286
+ const currentArchitecture = base ? new Set(archFiles(config.arch)) : null;
287
+ const files = selected.filter(file => {
288
+ if (!existsSync(file) || (base && file.endsWith('.mmd') && !currentArchitecture.has(file))) { data.deleted.push(relative(config, file)); return false; }
289
+ return true;
290
+ });
291
+ if (!selected.length) emptySelection(warnings);
292
+ if (files.length) browser = await launchBrowser();
238
293
  const captures = [];
239
294
  for (const file of files) {
240
- const built = base&&file.endsWith('.mmd') ? await (await import('./arch-overlay.mjs')).buildOverlay(config,file,{base,browser}) : await buildSource(config,file,{allowLegacy:false,browser});
241
- for (const frame of built.frames.filter(f => !options.frame || f.name === options.frame)) {
242
- for (const theme of themes) {
243
- const source = file.endsWith('.mmd') ? relative(config,file) : path.relative(config.design, file);
244
- const target = path.join(output, source.replace(/\.(?:tsx|mmd)$/, ''), `${encodeURIComponent(frame.name)}-${theme}.png`);
245
- captures.push({source,frame,theme,target});
246
- }
295
+ const built = base && file.endsWith('.mmd') ? await (await import('./arch-overlay.mjs')).buildOverlay(config, file, { base, browser }) : await buildSource(config, file, { allowLegacy: false, browser });
296
+ for (const frame of built.frames.filter(frame => !options.frame || frame.name === options.frame)) for (const theme of themes) {
297
+ const outputSource = file.endsWith('.mmd') ? relative(config, file) : path.relative(config.design, file);
298
+ const target = path.join(output, outputSource.replace(/\.(?:tsx|mmd)$/, ''), `${encodeURIComponent(frame.name)}-${theme}.png`);
299
+ captures.push({ source: relative(config, file), frame, theme, target });
247
300
  }
248
301
  }
249
- if (options.frame && !captures.length && !deleted.length) throw Error(`Unknown frame ${options.frame}; choose a declared frame`);
302
+ if (options.frame && !captures.length && !data.deleted.length) throw new CliError('FRAME_NOT_FOUND', `Unknown frame ${options.frame}; choose a declared frame`);
250
303
  let next = 0;
251
- const workers = await Promise.allSettled(Array.from({length:Math.min(4,availableParallelism(),captures.length)},async () => {
304
+ await Promise.allSettled(Array.from({ length: Math.min(4, availableParallelism(), captures.length) }, async () => {
252
305
  while (next < captures.length) {
253
- const {frame,theme,target} = captures[next++];
254
- // Chromium reuses image resampling state across setContent calls.
255
- // A fresh page/context per capture keeps PNG bytes independent of history.
256
- const page = await browser.newPage({deviceScaleFactor:scale});
306
+ const index = next++, { source, frame, theme, target } = captures[index];
307
+ let page, failure;
257
308
  try {
258
- await loadFrame(page,frame,theme);
259
- mkdirSync(path.dirname(target),{recursive:true});
260
- await page.locator('[data-adg-frame]').screenshot({path:target});
261
- } finally { await page.close(); }
309
+ page = await browserTask(browser, () => browser.newPage({ deviceScaleFactor: scale }));
310
+ await loadFrame(page, frame, theme);
311
+ mkdirSync(path.dirname(target), { recursive: true });
312
+ const { box, png } = await browserTask(browser, async () => {
313
+ const element = page.locator('[data-adg-frame]');
314
+ const box = await element.boundingBox();
315
+ if (!box) throw Error('Frame has no visible bounds.');
316
+ return { box, png: await element.screenshot({ path: target }) };
317
+ });
318
+ completed[index] = { source, frame: frame.name, theme, path: target, scale, width: box.width, height: box.height, pixelWidth: png.readUInt32BE(16), pixelHeight: png.readUInt32BE(20) };
319
+ } catch (cause) {
320
+ failure = commandFailure(cause, data, warnings);
321
+ failures.push({ index, failure });
322
+ throw failure;
323
+ } finally {
324
+ if (page) try { await cleanup(() => page.close(), failure); }
325
+ catch (cause) { failures.push({ index, failure: commandFailure(cause, data, warnings) }); throw cause; }
326
+ }
262
327
  }
263
328
  }));
264
- const failed = workers.find(worker => worker.status === 'rejected');
265
- if (failed) throw failed.reason;
266
- if (options.json) {
267
- const output=captures.map(({source,frame,theme,target})=>({source:source.split(path.sep).join('/'),frame:frame.name,theme,path:target}));
268
- console.log(JSON.stringify(base?{base:{rev:base.rev,sha:base.sha},captures:output,deleted}:output));
329
+ data.captures = completed.filter(Boolean);
330
+ failures.sort((a, b) => a.index - b.index);
331
+ if (failures.length) {
332
+ for (const { failure } of failures.slice(1)) warnings.push(classifyError(failure).error);
333
+ throw failures[0].failure;
269
334
  }
270
- else for (const {target} of captures) console.log(relative(config,target));
271
- } finally { await browser?.close(); }
272
- return 0;
335
+ if (!options.json) for (const capture of data.captures) log(relative(config, capture.path));
336
+ await cleanup(() => browser?.close(), null);
337
+ browser = null;
338
+ data.complete = true;
339
+ return { data, warnings };
340
+ } catch (cause) {
341
+ data.captures = completed.filter(Boolean);
342
+ primary = commandFailure(cause, data, warnings);
343
+ throw primary;
344
+ } finally { if (browser) await cleanup(() => browser.close(), primary); }
273
345
  }
@@ -7,6 +7,8 @@ import { matchTexts, textDelta } from './text.mjs';
7
7
  import { selectSources, relative } from './project.mjs';
8
8
  import { buildSource } from './build.mjs';
9
9
  import { viewport } from './config.mjs';
10
+ import { CliError, classifyError } from '../cli-output.mjs';
11
+ import { commandFailure, cleanup, emptySelection } from './results.mjs';
10
12
 
11
13
  export function compareReport(asset, frame, fixture, design, implementation) {
12
14
  const { pairs, missing, extra } = matchTexts(design.texts, implementation.texts);
@@ -45,58 +47,63 @@ async function overlay(page, target) {
45
47
  writeFileSync(path.join(target, 'overlay.png'), Buffer.from(data, 'base64'));
46
48
  }
47
49
  const safeName = value => encodeURIComponent(value).replace(/\./g, '%2E');
48
- async function settle(read) {
49
- const started = performance.now();
50
+ export async function settle(read, { now: monotonicNow = () => performance.now(), sleep = delay } = {}) {
51
+ const started = monotonicNow();
50
52
  let previous, changed = started;
51
53
  for (;;) {
52
54
  const implementation = await read();
53
55
  const state = JSON.stringify({ box: implementation.box, texts: implementation.texts.map(({ text, x, y, width, height }) => ({ text, x, y, width, height })) });
54
- const now = performance.now();
56
+ const now = monotonicNow();
55
57
  if (state !== previous) { previous = state; changed = now; }
56
58
  if (now - changed >= 300) return { implementation, settled: true };
57
59
  if (now - started >= 5000) return { implementation, settled: false };
58
- await delay(Math.min(50, 5000 - (now - started)));
60
+ await sleep(Math.min(50, 5000 - (now - started)));
59
61
  }
60
62
  }
61
- export async function compare(config, args, options) {
62
- if (options.all) return compareAll(config);
63
- const file = selectSources(config, args)[0], adapter = config.compare;
64
- if (!adapter.fixture) throw new Error('Compare needs compare.fixture(name); add it to adg.config.mjs');
65
- if ([options.region,options.selector,options.page].filter(Boolean).length > 1) throw Error('Choose --region, --selector or --page');
66
- const frame = options.frame;
67
- const built = await buildSource(config,file,{allowLegacy:false}), definition = built.frames.find(f=>f.name===frame);
68
- if (!definition) throw Error(`Unknown frame ${frame}; choose a declared frame`);
63
+ async function adapterCall(adapter, method, ...args) {
64
+ try { return await adapter[method](...args); }
65
+ catch (cause) {
66
+ if (cause instanceof CliError) throw cause;
67
+ const code = classifyError(cause).error.code;
68
+ throw new CliError(code === 'INTERNAL_ERROR' ? 'COMPARE_ADAPTER_FAILED' : code, cause.message, { cause });
69
+ }
70
+ }
71
+
72
+ async function compareFrame(config, file, definition, options, data, { launchBrowser, clock, log }) {
73
+ const adapter = config.compare, frame = definition.name;
74
+ if (!adapter.fixture) throw new CliError('CONFIG_INVALID', 'Compare needs compare.fixture(name); add it to adg.config.mjs');
75
+ if ([options.region,options.selector,options.page].filter(Boolean).length > 1) throw new CliError('USAGE_INVALID', 'Choose --region, --selector or --page');
69
76
  const settings = {...definition.capture};
70
77
  if (options.region || options.selector || options.page) { delete settings.region; delete settings.selector; delete settings.page; }
71
78
  for (const key of ['region','selector','page','origin','viewport']) if (options[key] !== undefined) settings[key] = options[key];
72
79
  settings.clicks = options.click ?? settings.clicks ?? [];
73
- const browser = await launch();
74
- let stop;
80
+ const browser = await launchBrowser();
81
+ let stop, primary;
75
82
  try {
76
83
  const fixtureName = options.fixture ?? definition.fixture;
77
- if (!fixtureName) throw Error('Frame needs a fixture; supply --fixture or Frame fixture');
78
- const fixture = await adapter.fixture(fixtureName);
79
- if (!fixture || typeof fixture.url !== 'string' || !['light', 'dark'].includes(fixture.theme) || typeof fixture.locale !== 'string' || !fixture.locale || !Number.isFinite(Date.parse(fixture.clock))) throw new Error('compare.fixture must return url, theme (light/dark), locale and a valid clock; fix adg.config.mjs');
84
+ if (!fixtureName) throw new CliError('CONFIG_INVALID', 'Frame needs a fixture; supply --fixture or Frame fixture');
85
+ const fixture = await adapterCall(adapter, 'fixture', fixtureName);
86
+ if (!fixture || typeof fixture.url !== 'string' || !['light', 'dark'].includes(fixture.theme) || typeof fixture.locale !== 'string' || !fixture.locale || !Number.isFinite(Date.parse(fixture.clock))) throw new CliError('CONFIG_INVALID', 'compare.fixture must return url, theme (light/dark), locale and a valid clock; fix adg.config.mjs');
80
87
  if (fixture.timezone !== undefined) {
81
88
  try {
82
89
  if (typeof fixture.timezone !== 'string' || !fixture.timezone || /^[+-]/.test(fixture.timezone)) throw new Error();
83
90
  new Intl.DateTimeFormat('en-US', { timeZone: fixture.timezone });
84
- } catch { throw new Error('compare.fixture timezone must be a valid IANA time zone such as Asia/Shanghai; fix adg.config.mjs'); }
91
+ } catch { throw new CliError('CONFIG_INVALID', 'compare.fixture timezone must be a valid IANA time zone such as Asia/Shanghai; fix adg.config.mjs'); }
85
92
  }
86
93
  const sheet = await browser.newPage({colorScheme:fixture.theme,locale:fixture.locale,timezoneId:fixture.timezone,reducedMotion:'reduce'});
87
94
  const frameBox = await loadFrame(sheet,definition,fixture.theme);
88
95
  let design = await sheet.locator('[data-adg-frame] > :first-child').evaluate(implementationTexts);
89
96
  const size = viewport(settings.viewport ?? adapter.viewport);
90
97
  const origin = (settings.origin ?? '0 0').trim().split(/\s+/).map(Number);
91
- if (settings.page && (origin.length !== 2 || !origin.every(Number.isFinite) || origin.some(n=>n<0) || origin[0]+frameBox.width>size.width || origin[1]+frameBox.height>size.height)) throw Error('Frame does not fit capture viewport; fix origin or viewport');
92
- if (!settings.page && !settings.region && !settings.selector) throw Error('Frame needs capture; supply --page, --region or --selector');
98
+ if (settings.page && (origin.length !== 2 || !origin.every(Number.isFinite) || origin.some(n=>n<0) || origin[0]+frameBox.width>size.width || origin[1]+frameBox.height>size.height)) throw new CliError('CONFIG_INVALID', 'Frame does not fit capture viewport; fix origin or viewport');
99
+ if (!settings.page && !settings.region && !settings.selector) throw new CliError('CONFIG_INVALID', 'Frame needs capture; supply --page, --region or --selector');
93
100
  const absolute = /^https?:\/\//.test(fixture.url);
94
- if (!adapter.start && !absolute) throw new Error('Relative fixture URL needs compare.start; add it or return an absolute URL');
101
+ if (!adapter.start && !absolute) throw new CliError('CONFIG_INVALID', 'Relative fixture URL needs compare.start; add it or return an absolute URL');
95
102
  const url = new URL(fixture.url, `http://127.0.0.1:${adapter.port}`).href;
96
- if (!/^https?:/.test(url)) throw new Error('Fixture URL must use HTTP or HTTPS; fix compare.fixture');
103
+ if (!/^https?:/.test(url)) throw new CliError('CONFIG_INVALID', 'Fixture URL must use HTTP or HTTPS; fix compare.fixture');
97
104
  if (adapter.start) {
98
- stop = await adapter.start({ port: adapter.port, root: config.root });
99
- if (typeof stop !== 'function') throw new Error('compare.start must return a stop function; fix adg.config.mjs');
105
+ stop = await adapterCall(adapter, 'start', { port: adapter.port, root: config.root });
106
+ if (typeof stop !== 'function') throw new CliError('CONFIG_INVALID', 'compare.start must return a stop function; fix adg.config.mjs');
100
107
  }
101
108
  await sheet.emulateMedia({ colorScheme: fixture.theme, reducedMotion: 'reduce' });
102
109
  await sheet.evaluate(theme => document.documentElement.setAttribute('data-theme', theme), fixture.theme);
@@ -119,8 +126,11 @@ export async function compare(config, args, options) {
119
126
  else { const observer = new MutationObserver(() => { if (document.documentElement) { apply(); observer.disconnect(); } }); observer.observe(document, { childList: true }); }
120
127
  document.addEventListener('DOMContentLoaded', apply, { once: true });
121
128
  }, { clock: fixture.clock, theme: fixture.theme });
122
- await app.goto(url, { waitUntil: 'load' });
123
- if (adapter.ready) await adapter.ready(app, fixtureName);
129
+ let response;
130
+ try { response = await app.goto(url, { waitUntil: 'load' }); }
131
+ catch (cause) { throw new CliError(browser.isConnected() ? 'NETWORK_FAILED' : 'BROWSER_FAILED', cause.message, { cause }); }
132
+ if ([401,403].includes(response?.status())) throw new CliError('AUTH_REQUIRED', `Fixture navigation was refused with HTTP ${response.status()}.`);
133
+ if (adapter.ready) await adapterCall(adapter, 'ready', app, fixtureName);
124
134
  for (const name of settings.clicks) {
125
135
  let control;
126
136
  for (const role of ['button', 'radio', 'tab', 'checkbox', 'switch', 'menuitem', 'menuitemradio', 'option', 'link']) {
@@ -128,48 +138,85 @@ export async function compare(config, args, options) {
128
138
  if (await candidate.count()) { control = candidate; break; }
129
139
  }
130
140
  if (!control) {
131
- console.error(`adg: No visible control matches --click=${JSON.stringify(name)}`);
132
- return 1;
141
+ throw new CliError('COMPARE_TARGET_NOT_FOUND', `No visible control matches --click=${JSON.stringify(name)}`);
133
142
  }
134
143
  await control.click();
135
144
  }
136
145
  await app.evaluate(() => document.fonts.ready);
137
146
  const capture = settings.page ? { x: origin[0], y: origin[1], width: frameBox.width, height: frameBox.height } : undefined;
138
147
  const panel = capture ? app.locator('html') : settings.selector ? app.locator(settings.selector).first() : app.getByRole('region', { name: settings.region, exact: true }).or(app.getByRole('dialog', { name: settings.region, exact: true })).first();
139
- if (!capture) await panel.scrollIntoViewIfNeeded();
148
+ if (!capture) {
149
+ if (!await panel.count()) throw new CliError('COMPARE_TARGET_NOT_FOUND', 'Frame capture target does not exist.');
150
+ await panel.scrollIntoViewIfNeeded();
151
+ }
140
152
  const { implementation, settled } = await settle(async () => {
141
153
  const result = await panel.evaluate(implementationTexts, capture);
142
154
  if (adapter.texts) {
143
- const additional = await adapter.texts(app), box = result.box;
144
- if (!Array.isArray(additional) || additional.some(t => typeof t.text !== 'string' || !['x', 'y', 'width', 'height'].every(key => Number.isFinite(t[key])))) throw new Error('compare.texts must return text boxes in page coordinates; fix adg.config.mjs');
155
+ const additional = await adapterCall(adapter, 'texts', app), box = result.box;
156
+ if (!Array.isArray(additional) || additional.some(t => typeof t.text !== 'string' || !['x', 'y', 'width', 'height'].every(key => Number.isFinite(t[key])))) throw new CliError('CONFIG_INVALID', 'compare.texts must return text boxes in page coordinates; fix adg.config.mjs');
145
157
  result.texts.push(...additional.filter(t => t.x >= box.x && t.y >= box.y && t.x + t.width <= box.x + box.width && t.y + t.height <= box.y + box.height).map(t => ({ ...t, x: t.x - box.x, y: t.y - box.y })));
146
158
  }
147
159
  return result;
148
- });
160
+ }, clock);
149
161
  const screenshot = { path: path.join(target, 'implementation.png') };
150
162
  if (capture) await app.screenshot({ ...screenshot, clip: capture });
151
163
  else await panel.screenshot(screenshot);
152
164
  const canvasPage = await browser.newPage();
153
165
  await overlay(canvasPage, target);
154
166
  const report = { ...compareReport(relative(config, file), frame, fixtureName, {...design,box:frameBox}, implementation), settled };
155
- if (options.collect) options.collect.push({...report, report: path.relative(path.join(config.output,'compare'),path.join(target,'index.html'))});
156
167
  writeFileSync(path.join(target, 'report.json'), JSON.stringify(report, null, 2) + '\n');
157
168
  writeFileSync(path.join(target, 'index.html'), reportHtml(report));
158
- console.log(`${relative(config, path.join(target, 'index.html'))}: matched ${report.matched}, ${report.offBy2px.length} off by >2px, ${report.missing.length} missing, ${report.extra.length} extra.`);
159
- return report.offBy2px.length || report.missing.length || report.extra.length ? 1 : 0;
169
+ const paths = { design: path.join(target,'design.png'), implementation: path.join(target,'implementation.png'), overlay: path.join(target,'overlay.png'), report: path.join(target,'report.json'), html: path.join(target,'index.html') };
170
+ const {asset, ...measured} = report;
171
+ data.comparisons.push({source:asset, ...measured, theme:fixture.theme, paths});
172
+ data.summary.frames++;
173
+ data.summary.matched += report.matched;
174
+ data.summary.offsets += report.offBy2px.length;
175
+ data.summary.missing += report.missing.length;
176
+ data.summary.extra += report.extra.length;
177
+ if (!data.all) data.indexPath = paths.html;
178
+ log(`${relative(config, paths.html)}: matched ${report.matched}, ${report.offBy2px.length} off by >2px, ${report.missing.length} missing, ${report.extra.length} extra.`);
179
+ return {...report, report:path.relative(path.join(config.output,'compare'),paths.html)};
180
+ } catch (cause) {
181
+ primary = commandFailure(cause, data, [], browser.isConnected() ? 'RENDER_FAILED' : 'BROWSER_FAILED');
182
+ throw primary;
160
183
  } finally {
161
- try { await browser.close(); } finally { if (typeof stop === 'function') await stop(); }
184
+ try { await cleanup(() => browser.close(), primary); }
185
+ catch (cause) { primary = commandFailure(cause, data, []); throw primary; }
186
+ finally { if (typeof stop === 'function') await cleanup(stop, primary); }
162
187
  }
163
188
  }
164
189
 
165
- async function compareAll(config) {
166
- const files = selectSources(config), summary = []; let code = 0;
167
- for (const file of files) {
168
- const built = await buildSource(config,file,{allowLegacy:false});
169
- for (const frame of built.frames.filter(f=>f.fixture)) code = Math.max(code,await compare(config,[file],{frame:frame.name,collect:summary}));
170
- }
171
- const target=path.join(config.output,'compare'); mkdirSync(target,{recursive:true});
172
- writeFileSync(path.join(target,'summary.json'),JSON.stringify(summary,null,2)+'\n');
173
- writeFileSync(path.join(target,'index.html'),`<!doctype html><meta charset="utf-8"><title>Design comparisons</title><table><tr><th>Source</th><th>Frame</th><th>Matched</th><th>Offsets</th><th>Missing</th><th>Extra</th></tr>${summary.map(r=>`<tr><td>${cell(r.asset)}</td><td><a href="${cell(r.report)}">${cell(r.frame)}</a></td><td>${r.matched}</td><td>${r.offBy2px.length}</td><td>${r.missing.length}</td><td>${r.extra.length}</td></tr>`).join('')}</table>`);
174
- return code;
190
+ export async function compare(config, args = [], options = {}, { launchBrowser = launch, clock, log = console.log } = {}) {
191
+ /** @type {import('./results.mjs').CompareData} */
192
+ const data = {project:config.root, complete:false, all:!!options.all, comparisons:[], skipped:[], summary:{frames:0,matched:0,offsets:0,missing:0,extra:0}, indexPath:null, summaryPath:null};
193
+ const warnings = [], reports = [];
194
+ try {
195
+ const files = selectSources(config, args);
196
+ for (const file of files) {
197
+ const built = await buildSource(config,file,{allowLegacy:false});
198
+ const frames = options.all ? built.frames : built.frames.filter(frame => frame.name === options.frame);
199
+ if (!options.all && !frames.length) throw new CliError('FRAME_NOT_FOUND', `Unknown frame ${options.frame}; choose a declared frame`);
200
+ for (const frame of frames) {
201
+ if (options.all && !frame.fixture) {
202
+ data.skipped.push({source:relative(config,file),frame:frame.name,reason:'no_fixture'});
203
+ if (!warnings.length) warnings.push({code:'COMPARE_FRAMES_SKIPPED',message:'Frames without fixtures were skipped.',next:[]});
204
+ continue;
205
+ }
206
+ reports.push(await compareFrame(config,file,frame,options.all ? {frame:frame.name} : options,data,{launchBrowser,clock,log}));
207
+ if (!data.comparisons.at(-1).settled) throw new CliError('COMPARE_UNSETTLED', 'Comparison text boxes did not settle within 5 seconds.', {humanReported:true});
208
+ }
209
+ }
210
+ if (options.all) {
211
+ const target=path.join(config.output,'compare'); mkdirSync(target,{recursive:true});
212
+ writeFileSync(path.join(target,'summary.json'),JSON.stringify(reports,null,2)+'\n');
213
+ data.summaryPath = path.join(target,'summary.json');
214
+ writeFileSync(path.join(target,'index.html'),`<!doctype html><meta charset="utf-8"><title>Design comparisons</title><table><tr><th>Source</th><th>Frame</th><th>Matched</th><th>Offsets</th><th>Missing</th><th>Extra</th></tr>${reports.map(r=>`<tr><td>${cell(r.asset)}</td><td><a href="${cell(r.report)}">${cell(r.frame)}</a></td><td>${r.matched}</td><td>${r.offBy2px.length}</td><td>${r.missing.length}</td><td>${r.extra.length}</td></tr>`).join('')}</table>`);
215
+ data.indexPath = path.join(target,'index.html');
216
+ }
217
+ if (!data.comparisons.length) emptySelection(warnings);
218
+ data.complete = true;
219
+ if (data.summary.offsets || data.summary.missing || data.summary.extra) throw new CliError('COMPARE_FAILED', 'Comparison found text or position differences.', {data,warnings,humanReported:true});
220
+ return {data,warnings};
221
+ } catch (cause) { throw commandFailure(cause,data,warnings); }
175
222
  }