@whzxc/agent-design-gallery 0.14.1 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/README.md +29 -16
  2. package/package.json +2 -1
  3. package/public/access.css +15 -2
  4. package/public/app.js +1284 -521
  5. package/public/arrangement-worker.js +7 -7
  6. package/public/arrangement.js +35 -30
  7. package/public/assets.js +85 -48
  8. package/public/auth.js +59 -4
  9. package/public/boards.js +129 -0
  10. package/public/comment-anchors.js +50 -0
  11. package/public/comments.css +400 -0
  12. package/public/comments.js +1106 -0
  13. package/public/context-menu.js +97 -0
  14. package/public/frame-identity.js +51 -14
  15. package/public/hub.css +25 -3
  16. package/public/hub.html +10 -2
  17. package/public/hub.js +127 -23
  18. package/public/icons.js +9 -0
  19. package/public/index.html +26 -10
  20. package/public/instance-actions.js +9 -2
  21. package/public/layout.js +156 -86
  22. package/public/motion-flow.js +28 -0
  23. package/public/motion-identity.js +100 -0
  24. package/public/motion-paint.js +332 -0
  25. package/public/motion-scene.js +165 -0
  26. package/public/motion-specimens.js +335 -0
  27. package/public/player.css +270 -0
  28. package/public/player.js +753 -0
  29. package/public/recent-updates.js +535 -0
  30. package/public/selection.js +1 -1
  31. package/public/style.css +91 -154
  32. package/public/switcher.css +5 -4
  33. package/public/switcher.js +109 -34
  34. package/public/token-catalog.js +8 -3
  35. package/public/tokens.css +20 -1
  36. package/public/view-boards.css +131 -0
  37. package/public/view-boards.js +350 -0
  38. package/public/view-route.js +1 -2
  39. package/src/boards/board.mjs +30 -0
  40. package/src/boards/motion-board.mjs +202 -0
  41. package/src/boards/token-board.mjs +200 -0
  42. package/src/cli-output.mjs +10 -5
  43. package/src/cli.mjs +89 -35
  44. package/src/comments.mjs +293 -0
  45. package/src/http.mjs +7 -5
  46. package/src/hub/project-link.mjs +41 -0
  47. package/src/hub/registry.mjs +5 -0
  48. package/src/hub.mjs +14 -10
  49. package/src/link.mjs +13 -1
  50. package/src/recent-frames.mjs +295 -0
  51. package/src/recent-history.mjs +100 -0
  52. package/src/recent-job.mjs +63 -0
  53. package/src/recent-worker.mjs +171 -0
  54. package/src/server.mjs +285 -110
  55. package/src/service.mjs +46 -12
  56. package/src/toolkit/arch-git.mjs +8 -14
  57. package/src/toolkit/arch.mjs +3 -2
  58. package/src/toolkit/asset-rules.mjs +24 -1
  59. package/src/toolkit/browser.mjs +1 -13
  60. package/src/toolkit/build-store.mjs +9 -1
  61. package/src/toolkit/build-worker.mjs +6 -0
  62. package/src/toolkit/build.mjs +22 -16
  63. package/src/toolkit/commands.mjs +105 -9
  64. package/src/toolkit/compare.mjs +13 -11
  65. package/src/toolkit/config.mjs +2 -2
  66. package/{public/review.js → src/toolkit/diff-document.mjs} +137 -43
  67. package/src/toolkit/diff-inputs.mjs +97 -52
  68. package/src/toolkit/diff.mjs +198 -43
  69. package/src/toolkit/frame-declarations.mjs +36 -0
  70. package/src/toolkit/git-blobs.mjs +50 -0
  71. package/src/toolkit/impact-inputs.mjs +11 -19
  72. package/src/toolkit/impact-selection.mjs +27 -12
  73. package/src/toolkit/impact.mjs +49 -15
  74. package/src/toolkit/implementation-map.mjs +17 -6
  75. package/src/toolkit/input-generation.mjs +15 -0
  76. package/src/toolkit/inspect-output.mjs +1 -1
  77. package/src/toolkit/inspect.d.ts +9 -1
  78. package/src/toolkit/inspect.mjs +25 -1
  79. package/src/toolkit/motion-check.mjs +382 -0
  80. package/src/toolkit/motion-css.mjs +105 -0
  81. package/src/toolkit/motion-flows.mjs +95 -0
  82. package/src/toolkit/motion-impact.mjs +87 -0
  83. package/src/toolkit/motion-inventory.mjs +202 -0
  84. package/src/toolkit/motion-label.mjs +111 -0
  85. package/src/toolkit/motion-patterns.mjs +216 -0
  86. package/src/toolkit/motion-primitives.mjs +94 -0
  87. package/src/toolkit/motion-queries.mjs +169 -0
  88. package/src/toolkit/motion.mjs +300 -0
  89. package/src/toolkit/move-pairing.mjs +140 -0
  90. package/src/toolkit/owner.mjs +19 -6
  91. package/src/toolkit/play-endpoint.mjs +66 -0
  92. package/src/toolkit/project-index.mjs +4 -4
  93. package/src/toolkit/recent-structure.mjs +201 -0
  94. package/src/toolkit/results.mjs +3 -3
  95. package/src/toolkit/review-document.mjs +440 -0
  96. package/src/toolkit/review-embed-document.mjs +671 -0
  97. package/src/toolkit/review-filmstrip.mjs +76 -0
  98. package/src/toolkit/review-groups.mjs +29 -0
  99. package/src/toolkit/review-motion-card.mjs +51 -0
  100. package/src/toolkit/review-motion.mjs +159 -0
  101. package/src/toolkit/review-observation.mjs +131 -0
  102. package/src/toolkit/review-playback.js +123 -0
  103. package/src/toolkit/review-sheet.mjs +125 -0
  104. package/src/toolkit/review-specimens.mjs +60 -0
  105. package/src/toolkit/review.mjs +240 -0
  106. package/src/toolkit/runtime.mjs +8 -2
  107. package/src/toolkit/theme.mjs +16 -0
  108. package/src/viewer-cache.mjs +48 -12
  109. package/public/annotations.js +0 -816
  110. package/public/labels.js +0 -122
  111. package/src/annotations.mjs +0 -238
