@whzxc/agent-design-gallery 0.9.0 → 0.13.1

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/README.md +19 -3
  2. package/package.json +4 -1
  3. package/public/annotations.js +816 -0
  4. package/public/app.js +245 -12
  5. package/public/assets.js +4 -13
  6. package/public/frame-identity.js +223 -0
  7. package/public/icons.js +1 -0
  8. package/public/index.html +3 -0
  9. package/public/selection.js +1 -1
  10. package/public/style.css +72 -2
  11. package/src/annotations.mjs +238 -0
  12. package/src/cli-output.mjs +49 -2
  13. package/src/cli.mjs +83 -12
  14. package/src/http.mjs +2 -1
  15. package/src/hub/instances.mjs +1 -1
  16. package/src/hub/registry.mjs +1 -1
  17. package/src/hub.mjs +2 -2
  18. package/src/server.mjs +59 -11
  19. package/src/service.mjs +1 -1
  20. package/src/toolkit/arch-git.mjs +19 -0
  21. package/src/toolkit/arch-overlay.mjs +1 -1
  22. package/src/toolkit/asset-rules.mjs +42 -3
  23. package/src/toolkit/build-store.mjs +5 -3
  24. package/src/toolkit/build-worker.mjs +5 -2
  25. package/src/toolkit/build.mjs +36 -14
  26. package/src/toolkit/commands.mjs +85 -22
  27. package/src/toolkit/config.mjs +8 -6
  28. package/src/toolkit/diff-inputs.mjs +5 -5
  29. package/src/toolkit/diff.mjs +18 -11
  30. package/src/toolkit/document.mjs +6 -6
  31. package/src/toolkit/frame-document.mjs +6 -0
  32. package/src/toolkit/frame-facets.mjs +167 -0
  33. package/src/toolkit/frame-identity.mjs +100 -0
  34. package/src/toolkit/frame-observation.mjs +147 -0
  35. package/src/toolkit/frame-primitives.mjs +85 -0
  36. package/src/toolkit/html.mjs +1 -0
  37. package/src/toolkit/impact-eligibility.mjs +136 -0
  38. package/src/toolkit/impact-inputs.mjs +52 -0
  39. package/src/toolkit/impact-output.mjs +46 -0
  40. package/src/toolkit/impact-proof.mjs +67 -0
  41. package/src/toolkit/impact-selection.mjs +96 -0
  42. package/src/toolkit/impact.mjs +382 -0
  43. package/src/toolkit/implementation-query.mjs +53 -0
  44. package/src/toolkit/input-generation.mjs +51 -0
  45. package/src/toolkit/inspect-encoding.mjs +459 -0
  46. package/src/toolkit/inspect-observation.mjs +56 -0
  47. package/src/toolkit/inspect-output.mjs +169 -0
  48. package/src/toolkit/inspect-styles.mjs +34 -0
  49. package/src/toolkit/inspect.d.ts +118 -0
  50. package/src/toolkit/inspect.mjs +125 -0
  51. package/src/toolkit/owner-observation.mjs +23 -189
  52. package/src/toolkit/owner-search.mjs +2 -2
  53. package/src/toolkit/owner.mjs +37 -45
  54. package/src/toolkit/part-diff.mjs +2 -0
  55. package/src/toolkit/part-snapshot.mjs +15 -23
  56. package/src/toolkit/project-index.mjs +100 -22
  57. package/src/toolkit/project.mjs +52 -6
  58. package/src/toolkit/results.mjs +2 -2
  59. package/src/toolkit/runtime.d.ts +7 -5
  60. package/src/toolkit/runtime.mjs +20 -7
  61. package/src/toolkit/token-reachability.mjs +71 -0
@@ -1,20 +1,23 @@
1
- import { readFile, realpath } from 'node:fs/promises';
1
+ import { readFile, realpath, readdir } from 'node:fs/promises';
2
2
  import { readFileSync } from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { listSources, archFiles, sourceDirectories, relative, loadTokens } from './project.mjs';
5
5
  import { tokenLocations } from './tokens.mjs';
6
6
  import { CliError } from '../cli-output.mjs';
7
- import { buildSource } from './build.mjs';
8
- import { createBuildStore } from './build-store.mjs';
7
+ import { createBuildStore, BuildPool } from './build-store.mjs';
9
8
  import { sourceFacts } from './source-facts.mjs';
10
9
  import { sidecar } from './arch.mjs';
11
10
  import { loadImplementationMap, validateImplementationMap } from './implementation-map.mjs';
12
11
  import { createIndexStore, indexDigest } from './index-store.mjs';
