@whzxc/agent-design-gallery 0.14.0 → 0.15.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 (64) hide show
  1. package/README.md +26 -16
  2. package/package.json +1 -1
  3. package/public/access.css +15 -2
  4. package/public/app.js +708 -483
  5. package/public/arrangement-worker.js +7 -7
  6. package/public/arrangement.js +35 -30
  7. package/public/assets.js +60 -38
  8. package/public/auth.js +59 -4
  9. package/public/boards.js +124 -0
  10. package/public/comment-anchors.js +50 -0
  11. package/public/comments.css +400 -0
  12. package/public/comments.js +1106 -0
  13. package/public/context-menu.js +97 -0
  14. package/public/frame-identity.js +26 -2
  15. package/public/hub.css +25 -3
  16. package/public/hub.html +10 -2
  17. package/public/hub.js +127 -23
  18. package/public/icons.js +2 -0
  19. package/public/index.html +13 -9
  20. package/public/instance-actions.js +9 -2
  21. package/public/layout.js +156 -86
  22. package/public/selection.js +1 -1
  23. package/public/style.css +74 -152
  24. package/public/switcher.css +5 -4
  25. package/public/switcher.js +109 -34
  26. package/public/token-catalog.js +8 -3
  27. package/public/tokens.css +14 -1
  28. package/public/view-route.js +0 -1
  29. package/src/boards/board.mjs +30 -0
  30. package/src/boards/token-board.mjs +196 -0
  31. package/src/cli-output.mjs +8 -5
  32. package/src/cli.mjs +49 -29
  33. package/src/comments.mjs +293 -0
  34. package/src/http.mjs +2 -3
  35. package/src/hub/project-link.mjs +41 -0
  36. package/src/hub/registry.mjs +5 -0
  37. package/src/hub.mjs +14 -10
  38. package/src/link.mjs +13 -1
  39. package/src/server.mjs +57 -93
  40. package/src/service.mjs +46 -12
  41. package/src/toolkit/arch.mjs +3 -2
  42. package/src/toolkit/asset-rules.mjs +24 -1
  43. package/src/toolkit/build-worker.mjs +6 -2
  44. package/src/toolkit/build.mjs +4 -2
  45. package/src/toolkit/commands.mjs +12 -7
  46. package/{public/review.js → src/toolkit/diff-document.mjs} +137 -43
  47. package/src/toolkit/diff-inputs.mjs +66 -30
  48. package/src/toolkit/diff.mjs +181 -39
  49. package/src/toolkit/impact-selection.mjs +25 -10
  50. package/src/toolkit/impact.mjs +32 -12
  51. package/src/toolkit/move-pairing.mjs +140 -0
  52. package/src/toolkit/project-index.mjs +2 -2
  53. package/src/toolkit/results.mjs +1 -1
  54. package/src/toolkit/review-document.mjs +435 -0
  55. package/src/toolkit/review-groups.mjs +29 -0
  56. package/src/toolkit/review-observation.mjs +131 -0
  57. package/src/toolkit/review-sheet.mjs +117 -0
  58. package/src/toolkit/review-specimens.mjs +60 -0
  59. package/src/toolkit/review.mjs +140 -0
  60. package/src/toolkit/runtime.mjs +1 -1
  61. package/src/toolkit/theme.mjs +16 -0
  62. package/public/annotations.js +0 -816
  63. package/public/labels.js +0 -122
  64. package/src/annotations.mjs +0 -238
package/src/server.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  // Adapted from ARC's MIT-licensed tooling/design-server.mjs.
2
- import { annotations, annotationFile, readAnnotationContext } from './annotations.mjs';
2
+ import { changeComment, commentFile, commentRevision, listComments, readComment } from './comments.mjs';
3
3
  import { randomUUID, createHash } from 'node:crypto';
4
4
  import { directLocal, viewerFile, shell, json } from './http.mjs';
5
5
  import { createServer } from "node:http";
@@ -24,9 +24,9 @@ import { createViewerCache } from './viewer-cache.mjs';
24
24
  import { refreshTypes, archFiles, isSourcePath, readGroups, sourceDirectories, isFeatureInternal } from './toolkit/project.mjs';
25
25
  import { loadConfig } from './toolkit/config.mjs';
26
26
  import { parseTokens } from './toolkit/tokens.mjs';
27
+ import { tokenBoard } from './boards/token-board.mjs';
27
28
  import { sourceRelationships } from '../public/relationships.js';
28
29
  import { resolveScope } from '../public/assets.js';
29
- import { diff } from './toolkit/diff.mjs';
30
30
  const digest = value => createHash('sha256').update(value).digest('hex');
31
31
  const tokenFile = 'tokens.css';
