@whzxc/agent-design-gallery 0.0.0-stage → 0.7.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 (61) hide show
  1. package/LICENSE +69 -0
  2. package/README.md +218 -2
  3. package/package.json +43 -4
  4. package/public/access.css +10 -0
  5. package/public/app.js +1674 -0
  6. package/public/arrangement-worker.js +11 -0
  7. package/public/arrangement.js +49 -0
  8. package/public/assets.js +356 -0
  9. package/public/auth.js +69 -0
  10. package/public/favicon.svg +6 -0
  11. package/public/hub.css +67 -0
  12. package/public/hub.html +33 -0
  13. package/public/hub.js +165 -0
  14. package/public/icons.js +50 -0
  15. package/public/index.html +70 -0
  16. package/public/instance-actions.js +27 -0
  17. package/public/labels.js +122 -0
  18. package/public/layout.js +119 -0
  19. package/public/relationships.js +28 -0
  20. package/public/selection.js +20 -0
  21. package/public/style.css +194 -0
  22. package/public/switcher.css +37 -0
  23. package/public/switcher.js +176 -0
  24. package/public/token-catalog.js +129 -0
  25. package/public/tokens.css +61 -0
  26. package/public/view-route.js +66 -0
  27. package/src/cli-output.mjs +236 -0
  28. package/src/cli.mjs +176 -0
  29. package/src/http.mjs +38 -0
  30. package/src/hub/auth.mjs +41 -0
  31. package/src/hub/instances.mjs +99 -0
  32. package/src/hub/proxy.mjs +30 -0
  33. package/src/hub/registry.mjs +181 -0
  34. package/src/hub.mjs +128 -0
  35. package/src/lifecycle.mjs +109 -0
  36. package/src/link.mjs +55 -0
  37. package/src/open.mjs +61 -0
  38. package/src/perf.mjs +12 -0
  39. package/src/server.mjs +679 -0
  40. package/src/service.mjs +184 -0
  41. package/src/toolkit/arch-browser.mjs +40 -0
  42. package/src/toolkit/arch-git.mjs +55 -0
  43. package/src/toolkit/arch-overlay.mjs +225 -0
  44. package/src/toolkit/arch.mjs +221 -0
  45. package/src/toolkit/asset-rules.mjs +14 -0
  46. package/src/toolkit/browser.mjs +33 -0
  47. package/src/toolkit/build-store.mjs +266 -0
  48. package/src/toolkit/build-worker.mjs +35 -0
  49. package/src/toolkit/build.mjs +147 -0
  50. package/src/toolkit/commands.mjs +345 -0
  51. package/src/toolkit/compare.mjs +222 -0
  52. package/src/toolkit/config.mjs +136 -0
  53. package/src/toolkit/document.mjs +85 -0
  54. package/src/toolkit/migrate.mjs +85 -0
  55. package/src/toolkit/project.mjs +172 -0
  56. package/src/toolkit/results.mjs +44 -0
  57. package/src/toolkit/runtime.d.ts +14 -0
  58. package/src/toolkit/runtime.mjs +54 -0
  59. package/src/toolkit/text.mjs +12 -0
  60. package/src/toolkit/tokens.mjs +37 -0
  61. package/src/viewer-cache.mjs +85 -0
