@whzxc/agent-design-gallery 0.0.0-stage → 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.
Files changed (61) hide show
  1. package/LICENSE +69 -0
  2. package/README.md +218 -2
  3. package/package.json +43 -4
  4. package/public/access.css +10 -0
  5. package/public/app.js +1674 -0
  6. package/public/arrangement-worker.js +11 -0
  7. package/public/arrangement.js +49 -0
  8. package/public/assets.js +356 -0
  9. package/public/auth.js +69 -0
  10. package/public/favicon.svg +6 -0
  11. package/public/hub.css +67 -0
  12. package/public/hub.html +33 -0
  13. package/public/hub.js +165 -0
  14. package/public/icons.js +50 -0
  15. package/public/index.html +70 -0
  16. package/public/instance-actions.js +27 -0
  17. package/public/labels.js +122 -0
  18. package/public/layout.js +119 -0
  19. package/public/relationships.js +28 -0
  20. package/public/selection.js +20 -0
  21. package/public/style.css +194 -0
  22. package/public/switcher.css +37 -0
  23. package/public/switcher.js +176 -0
  24. package/public/token-catalog.js +129 -0
  25. package/public/tokens.css +61 -0
  26. package/public/view-route.js +66 -0
  27. package/src/cli-output.mjs +236 -0
  28. package/src/cli.mjs +176 -0
  29. package/src/http.mjs +38 -0
  30. package/src/hub/auth.mjs +41 -0
  31. package/src/hub/instances.mjs +99 -0
  32. package/src/hub/proxy.mjs +30 -0
  33. package/src/hub/registry.mjs +181 -0
  34. package/src/hub.mjs +128 -0
  35. package/src/lifecycle.mjs +109 -0
  36. package/src/link.mjs +55 -0
  37. package/src/open.mjs +61 -0
  38. package/src/perf.mjs +12 -0
  39. package/src/server.mjs +679 -0
  40. package/src/service.mjs +184 -0
  41. package/src/toolkit/arch-browser.mjs +40 -0
  42. package/src/toolkit/arch-git.mjs +55 -0
  43. package/src/toolkit/arch-overlay.mjs +225 -0
  44. package/src/toolkit/arch.mjs +221 -0
  45. package/src/toolkit/asset-rules.mjs +14 -0
  46. package/src/toolkit/browser.mjs +33 -0
  47. package/src/toolkit/build-store.mjs +266 -0
  48. package/src/toolkit/build-worker.mjs +35 -0
  49. package/src/toolkit/build.mjs +147 -0
  50. package/src/toolkit/commands.mjs +345 -0
  51. package/src/toolkit/compare.mjs +222 -0
  52. package/src/toolkit/config.mjs +136 -0
  53. package/src/toolkit/document.mjs +85 -0
  54. package/src/toolkit/migrate.mjs +85 -0
  55. package/src/toolkit/project.mjs +172 -0
  56. package/src/toolkit/results.mjs +44 -0
  57. package/src/toolkit/runtime.d.ts +14 -0
  58. package/src/toolkit/runtime.mjs +54 -0
  59. package/src/toolkit/text.mjs +12 -0
  60. package/src/toolkit/tokens.mjs +37 -0
  61. package/src/viewer-cache.mjs +85 -0
