@whzxc/agent-design-gallery 0.15.0 → 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 (76) hide show
  1. package/README.md +5 -2
  2. package/package.json +2 -1
  3. package/public/app.js +602 -64
  4. package/public/assets.js +25 -10
  5. package/public/boards.js +8 -3
  6. package/public/frame-identity.js +25 -12
  7. package/public/icons.js +7 -0
  8. package/public/index.html +14 -2
  9. package/public/motion-flow.js +28 -0
  10. package/public/motion-identity.js +100 -0
  11. package/public/motion-paint.js +332 -0
  12. package/public/motion-scene.js +165 -0
  13. package/public/motion-specimens.js +335 -0
  14. package/public/player.css +270 -0
  15. package/public/player.js +753 -0
  16. package/public/recent-updates.js +535 -0
  17. package/public/style.css +17 -2
  18. package/public/tokens.css +6 -0
  19. package/public/view-boards.css +131 -0
  20. package/public/view-boards.js +350 -0
  21. package/public/view-route.js +1 -1
  22. package/src/boards/motion-board.mjs +202 -0
  23. package/src/boards/token-board.mjs +9 -5
  24. package/src/cli-output.mjs +3 -1
  25. package/src/cli.mjs +52 -18
  26. package/src/http.mjs +5 -2
  27. package/src/recent-frames.mjs +295 -0
  28. package/src/recent-history.mjs +100 -0
  29. package/src/recent-job.mjs +63 -0
  30. package/src/recent-worker.mjs +171 -0
  31. package/src/server.mjs +229 -18
  32. package/src/toolkit/arch-git.mjs +8 -14
  33. package/src/toolkit/browser.mjs +1 -13
  34. package/src/toolkit/build-store.mjs +9 -1
  35. package/src/toolkit/build-worker.mjs +6 -0
  36. package/src/toolkit/build.mjs +22 -16
  37. package/src/toolkit/commands.mjs +93 -2
  38. package/src/toolkit/compare.mjs +13 -11
  39. package/src/toolkit/config.mjs +2 -2
  40. package/src/toolkit/diff-inputs.mjs +35 -26
  41. package/src/toolkit/diff.mjs +24 -11
  42. package/src/toolkit/frame-declarations.mjs +36 -0
  43. package/src/toolkit/git-blobs.mjs +50 -0
  44. package/src/toolkit/impact-inputs.mjs +11 -19
  45. package/src/toolkit/impact-selection.mjs +2 -2
  46. package/src/toolkit/impact.mjs +17 -3
  47. package/src/toolkit/implementation-map.mjs +17 -6
  48. package/src/toolkit/input-generation.mjs +15 -0
  49. package/src/toolkit/inspect-output.mjs +1 -1
  50. package/src/toolkit/inspect.d.ts +9 -1
  51. package/src/toolkit/inspect.mjs +25 -1
  52. package/src/toolkit/motion-check.mjs +382 -0
  53. package/src/toolkit/motion-css.mjs +105 -0
  54. package/src/toolkit/motion-flows.mjs +95 -0
  55. package/src/toolkit/motion-impact.mjs +87 -0
  56. package/src/toolkit/motion-inventory.mjs +202 -0
  57. package/src/toolkit/motion-label.mjs +111 -0
  58. package/src/toolkit/motion-patterns.mjs +216 -0
  59. package/src/toolkit/motion-primitives.mjs +94 -0
  60. package/src/toolkit/motion-queries.mjs +169 -0
  61. package/src/toolkit/motion.mjs +300 -0
  62. package/src/toolkit/owner.mjs +19 -6
  63. package/src/toolkit/play-endpoint.mjs +66 -0
  64. package/src/toolkit/project-index.mjs +2 -2
  65. package/src/toolkit/recent-structure.mjs +201 -0
  66. package/src/toolkit/results.mjs +2 -2
  67. package/src/toolkit/review-document.mjs +9 -4
  68. package/src/toolkit/review-embed-document.mjs +671 -0
  69. package/src/toolkit/review-filmstrip.mjs +76 -0
  70. package/src/toolkit/review-motion-card.mjs +51 -0
  71. package/src/toolkit/review-motion.mjs +159 -0
  72. package/src/toolkit/review-playback.js +123 -0
  73. package/src/toolkit/review-sheet.mjs +36 -28
  74. package/src/toolkit/review.mjs +131 -31
  75. package/src/toolkit/runtime.mjs +7 -1
  76. package/src/viewer-cache.mjs +48 -12
@@ -1,6 +1,13 @@
1
+ import { labelResolver } from './motion-label.mjs';
1
2
  import { mkdirSync, readFileSync, existsSync } from 'node:fs';
2
3
  import path from 'node:path';
3
4
  import { availableParallelism } from 'node:os';
5
+ import { motionSummary, motionRows, readMotion } from './motion.mjs';
6
+ import { scanMotion } from './motion-inventory.mjs';
7
+ import { loadMotionPatterns } from './motion-patterns.mjs';
8
+ import { deadEndFindings } from './motion-flows.mjs';
9
+ import { motionEvaluator } from './motion-check.mjs';
10
+ import { sourceMotion } from './motion-css.mjs';
4
11
  import { buildSource } from './build.mjs';
