@whzxc/agent-design-gallery 0.0.0-stage → 0.6.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 (55) hide show
  1. package/LICENSE +69 -0
  2. package/README.md +216 -2
  3. package/package.json +43 -4
  4. package/public/access.css +10 -0
  5. package/public/app.js +1646 -0
  6. package/public/assets.js +344 -0
  7. package/public/auth.js +69 -0
  8. package/public/favicon.svg +6 -0
  9. package/public/hub.css +67 -0
  10. package/public/hub.html +33 -0
  11. package/public/hub.js +165 -0
  12. package/public/icons.js +50 -0
  13. package/public/index.html +70 -0
  14. package/public/instance-actions.js +27 -0
  15. package/public/labels.js +122 -0
  16. package/public/layout.js +103 -0
  17. package/public/relationships.js +28 -0
  18. package/public/selection.js +20 -0
  19. package/public/style.css +194 -0
  20. package/public/switcher.css +37 -0
  21. package/public/switcher.js +176 -0
  22. package/public/token-catalog.js +129 -0
  23. package/public/tokens.css +61 -0
  24. package/public/view-route.js +66 -0
  25. package/src/cli.mjs +105 -0
  26. package/src/http.mjs +37 -0
  27. package/src/hub/auth.mjs +40 -0
  28. package/src/hub/instances.mjs +99 -0
  29. package/src/hub/proxy.mjs +28 -0
  30. package/src/hub/registry.mjs +147 -0
  31. package/src/hub.mjs +113 -0
  32. package/src/link.mjs +54 -0
  33. package/src/open.mjs +57 -0
  34. package/src/server.mjs +642 -0
  35. package/src/service.mjs +163 -0
  36. package/src/toolkit/arch-browser.mjs +40 -0
  37. package/src/toolkit/arch-git.mjs +54 -0
  38. package/src/toolkit/arch-overlay.mjs +225 -0
  39. package/src/toolkit/arch.mjs +217 -0
  40. package/src/toolkit/asset-rules.mjs +14 -0
  41. package/src/toolkit/browser.mjs +21 -0
  42. package/src/toolkit/build-store.mjs +258 -0
  43. package/src/toolkit/build-worker.mjs +32 -0
  44. package/src/toolkit/build.mjs +133 -0
  45. package/src/toolkit/commands.mjs +273 -0
  46. package/src/toolkit/compare.mjs +175 -0
  47. package/src/toolkit/config.mjs +135 -0
  48. package/src/toolkit/document.mjs +85 -0
  49. package/src/toolkit/migrate.mjs +73 -0
  50. package/src/toolkit/project.mjs +160 -0
  51. package/src/toolkit/runtime.d.ts +14 -0
  52. package/src/toolkit/runtime.mjs +54 -0
  53. package/src/toolkit/text.mjs +12 -0
  54. package/src/toolkit/tokens.mjs +36 -0
  55. package/src/viewer-cache.mjs +85 -0