@@ -1,21 +1,61 @@
1
1
  import path from 'node:path';
2
+ import { createHash } from 'node:crypto';
2
3
  import { readFileSync } from 'node:fs';
3
4
  import { mkdir, rm, writeFile } from 'node:fs/promises';
4
5
  import { availableParallelism } from 'node:os';
5
6
  import { launch, loadFrame, browserTask, readyResources } from './browser.mjs';
6
7
  import { prepareDiffInputs } from './diff-inputs.mjs';
8
+ import { pairFrameMoves } from './move-pairing.mjs';
7
9
  import { currentHead } from './arch-git.mjs';
10
+ import { relative, sourceDirectories, sourceFeature } from './project.mjs';
8
11
  import { pixelComparator, imageDifference } from './pixel-diff.mjs';
9
12
  import { partContext, captureEvidence, capturePart, isolateParent, frameIdentity, comparisonIdentity } from './part-diff.mjs';
10
13
  import { commandFailure, cleanup, emptySelection } from './results.mjs';
11
14
  import { CliError, classifyError, asCliError, nextActions } from '../cli-output.mjs';
12
15
  import { withImpacted } from './impact-selection.mjs';
13
16
  import { resolveDiffPolicy } from './diff-policy.mjs';
14
- import { buildReview, reviewDocumentHtml } from '../../public/review.js';
17
+ import { buildReview, reviewDocumentHtml } from './diff-document.mjs';
18
+ import { resolveThemes, systemTheme } from './theme.mjs';
19
+ import { renderReviewSheet } from './review-sheet.mjs';
15
20
 
16
21
  const metadata = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8'));
17
22
  const safeName = name => encodeURIComponent(name).replace(/\./g, '%2E');
18
23
  const classNames = ['imperceptible', 'antialiasing', 'boundary_bleed', 'bitmap_resampling', 'other'];
24
+ const allThemes = ['light', 'dark'];
25
+
26
+ /** Git owns direct changes; impact reasons own inherited cause sets when available. */
27
+ export function reviewChange(row, inputs, built, selection = null) {
28
+ const changed = new Set((inputs.changes ?? []).flatMap(change => [change.before, change.after]).filter(Boolean));
29
+ const sides = [inputs.before, inputs.after ?? inputs.before];
30
+ const own = [...changed].filter(name => sides.some(({ config }) => {
31
+ const design = path.relative(config.root, config.design).split(path.sep).join('/');
32
+ const relativeSource = path.posix.relative(design, row.source);
33
+ const feature = sourceFeature(relativeSource, sourceDirectories(config));
34
+ return name === row.source || feature !== relativeSource && name.startsWith(path.posix.join(design, feature) + '/');
35
+ }));
36
+ if (own.length) return { kind: 'direct', causes: own.sort() };
37
+ const causes = new Set();
38
+ if (selection) {
39
+ const facts = new Map(selection.facts.map(fact => [fact.id, fact]));
40
+ for (const group of selection.frames) {
41
+ if (group.source !== row.source || !group.frames.includes(row.frame)) continue;
42
+ for (const entry of group.rows) for (const reason of entry.reasons ?? []) {
43
+ const source = facts.get(reason.fact)?.source;
44
+ if (source && reason.scope !== 'support') causes.add(source);
45
+ }
46
+ }
47
+ } else {
48
+ for (const [index, side] of sides.entries()) {
49
+ const source = [built.before, built.after][index]?.get(row.source);
50
+ for (const dependency of source?.dependencies ?? []) {
51
+ const name = path.relative(side.config.root, dependency).split(path.sep).join('/');
52
+ if (changed.has(name)) causes.add(name);
53
+ }
54
+ }
55
+ for (const name of inputs.globalChanges ?? []) causes.add(name);
56
+ }
57
+ return { kind: 'inherited', causes: [...causes].sort() };
58
+ }
19
59
 