32
32
  function tokenSourcePath(directory, project) {
@@ -39,7 +39,7 @@ export async function startServer({
39
39
  directory,
40
40
  port = 0,
41
41
  stateDirectory = defaultState,
42
- annotationStateDirectory = stateDirectory,
42
+ commentStateDirectory = stateDirectory,
43
43
  fixtures = null,
44
44
  readOnly = false,
45
45
  instanceId = randomUUID(),
@@ -64,7 +64,7 @@ export async function startServer({
64
64
  revision = 0,
65
65
  closing = false,
66
66
  buildStore, viewerCache, codePaths=new Set();
67
- const overlayStores = new Map(), overlayHashes = new Set(), activeReviews = new Set();
67
+ const overlayStores = new Map(), overlayHashes = new Set();
68
68
  let resettingOverlays = false;
69
69
  const knownBuilds = new Map(), legacyDependencies = new Map(), failedSources=new Set(), dirtyBuilds=new Set();
70
70
  const describe=built=>({...built,css:undefined,frames:built.frames.map(({html,...frame})=>frame)});
@@ -84,29 +84,33 @@ export async function startServer({
84
84
  });
85
85
  return writes;
86
86
  };
87
- const emit = (data) => {
87
+ const emit = (data, event) => {
88
+ const type = event ? `event: ${event}\n` : '';
88
89
  for (const client of clients)
89
- client.write(`data: ${JSON.stringify(data)}\n\n`);
90
+ client.write(`${type}data: ${JSON.stringify(data)}\n\n`);
90
91
  };
91
- let annotationStamp = null;
92
- async function readAnnotationStamp() {
93
- if (!activeProject) return null;
92
+ let commentsFile, commentStamp, checkingComments = false;
93
+ async function readCommentStamp(file) {
94
94
  try {
95
- const info = await stat(annotationFile(activeProject.root, annotationStateDirectory));
96
- return `${info.mtimeMs}-${info.size}`;
95
+ const info = await stat(file, { bigint: true });
96
+ return `${info.ino}-${info.mtimeNs}-${info.ctimeNs}`;
97
97
  } catch (e) {
98
98
  return e.code === 'ENOENT' ? 'missing' : null;
99
99
  }
100
100
  }
101
- const annotationTimer = setInterval(async () => {
102
- if (closing || !clients.size || !activeProject) return;
103
- const next = await readAnnotationStamp();
104
- if (next && next !== annotationStamp) {
105
- annotationStamp = next;
106
- emit({ annotations: true });
107
- }
108
- }, 800);
109
- annotationTimer.unref?.();
101
+ const commentTimer = setInterval(async () => {
102
+ if (closing || !clients.size || !commentsFile || checkingComments) return;
103
+ checkingComments = true;
104
+ const file = commentsFile;
105
+ try {
106
+ const next = await readCommentStamp(file);
107
+ if (file === commentsFile && next && next !== commentStamp) {
108
+ commentStamp = next;
109
+ emit({ comments: true }, 'comments');
110
+ }
111
+ } finally { checkingComments = false; }
112
+ }, 400);
113
+ commentTimer.unref?.();
110
114
  const diagnostic = (error, name = null, fallback = 'SOURCE_BUILD_FAILED') => {
111
115
  if (error.name === 'AbortError') return;
112
116
  const at = error.location ?? error.errors?.[0]?.location ?? error.cause?.errors?.[0]?.location;
@@ -251,7 +255,8 @@ export async function startServer({
251
255
  watcher = nextWatcher;
252
256
  activeProject=project;watchArch(project,next);
253
257
  root = next;
254
- annotationStamp = await readAnnotationStamp();
258
+ commentsFile = await commentFile(project.root, commentStateDirectory);
259
+ commentStamp = await readCommentStamp(commentsFile);
255
260
  tokenSource = hasTokens ? tokenSourcePath(next, project) : null;
256
261
  codePaths=nextCode;
257
262
  sources = nextSources;
@@ -369,17 +374,26 @@ export async function startServer({
369
374
  const data=baseManifest(),context=await contextFor(url), requested=url.searchParams.get('scope');
370
375
  const fixtureScope=fixtures?.states[url.searchParams.get('fixture')]?.scope;
371
376
  const desired = fixtureScope ?? requested ?? 'all';
377
+ if (data.tokenSource) {
378
+ try {
379
+ const css = await readFile(path.join(data.directory, tokenFile), 'utf8');
380
+ const { light, dark } = parseTokens(css);
381
+ const declarations = values => [...values].map(([name, value]) => `${name}:${value};`).join('\n');
382
+ data.boardCss = `#board-chrome{${declarations(light)}}
383
+ :where([data-theme="dark"]) #board-chrome, #board-chrome[data-theme="dark"]{${declarations(dark)}}`;
384
+ if (desired === 'tokens' || desired === 'all') {
385
+ data.tokens = [...light].map(([name, value]) => [name, value, dark.get(name) ?? null]);
386
+ data.tokenBoard = tokenBoard(data.tokenSource, css, { projectName: data.label });
387
+ }
388
+ } catch (error) {
389
+ data.tokenError = error.code ? `Cannot read ${data.tokenSource}.` : error.message;
390
+ diagnostic(new CliError('TOKENS_INVALID', error.message, { cause: error }));
391
+ }
392
+ }
372
393
  if (desired === 'tokens' && data.tokenSource) {
373
394
  // Keep the layer choices available without measuring or building any artboards.
374
395
  const { layers } = resolveScope(data, sources, 'all');
375
396
  const result = { ...data, scope: 'tokens', layers, assets: [] };
376
- try {
377
- const { light, dark } = parseTokens(await readFile(path.join(data.directory, tokenFile), 'utf8'));
378
- result.tokens = [...light].map(([name, value]) => [name, value, dark.get(name) ?? null]);
379
- } catch (error) {
380
- result.tokenError = error.code ? `Cannot read ${data.tokenSource}.` : error.message;
381
- diagnostic(new CliError('TOKENS_INVALID',error.message,{cause:error}));
382
- }
383
397
  return applyFixtureManifest(result, url.searchParams.get('fixture'));
384
398
  }
385
399
  const scoped=resolveScope(data,sources,desired === 'tokens' ? 'default' : desired);
@@ -424,42 +438,10 @@ export async function startServer({
424
438
  }
425
439
  return {...asset,metadata,metadataRefs,previewIds};
426
440
  }));
427
- data.packing=(await viewerCache.get(digest('catalog'),'light',context))?.metadata.packing??[];
428
441
  }
429
442
  data.features={compactSources:1,persistedMetadata:1,incrementalHashes:1};
430
443
  return applyFixtureManifest(data,url.searchParams.get('fixture'));
431
444
  }
432
- async function reviewManifest(url) {
433
- const baseParam = url.searchParams.get('base');
434
- if (typeof baseParam !== 'string' || !baseParam.trim())
435
- throw new CliError('USAGE_INVALID', 'Set ?base=<rev> to a Git revision.');
436
- if (!activeProject || !root)
437
- throw new CliError('DIRECTORY_NOT_FOUND', 'No project is open.');
438
- const data = baseManifest();
439
- const { layers } = resolveScope(data, sources, 'all');
440
- const reviewDir = path.join(stateDirectory, 'cache', digest(root), 'review', randomUUID());
441
- let review = null;
442
- const task = (async () => {
443
- try {
444
- await diff(activeProject, [], {
445
- base: baseParam,
446
- impacted: true,
447
- 'out-dir': reviewDir,
448
- 'state-dir': stateDirectory,
449
- json: true,
450
- }, { log: () => {}, onReview: value => { review = value; } });
451
- } catch (error) {
452
- if (error.code !== 'DIFF_FAILED') throw error;
453
- } finally {
454
- await rm(reviewDir, { recursive: true, force: true }).catch(() => {});
455
- }
456
- if (!review) throw new CliError('INTERNAL_ERROR', 'Review output was not produced.');
457
- return { ...data, scope: 'review', layers, assets: [], base: review.base, review: { ...review, label: data.label } };
458
- })();
459
- activeReviews.add(task);
460
- try { return await task; }
461
- finally { activeReviews.delete(task); }
462
- }
463
445
  async function sourceBuild(name) {
464
446
  const endBuild = perfSpan('build', name);
465
447
  let built;
@@ -553,29 +535,22 @@ export async function startServer({
553
535
  const file = ['GET', 'HEAD'].includes(request.method) && viewerFile(url.pathname);
554
536
  if (file) return await shell(request, response, file, request.headers['x-adg-viewer-base']);
555
537
  if (!directLocal(request)) return json(response, 401, { error: 'Unauthorized' });
556
- if (url.pathname === '/api/annotations') {
538
+ if (url.pathname === '/api/comments') {
557
539
  if (request.method !== 'GET' && request.method !== 'POST') return json(response,405,{error:'Use GET or POST.'});
558
540
  if (request.method === 'POST' && request.headers.origin && ![`http://${host}`,`https://${host}`].includes(request.headers.origin)) return json(response,403,{error:'Cross-origin request refused.'});
559
- const config = await loadConfig(root);
541
+ if (!activeProject) return json(response, 404, { error: 'No project is open.' });
542
+ const { root: projectRoot } = activeProject;
560
543
  if (request.method === 'GET') {
561
- if (url.searchParams.has('id')) {
562
- const id = url.searchParams.get('id');
563
- const result = url.searchParams.get('context') === '1'
564
- ? await readAnnotationContext(config, annotationStateDirectory, id)
565
- : await annotations(config.root, annotationStateDirectory, 'read', { id });
566
- return json(response, 200, result);
567
- }
568
- const status = url.searchParams.get('status') ?? 'all';
569
- return json(response, 200, await annotations(config.root, annotationStateDirectory, 'list', { status }));
544
+ if (url.searchParams.has('id'))
545
+ return json(response, 200, await readComment(projectRoot, commentStateDirectory, url.searchParams.get('id')));
546
+ const [result, revision] = await Promise.all([
547
+ listComments(projectRoot, commentStateDirectory, { status: url.searchParams.get('status') ?? 'all' }),
548
+ commentRevision(projectRoot),
549
+ ]);
550
+ return json(response, 200, { ...result, revision });
570
551
  }
571
- const input = await body(request);
572
- const result = await annotations(config.root, annotationStateDirectory, input.action, {
573
- ...input,
574
- ...(input.action === 'reply' && !input.author ? { author: 'user' } : {}),
575
- });
576
- annotationStamp = await readAnnotationStamp();
577
- emit({ annotations: true });
578
- return json(response, 200, result);
552
+ const input = await body(request, 256 * 1024);
553
+ return json(response, 200, await changeComment(projectRoot, commentStateDirectory, input, { viewer: true }));
579
554
  }
580
555
  if(url.pathname==='/api/cache-stats'&&request.method==='GET')return json(response,200,{process:process.memoryUsage(),builds:buildStore?.stats(),viewer:viewerCache?.stats()});
581
556
  if (url.pathname === '/api/health' && request.method === 'GET') return json(response, 200, { id: instanceId, capabilities: { keyAuth: 1 } });
@@ -603,12 +578,6 @@ export async function startServer({
603
578
  }
604
579
  return json(response,200,{ok:true});
605
580
  }
606
- if(url.pathname==='/catalog') {
607
- const data=await body(request,1024*1024),context=await contextFor(url);
608
- if(!Array.isArray(data.packing)||data.packing.length>32)throw Error('Invalid packing cache.');
609
- await viewerCache.save(digest('catalog'),'light',context,{packing:data.packing});
610
- return json(response,200,{ok:true});
611
- }
612
581
  const data = await body(request);
613
582
  if (url.pathname === "/preferences") {
614
583
  if (typeof data.sidebar === "boolean") state.sidebar = data.sidebar;
@@ -645,7 +614,6 @@ export async function startServer({
645
614
  return;
646
615
  }
647
616
  if (url.pathname === "/events") {
648
- annotationStamp ??= await readAnnotationStamp();
649
617
  response.writeHead(200, {
650
618
  "Content-Type": "text/event-stream",
651
619
  "Cache-Control": "no-store",
@@ -668,9 +636,6 @@ export async function startServer({
668
636
  if (url.pathname === "/manifest") {
669
637
  content = JSON.stringify(await manifest(url));
670
638
  type = "application/json";
671
- } else if (url.pathname === "/review") {
672
- content = JSON.stringify(await reviewManifest(url));
673
- type = "application/json";
674
639
  } else if (url.pathname === "/relationships") {
675
640
  const assets = await Promise.all([...files.keys()].filter(name => /\.(tsx|mmd)$/.test(name)).map(async name => ({path:name, imports:(await sourceBuild(name)).imports})));
676
641
  content = JSON.stringify(sourceRelationships(assets));
@@ -708,15 +673,15 @@ export async function startServer({
708
673
  response.end(request.method === "HEAD" ? undefined : content);
709
674
  } catch (error) {
710
675
  if (response.destroyed) return;
711
- response.writeHead(error.name==='AbortError'?409:400, { "Content-Type": "application/json" });
712
- response.end(JSON.stringify({ error: error.message }));
676
+ const status = { COMMENT_NOT_FOUND: 404, COMMENT_FORBIDDEN: 403 }[error.code] ?? (error.name === 'AbortError' ? 409 : 400);
677
+ return json(response, status, { error: error.message });
713
678
  }
714
679
  });
715
680
  let closePromise;
716
681
  const close = () => closePromise ??= (async () => {
717
682
  closing = true;
718
683
  clearTimeout(refreshTimer);
719
- clearInterval(annotationTimer);
684
+ clearInterval(commentTimer);
720
685
  let primary;
721
686
  for (const step of [
722
687
  async () => { watcher?.close(); },
@@ -728,7 +693,6 @@ export async function startServer({
728
693
  },
729
694
  async () => { await writes; },
730
695
  async () => { await buildStore?.close(); },
731
- async () => { await Promise.allSettled([...activeReviews]); },
732
696
  closeOverlays,
733
697
  async () => { await viewerCache?.close(); },
734
698
  ]) {
package/src/service.mjs CHANGED
@@ -4,7 +4,9 @@ import { homedir } from 'node:os';
4
4
  import path from 'node:path';
5
5
  import { fileURLToPath } from 'node:url';
6
6
  import { promisify } from 'node:util';
7
+ import { setTimeout as delay } from 'node:timers/promises';
7
8
  import { defaultStateDirectory } from './hub/registry.mjs';
9
+ import { hubPublicOrigin } from './hub/project-link.mjs';
8
10
  import { CliError } from './cli-output.mjs';
9
11
  import { commandFailure } from './toolkit/results.mjs';
10
12
 
@@ -17,13 +19,14 @@ const unxml = value => value.replace(/&(amp|lt|gt|quot|apos);/g, (_, entity) =>
17
19
  amp: '&', lt: '<', gt: '>', quot: '"', apos: "'",
18
20
  })[entity]);
19
21
 
20
- export function renderLaunchAgent({ nodePath, cliPath, stateDirectory, port = 4310 }) {
22
+ export function renderLaunchAgent({ nodePath, cliPath, stateDirectory, port = 4310, publicOrigin }) {
21
23
  const args = [nodePath, cliPath, 'serve', '--port', String(port), '--state-dir', stateDirectory];
24
+ const environment = publicOrigin ? `\n <key>EnvironmentVariables</key><dict>\n <key>ADG_PUBLIC_ORIGIN</key><string>${xml(publicOrigin)}</string>\n </dict>` : '';
22
25
  return `<?xml version="1.0" encoding="UTF-8"?>
23
26
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
24
27
  <plist version="1.0"><dict>
25
28
  <key>Label</key><string>${SERVICE_LABEL}</string>
26
- <key>ProgramArguments</key><array>${args.map(arg => `<string>${xml(arg)}</string>`).join('')}</array>
29
+ <key>ProgramArguments</key><array>${args.map(arg => `<string>${xml(arg)}</string>`).join('')}</array>${environment}
27
30
  <key>RunAtLoad</key><true/>
28
31
  <key>KeepAlive</key><true/>
29
32
  <key>StandardOutPath</key><string>${xml(path.join(stateDirectory, 'service.stdout.log'))}</string>
@@ -36,6 +39,11 @@ function launchArguments(plist) {
36
39
  const array = plist?.match(/<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/)?.[1] ?? '';
37
40
  return [...array.matchAll(/<string>([\s\S]*?)<\/string>/g)].map(match => unxml(match[1]));
38
41
  }
42
+ function launchPublicOrigin(plist) {
43
+ const environment = plist?.match(/<key>EnvironmentVariables<\/key>\s*<dict>([\s\S]*?)<\/dict>/)?.[1];
44
+ const value = environment?.match(/<key>ADG_PUBLIC_ORIGIN<\/key>\s*<string>([\s\S]*?)<\/string>/)?.[1];
45
+ return value === undefined ? undefined : unxml(value);
46
+ }
39
47
  const readOptional = async file => {
40
48
  try { return await readFile(file, 'utf8'); }
41
49
  catch (error) { if (error.code !== 'ENOENT') throw error; return null; }
@@ -56,7 +64,7 @@ function statusData(status, installedPlist, agentFile, stateDirectory) {
56
64
  return { label: SERVICE_LABEL, installed: installedPlist !== null, loaded: status !== null,
57
65
  state: status?.match(/^\s*state = (.+)$/m)?.[1] ?? null,
58
66
  pid: Number(status?.match(/^\s*pid = (\d+)$/m)?.[1]) || null,
59
- plist: agentFile, stateDirectory,
67
+ plist: agentFile, stateDirectory, publicOrigin: launchPublicOrigin(installedPlist) ?? null,
60
68
  logs: { stdout: path.join(stateDirectory, 'service.stdout.log'), stderr: path.join(stateDirectory, 'service.stderr.log') } };
61
69
  }
62
70
 
@@ -142,8 +150,9 @@ export async function service(action, values = {}, {
142
150
  if (!['install','uninstall','status','logs','migrate'].includes(action)) throw new CliError('USAGE_INVALID','Expected adg service install|uninstall|status|logs|migrate; run adg service --help.');
143
151
  if (action === 'migrate') return migrateService(values,{home,run,nodePath,cliPath,uid,output});
144
152
  const agentFile=path.join(home,'Library','LaunchAgents',`${SERVICE_LABEL}.plist`);
145
- const installedPlist=await readOptional(agentFile),installedArgs=launchArguments(installedPlist),stateFlag=installedArgs.indexOf('--state-dir');
146
- const stateDirectory=path.resolve(values['state-dir'] ?? (action === 'install' ? undefined : stateFlag >= 0 ? installedArgs[stateFlag+1] : undefined) ?? defaultStateDirectory);
153
+ const installedPlist=await readOptional(agentFile),installedArgs=launchArguments(installedPlist);
154
+ const argument = flag => installedArgs.includes(flag) ? installedArgs[installedArgs.indexOf(flag) + 1] : undefined;
155
+ const stateDirectory=path.resolve(values['state-dir'] ?? argument('--state-dir') ?? defaultStateDirectory);
147
156
  const domain=`gui/${uid}`,target=`${domain}/${SERVICE_LABEL}`;
148
157
  const stdout=path.join(stateDirectory,'service.stdout.log'),stderr=path.join(stateDirectory,'service.stderr.log');
149
158
  if (action === 'logs') {
@@ -166,18 +175,43 @@ export async function service(action, values = {}, {
166
175
  output(`Uninstalled ${SERVICE_LABEL}. State and logs retained in ${stateDirectory}.`);
167
176
  return {data:{label:SERVICE_LABEL,plist:agentFile,stateDirectory,retained:true}};
168
177
  }
169
- const port=values.port===undefined ? 4310 : Number(values.port);
178
+ const port=Number(values.port ?? argument('--port') ?? 4310);
170
179
  if (!Number.isInteger(port) || port < 1 || port > 65535) throw new CliError('USAGE_INVALID','--port must be an integer from 1 to 65535.');
171
- if (installedPlist !== null) throw new CliError('SERVICE_ALREADY_INSTALLED',`${SERVICE_LABEL} is already installed; run adg service uninstall before reinstalling.`);
180
+ const publicOrigin=hubPublicOrigin(values['public-origin'] ?? launchPublicOrigin(installedPlist),'--public-origin');
172
181
  const executable=await realpath(nodePath),entry=await realpath(cliPath);
182
+ const plist=renderLaunchAgent({nodePath:executable,cliPath:entry,stateDirectory,port,publicOrigin});
183
+ const previous=installedPlist === null ? null : await loadedJob(run,target);
184
+ if (previous !== null && installedPlist === plist) {
185
+ output(`${SERVICE_LABEL} is already installed and loaded.`);
186
+ return {data:{service:statusData(previous,plist,agentFile,stateDirectory),port}};
187
+ }
188
+ const bootstrap = async () => {
189
+ for (let attempt = 0;; attempt++) {
190
+ try { return await run('/bin/launchctl',['bootstrap',domain,agentFile]); }
191
+ catch (cause) {
192
+ // launchd can still be releasing the previous job after bootout returns.
193
+ if (previous === null || cause.code !== 5 || attempt === 5) throw cause;
194
+ await delay(100 * 2 ** attempt);
195
+ }
196
+ }
197
+ };
173
198
  await mkdir(path.dirname(agentFile),{recursive:true});await mkdir(stateDirectory,{recursive:true});
174
199
  await Promise.all([stdout,stderr].map(file=>writeFile(file,'',{flag:'a'})));
175
- const plist=renderLaunchAgent({nodePath:executable,cliPath:entry,stateDirectory,port});
176
- await writeFile(agentFile,plist);
177
- try { await run('/bin/launchctl',['bootstrap',domain,agentFile]); }
200
+ if (previous !== null) await job(run,['bootout',target]);
201
+ try {
202
+ await writeFile(agentFile,plist);
203
+ await bootstrap();
204
+ }
178
205
  catch (cause) {
179
- await rm(agentFile,{force:true});
180
- throw new CliError('SERVICE_FAILED',`Cannot install ${SERVICE_LABEL}: ${cause.stderr?.trim() || cause.message}`,{cause});
206
+ let message=`Cannot install ${SERVICE_LABEL}: ${cause.stderr?.trim() || cause.message}`;
207
+ try {
208
+ if (installedPlist === null) await rm(agentFile,{force:true});
209
+ else {
210
+ await writeFile(agentFile,installedPlist);
211
+ if (previous !== null) await bootstrap();
212
+ }
213
+ } catch (restore) { message += ` Could not restore the previous service: ${restore.message}`; }
214
+ throw new CliError('SERVICE_FAILED',message,{cause});
181
215
  }
182
216
  output(`Installed ${SERVICE_LABEL}. Logs: ${stdout} and ${stderr}.`);
183
217
  return {data:{service:statusData(await loadedJob(run,target),plist,agentFile,stateDirectory),port}};
@@ -193,11 +193,12 @@ export async function buildArch(config,file,{snapshot,model:overlayModel,browser
193
193
  const result=await renderArch(overlayModel??checked.model,tokenSource,{browser});
194
194
  const legend=checked.classes.length?`<div class="arch-legend">${checked.classes.map(name=>`<span class="arch-key ${name}" style="--arch-color:var(--arch-${name})"><i class="arch-swatch"></i>${name}</span>`).join('')}</div>`:'';
195
195
  const html=`<section data-adg-arch>${legend}${result.svg}</section>`;
196
- const css=`${archStyles()}\n${tokenSource}\nhtml,body{margin:0;font-family:var(--font-ui);color:var(--text);background:var(--canvas)}[data-adg-frame]{display:flex;width:max-content}`;
196
+ const cssAfterTokens='\nhtml,body{margin:0;font-family:var(--font-ui);color:var(--text);background:var(--canvas)}[data-adg-frame]{display:flex;width:max-content}';
197
+ const css=`${archStyles()}\n${tokenSource}${cssAfterTokens}`;
197
198
  const note=[metadata.body,metadata.owners.length?`Owners: ${metadata.owners.join(', ')}`:'',metadata.status?`Status: ${metadata.status}`:''].filter(Boolean).join('\n');
198
199
  const frame={frame:true,name:'default',html,note};
199
200
  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="default">${html}</div></body></html>`;
200
- return {frames:[frame],css,imports:[],dependencies};
201
+ return {frames:[frame],css,cssAfterTokens,imports:[],dependencies};
201
202
  }
202
203
 
203
204
  // Executed in the same Chromium page as ordinary frame checks. Bounds are in
@@ -1,4 +1,4 @@
1
- import { isFeatureEntry, sourceFeature } from './project.mjs';
1
+ import { isFeatureEntry, isFeatureInternal, sourceFeature } from './project.mjs';
2
2
 
3
3
  // Production sources are ordered from lower to higher layers. Studies are explorations.
4
4
  export function importDirectionViolations(graph, sources, { strictLayers = false } = {}) {
@@ -51,3 +51,26 @@ export function singleConsumerComponents(graph, sources, partsBySource) {
51
51
  }
52
52
  return warnings;
53
53
  }
54
+
55
+ /** Chapter guidance never changes the check verdict. Paths are design-relative. */
56
+ export function chapterWarnings(files, groups, sources) {
57
+ const production = sources.filter(source => source !== 'studies');
58
+ const requiredLayers = new Set(production.slice(0, Math.min(2, production.length - 1)));
59
+ files = files.filter(file => !isFeatureInternal(file, sources));
60
+ const inventory = new Set(files);
61
+ const assigned = new Set(groups.flatMap(group => group.assets));
62
+ const missing = files.filter(file => requiredLayers.has(file.split('/')[0]) && !assigned.has(file)).sort();
63
+ const warnings = [];
64
+ if (missing.length) warnings.push({
65
+ code: 'CHAPTER_SOURCES_UNASSIGNED', count: missing.length, paths: missing,
66
+ message: `${missing.length} component/module sources have no gallery.json chapter: ${missing.join(', ')}.`, next: [],
67
+ });
68
+ for (const group of groups) {
69
+ const paths = [...new Set(group.assets.filter(source => inventory.has(source)))];
70
+ if (paths.length > 12) warnings.push({
71
+ code: 'CHAPTER_TOO_LARGE', chapter: group.title, count: paths.length, paths,
72
+ message: `Chapter "${group.title}" has ${paths.length} sources; split it into feature chapters of about 3 to 12 sources.`, next: [],
73
+ });
74
+ }
75
+ return warnings;
76
+ }
@@ -1,5 +1,6 @@
1
1
  import { parentPort } from 'node:worker_threads';
2
2
  import { createHash } from 'node:crypto';
3
+ import { realpathSync } from 'node:fs';
3
4
  import path from 'node:path';
4
5
  import { buildSource } from './build.mjs';
5
6
  import { createArchBrowser } from './arch-browser.mjs';
@@ -20,9 +21,12 @@ parentPort.on('message', async ({ id, config, name, type }) => {
20
21
  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
22
  const built = await (name.endsWith('.mmd') ? archBrowser.run(build) : build());
22
23
  const frames = JSON.parse(JSON.stringify(built.frames.map(({ document, ...frame }) => frame)));
23
- const dependencies = [...new Set(built.dependencies.map(file => path.relative(config.design, file).split(path.sep).join('/')))].sort();
24
+ const designRoot = realpathSync(config.design);
25
+ const dependencies = [...new Set(built.dependencies.map(file => path.relative(file.startsWith(designRoot + path.sep) ? designRoot : config.design, file).split(path.sep).join('/')))].sort();
24
26
  const dependencyHashes = Object.fromEntries(dependencies.map(name => {
25
- const bytes=snapshot.get(path.join(config.design,name));
27
+ const designFile = path.join(designRoot, name), rawFile = path.join(config.design, name);
28
+ const bytes = snapshot.has(designFile) ? snapshot.get(designFile) : snapshot.get(rawFile);
29
+ if (bytes === undefined) throw Error(`Missing snapshot bytes for dependency ${name}`);
26
30
  return [name,createHash('sha256').update(bytes===null?'missing\0':'present\0').update(bytes??'').digest('hex')];
27
31
  }));
28
32
  if (!shuttingDown) parentPort.postMessage({ id, result: { ...(built.observationDynamic?{observationDynamic:true}:{}), frames, parts: built.parts ?? [], css: built.css,
@@ -101,7 +101,7 @@ async function buildDesignSource(config, file, { write = true, allowLegacy = tru
101
101
  return encoding ? value.toString(encoding) : value;
102
102
  };
103
103
  file = realpathSync(file);
104
- const base = realpathSync(config.design), dependencies = new Set([path.join(base, 'tokens.css')]);
104
+ const base = realpathSync(config.design), dependencies = new Set();
105
105
  const imports = new Set(), sources = sourceDirectories(config);
106
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) {
107
107
  api.onResolve({ filter: /.*/ }, args => {
@@ -172,7 +172,9 @@ async function buildDesignSource(config, file, { write = true, allowLegacy = tru
172
172
  try { validateFrame(frame); if (names.has(frame.name)) throw Error(`Duplicate frame name ${frame.name}`); names.add(frame.name); }
173
173
  catch(error) { throw Error(`${relative(config,file)}: ${frame?.name ?? '-'}: ${error.message}`); }
174
174
  }
175
- const tokenSource = read(path.join(base,'tokens.css'),'utf8'), tokens = snapshot ? parseTokens(tokenSource) : loadTokens(config);
175
+ const tokenFile = path.join(base, 'tokens.css');
176
+ dependencies.add(tokenFile);
177
+ const tokenSource = read(tokenFile,'utf8'), tokens = snapshot ? parseTokens(tokenSource) : loadTokens(config);
176
178
  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;`);
177
179
  const classes = [...new Set(frames.flatMap(f => [...f.html.matchAll(/\bclass="([^"]*)"/g)].flatMap(m => m[1].split(/\s+/))))];
178
180
  const utilities = compiler.build(classes);
@@ -2,14 +2,15 @@ import { mkdirSync, readFileSync, existsSync } from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { availableParallelism } from 'node:os';
4
4
  import { buildSource } from './build.mjs';
5
- import { selectSources, relative, loadTokens, sourceDirectories, archFiles, featureFolderProblems } from './project.mjs';
6
- import { importDirectionViolations, singleConsumerComponents } from './asset-rules.mjs';
5
+ import { selectSources, relative, loadTokens, sourceDirectories, archFiles, featureFolderProblems, readGroups, listSources } from './project.mjs';
6
+ import { importDirectionViolations, singleConsumerComponents, chapterWarnings } from './asset-rules.mjs';
7
7
  import { launch, loadFrame, browserTask } from './browser.mjs';
8
8
  import { CliError, classifyError } from '../cli-output.mjs';
9
9
  import { commandFailure, cleanup, emptySelection } from './results.mjs';
10
10
  import { loadImplementationMap, validateImplementationMap } from './implementation-map.mjs';
11
11
  import { withImpacted } from './impact-selection.mjs';
12
12
  import { mappingFacts, frameOwners } from './source-facts.mjs';
13
+ import { resolveThemes, systemTheme } from './theme.mjs';
13
14
 
14
15
  function frameStructure(frame) {
15
16
  return frame.html
@@ -220,6 +221,11 @@ export async function check(config, args = [], options = {}, log = console.log,
220
221
  else warnings.push(classifyError(failure).error);
221
222
  };
222
223
  try {
224
+ const directories = sourceDirectories(config);
225
+ const chapterFiles = listSources(config.design, directories).map(file => path.relative(config.design, file).split(path.sep).join('/'));
226
+ const chapters = chapterWarnings(chapterFiles, readGroups(config.design, directories), directories);
227
+ warnings.push(...chapters);
228
+ if (!options.json) for (const warning of chapters) log(`WARNING ${warning.message}`);
223
229
  const mapping = await loadImplementationMap(config);
224
230
  const files = session ? session.sources.map(source => path.join(config.root, source)).filter(existsSync) : selectSources(config, args, { write });
225
231
  data.sources = files.map(file => relative(config, file));
@@ -340,21 +346,20 @@ export async function check(config, args = [], options = {}, log = console.log,
340
346
  } finally { if (browser) await cleanup(() => browser.close(), primary); }
341
347
  }
342
348
 
343
- export async function render(config, args = [], options = {}, log = console.log, { launchBrowser = launch, session } = {}) {
349
+ export async function render(config, args = [], options = {}, log = console.log, { launchBrowser = launch, session, readSystemTheme = systemTheme } = {}) {
350
+ const themes = resolveThemes(options.theme, readSystemTheme);
351
+ options = { ...options, theme: themes.length === 2 ? 'both' : themes[0] };
344
352
  if (options.impacted && !session) return withImpacted(config, args, options, 'render', selected =>
345
353
  render(config, args, options, log, { launchBrowser, session: selected }));
346
354
  const output = options['out-dir'] ? path.resolve(config.root, options['out-dir']) : config.output;
347
355
  /** @type {import('./results.mjs').RenderData} */
348
- const data = { project: config.root, outputDirectory: output, complete: false, impact: session?.selection ?? null, base: null, captures: [], deleted: [] };
356
+ const data = { project: config.root, outputDirectory: output, complete: false, impact: session?.selection ?? null, base: null, themes, captures: [], deleted: [] };
349
357
  const warnings = [], completed = [], failures = [];
350
358
  let browser, primary;
351
359
  try {
352
360
  const scale = Number(options.scale ?? 2);
353
361
  if (!(Number.isFinite(scale) && scale > 0)) throw new CliError('USAGE_INVALID', 'Invalid --scale; use a positive number');
354
- const themeOption = options.theme ?? 'both';
355
- if (!['both', 'light', 'dark'].includes(themeOption)) throw new CliError('USAGE_INVALID', 'Choose --theme=both, light, or dark.');
356
362
  if (options['out-dir'] === '') throw new CliError('USAGE_INVALID', 'Set --out-dir to a directory.');
357
- const themes = themeOption === 'both' ? ['light', 'dark'] : [themeOption];
358
363
  let base, additional = [];
359
364
  if (!session && options.base !== undefined && (!args.length || args.some(arg => arg.endsWith('.mmd')))) {
360
365
  const git = await import('./arch-git.mjs');