@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,6 +1,7 @@
1
1
  import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync, realpathSync } from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { parseTokens } from './tokens.mjs';
4
+ import { CliError, classifyError } from '../cli-output.mjs';
4
5
  export const starterTokens = `:root {
5
6
  --font-ui: system-ui, sans-serif;
6
7
  --font-mono: ui-monospace, monospace;
@@ -23,16 +24,18 @@ export function sourceDirectories(config = {}) {
23
24
  readdirSync(path.join(config.design, 'studies'), {withFileTypes:true}).some(entry => entry.isFile() && isSourcePath(`studies/${entry.name}`, ['studies']));
24
25
  const sources = config.sources === undefined ? [...defaultSources, ...(studies ? ['studies'] : [])] : config.sources;
25
26
  if (!Array.isArray(sources) || !sources.length || sources.some(name => typeof name !== 'string' || !/^[A-Za-z0-9_-]+$/.test(name))) {
26
- throw Error('Set sources to a non-empty array of plain top-level directory names in adg.config.mjs; nesting is not allowed');
27
+ throw new CliError('CONFIG_INVALID', 'Set sources to a non-empty array of plain top-level directory names in adg.config.mjs; nesting is not allowed');
27
28
  }
28
29
  return [...new Set(sources)];
29
30
  }
30
31
  const sourceLocations = sources => sources.map(name => `${name}/`).join(', ');
31
- export function refreshTypes(config) {
32
+ export function refreshTypes(config, changes) {
32
33
  mkdirSync(path.join(config.design, '.adg'), { recursive: true });
33
34
  const runtime = readFileSync(new URL('./runtime.d.ts', import.meta.url), 'utf8');
34
35
  writeFileSync(path.join(config.design, '.adg/runtime.d.ts'), runtime);
36
+ changes?.push({ action: 'regenerated', path: path.join(config.design, '.adg/runtime.d.ts'), from: null });
35
37
  writeFileSync(path.join(config.design, '.adg/assets.d.ts'), `declare module '*?url' { const url: string; export default url; }\ndeclare module '*.svg' { const Art: (props: Record<string, unknown>) => any; export default Art; }\n${['png','jpg','jpeg','webp'].map(ext => `declare module '*.${ext}' { const url: string; export default url; }`).join('\n')}\n`);
38
+ changes?.push({ action: 'regenerated', path: path.join(config.design, '.adg/assets.d.ts'), from: null });
36
39
  }
37
40
  export const tsconfig = { compilerOptions: { target: 'ESNext', module: 'ESNext', moduleResolution: 'Bundler', jsx: 'react-jsx', jsxImportSource: 'adg', noEmit: true, strict: true, paths: { adg: ['./.adg/runtime.d.ts'], 'adg/jsx-runtime': ['./.adg/runtime.d.ts'] } }, include: ['**/*.tsx', '**/*.ts', '.adg/*.d.ts'] };
38
41
  function starterSources(sources) {
@@ -61,31 +64,42 @@ export default () => <Frame name="default"${last ? ' width={640} height={360}' :
61
64
  });
62
65
  }
63
66
  export function init(config, log = console.log) {
64
- config.design ??= path.join(config.root, 'design');
65
- refreshTypes(config); rejectLegacy(config);
66
- const sources=sourceDirectories(config), fresh=sources.some(name=>name!=='studies') &&
67
- !listSources(config.design,sources).length && !existsSync(path.join(config.design,'fixtures/example.ts'));
68
- for (const [file, content] of [
69
- [path.join(config.root, 'adg.config.mjs'), "export default { requires: '>=0.5.0', design: 'design', output: 'output/design' };\n"],
70
- [path.join(config.design, 'tokens.css'), starterTokens],
71
- ...[...sources.filter(name=>name!=='studies'), 'fixtures', 'art'].map(name => [path.join(config.design, name), null]),
72
- ...(fresh ? [
73
- [path.join(config.design,'fixtures/example.ts'), "export const example = { title: 'Example', action: 'Continue' };\n"],
74
- ...starterSources(sources).map(([name,content])=>[path.join(config.design,name),content]),
75
- ] : []),
76
- [path.join(config.design, 'tsconfig.json'), JSON.stringify(tsconfig, null, 2) + '\n'],
77
- ]) {
78
- if (existsSync(file)) { log(`skipped ${relative(config, file)}`); continue; }
79
- mkdirSync(content === null ? file : path.dirname(file), { recursive: true });
80
- if (content !== null) writeFileSync(file, content);
81
- log(`created ${relative(config, file)}`);
67
+ const data = { project: config.root, complete: false, changes: [] };
68
+ try {
69
+ config.design ??= path.join(config.root, 'design');
70
+ refreshTypes(config, data.changes); rejectLegacy(config);
71
+ const sources=sourceDirectories(config), fresh=sources.some(name=>name!=='studies') &&
72
+ !listSources(config.design,sources).length && !existsSync(path.join(config.design,'fixtures/example.ts'));
73
+ for (const [file, content] of [
74
+ [path.join(config.root, 'adg.config.mjs'), "export default { requires: '>=0.5.0', design: 'design', output: 'output/design' };\n"],
75
+ [path.join(config.design, 'tokens.css'), starterTokens],
76
+ ...[...sources.filter(name=>name!=='studies'), 'fixtures', 'art'].map(name => [path.join(config.design, name), null]),
77
+ ...(fresh ? [
78
+ [path.join(config.design,'fixtures/example.ts'), "export const example = { title: 'Example', action: 'Continue' };\n"],
79
+ ...starterSources(sources).map(([name,content])=>[path.join(config.design,name),content]),
80
+ ] : []),
81
+ [path.join(config.design, 'tsconfig.json'), JSON.stringify(tsconfig, null, 2) + '\n'],
82
+ ]) {
83
+ if (existsSync(file)) { data.changes.push({ action: 'skipped', path: file, from: null }); log(`skipped ${relative(config, file)}`); continue; }
84
+ mkdirSync(content === null ? file : path.dirname(file), { recursive: true });
85
+ if (content !== null) writeFileSync(file, content);
86
+ data.changes.push({ action: 'created', path: file, from: null });
87
+ log(`created ${relative(config, file)}`);
88
+ }
89
+ const ignore = path.join(config.root, '.gitignore');
90
+ const existed = existsSync(ignore), original = existed ? readFileSync(ignore, 'utf8') : '';
91
+ let text = original;
92
+ for (const entry of [`/${relative(config, config.design)}/.adg/`, `/${relative(config, config.output ?? path.join(config.root, 'output/design'))}/`]) if (!text.split('\n').includes(entry)) text += `\n${entry}\n`;
93
+ writeFileSync(ignore, text);
94
+ if (!existed || text !== original) data.changes.push({ action: existed ? 'updated' : 'created', path: ignore, from: null });
95
+ refreshTypes(config, data.changes);
96
+ data.complete = true;
97
+ return data;
98
+ } catch (error) {
99
+ if (!data.changes.length) throw error;
100
+ if (error instanceof CliError) { error.data = data; throw error; }
101
+ throw new CliError(classifyError(error).error.code, error.message, { cause: error, data });
82
102
  }
83
- const ignore = path.join(config.root, '.gitignore');
84
- let text = existsSync(ignore) ? readFileSync(ignore, 'utf8') : '';
85
- for (const entry of [`/${relative(config, config.design)}/.adg/`, `/${relative(config, config.output ?? path.join(config.root, 'output/design'))}/`]) if (!text.split('\n').includes(entry)) text += `\n${entry}\n`;
86
- writeFileSync(ignore, text);
87
- refreshTypes(config);
88
- return 0;
89
103
  }
90
104
  export function listSources(directory, sources = sourceDirectories({design:directory})) {
91
105
  return sources.flatMap(name => {
@@ -115,7 +129,7 @@ export function readGroups(directory, sources = sourceDirectories({design:direct
115
129
  return data.groups;
116
130
  } catch (error) {
117
131
  if (error.code === 'ENOENT') return [];
118
- throw Error(`gallery.json: ${error.message}`);
132
+ throw new CliError('CONFIG_INVALID', `gallery.json: ${error.message}`, { cause: error });
119
133
  }
120
134
  }
121
135
  export function rejectLegacy(config, files) {
@@ -123,9 +137,7 @@ export function rejectLegacy(config, files) {
123
137
  files ??= directories.flatMap(base => existsSync(base) ? readdirSync(base).map(name => path.join(base, name)) : []);
124
138
  for (const file of files) {
125
139
  if (/\.svg$/i.test(file) && directories.includes(path.dirname(file))) {
126
- const error = Error(`${relative(config, file)}: convert this SVG source to TSX; move artwork to design/art/`);
127
- error.code = 'LEGACY_SVG';
128
- throw error;
140
+ throw new CliError('LEGACY_SOURCE', `${relative(config, file)}: convert this SVG source to TSX; move artwork to design/art/`);
129
141
  }
130
142
  }
131
143
  }
@@ -141,7 +153,7 @@ export function selectSources(config, args = [], { write = true, additional = []
141
153
  if(path.isAbsolute(arg)) {
142
154
  const root=realpathSync(config.root),file=existsSync(arg)?realpathSync(arg):path.resolve(arg);
143
155
  const relative=path.relative(root,file);
144
- if(relative==='..'||relative.startsWith('..'+path.sep)||path.isAbsolute(relative))throw Error(`Source ${arg} is outside the project root; choose a source inside ${config.root}.`);
156
+ if(relative==='..'||relative.startsWith('..'+path.sep)||path.isAbsolute(relative))throw new CliError('SOURCE_NOT_FOUND', `Source ${arg} is outside the project root; choose a source inside ${config.root}.`);
145
157
  const found=sources.find(source=>(existsSync(source)?realpathSync(source):path.resolve(source))===file);
146
158
  if(found)return found;
147
159
  }
@@ -149,12 +161,12 @@ export function selectSources(config, args = [], { write = true, additional = []
149
161
  let file = path.isAbsolute(arg) || fromRoot.startsWith(config.design + path.sep) ? fromRoot : path.resolve(config.design, arg);
150
162
  if (existsSync(file)) rejectLegacy(config, [file]);
151
163
  if (!file.endsWith('.tsx')) file += '.tsx';
152
- if (!sources.includes(file)) throw Error(`Invalid source ${arg}; name a discovered .mmd file or a TSX file directly in ${directories.map(name => path.join(config.design, name) + '/').join(', ')}`);
164
+ if (!sources.includes(file)) throw new CliError('SOURCE_NOT_FOUND', `Invalid source ${arg}; name a discovered .mmd file or a TSX file directly in ${directories.map(name => path.join(config.design, name) + '/').join(', ')}`);
153
165
  return file;
154
166
  });
155
167
  }
156
168
  export const relative = (config, file) => path.relative(config.root, file).split(path.sep).join('/');
157
169
  export function loadTokens(config) {
158
170
  try { return parseTokens(readFileSync(path.join(config.design, 'tokens.css'), 'utf8')); }
159
- catch (error) { throw Error(`${error.message}; fix design/tokens.css or run adg init`); }
171
+ catch (error) { throw new CliError('TOKENS_INVALID', `${error.message}; fix design/tokens.css or run adg init`, { cause: error }); }
160
172
  }
@@ -0,0 +1,44 @@
1
+ import { CliError, classifyError } from '../cli-output.mjs';
2
+
3
+ /** @typedef {'light' | 'dark'} Theme */
4
+ /** @typedef {{source: string | null, frame: string | null, theme: Theme | null, line: number | null, column: number | null}} Location */
5
+ /** @typedef {Location & {code: string, message: string}} Finding */
6
+ /** @typedef {{project: string, readOnly: boolean, complete: boolean, sources: string[], summary: {sources: number, frames: number, evaluations: number, problems: number}, findings: Finding[]}} CheckData */
7
+ /** @typedef {{source: string, frame: string, theme: Theme, path: string, scale: number, width: number, height: number, pixelWidth: number, pixelHeight: number}} Capture */
8
+ /** @typedef {{project: string, outputDirectory: string, complete: boolean, base: {rev: string, sha: string} | null, captures: Capture[], deleted: string[]}} RenderData */
9
+ /** @typedef {{source: string, frame: string, fixture: string, theme: Theme, settled: boolean, size: {design: [number, number], implementation: [number, number]}, matched: number, offBy2px: {text: string, dx: number, dy: number, dw: number, off: number}[], missing: string[], extra: string[], paths: {design: string, implementation: string, overlay: string, report: string, html: string}}} Comparison */
10
+ /** @typedef {{project: string, complete: boolean, all: boolean, comparisons: Comparison[], skipped: {source: string, frame: string, reason: 'no_fixture'}[], summary: {frames: number, matched: number, offsets: number, missing: number, extra: number}, indexPath: string | null, summaryPath: string | null}} CompareData */
11
+
12
+ /**
13
+ * Attach observed command data without replacing a typed boundary's code or message.
14
+ * @param {unknown} error
15
+ * @param {{complete: boolean}} data
16
+ * @param {import('../cli-output.mjs').Diagnostic[]} warnings
17
+ * @param {import('../cli-output.mjs').ErrorCode} [fallback]
18
+ */
19
+ export function commandFailure(error, data, warnings, fallback = 'INTERNAL_ERROR') {
20
+ const classified = classifyError(error);
21
+ const failure = error instanceof CliError ? error : new CliError(classified.error.code === 'INTERNAL_ERROR' ? fallback : classified.error.code, classified.error.message, { cause: error });
22
+ if (!['CHECK_FAILED', 'COMPARE_FAILED', 'DIFF_FAILED'].includes(failure.code)) data.complete = false;
23
+ failure.data = data;
24
+ failure.warnings = [...new Set([...warnings, ...failure.warnings])];
25
+ return failure;
26
+ }
27
+
28
+ /** Always attempt cleanup, retaining an earlier operation failure as primary.
29
+ * @param {() => Promise<unknown>} close
30
+ * @param {unknown} primary
31
+ */
32
+ export async function cleanup(close, primary) {
33
+ try { await close(); }
34
+ catch (error) {
35
+ const failure = new CliError('SHUTDOWN_FAILED', error instanceof Error ? error.message : String(error), { cause: error });
36
+ if (primary instanceof CliError) primary.warnings.push(classifyError(failure).error);
37
+ else if (!primary) throw failure;
38
+ }
39
+ }
40
+
41
+ /** @param {import('../cli-output.mjs').Diagnostic[]} warnings */
42
+ export function emptySelection(warnings) {
43
+ warnings.push({ code: 'EMPTY_SELECTION', message: 'No sources or fixture frames were selected.', next: [] });
44
+ }
@@ -1,6 +1,7 @@
1
1
  export type Content = unknown;
2
2
  export type Capture = ({ region: string; selector?: never; page?: never } | { selector: string; region?: never; page?: never } | { page: true; region?: never; selector?: never }) & { viewport?: string; origin?: string; clicks?: string[] };
3
- export interface FrameProps { name: string; width?: number; height?: number; fixture?: string; capture?: Capture; note?: string; children?: Content }
3
+ export interface FrameParent { source: string; frame: string; selector: string }
4
+ export interface FrameProps { name: string; width?: number; height?: number; fixture?: string; capture?: Capture; parent?: FrameParent; note?: string; children?: Content }
4
5
  export interface IconProps { name: string; size?: number; class?: string }
5
6
  export function Frame(props: FrameProps): JSX.Element;
6
7
  export function Icon(props: IconProps): JSX.Element;
@@ -1,23 +1,24 @@
1
+ import { CliError } from '../cli-output.mjs';
1
2
  export function parseTokens(css) {
2
3
  const source = css.replace(/\/\*[\s\S]*?\*\//g, '');
3
4
  const blocks = [...source.matchAll(/([^{}]+)\{([^{}]*)\}/g)];
4
5
  if (blocks.length !== 2 || source.replace(/[^{}]+\{[^{}]*\}/g, '').trim() ||
5
6
  blocks[0][1].trim() !== ':root' || blocks[1][1].trim() !== ':root[data-theme="dark"]') {
6
- throw new Error('tokens.css needs exactly :root and :root[data-theme="dark"] blocks; fix the token source');
7
+ throw new CliError('TOKENS_INVALID', 'tokens.css needs exactly :root and :root[data-theme="dark"] blocks; fix the token source');
7
8
  }
8
9
  const maps = blocks.map(([, , body]) => {
9
10
  const map = new Map();
10
11
  for (const line of body.split('\n').map(line => line.trim()).filter(Boolean)) {
11
12
  const match = line.match(/^(--[\w-]+)\s*:\s*([^;]+);$/);
12
- if (!match || map.has(match[1])) throw new Error(`Invalid token declaration ${line}; put each unique token on its own line`);
13
+ if (!match || map.has(match[1])) throw new CliError('TOKENS_INVALID', `Invalid token declaration ${line}; put each unique token on its own line`);
13
14
  map.set(match[1], match[2].trim());
14
15
  }
15
16
  return map;
16
17
  });
17
18
  for (const key of ['--font-ui', '--font-mono', '--canvas', '--text']) {
18
- if (!maps[0].has(key)) throw new Error(`tokens.css is missing ${key}; add it to :root`);
19
+ if (!maps[0].has(key)) throw new CliError('TOKENS_INVALID', `tokens.css is missing ${key}; add it to :root`);
19
20
  }
20
- for (const key of maps[1].keys()) if (!maps[0].has(key)) throw new Error(`Dark token ${key} has no light value; add it to :root`);
21
+ for (const key of maps[1].keys()) if (!maps[0].has(key)) throw new CliError('TOKENS_INVALID', `Dark token ${key} has no light value; add it to :root`);
21
22
  return { light: maps[0], dark: maps[1] };
22
23
  }
23
24