@whzxc/agent-design-gallery 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/cli.mjs CHANGED
@@ -4,6 +4,7 @@ import { parseArgs } from 'node:util';
4
4
  import { pathToFileURL } from 'node:url';
5
5
  import { realpathSync } from 'node:fs';
6
6
  import { VERSION, loadConfig } from './toolkit/config.mjs';
7
+ import { CliError, createOutput, withHumanOutput } from './cli-output.mjs';
7
8
 
8
9
  export const commands = ['open', 'link', 'serve', 'root', 'service', 'migrate', 'init', 'check', 'render', 'compare'];
9
10
  const targetOptions = '[--asset=<path> [--frame=<name>] | --group=<name> | --layer=<name> | --tokens] [--mode=query|path] [--base=<rev>]';
@@ -23,7 +24,7 @@ const details = {
23
24
  root: 'Manage registered scan roots. add scans immediately. scan rescans registered roots only; depth is 0 through 3. Hidden directories, node_modules and Git worktrees are skipped.',
24
25
  open: 'Browse TSX, Mermaid architecture sources and legacy SVG designs on an independent random-port server.', init: 'Create design sources, tokens and editor configuration without overwriting files.',
25
26
  link: 'Print a clean ADG preview URL. Query mode isolates a target. Path mode locates it in the design hierarchy.',
26
- check: 'Check import direction and every selected frame in both themes. --read-only skips generated types and build files.', render: 'Render selected frames as PNG. Defaults to both themes at 2×. --json prints a list of captures with absolute paths.',
27
+ check: 'Check import direction and every selected frame in both themes. --read-only skips generated types and build files.', render: 'Render selected frames as PNG. Defaults to both themes at 2×. --json prints a versioned result with capture geometry and absolute paths.',
27
28
  compare: 'Compare fixture text positions. Flags override Frame fixture and capture. --all writes a summary for every fixture frame.',
28
29
  };