13
12
  import { defaultStateDirectory } from '../hub/registry.mjs';
14
13
  import { sourceRelationships } from '../../public/relationships.js';
14
+ import { entryTokenReachability } from './token-reachability.mjs';
15
+ import { identityVersion } from './frame-identity.mjs';
16
+ import { inspectVersion } from './inspect-styles.mjs';
17
+ import { frameDocument } from './frame-document.mjs';
15
18
  export { sourceFacts } from './source-facts.mjs';
16
19
 
17
- const collectorIdentity = indexDigest(Buffer.concat(await Promise.all(['project-index.mjs', 'source-facts.mjs', 'implementation-map.mjs', 'owner-locators.mjs', 'owner-observation.mjs', 'owner-colors.mjs', 'tokens.mjs', 'arch.mjs'].map(name => readFile(new URL(name, import.meta.url))))));
20
+ const collectorIdentity = indexDigest(Buffer.concat(await Promise.all(['project-index.mjs', 'source-facts.mjs', 'implementation-map.mjs', 'owner-locators.mjs', 'owner-observation.mjs', 'frame-observation.mjs', 'frame-facets.mjs', 'frame-primitives.mjs', 'frame-identity.mjs', 'inspect-styles.mjs', 'owner-colors.mjs', 'tokens.mjs', 'token-reachability.mjs', 'arch.mjs'].map(name => readFile(new URL(name, import.meta.url))))));
18
21
 
19
22
  export function discoverProject(config) {
20
23
  const tsx = listSources(config.design, sourceDirectories(config)).map(file => relative(config, file));
@@ -29,12 +32,31 @@ export function tokenFacts(config) {
29
32
  .map(item => ({ ...item, line: (item.theme === 'dark' && !item.inherited ? locations.dark : locations.light).get(name), references: [...item.declaration.matchAll(/var\(\s*(--[\w-]+)/g)].map(match => match[1]) })) }));
30
33
  }
31
34
 
