@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
package/src/http.mjs CHANGED
@@ -9,10 +9,11 @@ export function directLocal(request) {
9
9
  export const viewerFiles = {
10
10
  '/access.css': 'access.css', '/switcher.js': 'switcher.js', '/switcher.css': 'switcher.css', '/instance-actions.js': 'instance-actions.js',
11
11
  '/': 'index.html', '/index.html': 'index.html', '/app.js': 'app.js', '/auth.js': 'auth.js', '/favicon.svg': 'favicon.svg',
12
- '/assets.js': 'assets.js', '/icons.js': 'icons.js', '/layout.js': 'layout.js', '/labels.js': 'labels.js',
12
+ '/assets.js': 'assets.js', '/frame-identity.js': 'frame-identity.js', '/icons.js': 'icons.js', '/layout.js': 'layout.js', '/labels.js': 'labels.js',
13
13
  '/arrangement.js': 'arrangement.js', '/arrangement-worker.js': 'arrangement-worker.js',
14
14
  '/relationships.js': 'relationships.js', '/selection.js': 'selection.js', '/style.css': 'style.css', '/tokens.css': 'tokens.css',
15
15
  '/token-catalog.js': 'token-catalog.js',
16
+ '/annotations.js': 'annotations.js',
16
17
  '/view-route.js': 'view-route.js',
17
18
  };
18
19
  export const viewerFile = pathname => isViewPath(pathname) ? 'index.html' : viewerFiles[pathname];
@@ -8,7 +8,7 @@ import { setTimeout as delay } from 'node:timers/promises';
8
8
  import { loadConfig, VERSION } from '../toolkit/config.mjs';
9
9
 
10
10
  // Shared instance discovery does not load or start the resident hub.
11
- const defaultStateDirectory = path.join(process.env.XDG_STATE_HOME || path.join(os.homedir(), '.local/state'), 'agent-design-gallery');
11
+ const defaultStateDirectory = path.join(os.homedir(), '.agent-design-gallery');
12
12
  const exec = promisify(execFile);
13
13
  const validId = id => typeof id === 'string' && /^[A-Za-z0-9_-]{1,128}$/.test(id);
14
14
  const validPort = port => Number.isInteger(port) && port > 0 && port <= 65535;
@@ -9,7 +9,7 @@ import { listSources, archFiles } from '../toolkit/project.mjs';
9
9
  import { CliError } from '../cli-output.mjs';
10
10
 
11
11
  const exec = promisify(execFile);
12
- export const defaultStateDirectory = path.join(process.env.XDG_STATE_HOME || path.join(os.homedir(), '.local/state'), 'agent-design-gallery');
12
+ export const defaultStateDirectory = path.join(os.homedir(), '.agent-design-gallery');
13
13
  const canonical = async (directory, cwd = process.cwd()) => {
14
14
  try { return await realpath(path.resolve(cwd, directory.replace(/^~(?=$|[\\/])/, os.homedir()))); }
15
15
  catch (error) {
package/src/hub.mjs CHANGED
@@ -52,7 +52,7 @@ export async function startHub({ port = 4310, stateDirectory = defaultStateDirec
52
52
  if (url.pathname === '/api/roots' && request.method === 'GET') return json(response, 200, await listRoots(stateDirectory));
53
53
  if (url.pathname === '/api/rescan' && request.method === 'POST') return json(response, 200, (await scanRoots(undefined, stateDirectory)).data.roots);
54
54
  if (route) {
55
- if (!read && !(request.method === 'POST' && (route[2] === '/preferences' || route[2] === '/catalog' || /^\/(metadata|preview)\/[a-f0-9]{64}$/.test(route[2]??'')))) return json(response, 405, { error: 'Only viewer preferences and derived cache data may be changed.' });
55
+ if (!read && !(request.method === 'POST' && (route[2] === '/api/annotations' || route[2] === '/preferences' || route[2] === '/catalog' || /^\/(metadata|preview)\/[a-f0-9]{64}$/.test(route[2]??'')))) return json(response, 405, { error: 'Only annotations, viewer preferences and derived cache data may be changed.' });
56
56
  if (instanceRoute) {
57
57
  const instance = (await listInstances(stateDirectory)).find(item => item.id === instanceRoute[1]);
58
58
  if (!instance) return json(response, 404, { error: 'Instance is no longer live.' });
@@ -71,7 +71,7 @@ export async function startHub({ port = 4310, stateDirectory = defaultStateDirec
71
71
  const project = (await listProjects(stateDirectory)).find(item => item.slug === slug);
72
72
  if (!project) throw new CliError('PROJECT_NOT_FOUND','Unknown project; run adg root scan.');
73
73
  if (project.error) { await loadConfig(project.path); throw new CliError('CONFIG_INVALID',project.error); }
74
- entry.viewer = await startViewer({ directory: project.design, stateDirectory: path.join(stateDirectory, 'projects', slug), onDiagnostic, onFatal });
74
+ entry.viewer = await startViewer({ directory: project.design, annotationStateDirectory: stateDirectory, stateDirectory: path.join(stateDirectory, 'projects', slug), onDiagnostic, onFatal });
75
75
  return entry.viewer;
76
76
  })();
77
77
  viewers.set(slug, entry);
package/src/server.mjs CHANGED
@@ -1,4 +1,5 @@
1
1
  // Adapted from ARC's MIT-licensed tooling/design-server.mjs.
2
+ import { annotations, annotationFile, readAnnotationContext } from './annotations.mjs';
2
3
  import { randomUUID, createHash } from 'node:crypto';
3
4
  import { directLocal, viewerFile, shell, json } from './http.mjs';
4
5
  import { createServer } from "node:http";
@@ -19,7 +20,7 @@ import { createBuildStore } from './toolkit/build-store.mjs';
19
20
  import { CliError, asCliError } from './cli-output.mjs';
20
21
  import { cleanup } from './toolkit/results.mjs';
21
22
  import { createViewerCache } from './viewer-cache.mjs';
22
- import { refreshTypes, archFiles, isSourcePath, readGroups, sourceDirectories } from './toolkit/project.mjs';
23
+ import { refreshTypes, archFiles, isSourcePath, readGroups, sourceDirectories, isFeatureInternal } from './toolkit/project.mjs';
23
24
  import { loadConfig } from './toolkit/config.mjs';
24
25
  import { parseTokens } from './toolkit/tokens.mjs';
25
26
  import { sourceRelationships } from '../public/relationships.js';
@@ -30,15 +31,13 @@ function tokenSourcePath(directory, project) {
30
31
  const base = project.design === directory ? project.root : path.dirname(directory);
31
32
  return path.relative(base, path.join(directory, tokenFile)).split(path.sep).join('/');
32
33
  }
33
- const viewerVersion = Promise.all(['assets.js','layout.js','selection.js','arrangement.js','arrangement-worker.js'].map(file => readFile(new URL('../public/'+file,import.meta.url)))).then(parts => digest(Buffer.concat(parts)));
34
- const defaultState = path.join(
35
- process.env.XDG_STATE_HOME || path.join(os.homedir(), ".local/state"),
36
- "agent-design-gallery",
37
- );
34
+ const viewerVersion = Promise.all(['assets.js','frame-identity.js','layout.js','selection.js','arrangement.js','arrangement-worker.js'].map(file => readFile(new URL('../public/'+file,import.meta.url)))).then(parts => digest(Buffer.concat(parts)));
35
+ const defaultState = path.join(os.homedir(), ".agent-design-gallery");
38
36
  export async function startServer({
39
37
  directory,
40
38
  port = 0,
41
39
  stateDirectory = defaultState,
40
+ annotationStateDirectory = stateDirectory,
42
41
  fixtures = null,
43
42
  readOnly = false,
44
43
  instanceId = randomUUID(),
@@ -87,6 +86,25 @@ export async function startServer({
87
86
  for (const client of clients)
88
87
  client.write(`data: ${JSON.stringify(data)}\n\n`);
89
88
  };
89
+ let annotationStamp = null;
90
+ async function readAnnotationStamp() {
91
+ if (!activeProject) return null;
92
+ try {
93
+ const info = await stat(annotationFile(activeProject.root, annotationStateDirectory));
94
+ return `${info.mtimeMs}-${info.size}`;
95
+ } catch (e) {
96
+ return e.code === 'ENOENT' ? 'missing' : null;
97
+ }
98
+ }
99
+ const annotationTimer = setInterval(async () => {
100
+ if (closing || !clients.size || !activeProject) return;
101
+ const next = await readAnnotationStamp();
102
+ if (next && next !== annotationStamp) {
103
+ annotationStamp = next;
104
+ emit({ annotations: true });
105
+ }
106
+ }, 800);
107
+ annotationTimer.unref?.();
90
108
  const diagnostic = (error, name = null, fallback = 'SOURCE_BUILD_FAILED') => {
91
109
  if (error.name === 'AbortError') return;
92
110
  const at = error.location ?? error.errors?.[0]?.location ?? error.cause?.errors?.[0]?.location;
@@ -231,6 +249,7 @@ export async function startServer({
231
249
  watcher = nextWatcher;
232
250
  activeProject=project;watchArch(project,next);
233
251
  root = next;
252
+ annotationStamp = await readAnnotationStamp();
234
253
  tokenSource = hasTokens ? tokenSourcePath(next, project) : null;
235
254
  codePaths=nextCode;
236
255
  sources = nextSources;
@@ -319,10 +338,12 @@ export async function startServer({
319
338
  }
320
339
  const baseManifest = () => ({
321
340
  directory: root ?? null,
341
+ projectRoot: activeProject?.root ?? null,
342
+ sourcePrefix: activeProject && root ? path.relative(activeProject.root, root).split(path.sep).join('/') : '',
322
343
  label: root
323
344
  ? path.basename(root) === "design" ? path.basename(path.dirname(root)) : path.basename(root)
324
345
  : "Agent Design Gallery",
325
- assets: [...files.values()].sort((a, b) => a.path.localeCompare(b.path)),
346
+ assets: [...files.values()].filter(asset => !isFeatureInternal(asset.path, sources)).sort((a, b) => a.path.localeCompare(b.path)),
326
347
  groups,
327
348
  revision,
328
349
  recent: state.recent,
@@ -337,7 +358,7 @@ export async function startServer({
337
358
  if (Number.isFinite(fixtures.assetModifiedAt)) data.assets = data.assets.map(a => ({...a,modifiedAt:fixtures.assetModifiedAt}));
338
359
  const preset = fixtures.states[name];
339
360
  if (!preset) throw new Error(`Unknown fixture ${name}; choose a declared ADG fixture.`);
340
- return { ...data, ...(preset.empty ? { directory: null, assets: [], groups: [] } : {}),
361
+ return { ...data, ...(preset.empty ? { directory: null, projectRoot: null, sourcePrefix: '', assets: [], groups: [] } : {}),
341
362
  label: 'agent-remote-control', recent: fixtures.recent, view: null, theme: preset.themeChoice ?? preset.theme,
342
363
  sidebar: preset.sidebar, inspector: !!preset.inspector, fixture: { name, ...preset } };
343
364
  }
@@ -427,8 +448,9 @@ export async function startServer({
427
448
  const built=base&&name.endsWith('.mmd')?await overlayBuild(name,base):await sourceBuild(name);
428
449
  const frames = onlyFrame ? built.frames.filter(frame => frame.name === onlyFrame) : built.frames;
429
450
  if (!frames.length && onlyFrame) throw new CliError('FRAME_NOT_FOUND', `Frame ${onlyFrame} does not exist in ${name}.`);
451
+ const projectSource = activeProject ? path.relative(activeProject.root, path.join(root, name)).split(path.sep).join('/') : name;
430
452
  return {version:built.hash,imports:built.imports,dependencies:built.dependencies,
431
- body:JSON.stringify({format:'tsx',hash:built.hash,css:built.css,imports:built.imports,component:!onlyFrame && name.endsWith('.tsx') && !name.startsWith('surfaces/'),frames})};
453
+ body:JSON.stringify({format:'tsx',hash:built.hash,projectSource,css:built.css,imports:built.imports,component:!onlyFrame && name.endsWith('.tsx') && !name.startsWith('surfaces/'),frames})};
432
454
  }
433
455
  let content = await readFile(path.join(root, name), "utf8");
434
456
  content = content.replace(
@@ -498,6 +520,30 @@ export async function startServer({
498
520
  const file = ['GET', 'HEAD'].includes(request.method) && viewerFile(url.pathname);
499
521
  if (file) return await shell(request, response, file, request.headers['x-adg-viewer-base']);
500
522
  if (!directLocal(request)) return json(response, 401, { error: 'Unauthorized' });
523
+ if (url.pathname === '/api/annotations') {
524
+ if (request.method !== 'GET' && request.method !== 'POST') return json(response,405,{error:'Use GET or POST.'});
525
+ if (request.method === 'POST' && request.headers.origin && ![`http://${host}`,`https://${host}`].includes(request.headers.origin)) return json(response,403,{error:'Cross-origin request refused.'});
526
+ const config = await loadConfig(root);
527
+ if (request.method === 'GET') {
528
+ if (url.searchParams.has('id')) {
529
+ const id = url.searchParams.get('id');
530
+ const result = url.searchParams.get('context') === '1'
531
+ ? await readAnnotationContext(config, annotationStateDirectory, id)
532
+ : await annotations(config.root, annotationStateDirectory, 'read', { id });
533
+ return json(response, 200, result);
534
+ }
535
+ const status = url.searchParams.get('status') ?? 'all';
536
+ return json(response, 200, await annotations(config.root, annotationStateDirectory, 'list', { status }));
537
+ }
538
+ const input = await body(request);
539
+ const result = await annotations(config.root, annotationStateDirectory, input.action, {
540
+ ...input,
541
+ ...(input.action === 'reply' && !input.author ? { author: 'user' } : {}),
542
+ });
543
+ annotationStamp = await readAnnotationStamp();
544
+ emit({ annotations: true });
545
+ return json(response, 200, result);
546
+ }
501
547
  if(url.pathname==='/api/cache-stats'&&request.method==='GET')return json(response,200,{process:process.memoryUsage(),builds:buildStore?.stats(),viewer:viewerCache?.stats()});
502
548
  if (url.pathname === '/api/health' && request.method === 'GET') return json(response, 200, { id: instanceId, capabilities: { keyAuth: 1 } });
503
549
  if (request.method === "POST") {
@@ -566,6 +612,7 @@ export async function startServer({
566
612
  return;
567
613
  }
568
614
  if (url.pathname === "/events") {
615
+ annotationStamp ??= await readAnnotationStamp();
569
616
  response.writeHead(200, {
570
617
  "Content-Type": "text/event-stream",
571
618
  "Cache-Control": "no-store",
@@ -594,7 +641,7 @@ export async function startServer({
594
641
  type = "application/json";
595
642
  } else if (url.pathname.startsWith("/asset/")) {
596
643
  const name = decodeURIComponent(url.pathname.slice(7));
597
- if (!files.has(name)) {
644
+ if (!files.has(name) || isFeatureInternal(name, sources)) {
598
645
  response.writeHead(404);
599
646
  response.end("Unknown SVG.");
600
647
  return;
@@ -633,6 +680,7 @@ export async function startServer({
633
680
  const close = () => closePromise ??= (async () => {
634
681
  closing = true;
635
682
  clearTimeout(refreshTimer);
683
+ clearInterval(annotationTimer);
636
684
  let primary;
637
685
  for (const step of [
638
686
  async () => { watcher?.close(); },
@@ -673,7 +721,7 @@ export async function startServer({
673
721
  return { id: instanceId, directory: root, stateDirectory:path.resolve(stateDirectory), url: `http://127.0.0.1:${server.address().port}/`, port: server.address().port, close,
674
722
  cacheStats:()=>({builds:buildStore?.stats(),viewer:viewerCache?.stats()}),
675
723
  stats: () => {
676
- const entries = [...files.keys()].filter(name => /\.(tsx|mmd)$/.test(name));
724
+ const entries = [...files.keys()].filter(name => /\.(tsx|mmd)$/.test(name) && !isFeatureInternal(name, sources));
677
725
  return { sourceCount: entries.length, frameCount: entries.every(name => frameCounts.has(name)) ? entries.reduce((n, name) => n + frameCounts.get(name), 0) : null };
678
726
  } };
679
727
  }
package/src/service.mjs CHANGED
@@ -68,7 +68,7 @@ async function migrateService(values, { home, run, nodePath, cliPath, uid, outpu
68
68
  const argument = flag => args.includes(flag) ? args[args.indexOf(flag) + 1] : undefined;
69
69
  const base = process.env.XDG_STATE_HOME || path.join(home, '.local/state');
70
70
  const oldState = path.resolve(argument('--state-dir') ?? path.join(base, 'svg-design-gallery'));
71
- const newState = path.resolve(values['state-dir'] ?? path.join(base, 'agent-design-gallery'));
71
+ const newState = path.resolve(values['state-dir'] ?? path.join(home, '.agent-design-gallery'));
72
72
  const data = { complete: false, from: {label:oldLabel,stateDirectory:oldState,plist:oldAgent},
73
73
  to: {label:SERVICE_LABEL,stateDirectory:newState,plist:newAgent}, changes: [], keyPrefixUpdated:false, references:[], service:null };
74
74
  const warnings = [];
@@ -150,6 +150,25 @@ export async function sourceRenames(base) {
150
150
  }
151
151
  return renames;
152
152
  }
153
+
154
+ /** Actual endpoint changes; working-tree mode includes staged, unstaged and untracked paths. */
155
+ export async function revisionChanges(base, head = null) {
156
+ const fields = (await git(base.root, ['diff', '--name-status', '-z', '--find-renames', base.sha, ...(head ? [head.sha] : []), '--'])).split('\0');
157
+ const changes = [];
158
+ for (let i = 0; i < fields.length - 1;) {
159
+ const code = fields[i++], first = fields[i++];
160
+ if (code.startsWith('R') || code.startsWith('C')) {
161
+ const second = fields[i++];
162
+ changes.push(code.startsWith('R') ? { before: first, after: second, status: 'renamed' } : { before: null, after: second, status: 'added' });
163
+ } else changes.push({ before: code === 'A' ? null : first, after: code === 'D' ? null : first,
164
+ status: code === 'A' ? 'added' : code === 'D' ? 'deleted' : code === 'T' ? 'type_changed' : 'modified' });
165
+ }
166
+ if (!head) {
167
+ const names = (await git(base.root, ['ls-files', '--others', '--exclude-standard', '-z'])).split('\0').filter(Boolean);
168
+ for (const name of names) if (!changes.some(change => change.after === name)) changes.push({ before: null, after: name, status: 'added' });
169
+ }
170
+ return changes.sort((a, b) => (a.after ?? a.before) < (b.after ?? b.before) ? -1 : (a.after ?? a.before) > (b.after ?? b.before) ? 1 : 0);
171
+ }
153
172
  export async function resolveBase(config, rev) {
154
173
  if(typeof rev!=='string'||!rev.trim())throw new CliError('USAGE_INVALID', 'Set --base to a Git revision, for example HEAD.');
155
174
  let root;
@@ -2,7 +2,7 @@ import { parse } from 'pele';
2
2
  import { buildArch, inspectArch, vocabulary } from './arch.mjs';
3
3
  import { readFileSync } from 'node:fs';
4
4
  import { readBase } from './arch-git.mjs';
5
- import { escape } from './runtime.mjs';
5
+ import { escape } from './html.mjs';
6
6
 
7
7
  export const diffClasses=['added','changed','removed'];
8
8
  const words=value=>(Array.isArray(value)?value.join(' '):value??'').split(/[\s,]+/).filter(Boolean);
@@ -1,14 +1,53 @@
1
+ import { isFeatureEntry, sourceFeature } from './project.mjs';
2
+
1
3
  // Production sources are ordered from lower to higher layers. Studies are explorations.
2
- export function importDirectionViolations(graph, sources) {
3
- const rank=new Map(sources.filter(name=>name!=='studies').map((name,index)=>[name,index]));
4
+ export function importDirectionViolations(graph, sources, { strictLayers = false } = {}) {
5
+ const production=sources.filter(name=>name!=='studies'), rank=new Map(production.map((name,index)=>[name,index])), moduleLayer=production.length >= 3 ? production[1] : null, topLayer=production.at(-1);
4
6
  const violations=[];
5
7
  for (const source of Object.keys(graph).sort()) {
6
8
  const from=source.split('/')[0];
7
9
  if (!rank.has(from)) continue;
8
10
  for (const target of [...new Set(graph[source].uses)].sort()) {
9
11
  const to=target.split('/')[0];
10
- if (rank.has(to) && rank.get(to)>rank.get(from)) violations.push({source,target,from,to});
12
+ if (!rank.has(to)) continue;
13
+ const sameLayer=rank.get(to)===rank.get(from), crossFeature=sameLayer && rank.get(from)===rank.get(moduleLayer) && sourceFeature(source,sources)!==sourceFeature(target,sources);
14
+ const surfaceInternal=from===topLayer && to===moduleLayer && !isFeatureEntry(target,sources);
15
+ const sameLayerViolation=sameLayer && rank.get(from)>0 && (rank.get(from)!==rank.get(moduleLayer) || crossFeature);
16
+ if (rank.get(to)>rank.get(from) || (strictLayers && (sameLayerViolation || surfaceInternal))) {
17
+ violations.push({source,target,from,to,sameLayer,featureBoundary:crossFeature||surfaceInternal});
18
+ }
11
19
  }
12
20
  }
13
21
  return violations;
14
22
  }
23
+
24
+ // A component is a library asset only when distinct higher-layer sources reach it.
25
+ // Walk the resolved source graph backwards so component-to-component indirection
26
+ // and feature/surface transitive use are counted without treating its own frames
27
+ // as consumers.
28
+ export function singleConsumerComponents(graph, sources, partsBySource) {
29
+ const production = sources.filter(name => name !== 'studies');
30
+ const rank = new Map(production.map((name, index) => [name, index]));
31
+ const reverse = new Map();
32
+ for (const [source, row] of Object.entries(graph)) for (const target of new Set(row.uses ?? [])) {
33
+ const list = reverse.get(target) ?? []; list.push(source); reverse.set(target, list);
34
+ }
35
+ const warnings = [];
36
+ for (const [source, parts] of Object.entries(partsBySource)) {
37
+ const layer = source.split('/')[0];
38
+ if (layer !== production[0] || !rank.has(layer)) continue;
39
+ for (const part of parts) {
40
+ const consumers = new Set();
41
+ const queue = [source], seen = new Set([source]);
42
+ while (queue.length) for (const importer of reverse.get(queue.shift()) ?? []) {
43
+ if (seen.has(importer)) continue;
44
+ seen.add(importer);
45
+ const importerLayer = importer.split('/')[0];
46
+ if (importerLayer === layer) queue.push(importer);
47
+ else if (rank.has(importerLayer) && rank.get(importerLayer) > rank.get(layer)) consumers.add(sourceFeature(importer, sources));
48
+ }
49
+ if (consumers.size < 2) warnings.push({ code: 'SINGLE_CONSUMER_COMPONENT', source, part, consumers: [...consumers].sort(), message: `${source}#${part} is reached by ${consumers.size} distinct higher-layer source${consumers.size === 1 ? '' : 's'}; move it back to its feature or add another feature consumer` });
50
+ }
51
+ }
52
+ return warnings;
53
+ }
@@ -12,7 +12,7 @@ const aborted = () => Object.assign(new Error('Build superseded'), { name: 'Abor
12
12
  const memoryLimit = 32 * 1024 * 1024, diskLimit = 256 * 1024 * 1024;
13
13
  const workerLimit = 2, recycleAfter = 32;
14
14
 
15
- class BuildPool {
15
+ export class BuildPool {
16
16
  slots = new Set(); retiring = new Set(); queue = []; nextId = 0; closed = false;
17
17
  counters = { attempts: 0, spawned: 0, recycled: 0, cancelled: 0 };
18
18
  run(payload, signal) {
@@ -113,7 +113,7 @@ export async function createBuildStore({ config, cacheDirectory }) {
113
113
  const workerConfig = { root: await realpath(config.root), design, output: config.output, sources: config.sources, arch:config.arch, check:config.check, ...(config.overlay?{overlay:config.overlay}:{}) };
114
114
  const require = createRequire(import.meta.url);
115
115
  const fingerprint = digest(Buffer.concat(await Promise.all([
116
- ...['../../package.json', './build.mjs', './runtime.mjs', './tokens.mjs', './text.mjs', './project.mjs', './build-worker.mjs', './build-store.mjs', './arch.mjs', './arch-browser.mjs', './browser.mjs'].map(file => new URL(file, import.meta.url)),
116
+ ...['../../package.json', './build.mjs', './frame-document.mjs', './html.mjs', './runtime.mjs', './tokens.mjs', './text.mjs', './project.mjs', './build-worker.mjs', './build-store.mjs', './arch.mjs', './arch-browser.mjs', './browser.mjs'].map(file => new URL(file, import.meta.url)),
117
117
  ...(config.overlay?['./arch-overlay.mjs','./arch-git.mjs'].map(file=>new URL(file,import.meta.url)):[]),
118
118
  require.resolve('esbuild/package.json'), require.resolve('tailwindcss/package.json'),
119
119
  ].map(file => readFile(file)))));
@@ -238,7 +238,9 @@ export async function createBuildStore({ config, cacheDirectory }) {
238
238
  const built = await pool.run({ config: workerConfig, name }, controller.signal); counters.builds++;
239
239
  endQueue?.({frames: built.frames.length});
240
240
  if (controller.signal.aborted || generation !== (generations.get(name) ?? 0)) throw aborted();
241
- const payload = { frames: built.frames, parts: built.parts, css: built.css };
241
+ const payload = { frames: built.frames, parts: built.parts, css: built.css,
242
+ ...(built.tokenCss !== undefined ? { tokenCss: built.tokenCss, cssWithoutTokens: built.cssWithoutTokens,
243
+ cssBeforeTokens: built.cssBeforeTokens, cssAfterTokens: built.cssAfterTokens } : {}) };
242
244
  const hash = digest(JSON.stringify({ path: name, component: !name.startsWith('surfaces/'), ...payload, ...(config.overlay?{base:config.overlay.sha,baseBlob:built.baseBlob}:{}), imports: built.imports }));
243
245
  const entry = { path: name, hash, inputHash: inputHash(built.dependencyHashes,built.baseBlob), ...(config.overlay?{baseBlob:built.baseBlob}:{}), imports: built.imports, dependencies: built.dependencies, dependencyHashes: built.dependencyHashes,
244
246
  parts: built.parts, frames: built.frames.map(({ html, ...frame }) => frame) };
@@ -17,7 +17,7 @@ parentPort.on('message', async ({ id, config, name, type }) => {
17
17
  if (shuttingDown) return;
18
18
  try {
19
19
  const snapshot = new Map();
20
- const build = async browser => config.overlay && name.endsWith('.mmd') ? (await import('./arch-overlay.mjs')).buildOverlay(config,path.join(config.root,name),{base:config.overlay,browser,snapshot}) : buildSource(config, path.join(name.endsWith('.mmd')?config.root:config.design, name), { write: false, snapshot, browser });
20
+ const build = async browser => config.overlay && name.endsWith('.mmd') ? (await import('./arch-overlay.mjs')).buildOverlay(config,path.join(config.root,name),{base:config.overlay,browser,snapshot}) : buildSource(config, path.join(name.endsWith('.mmd')?config.root:config.design, name), { write: false, snapshot, browser, allowLegacy: config.allowLegacy ?? true });
21
21
  const built = await (name.endsWith('.mmd') ? archBrowser.run(build) : build());
22
22
  const frames = JSON.parse(JSON.stringify(built.frames.map(({ document, ...frame }) => frame)));
23
23
  const dependencies = [...new Set(built.dependencies.map(file => path.relative(config.design, file).split(path.sep).join('/')))].sort();
@@ -25,7 +25,10 @@ parentPort.on('message', async ({ id, config, name, type }) => {
25
25
  const bytes=snapshot.get(path.join(config.design,name));
26
26
  return [name,createHash('sha256').update(bytes===null?'missing\0':'present\0').update(bytes??'').digest('hex')];
27
27
  }));
28
- if (!shuttingDown) parentPort.postMessage({ id, result: { frames, parts: built.parts ?? [], css: built.css, ...(config.overlay?{baseBlob:built.baseBlob}:{}), imports: built.imports, dependencies, dependencyHashes }, heapBytes: process.memoryUsage().heapUsed });
28
+ if (!shuttingDown) parentPort.postMessage({ id, result: { ...(built.observationDynamic?{observationDynamic:true}:{}), frames, parts: built.parts ?? [], css: built.css,
29
+ ...(built.tokenCss !== undefined ? { tokenCss: built.tokenCss, cssWithoutTokens: built.cssWithoutTokens,
30
+ cssBeforeTokens: built.cssBeforeTokens, cssAfterTokens: built.cssAfterTokens } : {}),
31
+ ...(config.overlay?{baseBlob:built.baseBlob}:{}), imports: built.imports, dependencies, dependencyHashes }, heapBytes: process.memoryUsage().heapUsed });
29
32
  } catch (error) {
30
33
  const diagnostics=error.errors ?? error.cause?.errors ?? [];
31
34
  // esbuild's onLoad error keeps transform diagnostics under detail.errors.
@@ -4,10 +4,11 @@ import { statSync, readFileSync, realpathSync, mkdirSync, writeFileSync } from '
4
4
  import { createRequire } from 'node:module';
5
5
  import path from 'node:path';
6
6
  import { fileURLToPath, pathToFileURL } from 'node:url';
7
- import { loadTokens, refreshTypes, rejectLegacy, relative, isSourcePath, sourceDirectories } from './project.mjs';
7
+ import { loadTokens, refreshTypes, rejectLegacy, relative, isSourcePath, sourceDirectories, isFeatureInternal } from './project.mjs';
8
8
  import { themeCss, parseTokens } from './tokens.mjs';
9
- import { escape, componentOwner } from './runtime.mjs';
9
+ import { componentOwner } from './runtime.mjs';
10
10
  import { CliError, classifyError } from '../cli-output.mjs';
11
+ import { frameDocument } from './frame-document.mjs';
11
12
  const require = createRequire(import.meta.url);
12
13
  const runtime = fileURLToPath(new URL('./runtime.mjs', import.meta.url));
13
14
  const tailwind = path.dirname(require.resolve('tailwindcss/package.json'));
@@ -17,6 +18,7 @@ const tailwind = path.dirname(require.resolve('tailwindcss/package.json'));
17
18
  const sourceTransforms = new Map();
18
19
  let transformBytes = 0;
19
20
  const transformLimit = 8 * 1024 * 1024;
21
+ let evaluation = 0;
20
22
  function forgetTransform(file) {
21
23
  const entry = sourceTransforms.get(file);
22
24
  if (entry) { transformBytes -= entry.bytes; sourceTransforms.delete(file); }
@@ -65,6 +67,7 @@ export function validateFrame(frame) {
65
67
  try { if (typeof frame.locale !== 'string' || !frame.locale.trim()) throw Error(); frame.locale = Intl.getCanonicalLocales(frame.locale)[0]; }
66
68
  catch { throw Error('Invalid Frame locale; use a BCP 47 language tag.'); }
67
69
  }
70
+ if (frame.proposed !== undefined && (typeof frame.proposed !== 'string' || !frame.proposed.trim())) throw Error('Invalid Frame proposed; use a nonempty review scope string');
68
71
  const parent = frame.parent;
69
72
  if (parent !== undefined) {
70
73
  if (!parent || typeof parent !== 'object' || Array.isArray(parent) ||
@@ -103,6 +106,7 @@ async function buildDesignSource(config, file, { write = true, allowLegacy = tru
103
106
  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) {
104
107
  api.onResolve({ filter: /.*/ }, args => {
105
108
  if (args.path === 'adg:self') return {path:args.importer};
109
+ if (args.path.startsWith('adg:art-bytes:')) return {path:args.path.slice('adg:art-bytes:'.length),namespace:'art-bytes'};
106
110
  if (['adg','adg/jsx-runtime','adg/jsx-dev-runtime'].includes(args.path)) return { path: pathToFileURL(runtime).href, external: true };
107
111
  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/` }] };
108
112
  const url = args.path.endsWith('?url');
@@ -119,7 +123,12 @@ async function buildDesignSource(config, file, { write = true, allowLegacy = tru
119
123
  if (url && !resolved.startsWith(path.join(base,'art')+path.sep)) return {errors:[{text:'?url imports must be under design/art/'}]};
120
124
  return { path: resolved, ...(url ? {namespace:'art-url'} : {}) };
121
125
  });
122
- api.onLoad({filter:/.*/,namespace:'art-url'}, args => ({contents:read(args.path),loader:'dataurl'}));
126
+ api.onLoad({filter:/.*/,namespace:'art-bytes'}, args => ({contents:read(args.path),loader:'dataurl'}));
127
+ const artModule = file => {
128
+ const source=path.relative(base,file).split(path.sep).join('/');
129
+ return {contents:`import data from ${JSON.stringify('adg:art-bytes:'+file)};import {registerArtwork} from 'adg';export default registerArtwork(data,${JSON.stringify(source)});`,loader:'js'};
130
+ };
131
+ api.onLoad({filter:/.*/,namespace:'art-url'}, args => artModule(args.path));
123
132
  api.onLoad({filter:/\.tsx$/}, async args => {
124
133
  const sourcePath = path.relative(base, args.path).split(path.sep).join('/');
125
134
  if (!isSourcePath(sourcePath, sources)) return snapshot ? {contents:read(args.path,'utf8'),loader:'tsx'} : undefined;
@@ -127,12 +136,12 @@ async function buildDesignSource(config, file, { write = true, allowLegacy = tru
127
136
  return registeredSource(args.path, sourcePath, original);
128
137
  });
129
138
  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'}));
130
- api.onLoad({ filter: /\.(png|jpe?g|webp)$/i }, args => ({ contents: read(args.path), loader: 'dataurl' }));
139
+ api.onLoad({ filter: /\.(png|jpe?g|webp)$/i }, args => artModule(args.path));
131
140
  api.onLoad({ filter: /\.svg$/i }, args => {
132
141
  const source = read(args.path,'utf8');
133
142
  const forbidden = /<(?:style|script)\b|\s(?:on[\w-]+|className)\s*=/i.exec(source);
134
143
  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}}]}; }
135
- return { contents: `import { artwork } from 'adg'; export default props => artwork(${JSON.stringify(source)}, props);`, loader:'js' };
144
+ return { contents: `import { artwork } from 'adg'; export default props => artwork(${JSON.stringify(source)}, props, ${JSON.stringify(path.relative(base,args.path).split(path.sep).join('/'))});`, loader:'js' };
136
145
  });
137
146
  } }] }).catch(error => {
138
147
  const typed = error.errors?.find(item => item.detail instanceof CliError)?.detail;
@@ -140,7 +149,21 @@ async function buildDesignSource(config, file, { write = true, allowLegacy = tru
140
149
  // Retain esbuild's human diagnostics and details while carrying the owning boundary's code.
141
150
  throw Object.assign(new CliError(typed.code, error.message, { cause: error, context: typed.context }), { errors: error.errors });
142
151
  });
143
- const mod = await import(`data:text/javascript;base64,${Buffer.from(result.outputFiles[0].text).toString('base64')}#${Date.now()}`);
152
+ const executable=result.outputFiles[0].text;
153
+ // Conservative cache eligibility hint from this entry's bundled helpers; quoted copy is not code.
154
+ const observationDynamic=/\b(?:(?:Date\s*\.\s*now|Math\s*\.\s*random)\s*\(|(?:new\s+)?Date\s*\()/.test(executable.replace(/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'/g,'""'));
155
+ const mod = await import(`data:text/javascript;base64,${Buffer.from(executable).toString('base64')}#${++evaluation}`);
156
+ const sourceName = path.relative(base, file).split(path.sep).join('/');
157
+ const parts = Object.keys(mod).filter(name => {
158
+ const owner = typeof mod[name] === 'function' && componentOwner(mod[name]);
159
+ return owner && owner.source === sourceName && owner.export === name;
160
+ }).sort();
161
+ const internal = isFeatureInternal(sourceName, sources);
162
+ if (internal) {
163
+ const original = read(file, 'utf8');
164
+ if (/export\s+default[\s\S]*<Frame\b/.test(original)) throw Error(`${relative(config,file)}: feature-internal source must not export Frame defaults; move frames to index.tsx`);
165
+ return { frames: [], parts, dependencies: [...dependencies], imports: [...imports].sort(), css: '', tokenCss: '', cssWithoutTokens: '', cssBeforeTokens: '', cssAfterTokens: '' };
166
+ }
144
167
  if (typeof mod.default !== 'function') throw Error(`${relative(config,file)}: export a default function returning Frames`);
145
168
  const value = mod.default(), frames = (Array.isArray(value) ? value.flat(Infinity) : [value]).filter(v => v != null && v !== false);
146
169
  if (!frames.length) throw Error(`${relative(config,file)}: default export must return at least one Frame`);
@@ -152,15 +175,14 @@ async function buildDesignSource(config, file, { write = true, allowLegacy = tru
152
175
  const tokenSource = read(path.join(base,'tokens.css'),'utf8'), tokens = snapshot ? parseTokens(tokenSource) : loadTokens(config);
153
176
  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;`);
154
177
  const classes = [...new Set(frames.flatMap(f => [...f.html.matchAll(/\bclass="([^"]*)"/g)].flatMap(m => m[1].split(/\s+/))))];
155
- 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}}`;
178
+ const utilities = compiler.build(classes);
179
+ const defaults = 'html,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}}';
180
+ const css = `${utilities}\n${tokenSource}\n${defaults}`;
156
181
  for (const frame of frames) {
157
- 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>`;
182
+ frame.document = theme => frameDocument(frame, theme, css);
158
183
  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')); }
159
184
  }
160
- const sourceName = path.relative(base, file).split(path.sep).join('/');
161
- const parts = Object.keys(mod).filter(name => {
162
- const owner = typeof mod[name] === 'function' && componentOwner(mod[name]);
163
- return owner && owner.source === sourceName && owner.export === name;
164
- }).sort();
165
- return { frames, parts, dependencies: [...dependencies], imports: [...imports].sort(), css };
185
+ return { ...(observationDynamic?{observationDynamic:true}:{}), frames, parts, dependencies: [...dependencies], imports: [...imports].sort(), css,
186
+ tokenCss: tokenSource, cssWithoutTokens: `${utilities}\n${defaults}`,
187
+ cssBeforeTokens: `${utilities}\n`, cssAfterTokens: `\n${defaults}` };
166
188
  }