29
30
  export function help(command) {
@@ -31,75 +32,145 @@ export function help(command) {
31
32
  return `Usage: adg [open] [directory] [options]\n\n${commands.map(name => ` adg ${name} ${usage[name]}`).join('\n')}\n\nAny first argument that is not a command opens a directory. Use adg open check for a directory named check.\nRun adg <command> --help for details. -v, --version prints the installed version.`;
32
33
  }
33
34
  export function parseCli(args) {
35
+ let globalJson = false;
36
+ while (args[0] === '--json') { globalJson = true; args = args.slice(1); }
34
37
  const explicit = commands.includes(args[0]), command = explicit ? args[0] : 'open';
35
- const options = { help: { type: 'boolean', short: 'h' }, version: { type: 'boolean', short: 'v' } };
38
+ const options = { help: { type: 'boolean', short: 'h' }, version: { type: 'boolean', short: 'v' }, json: { type: 'boolean' } };
36
39
  const locators = ['asset', 'frame', 'group', 'layer', 'mode', 'base'];
37
40
  const strings = { open: ['port', 'state-dir', ...locators], link: locators, serve: ['port', 'state-dir'], root: ['depth', 'state-dir'], service: ['port', 'state-dir'], render: ['scale', 'frame', 'theme', 'out-dir', 'base'], compare: ['frame', 'fixture', 'region', 'selector', 'viewport', 'origin'] };
38
41
  for (const name of strings[command] ?? []) options[name] = { type: 'string' };
39
42
  if (command === 'serve') for (const name of ['print-key', 'rotate-key']) options[name] = { type: 'boolean' };
40
43
  if (command === 'open') options['no-open'] = { type: 'boolean' };
41
44
  if (command === 'open' || command === 'link') options.tokens = { type: 'boolean' };
42
- if (command === 'render') options.json = { type: 'boolean' };
43
45
  if (command === 'check') options['read-only'] = { type: 'boolean' };
44
46
  if (command === 'compare') { options.all = { type: 'boolean' }; options.page = { type: 'boolean' }; }
45
47
  if (command === 'compare') options.click = { type: 'string', multiple: true };
46
48
  let parsed;
47
49
  try { parsed = parseArgs({ args: explicit ? args.slice(1) : args, options, allowPositionals: true }); }
48
- catch (error) { throw new Error(`${error.message}; run adg ${command} --help`); }
50
+ catch (error) { throw new CliError('USAGE_INVALID', `${error.message}; run adg ${command} --help`); }
49
51
  const { values, positionals } = parsed;
52
+ if (globalJson) values.json = true;
50
53
  if (!values.help && !values.version) {
51
- if ((command === 'init' && positionals.length) || (['open', 'migrate'].includes(command) && positionals.length > 1) || (command === 'compare' && (values.all ? positionals.length || values.frame : positionals.length !== 1 || !values.frame))) throw new Error(`Invalid arguments; run adg ${command} --help`);
54
+ if ((command === 'init' && positionals.length) || (['open', 'migrate'].includes(command) && positionals.length > 1) || (command === 'compare' && (values.all ? positionals.length || values.frame : positionals.length !== 1 || !values.frame))) throw new CliError('USAGE_INVALID', `Invalid arguments; run adg ${command} --help`);
55
+ if (command === 'link' && positionals.length !== 1) throw new CliError('USAGE_INVALID', 'Expected one viewer URL. Run adg link --help.');
56
+ if (command === 'service' && (positionals.length !== 1 || !serviceActions.includes(positionals[0]) || (values.port !== undefined && positionals[0] !== 'install'))) throw new CliError('USAGE_INVALID', 'Invalid arguments; run adg service --help');
57
+ if (command === 'root') {
58
+ const [action, directory, ...extra] = positionals;
59
+ if (extra.length || !rootActions.includes(action) || (['add', 'remove'].includes(action) && !directory) || (action === 'list' && directory) || (values.depth !== undefined && action !== 'add')) throw new CliError('USAGE_INVALID', 'Invalid arguments; run adg root --help');
60
+ }
61
+ if (command === 'serve' && positionals.length) throw new CliError('USAGE_INVALID', 'Invalid arguments; run adg serve --help');
62
+ if (command === 'serve' && ((values['print-key'] && values['rotate-key']) || (values.port !== undefined && (values['print-key'] || values['rotate-key'])))) throw new CliError('USAGE_INVALID','Choose --print-key or --rotate-key without --port; run adg serve --help');
63
+ } else if (values.json && values.help && ['root', 'service'].includes(command) && (positionals.length > 1 || (positionals.length && !(command === 'root' ? rootActions : serviceActions).includes(positionals[0])))) {
64
+ throw new CliError('USAGE_INVALID', `Invalid arguments; run adg ${command} --help`);
52
65
  }
53
66
  return { command, values, positionals, explicit };
54
67
  }
55
- export async function main(args = process.argv.slice(2), cwd = process.cwd()) {
56
- const { command, values, positionals, explicit } = parseCli(args);
57
- if (values.help) { console.log(help(explicit ? command : undefined)); return 0; }
58
- if (values.version) { console.log(VERSION); return 0; }
59
- if (command === 'migrate') return (await import('./toolkit/migrate.mjs')).migrate(positionals[0] === undefined ? cwd : path.resolve(cwd, positionals[0]));
60
- if (command === 'open') return (await import('./open.mjs')).open(positionals, values);
68
+ const rootActions = ['add', 'remove', 'list', 'scan'];
69
+ const serviceActions = ['install', 'uninstall', 'status', 'logs', 'migrate'];
70
+
71
+ export function commandIdentity({ command, positionals = [] }) {
72
+ const actions = command === 'root' ? rootActions : command === 'service' ? serviceActions : [];
73
+ return actions.includes(positionals[0]) ? `${command} ${positionals[0]}` : command;
74
+ }
75
+
76
+ export function jsonRequested(args) {
77
+ const separator = args.indexOf('--');
78
+ return (separator < 0 ? args : args.slice(0, separator)).includes('--json');
79
+ }
80
+
81
+ function errorCommand(args) {
82
+ while (args[0] === '--json') args = args.slice(1);
83
+ if (commands.includes(args[0])) return commandIdentity({ command: args[0], positionals: args.slice(1) });
84
+ return args[0] && !args[0].startsWith('-') ? 'open' : 'adg';
85
+ }
86
+
87
+ async function dispatch({ command, values, positionals }, cwd, output, serviceOptions) {
88
+ if (command === 'migrate') return { data: await (await import('./toolkit/migrate.mjs')).migrate(positionals[0] === undefined ? cwd : path.resolve(cwd, positionals[0]), output.log) };
61
89
  if (command === 'link') {
62
- if (positionals.length !== 1) throw Error('Expected one viewer URL. Run adg link --help.');
63
90
  const { previewTarget, previewURL } = await import('./link.mjs');
64
- console.log(previewURL(positionals[0], previewTarget(values)).href);
65
- return 0;
91
+ const data = { url: previewURL(positionals[0], previewTarget(values)).href };
92
+ if (!values.json) output.log(data.url);
93
+ return { data };
66
94
  }
67
95
  if (command === 'service') {
68
- if (positionals.length !== 1 || !['install', 'uninstall', 'status', 'logs', 'migrate'].includes(positionals[0]) || (values.port !== undefined && positionals[0] !== 'install')) throw new Error('Invalid arguments; run adg service --help');
69
- return (await import('./service.mjs')).service(positionals[0], values);
96
+ const options={...serviceOptions,output:output.log};
97
+ if (values['state-dir'] !== undefined) values={...values,'state-dir':path.resolve(cwd,values['state-dir'])};
98
+ return (await import('./service.mjs')).service(positionals[0], values, options);
70
99
  }
71
100
  if (command === 'root') {
72
- const [action, directory, ...extra] = positionals;
73
- if (extra.length || !['add', 'remove', 'list', 'scan'].includes(action) || (['add', 'remove'].includes(action) && !directory) || (action === 'list' && directory) || (values.depth !== undefined && action !== 'add')) throw new Error('Invalid arguments; run adg root --help');
101
+ const [action, directory] = positionals;
74
102
  const registry = await import('./hub/registry.mjs');
75
- const state = values['state-dir'];
76
- const result = action === 'add' ? await registry.addRoot(directory, values.depth === undefined ? 2 : Number(values.depth), state)
77
- : action === 'remove' ? await registry.removeRoot(directory, state)
78
- : action === 'scan' ? await registry.scanRoots(directory, state) : await registry.listRoots(state);
79
- console.log(JSON.stringify(result, null, 2)); return 0;
103
+ const state = path.resolve(cwd, values['state-dir'] ?? registry.defaultStateDirectory);
104
+ const options = { cwd, error: output.progress };
105
+ const result = action === 'add' ? await registry.addRoot(directory, values.depth === undefined ? 2 : Number(values.depth), state, options)
106
+ : action === 'remove' ? await registry.removeRoot(directory, state, options)
107
+ : action === 'scan' ? await registry.scanRoots(directory, state, options)
108
+ : { data: { stateDirectory: state, roots: await registry.listRoots(state), affected: [] } };
109
+ if (!values.json) output.log(JSON.stringify(result.data.roots, null, 2));
110
+ return result;
80
111
  }
81
112
  if (command === 'serve') {
82
- if (positionals.length) throw new Error('Invalid arguments; run adg serve --help');
83
- if (values['print-key'] || values['rotate-key']) {
84
- const key = await (await import('./hub/auth.mjs')).hubKey(values['state-dir'], { rotate: !!values['rotate-key'] });
85
- console.log(values['print-key'] ? key : 'Hub key rotated.'); return 0;
86
- }
87
- const port = values.port === undefined ? 4310 : Number(values.port);
88
- if (!Number.isInteger(port) || port < 0 || port > 65535) throw new Error('--port must be an integer from 0 to 65535.');
89
- const hub = await (await import('./hub.mjs')).startHub({ port, stateDirectory: values['state-dir'] });
90
- console.log(`ADG: ${hub.url}`);
91
- for (const signal of ['SIGINT', 'SIGTERM']) process.once(signal, () => hub.close().catch(error => { console.error(error.message); process.exitCode = 2; }));
92
- return 0;
113
+ const {defaultStateDirectory}=await import('./hub/registry.mjs');
114
+ const stateDirectory=path.resolve(cwd,values['state-dir'] ?? defaultStateDirectory);
115
+ const key=await (await import('./hub/auth.mjs')).hubKey(stateDirectory,{rotate:!!values['rotate-key']});
116
+ if (!values.json && !values['print-key']) output.log('Hub key rotated.');
117
+ return {data:values['print-key'] ? {action:'print-key',stateDirectory,key} : {action:'rotate-key',stateDirectory,rotated:true}};
93
118
  }
94
119
  const config = await loadConfig(cwd);
95
- if (command === 'init') return (await import('./toolkit/project.mjs'))[command](config);
96
- if (command === 'compare') return (await import('./toolkit/compare.mjs')).compare(config, positionals, values);
97
- return (await import('./toolkit/commands.mjs'))[command](config, positionals, values);
120
+ if (command === 'init') return { data: (await import('./toolkit/project.mjs')).init(config, output.log) };
121
+ if (command === 'compare') return (await import('./toolkit/compare.mjs')).compare(config, positionals, values, {log:output.log});
122
+ const toolkit = await import('./toolkit/commands.mjs');
123
+ return command === 'check' ? toolkit.check(config, positionals, values, output.log, output.progress) : toolkit.render(config, positionals, values, output.log);
124
+ }
125
+ export async function main(args = process.argv.slice(2), cwd = process.cwd(), {
126
+ stdout = process.stdout.write.bind(process.stdout), stderr = process.stderr.write.bind(process.stderr),
127
+ exit = code => { process.exitCode = code; },
128
+ serviceOptions, openOptions, hubOptions, signals = process, stdoutEvents = process.stdout,
129
+ } = {}) {
130
+ let command = errorCommand(args), parsed;
131
+ const json = jsonRequested(args);
132
+ let output = createOutput({ json, command, stdout, stderr });
133
+ let code;
134
+ try {
135
+ parsed = parseCli(args);
136
+ command = parsed.values.help ? 'help' : parsed.values.version ? 'version' : commandIdentity(parsed);
137
+ output = createOutput({ json, command, stdout, stderr, revealKey:command === 'serve' && !!parsed.values['print-key'] });
138
+ if (command === 'help') {
139
+ const text = help(parsed.explicit ? parsed.command : undefined);
140
+ if (json) output.success({ subject: parsed.explicit ? commandIdentity(parsed) : null, usage: text.split('\n')[0], text });
141
+ else output.log(text);
142
+ code = 0;
143
+ } else if (command === 'version') {
144
+ if (json) output.success({ version: VERSION });
145
+ else output.log(VERSION);
146
+ code = 0;
147
+ } else if (command === 'open' || (command === 'serve' && !parsed.values['print-key'] && !parsed.values['rotate-key'])) {
148
+ const {defaultStateDirectory}=await import('./hub/registry.mjs');
149
+ const stateDirectory=path.resolve(cwd,parsed.values['state-dir'] ?? defaultStateDirectory);
150
+ const port=parsed.values.port === undefined ? command === 'open' ? 0 : 4310 : Number(parsed.values.port);
151
+ if (!Number.isInteger(port) || port < 0 || port > 65535) throw new CliError('USAGE_INVALID','--port must be an integer from 0 to 65535.');
152
+ const {runForeground}=await import('./lifecycle.mjs');
153
+ const start=command === 'open'
154
+ ? async callbacks => (await import('./open.mjs')).open(parsed.positionals,parsed.values,{...openOptions,cwd,...callbacks})
155
+ : async callbacks => (await import('./hub.mjs')).startHub({...hubOptions,port,stateDirectory,...callbacks});
156
+ const run=()=>runForeground(command,start,{output,json,signals,stdoutEvents,context:{...parsed,command,stateDirectory}});
157
+ code=json ? await withHumanOutput(run,stderr) : await run();
158
+ } else {
159
+ const run=()=>dispatch(parsed,cwd,output,serviceOptions);
160
+ const result = json ? await withHumanOutput(run, stderr) : await run();
161
+ if (json) output.success(result.data, result.warnings);
162
+ else if (command === 'serve' && parsed.values['print-key']) stdout(`${result.data.key}\n`);
163
+ code = 0;
164
+ }
165
+ } catch (error) {
166
+ code = output.failure(error, {
167
+ ...(parsed ?? {}), command,
168
+ ...(parsed?.values['state-dir'] ? { stateDirectory: path.resolve(cwd, parsed.values['state-dir']) } : {}),
169
+ });
170
+ }
171
+ exit(code);
172
+ return code;
98
173
  }
99
174
  if (process.argv[1] && import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href) {
100
- main().then(code => { process.exitCode = code; }).catch(error => {
101
- const message = String(error.message).replace(/\s+/g, ' ').trim();
102
- console.error(`adg: ${message}`);
103
- process.exitCode = 2;
104
- });
175
+ await main();
105
176
  }
package/src/http.mjs CHANGED
@@ -10,6 +10,7 @@ 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
12
  '/assets.js': 'assets.js', '/icons.js': 'icons.js', '/layout.js': 'layout.js', '/labels.js': 'labels.js',
13
+ '/arrangement.js': 'arrangement.js', '/arrangement-worker.js': 'arrangement-worker.js',
13
14
  '/relationships.js': 'relationships.js', '/selection.js': 'selection.js', '/style.css': 'style.css', '/tokens.css': 'tokens.css',
14
15
  '/token-catalog.js': 'token-catalog.js',
15
16
  '/view-route.js': 'view-route.js',
package/src/hub/auth.mjs CHANGED
@@ -3,13 +3,14 @@ import { mkdir, readFile, writeFile, rename, chmod } from 'node:fs/promises';
3
3
  import path from 'node:path';
4
4
  import { directLocal } from '../http.mjs';
5
5
  import { defaultStateDirectory } from './registry.mjs';
6
+ import { CliError } from '../cli-output.mjs';
6
7
 
7
8
  export async function hubKey(stateDirectory = defaultStateDirectory, { rotate = false } = {}) {
8
9
  const file = path.join(stateDirectory, 'hub.key');
9
10
  if (!rotate) {
10
11
  try {
11
12
  const key = (await readFile(file, 'utf8')).trim();
12
- if (!/^adg_[a-f0-9]{64}$/.test(key)) throw new Error(`Invalid hub key in ${file}; run adg serve --rotate-key.`);
13
+ if (!/^adg_[a-f0-9]{64}$/.test(key)) throw new CliError('HUB_KEY_INVALID', `Invalid hub key in ${file}; run adg serve --rotate-key.`, { context: {stateDirectory:path.resolve(stateDirectory)} });
13
14
  await chmod(file, 0o600);
14
15
  return key;
15
16
  } catch (error) { if (error.code !== 'ENOENT') throw error; }
package/src/hub/proxy.mjs CHANGED
@@ -1,7 +1,8 @@
1
1
  import { request as httpRequest } from 'node:http';
2
+ import { CliError } from '../cli-output.mjs';
2
3
 
3
4
  // Pipe through the owning server, preserving streaming and backpressure.
4
- export function proxy(request, response, port, pathname, viewerBase) {
5
+ export function proxy(request, response, port, pathname, viewerBase, onDiagnostic) {
5
6
  return new Promise(resolve => {
6
7
  const headers = { ...request.headers, host: `127.0.0.1:${port}` };
7
8
  for (const name of Object.keys(headers)) {
@@ -15,11 +16,12 @@ export function proxy(request, response, port, pathname, viewerBase) {
15
16
  delete outgoing['set-cookie'];
16
17
  response.writeHead(incoming.statusCode, outgoing);
17
18
  incoming.pipe(response);
18
- incoming.on('error', () => response.destroy());
19
+ incoming.on('error', error => { if (!response.destroyed) onDiagnostic?.(new CliError('NETWORK_FAILED',error.message,{cause:error})); response.destroy(); });
19
20
  });
20
21
  const done = () => { upstream.destroy(); resolve(); };
21
22
  response.once('close', done);
22
- upstream.on('error', () => {
23
+ upstream.on('error', error => {
24
+ if (!response.destroyed) onDiagnostic?.(new CliError('NETWORK_FAILED','Viewer unavailable.',{cause:error}));
23
25
  if (!response.headersSent) response.writeHead(502, { 'Content-Type': 'application/json' });
24
26
  if (!response.destroyed) response.end(JSON.stringify({ error: 'Viewer unavailable.' }));
25
27
  });
@@ -6,10 +6,17 @@ import { execFile } from 'node:child_process';
6
6
  import { promisify } from 'node:util';
7
7
  import { configFile, loadConfig, VERSION, requireMigration, legacyConfigFile } from '../toolkit/config.mjs';
8
8
  import { listSources, archFiles } from '../toolkit/project.mjs';
9
+ import { CliError } from '../cli-output.mjs';
9
10
 
10
11
  const exec = promisify(execFile);
11
12
  export const defaultStateDirectory = path.join(process.env.XDG_STATE_HOME || path.join(os.homedir(), '.local/state'), 'agent-design-gallery');
12
- const canonical = async directory => realpath(path.resolve(directory.replace(/^~(?=$|[\\/])/, os.homedir())));
13
+ const canonical = async (directory, cwd = process.cwd()) => {
14
+ try { return await realpath(path.resolve(cwd, directory.replace(/^~(?=$|[\\/])/, os.homedir()))); }
15
+ catch (error) {
16
+ if (['ENOENT', 'ENOTDIR'].includes(error.code)) throw new CliError('DIRECTORY_NOT_FOUND', error.message, { cause: error });
17
+ throw error;
18
+ }
19
+ };
13
20
  export function projectSlug(directory) {
14
21
  return path.basename(directory).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'project';
15
22
  }
@@ -44,8 +51,16 @@ function assignSlugs(data, previousRoots) {
44
51
  data.slugVersion = 1;
45
52
  }
46
53
  async function registry(stateDirectory) {
47
- try { return JSON.parse(await readFile(path.join(stateDirectory, 'registry.json'), 'utf8')); }
48
- catch (error) { if (error.code === 'ENOENT') return { roots: [] }; throw new Error(`Cannot read registry: ${error.message}`); }
54
+ try {
55
+ const data = JSON.parse(await readFile(path.join(stateDirectory, 'registry.json'), 'utf8'));
56
+ if (!data || !Array.isArray(data.roots) || data.roots.some(root => !root || typeof root.path !== 'string' || !Number.isInteger(root.depth) || root.depth < 0 || root.depth > 3 || !Array.isArray(root.projects) || root.projects.some(project => !project || typeof project.path !== 'string'))) {
57
+ throw new CliError('STATE_INVALID', 'Expected roots with paths, depths and project lists.');
58
+ }
59
+ return data;
60
+ } catch (error) {
61
+ if (error.code === 'ENOENT') return { roots: [] };
62
+ throw new CliError(error instanceof SyntaxError || error.code === 'STATE_INVALID' ? 'STATE_INVALID' : 'IO_FAILED', `Cannot read registry: ${error.message}`, { cause: error });
63
+ }
49
64
  }
50
65
  async function save(data, stateDirectory) {
51
66
  await mkdir(stateDirectory, { recursive: true });
@@ -53,16 +68,24 @@ async function save(data, stateDirectory) {
53
68
  await writeFile(temporary, JSON.stringify(data, null, 2) + '\n');
54
69
  await rename(temporary, destination);
55
70
  }
56
- async function scan(root) {
71
+ async function scan(root, stateDirectory, warnings, { error: logError = console.error, readDirectory = readdir } = {}) {
72
+ const warn = (code, message, human) => {
73
+ warnings.push({ code, message, next: [{ argv: ['adg', 'root', 'scan', root.path, '--state-dir', stateDirectory, '--json'], reason: 'Rescan after repairing the project inputs or directory access.' }] });
74
+ if (human) logError(human);
75
+ };
57
76
  const projects = [];
58
77
  async function visit(directory, depth) {
59
78
  if (path.basename(directory).startsWith('.') || path.basename(directory) === 'node_modules') return;
60
79
  let entries;
61
80
  try {
62
81
  if ((await stat(path.join(directory, '.git')).catch(() => null))?.isFile()) return;
63
- entries = await readdir(directory, { withFileTypes: true });
82
+ entries = await readDirectory(directory, { withFileTypes: true });
64
83
  } catch (error) {
65
- if (directory === root.path) throw error;
84
+ if (directory === root.path) {
85
+ if (['ENOENT', 'ENOTDIR'].includes(error.code)) throw new CliError('DIRECTORY_NOT_FOUND', error.message, { cause: error });
86
+ throw error;
87
+ }
88
+ warn('SCAN_DIRECTORY_SKIPPED', `${directory}: ${error.message.replace(/\s*\n\s*/g, ' ')}`);
66
89
  return;
67
90
  }
68
91
  if (configFile(directory) || legacyConfigFile(directory)) {
@@ -70,7 +93,8 @@ async function scan(root) {
70
93
  try {
71
94
  await loadConfig(directory, { checkVersion: false });
72
95
  } catch (error) {
73
- console.error(`adg: ${directory}: ${error.message.replace(/\s*\n\s*/g, ' ')}; fix the project config and rescan.`);
96
+ const message = `${directory}: ${error.message.replace(/\s*\n\s*/g, ' ')}; fix the project config and rescan.`;
97
+ warn('PROJECT_CONFIG_INVALID', message, `adg: ${message}`);
74
98
  }
75
99
  }
76
100
  if (depth >= root.depth) return;
@@ -82,41 +106,51 @@ async function scan(root) {
82
106
  await visit(root.path, 0);
83
107
  return { ...root, projects, scannedAt: new Date().toISOString() };
84
108
  }
85
- export async function addRoot(directory, depth = 2, stateDirectory = defaultStateDirectory) {
86
- if (!Number.isInteger(depth) || depth < 0 || depth > 3) throw new Error('Depth must be an integer from 0 to 3.');
87
- const root = await canonical(directory);
88
- if (!(await stat(root)).isDirectory()) throw new Error(`Not a directory: ${directory}`);
89
- const data = await registry(stateDirectory), entry = await scan({ path: root, depth });
109
+ function rootResult(stateDirectory, roots, affected, warnings = []) {
110
+ return { data: { stateDirectory: path.resolve(stateDirectory), roots, affected }, warnings };
111
+ }
112
+ export async function addRoot(directory, depth = 2, stateDirectory = defaultStateDirectory, options = {}) {
113
+ if (!Number.isInteger(depth) || depth < 0 || depth > 3) throw new CliError('USAGE_INVALID', 'Depth must be an integer from 0 to 3.');
114
+ stateDirectory = path.resolve(stateDirectory);
115
+ const root = await canonical(directory, options.cwd);
116
+ if (!(await stat(root)).isDirectory()) throw new CliError('DIRECTORY_NOT_FOUND', `Not a directory: ${directory}`);
117
+ const warnings = [];
118
+ const data = await registry(stateDirectory), entry = await scan({ path: root, depth }, stateDirectory, warnings, options);
90
119
  const previousRoots = data.roots;
91
120
  data.roots = [...data.roots.filter(item => item.path !== root), entry].sort((a, b) => a.path.localeCompare(b.path));
92
121
  assignSlugs(data, previousRoots);
93
122
  await save(data, stateDirectory);
94
- return listRoots(stateDirectory);
123
+ return rootResult(stateDirectory, await listRoots(stateDirectory), [root], warnings);
95
124
  }
96
- export async function removeRoot(directory, stateDirectory = defaultStateDirectory) {
97
- const root = await canonical(directory).catch(error => {
98
- if (error.code === 'ENOENT') return path.resolve(directory.replace(/^~(?=$|[\\/])/, os.homedir()));
125
+ export async function removeRoot(directory, stateDirectory = defaultStateDirectory, options = {}) {
126
+ const root = await canonical(directory, options.cwd).catch(error => {
127
+ if (error.code === 'DIRECTORY_NOT_FOUND' && error.cause?.code === 'ENOENT') return path.resolve(options.cwd ?? process.cwd(), directory.replace(/^~(?=$|[\\/])/, os.homedir()));
99
128
  throw error;
100
129
  });
101
130
  const data = await registry(stateDirectory);
102
- if (!data.roots.some(item => item.path === root)) throw new Error(`Root is not registered: ${directory}`);
131
+ if (!data.roots.some(item => item.path === root)) throw new CliError('ROOT_NOT_REGISTERED', `Root is not registered: ${directory}`);
103
132
  data.roots = data.roots.filter(item => item.path !== root);
104
133
  await save(data, stateDirectory);
105
- return listRoots(stateDirectory);
134
+ return rootResult(stateDirectory, await listRoots(stateDirectory), [root]);
106
135
  }
107
136
  export async function listRoots(stateDirectory = defaultStateDirectory) {
108
137
  return (await registry(stateDirectory)).roots.map(({ projects, ...root }) => ({ ...root, projectCount: projects.length }));
109
138
  }
110
- export async function scanRoots(directory, stateDirectory = defaultStateDirectory) {
111
- const data = await registry(stateDirectory), selected = directory === undefined ? null : await canonical(directory);
112
- if (selected && !data.roots.some(root => root.path === selected)) throw new Error(`Root is not registered: ${directory}`);
139
+ export async function scanRoots(directory, stateDirectory = defaultStateDirectory, options = {}) {
140
+ stateDirectory = path.resolve(stateDirectory);
141
+ const data = await registry(stateDirectory), selected = directory === undefined ? null : await canonical(directory, options.cwd);
142
+ if (selected && !data.roots.some(root => root.path === selected)) throw new CliError('ROOT_NOT_REGISTERED', `Root is not registered: ${directory}`);
143
+ const warnings = [], affected = [];
113
144
  const previousRoots = [...data.roots];
114
145
  for (let index = 0; index < data.roots.length; index++) {
115
- if (!selected || data.roots[index].path === selected) data.roots[index] = await scan(data.roots[index]);
146
+ if (!selected || data.roots[index].path === selected) {
147
+ data.roots[index] = await scan(data.roots[index], stateDirectory, warnings, options);
148
+ affected.push(data.roots[index].path);
149
+ }
116
150
  }
117
151
  assignSlugs(data, previousRoots);
118
152
  await save(data, stateDirectory);
119
- return listRoots(stateDirectory);
153
+ return rootResult(stateDirectory, await listRoots(stateDirectory), affected.sort(), warnings);
120
154
  }
121
155
  const git = async (directory, args) => {
122
156
  try { return (await exec('git', ['-C', directory, ...args], { maxBuffer: 1024 * 1024 })).stdout.trim(); }
package/src/hub.mjs CHANGED
@@ -7,8 +7,11 @@ import { proxy } from './hub/proxy.mjs';
7
7
  import { listInstances, stopInstance } from './hub/instances.mjs';
8
8
  import { hubKey, authorized } from './hub/auth.mjs';
9
9
  import { json, shell, viewerFile } from './http.mjs';
10
+ import { CliError, asCliError } from './cli-output.mjs';
11
+ import { loadConfig } from './toolkit/config.mjs';
12
+ import { cleanup } from './toolkit/results.mjs';
10
13
 
11
- export async function startHub({ port = 4310, stateDirectory = defaultStateDirectory, idleTimeout = 300_000 } = {}) {
14
+ export async function startHub({ port = 4310, stateDirectory = defaultStateDirectory, idleTimeout = 300_000, onDiagnostic, onFatal, startViewer = startServer } = {}) {
12
15
  await hubKey(stateDirectory);
13
16
  let closing = false;
14
17
  const id = randomUUID(), viewers = new Map(), streams = new Set();
@@ -47,7 +50,7 @@ export async function startHub({ port = 4310, stateDirectory = defaultStateDirec
47
50
  return json(response, status, { error });
48
51
  }
49
52
  if (url.pathname === '/api/roots' && request.method === 'GET') return json(response, 200, await listRoots(stateDirectory));
50
- if (url.pathname === '/api/rescan' && request.method === 'POST') return json(response, 200, await scanRoots(undefined, stateDirectory));
53
+ if (url.pathname === '/api/rescan' && request.method === 'POST') return json(response, 200, (await scanRoots(undefined, stateDirectory)).data.roots);
51
54
  if (route) {
52
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.' });
53
56
  if (instanceRoute) {
@@ -56,7 +59,7 @@ export async function startHub({ port = 4310, stateDirectory = defaultStateDirec
56
59
  if (!instance.proxyable) return json(response, 409, { error: 'Instance viewer does not support authenticated proxying.' });
57
60
  if (!route[2]) { response.writeHead(302, { Location: `${url.pathname}/${url.search}` }); response.end(); return; }
58
61
  streams.add(response);
59
- try { await proxy(request, response, instance.port, route[2] + url.search, `/i/${instance.id}/`); }
62
+ try { await proxy(request, response, instance.port, route[2] + url.search, `/i/${instance.id}/`, onDiagnostic); }
60
63
  finally { streams.delete(response); }
61
64
  return;
62
65
  }
@@ -66,8 +69,9 @@ export async function startHub({ port = 4310, stateDirectory = defaultStateDirec
66
69
  entry = { active: 0, last: Date.now() };
67
70
  entry.pending = (async () => {
68
71
  const project = (await listProjects(stateDirectory)).find(item => item.slug === slug);
69
- if (!project) throw new Error('Unknown project; run adg root scan.');
70
- entry.viewer = await startServer({ directory: project.design, stateDirectory: path.join(stateDirectory, 'projects', slug) });
72
+ if (!project) throw new CliError('PROJECT_NOT_FOUND','Unknown project; run adg root scan.');
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 });
71
75
  return entry.viewer;
72
76
  })();
73
77
  viewers.set(slug, entry);
@@ -75,12 +79,15 @@ export async function startHub({ port = 4310, stateDirectory = defaultStateDirec
75
79
  try { await entry.pending; }
76
80
  catch (error) { if (viewers.get(slug) === entry) viewers.delete(slug); throw error; }
77
81
  entry.active++;
78
- try { await proxy(request, response, entry.viewer.port, route[2] + url.search); }
82
+ try { await proxy(request, response, entry.viewer.port, route[2] + url.search, undefined, onDiagnostic); }
79
83
  finally { entry.active--; entry.last = Date.now(); }
80
84
  return;
81
85
  }
82
86
  json(response, read ? 404 : 405, { error: 'Not found.' });
83
87
  } catch (error) {
88
+ if (error.code === 'STATE_INVALID') onFatal?.(error);
89
+ else if (error.name !== 'AbortError' && !['PROJECT_NOT_FOUND','USAGE_INVALID'].includes(error.code)) onDiagnostic?.(asCliError(error));
90
+ if (response.destroyed) return;
84
91
  if (response.headersSent) response.destroy();
85
92
  else json(response, 400, { error: error.message });
86
93
  }
@@ -89,25 +96,33 @@ export async function startHub({ port = 4310, stateDirectory = defaultStateDirec
89
96
  for (const [slug, entry] of viewers) {
90
97
  if (!entry.active && entry.viewer && Date.now() - entry.last > idleTimeout) {
91
98
  viewers.delete(slug);
92
- entry.viewer.close().catch(() => {});
99
+ entry.viewer.close().catch(error => { if (!closing) onDiagnostic?.(new CliError('SHUTDOWN_FAILED',error.message,{cause:error})); });
93
100
  }
94
101
  }
95
102
  }, Math.min(idleTimeout, 30_000));
96
103
  reap.unref();
97
- try { await new Promise((resolve, reject) => { server.once('error', reject); server.listen(port, '127.0.0.1', resolve); }); }
98
- catch (error) { clearInterval(reap); throw error; }
99
- return {
100
- id, url: `http://127.0.0.1:${server.address().port}/`,
101
- async close() {
102
- closing = true;
103
- clearInterval(reap);
104
+ let closePromise;
105
+ const close = () => closePromise ??= (async () => {
106
+ closing = true; clearInterval(reap);
107
+ let primary;
108
+ const steps = [async () => {
104
109
  for (const response of streams) response.destroy();
105
- await Promise.all([...viewers.values()].map(async entry => {
106
- let viewer; try { viewer = await entry.pending; } catch { return; }
107
- await viewer.close();
108
- }));
109
- server.closeAllConnections();
110
- await new Promise(resolve => server.close(resolve));
111
- },
110
+ const disconnected = server.listening ? new Promise(resolve => server.close(resolve)) : Promise.resolve();
111
+ server.closeAllConnections(); await disconnected;
112
+ }, ...[...viewers.values()].map(entry => async () => {
113
+ let viewer; try { viewer=await entry.pending; } catch { return; }
114
+ await viewer.close();
115
+ })];
116
+ for (const step of steps) try { await cleanup(step,primary); } catch (error) { primary=error; }
117
+ if (primary) throw primary;
118
+ })();
119
+ try { await new Promise((resolve,reject) => {
120
+ const startupError=error=>{server.off('listening',listening);reject(error);};
121
+ const listening=()=>{server.off('error',startupError);server.on('error',error=>{if(!closing)onFatal?.(asCliError(error));});resolve();};
122
+ server.once('error',startupError);server.listen(port,'127.0.0.1',listening);
123
+ }); }
124
+ catch (cause) { const primary=asCliError(cause);await cleanup(close,primary);throw primary; }
125
+ return {
126
+ id, url: `http://127.0.0.1:${server.address().port}/`,port:server.address().port,stateDirectory:path.resolve(stateDirectory),close,
112
127
  };
113
128
  }
@@ -0,0 +1,109 @@
1
+ import { asCliError, CliError, classifyError } from './cli-output.mjs';
2
+
3
+ /** @typedef {import('./toolkit/results.mjs').Location} Location */
4
+ /** @typedef {{onDiagnostic: (error: unknown, location?: Location | null) => void, onFatal: (error: unknown, location?: Location | null) => void}} ErrorCallbacks */
5
+ /** @typedef {{id: string, url: string, port: number, directory?: string | null, stateDirectory: string, close: () => Promise<unknown>, openBrowser?: () => void}} ForegroundHandle */
6
+ /** @typedef {{output: ReturnType<import('./cli-output.mjs').createOutput>, json: boolean, context?: import('./cli-output.mjs').ErrorContext, signals?: Pick<import('node:events').EventEmitter, 'on' | 'off'>, stdoutEvents?: Pick<import('node:events').EventEmitter, 'on' | 'off'>}} LifecycleOptions */
7
+
8
+ /** Own one foreground invocation from serving readiness through its single terminal event.
9
+ * @param {string} command
10
+ * @param {(callbacks: ErrorCallbacks) => Promise<ForegroundHandle>} start
11
+ * @param {LifecycleOptions} options
12
+ */
13
+ export async function runForeground(command, start, { output, json, context = {}, signals = process, stdoutEvents = process.stdout }) {
14
+ /** @type {ForegroundHandle | undefined} */
15
+ let handle;
16
+ /** @type {CliError | null} */
17
+ let startupFailure = null;
18
+ /** @type {'SIGINT' | 'SIGTERM' | null} */
19
+ let pendingSignal = null;
20
+ let ready = false, finishing = false, brokenOutput = false;
21
+ /** @type {import('./cli-output.mjs').Diagnostic[]} */
22
+ const pendingWarnings = [];
23
+ /** @type {(code: number) => void} */
24
+ let resolveDone = () => {};
25
+ /** @type {Promise<number>} */
26
+ const done = new Promise(resolve => { resolveDone = resolve; });
27
+
28
+ /** @param {unknown} [cause] @param {'SIGINT' | 'SIGTERM' | null} [signal] @param {Location | null} [location] */
29
+ const finish = (cause, signal = null, location = null) => {
30
+ if (finishing) return done;
31
+ finishing = true;
32
+ const stop = async () => {
33
+ let failure = cause === undefined ? null : asCliError(cause);
34
+ try { await handle?.close(); }
35
+ catch (error) {
36
+ const cleanup = error instanceof CliError && error.code === 'SHUTDOWN_FAILED' ? error : new CliError('SHUTDOWN_FAILED', error instanceof Error ? error.message : String(error), { cause: error });
37
+ if (failure) failure.warnings.push(classifyError(cleanup).error);
38
+ else failure = cleanup;
39
+ }
40
+ try {
41
+ if (failure) {
42
+ failure.data = ready ? { event:'diagnostic', location } : null;
43
+ failure.warnings.push(...pendingWarnings);
44
+ if (!brokenOutput) {
45
+ if (json || !ready) output.failure(failure,context);
46
+ else output.progress(failure.message);
47
+ }
48
+ return 2;
49
+ }
50
+ if (!brokenOutput && json) output.success({event:'stopped',signal});
51
+ return brokenOutput ? 2 : 0;
52
+ } catch { return 2; }
53
+ finally {
54
+ signals.off('SIGINT',interrupt); signals.off('SIGTERM',terminate);
55
+ stdoutEvents.off('error',outputError);
56
+ }
57
+ };
58
+ void stop().then(resolveDone, () => { resolveDone(2); });
59
+ return done;
60
+ };
61
+ /** @param {unknown} error */
62
+ const outputError = error => {
63
+ brokenOutput = true;
64
+ if (!handle) startupFailure ??= asCliError(error);
65
+ else void finish(error);
66
+ };
67
+ /** @param {'SIGINT' | 'SIGTERM'} signal */
68
+ const stopSignal = signal => {
69
+ if (!handle) pendingSignal ??= signal;
70
+ else void finish(undefined,signal);
71
+ };
72
+ const interrupt = () => stopSignal('SIGINT'), terminate = () => stopSignal('SIGTERM');
73
+ signals.on('SIGINT',interrupt); signals.on('SIGTERM',terminate);
74
+ stdoutEvents.on('error',outputError);
75
+ /** @type {ErrorCallbacks} */
76
+ const callbacks = {
77
+ onDiagnostic(error,location = null) {
78
+ if (finishing || (error instanceof Error && error.name === 'AbortError')) return;
79
+ const diagnostic = !(error instanceof Error) && error && typeof error === 'object' && 'code' in error && typeof error.code === 'string' && 'message' in error && typeof error.message === 'string' && 'next' in error && Array.isArray(error.next)
80
+ ? {code:error.code,message:error.message,next:error.next} : classifyError(asCliError(error),context).error;
81
+ if (!ready) { pendingWarnings.push(diagnostic); return; }
82
+ try {
83
+ if (json) output.success({event:'diagnostic',location},[diagnostic]);
84
+ else output.progress(diagnostic.message);
85
+ } catch (cause) { outputError(cause); }
86
+ },
87
+ onFatal(error,location = null) {
88
+ if (finishing || (error instanceof Error && error.name === 'AbortError')) return;
89
+ if (!handle) startupFailure ??= asCliError(error);
90
+ else void finish(error,null,location);
91
+ },
92
+ };
93
+ try {
94
+ handle = await start(callbacks);
95
+ if (startupFailure) return await finish(startupFailure);
96
+ if (pendingSignal) return await finish(undefined,pendingSignal);
97
+ const data = { event:'ready', url:handle.url, port:handle.port, pid:process.pid,
98
+ directory:command === 'open' ? handle.directory ?? null : null,
99
+ stateDirectory:handle.stateDirectory, instanceId:handle.id };
100
+ if (json) output.success(data,pendingWarnings.splice(0));
101
+ else { output.log(`ADG: ${handle.url}`); for (const warning of pendingWarnings.splice(0)) output.progress(warning.message); }
102
+ ready = true;
103
+ handle.openBrowser?.();
104
+ return await done;
105
+ } catch (cause) {
106
+ if (cause && typeof cause === 'object' && 'code' in cause && cause.code === 'EPIPE') brokenOutput = true;
107
+ return await finish(startupFailure ?? cause);
108
+ }
109
+ }