32
- export async function openProjectIndex(config, { stateDirectory = defaultStateDirectory, persist = true } = {}) {
35
+ async function resolutionFiles(config, artifactDirectory) {
36
+ const files = [];
37
+ async function visit(directory) {
38
+ for (const entry of await readdir(directory, { withFileTypes: true })) {
39
+ if (['.git', '.adg', 'node_modules'].includes(entry.name)) continue;
40
+ const file = path.join(directory, entry.name);
41
+ if (file === config.output) continue;
42
+ if (entry.isDirectory()) await visit(file);
43
+ else if (!(artifactDirectory && !path.relative(artifactDirectory, file).startsWith('..') && !path.isAbsolute(path.relative(artifactDirectory, file)) && /\.(?:png|json)$/.test(file))) files.push(path.relative(config.design, file));
44
+ }
45
+ }
46
+ try { await visit(config.design); } catch (error) { if (error.code !== 'ENOENT') throw error; }
47
+ return files.sort();
48
+ }
49
+
50
+ export async function openProjectIndex(config, { stateDirectory = defaultStateDirectory, persist = true, fresh = false, artifactDirectory } = {}) {
33
51
  const inventory = discoverProject(config), root = await realpath(config.root), buildPromises = new Map();
34
52
  const directory = path.join(stateDirectory, 'cache', indexDigest(root), 'index-v1');
35
53
  const shards = await createIndexStore({ directory, persist });
36
54
  const buildDirectory = path.join(stateDirectory, 'cache', indexDigest(root), 'build');
37
55
  let storePromise, closed = false;
56
+ let freshPool;
57
+ const materializations = new Map();
58
+ const resolution = fresh ? await resolutionFiles(config, artifactDirectory) : null;
59
+ const physicalDesign = inventory.tsx.length ? await realpath(config.design) : null;
38
60
  const observedInputs = new Map(), requestedSources = new Set();
39
61
  const assertOpen = () => { if (closed) throw Error('Project index is closed.'); };
40
62
  async function getBuild(source) {
@@ -42,17 +64,42 @@ export async function openProjectIndex(config, { stateDirectory = defaultStateDi
42
64
  if (!inventory.tsx.includes(source)) throw Error(`Undiscovered TSX source ${source}.`);
43
65
  requestedSources.add(source);
44
66
  if (!buildPromises.has(source)) buildPromises.set(source, (async () => {
45
- if (!persist) return buildSource(config, path.join(config.root, source), { write: false, allowLegacy: false });
46
- storePromise ??= createBuildStore({ config: { ...config, sourceFiles: inventory.tsx }, cacheDirectory: buildDirectory });
47
- const built = await (await storePromise).get(path.relative(config.design, path.join(config.root, source)).split(path.sep).join('/'));
48
- for (const [name, hash] of Object.entries(built.dependencyHashes)) {
49
- if (observedInputs.has(name) && observedInputs.get(name) !== hash) throw new CliError('OWNER_INDEX_CHANGED', `Design dependency changed during query: ${name}.`);
50
- observedInputs.set(name, hash);
67
+ let built;
68
+ if (!persist) {
69
+ const {buildSource}=await import('./build.mjs');
70
+ const snapshot = new Map();
71
+ built = await buildSource(config, path.join(config.root, source), { write: false, allowLegacy: false, snapshot });
72
+ built.dependencyHashes = Object.fromEntries([...snapshot].map(([file, bytes]) => [path.relative(config.design, file), indexDigest(bytes === null ? 'missing\0' : Buffer.concat([Buffer.from('present\0'), bytes]))]));
73
+ } else {
74
+ storePromise ??= createBuildStore({ config: { ...config, sourceFiles: inventory.tsx }, cacheDirectory: buildDirectory });
75
+ built = await (await storePromise).get(path.relative(config.design, path.join(config.root, source)).split(path.sep).join('/'));
51
76
  }
52
- return built;
77
+ return observeDependencies(built);
53
78
  })().finally(() => buildPromises.delete(source)));
54
79
  return buildPromises.get(source);
55
80
  }
81
+ function observeDependencies(built) {
82
+ for (const [name, hash] of Object.entries(built.dependencyHashes)) {
83
+ if (observedInputs.has(name) && observedInputs.get(name) !== hash) throw new CliError('OWNER_INDEX_CHANGED', `Design dependency changed during query: ${name}.`);
84
+ observedInputs.set(name, hash);
85
+ }
86
+ return built;
87
+ }
88
+ function materialize(source) {
89
+ assertOpen();
90
+ if (!inventory.tsx.includes(source)) throw Error(`Undiscovered TSX source ${source}.`);
91
+ if (!materializations.has(source)) {
92
+ requestedSources.add(source); freshPool ??= new BuildPool();
93
+ materializations.set(source, freshPool.run({ config: { root, design: physicalDesign ?? config.design, output: config.output,
94
+ sources: config.sources, arch: config.arch, check: config.check, allowLegacy: false },
95
+ name: path.relative(physicalDesign ?? config.design, path.join(root, source)).split(path.sep).join('/') }, new AbortController().signal).then(built => {
96
+ observeDependencies(built);
97
+ for (const frame of built.frames) frame.document = theme => frameDocument(frame, theme, built.css);
98
+ return built;
99
+ }));
100
+ }
101
+ return materializations.get(source);
102
+ }
56
103
  async function cached(projection, inputs, collect) {
57
104
  const key = JSON.stringify({ version: 1, collectorIdentity, projection, inputs });
58
105
  const hit = await shards.get(key);
@@ -62,9 +109,25 @@ export async function openProjectIndex(config, { stateDirectory = defaultStateDi
62
109
  return {
63
110
  inventory,
64
111
  getBuild,
65
- async source(source) {
66
- const built = await getBuild(source);
67
- return cached('source', { source, build: built.inputHash ?? indexDigest(JSON.stringify({ ...built, frames: built.frames.map(({ document, ...frame }) => frame) })) }, () => sourceFacts(config, source, built));
112
+ materialize,
113
+ async releaseMaterializers() {
114
+ // A finite frame query keeps the built bytes, not an idle compiler isolate during observation.
115
+ const pool=freshPool;freshPool=undefined;await pool?.close();
116
+ },
117
+ async source(source, { tokens = false, fresh = false } = {}) {
118
+ const built = fresh ? await materialize(source) : await getBuild(source);
119
+ const inputs = fresh ? null : { source, build: built.inputHash ?? indexDigest(JSON.stringify({ ...built, frames: built.frames.map(({ document, ...frame }) => frame) })) };
120
+ const facts = fresh ? sourceFacts(config, source, built) : await cached('source', inputs, () => sourceFacts(config, source, built));
121
+ if (!tokens) return facts;
122
+ const collect = () => {
123
+ const scan = entryTokenReachability((built.cssBeforeTokens + built.cssAfterTokens).replace(/<\/style/gi, '<\\/style'), built.tokenCss);
124
+ return built.frames.map(frame => {
125
+ const reach = scan(frameDocument(frame, 'light', ''));
126
+ return { frame: frame.name, themes: ['light', 'dark'].map(theme => ({ theme, ...reach(theme) })) };
127
+ });
128
+ };
129
+ const tokenDependencies = fresh ? collect() : await cached('token-dependencies', inputs, collect);
130
+ return { ...facts, tokenDependencies };
68
131
  },
69
132
  tokens() { assertOpen(); return tokenFacts(config); },
70
133
  async mappings({ selected, map: supplied, ...selection } = {}) {
@@ -73,11 +136,22 @@ export async function openProjectIndex(config, { stateDirectory = defaultStateDi
73
136
  const map = supplied ?? await loadImplementationMap(config);
74
137
  return { map, ...await validateImplementationMap(config, map, { sources: inventory.tsx, selected, getBuild, ...selection }) };
75
138
  },
76
- async observation(source, built, frame, theme, environment, collect) {
139
+ async observation(source, built, frame, theme, environment, collect, { facets = ['owner','identity'], policy = null } = {}) {
77
140
  assertOpen();
78
141
  if (environment === null) return collect();
79
- const build = built.inputHash ?? indexDigest(JSON.stringify({ css: built.css, frame }));
80
- return cached('owner-observation', { source, build, frame: frame.name, theme, environment }, collect);
142
+ const coverage=[...new Set(facets)].sort();
143
+ const inputs={source,document:indexDigest(frameDocument(frame,theme,built.css)),
144
+ metadata:{width:frame.width??null,height:frame.height??null,parent:frame.parent??null},
145
+ theme,environment,policy,identityVersion,inspectVersion};
146
+ const keyFor=facets=>JSON.stringify({version:1,collectorIdentity,projection:'frame-observation',inputs,facets});
147
+ const key=keyFor(coverage), saved=await shards.get(key);
148
+ if(Array.isArray(saved?.facets) && Object.hasOwn(saved,'value') && saved.facets.every(f=>coverage.includes(f)) && coverage.every(f=>saved.facets.includes(f)))return saved.value;
149
+ const full=['a11y','color','identity','layout','owner','structure','text','typography'];
150
+ if(coverage.every(f=>full.includes(f)) && coverage.length<full.length){
151
+ const richer=await shards.get(keyFor(full));
152
+ if(Array.isArray(richer?.facets) && Object.hasOwn(richer,'value') && coverage.every(f=>richer.facets.includes(f)))return richer.value;
153
+ }
154
+ const value=await collect();await shards.put(key,{facets:coverage,value});return value;
81
155
  },
82
156
  async palette(tokens, theme, environment, collect) {
83
157
  assertOpen();
@@ -94,6 +168,8 @@ export async function openProjectIndex(config, { stateDirectory = defaultStateDi
94
168
  await shards.put(key, [...entries]); return value;
95
169
  },
96
170
  async verifyInputs() {
171
+ if (JSON.stringify(discoverProject(config)) !== JSON.stringify(inventory)) throw new CliError('OWNER_INDEX_CHANGED', 'Design source inventory changed during query.');
172
+ if (resolution && JSON.stringify(await resolutionFiles(config, artifactDirectory)) !== JSON.stringify(resolution)) throw new CliError('OWNER_INDEX_CHANGED', 'Design resolution inventory changed during query.');
97
173
  for (const [name, hash] of observedInputs) {
98
174
  let value;
99
175
  try { value = indexDigest(Buffer.concat([Buffer.from('present\0'), await readFile(path.join(config.design, name))])); }
@@ -108,20 +184,22 @@ export async function openProjectIndex(config, { stateDirectory = defaultStateDi
108
184
  try { text = await readFile(path.join(config.root, side), 'utf8'); } catch (error) { if (error.code !== 'ENOENT') throw error; }
109
185
  return cached('architecture', { source, text }, () => ({ source, sidecar: side, ...sidecar(text) }));
110
186
  },
111
- async relationships() {
187
+ async relationships({ facts: supplied, projectPaths = false } = {}) {
112
188
  const assets = await Promise.all(inventory.tsx.map(async source => {
113
- const facts = await this.source(source);
189
+ const facts = supplied?.get(source) ?? await this.source(source);
190
+ if (projectPaths) return { path: source, imports: facts.imports };
114
191
  const designRelative = file => path.relative(config.design, path.join(config.root, file)).split(path.sep).join('/');
115
192
  return { path: designRelative(source), imports: facts.imports.map(designRelative) };
116
193
  }));
117
194
  assets.push(...inventory.architecture.map(source => ({ path: source, imports: [] })));
118
195
  return sourceRelationships(assets);
119
196
  },
120
- stats: async () => ({ shards: shards.stats(), builds: storePromise ? (await storePromise).stats() : null, requestedSources: [...requestedSources] }),
197
+ stats: async () => ({ shards: shards.stats(), builds: storePromise ? (await storePromise).stats() : null,
198
+ materializations: freshPool?.stats() ?? null, requestedSources: [...requestedSources] }),
121
199
  async close() {
122
200
  closed = true;
123
201
  try { if (storePromise) await (await storePromise).close(); }
124
- finally { await shards.close(); }
202
+ finally { try { await freshPool?.close(); materializations.clear(); } finally { await shards.close(); } }
125
203
  },
126
204
  };
127
205
  }
@@ -71,7 +71,7 @@ export function init(config, log = console.log) {
71
71
  const sources=sourceDirectories(config), fresh=sources.some(name=>name!=='studies') &&
72
72
  !listSources(config.design,sources).length && !existsSync(path.join(config.design,'fixtures/example.ts'));
73
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"],
74
+ [path.join(config.root, 'adg.config.mjs'), "export default { requires: '>=0.5.0', design: 'design', output: 'output/design', check: { strictLayers: true, lifecycle: true } };\n"],
75
75
  [path.join(config.design, 'tokens.css'), starterTokens],
76
76
  ...[...sources.filter(name=>name!=='studies'), 'fixtures', 'art'].map(name => [path.join(config.design, name), null]),
77
77
  ...(fresh ? [
@@ -105,14 +105,60 @@ export function listSources(directory, sources = sourceDirectories({design:direc
105
105
  return sources.flatMap(name => {
106
106
  const base = path.join(directory, name);
107
107
  if (!existsSync(base)) return [];
108
- return readdirSync(base, { withFileTypes: true })
109
- .filter(entry => entry.isFile() && isSourcePath(`${name}/${entry.name}`, sources))
110
- .map(entry => path.join(base, entry.name));
108
+ const files = [], production = sources.filter(item => item !== 'studies'), moduleLayer = production.length >= 3 ? production[1] : null;
109
+ const addDirect = folder => {
110
+ for (const entry of readdirSync(folder, { withFileTypes: true })) {
111
+ const source = `${name}/${entry.name}`;
112
+ if (entry.isFile() && isSourcePath(source, sources)) files.push(path.join(folder, entry.name));
113
+ }
114
+ };
115
+ addDirect(base);
116
+ if (name === moduleLayer) for (const entry of readdirSync(base, { withFileTypes: true })) if (entry.isDirectory()) {
117
+ const folder = path.join(base, entry.name);
118
+ for (const child of readdirSync(folder, { withFileTypes: true })) {
119
+ const source = `${name}/${entry.name}/${child.name}`;
120
+ if (child.isFile() && isSourcePath(source, sources)) files.push(path.join(folder, child.name));
121
+ }
122
+ }
123
+ return files;
111
124
  }).sort();
112
125
  }
113
126
  export function isSourcePath(name, sources = defaultSources) {
114
- const slash = name.indexOf('/');
115
- return slash > 0 && sources.includes(name.slice(0, slash)) && /^[^/.][^/]*\.tsx$/.test(name.slice(slash + 1));
127
+ const parts = name.split('/'), layer = parts[0], production = sources.filter(item => item !== 'studies'), moduleLayer = production.length >= 3 ? production[1] : null;
128
+ if (!sources.includes(layer) || parts.length < 2 || parts.some(part => !part || part === '.' || part === '..')) return false;
129
+ if (!/^([^/.][^/]*)\.tsx$/.test(parts.at(-1))) return false;
130
+ return parts.length === 2 || layer === moduleLayer && parts.length === 3;
131
+ }
132
+
133
+ export function sourceFeature(name, sources = defaultSources) {
134
+ const parts = name.split('/'), production = sources.filter(item => item !== 'studies'), moduleLayer = production.length >= 3 ? production[1] : null;
135
+ if (parts[0] !== moduleLayer) return name;
136
+ return parts.length >= 3 ? `${parts[0]}/${parts[1]}` : name;
137
+ }
138
+
139
+ export function isFeatureInternal(name, sources = defaultSources) {
140
+ const parts = name.split('/'), production = sources.filter(item => item !== 'studies'), moduleLayer = production.length >= 3 ? production[1] : null;
141
+ return !!moduleLayer && parts[0] === moduleLayer && parts.length === 3 && parts.at(-1) !== 'index.tsx';
142
+ }
143
+
144
+ export function featureFolderProblems(directory, sources = sourceDirectories({design: directory})) {
145
+ const production = sources.filter(item => item !== 'studies'), moduleLayer = production.length >= 3 ? production[1] : null;
146
+ if (!moduleLayer) return [];
147
+ const base = path.join(directory, moduleLayer), problems = [];
148
+ if (!existsSync(base)) return problems;
149
+ for (const entry of readdirSync(base, { withFileTypes: true })) if (entry.isDirectory()) {
150
+ const folder = path.join(base, entry.name), index = path.join(folder, 'index.tsx');
151
+ if (!existsSync(index)) problems.push({ code: 'FEATURE_INDEX_MISSING', file: folder, message: `${moduleLayer}/${entry.name} is a feature folder without index.tsx; add the public entry before using internal files` });
152
+ for (const child of readdirSync(folder, { withFileTypes: true })) if (child.isDirectory()) {
153
+ problems.push({ code: 'FEATURE_SOURCE_NESTED', file: path.join(folder, child.name), message: `${moduleLayer}/${entry.name}/${child.name} is nested deeper than one feature level; keep source files directly beside index.tsx` });
154
+ }
155
+ }
156
+ return problems;
157
+ }
158
+
159
+ export function isFeatureEntry(name, sources = defaultSources) {
160
+ const parts = name.split('/'), production = sources.filter(item => item !== 'studies'), moduleLayer = production.length >= 3 ? production[1] : null;
161
+ return parts[0] !== moduleLayer || parts.length === 2 || parts.length === 3 && parts.at(-1) === 'index.tsx';
116
162
  }
117
163
  export function readGroups(directory, sources = sourceDirectories({design:directory})) {
118
164
  try {
@@ -3,9 +3,9 @@ import { CliError, classifyError } from '../cli-output.mjs';
3
3
  /** @typedef {'light' | 'dark'} Theme */
4
4
  /** @typedef {{source: string | null, frame: string | null, theme: Theme | null, line: number | null, column: number | null}} Location */
5
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 */
6
+ /** @typedef {{project: string, readOnly: boolean, complete: boolean, impact: object | null, sources: string[], summary: {sources: number, frames: number, evaluations: number, problems: number}, findings: Finding[]}} CheckData */
7
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 */
8
+ /** @typedef {{project: string, outputDirectory: string, complete: boolean, impact: object | null, base: {rev: string, sha: string} | null, captures: Capture[], deleted: string[]}} RenderData */
9
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
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
11
 
@@ -1,15 +1,17 @@
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
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; locale?: string; children?: Content }
5
- export interface IconProps { name: string; size?: number; class?: string }
4
+ export interface FrameProps { name: string; width?: number; height?: number; fixture?: string; capture?: Capture; parent?: FrameParent; note?: string; locale?: string; proposed?: string; children?: Content }
5
+ export interface IconProps { "data-adg-id"?: string; name: string; size?: number; class?: string }
6
6
  export function Frame(props: FrameProps): JSX.Element;
7
7
  export function Icon(props: IconProps): JSX.Element;
8
- export function jsx(type: unknown, props: unknown): JSX.Element;
9
- export { jsx as jsxs, jsx as jsxDEV };
8
+ export function jsx(type: unknown, props: unknown, key?: string | number): JSX.Element;
9
+ export { jsx as jsxs };
10
+ export function jsxDEV(type: unknown, props: unknown, key?: string | number, isStatic?: boolean, source?: { fileName: string; lineNumber: number; columnNumber: number }): JSX.Element;
10
11
  export function Fragment(props: { children?: Content }): JSX.Element;
11
12
  export namespace JSX {
12
13
  type Element = any;
14
+ interface IntrinsicAttributes { key?: string | number }
13
15
  interface ElementChildrenAttribute { children: {} }
14
- interface IntrinsicElements { [name: string]: { class?: string; children?: Content; [attribute: string]: unknown } }
16
+ interface IntrinsicElements { [name: string]: { class?: string; "data-adg-id"?: string; children?: Content; [attribute: string]: unknown } }
15
17
  }
@@ -1,5 +1,6 @@
1
1
  import { icons } from 'lucide';
2
- export const escape = value => String(value).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
2
+ import { escape } from './html.mjs';
3
+ export { escape };
3
4
  const voids = new Set('area base br col embed hr img input link meta param source track wbr'.split(' '));
4
5
  export const markup = html => ({ html, toString() { return this.html; } });
5
6
  export function children(value) {
@@ -15,26 +16,36 @@ export function attributes(props) {
15
16
  return ` ${key}="${escape(value === true ? '' : value)}"`;
16
17
  }).join('');
17
18
  }
19
+ const artworkSources = new Map();
20
+ export function registerArtwork(url, source) { artworkSources.set(url,source); return url; }
18
21
  const componentOwners = new WeakMap();
19
22
  export const componentOwner = component => componentOwners.get(component);
20
23
  export function registerComponent(component, source, name) {
21
24
  if (typeof component === 'function' && !componentOwners.has(component)) componentOwners.set(component, {source, export:name});
22
25
  }
26
+ const stampIdentity = (value, identity) => Array.isArray(value) ? value.map((item, root) => stampIdentity(item, {...identity, root})) : value?.withIdentity ? value.withIdentity(identity) : value;
23
27
  const stamp = (value, owner) => Array.isArray(value) ? value.map(item => stamp(item, owner)) : value?.withOwner ? value.withOwner(owner) : value;
24
- export const Fragment = ({ children: value }) => ({...markup(children(value)), withOwner:owner => Fragment({children:stamp(value,owner)})});
25
- export function jsx(type, props = {}) {
28
+ export const Fragment = ({ children: value }) => ({...markup(children(value)), withOwner:owner => Fragment({children:stamp(value,owner)}), withIdentity:identity => Fragment({children:stampIdentity(Array.isArray(value)?value:[value],identity)})});
29
+ export function jsx(type, props = {}, key = props.key) {
30
+ if (key !== undefined && key !== null && !(typeof key === 'string' && key.length || typeof key === 'number' && Number.isFinite(key))) throw Error('JSX key must be a nonempty string or finite number');
31
+ props={...props,key:undefined};
26
32
  if (typeof type === 'function') {
27
33
  const value = type(props), owner = componentOwners.get(type);
28
- return owner ? stamp(value, owner) : value;
34
+ const owned = owner ? stamp(value, owner) : value;
35
+ return key == null ? owned : stampIdentity(owned, {key, ...(owner ? {owner} : {})});
29
36
  }
30
37
  if (['script', 'style'].includes(type.toLowerCase())) throw Error(`Forbidden <${type}>; use tokens and utility classes`);
38
+ const art=artworkSources.get(props.src ?? props.href ?? props['xlink:href']);
39
+ if(art)props={...props,'data-adg-art':art};
40
+ if (key != null) props = {...props, 'data-adg-keys':JSON.stringify([...(props['data-adg-keys'] ? JSON.parse(props['data-adg-keys']) : []), {key}])};
31
41
  const result = markup(`<${type}${attributes(props)}>${voids.has(type) ? '' : children(props.children) + `</${type}>`}`);
32
42
  result.withOwner = owner => jsx(type, {...props, 'data-adg-owners':JSON.stringify([...(props['data-adg-owners'] ? JSON.parse(props['data-adg-owners']) : []), owner])});
43
+ result.withIdentity = identity => jsx(type, {...props, key:undefined, 'data-adg-keys':JSON.stringify([...(props['data-adg-keys'] ? JSON.parse(props['data-adg-keys']) : []), identity])});
33
44
  return result;
34
45
  }
35
46
  export const jsxs = jsx;
36
47
  export function jsxDEV(type, props, key, isStatic, source) {
37
- try { return jsx(type, props); }
48
+ try { return jsx(type, props, key); }
38
49
  catch (error) { if (!error.located && source) { error.message = `${source.fileName}:${source.lineNumber}:${source.columnNumber}: ${error.message}`; error.located = true; } throw error; }
39
50
  }
40
51
  export function Frame({ children: content, ...props }) { return { frame: true, ...props, html: children(content) }; }
@@ -42,14 +53,16 @@ export function Icon({ name, size = 16, class: className, ...props }) {
42
53
  const key = name.split('-').map(s => s[0].toUpperCase() + s.slice(1)).join('');
43
54
  const geometry = icons[key];
44
55
  if (!geometry) throw Error(`Unknown Lucide icon ${name}`);
45
- 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)) });
56
+ 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, 'data-adg-icon':name, children: geometry.map(([tag, attrs]) => jsx(tag, attrs)) });
46
57
  }
47
- export function artwork(source, props) {
58
+ export function artwork(source, props, provenance) {
59
+ if (provenance) props={...props,'data-adg-art':provenance};
48
60
  const match = source.match(/<svg\b([^>]*)>([\s\S]*)<\/svg>/i);
49
61
  if (!match) throw Error('Invalid SVG artwork');
50
62
  let attrs = match[1];
51
63
  for (const key of Object.keys(props)) attrs = attrs.replace(new RegExp(`\\s${key}\\s*=\\s*(["']).*?\\1`, 'g'), '');
52
64
  const result = markup(`<svg${attrs}${attributes(props)}>${match[2]}</svg>`);
65
+ result.withIdentity = identity => artwork(source, {...props, 'data-adg-keys':JSON.stringify([...(props['data-adg-keys'] ? JSON.parse(props['data-adg-keys']) : []), identity])}, provenance);
53
66
  result.withOwner = owner => artwork(source, {...props, 'data-adg-owners':JSON.stringify([...(props['data-adg-owners'] ? JSON.parse(props['data-adg-owners']) : []), owner])});
54
67
  return result;
55
68
  }
@@ -0,0 +1,71 @@
1
+ import { decodeHTML } from 'entities';
2
+ import { parseTokens } from './tokens.mjs';
3
+
4
+ export function decodeCssEscapes(text) {
5
+ return text.replace(/\\(?:([\da-f]{1,6})(?:\r\n|[ \t\r\n\f])?|(\r\n|[\r\n\f])|([\s\S]))/gi, (_, hex, newline, char) => {
6
+ if (hex) {
7
+ const code = Number.parseInt(hex, 16);
8
+ return String.fromCodePoint(!code || code > 0x10ffff || code >= 0xd800 && code <= 0xdfff ? 0xfffd : code);
9
+ }
10
+ return newline ? '' : char;
11
+ });
12
+ }
13
+
14
+ function forms(text) {
15
+ const css = decodeCssEscapes(text), html = decodeHTML(text);
16
+ return [...new Set([text, css, html, decodeCssEscapes(html), decodeHTML(css)])];
17
+ }
18
+ // Decoding only adds candidates; raw spellings, text and inactive rules still participate.
19
+ const identifiers = text => [...new Set(forms(text).flatMap(value => [...value.matchAll(/--[\p{L}\p{N}_-]+/gu)].map(match => match[0])))];
20
+
21
+ function unbalancedVar(value) {
22
+ const stack = [];
23
+ let quote = null;
24
+ for (let i = 0; i < value.length; i++) {
25
+ const char = value[i];
26
+ if (char === '\\') { i++; continue; }
27
+ if (quote) { if (char === quote) quote = null; continue; }
28
+ if (char === '"' || char === "'") { quote = char; continue; }
29
+ if (char === '(') stack.push(/\bvar$/i.test(value.slice(Math.max(0, i - 3), i)));
30
+ else if (char === ')') stack.pop();
31
+ }
32
+ return stack.includes(true);
33
+ }
34
+
35
+ /** Conservative names/declarations (including absence), shared by candidates and later proofs. */
36
+ export function tokenReachability(document, tokenSource, theme) {
37
+ return reachability(identifiers(document).sort(), tokenSource, theme);
38
+ }
39
+
40
+ export function entryTokenReachability(css, tokenSource) {
41
+ const shared = identifiers(css);
42
+ let parsed;
43
+ try { parsed = parseTokens(tokenSource); } catch {}
44
+ return markup => {
45
+ const roots = [...new Set([...shared, ...identifiers(markup)])].sort();
46
+ return theme => reachability(roots, tokenSource, theme, parsed);
47
+ };
48
+ }
49
+
50
+ function reachability(roots, tokenSource, theme, parsed) {
51
+ let tokens, definitions;
52
+ const result = (mode, names, via, fallbackReasons) => ({ mode, names, via,
53
+ declarations: definitions ? Object.fromEntries(names.map(name => [name, definitions.get(name) ?? null])) : {}, fallbackReasons });
54
+ const fallback = reason => result('full_sheet', [...new Set([...roots, ...identifiers(tokenSource)])].sort(), {}, [reason]);
55
+ try { tokens = parsed ?? parseTokens(tokenSource); } catch { return fallback('tokens_parse_failed'); }
56
+ definitions = new Map(tokens.light);
57
+ if (theme === 'dark') for (const [name, value] of tokens.dark) definitions.set(name, value);
58
+ const via = {}, queue = roots.map(name => ({ name, route: [] }));
59
+ for (let i = 0; i < queue.length; i++) {
60
+ const { name, route } = queue[i];
61
+ if (Object.hasOwn(via, name)) continue;
62
+ via[name] = route;
63
+ const value = definitions.get(name);
64
+ if (value === undefined) continue;
65
+ const variants = forms(value);
66
+ if (variants.some(unbalancedVar)) return fallback('unbalanced_var');
67
+ const targets = new Set(variants.flatMap(value => [...value.matchAll(/\bvar\(\s*(--[\p{L}\p{N}_-]+)/giu)].map(match => match[1])));
68
+ for (const target of targets) queue.push({ name: target, route: [...route, name] });
69
+ }
70
+ return result('reachable_declarations', Object.keys(via).sort(), via, []);
71
+ }