@@ -0,0 +1,99 @@
1
+ import { mkdir, readFile, writeFile, readdir, realpath, rename, rm, stat } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import os from 'node:os';
4
+ import { randomUUID } from 'node:crypto';
5
+ import { execFile } from 'node:child_process';
6
+ import { promisify } from 'node:util';
7
+ import { setTimeout as delay } from 'node:timers/promises';
8
+ import { loadConfig, VERSION } from '../toolkit/config.mjs';
9
+
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');
12
+ const exec = promisify(execFile);
13
+ const validId = id => typeof id === 'string' && /^[A-Za-z0-9_-]{1,128}$/.test(id);
14
+ const validPort = port => Number.isInteger(port) && port > 0 && port <= 65535;
15
+ const alive = pid => {
16
+ try { process.kill(pid, 0); return true; }
17
+ catch (error) { return error.code === 'EPERM'; }
18
+ };
19
+ async function git(directory, args) {
20
+ try { return (await exec('git', ['-C', directory, ...args], { maxBuffer: 1024 * 1024 })).stdout.trim(); }
21
+ catch { return null; }
22
+ }
23
+
24
+ export async function registerInstance({ directory, port, stateDirectory = defaultStateDirectory, id = randomUUID() }) {
25
+ if (!validId(id)) throw new Error('Instance id must contain only letters, numbers, underscores or hyphens.');
26
+ if (!validPort(port)) throw new Error('Instance port must be an integer from 1 to 65535.');
27
+ directory = await realpath(directory);
28
+ const config = await loadConfig(directory, { checkVersion: false });
29
+ const [branch, gitRoot] = await Promise.all([
30
+ git(directory, ['symbolic-ref', '--short', 'HEAD']), git(directory, ['rev-parse', '--show-toplevel']),
31
+ ]);
32
+ const worktree = !!gitRoot && !!(await stat(path.join(gitRoot, '.git')).catch(() => null))?.isFile();
33
+ const record = { id, pid: process.pid, port, directory, name: config.name, branch, worktree,
34
+ startedAt: new Date().toISOString(), version: VERSION };
35
+ const folder = path.join(stateDirectory, 'instances'), destination = path.join(folder, `${id}.json`);
36
+ await mkdir(folder, { recursive: true });
37
+ const temporary = `${destination}.${process.pid}.tmp`;
38
+ await writeFile(temporary, JSON.stringify(record, null, 2) + '\n');
39
+ await rename(temporary, destination);
40
+ return { record, file: destination, remove: () => rm(destination, { force: true }) };
41
+ }
42
+
43
+ async function inspectInstance(file) {
44
+ let record;
45
+ try { record = JSON.parse(await readFile(file, 'utf8')); }
46
+ catch (error) {
47
+ if (error.code === 'ENOENT') return null;
48
+ if (error instanceof SyntaxError) { await rm(file, { force: true }); return null; }
49
+ throw error;
50
+ }
51
+ if (!record || !validId(record.id) || `${record.id}.json` !== path.basename(file) || !validPort(record.port) ||
52
+ !Number.isInteger(record.pid) || record.pid <= 0 || !alive(record.pid)) {
53
+ await rm(file, { force: true });
54
+ return null;
55
+ }
56
+ let health;
57
+ const unavailable = reason => ({ ...record, proxyable: false, stoppable: false, url: null, reason });
58
+ try {
59
+ const response = await fetch(`http://127.0.0.1:${record.port}/api/health`, { signal: AbortSignal.timeout(750), redirect: 'error' });
60
+ if (!response.ok) return unavailable('health-unavailable');
61
+ health = await response.json();
62
+ } catch { return unavailable('health-unavailable'); }
63
+ if (typeof health?.id !== 'string') return unavailable('health-contract-missing');
64
+ if (health.id !== record.id) {
65
+ await rm(file, { force: true });
66
+ return null;
67
+ }
68
+ const proxyable = health.capabilities?.keyAuth === 1;
69
+ return { ...record, proxyable, stoppable: proxyable && record.pid !== process.pid,
70
+ url: proxyable ? `/i/${record.id}/` : null,
71
+ ...(!proxyable ? { reason: 'proxy-auth-unsupported' } : {}) };
72
+ }
73
+
74
+ export async function listInstances(stateDirectory = defaultStateDirectory) {
75
+ const folder = path.join(stateDirectory, 'instances');
76
+ let entries;
77
+ try { entries = await readdir(folder, { withFileTypes: true }); }
78
+ catch (error) { if (error.code === 'ENOENT') return []; throw error; }
79
+ const instances = await Promise.all(entries.filter(entry => entry.isFile() && entry.name.endsWith('.json'))
80
+ .map(entry => inspectInstance(path.join(folder, entry.name))));
81
+ return instances.filter(Boolean).sort((a, b) => String(a.startedAt).localeCompare(String(b.startedAt)) || a.id.localeCompare(b.id));
82
+ }
83
+
84
+ export async function stopInstance(id, stateDirectory = defaultStateDirectory) {
85
+ if (!validId(id)) return 404;
86
+ const file = path.join(stateDirectory, 'instances', `${id}.json`);
87
+ const record = await inspectInstance(file);
88
+ if (!record) return 404;
89
+ if (!record.stoppable) return 409;
90
+ try { process.kill(record.pid, 'SIGTERM'); }
91
+ catch (error) { if (error.code !== 'ESRCH') throw error; }
92
+ const deadline = Date.now() + 5000;
93
+ while (alive(record.pid)) {
94
+ if (Date.now() >= deadline) return 503;
95
+ await delay(50);
96
+ }
97
+ await rm(file, { force: true });
98
+ return 200;
99
+ }
@@ -0,0 +1,30 @@
1
+ import { request as httpRequest } from 'node:http';
2
+ import { CliError } from '../cli-output.mjs';
3
+
4
+ // Pipe through the owning server, preserving streaming and backpressure.
5
+ export function proxy(request, response, port, pathname, viewerBase, onDiagnostic) {
6
+ return new Promise(resolve => {
7
+ const headers = { ...request.headers, host: `127.0.0.1:${port}` };
8
+ for (const name of Object.keys(headers)) {
9
+ if (['authorization', 'x-adg-key', 'x-adg-viewer-base', 'cookie', 'forwarded', 'origin', 'connection'].includes(name) || name.startsWith('x-forwarded-')) delete headers[name];
10
+ }
11
+ if (viewerBase) headers['x-adg-viewer-base'] = viewerBase;
12
+ const target = new URL(pathname, 'http://localhost');
13
+ target.searchParams.delete('key');
14
+ const upstream = httpRequest({ hostname: '127.0.0.1', port, method: request.method, path: target.pathname + target.search, headers }, incoming => {
15
+ const outgoing = { ...incoming.headers };
16
+ delete outgoing['set-cookie'];
17
+ response.writeHead(incoming.statusCode, outgoing);
18
+ incoming.pipe(response);
19
+ incoming.on('error', error => { if (!response.destroyed) onDiagnostic?.(new CliError('NETWORK_FAILED',error.message,{cause:error})); response.destroy(); });
20
+ });
21
+ const done = () => { upstream.destroy(); resolve(); };
22
+ response.once('close', done);
23
+ upstream.on('error', error => {
24
+ if (!response.destroyed) onDiagnostic?.(new CliError('NETWORK_FAILED','Viewer unavailable.',{cause:error}));
25
+ if (!response.headersSent) response.writeHead(502, { 'Content-Type': 'application/json' });
26
+ if (!response.destroyed) response.end(JSON.stringify({ error: 'Viewer unavailable.' }));
27
+ });
28
+ request.pipe(upstream);
29
+ });
30
+ }
@@ -0,0 +1,181 @@
1
+ import { readFile, writeFile, mkdir, readdir, realpath, stat, rename } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import os from 'node:os';
4
+ import { createHash } from 'node:crypto';
5
+ import { execFile } from 'node:child_process';
6
+ import { promisify } from 'node:util';
7
+ import { configFile, loadConfig, VERSION, requireMigration, legacyConfigFile } from '../toolkit/config.mjs';
8
+ import { listSources, archFiles } from '../toolkit/project.mjs';
9
+ import { CliError } from '../cli-output.mjs';
10
+
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');
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
+ };
20
+ export function projectSlug(directory) {
21
+ return path.basename(directory).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'project';
22
+ }
23
+ const pathHash = directory => createHash('sha256').update(directory).digest('hex');
24
+ function assignSlugs(data, previousRoots) {
25
+ const directories = [...new Set(data.roots.flatMap(root => root.projects.map(project => project.path)))].sort();
26
+ const current = new Set(directories);
27
+ const assigned = new Map(previousRoots.flatMap(root => root.projects)
28
+ .filter(project => current.has(project.path))
29
+ // Upgrade the old always-hashed format on the next explicit scan.
30
+ .filter(project => data.slugVersion === 1 || project.slug !== `${projectSlug(project.path)}-${pathHash(project.path).slice(0, 12)}`)
31
+ .map(project => [project.path, project.slug]));
32
+ const used = new Set(assigned.values());
33
+ const pending = [];
34
+ for (const directory of directories) {
35
+ if (assigned.has(directory)) continue;
36
+ const slug = projectSlug(directory);
37
+ if (used.has(slug)) { pending.push(directory); continue; }
38
+ assigned.set(directory, slug);
39
+ used.add(slug);
40
+ }
41
+ for (const directory of pending) {
42
+ const base = `${projectSlug(directory)}-${projectSlug(path.dirname(directory))}`;
43
+ let slug = base, length = 6;
44
+ while (used.has(slug)) slug = `${base}-${pathHash(directory).slice(0, length++)}`;
45
+ assigned.set(directory, slug);
46
+ used.add(slug);
47
+ }
48
+ for (const root of data.roots) {
49
+ for (const project of root.projects) project.slug = assigned.get(project.path);
50
+ }
51
+ data.slugVersion = 1;
52
+ }
53
+ async function registry(stateDirectory) {
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
+ }
64
+ }
65
+ async function save(data, stateDirectory) {
66
+ await mkdir(stateDirectory, { recursive: true });
67
+ const destination = path.join(stateDirectory, 'registry.json'), temporary = `${destination}.${process.pid}.tmp`;
68
+ await writeFile(temporary, JSON.stringify(data, null, 2) + '\n');
69
+ await rename(temporary, destination);
70
+ }
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
+ };
76
+ const projects = [];
77
+ async function visit(directory, depth) {
78
+ if (path.basename(directory).startsWith('.') || path.basename(directory) === 'node_modules') return;
79
+ let entries;
80
+ try {
81
+ if ((await stat(path.join(directory, '.git')).catch(() => null))?.isFile()) return;
82
+ entries = await readDirectory(directory, { withFileTypes: true });
83
+ } catch (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, ' ')}`);
89
+ return;
90
+ }
91
+ if (configFile(directory) || legacyConfigFile(directory)) {
92
+ projects.push({ path: directory });
93
+ try {
94
+ await loadConfig(directory, { checkVersion: false });
95
+ } catch (error) {
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}`);
98
+ }
99
+ }
100
+ if (depth >= root.depth) return;
101
+ for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
102
+ if (!entry.isDirectory() || entry.name.startsWith('.') || entry.name === 'node_modules') continue;
103
+ await visit(path.join(directory, entry.name), depth + 1);
104
+ }
105
+ }
106
+ await visit(root.path, 0);
107
+ return { ...root, projects, scannedAt: new Date().toISOString() };
108
+ }
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);
119
+ const previousRoots = data.roots;
120
+ data.roots = [...data.roots.filter(item => item.path !== root), entry].sort((a, b) => a.path.localeCompare(b.path));
121
+ assignSlugs(data, previousRoots);
122
+ await save(data, stateDirectory);
123
+ return rootResult(stateDirectory, await listRoots(stateDirectory), [root], warnings);
124
+ }
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()));
128
+ throw error;
129
+ });
130
+ const data = await registry(stateDirectory);
131
+ if (!data.roots.some(item => item.path === root)) throw new CliError('ROOT_NOT_REGISTERED', `Root is not registered: ${directory}`);
132
+ data.roots = data.roots.filter(item => item.path !== root);
133
+ await save(data, stateDirectory);
134
+ return rootResult(stateDirectory, await listRoots(stateDirectory), [root]);
135
+ }
136
+ export async function listRoots(stateDirectory = defaultStateDirectory) {
137
+ return (await registry(stateDirectory)).roots.map(({ projects, ...root }) => ({ ...root, projectCount: projects.length }));
138
+ }
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 = [];
144
+ const previousRoots = [...data.roots];
145
+ for (let index = 0; index < data.roots.length; 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
+ }
150
+ }
151
+ assignSlugs(data, previousRoots);
152
+ await save(data, stateDirectory);
153
+ return rootResult(stateDirectory, await listRoots(stateDirectory), affected.sort(), warnings);
154
+ }
155
+ const git = async (directory, args) => {
156
+ try { return (await exec('git', ['-C', directory, ...args], { maxBuffer: 1024 * 1024 })).stdout.trim(); }
157
+ catch { return null; }
158
+ };
159
+ export async function projectMetadata(record) {
160
+ const base = { ...record, name: path.basename(record.path), design: null, branch: null, head: null,
161
+ lastDesignChange: { committedAt: null, dirty: false }, sourceCount: null, frameCount: null,
162
+ compatibility: { version: VERSION, requires: null, compatible: null } };
163
+ try {
164
+ requireMigration(record.path);
165
+ if (!configFile(record.path)) throw new Error('Project config is missing; rescan registered roots.');
166
+ const config = await loadConfig(record.path, { checkVersion: false });
167
+ const relative = path.relative(record.path, config.design) || '.';
168
+ const [branch, head, committedAt, dirty] = await Promise.all([
169
+ git(record.path, ['symbolic-ref', '--short', 'HEAD']), git(record.path, ['rev-parse', '--short', 'HEAD']),
170
+ git(record.path, ['log', '-1', '--format=%cI', '--', relative]), git(record.path, ['status', '--porcelain', '--untracked-files=all', '--', relative]),
171
+ ]);
172
+ return { ...base, name: config.name, design: config.design, branch, head,
173
+ lastDesignChange: { committedAt: committedAt || null, dirty: !!dirty }, sourceCount: listSources(config.design, config.sources).length + archFiles(config.arch).length,
174
+ compatibility: { version: VERSION, requires: config.requires, compatible: config.compatible } };
175
+ } catch (error) { return { ...base, error: error.message }; }
176
+ }
177
+ export async function listProjects(stateDirectory = defaultStateDirectory) {
178
+ const records = (await registry(stateDirectory)).roots.flatMap(root => root.projects);
179
+ const unique = [...new Map(records.map(project => [project.path, project])).values()].sort((a, b) => a.path.localeCompare(b.path));
180
+ return Promise.all(unique.map(projectMetadata));
181
+ }
package/src/hub.mjs ADDED
@@ -0,0 +1,128 @@
1
+ import { createServer } from 'node:http';
2
+ import { randomUUID } from 'node:crypto';
3
+ import path from 'node:path';
4
+ import { startServer } from './server.mjs';
5
+ import { listProjects, listRoots, scanRoots, defaultStateDirectory } from './hub/registry.mjs';
6
+ import { proxy } from './hub/proxy.mjs';
7
+ import { listInstances, stopInstance } from './hub/instances.mjs';
8
+ import { hubKey, authorized } from './hub/auth.mjs';
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';
13
+
14
+ export async function startHub({ port = 4310, stateDirectory = defaultStateDirectory, idleTimeout = 300_000, onDiagnostic, onFatal, startViewer = startServer } = {}) {
15
+ await hubKey(stateDirectory);
16
+ let closing = false;
17
+ const id = randomUUID(), viewers = new Map(), streams = new Set();
18
+ const stopping = new Map();
19
+ const projects = async () => (await listProjects(stateDirectory)).map(project => ({ ...project, ...viewers.get(project.slug)?.viewer?.stats(), url: `/p/${project.slug}/` }));
20
+ const server = createServer(async (request, response) => {
21
+ try {
22
+ if (closing) return json(response, 503, { error: 'Hub is stopping.' });
23
+ const url = new URL(request.url, 'http://localhost');
24
+ const read = ['GET', 'HEAD'].includes(request.method);
25
+ const projectRoute = url.pathname.match(/^\/p\/([A-Za-z0-9_-]+)(\/.*)?$/);
26
+ const instanceRoute = url.pathname.match(/^\/i\/([A-Za-z0-9_-]+)(\/.*)?$/);
27
+ const stopRoute = url.pathname.match(/^\/api\/instances\/([A-Za-z0-9_-]+)\/stop$/);
28
+ const route = projectRoute ?? instanceRoute;
29
+ const publicFile = read && (route ? viewerFile(route[2] ?? '/') : { '/': 'hub.html', '/hub.js': 'hub.js', '/auth.js': 'auth.js', '/icons.js': 'icons.js', '/tokens.css': 'tokens.css', '/hub.css': 'hub.css', '/access.css': 'access.css', '/favicon.svg': 'favicon.svg', '/instance-actions.js': 'instance-actions.js' }[url.pathname]);
30
+ // Project shells do not discover, build, watch, or embed any project data.
31
+ // The switcher manages hub destinations, including in viewers started before this hub version.
32
+ if (publicFile && (!instanceRoute || ['switcher.js', 'switcher.css', 'instance-actions.js'].includes(publicFile))) {
33
+ if (route && !route[2]) { response.writeHead(302, { Location: `${url.pathname}/${url.search}` }); response.end(); return; }
34
+ return await shell(request, response, publicFile, projectRoute && `/p/${projectRoute[1]}/`);
35
+ }
36
+ if (!publicFile && !await authorized(request, url, stateDirectory)) return json(response, 401, { error: 'Unauthorized' });
37
+ if (request.method === 'POST' && request.headers.origin && ![`http://${request.headers.host}`, `https://${request.headers.host}`].includes(request.headers.origin))
38
+ return json(response, 403, { error: 'Cross-origin request refused.' });
39
+ if (url.pathname === '/api/health' && request.method === 'GET') return json(response, 200, { id });
40
+ if (url.pathname === '/api/projects' && request.method === 'GET') return json(response, 200, await projects());
41
+ if (url.pathname === '/api/instances' && request.method === 'GET') return json(response, 200, await listInstances(stateDirectory));
42
+ if (stopRoute && request.method === 'POST') {
43
+ const instanceId = stopRoute[1];
44
+ if (!stopping.has(instanceId))
45
+ stopping.set(instanceId, stopInstance(instanceId, stateDirectory).finally(() => stopping.delete(instanceId)));
46
+ const status = await stopping.get(instanceId);
47
+ if (status === 200) return json(response, 200, { ok: true });
48
+ const error = { 404: 'Instance is no longer live.', 409: 'Cannot verify that this viewer can be stopped.',
49
+ 503: 'The viewer is still shutting down.' }[status];
50
+ return json(response, status, { error });
51
+ }
52
+ if (url.pathname === '/api/roots' && request.method === 'GET') return json(response, 200, await listRoots(stateDirectory));
53
+ if (url.pathname === '/api/rescan' && request.method === 'POST') return json(response, 200, (await scanRoots(undefined, stateDirectory)).data.roots);
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.' });
56
+ if (instanceRoute) {
57
+ const instance = (await listInstances(stateDirectory)).find(item => item.id === instanceRoute[1]);
58
+ if (!instance) return json(response, 404, { error: 'Instance is no longer live.' });
59
+ if (!instance.proxyable) return json(response, 409, { error: 'Instance viewer does not support authenticated proxying.' });
60
+ if (!route[2]) { response.writeHead(302, { Location: `${url.pathname}/${url.search}` }); response.end(); return; }
61
+ streams.add(response);
62
+ try { await proxy(request, response, instance.port, route[2] + url.search, `/i/${instance.id}/`, onDiagnostic); }
63
+ finally { streams.delete(response); }
64
+ return;
65
+ }
66
+ const slug = projectRoute[1];
67
+ let entry = viewers.get(slug);
68
+ if (!entry) {
69
+ entry = { active: 0, last: Date.now() };
70
+ entry.pending = (async () => {
71
+ const project = (await listProjects(stateDirectory)).find(item => item.slug === 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 });
75
+ return entry.viewer;
76
+ })();
77
+ viewers.set(slug, entry);
78
+ }
79
+ try { await entry.pending; }
80
+ catch (error) { if (viewers.get(slug) === entry) viewers.delete(slug); throw error; }
81
+ entry.active++;
82
+ try { await proxy(request, response, entry.viewer.port, route[2] + url.search, undefined, onDiagnostic); }
83
+ finally { entry.active--; entry.last = Date.now(); }
84
+ return;
85
+ }
86
+ json(response, read ? 404 : 405, { error: 'Not found.' });
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;
91
+ if (response.headersSent) response.destroy();
92
+ else json(response, 400, { error: error.message });
93
+ }
94
+ });
95
+ const reap = setInterval(() => {
96
+ for (const [slug, entry] of viewers) {
97
+ if (!entry.active && entry.viewer && Date.now() - entry.last > idleTimeout) {
98
+ viewers.delete(slug);
99
+ entry.viewer.close().catch(error => { if (!closing) onDiagnostic?.(new CliError('SHUTDOWN_FAILED',error.message,{cause:error})); });
100
+ }
101
+ }
102
+ }, Math.min(idleTimeout, 30_000));
103
+ reap.unref();
104
+ let closePromise;
105
+ const close = () => closePromise ??= (async () => {
106
+ closing = true; clearInterval(reap);
107
+ let primary;
108
+ const steps = [async () => {
109
+ for (const response of streams) response.destroy();
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,
127
+ };
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
+ }
package/src/link.mjs ADDED
@@ -0,0 +1,55 @@
1
+ import { CliError } from './cli-output.mjs';
2
+ import { readViewRoute, viewURL, viewerBase } from '../public/view-route.js';
3
+
4
+ export function previewTarget(options) {
5
+ const { asset, frame, group, layer, tokens, base, mode = 'query' } = options;
6
+ if (!['path', 'query'].includes(mode)) throw new CliError('USAGE_INVALID', 'Choose --mode=path or --mode=query.');
7
+ const targets = [asset, group, layer, tokens].filter(value => value !== undefined && value !== false);
8
+ if (targets.length > 1 || (frame !== undefined && !asset) || targets.some(value => value === '') || frame === '')
9
+ throw new CliError('USAGE_INVALID', 'Choose one of --asset, --group, --layer, or --tokens. --frame needs --asset.');
10
+ if (asset && (!/\.(tsx|svg|mmd)$/i.test(asset) || asset.includes('\\') || asset.split('/').some(part => !part || part === '.' || part === '..')))
11
+ throw new CliError('USAGE_INVALID', 'Use a design-relative .tsx/.svg or project-root-relative .mmd file path for --asset.');
12
+ if (tokens && mode === 'path') throw new CliError('USAGE_INVALID', 'Use --mode=query for --tokens.');
13
+ if(base!==undefined && !base.trim())throw new CliError('USAGE_INVALID', 'Set --base to a Git revision, for example HEAD.');
14
+ return { asset, frame, group, layer, tokens, mode, ...(base!==undefined?{base}:{}) };
15
+ }
16
+
17
+ export function previewURL(input, target) {
18
+ let base;
19
+ try { base = new URL(input); }
20
+ catch { throw new CliError('USAGE_INVALID', 'Enter an absolute ADG viewer URL.'); }
21
+ if (!['http:', 'https:'].includes(base.protocol) || base.username || base.password)
22
+ throw new CliError('USAGE_INVALID', 'Enter an HTTP or HTTPS viewer URL without credentials.');
23
+ const pathname = base.pathname.replace(/^(\/(?:p|i)\/[A-Za-z0-9_-]+)$/, '$1/');
24
+ const root = viewerBase(pathname);
25
+ if (pathname !== root && !pathname.startsWith(`${root}view/`) && pathname !== `${root}index.html`)
26
+ throw new CliError('USAGE_INVALID', 'Use a direct viewer, hub project, or live instance URL.');
27
+ const previous = target.asset || target.group || target.layer || target.tokens ? null : readViewRoute(base);
28
+ const [kind, ...name] = (previous?.scope ?? '').split(':');
29
+ const key = name.join(':');
30
+ const asset = target.asset ?? previous?.target?.path ?? (kind === 'asset' ? key : null);
31
+ const group = asset ? null : target.group ?? previous?.target?.group ?? (kind === 'group' ? key : null);
32
+ const layer = target.layer ?? (kind === 'layer' ? key : null);
33
+ const frame = target.frame ?? previous?.target?.form;
34
+ const element = frame && previous?.target?.element;
35
+ const tokens = target.tokens || kind === 'tokens';
36
+ const { mode } = target;
37
+ base.pathname = root;
38
+ const revision=target.base ?? base.searchParams.get('base');
39
+ base.search = base.hash = '';
40
+ if(revision!==null && revision!==undefined)base.searchParams.set('base',revision);
41
+ if (tokens && mode === 'path') throw new CliError('USAGE_INVALID', 'Use --mode=query for --tokens.');
42
+ if (tokens) return viewURL(base, 'tokens');
43
+ if (mode === 'query') {
44
+ if (asset) base.searchParams.set('asset', asset);
45
+ if (group) base.searchParams.set('group', group);
46
+ if (!asset && !group && layer) base.searchParams.set('scope', `layer:${layer}`);
47
+ if (!asset && !group && kind === 'all') base.searchParams.set('scope', 'all');
48
+ if (frame) base.searchParams.set('frame', frame);
49
+ if (element) base.searchParams.set('element', element.id);
50
+ return base;
51
+ }
52
+ const parent = layer ?? (asset?.endsWith('.mmd') ? 'arch' : asset?.includes('/') ? asset.split('/')[0] : null);
53
+ if (!parent && !group && !asset && kind !== 'all') return base;
54
+ return viewURL(base, parent ? `layer:${parent}` : 'all', { path: asset, group, form: frame, element });
55
+ }