20
60
  function frameFailure(error, row, theme) {
21
61
  const failure = asCliError(error, 'RENDER_FAILED');
@@ -23,13 +63,18 @@ function frameFailure(error, row, theme) {
23
63
  return failure;
24
64
  }
25
65
 
26
- async function capturePair(browser, row, theme, scale, context) {
66
+ async function capturePair(browser, row, theme, scale, context, cachedTheme) {
27
67
  const captures = { before: null, after: null };
28
68
  let page;
29
69
  try {
30
70
  for (const side of ['before', 'after']) {
31
71
  if (!row[side]) continue;
32
72
  page ??= await browserTask(browser, () => browser.newPage({ deviceScaleFactor: scale, locale: 'en-US', timezoneId: 'UTC' }));
73
+ if (!context?.targets.has(frameIdentity(row)) && cachedTheme?.has(row[side])) {
74
+ captures[side] = cachedTheme.get(row[side]);
75
+ cachedTheme.delete(row[side]);
76
+ continue;
77
+ }
33
78
  await loadFrame(page, row[side], theme);
34
79
  captures[side] = await browserTask(browser, async () => {
35
80
  await page.evaluate(readyResources);
@@ -52,6 +97,36 @@ async function capturePair(browser, row, theme, scale, context) {
52
97
  }
53
98
  }
54
99
 
100
+ // Normalize decoded screenshot pixels before hashing so PNG encoding does not affect matching.
101
+ async function renderFingerprints(browser, candidates, theme, scale, cachedTheme, concurrency) {
102
+ const fingerprints = new Map();
103
+ for (let start = 0; start < candidates.length; start += concurrency) {
104
+ const results = await Promise.allSettled(candidates.slice(start, start + concurrency).map(async row => {
105
+ const pair = await capturePair(browser, row, theme, scale, null);
106
+ const frame = row.before ?? row.after, capture = pair.before ?? pair.after;
107
+ let failure;
108
+ try {
109
+ const pixels = await browserTask(browser, () => pair.page.evaluate(async base64 => {
110
+ const image = new Image();
111
+ image.src = 'data:image/png;base64,' + base64;
112
+ await image.decode();
113
+ const canvas = document.createElement('canvas');
114
+ canvas.width = image.naturalWidth;
115
+ canvas.height = image.naturalHeight;
116
+ canvas.getContext('2d', { colorSpace: 'srgb' }).drawImage(image, 0, 0);
117
+ return canvas.toDataURL('image/png');
118
+ }, capture.png.toString('base64')));
119
+ cachedTheme.set(frame, capture);
120
+ fingerprints.set(row, createHash('sha256').update(JSON.stringify(capture.size)).update(pixels).digest('hex'));
121
+ } catch (error) { failure = frameFailure(error, row, theme); throw failure; }
122
+ finally { await cleanup(() => pair.page.close(), failure); }
123
+ }));
124
+ const failed = results.find(result => result.status === 'rejected');
125
+ if (failed) throw failed.reason;
126
+ }
127
+ return fingerprints;
128
+ }
129
+
55
130
  async function comparePair(browser, pair, thresholds, context) {
56
131
  try {
57
132
  return await browserTask(browser, async () => {
@@ -79,11 +154,18 @@ async function comparePair(browser, pair, thresholds, context) {
79
154
  } catch (error) { throw frameFailure(error, pair.row, pair.theme); }
80
155
  }
81
156
 
82
- async function writePair(output, pair, thresholds, reviewImages) {
157
+ function revisionReasons(pair) {
158
+ const before = pair.before?.size, after = pair.after?.size;
159
+ const reasons = [];
160
+ if (before && after && Object.keys(before).some(key => before[key] !== after[key])) reasons.push('size_changed');
161
+ if (!pair.parent && pair.pixels.differentPixels) reasons.push('pixels_changed');
162
+ return reasons;
163
+ }
164
+
165
+ async function writePair(output, pair, thresholds, reviewImages, reviewFormat) {
83
166
  const { row, theme } = pair;
84
- const directory = path.join(output, row.support ? 'support' : 'frames', ...row.source.split('/').map(safeName), safeName(row.frame), theme);
85
- await mkdir(directory, { recursive: true });
86
- const paths = {
167
+ const directory = output && path.join(output, row.support ? 'support' : 'frames', ...row.source.split('/').map(safeName), safeName(row.frame), theme);
168
+ const paths = directory ? {
87
169
  before: pair.before ? path.join(directory, 'before.png') : null,
88
170
  after: pair.after ? path.join(directory, 'after.png') : null,
89
171
  difference: path.join(directory, 'difference.png'),
@@ -92,24 +174,27 @@ async function writePair(output, pair, thresholds, reviewImages) {
92
174
  parentCurrentSnapshot: pair.snapshots ? path.join(directory, 'parent-current.snapshot.json') : null,
93
175
  report: path.join(directory, 'comparison.json'), parentIsolated: pair.isolated ? path.join(directory, 'parent-isolated.png') : null,
94
176
  bleedMask: pair.bleedMask ? path.join(directory, 'bleed-mask.png') : null,
95
- };
177
+ } : null;
96
178
  const beforeSize = pair.before?.size ?? null, afterSize = pair.after?.size ?? null;
97
179
  const reasons = [];
98
- if (!pair.parent && row.status !== 'matched') reasons.push(row.status);
180
+ if (!pair.parent && row.status !== 'matched' && row.status !== 'moved') reasons.push(row.status);
99
181
  if (row.matchKind === 'renamed_or_unknown') reasons.push('renamed_or_unknown');
100
- if (beforeSize && afterSize && Object.keys(beforeSize).some(key => beforeSize[key] !== afterSize[key])) reasons.push('size_changed');
182
+ reasons.push(...revisionReasons(pair));
101
183
  if (pair.parent) {
102
184
  if (pair.snapshots.findings.length) reasons.push('snapshot_mismatch');
103
185
  if (pair.parentChanged) reasons.push('parent_changed');
104
186
  if (pair.singleTheme) reasons.push('theme_coverage_incomplete');
105
187
  if (pair.pixels.classes.other.pixels) reasons.push('other_pixels');
106
188
  if (!pair.pixels.classes.antialiasing.withinThreshold || !pair.pixels.classes.bitmap_resampling.withinThreshold) reasons.push('threshold_exceeded');
107
- } else if (pair.pixels.differentPixels) reasons.push('pixels_changed');
189
+ }
108
190
  const ref = { source: row.source, frame: row.frame };
191
+ const beforeRef = row.previousSource ? { source: row.previousSource, frame: row.previousFrame } : ref;
109
192
  const comparison = {
110
193
  id: JSON.stringify([row.source, row.frame, theme, ...(row.support ? ['support'] : [])]), ...ref, theme,
111
- status: row.status, matchKind: row.matchKind, matchCandidates: row.matchCandidates,
112
- relation: pair.parent ? 'parent_crop' : 'revision', before: pair.parent?.ref ?? (pair.before ? ref : null), after: pair.after ? ref : null,
194
+ status: row.status, matchKind: row.matchKind, matchCandidates: row.matchCandidates, change: row.change,
195
+ ...(row.previousSource ? { previousSource: row.previousSource } : {}),
196
+ relation: pair.parent ? 'parent_crop' : 'revision',
197
+ before: pair.parent?.ref ?? (pair.before ? beforeRef : null), after: pair.after ? ref : null,
113
198
  beforeSize, afterSize, parent: pair.parent ?? null, snapshots: pair.snapshots ?? null, pixels: pair.pixels,
114
199
  verdict: reasons.length ? 'changed' : pair.parent ? 'structural' : 'identical', reasons,
115
200
  note: { before: row.before?.note ?? null, after: row.after?.note ?? null },
@@ -117,13 +202,20 @@ async function writePair(output, pair, thresholds, reviewImages) {
117
202
  metadata: { before: row.before ? { locale: row.before.locale ?? null, proposed: row.before.proposed ?? null, fixture: row.before.fixture ?? null, capture: row.before.capture ?? null } : null,
118
203
  after: row.after ? { locale: row.after.locale ?? null, proposed: row.after.proposed ?? null, fixture: row.after.fixture ?? null, capture: row.after.capture ?? null } : null }, paths,
119
204
  };
120
- if (!row.support) {
205
+ const pngSummary = reviewFormat === 'png';
206
+ const omitDifference = pngSummary || reviewFormat === 'embed';
207
+ const shownInSummary = row.status === 'added' ||
208
+ (row.status !== 'removed' && (row.previousSource || comparison.verdict === 'changed'));
209
+ const embedCaptures = output || pngSummary;
210
+ if (reviewFormat !== 'rows' && !row.support && row.status !== 'moved' && (!pngSummary || shownInSummary)) {
121
211
  reviewImages.set(comparison.id, {
122
- before: pair.before ? `data:image/png;base64,${pair.before.png.toString('base64')}` : null,
123
- after: pair.after ? `data:image/png;base64,${pair.after.png.toString('base64')}` : null,
124
- difference: `data:image/png;base64,${pair.difference.toString('base64')}`,
212
+ before: embedCaptures && pair.before ? `data:image/png;base64,${pair.before.png.toString('base64')}` : null,
213
+ after: embedCaptures && pair.after ? `data:image/png;base64,${pair.after.png.toString('base64')}` : null,
214
+ difference: omitDifference ? null : `data:image/png;base64,${pair.difference.toString('base64')}`,
125
215
  });
126
216
  }
217
+ if (!directory) return comparison;
218
+ await mkdir(directory, { recursive: true });
127
219
  await Promise.all([
128
220
  pair.before && writeFile(paths.before, pair.before.png),
129
221
  pair.after && writeFile(paths.after, pair.after.png),
@@ -137,17 +229,24 @@ async function writePair(output, pair, thresholds, reviewImages) {
137
229
  }
138
230
 
139
231
  /** Exact ordinary frames and evidence-backed structural part comparisons. */
140
- export async function diff(config, args = [], options = {}, { launchBrowser = launch, prepareInputs = prepareDiffInputs, log = console.log, clock, session, onReview } = {}) {
141
- if (options.impacted && !session) return withImpacted(config, args, options, 'diff', selected =>
142
- diff(config, args, options, { launchBrowser, prepareInputs, log, clock, session: selected, onReview }));
143
- const started = performance.now(), scale = Number(options.scale ?? 2), themeOption = options.theme ?? 'both';
232
+ export async function diff(config, args = [], options = {}, { launchBrowser = launch, prepareInputs = prepareDiffInputs, log = console.log, clock, session, onReview, readSystemTheme = systemTheme, renderSheet = renderReviewSheet, sheetTheme, reviewFormat } = {}) {
233
+ const started = performance.now(), scale = Number(options.scale ?? 2);
144
234
  if (!Number.isFinite(scale) || scale <= 0) throw new CliError('USAGE_INVALID', 'Invalid --scale; use a positive number.');
145
- if (!['both', 'light', 'dark'].includes(themeOption)) throw new CliError('USAGE_INVALID', 'Choose --theme=both, light, or dark.');
235
+ const themes = resolveThemes(options.theme, readSystemTheme);
236
+ sheetTheme ??= themes.length === 1 ? themes[0] : readSystemTheme();
237
+ options = { ...options, theme: themes.length === 2 ? 'both' : themes[0] };
146
238
  if (options['out-dir'] === '') throw new CliError('USAGE_INVALID', 'Set --out-dir to a directory.');
147
- const themes = themeOption === 'both' ? ['light', 'dark'] : [themeOption];
148
- const output = options['out-dir'] === undefined ? path.join(config.output, 'diff') : path.resolve(config.root, options['out-dir']);
239
+ if (options.impacted && !session) {
240
+ return withImpacted(config, args, options, 'diff', selected =>
241
+ diff(config, args, options, { launchBrowser, prepareInputs, log, clock, session: selected,
242
+ readSystemTheme, renderSheet, sheetTheme, onReview, reviewFormat }));
243
+ }
244
+ const output = reviewFormat ? null : path.resolve(config.root, options['out-dir'] ?? path.join(config.output, 'diff'));
149
245
  const timings = { prepareMs: 0, buildMs: 0, captureMs: 0, compareMs: 0, writeMs: 0, totalMs: 0 };
150
246
  const warnings = [], completed = [], reviewImages = new Map();
247
+ const hiddenMoveReasons = new Set(), pendingMoveComparisons = new Map();
248
+ const cachedCaptures = new Map(allThemes.map(theme => [theme, new Map()]));
249
+ const concurrency = Math.min(4, availableParallelism());
151
250
  const thresholds = config.diff?.thresholds ?? resolveDiffPolicy().thresholds;
152
251
  let inputs, browser, data, primary, context;
153
252
  const timed = async (name, work) => {
@@ -158,43 +257,58 @@ export async function diff(config, args = [], options = {}, { launchBrowser = la
158
257
  try {
159
258
  const head = await timed('prepareMs', async () => {
160
259
  inputs = session ? session.diffInputs : await prepareInputs(config, args, options);
161
- return currentHead(inputs.base);
260
+ return inputs.after?.revision?.sha ?? currentHead(inputs.base);
162
261
  });
163
262
  warnings.push(...inputs.warnings);
164
263
  data = {
165
264
  project: config.root, outputDirectory: output, complete: false,
166
- base: { rev: inputs.base.rev, sha: inputs.base.sha }, current: { kind: 'working_tree', head },
265
+ base: { rev: inputs.base.rev, sha: inputs.base.sha }, current: { kind: inputs.after?.revision ? 'revision' : 'working_tree', head },
167
266
  selection: { sources: inputs.sources, frame: options.frame ?? null, themes, scale,
168
267
  existingCoverage: !inputs.sources.length ? 'empty' : args.length || options.frame !== undefined || themes.length !== 2 ? 'partial' : 'full' },
169
268
  environment: { adg: metadata.version, node: process.version, platform: process.platform, arch: process.arch, chromium: null,
170
269
  ...metadata.dependencies, locale: 'en-US', timezone: 'UTC', ...inputs.environment, baseThresholds: inputs.before.config.diff.thresholds },
171
- impact: session?.selection ?? null, classifierVersion: 1, thresholds, comparisons: [], support: [], verdict: null, reasons: [],
270
+ impact: session?.selection ?? null, classifierVersion: 1, thresholds, comparisons: [], support: [], failures: [], verdict: null, reasons: [],
172
271
  summary: { sources: inputs.sources.length, frames: 0, comparisons: 0, supportComparisons: 0, isolationCaptures: 0,
173
- added: 0, removed: 0, matched: 0, identical: 0, structural: 0, changed: 0,
272
+ added: 0, removed: 0, moved: 0, matched: 0, identical: 0, structural: 0, changed: 0,
174
273
  classPixels: Object.fromEntries(classNames.map(name => [name, 0])) },
175
- review: { added: 0, removed: 0, changed: 0 },
274
+ review: { added: 0, removed: 0, moved: 0, changed: 0, direct: 0, inherited: 0, groups: [], movePairs: [], sheet: null },
176
275
  differencePalette: { equal: '#00000000', imperceptible: '#64748b', antialiasing: '#f59e0b', boundary_bleed: '#0ea5e9', bitmap_resampling: '#a855f7', other: '#ff00ff' }, reportPath: null, indexPath: null, timings,
177
276
  };
178
- await timed('writeMs', () => Promise.all(['frames', 'support', 'report.json', 'index.html'].map(entry =>
277
+ if (output) await timed('writeMs', () => Promise.all(['frames', 'support', 'report.json', 'index.html', 'review-sheet.png'].map(entry =>
179
278
  rm(path.join(output, entry), { recursive: true, force: true }))));
180
279
  if (session ? session.chosen.some(row => row.source.endsWith('.mmd') && session.themes.some(theme => session.scheduled(row, theme))) : inputs.sources.length) browser = await launchBrowser();
181
- const built = await timed('buildMs', () => inputs.buildFrames({ browser }));
280
+ const built = await timed('buildMs', () => inputs.buildFrames({ browser, deferParts: true }));
281
+ data.failures = built.failures ?? [];
182
282
  if (session) built.frames = built.frames.filter(row => themes.some(theme => session.scheduled(row, theme)));
283
+ const moveThemes = [...new Set([...themes, ...allThemes])];
284
+ built.frames = await pairFrameMoves(built.frames, inputs, async (candidates, theme) => {
285
+ browser ??= await launchBrowser();
286
+ return timed('captureMs', () => renderFingerprints(browser, candidates, theme, scale, cachedCaptures.get(theme), concurrency));
287
+ }, moveThemes);
288
+ if (themes.length === 1) {
289
+ const offThemeCaptures = cachedCaptures.get(moveThemes[1]);
290
+ const pairedFrames = new Set(built.frames.filter(row => row.previousSource).flatMap(row => [row.before, row.after]));
291
+ for (const frame of offThemeCaptures.keys()) if (!pairedFrames.has(frame)) offThemeCaptures.delete(frame);
292
+ }
293
+ if (built.prepareParts) await timed('buildMs', built.prepareParts);
294
+ for (const row of [...built.frames, ...built.support]) row.change ??= reviewChange(row, inputs, built, session?.selection);
183
295
  context = partContext(built, inputs, scale, themes, clock);
184
296
  for (const warning of inputs.warnings) if (!warnings.includes(warning)) warnings.push(warning);
185
297
  data.summary.frames = built.frames.length;
186
298
  for (const row of built.frames) data.summary[row.status]++;
187
- if (!built.frames.length && (!session || !session.selection.coverage.expectedRows)) emptySelection(warnings);
299
+ if (!built.frames.length && !data.failures.length && (!session || !session.selection.coverage.expectedRows)) emptySelection(warnings);
188
300
  else if (built.frames.length) browser ??= await launchBrowser();
189
301
  if (browser) data.environment.chromium = browser.version();
190
302
  const selectedOrder = new Map(built.frames.flatMap(row => themes.map(theme => comparisonIdentity(row, theme))).map((key, index) => [key, index]));
191
303
  const supportKeys = new Set(built.support.map(frameIdentity));
192
304
  const ordinary = [...built.frames.filter(row => !row.parentRow), ...built.support.map(row => ({ ...row, support: true }))];
193
- const ordinaryJobs = ordinary.flatMap(row => themes.filter(theme => !session || row.support || session.scheduled(row, theme)).map(theme => ({ row, theme })));
305
+ const ordinaryJobs = ordinary.flatMap(row => (row.previousSource ? moveThemes :
306
+ themes.filter(theme => !session || row.support || session.scheduled(row, theme))).map(theme => ({ row, theme })));
194
307
  const partJobs = built.frames.filter(row => row.parentRow).flatMap(row => themes.filter(theme => !session || session.scheduled(row, theme)).map(theme => ({ row, theme })));
195
- const concurrency = Math.min(4, availableParallelism());
308
+ let comparedJobs = 0;
196
309
  for (const jobs of [ordinaryJobs, partJobs]) for (let start = 0; start < jobs.length; start += concurrency) {
197
310
  const failures = [], openPairs = [];
311
+ const changes = [];
198
312
  const phase = async (name, items, work) => {
199
313
  const settled = await timed(name, () => Promise.allSettled(items.map(work)));
200
314
  return settled.flatMap((result, index) => {
@@ -207,13 +321,34 @@ export async function diff(config, args = [], options = {}, { launchBrowser = la
207
321
  const batch = jobs.slice(start, start + concurrency);
208
322
  openPairs.push(...await phase('captureMs', batch, job => job.row.parentRow
209
323
  ? browserTask(browser, () => capturePart(browser, job.row, job.theme, context)).catch(error => { throw frameFailure(error, job.row, job.theme); })
210
- : capturePair(browser, job.row, job.theme, scale, context)));
324
+ : capturePair(browser, job.row, job.theme, scale, context, cachedCaptures.get(job.theme))));
211
325
  const compared = await phase('compareMs', openPairs, pair => comparePair(browser, pair, thresholds, context));
212
- const rows = await phase('writeMs', compared, pair => writePair(output, pair, thresholds, reviewImages));
326
+ const selected = compared.flatMap(pair => {
327
+ const { row } = pair;
328
+ if (!row.previousSource) return [pair];
329
+ const pairs = pendingMoveComparisons.get(row) ?? [];
330
+ pairs.push(pair);
331
+ if (pairs.length < allThemes.length) { pendingMoveComparisons.set(row, pairs); return []; }
332
+ pendingMoveComparisons.delete(row);
333
+ if (pairs.every(item => revisionReasons(item).length === 0)) {
334
+ row.status = 'moved';
335
+ data.summary.matched--;
336
+ data.summary.moved++;
337
+ }
338
+ for (const item of pairs) if (!themes.includes(item.theme)) {
339
+ for (const reason of revisionReasons(item)) hiddenMoveReasons.add(reason);
340
+ }
341
+ return pairs.filter(item => themes.includes(item.theme));
342
+ });
343
+ const rows = await phase('writeMs', selected, pair => writePair(output, pair, thresholds, reviewImages, reviewFormat));
213
344
  for (const row of rows) {
214
345
  context?.comparisons.set(comparisonIdentity(row, row.theme), row);
215
346
  if (supportKeys.has(frameIdentity(row))) { data.support.push(row); data.summary.supportComparisons++; }
216
347
  else {
348
+ if (options.onProgress && (row.status !== 'matched' || row.verdict==='changed')) {
349
+ changes.push({source:row.source,frame:row.frame,status:row.status==='matched'?'changed':row.status,
350
+ ...(row.previousSource ? {former:row.before} : {})});
351
+ }
217
352
  completed.push(row); data.summary.comparisons++; data.summary[row.verdict]++;
218
353
  for (const name of classNames) data.summary.classPixels[name] += row.pixels.classes[name].pixels;
219
354
  }
@@ -224,6 +359,8 @@ export async function diff(config, args = [], options = {}, { launchBrowser = la
224
359
  catch (error) { failures.push({ index: jobs.length, error }); }
225
360
  }
226
361
  }
362
+ comparedJobs += Math.min(concurrency,jobs.length-start);
363
+ options.onProgress?.({phase:'Comparing frame images',completed:comparedJobs,total:ordinaryJobs.length+partJobs.length,changes});
227
364
  data.comparisons = completed;
228
365
  completed.sort((a, b) => selectedOrder.get(comparisonIdentity(a, a.theme)) - selectedOrder.get(comparisonIdentity(b, b.theme)));
229
366
  data.summary.isolationCaptures = context?.isolation.size ?? 0;
@@ -233,6 +370,13 @@ export async function diff(config, args = [], options = {}, { launchBrowser = la
233
370
  throw failures[0].error;
234
371
  }
235
372
  }
373
+ if (output && options.impacted) await timed('writeMs', async () => {
374
+ await mkdir(output, { recursive: true });
375
+ browser ??= await launchBrowser();
376
+ const model = buildReview({ ...data, complete: !data.failures.length }, reviewImages, { label: config.name ?? path.basename(config.root) });
377
+ const designDirs = { before: relative(inputs.before.config, inputs.before.config.design), after: relative(config, config.design) };
378
+ data.review.sheet = await renderSheet(browser, model, sheetTheme, path.join(output, 'review-sheet.png'), completed, designDirs);
379
+ });
236
380
  } catch (error) {
237
381
  if (inputs) {
238
382
  if (error.message) error.message = inputs.translateDiagnostic(error.message);
@@ -247,10 +391,13 @@ export async function diff(config, args = [], options = {}, { launchBrowser = la
247
391
  }
248
392
  }
249
393
  if (!data) throw primary;
394
+ let sourceFailureOnly = !primary && data.failures.length > 0;
395
+ if (sourceFailureOnly) primary = commandFailure(new CliError('SOURCE_BUILD_FAILED',
396
+ `${new Set(data.failures.map(failure => failure.source)).size} source(s) could not be compared; review the source failures.`, { data }), data, warnings);
250
397
  data.complete = !primary;
251
398
  if (!primary) {
252
- data.verdict = data.summary.changed || data.support.some(row => row.verdict === 'changed') ? 'changed' : data.summary.structural ? 'structural' : 'identical';
253
- data.reasons = [...new Set([...completed, ...data.support].flatMap(row => row.reasons))];
399
+ data.verdict = data.summary.changed || hiddenMoveReasons.size || data.support.some(row => row.verdict === 'changed') ? 'changed' : data.summary.structural ? 'structural' : 'identical';
400
+ data.reasons = [...new Set([...completed, ...data.support].flatMap(row => row.reasons).concat([...hiddenMoveReasons]))];
254
401
  if (data.summary.structural && data.selection.existingCoverage !== 'full') {
255
402
  data.verdict = 'changed'; data.reasons.push('existing_coverage_incomplete');
256
403
  }
@@ -260,22 +407,30 @@ export async function diff(config, args = [], options = {}, { launchBrowser = la
260
407
  }
261
408
  }
262
409
  const reviewModel = buildReview(data, reviewImages, { label: config.name ?? path.basename(config.root) });
263
- data.review = reviewModel.counts;
410
+ data.review = { ...reviewModel.counts, movePairs: reviewModel.movePairs ?? [], groups: (reviewModel.groups ?? []).map(group => ({
411
+ causes: group.causes, frames: group.frames.map(({ source, frame }) => ({ source, frame })),
412
+ representative: { source: group.representative.source, frame: group.representative.frame },
413
+ outliers: group.outliers.map(({ source, frame }) => ({ source, frame })), medianArea: group.medianArea,
414
+ })), sheet: data.review.sheet };
264
415
  onReview?.(reviewModel);
265
416
  timings.totalMs = performance.now() - started;
266
- data.reportPath = path.join(output, 'report.json');
267
- data.indexPath = path.join(output, 'index.html');
268
- try {
417
+ if (output) try {
418
+ data.reportPath = path.join(output, 'report.json');
419
+ data.indexPath = path.join(output, 'index.html');
269
420
  await mkdir(output, { recursive: true });
270
421
  await writeFile(data.indexPath, reviewDocumentHtml(reviewModel));
271
422
  if (!session) await writeFile(data.reportPath, JSON.stringify(data, null, 2) + '\n');
272
423
  } catch (error) {
424
+ sourceFailureOnly = false;
273
425
  data.reportPath = null; data.indexPath = null; data.complete = false; data.verdict = null;
274
426
  if (primary) primary.warnings.push(classifyError(error).error);
275
427
  else primary = commandFailure(error, data, warnings);
276
428
  }
277
- if (primary) throw primary;
278
- if (!options.json) log(`${data.verdict}: ${data.review.added} added, ${data.review.removed} removed, ${data.review.changed} changed (${data.summary.frames} frames). ${data.indexPath}`);
429
+ if (primary) {
430
+ if (sourceFailureOnly) primary.partialSourceFailures = true;
431
+ throw primary;
432
+ }
433
+ if (!options.json) log(`${data.verdict}: ${data.review.added} added, ${data.review.removed} removed, ${data.review.moved} moved, ${data.review.changed} changed (${data.summary.frames} frames). ${data.indexPath}`);
279
434
  if (data.verdict === 'changed') throw new CliError('DIFF_FAILED', 'Design differences require review.', { data, warnings });
280
435
  return { data, warnings };
281
436
  }
@@ -0,0 +1,36 @@
1
+ import { parse } from '@babel/parser';
2
+
3
+ // Join the actual Frame invocation (including mapped/generated names) and emitted
4
+ // part identities to declaration text. Offsets or line numbers alone are not edits.
5
+ export function declarations(text) {
6
+ const { program } = parse(text, { sourceType: 'module', plugins: ['jsx', 'typescript', 'decorators-legacy'] });
7
+ const sites = new Map(),
8
+ bindings = new Map(),
9
+ exports = new Map();
10
+ function visit(node) {
11
+ if (!node || typeof node !== 'object') return;
12
+ if (node.type === 'JSXElement') {
13
+ sites.set(node.loc.start.line + ':' + (node.loc.start.column + 1), text.slice(node.start, node.end));
14
+ }
15
+ for (const [key, child] of Object.entries(node)) {
16
+ if (key === 'loc') continue;
17
+ if (Array.isArray(child)) child.forEach(visit);
18
+ else if (child?.type) visit(child);
19
+ }
20
+ }
21
+ for (const statement of program.body) {
22
+ const node = statement.declaration ?? statement;
23
+ const definitions = node.type === 'VariableDeclaration' ? node.declarations : [node];
24
+ for (const def of definitions) {
25
+ if (def.id?.name) bindings.set(def.id.name, text.slice(def.start, def.end));
26
+ }
27
+ for (const spec of statement.specifiers ?? []) {
28
+ if (spec.exported && spec.local) exports.set(spec.exported.name, spec.local.name);
29
+ }
30
+ visit(node);
31
+ }
32
+ return {
33
+ site: (origin) => sites.get(origin.line + ':' + origin.column),
34
+ part: (name) => bindings.get(exports.get(name) ?? name)
35
+ };
36
+ }
@@ -0,0 +1,50 @@
1
+ import { spawn } from 'node:child_process';
2
+
3
+ // A single cat-file process serves the blobs actually requested by esbuild.
4
+ export function gitBlobs(repository) {
5
+ const child = spawn('git', ['-C', repository, 'cat-file', '--batch'], { stdio: ['pipe', 'pipe', 'ignore'] });
6
+ const chunks = child.stdout[Symbol.asyncIterator]();
7
+ const done = new Promise(resolve => child.once('close', resolve));
8
+ let buffer = Buffer.alloc(0), queue = Promise.resolve(), failure;
9
+ child.on('error', error => { failure = error; });
10
+ child.stdin.on('error', error => { failure = error; });
11
+ async function fill() {
12
+ const next = await chunks.next();
13
+ if (next.done) throw failure ?? Error('Git blob stream ended early.');
14
+ buffer = buffer.length ? Buffer.concat([buffer, next.value]) : next.value;
15
+ }
16
+ async function read(oid) {
17
+ if (failure) throw failure;
18
+ child.stdin.write(oid + '\n');
19
+ let end;
20
+ while ((end = buffer.indexOf(10)) < 0) await fill();
21
+ const header = buffer.toString('ascii', 0, end);
22
+ const size = Number(header.split(' ')[2]);
23
+ if (!Number.isSafeInteger(size)) throw Error('Git blob is absent: ' + oid);
24
+ buffer = buffer.subarray(end + 1);
25
+ const bytes = Buffer.allocUnsafe(size);
26
+ let position = 0;
27
+ while (position < size) {
28
+ if (!buffer.length) await fill();
29
+ const take = Math.min(buffer.length, size - position);
30
+ buffer.copy(bytes, position, 0, take);
31
+ position += take;
32
+ buffer = buffer.subarray(take);
33
+ }
34
+ if (!buffer.length) await fill();
35
+ buffer = buffer.subarray(1);
36
+ return bytes;
37
+ }
38
+ return {
39
+ read(oid) {
40
+ const result = queue.then(() => read(oid));
41
+ queue = result.catch(error => { failure = error; });
42
+ return result;
43
+ },
44
+ async close() {
45
+ await queue;
46
+ child.stdin.end();
47
+ await done;
48
+ }
49
+ };
50
+ }
@@ -12,41 +12,33 @@ export { configInputFiles } from './input-generation.mjs';
12
12
 
13
13
  /** Reuse diff's historical config, dependency environment and disposable-tree lifecycle. */
14
14
  export async function prepareImpactInputs(config, values) {
15
- const sessions = [];
15
+ const base = await prepareDiffInputs(config, [], values);
16
16
  try {
17
- const base = await prepareDiffInputs(config, [], { base: values.base }); sessions.push(base);
18
- let head;
19
- if (values.head !== undefined) { head = await prepareDiffInputs(config, [], { base: values.head }); sessions.push(head); }
20
- const before = base.before, after = head ? head.before : base.after;
17
+ const { before, after } = base;
18
+ const head = after.revision;
21
19
  const projectPrefix = slash(path.relative(base.base.root, await realpath(config.root)));
22
20
  const outputs = [before, after].map(side => slash(path.join(projectPrefix, path.relative(side.config.root, side.config.output))));
23
21
  const artifacts = values['out-dir'] === undefined ? null : slash(path.relative(base.base.root, path.resolve(await realpath(config.root), values['out-dir'])));
24
22
  const excluded = name => name.split('/').some(part => ['.git', 'node_modules', '.adg'].includes(part)) || outputs.some(output => within(name, output)) || artifacts !== null && within(name, artifacts) && /\.(?:png|json)$/.test(name);
25
- const changes = (await revisionChanges(base.base, head?.base)).filter(change => [change.before, change.after].some(name => name !== null && !excluded(name)));
23
+ const changes = (await revisionChanges(base.base, head)).filter(change => [change.before, change.after].some(name => name !== null && !excluded(name)));
26
24
  return {
27
25
  session: base,
28
26
  before: { config: before.config, revision: base.base },
29
- after: { config: after.config, revision: head?.base ?? null },
30
- query: { kind: 'git', base: { rev: base.base.rev, sha: base.base.sha }, head: head ? { rev: head.base.rev, sha: head.base.sha } : null },
27
+ after: { config: after.config, revision: head ?? null },
28
+ query: { kind: 'git', base: { rev: base.base.rev, sha: base.base.sha }, head: head ? { rev: head.rev, sha: head.sha } : null },
31
29
  repository: base.base.root, projectPrefix, changes,
32
- head: head?.base.sha ?? await currentHead(base.base),
33
- warnings: sessions.flatMap(session => session.warnings),
34
- translate: value => sessions.reduce((result, session) => session.translateDiagnostic(result), value),
30
+ head: head?.sha ?? await currentHead(base.base),
31
+ warnings: base.warnings,
32
+ translate: base.translateDiagnostic,
35
33
  async verifyChanges() {
36
34
  if (head) return;
37
35
  const current = (await revisionChanges(base.base)).filter(change => [change.before, change.after].some(name => name !== null && !excluded(name)));
38
36
  if (JSON.stringify(current) !== JSON.stringify(changes)) throw new CliError('IMPACT_INPUT_CHANGED', 'Git input inventory changed during query.');
39
37
  },
40
- async close() {
41
- let failure;
42
- for (const session of [...sessions].reverse()) {
43
- try { await session.close(); } catch (error) { failure ??= error; }
44
- }
45
- if (failure) throw failure;
46
- },
38
+ close: base.close,
47
39
  };
48
40
  } catch (error) {
49
- for (const session of [...sessions].reverse()) await cleanup(() => session.close(), error);
41
+ await cleanup(base.close, error);
50
42
  throw error;
51
43
  }
52
44
  }