@whzxc/agent-design-gallery 0.6.0 → 0.8.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/README.md +12 -1
- package/package.json +1 -1
- package/public/app.js +38 -10
- package/public/arrangement-worker.js +11 -0
- package/public/arrangement.js +49 -0
- package/public/assets.js +16 -4
- package/public/layout.js +29 -13
- package/src/cli-output.mjs +258 -0
- package/src/cli.mjs +120 -45
- package/src/http.mjs +1 -0
- package/src/hub/auth.mjs +2 -1
- package/src/hub/proxy.mjs +5 -3
- package/src/hub/registry.mjs +57 -23
- package/src/hub.mjs +36 -21
- package/src/lifecycle.mjs +109 -0
- package/src/link.mjs +10 -9
- package/src/open.mjs +58 -54
- package/src/perf.mjs +12 -0
- package/src/server.mjs +78 -41
- package/src/service.mjs +115 -94
- package/src/toolkit/arch-git.mjs +142 -10
- package/src/toolkit/arch-overlay.mjs +1 -1
- package/src/toolkit/arch.mjs +62 -58
- package/src/toolkit/browser.mjs +38 -12
- package/src/toolkit/build-store.mjs +11 -3
- package/src/toolkit/build-worker.mjs +4 -1
- package/src/toolkit/build.mjs +26 -2
- package/src/toolkit/commands.mjs +158 -86
- package/src/toolkit/compare.mjs +93 -46
- package/src/toolkit/config.mjs +23 -20
- package/src/toolkit/diff-inputs.mjs +239 -0
- package/src/toolkit/diff-policy.mjs +28 -0
- package/src/toolkit/diff.mjs +258 -0
- package/src/toolkit/migrate.mjs +42 -30
- package/src/toolkit/part-diff.mjs +118 -0
- package/src/toolkit/part-snapshot.mjs +264 -0
- package/src/toolkit/pixel-diff.mjs +103 -0
- package/src/toolkit/project.mjs +45 -33
- package/src/toolkit/results.mjs +44 -0
- package/src/toolkit/runtime.d.ts +2 -1
- package/src/toolkit/tokens.mjs +5 -4
package/src/hub/registry.mjs
CHANGED
|
@@ -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
|
|
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 {
|
|
48
|
-
|
|
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
|
|
82
|
+
entries = await readDirectory(directory, { withFileTypes: true });
|
|
64
83
|
} catch (error) {
|
|
65
|
-
if (directory === root.path)
|
|
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
|
-
|
|
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
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
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
|
|
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
|
-
|
|
112
|
-
|
|
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)
|
|
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
|
|
70
|
-
|
|
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
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
async
|
|
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
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
|
|
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
|
+
}
|
package/src/link.mjs
CHANGED
|
@@ -1,28 +1,29 @@
|
|
|
1
|
+
import { CliError } from './cli-output.mjs';
|
|
1
2
|
import { readViewRoute, viewURL, viewerBase } from '../public/view-route.js';
|
|
2
3
|
|
|
3
4
|
export function previewTarget(options) {
|
|
4
5
|
const { asset, frame, group, layer, tokens, base, mode = 'query' } = options;
|
|
5
|
-
if (!['path', 'query'].includes(mode)) throw
|
|
6
|
+
if (!['path', 'query'].includes(mode)) throw new CliError('USAGE_INVALID', 'Choose --mode=path or --mode=query.');
|
|
6
7
|
const targets = [asset, group, layer, tokens].filter(value => value !== undefined && value !== false);
|
|
7
8
|
if (targets.length > 1 || (frame !== undefined && !asset) || targets.some(value => value === '') || frame === '')
|
|
8
|
-
throw
|
|
9
|
+
throw new CliError('USAGE_INVALID', 'Choose one of --asset, --group, --layer, or --tokens. --frame needs --asset.');
|
|
9
10
|
if (asset && (!/\.(tsx|svg|mmd)$/i.test(asset) || asset.includes('\\') || asset.split('/').some(part => !part || part === '.' || part === '..')))
|
|
10
|
-
throw
|
|
11
|
-
if (tokens && mode === 'path') throw
|
|
12
|
-
if(base!==undefined && !base.trim())throw
|
|
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.');
|
|
13
14
|
return { asset, frame, group, layer, tokens, mode, ...(base!==undefined?{base}:{}) };
|
|
14
15
|
}
|
|
15
16
|
|
|
16
17
|
export function previewURL(input, target) {
|
|
17
18
|
let base;
|
|
18
19
|
try { base = new URL(input); }
|
|
19
|
-
catch { throw
|
|
20
|
+
catch { throw new CliError('USAGE_INVALID', 'Enter an absolute ADG viewer URL.'); }
|
|
20
21
|
if (!['http:', 'https:'].includes(base.protocol) || base.username || base.password)
|
|
21
|
-
throw
|
|
22
|
+
throw new CliError('USAGE_INVALID', 'Enter an HTTP or HTTPS viewer URL without credentials.');
|
|
22
23
|
const pathname = base.pathname.replace(/^(\/(?:p|i)\/[A-Za-z0-9_-]+)$/, '$1/');
|
|
23
24
|
const root = viewerBase(pathname);
|
|
24
25
|
if (pathname !== root && !pathname.startsWith(`${root}view/`) && pathname !== `${root}index.html`)
|
|
25
|
-
throw
|
|
26
|
+
throw new CliError('USAGE_INVALID', 'Use a direct viewer, hub project, or live instance URL.');
|
|
26
27
|
const previous = target.asset || target.group || target.layer || target.tokens ? null : readViewRoute(base);
|
|
27
28
|
const [kind, ...name] = (previous?.scope ?? '').split(':');
|
|
28
29
|
const key = name.join(':');
|
|
@@ -37,7 +38,7 @@ export function previewURL(input, target) {
|
|
|
37
38
|
const revision=target.base ?? base.searchParams.get('base');
|
|
38
39
|
base.search = base.hash = '';
|
|
39
40
|
if(revision!==null && revision!==undefined)base.searchParams.set('base',revision);
|
|
40
|
-
if (tokens && mode === 'path') throw
|
|
41
|
+
if (tokens && mode === 'path') throw new CliError('USAGE_INVALID', 'Use --mode=query for --tokens.');
|
|
41
42
|
if (tokens) return viewURL(base, 'tokens');
|
|
42
43
|
if (mode === 'query') {
|
|
43
44
|
if (asset) base.searchParams.set('asset', asset);
|
package/src/open.mjs
CHANGED
|
@@ -1,57 +1,61 @@
|
|
|
1
|
-
import { spawn } from
|
|
2
|
-
import { loadConfig } from
|
|
3
|
-
import { registerInstance } from
|
|
4
|
-
import {
|
|
5
|
-
import
|
|
6
|
-
import
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { loadConfig } from './toolkit/config.mjs';
|
|
3
|
+
import { registerInstance } from './hub/instances.mjs';
|
|
4
|
+
import { defaultStateDirectory } from './hub/registry.mjs';
|
|
5
|
+
import { existsSync, unlinkSync } from 'node:fs';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import { startServer } from './server.mjs';
|
|
7
8
|
import { previewTarget, previewURL } from './link.mjs';
|
|
9
|
+
import { CliError, asCliError, sanitize } from './cli-output.mjs';
|
|
10
|
+
import { cleanup } from './toolkit/results.mjs';
|
|
8
11
|
|
|
9
|
-
export async function open(positionals, values
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
);
|
|
56
|
-
|
|
12
|
+
export async function open(positionals, values, {
|
|
13
|
+
cwd = process.cwd(), startViewer = startServer, register = registerInstance, spawnBrowser = spawn,
|
|
14
|
+
onDiagnostic, onFatal,
|
|
15
|
+
} = {}) {
|
|
16
|
+
if (positionals.length > 1) throw new CliError('USAGE_INVALID','Expected one directory. Run adg --help.');
|
|
17
|
+
const target = previewTarget(values), port = values.port === undefined ? 0 : Number(values.port);
|
|
18
|
+
if (!Number.isInteger(port) || port < 0 || port > 65535) throw new CliError('USAGE_INVALID','--port must be an integer from 0 to 65535.');
|
|
19
|
+
const input = path.resolve(cwd,positionals[0] ?? '.');
|
|
20
|
+
const config = await loadConfig(input);
|
|
21
|
+
if (values.base !== undefined && (!target.asset || target.asset.endsWith('.mmd'))) await (await import('./toolkit/arch-git.mjs')).resolveBase(config,values.base);
|
|
22
|
+
const directory = config.root === input && existsSync(config.design) ? config.design : input;
|
|
23
|
+
const stateDirectory = path.resolve(cwd,values['state-dir'] ?? defaultStateDirectory);
|
|
24
|
+
const server = await startViewer({directory,port,stateDirectory,onDiagnostic,onFatal});
|
|
25
|
+
let instance;
|
|
26
|
+
try { instance = await register({directory:server.directory,port:server.port,id:server.id,stateDirectory}); }
|
|
27
|
+
catch (cause) {
|
|
28
|
+
const primary = asCliError(cause);
|
|
29
|
+
await cleanup(() => server.close(),primary);
|
|
30
|
+
throw primary;
|
|
31
|
+
}
|
|
32
|
+
const exitCleanup = () => { try { unlinkSync(instance.file); } catch {} };
|
|
33
|
+
process.once('exit',exitCleanup);
|
|
34
|
+
const url = previewURL(server.url,target).href;
|
|
35
|
+
let closing;
|
|
36
|
+
return {
|
|
37
|
+
id:server.id,url,port:server.port,directory:server.directory,stateDirectory,
|
|
38
|
+
close() {
|
|
39
|
+
return closing ??= (async () => {
|
|
40
|
+
let primary;
|
|
41
|
+
try { await server.close(); }
|
|
42
|
+
catch (cause) { primary = new CliError('SHUTDOWN_FAILED',cause.message,{cause}); }
|
|
43
|
+
try { await cleanup(() => instance.remove(),primary); }
|
|
44
|
+
catch (cause) { primary = cause; }
|
|
45
|
+
finally { process.off('exit',exitCleanup); }
|
|
46
|
+
if (primary) throw primary;
|
|
47
|
+
})();
|
|
48
|
+
},
|
|
49
|
+
openBrowser() {
|
|
50
|
+
if (values['no-open']) return;
|
|
51
|
+
const command = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'rundll32.exe' : 'xdg-open';
|
|
52
|
+
const args = process.platform === 'win32' ? ['url.dll,FileProtocolHandler',url] : [url];
|
|
53
|
+
const warn=()=>{
|
|
54
|
+
const diagnostic={code:'BROWSER_OPEN_FAILED',message:`Open ${url} in your browser.`,next:[]};
|
|
55
|
+
if(onDiagnostic)onDiagnostic(diagnostic);else console.error(sanitize(diagnostic.message));
|
|
56
|
+
};
|
|
57
|
+
try {const child=spawnBrowser(command,args,{stdio:'ignore',detached:true});child.on('error',warn);child.unref();}
|
|
58
|
+
catch {warn();}
|
|
59
|
+
},
|
|
60
|
+
};
|
|
57
61
|
}
|
package/src/perf.mjs
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { appendFileSync } from 'node:fs';
|
|
2
|
+
|
|
3
|
+
// Opt-in local diagnostics. Epoch timestamps align Node and browser spans.
|
|
4
|
+
const destination = process.env.ADG_PERF_LOG;
|
|
5
|
+
export function perfSpan(phase, source, detail = {}) {
|
|
6
|
+
if (!destination) return;
|
|
7
|
+
const start = performance.timeOrigin + performance.now();
|
|
8
|
+
return (extra = {}) => appendFileSync(destination, JSON.stringify({
|
|
9
|
+
phase, source, start, end: performance.timeOrigin + performance.now(),
|
|
10
|
+
pid: process.pid, ...detail, ...extra,
|
|
11
|
+
}) + '\n');
|
|
12
|
+
}
|