@@ -0,0 +1,135 @@
1
+ import { existsSync, readFileSync, statSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { pathToFileURL } from 'node:url';
4
+ import { createRequire } from 'node:module';
5
+ import { build } from 'esbuild';
6
+ import { sourceDirectories, archFiles } from './project.mjs';
7
+
8
+ export const VERSION = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url))).version;
9
+ export const UPDATE = 'npm install -g @whzxc/agent-design-gallery';
10
+ export const CONFIG_NAMES = ['adg.config.mjs', 'adg.config.js', 'adg.config.ts'];
11
+ export const configFile = directory => CONFIG_NAMES.map(name => path.join(directory, name)).find(file => statSync(file, { throwIfNoEntry: false })?.isFile());
12
+
13
+ // Old names belong only to this one-time migration and the discovery error.
14
+ export const LEGACY_CONFIG_NAMES = ['sdg.config.mjs', 'sdg.config.js', 'sdg.config.ts'];
15
+ export function legacyConfigFile(directory) {
16
+ return LEGACY_CONFIG_NAMES.map(name => path.join(directory, name)).find(existsSync);
17
+ }
18
+ export function requireMigration(directory) {
19
+ const old = legacyConfigFile(directory);
20
+ if (old && !CONFIG_NAMES.some(name => existsSync(path.join(directory, name)))) {
21
+ throw Error(`Found ${old}; run adg migrate ${JSON.stringify(directory)} before using this project.`);
22
+ }
23
+ }
24
+
25
+ export function discoverRoot(cwd = process.cwd()) {
26
+ let directory = path.resolve(cwd), packageRoot;
27
+ while (true) {
28
+ requireMigration(directory);
29
+ if (configFile(directory)) return directory;
30
+ if (!packageRoot && existsSync(path.join(directory, 'package.json'))) packageRoot = directory;
31
+ const parent = path.dirname(directory);
32
+ if (parent === directory) return packageRoot ?? path.resolve(cwd);
33
+ directory = parent;
34
+ }
35
+ }
36
+
37
+ function versionParts(value) {
38
+ const match = value.match(/^(\d+)\.(\d+)\.(\d+)(?:-([\w.-]+))?(?:\+[\w.-]+)?$/);
39
+ if (!match) throw new Error(`Invalid version ${value}; use major.minor.patch in requires`);
40
+ return [...match.slice(1, 4).map(Number), match[4]];
41
+ }
42
+ function order(a, b) {
43
+ for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return Math.sign(a[i] - b[i]);
44
+ if (a[3] === b[3]) return 0;
45
+ if (!a[3]) return 1;
46
+ if (!b[3]) return -1;
47
+ const x = a[3].split('.'), y = b[3].split('.');
48
+ for (let i = 0; i < Math.max(x.length, y.length); i++) {
49
+ if (x[i] === y[i]) continue;
50
+ if (x[i] === undefined) return -1;
51
+ if (y[i] === undefined) return 1;
52
+ const nx = /^\d+$/.test(x[i]), ny = /^\d+$/.test(y[i]);
53
+ return nx && ny ? Math.sign(Number(x[i]) - Number(y[i])) : nx !== ny ? (nx ? -1 : 1) : (x[i] < y[i] ? -1 : 1);
54
+ }
55
+ return 0;
56
+ }
57
+
58
+ // Intentionally small range grammar: exact, comparisons, ^, ~, AND and ||.
59
+ // Unsupported syntax fails explicitly instead of silently accepting a version.
60
+ export function satisfies(version, range) {
61
+ const actual = versionParts(version);
62
+ if (typeof range !== 'string' || !range.trim()) throw new Error('Invalid requires; use a range such as >=0.3.0');
63
+ const alternatives = range.split('||').map(branch => {
64
+ const terms = branch.trim().replace(/(>=|<=|>|<|=|\^|~)\s+/g, '$1').split(/\s+/);
65
+ return terms.map(term => {
66
+ if (term === '*') return !actual[3];
67
+ const match = term.match(/^(>=|<=|>|<|=|\^|~)?(\d+\.\d+\.\d+(?:-[\w.-]+)?(?:\+[\w.-]+)?)$/);
68
+ if (!match) throw new Error(`Unsupported requires ${range}; use comparisons with full versions, such as >=0.3.0`);
69
+ const target = versionParts(match[2]), delta = order(actual, target), op = match[1] ?? '=';
70
+ if (actual[3] && (!target[3] || actual.slice(0, 3).some((v, i) => v !== target[i]))) return false;
71
+ if (op === '^' || op === '~') {
72
+ const upper = [...target]; upper[3] = undefined;
73
+ const index = op === '~' ? 1 : target[0] ? 0 : target[1] ? 1 : 2;
74
+ upper[index]++; for (let i = index + 1; i < 3; i++) upper[i] = 0;
75
+ return delta >= 0 && order(actual, upper) < 0;
76
+ }
77
+ return ({ '=': delta === 0, '>=': delta >= 0, '<=': delta <= 0, '>': delta > 0, '<': delta < 0 })[op];
78
+ }).every(Boolean);
79
+ });
80
+ return alternatives.some(Boolean);
81
+ }
82
+
83
+ export function viewport(value) {
84
+ const match = typeof value === 'string' && value.match(/^([1-9]\d*)x([1-9]\d*)$/);
85
+ if (!match) throw new Error(`Invalid viewport ${value}; use <width>x<height>, for example 1280x800`);
86
+ return { width: Number(match[1]), height: Number(match[2]) };
87
+ }
88
+ async function importConfig(file) {
89
+ if (!file.endsWith('.ts')) {
90
+ const info = statSync(file), url = pathToFileURL(file);
91
+ url.searchParams.set('revision', `${info.mtimeMs}-${info.size}`);
92
+ return (await import(url.href)).default;
93
+ }
94
+ const require = createRequire(pathToFileURL(file));
95
+ const result = await build({ entryPoints: [file], bundle: true, write: false, format: 'esm', platform: 'node', logLevel: 'silent',
96
+ define: { 'import.meta.url': JSON.stringify(pathToFileURL(file).href) },
97
+ plugins: [{ name: 'config-imports', setup(api) {
98
+ api.onResolve({filter: /.*/}, args => {
99
+ if (args.kind === 'entry-point' || args.path.startsWith('node:')) return;
100
+ const candidate = args.path.startsWith('.') ? path.resolve(args.resolveDir, args.path) : args.path;
101
+ // Keep JS modules at their original URLs, including their own import.meta.url.
102
+ // TypeScript helpers are bundled by esbuild without writing generated files.
103
+ if (/\.[cm]?js$/.test(candidate) || !candidate.startsWith('/')) {
104
+ const resolved = require.resolve(candidate);
105
+ return { path: resolved.startsWith('/') ? pathToFileURL(resolved).href : resolved, external: true };
106
+ }
107
+ });
108
+ }}] });
109
+ return (await import(`data:text/javascript;base64,${Buffer.from(result.outputFiles[0].text).toString('base64')}`)).default;
110
+ }
111
+ export async function loadConfig(cwd = process.cwd(), { checkVersion = true } = {}) {
112
+ const root = discoverRoot(cwd), file = configFile(root);
113
+ let config = {};
114
+ if (file) {
115
+ try { config = await importConfig(file); }
116
+ catch (error) { throw new Error(`Cannot load ${file}: ${error.message}; fix ${path.basename(file)}`); }
117
+ }
118
+ if (!config || typeof config !== 'object' || Array.isArray(config)) throw new Error('Export a default object from adg.config.mjs');
119
+ if (config.name !== undefined && (typeof config.name !== 'string' || !config.name.trim())) throw new Error('Set name to a non-empty project name in the ADG config');
120
+ const compatible = config.requires === undefined || satisfies(VERSION, config.requires);
121
+ if (checkVersion && !compatible) throw new Error(`ADG ${VERSION} does not satisfy requires ${config.requires}; run ${UPDATE}`);
122
+ 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 Error(`Set ${key} to a directory path in adg.config.mjs`);
123
+ if (config.check !== undefined && (!config.check || typeof config.check!=='object' || Array.isArray(config.check))) throw new Error('Set check to an object in adg.config.mjs');
124
+ if (config.check?.importDirection !== undefined && typeof config.check.importDirection!=='boolean') throw new Error('Set check.importDirection to true or false in adg.config.mjs');
125
+ const compare = { port: 5188, viewport: '1280x800', ...config.compare };
126
+ viewport(compare.viewport);
127
+ if (!Number.isInteger(compare.port) || compare.port < 1 || compare.port > 65535) throw new Error('Set compare.port to an integer from 1 to 65535 in adg.config.mjs');
128
+ for (const key of ['start', 'fixture', 'ready', 'texts']) if (compare[key] !== undefined && typeof compare[key] !== 'function') throw new Error(`Set compare.${key} to a function in adg.config.mjs`);
129
+ if (compare.block !== undefined && (!Array.isArray(compare.block) || compare.block.some(value => typeof value !== 'string'))) throw new Error('Set compare.block to an array of request patterns in adg.config.mjs');
130
+ if (config.check?.archMaxEdges !== undefined && (!Number.isInteger(config.check.archMaxEdges) || config.check.archMaxEdges < 0)) throw Error('Set check.archMaxEdges to a non-negative integer in adg.config.mjs');
131
+ if (typeof config.arch === 'string' && (path.isAbsolute(config.arch) || path.relative(root,path.resolve(root,config.arch)).startsWith('..'))) throw Error('Set arch to a project-root-relative directory in adg.config.mjs');
132
+ const arch = config.arch === false ? false : path.resolve(root,config.arch ?? 'arch');
133
+ const design=path.resolve(root,config.design??'design');
134
+ 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,...config.check}, compare };
135
+ }
@@ -0,0 +1,85 @@
1
+ export function implementationTexts(root, clip) {
2
+ const bounds = root.getBoundingClientRect();
3
+ const origin = clip ? { left: clip.x - scrollX, top: clip.y - scrollY, right: clip.x - scrollX + clip.width, bottom: clip.y - scrollY + clip.height } : bounds;
4
+ const texts = [];
5
+ const measure = document.createElement('canvas').getContext('2d');
6
+ const visible = owner => {
7
+ for (let el = owner; el; el = el.parentElement) {
8
+ const style = getComputedStyle(el);
9
+ if (style.display === 'none' || style.visibility === 'hidden' || style.opacity === '0') return false;
10
+ }
11
+ const hidden = owner.closest('[aria-hidden="true"]');
12
+ return (!hidden || hidden === root || !root.contains(hidden)) && !owner.closest('script, style, .sr-only');
13
+ };
14
+ const inside = (box, owner) => {
15
+ let left = origin.left, right = origin.right, top = origin.top, bottom = origin.bottom;
16
+ for (let el = owner; el; el = el.parentElement) {
17
+ const style = getComputedStyle(el), bounds = el.getBoundingClientRect();
18
+ if (/(hidden|clip|auto|scroll)/.test(style.overflowX)) { left = Math.max(left, bounds.left); right = Math.min(right, bounds.right); }
19
+ if (/(hidden|clip|auto|scroll)/.test(style.overflowY)) { top = Math.max(top, bounds.top); bottom = Math.min(bottom, bounds.bottom); }
20
+ }
21
+ return box.left >= left - 0.5 && box.right <= right + 0.5 && (box.top + box.bottom) / 2 >= top && (box.top + box.bottom) / 2 <= bottom;
22
+ };
23
+ const push = (text, box, owner, style = getComputedStyle(owner)) => {
24
+ if (!inside(box, owner)) return;
25
+ texts.push({ text, x: box.left - origin.left, y: box.top - origin.top, width: box.right - box.left, height: box.bottom - box.top,
26
+ space: (measure.font = `${style.fontWeight} ${style.fontSize} ${style.fontFamily}`, measure.measureText(' ').width), anchor: style.textAlign === 'center' ? 'middle' : style.textAlign === 'right' ? 'end' : 'start', fill: style.color, size: style.fontSize, weight: style.fontWeight, family: style.fontFamily });
27
+ };
28
+ const linesFor = node => {
29
+ const result=[];
30
+ const range = document.createRange(), lines = [];
31
+ for (let index = 0; index < node.length; index++) {
32
+ range.setStart(node, index); range.setEnd(node, index + 1);
33
+ const rect = [...range.getClientRects()].find(r => r.width > 0 && r.height > 1);
34
+ if (!rect) continue;
35
+ let line = lines.at(-1);
36
+ if (!line || Math.abs(line.top - rect.top) >= rect.height / 2) {
37
+ line = { text: '', top: rect.top, bottom: rect.bottom, chars: [] }; lines.push(line);
38
+ }
39
+ line.text += node.data[index]; line.chars.push({ index, rect }); line.bottom = Math.max(line.bottom, rect.bottom);
40
+ }
41
+ for (const line of lines) {
42
+ const content = line.text.replace(/\s+/g, ' ').trim();
43
+ if (!content) continue;
44
+ const chars = line.chars.filter(({ index }) => !/\s/.test(node.data[index]));
45
+ const box = { left: Math.min(...chars.map(c => c.rect.left)), right: Math.max(...chars.map(c => c.rect.right)), top: line.top, bottom: line.bottom };
46
+ result.push({content,box});
47
+ }
48
+ return result;
49
+ };
50
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
51
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {
52
+ const owner=node.parentElement;
53
+ if (!node.textContent.trim() || !owner || owner.closest('input,textarea') || !visible(owner)) continue;
54
+ for (const {content,box} of linesFor(node)) push(content,box,owner);
55
+ }
56
+ const canvas = document.createElement('canvas').getContext('2d');
57
+ const fields='input:not([type]), input[type=text], input[type=search], input[type=email], input[type=url], input[type=tel], input[type=number], textarea';
58
+ for (const input of [...(root.matches(fields) ? [root] : []), ...root.querySelectorAll(fields)]) {
59
+ if (!visible(input)) continue;
60
+ const raw = input.value || input.placeholder || '';
61
+ const content = raw.replace(/\s+/g, ' ').trim();
62
+ if (!content) continue;
63
+ const rect = input.getBoundingClientRect(), style = getComputedStyle(input, input.value ? null : '::placeholder');
64
+ if (rect.width < 1) continue;
65
+ if (input.tagName === 'TEXTAREA') {
66
+ const box=getComputedStyle(input), mirror=document.createElement('div');
67
+ Object.assign(mirror.style,{position:'fixed',visibility:'hidden',left:(rect.left+parseFloat(box.borderLeftWidth)+parseFloat(box.paddingLeft)-input.scrollLeft)+'px',top:(rect.top+parseFloat(box.borderTopWidth)+parseFloat(box.paddingTop)-input.scrollTop)+'px',width:(input.clientWidth-parseFloat(box.paddingLeft)-parseFloat(box.paddingRight))+'px',fontFamily:style.fontFamily,fontSize:style.fontSize,fontWeight:style.fontWeight,lineHeight:style.lineHeight,letterSpacing:style.letterSpacing,whiteSpace:input.wrap==='off'?'pre':'pre-wrap',overflowWrap:'break-word'});
68
+ mirror.textContent=raw;document.body.append(mirror);
69
+ for (const {content,box} of linesFor(mirror.firstChild)) push(content,box,input,style);
70
+ mirror.remove();continue;
71
+ }
72
+ canvas.font = `${style.fontWeight} ${style.fontSize} ${style.fontFamily}`;
73
+ const box = getComputedStyle(input), height = parseFloat(style.fontSize) * 1.2;
74
+ const left = rect.left + parseFloat(box.borderLeftWidth) + parseFloat(box.paddingLeft);
75
+ const top = input.tagName === 'TEXTAREA' ? rect.top + parseFloat(box.borderTopWidth) + parseFloat(box.paddingTop) : rect.top + rect.height / 2 - height / 2;
76
+ push(content, { left, right: left + canvas.measureText(content).width, top, bottom: top + height }, input, style);
77
+ }
78
+ const merged = [];
79
+ for (const item of texts.sort((a,b) => a.y - b.y || a.x - b.x)) {
80
+ const previous = merged.findLast(p => Math.abs(p.y + p.height/2 - item.y - item.height/2) < 1 && item.x >= p.x + p.width - .5 && item.x - p.x - p.width < Math.max(p.space, item.space) - .1);
81
+ if (previous) { const gap = item.x - previous.x - previous.width; previous.text += (gap > .5 ? ' ' : '') + item.text; previous.width = item.x + item.width - previous.x; }
82
+ else merged.push({...item});
83
+ }
84
+ return { box: { x: origin.left + scrollX, y: origin.top + scrollY, width: origin.right - origin.left, height: origin.bottom - origin.top }, texts: merged };
85
+ }
@@ -0,0 +1,73 @@
1
+ import { existsSync, readFileSync, writeFileSync, readdirSync, renameSync, rmSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { CONFIG_NAMES, LEGACY_CONFIG_NAMES, loadConfig } from './config.mjs';
4
+ import { refreshTypes, relative } from './project.mjs';
5
+
6
+ function files(directory) {
7
+ if (!existsSync(directory)) return [];
8
+ return readdirSync(directory, { withFileTypes: true }).flatMap(entry => {
9
+ if (['.git', 'node_modules', '.sdg', '.adg'].includes(entry.name)) return [];
10
+ const file = path.join(directory, entry.name);
11
+ return entry.isDirectory() ? files(file) : entry.isFile() ? [file] : [];
12
+ });
13
+ }
14
+
15
+ // Keep source formatting, comments and ordinary string literals intact. Tokenize
16
+ // strings/comments first so text containing an import is never treated as code.
17
+ export function rewriteImports(source) {
18
+ const tokens = /\/\/[^\n]*|\/\*[\s\S]*?\*\/|"(?:\\[\s\S]|[^"\\])*"|'(?:\\[\s\S]|[^'\\])*'|`(?:\\[\s\S]|[^`\\])*`|[\w$]+|[^\s]/g;
19
+ let previous = [], result = '', end = 0;
20
+ for (const match of source.matchAll(tokens)) {
21
+ const value = match[0];
22
+ if (value.startsWith('//') || value.startsWith('/*')) continue;
23
+ if (/^["']/.test(value) && (['from', 'import'].includes(previous.at(-1)) ||
24
+ (previous.at(-1) === '(' && previous.at(-2) === 'import'))) {
25
+ const replacement = value.replace(/^(["'])sdg(?=["'/:])/, '$1adg');
26
+ if (replacement !== value) {
27
+ result += source.slice(end, match.index) + replacement;
28
+ end = match.index + value.length;
29
+ }
30
+ }
31
+ previous.push(value);
32
+ if (previous.length > 2) previous.shift();
33
+ }
34
+ return result + source.slice(end);
35
+ }
36
+
37
+ export async function migrate(project = process.cwd(), log = console.log) {
38
+ const root = path.resolve(project);
39
+ const oldConfigs = LEGACY_CONFIG_NAMES.filter(name => existsSync(path.join(root, name)));
40
+ const newConfigs = CONFIG_NAMES.filter(name => existsSync(path.join(root, name)));
41
+ if (oldConfigs.length && newConfigs.length) throw Error(`Both old and new config names exist in ${root}; keep one configuration before running adg migrate.`);
42
+ for (const name of oldConfigs) {
43
+ const next = name.replace('sdg.', 'adg.');
44
+ renameSync(path.join(root, name), path.join(root, next));
45
+ log(`Renamed ${name} -> ${next}`);
46
+ }
47
+ const config = await loadConfig(root, { checkVersion: false });
48
+ if (config.root !== root) throw Error(`No project configuration in ${root}; run adg migrate from the project root.`);
49
+ const update = (file, next) => {
50
+ const original = readFileSync(file, 'utf8');
51
+ if (next === original) return;
52
+ writeFileSync(file, next);
53
+ log(`Updated ${relative(config, file)}`);
54
+ };
55
+ for (const file of files(config.design)) {
56
+ if (/\.[cm]?[jt]sx?$/.test(file)) update(file, rewriteImports(readFileSync(file, 'utf8')));
57
+ if (/^tsconfig(?:\.[^.]+)*\.json$/.test(path.basename(file))) {
58
+ update(file, readFileSync(file, 'utf8')
59
+ .replace(/(["'])sdg(?=["'/:])/g, '$1adg').replace(/\.sdg(?=[/\\])/g, '.adg'));
60
+ }
61
+ }
62
+ for (const file of files(root).filter(file => path.basename(file) === '.gitignore')) {
63
+ update(file, readFileSync(file, 'utf8').replace(/^(?!\s*#)(.*)$/gm, line => line.replace(/(^|\/)\.sdg(?=\/|\r?$)/g, '$1.adg')));
64
+ }
65
+ const oldGenerated = path.join(config.design, '.sdg');
66
+ if (existsSync(oldGenerated)) {
67
+ rmSync(oldGenerated, { recursive: true });
68
+ log(`Deleted ${relative(config, oldGenerated)}/`);
69
+ }
70
+ refreshTypes(config);
71
+ log(`Regenerated ${relative(config, path.join(config.design, '.adg'))}/`);
72
+ return 0;
73
+ }
@@ -0,0 +1,160 @@
1
+ import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync, realpathSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { parseTokens } from './tokens.mjs';
4
+ export const starterTokens = `:root {
5
+ --font-ui: system-ui, sans-serif;
6
+ --font-mono: ui-monospace, monospace;
7
+ --canvas: #ffffff;
8
+ --text: #171717;
9
+ }
10
+ :root[data-theme="dark"] {
11
+ --canvas: #171717;
12
+ --text: #ffffff;
13
+ }
14
+ `;
15
+ export function archFiles(directory) {
16
+ if (!directory || !existsSync(directory)) return [];
17
+ return readdirSync(directory, {withFileTypes:true}).flatMap(entry => entry.name.startsWith('.') ? [] :
18
+ entry.isDirectory() ? archFiles(path.join(directory,entry.name)) : entry.isFile() && entry.name.endsWith('.mmd') ? [path.join(directory,entry.name)] : []).sort();
19
+ }
20
+ const defaultSources = ['components', 'modules', 'surfaces'];
21
+ export function sourceDirectories(config = {}) {
22
+ const studies = config.sources === undefined && config.design && existsSync(path.join(config.design, 'studies')) &&
23
+ readdirSync(path.join(config.design, 'studies'), {withFileTypes:true}).some(entry => entry.isFile() && isSourcePath(`studies/${entry.name}`, ['studies']));
24
+ const sources = config.sources === undefined ? [...defaultSources, ...(studies ? ['studies'] : [])] : config.sources;
25
+ 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
+ }
28
+ return [...new Set(sources)];
29
+ }
30
+ const sourceLocations = sources => sources.map(name => `${name}/`).join(', ');
31
+ export function refreshTypes(config) {
32
+ mkdirSync(path.join(config.design, '.adg'), { recursive: true });
33
+ const runtime = readFileSync(new URL('./runtime.d.ts', import.meta.url), 'utf8');
34
+ writeFileSync(path.join(config.design, '.adg/runtime.d.ts'), runtime);
35
+ 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`);
36
+ }
37
+ 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
+ function starterSources(sources) {
39
+ const layers=sources.filter(name=>name!=='studies');
40
+ return layers.map((directory,index) => {
41
+ const imports=`import { Frame } from 'adg';\n`;
42
+ let body;
43
+ if (!index) body=`import { example } from '../fixtures/example';
44
+
45
+ export function Example({ label = example.action }: { label?: string }) {
46
+ return <button class="rounded-lg bg-text px-4 py-2 text-canvas">{label}</button>;
47
+ }
48
+ export default () => <Frame name="default"><Example /></Frame>;
49
+ `;
50
+ else {
51
+ const last=index===layers.length-1;
52
+ body=`import { Example as Part } from '../${layers[index-1]}/example';
53
+ ${last ? '' : "import { example } from '../fixtures/example';\n"}
54
+ export function Example() {
55
+ return ${last ? '<main class="flex h-[360px] w-[640px] items-center justify-center bg-canvas p-6"><Part /></main>' : '<section class="flex flex-col items-start gap-3 p-4"><h2>{example.title}</h2><Part /></section>'};
56
+ }
57
+ export default () => <Frame name="default"${last ? ' width={640} height={360}' : ''}><Example /></Frame>;
58
+ `;
59
+ }
60
+ return [path.join(directory,'example.tsx'),imports+body];
61
+ });
62
+ }
63
+ 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)}`);
82
+ }
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
+ }
90
+ export function listSources(directory, sources = sourceDirectories({design:directory})) {
91
+ return sources.flatMap(name => {
92
+ const base = path.join(directory, name);
93
+ if (!existsSync(base)) return [];
94
+ return readdirSync(base, { withFileTypes: true })
95
+ .filter(entry => entry.isFile() && isSourcePath(`${name}/${entry.name}`, sources))
96
+ .map(entry => path.join(base, entry.name));
97
+ }).sort();
98
+ }
99
+ export function isSourcePath(name, sources = defaultSources) {
100
+ const slash = name.indexOf('/');
101
+ return slash > 0 && sources.includes(name.slice(0, slash)) && /^[^/.][^/]*\.tsx$/.test(name.slice(slash + 1));
102
+ }
103
+ export function readGroups(directory, sources = sourceDirectories({design:directory})) {
104
+ try {
105
+ const data = JSON.parse(readFileSync(path.join(directory, 'gallery.json'), 'utf8'));
106
+ if (!Array.isArray(data.groups) || data.groups.some(group => typeof group.title !== 'string' || !Array.isArray(group.assets))) {
107
+ throw Error('Expected groups with title and assets (relative source paths).');
108
+ }
109
+ for (const group of data.groups) for (const asset of group.assets) {
110
+ // Legacy SVGs remain browsable during staged conversion.
111
+ if (typeof asset !== 'string' || !isSourcePath(asset.replace(/\.svg$/i, '.tsx'), sources)) {
112
+ throw Error(`Invalid source ${asset}; use files directly in ${sourceLocations(sources)}.`);
113
+ }
114
+ }
115
+ return data.groups;
116
+ } catch (error) {
117
+ if (error.code === 'ENOENT') return [];
118
+ throw Error(`gallery.json: ${error.message}`);
119
+ }
120
+ }
121
+ export function rejectLegacy(config, files) {
122
+ const directories = sourceDirectories(config).map(dir => path.join(config.design, dir));
123
+ files ??= directories.flatMap(base => existsSync(base) ? readdirSync(base).map(name => path.join(base, name)) : []);
124
+ for (const file of files) {
125
+ 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;
129
+ }
130
+ }
131
+ }
132
+ export function selectSources(config, args = [], { write = true, additional = [] } = {}) {
133
+ if (write && (!args.length || args.some(arg=>!arg.endsWith('.mmd')))) refreshTypes(config);
134
+ if (!args.length) rejectLegacy(config);
135
+ const directories = sourceDirectories(config);
136
+ readGroups(config.design, directories);
137
+ const sources = [...new Set([...listSources(config.design, directories), ...archFiles(config.arch), ...additional])];
138
+ if (!args.length) return sources;
139
+ return args.map(arg => {
140
+ const fromRoot = path.resolve(config.root, arg);
141
+ if(path.isAbsolute(arg)) {
142
+ const root=realpathSync(config.root),file=existsSync(arg)?realpathSync(arg):path.resolve(arg);
143
+ 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}.`);
145
+ const found=sources.find(source=>(existsSync(source)?realpathSync(source):path.resolve(source))===file);
146
+ if(found)return found;
147
+ }
148
+ if (arg.endsWith('.mmd') && sources.includes(fromRoot)) return fromRoot;
149
+ let file = path.isAbsolute(arg) || fromRoot.startsWith(config.design + path.sep) ? fromRoot : path.resolve(config.design, arg);
150
+ if (existsSync(file)) rejectLegacy(config, [file]);
151
+ 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(', ')}`);
153
+ return file;
154
+ });
155
+ }
156
+ export const relative = (config, file) => path.relative(config.root, file).split(path.sep).join('/');
157
+ export function loadTokens(config) {
158
+ 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`); }
160
+ }
@@ -0,0 +1,14 @@
1
+ export type Content = unknown;
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 }
4
+ export interface IconProps { name: string; size?: number; class?: string }
5
+ export function Frame(props: FrameProps): JSX.Element;
6
+ export function Icon(props: IconProps): JSX.Element;
7
+ export function jsx(type: unknown, props: unknown): JSX.Element;
8
+ export { jsx as jsxs, jsx as jsxDEV };
9
+ export function Fragment(props: { children?: Content }): JSX.Element;
10
+ export namespace JSX {
11
+ type Element = any;
12
+ interface ElementChildrenAttribute { children: {} }
13
+ interface IntrinsicElements { [name: string]: { class?: string; children?: Content; [attribute: string]: unknown } }
14
+ }
@@ -0,0 +1,54 @@
1
+ import { icons } from 'lucide';
2
+ export const escape = value => String(value).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
3
+ const voids = new Set('area base br col embed hr img input link meta param source track wbr'.split(' '));
4
+ export const markup = html => ({ html, toString() { return this.html; } });
5
+ export function children(value) {
6
+ if (value == null || typeof value === 'boolean') return '';
7
+ if (Array.isArray(value)) return value.map(children).join('');
8
+ if (typeof value === 'object' && typeof value.html === 'string') return value.html;
9
+ return escape(value);
10
+ }
11
+ export function attributes(props) {
12
+ return Object.entries(props).filter(([key, value]) => !['children', 'key', '__source'].includes(key) && value != null && value !== false).map(([key, value]) => {
13
+ if (/^on/i.test(key) || key === 'className' || key === 'dangerouslySetInnerHTML') throw Error(`Forbidden attribute ${key}; use static markup and class`);
14
+ if (key === 'style' && typeof value === 'object') value = Object.entries(value).map(([name, v]) => `${name.startsWith('--') ? name : name.replace(/[A-Z]/g, c => '-' + c.toLowerCase())}:${typeof v === 'number' && !/^(opacity|zIndex|fontWeight|lineHeight|flex|flexGrow|flexShrink|order|gridColumn|gridRow|scale)$/.test(name) && !name.startsWith('--') ? v + 'px' : v}`).join(';');
15
+ return ` ${key}="${escape(value === true ? '' : value)}"`;
16
+ }).join('');
17
+ }
18
+ const componentOwners = new WeakMap();
19
+ export function registerComponent(component, source, name) {
20
+ if (typeof component === 'function' && !componentOwners.has(component)) componentOwners.set(component, {source, export:name});
21
+ }
22
+ const stamp = (value, owner) => Array.isArray(value) ? value.map(item => stamp(item, owner)) : value?.withOwner ? value.withOwner(owner) : value;
23
+ export const Fragment = ({ children: value }) => ({...markup(children(value)), withOwner:owner => Fragment({children:stamp(value,owner)})});
24
+ export function jsx(type, props = {}) {
25
+ if (typeof type === 'function') {
26
+ const value = type(props), owner = componentOwners.get(type);
27
+ return owner ? stamp(value, owner) : value;
28
+ }
29
+ if (['script', 'style'].includes(type.toLowerCase())) throw Error(`Forbidden <${type}>; use tokens and utility classes`);
30
+ const result = markup(`<${type}${attributes(props)}>${voids.has(type) ? '' : children(props.children) + `</${type}>`}`);
31
+ result.withOwner = owner => jsx(type, {...props, 'data-adg-owners':JSON.stringify([...(props['data-adg-owners'] ? JSON.parse(props['data-adg-owners']) : []), owner])});
32
+ return result;
33
+ }
34
+ export const jsxs = jsx;
35
+ export function jsxDEV(type, props, key, isStatic, source) {
36
+ try { return jsx(type, props); }
37
+ catch (error) { if (!error.located && source) { error.message = `${source.fileName}:${source.lineNumber}:${source.columnNumber}: ${error.message}`; error.located = true; } throw error; }
38
+ }
39
+ export function Frame({ children: content, ...props }) { return { frame: true, ...props, html: children(content) }; }
40
+ export function Icon({ name, size = 16, class: className, ...props }) {
41
+ const key = name.split('-').map(s => s[0].toUpperCase() + s.slice(1)).join('');
42
+ const geometry = icons[key];
43
+ if (!geometry) throw Error(`Unknown Lucide icon ${name}`);
44
+ return jsx('svg', { xmlns: 'http://www.w3.org/2000/svg', width: size, height: size, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', 'stroke-width': 1.75 * 24 / size, 'stroke-linecap': 'round', 'stroke-linejoin': 'round', 'aria-hidden': 'true', class: className, ...props, children: geometry.map(([tag, attrs]) => jsx(tag, attrs)) });
45
+ }
46
+ export function artwork(source, props) {
47
+ const match = source.match(/<svg\b([^>]*)>([\s\S]*)<\/svg>/i);
48
+ if (!match) throw Error('Invalid SVG artwork');
49
+ let attrs = match[1];
50
+ for (const key of Object.keys(props)) attrs = attrs.replace(new RegExp(`\\s${key}\\s*=\\s*(["']).*?\\1`, 'g'), '');
51
+ const result = markup(`<svg${attrs}${attributes(props)}>${match[2]}</svg>`);
52
+ result.withOwner = owner => artwork(source, {...props, 'data-adg-owners':JSON.stringify([...(props['data-adg-owners'] ? JSON.parse(props['data-adg-owners']) : []), owner])});
53
+ return result;
54
+ }
@@ -0,0 +1,12 @@
1
+ export function matchTexts(design, implementation) {
2
+ const candidates = design.flatMap((d, di) => implementation.flatMap((i, ii) => d.text === i.text ? [{di,ii,distance:Math.hypot(d.x-i.x,d.y-i.y)}] : [])).sort((a,b)=>a.distance-b.distance);
3
+ const usedD=new Set(), usedI=new Set(), pairs=[];
4
+ for (const {di,ii} of candidates) if (!usedD.has(di) && !usedI.has(ii)) { usedD.add(di); usedI.add(ii); pairs.push([design[di],implementation[ii]]); }
5
+ return {pairs,missing:design.filter((_,i)=>!usedD.has(i)),extra:implementation.filter((_,i)=>!usedI.has(i))};
6
+ }
7
+
8
+ // Compares the anchored edge, vertical center and width of a paired text.
9
+ export function textDelta(design, implementation) {
10
+ const edge = box => design.anchor === 'middle' ? box.x + box.width / 2 : design.anchor === 'end' ? box.x + box.width : box.x;
11
+ return { dx: edge(implementation) - edge(design), dy: (implementation.y + implementation.height / 2) - (design.y + design.height / 2), dw: implementation.width - design.width };
12
+ }
@@ -0,0 +1,36 @@
1
+ export function parseTokens(css) {
2
+ const source = css.replace(/\/\*[\s\S]*?\*\//g, '');
3
+ const blocks = [...source.matchAll(/([^{}]+)\{([^{}]*)\}/g)];
4
+ if (blocks.length !== 2 || source.replace(/[^{}]+\{[^{}]*\}/g, '').trim() ||
5
+ 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
+ }
8
+ const maps = blocks.map(([, , body]) => {
9
+ const map = new Map();
10
+ for (const line of body.split('\n').map(line => line.trim()).filter(Boolean)) {
11
+ 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
+ map.set(match[1], match[2].trim());
14
+ }
15
+ return map;
16
+ });
17
+ 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
+ }
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
+ return { light: maps[0], dark: maps[1] };
22
+ }
23
+
24
+ const namedColors = new Set(('aliceblue antiquewhite aqua aquamarine azure beige bisque black blanchedalmond blue blueviolet brown burlywood cadetblue chartreuse chocolate coral cornflowerblue cornsilk crimson cyan darkblue darkcyan darkgoldenrod darkgray darkgreen darkgrey darkkhaki darkmagenta darkolivegreen darkorange darkorchid darkred darksalmon darkseagreen darkslateblue darkslategray darkslategrey darkturquoise darkviolet deeppink deepskyblue dimgray dimgrey dodgerblue firebrick floralwhite forestgreen fuchsia gainsboro ghostwhite gold goldenrod gray green greenyellow grey honeydew hotpink indianred indigo ivory khaki lavender lavenderblush lawngreen lemonchiffon lightblue lightcoral lightcyan lightgoldenrodyellow lightgray lightgreen lightgrey lightpink lightsalmon lightseagreen lightskyblue lightslategray lightslategrey lightsteelblue lightyellow lime limegreen linen magenta maroon mediumaquamarine mediumblue mediumorchid mediumpurple mediumseagreen mediumslateblue mediumspringgreen mediumturquoise mediumvioletred midnightblue mintcream mistyrose moccasin navajowhite navy oldlace olive olivedrab orange orangered orchid palegoldenrod palegreen paleturquoise palevioletred papayawhip peachpuff peru pink plum powderblue purple rebeccapurple red rosybrown royalblue saddlebrown salmon sandybrown seagreen seashell sienna silver skyblue slateblue slategray slategrey snow springgreen steelblue tan teal thistle tomato transparent turquoise violet wheat white whitesmoke yellow yellowgreen').split(' '));
25
+ export function themeCss(tokens) {
26
+ const color = (value, seen = new Set()) => {
27
+ const alias = /^var\((--[\w-]+)\)$/.exec(value);
28
+ if (alias) { if (seen.has(alias[1])) return false; seen.add(alias[1]); return color(tokens.light.get(alias[1]) ?? '', seen); }
29
+ return namedColors.has(value.toLowerCase()) || /^(#|rgba?\(|hsla?\(|oklch\(|oklab\(|lab\(|lch\(|color\(|color-mix\(|(?:transparent|black|white|red|blue|green|rebeccapurple|orange|purple|pink|gray|grey|yellow|cyan|magenta|currentColor)$)/i.test(value);
30
+ };
31
+ const declarations = [...tokens.light].flatMap(([key, value]) => {
32
+ const theme = color(value) ? '--color-' + key.slice(2) : /^(--font-|--radius-|--shadow-)/.test(key) || (key.startsWith('--text-') && /^[-.\d]+(?:px|rem|em|ch)$/.test(value)) ? key : null;
33
+ return theme ? [`${theme}:var(${key});`] : [];
34
+ });
35
+ return `@theme { --color-*:initial; --text-*:initial; --font-*:initial; --radius-*:initial; --shadow-*:initial; --inset-shadow-*:initial; --drop-shadow-*:initial; --text-shadow-*:initial; }\n@theme inline reference { ${declarations.join('\n')} }`;
36
+ }