5
12
  import { selectSources, relative, loadTokens, sourceDirectories, archFiles, featureFolderProblems, readGroups, listSources } from './project.mjs';
6
13
  import { importDirectionViolations, singleConsumerComponents, chapterWarnings } from './asset-rules.mjs';
@@ -220,7 +227,43 @@ export async function check(config, args = [], options = {}, log = console.log,
220
227
  if (!primary) primary = failure;
221
228
  else warnings.push(classifyError(failure).error);
222
229
  };
230
+ const emit = ({source,frame,theme,warning,...problem}) => {
231
+ if (warning) {
232
+ warnings.push({code:problem.code,message:source+': '+(problem.transition??frame??'')+(theme?' ('+theme+')':'')+' '+problem.message,next:[]});
233
+ if (!options.json) log('WARNING '+warnings.at(-1).message);
234
+ } else add(problem,path.join(config.root,source),frame??null,theme??null);
235
+ };
223
236
  try {
237
+ const motion = session?.views[1].motion ?? readMotion(config);
238
+ if (!args.length && !session) {
239
+ const inventory = scanMotion(config, loadMotionPatterns(config), motion);
240
+ const issues = options['motion-details'] ? inventory.issues : inventory.issues.slice(0, 16);
241
+ data.motionPatterns = {
242
+ animations: inventory.animations, unmapped: inventory.unmapped, unused: inventory.unused,
243
+ findings: inventory.issues.length, omitted: inventory.issues.length - issues.length,
244
+ };
245
+ for (const { source, ...issue } of issues) {
246
+ if (config.check?.strictMotion) add(issue, path.join(config.root, source));
247
+ else {
248
+ const message = source + (issue.line ? ':' + issue.line : '') + ': ' + issue.message;
249
+ warnings.push({ code: issue.code, message, next: [] });
250
+ if (!options.json) log('WARNING ' + message);
251
+ }
252
+ }
253
+ if (data.motionPatterns.omitted && !options.json)
254
+ log(data.motionPatterns.omitted + ' more motion inventory findings. Use --motion-details for all locations.');
255
+ if (options['motion-only']) {
256
+ for (const finding of motion.findings) emit(finding);
257
+ for (const finding of deadEndFindings(motion, motion.records, config.check?.strictMotion)) emit(finding);
258
+ for (const problem of humanProblems) error(problem);
259
+ data.complete = true;
260
+ const message = 'Motion inventory: ' + inventory.animations + ' animation sites, ' + inventory.unmapped +
261
+ ' unmapped, ' + inventory.unused + ' unused patterns.';
262
+ log(message);
263
+ if (data.findings.length) throw new CliError('CHECK_FAILED', message, { data, warnings, humanReported: true });
264
+ return { data, warnings };
265
+ }
266
+ }
224
267
  const directories = sourceDirectories(config);
225
268
  const chapterFiles = listSources(config.design, directories).map(file => path.relative(config.design, file).split(path.sep).join('/'));
226
269
  const chapters = chapterWarnings(chapterFiles, readGroups(config.design, directories), directories);
@@ -231,6 +274,17 @@ export async function check(config, args = [], options = {}, log = console.log,
231
274
  data.sources = files.map(file => relative(config, file));
232
275
  data.summary.sources = files.length;
233
276
  if (config.check?.strictLayers === true) for (const problem of featureFolderProblems(config.design, sourceDirectories(config))) add({ code: problem.code, message: problem.message, line: null, column: null }, problem.file);
277
+ const selectedRecord = r => (!args.length || [r.owner,r.edge?.to?.source].some(src=>data.sources.includes(src))) &&
278
+ (!options.frame || [r.edge?.from,r.edge?.to].some(ref=>ref?.frame===options.frame && data.sources.includes(ref.source))) &&
279
+ (!session || session.motionIds.has(r.edge?.id) || !r.valid);
280
+ const records = motion.records.filter(selectedRecord);
281
+ const cssFindings=new Map();
282
+ const scopeFiles = new Set(records.map(r=>r.source));
283
+ const inScope = sidecar => !args.length || scopeFiles.has(sidecar) || data.sources.includes(sidecar.replace(/\.motion\.json$/,'.tsx'));
284
+ for (const source of motion.files) if (inScope(source) && !chapterFiles.includes(path.relative(config.design,path.resolve(config.root,source)).replace(/\.motion\.json$/,'.tsx')))
285
+ emit({code:'MOTION_SCHEMA',source,pointer:'',message:'Motion sidecar has no owning TSX entry.',line:1,column:1});
286
+ for (const finding of motion.findings) if(inScope(finding.source)) emit(finding);
287
+ for (const finding of deadEndFindings(motion, records, config.check?.strictMotion)) emit(finding);
234
288
  const tokens = files.length ? loadTokens(config) : null;
235
289
  const arch = files.some(file => file.endsWith('.mmd')) ? await import('./arch.mjs') : null;
236
290
  let page;
@@ -267,6 +321,14 @@ export async function check(config, args = [], options = {}, log = console.log,
267
321
  if (mapping.present && !architecture) builtSources.set(relative(config, file), mappingFacts(built));
268
322
  graph[path.relative(config.design, file).split(path.sep).join('/')] = { uses: built.imports };
269
323
  for (const frame of built.frames) for (const theme of session?.themes ?? ['light', 'dark']) {
324
+ if (session && options.frame && frame.name !== options.frame) continue;
325
+ const lintMotion = !session || session.assessments.get(JSON.stringify([relative(config,file),frame.name,theme]))?.candidate ||
326
+ session.views[0].config.check?.strictMotion !== config.check?.strictMotion || !session.views[0].tokenBytes.equals(session.views[1].tokenBytes);
327
+ if (!architecture && lintMotion) for (const message of sourceMotion(built,frame,tokens,theme)) {
328
+ const key=JSON.stringify([file,frame.name,message]);
329
+ if(cssFindings.has(key))cssFindings.get(key).theme=null;
330
+ else cssFindings.set(key,{code:'MOTION_SOURCE_CSS',source:relative(config,file),frame:frame.name,theme,message,line:null,column:null,warning:!config.check?.strictMotion});
331
+ }
270
332
  if (session && !session.scheduled({ source: relative(config, file), frame: frame.name }, theme)) continue;
271
333
  browser ??= await launchBrowser();
272
334
  try {
@@ -281,20 +343,49 @@ export async function check(config, args = [], options = {}, log = console.log,
281
343
  }
282
344
  }
283
345
  }
346
+ for(const finding of cssFindings.values())emit(finding);
284
347
  let validatedMap = null;
285
348
  if (mapping.present) {
286
349
  const { listSources } = await import('./project.mjs');
287
350
  validatedMap = await validateImplementationMap(config, mapping, {
288
351
  sources: listSources(config.design, sourceDirectories(config)).map(file => relative(config, file)),
289
- selected: args.length ? data.sources : undefined,
352
+ selected: args.length ? [...new Set([...data.sources,...records.map(r=>r.owner)])] : undefined,
290
353
  getBuild: source => {
291
354
  if (failedSources.has(source)) throw failedSources.get(source);
292
355
  if (!builtSources.has(source)) builtSources.set(source, session?.views[1].built.get(source) ?? buildSource(config, path.join(config.root, source), { write: false, allowLegacy: false }));
293
356
  return builtSources.get(source);
294
357
  },
295
- onFinding: ({ code, message, line, column, frame }) => add({ code, message, line, column }, mapping.file, frame),
358
+ onFinding: ({ code, message, line, column, frame, pointer, target }) => add({ code, message, line, column, ...(code==='MOTION_BINDING'?{pointer,transition:target.transition}:{}) }, mapping.file, frame),
296
359
  });
297
360
  }
361
+ if (records.some(r=>r.valid)) {
362
+ const evaluate=motionEvaluator(config,{flows:motion.flows,themes:session?.themes,bindings:validatedMap?.transitionBindings,hasMap:mapping.present,
363
+ getBuild:source=>allBuilt.get(source)??session?.views[1].built.get(source),
364
+ getPage:async()=>{browser??=await launchBrowser();return page??=await browser.newPage();}});
365
+ // Other edges on this origin can conflict even when a Git or destination filter selects only one edge.
366
+ const origins=new Set(records.filter(r=>r.valid).map(r=>JSON.stringify([r.edge.from.source,r.edge.from.frame])));
367
+ const peers=motion.records.filter(r=>r.valid && !records.includes(r) && origins.has(JSON.stringify([r.edge.from.source,r.edge.from.frame])));
368
+ for(const peer of peers)await evaluate(peer);
369
+ for (const record of records.filter(r=>r.valid)) {
370
+ try { for(const finding of (await evaluate(record)).findings)emit(finding); }
371
+ catch(cause){failed(cause);}
372
+ }
373
+ }
374
+ const rows = motionRows(records);
375
+ if (options.transitions) {
376
+ const actionName = labelResolver(config, source => {
377
+ const built = allBuilt.get(source) ?? session?.views[1].built.get(source);
378
+ if (built) return built;
379
+ const file = path.join(config.root, source);
380
+ if (chapterFiles.includes(path.relative(config.design, file).split(path.sep).join('/')))
381
+ return buildSource(config, file, { write: false });
382
+ });
383
+ const edges = await Promise.all(rows.map(async record => ({
384
+ id: record.edge.id, label: await actionName(record),
385
+ ...(record.edge.proposed ? { proposed: record.edge.proposed } : {})
386
+ })));
387
+ motionSummary(data, edges, true);
388
+ } else motionSummary(data, rows);
298
389
  await cleanup(() => browser?.close(), primary);
299
390
  browser = null;
300
391
  if (config.check?.importDirection !== false) for (const { source, target, from, to, sameLayer, featureBoundary } of importDirectionViolations(graph, sourceDirectories(config), { strictLayers: config.check?.strictLayers === true })) {
@@ -17,11 +17,11 @@ export function compareReport(asset, frame, fixture, design, implementation) {
17
17
  offBy2px: rows.filter(row => row.off > 2).sort((a, b) => b.off - a.off), missing: missing.map(m => m.text), extra: extra.map(e => e.text) };
18
18
  }
19
19
  const cell = value => String(value).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/"/g, '&quot;');
20
- export function reportHtml(report) {
20
+ export function reportHtml(report, screenshots = true) {
21
21
  const fmt = value => (value > 0 ? '+' : '') + value.toFixed(1);
22
22
  return `<!doctype html><meta charset="utf-8"><title>${cell(report.asset)} ${cell(report.frame)}</title><style>body{font:13px system-ui;margin:24px;background:#f4f4f4}.row{display:flex;gap:16px;align-items:flex-start;overflow:auto}figure{margin:0}img{display:block;max-width:none;border:1px solid #ccc}table{border-collapse:collapse;margin-top:24px}td,th{padding:4px 10px;border-bottom:1px solid #ddd;text-align:left}td.n{font-family:ui-monospace,monospace;text-align:right}</style>
23
23
  <h1>${cell(report.asset)} · ${cell(report.frame)} vs ${cell(report.fixture)}</h1><p>Matched ${report.matched} texts. ${report.offBy2px.length} differ by more than 2px. ${report.missing.length} missing in implementation. ${report.extra.length} extra in implementation.</p>
24
- <div class="row">${['design', 'implementation', 'overlay'].map(name => `<figure><figcaption>${name}</figcaption><img src="${name}.png"></figure>`).join('')}</div>
24
+ ${screenshots ? `<div class="row">${['design', 'implementation', 'overlay'].map(name => `<figure><figcaption>${name}</figcaption><img src="${name}.png"></figure>`).join('')}</div>` : ''}
25
25
  <table><tr><th>Text</th><th>dx</th><th>dy</th><th>dw</th></tr>${report.offBy2px.map(row => `<tr><td>${cell(row.text)}</td><td class="n">${fmt(row.dx)}</td><td class="n">${fmt(row.dy)}</td><td class="n">${fmt(row.dw)}</td></tr>`).join('')}</table>
26
26
  <h2>Missing in implementation</h2><p>${report.missing.map(cell).join(' · ') || 'None'}</p><h2>Extra in implementation</h2><p>${report.extra.map(cell).join(' · ') || 'None'}</p>`;
27
27
  }
@@ -110,7 +110,8 @@ async function compareFrame(config, file, definition, options, data, { launchBro
110
110
  design = await sheet.locator('[data-adg-frame] > :first-child').evaluate(implementationTexts);
111
111
  const target = path.join(config.output, 'compare', `${path.relative(config.design,file).replace(/\.tsx$/, '').split(path.sep).join('-')}-${safeName(frame)}-${safeName(fixtureName)}`);
112
112
  mkdirSync(target, { recursive: true });
113
- await sheet.screenshot({ path: path.join(target, 'design.png'), clip: frameBox });
113
+ const screenshots = !options['no-screenshots'];
114
+ if (screenshots) await sheet.screenshot({ path: path.join(target, 'design.png'), clip: frameBox });
114
115
  const app = await browser.newPage({ viewport: size, colorScheme: fixture.theme, reducedMotion: 'reduce', locale: fixture.locale, timezoneId: fixture.timezone });
115
116
  for (const pattern of adapter.block ?? []) await app.route(pattern, route => route.abort());
116
117
  await app.addInitScript(({ clock, theme }) => {
@@ -158,15 +159,16 @@ async function compareFrame(config, file, definition, options, data, { launchBro
158
159
  }
159
160
  return result;
160
161
  }, clock);
161
- const screenshot = { path: path.join(target, 'implementation.png') };
162
- if (capture) await app.screenshot({ ...screenshot, clip: capture });
163
- else await panel.screenshot(screenshot);
164
- const canvasPage = await browser.newPage();
165
- await overlay(canvasPage, target);
162
+ if (screenshots) {
163
+ const screenshot = { path: path.join(target, 'implementation.png') };
164
+ if (capture) await app.screenshot({ ...screenshot, clip: capture });
165
+ else await panel.screenshot(screenshot);
166
+ await overlay(await browser.newPage(), target);
167
+ }
166
168
  const report = { ...compareReport(relative(config, file), frame, fixtureName, {...design,box:frameBox}, implementation), settled };
167
169
  writeFileSync(path.join(target, 'report.json'), JSON.stringify(report, null, 2) + '\n');
168
- writeFileSync(path.join(target, 'index.html'), reportHtml(report));
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
+ writeFileSync(path.join(target, 'index.html'), reportHtml(report, screenshots));
171
+ const paths = { ...(screenshots ? { 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
172
  const {asset, ...measured} = report;
171
173
  data.comparisons.push({source:asset, ...measured, theme:fixture.theme, paths});
172
174
  data.summary.frames++;
@@ -203,7 +205,7 @@ export async function compare(config, args = [], options = {}, { launchBrowser =
203
205
  if (!warnings.length) warnings.push({code:'COMPARE_FRAMES_SKIPPED',message:'Frames without fixtures were skipped.',next:[]});
204
206
  continue;
205
207
  }
206
- reports.push(await compareFrame(config,file,frame,options.all ? {frame:frame.name} : options,data,{launchBrowser,clock,log}));
208
+ reports.push(await compareFrame(config,file,frame,options.all ? {frame:frame.name, 'no-screenshots':options['no-screenshots']} : options,data,{launchBrowser,clock,log}));
207
209
  if (!data.comparisons.at(-1).settled) throw new CliError('COMPARE_UNSETTLED', 'Comparison text boxes did not settle within 5 seconds.', {humanReported:true});
208
210
  }
209
211
  }
@@ -126,7 +126,7 @@ export async function loadConfig(cwd = process.cwd(), { checkVersion = true, dis
126
126
  for (const key of ['design', 'output', 'arch']) if (config[key] !== undefined && !(key === 'arch' && config[key] === false) && (typeof config[key] !== 'string' || !config[key].trim())) throw new CliError('CONFIG_INVALID', `Set ${key} to a directory path in adg.config.mjs`);
127
127
  if (config.check !== undefined && (!config.check || typeof config.check!=='object' || Array.isArray(config.check))) throw new CliError('CONFIG_INVALID', 'Set check to an object in adg.config.mjs');
128
128
  if (config.check?.importDirection !== undefined && typeof config.check.importDirection!=='boolean') throw new CliError('CONFIG_INVALID', 'Set check.importDirection to true or false in adg.config.mjs');
129
- for (const key of ['strictLayers', 'lifecycle', 'singleConsumer']) if (config.check?.[key] !== undefined && typeof config.check[key] !== 'boolean') throw new CliError('CONFIG_INVALID', `Set check.${key} to true or false in adg.config.mjs`);
129
+ for (const key of ['strictLayers', 'strictMotion', 'lifecycle', 'singleConsumer']) if (config.check?.[key] !== undefined && typeof config.check[key] !== 'boolean') throw new CliError('CONFIG_INVALID', `Set check.${key} to true or false in adg.config.mjs`);
130
130
  const compare = { port: 5188, viewport: '1280x800', ...config.compare };
131
131
  viewport(compare.viewport);
132
132
  if (!Number.isInteger(compare.port) || compare.port < 1 || compare.port > 65535) throw new CliError('CONFIG_INVALID', 'Set compare.port to an integer from 1 to 65535 in adg.config.mjs');
@@ -136,5 +136,5 @@ export async function loadConfig(cwd = process.cwd(), { checkVersion = true, dis
136
136
  if (typeof config.arch === 'string' && (path.isAbsolute(config.arch) || path.relative(root,path.resolve(root,config.arch)).startsWith('..'))) throw new CliError('CONFIG_INVALID', 'Set arch to a project-root-relative directory in adg.config.mjs');
137
137
  const arch = config.arch === false ? false : path.resolve(root,config.arch ?? 'arch');
138
138
  const design=path.resolve(root,config.design??'design');
139
- return { root, name: config.name ?? path.basename(root), requires: config.requires ?? null, compatible, archDirectory: arch, arch: arch && (config.arch !== undefined || archFiles(arch).length) ? arch : false, sources: sourceDirectories({...config,design}), design, output: path.resolve(root, config.output ?? 'output/design'), check:{archMaxEdges:30,importDirection:true,strictLayers:false,lifecycle:false,singleConsumer:true,...config.check}, compare, diff: resolveDiffPolicy(config.diff) };
139
+ return { root, name: config.name ?? path.basename(root), requires: config.requires ?? null, compatible, archDirectory: arch, arch: arch && (config.arch !== undefined || archFiles(arch).length) ? arch : false, sources: sourceDirectories({...config,design}), design, output: path.resolve(root, config.output ?? 'output/design'), check:{archMaxEdges:30,importDirection:true,strictLayers:false,strictMotion:false,lifecycle:false,singleConsumer:true,...config.check}, compare, diff: resolveDiffPolicy(config.diff) };
140
140
  }
@@ -1,7 +1,7 @@
1
1
  import path from 'node:path';
2
2
  import { existsSync } from 'node:fs';
3
3
  import { mkdir, readFile, realpath, rm, symlink } from 'node:fs/promises';
4
- import { resolveBase, materializeBase, sourceRenames, revisionValue, revisionError, revisionChanges } from './arch-git.mjs';
4
+ import { resolveBase, materializeBase, revisionValue, revisionError, revisionChanges } from './arch-git.mjs';
5
5
  import { configInputFiles } from './input-generation.mjs';
6
6
  import { loadConfig, legacyConfigFile } from './config.mjs';
7
7
  import { selectSources, relative } from './project.mjs';
@@ -142,11 +142,8 @@ function groupFrames(rows, field) {
142
142
  return groups;
143
143
  }
144
144
 
145
- /** Prepare revision inputs. The caller closes the session and owns any supplied browser. */
146
- export async function prepareDiffInputs(config, args = [], options = {}) {
147
- const base = await resolveBase(config, options.base);
148
- const root = await realpath(config.root);
149
- const tree = await materializeBase(base);
145
+ export async function openDiffRevision(base, root, temporaryDirectory) {
146
+ const tree = await materializeBase(base, temporaryDirectory);
150
147
  const warnings = [];
151
148
  try {
152
149
  const configDependencies = await reuseEnvironment(base, tree, root);
@@ -155,6 +152,7 @@ export async function prepareDiffInputs(config, args = [], options = {}) {
155
152
  message: `Base config uses current node_modules; environment files differ: ${configDependencies.changedFiles.join(', ')}.`, next: [],
156
153
  });
157
154
  const beforeRoot = path.join(tree.directory, path.relative(base.root, root));
155
+ await mkdir(beforeRoot,{recursive:true});
158
156
  const baseMigration = { applied: false, changes: [] };
159
157
  const translate = value => revisionValue(value, tree.directory, base.root);
160
158
  let beforeConfig;
@@ -172,23 +170,39 @@ export async function prepareDiffInputs(config, args = [], options = {}) {
172
170
  }
173
171
  return loadConfig(beforeRoot, { discover: false });
174
172
  }, translate);
175
- } catch (error) { throw revisionError(historicalFailure(error), tree.directory, base); }
176
- const before = { config: beforeConfig, sources: inventory(beforeConfig, tree.directory) };
173
+ } catch (error) { throw historicalFailure(error); }
174
+ return { config: beforeConfig, sources: inventory(beforeConfig, tree.directory), revision: base,
175
+ warnings, translate, environment: { configDependencies, baseMigration }, close: tree.close };
176
+ } catch (cause) {
177
+ const failure = revisionError(cause, tree.directory, base);
178
+ await cleanup(tree.close, failure);
179
+ throw failure;
180
+ }
181
+ }
182
+
183
+ /** Prepare both endpoints before selecting sources, hints or parent support frames. */
184
+ export async function prepareDiffInputs(config, args = [], options = {}) {
185
+ const root = await realpath(config.root);
186
+ const open = options.openRevision ?? (async rev => openDiffRevision(await resolveBase(config, rev), root));
187
+ const before = await open(options.base);
188
+ const { revision: base, translate, environment: { configDependencies, baseMigration } } = before;
189
+ const warnings = [...before.warnings];
190
+ let target;
191
+ const close = async () => { try { await target?.close(); } finally { await before.close(); } };
192
+ try {
193
+ if (options.head) { target = await open(options.head); warnings.push(...target.warnings); }
177
194
  // Resolve symlinked project roots consistently with the Git base identity.
178
195
  const currentConfig = { ...config, root };
179
196
  for (const key of ['design', 'arch', 'archDirectory', 'output']) {
180
197
  if (config[key]) currentConfig[key] = path.resolve(root, path.relative(config.root, config[key]));
181
198
  }
182
- const after = { config: currentConfig, sources: inventory(currentConfig, base.root) };
199
+ const after = target ?? { config: currentConfig, sources: inventory(currentConfig, base.root) };
183
200
  const union = new Set([...before.sources.keys(), ...after.sources.keys()]);
184
- const sources = await selectedSources(currentConfig, beforeConfig, root, union, args);
185
- const renames = (await sourceRenames(base)).flatMap(rename => {
186
- const old = path.relative(root, path.join(base.root, rename.before));
187
- const current = path.relative(root, path.join(base.root, rename.after));
188
- return outside(old) || outside(current) ? [] : [{ before: slash(old), after: slash(current) }];
189
- });
190
- const changes = (await revisionChanges(base)).map(change => Object.fromEntries(['before', 'after'].map(side => [side,
191
- change[side] === null ? null : slash(path.relative(root, path.join(base.root, change[side])))])));
201
+ const sources = await selectedSources(currentConfig, before.config, root, union, args);
202
+ const inputs = await revisionChanges(base, target?.revision);
203
+ const projectPath = name => name === null ? null : slash(path.relative(root, path.join(base.root, name)));
204
+ const changes = inputs.map(change => ({...change, before:projectPath(change.before), after:projectPath(change.after)}));
205
+ const renames = changes.filter(c => c.status === 'renamed' && !outside(c.before) && !outside(c.after));
192
206
  const changed = new Set(changes.flatMap(change => [change.before, change.after]).filter(Boolean));
193
207
  const configFiles = await Promise.all([before, after].map(async side =>
194
208
  (await configInputFiles(side.config)).map(file => relative(side.config, file))));
@@ -196,7 +210,7 @@ export async function prepareDiffInputs(config, args = [], options = {}) {
196
210
  slash(path.relative(root, path.join(base.root, name))))])].filter(name => changed.has(name));
197
211
  let closed = false;
198
212
  return {
199
- base, before, after, sources, renames, changes, globalChanges, warnings, translateDiagnostic: translate, environment: { configDependencies, baseMigration },
213
+ base, before, after, sources, renames, changes, globalChanges, warnings, translateDiagnostic: value => translate(target ? target.translate(value) : value), environment: { configDependencies, baseMigration },
200
214
  async buildFrames({ browser, materialized, failures: previousFailures = [], sources: requestedSources = sources, frame: requestedFrame = options.frame, deferParts = false } = {}) {
201
215
  if (closed) throw new CliError('SOURCE_BUILD_FAILED', 'Diff inputs are closed; prepare a new comparison.');
202
216
  const built = materialized ? materialized.map(values => new Map(values)) : [new Map(), new Map()], snapshots = [new Map(), new Map()];
@@ -261,15 +275,10 @@ export async function prepareDiffInputs(config, args = [], options = {}) {
261
275
  else await prepareParts();
262
276
  return result;
263
277
  },
264
- async close() { closed = true; await tree.close(); },
278
+ async close() { closed = true; await close(); },
265
279
  };
266
280
  } catch (error) {
267
- const failure = error instanceof CliError ? error : revisionError(error, tree.directory, base);
268
- failure.message = revisionValue(failure.message, tree.directory, base.root);
269
- failure.context = revisionValue(failure.context, tree.directory, base.root);
270
- failure.warnings.push(...warnings);
271
- await cleanup(tree.close, failure);
272
- failure.warnings = revisionValue(failure.warnings, tree.directory, base.root);
273
- throw failure;
281
+ await cleanup(close, error);
282
+ throw error;
274
283
  }
275
284
  }
@@ -162,7 +162,7 @@ function revisionReasons(pair) {
162
162
  return reasons;
163
163
  }
164
164
 
165
- async function writePair(output, pair, thresholds, reviewImages) {
165
+ async function writePair(output, pair, thresholds, reviewImages, reviewFormat) {
166
166
  const { row, theme } = pair;
167
167
  const directory = output && path.join(output, row.support ? 'support' : 'frames', ...row.source.split('/').map(safeName), safeName(row.frame), theme);
168
168
  const paths = directory ? {
@@ -202,11 +202,16 @@ async function writePair(output, pair, thresholds, reviewImages) {
202
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,
203
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,
204
204
  };
205
- if (!row.support && row.status !== 'moved') {
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)) {
206
211
  reviewImages.set(comparison.id, {
207
- before: output && pair.before ? `data:image/png;base64,${pair.before.png.toString('base64')}` : null,
208
- after: output && pair.after ? `data:image/png;base64,${pair.after.png.toString('base64')}` : null,
209
- 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')}`,
210
215
  });
211
216
  }
212
217
  if (!directory) return comparison;
@@ -224,7 +229,7 @@ async function writePair(output, pair, thresholds, reviewImages) {
224
229
  }
225
230
 
226
231
  /** Exact ordinary frames and evidence-backed structural part comparisons. */
227
- export async function diff(config, args = [], options = {}, { launchBrowser = launch, prepareInputs = prepareDiffInputs, log = console.log, clock, session, onReview, readSystemTheme = systemTheme, renderSheet = renderReviewSheet, sheetTheme, reviewOnly = false } = {}) {
232
+ export async function diff(config, args = [], options = {}, { launchBrowser = launch, prepareInputs = prepareDiffInputs, log = console.log, clock, session, onReview, readSystemTheme = systemTheme, renderSheet = renderReviewSheet, sheetTheme, reviewFormat } = {}) {
228
233
  const started = performance.now(), scale = Number(options.scale ?? 2);
229
234
  if (!Number.isFinite(scale) || scale <= 0) throw new CliError('USAGE_INVALID', 'Invalid --scale; use a positive number.');
230
235
  const themes = resolveThemes(options.theme, readSystemTheme);
@@ -234,9 +239,9 @@ export async function diff(config, args = [], options = {}, { launchBrowser = la
234
239
  if (options.impacted && !session) {
235
240
  return withImpacted(config, args, options, 'diff', selected =>
236
241
  diff(config, args, options, { launchBrowser, prepareInputs, log, clock, session: selected,
237
- readSystemTheme, renderSheet, sheetTheme, onReview, reviewOnly }));
242
+ readSystemTheme, renderSheet, sheetTheme, onReview, reviewFormat }));
238
243
  }
239
- const output = reviewOnly ? null : path.resolve(config.root, options['out-dir'] ?? path.join(config.output, 'diff'));
244
+ const output = reviewFormat ? null : path.resolve(config.root, options['out-dir'] ?? path.join(config.output, 'diff'));
240
245
  const timings = { prepareMs: 0, buildMs: 0, captureMs: 0, compareMs: 0, writeMs: 0, totalMs: 0 };
241
246
  const warnings = [], completed = [], reviewImages = new Map();
242
247
  const hiddenMoveReasons = new Set(), pendingMoveComparisons = new Map();
@@ -252,12 +257,12 @@ export async function diff(config, args = [], options = {}, { launchBrowser = la
252
257
  try {
253
258
  const head = await timed('prepareMs', async () => {
254
259
  inputs = session ? session.diffInputs : await prepareInputs(config, args, options);
255
- return currentHead(inputs.base);
260
+ return inputs.after?.revision?.sha ?? currentHead(inputs.base);
256
261
  });
257
262
  warnings.push(...inputs.warnings);
258
263
  data = {
259
264
  project: config.root, outputDirectory: output, complete: false,
260
- 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 },
261
266
  selection: { sources: inputs.sources, frame: options.frame ?? null, themes, scale,
262
267
  existingCoverage: !inputs.sources.length ? 'empty' : args.length || options.frame !== undefined || themes.length !== 2 ? 'partial' : 'full' },
263
268
  environment: { adg: metadata.version, node: process.version, platform: process.platform, arch: process.arch, chromium: null,
@@ -300,8 +305,10 @@ export async function diff(config, args = [], options = {}, { launchBrowser = la
300
305
  const ordinaryJobs = ordinary.flatMap(row => (row.previousSource ? moveThemes :
301
306
  themes.filter(theme => !session || row.support || session.scheduled(row, theme))).map(theme => ({ row, theme })));
302
307
  const partJobs = built.frames.filter(row => row.parentRow).flatMap(row => themes.filter(theme => !session || session.scheduled(row, theme)).map(theme => ({ row, theme })));
308
+ let comparedJobs = 0;
303
309
  for (const jobs of [ordinaryJobs, partJobs]) for (let start = 0; start < jobs.length; start += concurrency) {
304
310
  const failures = [], openPairs = [];
311
+ const changes = [];
305
312
  const phase = async (name, items, work) => {
306
313
  const settled = await timed(name, () => Promise.allSettled(items.map(work)));
307
314
  return settled.flatMap((result, index) => {
@@ -333,11 +340,15 @@ export async function diff(config, args = [], options = {}, { launchBrowser = la
333
340
  }
334
341
  return pairs.filter(item => themes.includes(item.theme));
335
342
  });
336
- const rows = await phase('writeMs', selected, pair => writePair(output, pair, thresholds, reviewImages));
343
+ const rows = await phase('writeMs', selected, pair => writePair(output, pair, thresholds, reviewImages, reviewFormat));
337
344
  for (const row of rows) {
338
345
  context?.comparisons.set(comparisonIdentity(row, row.theme), row);
339
346
  if (supportKeys.has(frameIdentity(row))) { data.support.push(row); data.summary.supportComparisons++; }
340
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
+ }
341
352
  completed.push(row); data.summary.comparisons++; data.summary[row.verdict]++;
342
353
  for (const name of classNames) data.summary.classPixels[name] += row.pixels.classes[name].pixels;
343
354
  }
@@ -348,6 +359,8 @@ export async function diff(config, args = [], options = {}, { launchBrowser = la
348
359
  catch (error) { failures.push({ index: jobs.length, error }); }
349
360
  }
350
361
  }
362
+ comparedJobs += Math.min(concurrency,jobs.length-start);
363
+ options.onProgress?.({phase:'Comparing frame images',completed:comparedJobs,total:ordinaryJobs.length+partJobs.length,changes});
351
364
  data.comparisons = completed;
352
365
  completed.sort((a, b) => selectedOrder.get(comparisonIdentity(a, a.theme)) - selectedOrder.get(comparisonIdentity(b, b.theme)));
353
366
  data.summary.isolationCaptures = context?.isolation.size ?? 0;
@@ -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
  }
@@ -25,7 +25,7 @@ export async function withImpacted(config, args, options, command, work) {
25
25
  if (outcome?.data && 'verdict' in outcome.data) outcome.data.verdict = null;
26
26
  }
27
27
  try {
28
- const plan = await impact(config, { base: options.base, json: true, 'state-dir': options['state-dir'], 'out-dir': options['out-dir'], explain: options.explain }, {
28
+ const plan = await impact(config, { base: options.base, head: options.head, openRevision: options.openRevision, json: true, 'state-dir': options['state-dir'], 'out-dir': options['out-dir'], explain: options.explain }, {
29
29
  consume: async session => {
30
30
  const { rows, views, assessments, inputs, data } = session;
31
31
  const sources = await selectedSources(views[1].config, views[0].config, views[1].config.root,
@@ -90,7 +90,7 @@ export async function withImpacted(config, args, options, command, work) {
90
90
  if (outcome?.data) {
91
91
  finalize(outcome.data);
92
92
  if (selection.coverage.scope === 'partial') warnings.push({ code: 'IMPACT_COVERAGE_PARTIAL', message: 'Impact selection has partial frame/theme coverage.', next });
93
- if (!failure && !chosen.some(row => (command === 'diff' || row.after) && themes.some(theme => scheduled(row, theme)))) warnings.push({ code: 'IMPACT_NO_CHANGES', message: 'No capture or browser-evaluation jobs were scheduled.', next });
93
+ if (!failure && !outcome.data.motion?.count && !chosen.some(row => (command === 'diff' || row.after) && themes.some(theme => scheduled(row, theme)))) warnings.push({ code: 'IMPACT_NO_CHANGES', message: 'No capture or browser-evaluation jobs were scheduled.', next });
94
94
  }
95
95
  if (failure && !['CHECK_FAILED', 'DIFF_FAILED'].includes(failure.code) && !(command === 'diff' && failure.partialSourceFailures === true)) throw failure;
96
96
  },