@@ -0,0 +1,147 @@
1
+ import { build, transform } from 'esbuild';
2
+ import { compile } from 'tailwindcss';
3
+ import { statSync, readFileSync, realpathSync, mkdirSync, writeFileSync } from 'node:fs';
4
+ import { createRequire } from 'node:module';
5
+ import path from 'node:path';
6
+ import { fileURLToPath, pathToFileURL } from 'node:url';
7
+ import { loadTokens, refreshTypes, rejectLegacy, relative, isSourcePath, sourceDirectories } from './project.mjs';
8
+ import { themeCss, parseTokens } from './tokens.mjs';
9
+ import { escape } from './runtime.mjs';
10
+ import { CliError, classifyError } from '../cli-output.mjs';
11
+ const require = createRequire(import.meta.url);
12
+ const runtime = fileURLToPath(new URL('./runtime.mjs', import.meta.url));
13
+ const tailwind = path.dirname(require.resolve('tailwindcss/package.json'));
14
+ // Imported source entries recur in many bundles. Retain their registration
15
+ // transforms by exact content, including pending work, without retaining a
16
+ // project's entire build graph or trusting modification times.
17
+ const sourceTransforms = new Map();
18
+ let transformBytes = 0;
19
+ const transformLimit = 8 * 1024 * 1024;
20
+ function forgetTransform(file) {
21
+ const entry = sourceTransforms.get(file);
22
+ if (entry) { transformBytes -= entry.bytes; sourceTransforms.delete(file); }
23
+ }
24
+ async function registeredSource(file, sourcePath, original) {
25
+ let entry = sourceTransforms.get(file);
26
+ if (entry?.original === original && entry.sourcePath === sourcePath) {
27
+ sourceTransforms.delete(file); sourceTransforms.set(file, entry);
28
+ return entry.result;
29
+ }
30
+ forgetTransform(file);
31
+ entry = { original, sourcePath, bytes: Buffer.byteLength(original) * 2, result: null };
32
+ entry.result = (async () => {
33
+ // esbuild's normalized export list supplies public names; static namespace
34
+ // accesses preserve aliases and let the bundler drop imported frame renderers.
35
+ const compiled = await transform(original, {loader:'tsx',format:'esm',jsx:'preserve'});
36
+ const names = [...compiled.code.matchAll(/\nexport\s*\{([^}]+)\}\s*;\s*$/g)].flatMap(match => match[1].split(',').map(item => item.trim().split(/\s+as\s+/).at(-1)).filter(name => name && name !== 'default'));
37
+ const registrations = names.map(name => `__adgRegister(__adgExports[${JSON.stringify(name)}],${JSON.stringify(sourcePath)},${JSON.stringify(name)});`).join('\n');
38
+ const contents = `${original}
39
+ import * as __adgExports from 'adg:self';
40
+ import {registerComponent as __adgRegister} from 'adg';
41
+ ${registrations}
42
+ `;
43
+ // Account for the generated text too; large individual sources need not
44
+ // occupy the cache even though their current callers can finish normally.
45
+ if (sourceTransforms.get(file) === entry) {
46
+ transformBytes += Buffer.byteLength(contents) - Buffer.byteLength(original);
47
+ entry.bytes = Buffer.byteLength(original) + Buffer.byteLength(contents);
48
+ trimTransforms();
49
+ }
50
+ return {contents,loader:'tsx'};
51
+ })();
52
+ sourceTransforms.set(file, entry); transformBytes += entry.bytes;
53
+ trimTransforms();
54
+ try { return await entry.result; }
55
+ catch (error) { if (sourceTransforms.get(file) === entry) forgetTransform(file); throw error; }
56
+ }
57
+ function trimTransforms() {
58
+ while (sourceTransforms.size > 256 || transformBytes > transformLimit)
59
+ forgetTransform(sourceTransforms.keys().next().value);
60
+ }
61
+ export function validateFrame(frame) {
62
+ if (!frame?.frame || typeof frame.name !== 'string' || !frame.name.trim()) throw Error('Default export must return named Frames');
63
+ for (const key of ['width', 'height']) if (frame[key] !== undefined && !(Number.isFinite(frame[key]) && frame[key] > 0)) throw Error(`Invalid Frame ${key}; use positive CSS pixels`);
64
+ const c = frame.capture;
65
+ if (c !== undefined) {
66
+ if (!c || typeof c !== 'object' || ['region','selector','page'].filter(k => c[k] !== undefined).length !== 1 || (c.page !== undefined && c.page !== true) || ['region','selector'].some(k => c[k] !== undefined && (typeof c[k] !== 'string' || !c[k].trim())) || (c.viewport !== undefined && !/^[1-9]\d*x[1-9]\d*$/.test(c.viewport)) || (c.origin !== undefined && (!c.page || !/^\d+(?:\.\d+)? \d+(?:\.\d+)?$/.test(c.origin))) || (c.clicks !== undefined && (!Array.isArray(c.clicks) || c.clicks.some(v => typeof v !== 'string' || !v)))) throw Error('Invalid capture; use region, selector or page with viewport, origin and clicks');
67
+ }
68
+ }
69
+ export async function buildSource(config, file, options = {}) {
70
+ try { return await buildDesignSource(config, file, options); }
71
+ catch (error) {
72
+ if (error instanceof CliError) throw error;
73
+ const code = classifyError(error).error.code;
74
+ throw new CliError(code === 'INTERNAL_ERROR' ? 'SOURCE_BUILD_FAILED' : code, error.message, { cause: error });
75
+ }
76
+ }
77
+ async function buildDesignSource(config, file, { write = true, allowLegacy = true, snapshot, browser } = {}) {
78
+ if (file.endsWith('.mmd')) return (await import('./arch.mjs')).buildArch(config,file,{snapshot,browser});
79
+ if (write) refreshTypes(config);
80
+ const read = (name, encoding) => {
81
+ if (!snapshot) return readFileSync(name, encoding);
82
+ if (!snapshot.has(name)) snapshot.set(name, readFileSync(name));
83
+ const value = snapshot.get(name);
84
+ return encoding ? value.toString(encoding) : value;
85
+ };
86
+ file = realpathSync(file);
87
+ const base = realpathSync(config.design), dependencies = new Set([path.join(base, 'tokens.css')]);
88
+ const imports = new Set(), sources = sourceDirectories(config);
89
+ const result = await build({ entryPoints: [file], bundle: true, write: false, format: 'esm', platform: 'node', jsx: 'automatic', jsxImportSource: 'adg', jsxDev: true, metafile: true, logLevel: 'silent', plugins: [{ name: 'adg-sources', setup(api) {
90
+ api.onResolve({ filter: /.*/ }, args => {
91
+ if (args.path === 'adg:self') return {path:args.importer};
92
+ if (['adg','adg/jsx-runtime','adg/jsx-dev-runtime'].includes(args.path)) return { path: pathToFileURL(runtime).href, external: true };
93
+ if (args.kind !== 'entry-point' && !args.path.startsWith('.')) return { errors: [{ text: `Bare import ${args.path} is unavailable; import adg or a relative file inside design/` }] };
94
+ const url = args.path.endsWith('?url');
95
+ const requested = url ? args.path.slice(0,-4) : args.path;
96
+ let resolved = args.kind === 'entry-point' ? path.resolve(requested) : path.resolve(args.resolveDir, requested);
97
+ resolved = [resolved, ...['.tsx','.ts','.js','/index.tsx','/index.ts','/index.js'].map(ext => resolved + ext)].find(candidate => statSync(candidate, { throwIfNoEntry: false })?.isFile());
98
+ if (!resolved) return { errors: [{ text: `Cannot resolve ${args.path}` }] };
99
+ resolved = realpathSync(resolved);
100
+ if (!resolved.startsWith(base + path.sep)) return { errors: [{ text: `Import ${args.path} leaves design/; move it inside design/` }] };
101
+ if (!allowLegacy) rejectLegacy(config, [path.join(config.design, path.relative(base, resolved))]);
102
+ dependencies.add(resolved);
103
+ const sourcePath = path.relative(base, resolved).split(path.sep).join('/');
104
+ if (args.importer === file && isSourcePath(sourcePath, sources)) imports.add(sourcePath);
105
+ if (url && !resolved.startsWith(path.join(base,'art')+path.sep)) return {errors:[{text:'?url imports must be under design/art/'}]};
106
+ return { path: resolved, ...(url ? {namespace:'art-url'} : {}) };
107
+ });
108
+ api.onLoad({filter:/.*/,namespace:'art-url'}, args => ({contents:read(args.path),loader:'dataurl'}));
109
+ api.onLoad({filter:/\.tsx$/}, async args => {
110
+ const sourcePath = path.relative(base, args.path).split(path.sep).join('/');
111
+ if (!isSourcePath(sourcePath, sources)) return snapshot ? {contents:read(args.path,'utf8'),loader:'tsx'} : undefined;
112
+ const original=read(args.path,'utf8');
113
+ return registeredSource(args.path, sourcePath, original);
114
+ });
115
+ if (snapshot) api.onLoad({filter:/\.(?:[cm]?js|jsx|ts|json)$/}, args => ({contents:read(args.path,'utf8'),loader:args.path.endsWith('.ts')?'ts':args.path.endsWith('.jsx')?'jsx':args.path.endsWith('.json')?'json':'js'}));
116
+ api.onLoad({ filter: /\.(png|jpe?g|webp)$/i }, args => ({ contents: read(args.path), loader: 'dataurl' }));
117
+ api.onLoad({ filter: /\.svg$/i }, args => {
118
+ const source = read(args.path,'utf8');
119
+ const forbidden = /<(?:style|script)\b|\s(?:on[\w-]+|className)\s*=/i.exec(source);
120
+ if (forbidden) { const before=source.slice(0,forbidden.index); return {errors:[{text:'Forbidden SVG markup; remove styles, scripts and event attributes',location:{file:args.path,line:before.split('\n').length,column:before.length-before.lastIndexOf('\n')-1}}]}; }
121
+ return { contents: `import { artwork } from 'adg'; export default props => artwork(${JSON.stringify(source)}, props);`, loader:'js' };
122
+ });
123
+ } }] }).catch(error => {
124
+ const typed = error.errors?.find(item => item.detail instanceof CliError)?.detail;
125
+ if (!typed) throw error;
126
+ // Retain esbuild's human diagnostics and details while carrying the owning boundary's code.
127
+ throw Object.assign(new CliError(typed.code, error.message, { cause: error, context: typed.context }), { errors: error.errors });
128
+ });
129
+ const mod = await import(`data:text/javascript;base64,${Buffer.from(result.outputFiles[0].text).toString('base64')}#${Date.now()}`);
130
+ if (typeof mod.default !== 'function') throw Error(`${relative(config,file)}: export a default function returning Frames`);
131
+ const value = mod.default(), frames = (Array.isArray(value) ? value.flat(Infinity) : [value]).filter(v => v != null && v !== false);
132
+ if (!frames.length) throw Error(`${relative(config,file)}: default export must return at least one Frame`);
133
+ const names = new Set();
134
+ for (const frame of frames) {
135
+ try { validateFrame(frame); if (names.has(frame.name)) throw Error(`Duplicate frame name ${frame.name}`); names.add(frame.name); }
136
+ catch(error) { throw Error(`${relative(config,file)}: ${frame?.name ?? '-'}: ${error.message}`); }
137
+ }
138
+ const tokenSource = read(path.join(base,'tokens.css'),'utf8'), tokens = snapshot ? parseTokens(tokenSource) : loadTokens(config);
139
+ const compiler = await compile(`${readFileSync(path.join(tailwind,'theme.css'),'utf8')}\n${themeCss(tokens)}\n${readFileSync(path.join(tailwind,'preflight.css'),'utf8')}\n@custom-variant dark (&:where([data-theme=dark], [data-theme=dark] *));\n@tailwind utilities;`);
140
+ const classes = [...new Set(frames.flatMap(f => [...f.html.matchAll(/\bclass="([^"]*)"/g)].flatMap(m => m[1].split(/\s+/))))];
141
+ const css = `${compiler.build(classes)}\n${tokenSource}\nhtml,body{margin:0;font-family:var(--font-ui);color:var(--text);background:var(--canvas)}[data-adg-frame]{display:flex;align-items:flex-start;position:relative;background:var(--canvas)}[data-adg-frame]>*,svg{flex-shrink:0} @media(prefers-reduced-motion:reduce){*,*::before,*::after{animation:none!important;transition:none!important}}`;
142
+ for (const frame of frames) {
143
+ frame.document = theme => `<!doctype html><html data-theme="${theme}"><head><meta charset="utf-8"><style>${css.replace(/<\/style/gi,'<\\/style')}</style></head><body><div data-adg-frame="${escape(frame.name)}" style="${frame.width ? `width:${frame.width}px;` : 'width:max-content;'}${frame.height ? `height:${frame.height}px;` : ''}">${frame.html}</div></body></html>`;
144
+ if (write) { const destination = path.join(config.output, path.relative(base,file).replace(/\.tsx$/, ''), `${encodeURIComponent(frame.name)}.html`); mkdirSync(path.dirname(destination),{recursive:true}); writeFileSync(destination,frame.document('light')); }
145
+ }
146
+ return { frames, dependencies: [...dependencies], imports: [...imports].sort(), css };
147
+ }
@@ -0,0 +1,345 @@
1
+ import { mkdirSync, readFileSync, existsSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { availableParallelism } from 'node:os';
4
+ import { buildSource } from './build.mjs';
5
+ import { selectSources, relative, loadTokens, sourceDirectories, archFiles } from './project.mjs';
6
+ import { importDirectionViolations } from './asset-rules.mjs';
7
+ import { launch, loadFrame, browserTask } from './browser.mjs';
8
+ import { CliError, classifyError } from '../cli-output.mjs';
9
+ import { commandFailure, cleanup, emptySelection } from './results.mjs';
10
+ export function inspectFrame(tokenNames) {
11
+ const frame = document.querySelector('[data-adg-frame]'), box = frame.getBoundingClientRect(), problems = new Map();
12
+ const add = (code, message) => problems.set(message, {code, message, line:null, column:null});
13
+ if (frame.children.length !== 1 || [...frame.childNodes].some(n => n.nodeType === 3 && n.textContent.trim())) add('FRAME_ROOT_INVALID', 'Frame needs exactly one root element');
14
+ const sample = document.createElement('i'); document.body.append(sample);
15
+ const canvas = document.createElement('canvas'); canvas.width = canvas.height = 1;
16
+ const context = canvas.getContext('2d', { colorSpace: 'srgb', colorType: 'float16', willReadFrequently: true });
17
+ context.globalCompositeOperation = 'copy';
18
+ const normalized = new Map();
19
+ const normalize = value => {
20
+ if (!normalized.has(value)) {
21
+ context.fillStyle = value; context.fillRect(0, 0, 1, 1);
22
+ // Float pixels retain un-premultiplied RGB even at low opacity.
23
+ const [r, g, b, a] = context.getImageData(0, 0, 1, 1, { colorSpace: 'srgb', pixelFormat: 'rgba-float16' }).data;
24
+ normalized.set(value, [r, g, b].map(channel => Math.round(channel * 255)).concat(a));
25
+ }
26
+ return normalized.get(value);
27
+ };
28
+ const colors = [];
29
+ for (const name of tokenNames) {
30
+ const value = getComputedStyle(document.documentElement).getPropertyValue(name).trim();
31
+ if (CSS.supports('color', value)) { sample.style.color = value; colors.push(normalize(getComputedStyle(sample).color)); }
32
+ for (const color of value.match(/(?:rgba?|hsla?|oklch|oklab|color)\([^)]*\)|#[\da-f]{3,8}\b/gi) ?? []) { sample.style.color = color; colors.push(normalize(getComputedStyle(sample).color)); }
33
+ }
34
+ sample.remove();
35
+ const outside = r => r.left < box.left - 1 || r.right > box.right + 1 || r.top < box.top - 1 || r.bottom > box.bottom + 1;
36
+ const styles = new Map(), bounds = new Map(), effects = new Map();
37
+ const style = el => { if (!styles.has(el)) styles.set(el,getComputedStyle(el)); return styles.get(el); };
38
+ const rectFor = el => { if (!bounds.has(el)) bounds.set(el,el.getBoundingClientRect()); return bounds.get(el); };
39
+ const intersect = (a,b) => ({left:Math.max(a.left,b.left),right:Math.min(a.right,b.right),top:Math.max(a.top,b.top),bottom:Math.min(a.bottom,b.bottom)});
40
+ const nonempty = r => r.right > r.left && r.bottom > r.top;
41
+ const clipped = (rect,start) => {
42
+ let visible = {left:rect.left,right:rect.right,top:rect.top,bottom:rect.bottom};
43
+ for (let p=start;p;p=p.parentElement) {
44
+ const ps=style(p),pr=rectFor(p);
45
+ // Overflow does not clip non-replaced inline boxes. Client bounds exclude
46
+ // borders/scrollbars and include padding, unlike the border-box DOMRect.
47
+ if (!(p instanceof HTMLElement && ps.display==='inline')) {
48
+ const sx=pr.width/(p.offsetWidth || p.clientWidth || pr.width || 1);
49
+ const sy=pr.height/(p.offsetHeight || p.clientHeight || pr.height || 1);
50
+ const left=pr.left+p.clientLeft*sx,top=pr.top+p.clientTop*sy;
51
+ if (ps.overflowX!=='visible') visible={...visible,left:Math.max(visible.left,left),right:Math.min(visible.right,left+p.clientWidth*sx)};
52
+ if (ps.overflowY!=='visible') visible={...visible,top:Math.max(visible.top,top),bottom:Math.min(visible.bottom,top+p.clientHeight*sy)};
53
+ }
54
+ if (p===frame) break;
55
+ }
56
+ return visible;
57
+ };
58
+ const opaqueEffects = el => {
59
+ if (!el) return true;
60
+ if (!effects.has(el)) {
61
+ const s=style(el);
62
+ effects.set(el,Number(s.opacity)===1 && s.filter==='none' && s.clipPath==='none' &&
63
+ s.maskImage==='none' && s.mixBlendMode==='normal' && opaqueEffects(el.parentElement));
64
+ }
65
+ return effects.get(el);
66
+ };
67
+ const opaqueColor = value => {
68
+ // Float16 canvas alpha rounds near-opaque colors up to 1. Read an explicit
69
+ // computed alpha before using canvas normalization for opaque color syntax.
70
+ if (value.startsWith('rgba(') || value.includes('/')) {
71
+ const alpha=value.match(/(?:,|\/)\s*([\d.e+-]+)(%)?\s*\)$/i);
72
+ return !!alpha && Number(alpha[1])===(alpha[2]?100:1);
73
+ }
74
+ return normalize(value)[3]===1;
75
+ };
76
+ const lines = [], covers = [];
77
+ for (const el of [frame, ...frame.querySelectorAll('*')]) {
78
+ const s = style(el), r = rectFor(el);
79
+ if (['STYLE','SCRIPT'].includes(el.tagName.toUpperCase())) add('MARKUP_FORBIDDEN', `Forbidden <${el.tagName.toLowerCase()}> in output`);
80
+ for (const attr of el.attributes) if (/^on/i.test(attr.name) || attr.name === 'classname') add('MARKUP_FORBIDDEN', `Forbidden attribute ${attr.name} in output`);
81
+ if (!el.closest('[data-free]')) {
82
+ const authored = (el.getAttribute('class') ?? '') + ' ' + (el.getAttribute('style') ?? '');
83
+ if ([...authored.matchAll(/(-?(?:\d*\.)?\d+)px\b/g)].some(m => !Number.isInteger(Number(m[1])))) add('FRACTIONAL_LENGTH', 'Fractional pixel length outside data-free');
84
+ for (const [,property] of (el.getAttribute('style') ?? '').matchAll(/(?:^|;)\s*([-\w]+)\s*:/g)) if (!['width','height'].includes(property) && !property.startsWith('--')) add('STYLE_FORBIDDEN', `Style ${property} outside data-free; use layout classes`);
85
+ }
86
+ if (s.display === 'none' || s.visibility === 'hidden' || r.width === 0 || r.height === 0) continue;
87
+ const visibleBox=clipped(r,el.parentElement);
88
+ if (nonempty(visibleBox) && outside(visibleBox)) add('FRAME_OVERFLOW', 'Content overflows the frame');
89
+ // A border-box background has the same rounded hit shape as its element.
90
+ // Other background clips/masks cannot establish rectangular opaque coverage.
91
+ if (el instanceof HTMLElement && s.backgroundClip==='border-box' && opaqueColor(s.backgroundColor) && opaqueEffects(el)) {
92
+ covers.push({el,rect:intersect(visibleBox,box)});
93
+ }
94
+ if (!el.closest('[data-brand]')) {
95
+ const paints = [s.color, s.backgroundColor];
96
+ for (const side of ['Top','Right','Bottom','Left']) if (parseFloat(s[`border${side}Width`]) > 0) paints.push(s[`border${side}Color`]);
97
+ if (s.outlineStyle !== 'none') paints.push(s.outlineColor);
98
+ if (el instanceof SVGElement && /^(path|rect|circle|ellipse|polygon|polyline|line|text)$/.test(el.localName)) paints.push(s.fill, s.stroke);
99
+ paints.push(...((s.boxShadow+' '+s.textShadow+' '+s.backgroundImage).match(/(?:rgba?|hsla?|oklch|oklab|color)\([^)]*\)/g) ?? []));
100
+ for (const value of paints) {
101
+ if (!value || value === 'none' || value.startsWith('url(')) continue;
102
+ const paint = normalize(value), alpha = paint[3];
103
+ if (alpha === 0) continue;
104
+ const matches = colors.some(color => alpha < 1
105
+ ? paint.slice(0, 3).every((channel, i) => Math.abs(channel - color[i]) <= 2)
106
+ : paint.every((channel, i) => channel === color[i]));
107
+ if (!matches) add('TOKEN_COLOR_MISMATCH', `Color ${value} matches no token`);
108
+ }
109
+ }
110
+ for (const node of el.childNodes) {
111
+ if (node.nodeType !== 3 || !node.textContent.trim()) continue;
112
+ const range = document.createRange(); range.selectNodeContents(node);
113
+ for (const rect of range.getClientRects()) {
114
+ if (rect.width < 1) continue;
115
+ const label = node.textContent.trim().replace(/\s+/g, ' ');
116
+ const visible=clipped(rect,el);
117
+ if (!nonempty(visible)) continue;
118
+ if (outside(visible)) add('TEXT_OUTSIDE_FRAME', `Text leaves frame: ${label}`);
119
+ if (visible.left < r.left - 1 || visible.right > r.right + 1 ||
120
+ (visible.top+visible.bottom)/2 < r.top - 1 || (visible.top+visible.bottom)/2 > r.bottom + 1) add('TEXT_OVERFLOW', `Text overflows its box: ${label}`);
121
+ const inFrame=intersect(visible,box);
122
+ if (nonempty(inFrame)) lines.push({rect:inFrame,label,el});
123
+ }
124
+ }
125
+ }
126
+ // Hit testing omits inert and pointer-events:none content, though it still paints.
127
+ // Normalize only the text/cover nodes after validating authored styles, then
128
+ // restore their exact attributes so inspection has no lasting DOM changes.
129
+ const restored = [], inert = [];
130
+ for (let el=frame;el;el=el.parentElement) if (el.hasAttribute('inert')) inert.push([el,el.getAttribute('inert')]);
131
+ for (const el of frame.querySelectorAll('[inert]')) inert.push([el,el.getAttribute('inert')]);
132
+ for (const [el] of inert) el.removeAttribute('inert');
133
+ for (const el of new Set([...lines.map(line=>line.el),...covers.map(cover=>cover.el)])) {
134
+ if (style(el).pointerEvents==='none') {
135
+ restored.push([el,el.getAttribute('style')]);el.style.setProperty('pointer-events','auto','important');
136
+ }
137
+ }
138
+ const hits = new Map();
139
+ const paintStack = (x,y) => {
140
+ const key=`${x},${y}`;
141
+ if (!hits.has(key)) hits.set(key,document.elementsFromPoint(x,y));
142
+ return hits.get(key);
143
+ };
144
+ const occluded = (el,rect) => {
145
+ const dx=Math.min(.01,(rect.right-rect.left)/100),dy=Math.min(.01,(rect.bottom-rect.top)/100);
146
+ const points=[[rect.left+dx,rect.top+dy],[rect.right-dx,rect.top+dy],
147
+ [rect.left+dx,rect.bottom-dy],[rect.right-dx,rect.bottom-dy],[(rect.left+rect.right)/2,(rect.top+rect.bottom)/2]];
148
+ return covers.some(cover => {
149
+ if (cover.el.contains(el) || cover.rect.left>rect.left || cover.rect.right<rect.right ||
150
+ cover.rect.top>rect.top || cover.rect.bottom<rect.bottom) return false;
151
+ const samples=points.map(([x,y])=>{
152
+ const stack=paintStack(x,y);return [stack.indexOf(el),stack.indexOf(cover.el)];
153
+ });
154
+ // The SAME convex background must hit every corner. Rounded controls can
155
+ // omit their text owner at an edge, so establish paint order where both
156
+ // elements hit; absence alone is never evidence that the text is behind.
157
+ return samples.every(([subject,foreground])=>foreground>=0 && (subject<0 || foreground<subject)) &&
158
+ samples.some(([subject,foreground])=>subject>=0 && foreground<subject);
159
+ });
160
+ };
161
+ try {
162
+ for (let i=0;i<lines.length;i++) for(let j=i+1;j<lines.length;j++) {
163
+ const a=lines[i], b=lines[j];
164
+ // Each Range belongs to a direct text node; an ancestor's own text and a
165
+ // positioned child's text are distinct visible lines, not duplicate ranges.
166
+ if (a.el===b.el) continue;
167
+ const overlap=intersect(a.rect,b.rect);
168
+ if (overlap.right-overlap.left>1 && overlap.bottom-overlap.top>2 &&
169
+ !occluded(a.el,overlap) && !occluded(b.el,overlap)) add('TEXT_OVERLAP', `Text overlaps: ${a.label} / ${b.label}`);
170
+ }
171
+ } finally {
172
+ for (const [el,authored] of restored) {
173
+ // Flush a CSSOM-created attribute before removing it (Chromium creates it lazily).
174
+ el.getAttribute('style');
175
+ if (authored===null) el.removeAttribute('style');
176
+ else el.setAttribute('style',authored);
177
+ }
178
+ for (const [el,authored] of inert) el.setAttribute('inert',authored);
179
+ }
180
+ return [...problems.values()];
181
+ }
182
+ export async function check(config, args = [], options = {}, log = console.log, error = console.error, { launchBrowser = launch } = {}) {
183
+ const write = !options['read-only'];
184
+ /** @type {import('./results.mjs').CheckData} */
185
+ const data = { project: config.root, readOnly: !write, complete: false, sources: [], summary: { sources: 0, frames: 0, evaluations: 0, problems: 0 }, findings: [] };
186
+ const warnings = [], humanProblems = new Set(), findingKeys = new Set(), graph = {};
187
+ let browser, primary;
188
+ const add = (problem, file, frame = null, theme = null, source = relative(config, file)) => {
189
+ const finding = { ...problem, source, frame, theme };
190
+ const key = JSON.stringify(finding);
191
+ if (!findingKeys.has(key)) { findingKeys.add(key); data.findings.push(finding); }
192
+ humanProblems.add(`${relative(config, file)}: ${frame === null ? '' : `${frame}: ${theme}: `}${problem.message}`);
193
+ data.summary.problems = data.findings.length;
194
+ };
195
+ const failed = cause => {
196
+ const failure = cause instanceof CliError ? cause : new CliError('SOURCE_BUILD_FAILED', cause.message, { cause });
197
+ if (!primary) primary = failure;
198
+ else warnings.push(classifyError(failure).error);
199
+ };
200
+ try {
201
+ const files = selectSources(config, args, { write });
202
+ data.sources = files.map(file => relative(config, file));
203
+ data.summary.sources = files.length;
204
+ const tokens = files.length ? loadTokens(config) : null;
205
+ const arch = files.some(file => file.endsWith('.mmd')) ? await import('./arch.mjs') : null;
206
+ let page;
207
+ for (const file of files) {
208
+ const architecture = file.endsWith('.mmd');
209
+ if (architecture) {
210
+ const side = file.replace(/\.mmd$/, '.md');
211
+ const metadata = arch.sidecar(existsSync(side) ? readFileSync(side, 'utf8') : '');
212
+ const validation = arch.inspectArch(readFileSync(file, 'utf8'), config.check?.archMaxEdges ?? 30).problems;
213
+ const sidecarProblems = [...metadata.problems, ...arch.ownerProblems(config, metadata)];
214
+ for (const problem of validation) add(problem, file);
215
+ for (const problem of sidecarProblems) add(problem, file, null, null, relative(config, side));
216
+ if (validation.length || sidecarProblems.length) continue;
217
+ }
218
+ let built;
219
+ try {
220
+ // Static architecture rejection is a completed rule evaluation and needs no browser.
221
+ browser ??= await launchBrowser();
222
+ built = await buildSource(config, file, { allowLegacy: false, write, browser });
223
+ } catch (cause) {
224
+ const legacy = cause.errors?.find(item => item.detail?.code === 'LEGACY_SOURCE');
225
+ if (legacy) throw legacy.detail;
226
+ if (['PLAYWRIGHT_UNAVAILABLE', 'CHROMIUM_UNAVAILABLE', 'BROWSER_FAILED', 'LEGACY_SOURCE'].includes(cause.code)) throw cause;
227
+ failed(cause);
228
+ for (const message of cause.message.split('\n')) humanProblems.add(`${relative(config, file)}: ${architecture ? '' : '-: '}${message.replace(/\s+/g, ' ')}`);
229
+ continue;
230
+ }
231
+ data.summary.frames += built.frames.length;
232
+ graph[path.relative(config.design, file).split(path.sep).join('/')] = { uses: built.imports };
233
+ for (const frame of built.frames) for (const theme of ['light', 'dark']) {
234
+ try {
235
+ page ??= await browserTask(browser, () => browser.newPage());
236
+ await loadFrame(page, frame, theme);
237
+ const findings = await browserTask(browser, () => page.evaluate(architecture ? arch.inspectArchLabels : inspectFrame, architecture ? undefined : [...tokens.light.keys()]));
238
+ for (const finding of findings) add(finding, file, frame.name, theme);
239
+ data.summary.evaluations++;
240
+ } catch (cause) {
241
+ failed(cause);
242
+ humanProblems.add(`${relative(config, file)}: ${frame.name}: ${theme}: ${cause.message.replace(/\s+/g, ' ')}`);
243
+ }
244
+ }
245
+ }
246
+ await cleanup(() => browser?.close(), primary);
247
+ browser = null;
248
+ if (config.check?.importDirection !== false) for (const { source, target, from, to } of importDirectionViolations(graph, sourceDirectories(config))) {
249
+ add({ code: 'IMPORT_DIRECTION', message: `import ${target} violates import direction (${from} -> ${to}); import from the same or a lower layer in sources`, line: null, column: null }, path.join(config.design, source));
250
+ }
251
+ for (const problem of humanProblems) error(problem);
252
+ const message = `Design check ${humanProblems.size ? 'failed' : 'passed'} for ${files.length} sources${humanProblems.size ? `: ${humanProblems.size} problems` : ''}.`;
253
+ log(message);
254
+ if (!files.length) emptySelection(warnings);
255
+ if (primary) { primary.humanReported = true; throw primary; }
256
+ data.complete = true;
257
+ if (data.findings.length) throw new CliError('CHECK_FAILED', message, { data, warnings, humanReported: true });
258
+ return { data, warnings };
259
+ } catch (cause) {
260
+ primary = commandFailure(cause, data, warnings);
261
+ throw primary;
262
+ } finally { if (browser) await cleanup(() => browser.close(), primary); }
263
+ }
264
+
265
+ export async function render(config, args = [], options = {}, log = console.log, { launchBrowser = launch } = {}) {
266
+ const output = options['out-dir'] ? path.resolve(config.root, options['out-dir']) : config.output;
267
+ /** @type {import('./results.mjs').RenderData} */
268
+ const data = { project: config.root, outputDirectory: output, complete: false, base: null, captures: [], deleted: [] };
269
+ const warnings = [], completed = [], failures = [];
270
+ let browser, primary;
271
+ try {
272
+ const scale = Number(options.scale ?? 2);
273
+ if (!(Number.isFinite(scale) && scale > 0)) throw new CliError('USAGE_INVALID', 'Invalid --scale; use a positive number');
274
+ const themeOption = options.theme ?? 'both';
275
+ if (!['both', 'light', 'dark'].includes(themeOption)) throw new CliError('USAGE_INVALID', 'Choose --theme=both, light, or dark.');
276
+ if (options['out-dir'] === '') throw new CliError('USAGE_INVALID', 'Set --out-dir to a directory.');
277
+ const themes = themeOption === 'both' ? ['light', 'dark'] : [themeOption];
278
+ let base, additional = [];
279
+ if (options.base !== undefined && (!args.length || args.some(arg => arg.endsWith('.mmd')))) {
280
+ const git = await import('./arch-git.mjs');
281
+ base = await git.resolveBase(config, options.base);
282
+ additional = await git.baseArchFiles(config, base);
283
+ data.base = { rev: base.rev, sha: base.sha };
284
+ } else if (options.base !== undefined) warnings.push({ code: 'USAGE_INVALID', message: '--base applies only to architecture sources.', next: [] });
285
+ const selected = selectSources(config, args, { additional });
286
+ const currentArchitecture = base ? new Set(archFiles(config.arch)) : null;
287
+ const files = selected.filter(file => {
288
+ if (!existsSync(file) || (base && file.endsWith('.mmd') && !currentArchitecture.has(file))) { data.deleted.push(relative(config, file)); return false; }
289
+ return true;
290
+ });
291
+ if (!selected.length) emptySelection(warnings);
292
+ if (files.length) browser = await launchBrowser();
293
+ const captures = [];
294
+ for (const file of files) {
295
+ const built = base && file.endsWith('.mmd') ? await (await import('./arch-overlay.mjs')).buildOverlay(config, file, { base, browser }) : await buildSource(config, file, { allowLegacy: false, browser });
296
+ for (const frame of built.frames.filter(frame => !options.frame || frame.name === options.frame)) for (const theme of themes) {
297
+ const outputSource = file.endsWith('.mmd') ? relative(config, file) : path.relative(config.design, file);
298
+ const target = path.join(output, outputSource.replace(/\.(?:tsx|mmd)$/, ''), `${encodeURIComponent(frame.name)}-${theme}.png`);
299
+ captures.push({ source: relative(config, file), frame, theme, target });
300
+ }
301
+ }
302
+ if (options.frame && !captures.length && !data.deleted.length) throw new CliError('FRAME_NOT_FOUND', `Unknown frame ${options.frame}; choose a declared frame`);
303
+ let next = 0;
304
+ await Promise.allSettled(Array.from({ length: Math.min(4, availableParallelism(), captures.length) }, async () => {
305
+ while (next < captures.length) {
306
+ const index = next++, { source, frame, theme, target } = captures[index];
307
+ let page, failure;
308
+ try {
309
+ page = await browserTask(browser, () => browser.newPage({ deviceScaleFactor: scale }));
310
+ await loadFrame(page, frame, theme);
311
+ mkdirSync(path.dirname(target), { recursive: true });
312
+ const { box, png } = await browserTask(browser, async () => {
313
+ const element = page.locator('[data-adg-frame]');
314
+ const box = await element.boundingBox();
315
+ if (!box) throw Error('Frame has no visible bounds.');
316
+ return { box, png: await element.screenshot({ path: target }) };
317
+ });
318
+ completed[index] = { source, frame: frame.name, theme, path: target, scale, width: box.width, height: box.height, pixelWidth: png.readUInt32BE(16), pixelHeight: png.readUInt32BE(20) };
319
+ } catch (cause) {
320
+ failure = commandFailure(cause, data, warnings);
321
+ failures.push({ index, failure });
322
+ throw failure;
323
+ } finally {
324
+ if (page) try { await cleanup(() => page.close(), failure); }
325
+ catch (cause) { failures.push({ index, failure: commandFailure(cause, data, warnings) }); throw cause; }
326
+ }
327
+ }
328
+ }));
329
+ data.captures = completed.filter(Boolean);
330
+ failures.sort((a, b) => a.index - b.index);
331
+ if (failures.length) {
332
+ for (const { failure } of failures.slice(1)) warnings.push(classifyError(failure).error);
333
+ throw failures[0].failure;
334
+ }
335
+ if (!options.json) for (const capture of data.captures) log(relative(config, capture.path));
336
+ await cleanup(() => browser?.close(), null);
337
+ browser = null;
338
+ data.complete = true;
339
+ return { data, warnings };
340
+ } catch (cause) {
341
+ data.captures = completed.filter(Boolean);
342
+ primary = commandFailure(cause, data, warnings);
343
+ throw primary;
344
+ } finally { if (browser) await cleanup(() => browser.close(), primary); }
345
+ }