@whzxc/agent-design-gallery 0.0.0-stage → 0.6.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/LICENSE +69 -0
- package/README.md +216 -2
- package/package.json +43 -4
- package/public/access.css +10 -0
- package/public/app.js +1646 -0
- package/public/assets.js +344 -0
- package/public/auth.js +69 -0
- package/public/favicon.svg +6 -0
- package/public/hub.css +67 -0
- package/public/hub.html +33 -0
- package/public/hub.js +165 -0
- package/public/icons.js +50 -0
- package/public/index.html +70 -0
- package/public/instance-actions.js +27 -0
- package/public/labels.js +122 -0
- package/public/layout.js +103 -0
- package/public/relationships.js +28 -0
- package/public/selection.js +20 -0
- package/public/style.css +194 -0
- package/public/switcher.css +37 -0
- package/public/switcher.js +176 -0
- package/public/token-catalog.js +129 -0
- package/public/tokens.css +61 -0
- package/public/view-route.js +66 -0
- package/src/cli.mjs +105 -0
- package/src/http.mjs +37 -0
- package/src/hub/auth.mjs +40 -0
- package/src/hub/instances.mjs +99 -0
- package/src/hub/proxy.mjs +28 -0
- package/src/hub/registry.mjs +147 -0
- package/src/hub.mjs +113 -0
- package/src/link.mjs +54 -0
- package/src/open.mjs +57 -0
- package/src/server.mjs +642 -0
- package/src/service.mjs +163 -0
- package/src/toolkit/arch-browser.mjs +40 -0
- package/src/toolkit/arch-git.mjs +54 -0
- package/src/toolkit/arch-overlay.mjs +225 -0
- package/src/toolkit/arch.mjs +217 -0
- package/src/toolkit/asset-rules.mjs +14 -0
- package/src/toolkit/browser.mjs +21 -0
- package/src/toolkit/build-store.mjs +258 -0
- package/src/toolkit/build-worker.mjs +32 -0
- package/src/toolkit/build.mjs +133 -0
- package/src/toolkit/commands.mjs +273 -0
- package/src/toolkit/compare.mjs +175 -0
- package/src/toolkit/config.mjs +135 -0
- package/src/toolkit/document.mjs +85 -0
- package/src/toolkit/migrate.mjs +73 -0
- package/src/toolkit/project.mjs +160 -0
- package/src/toolkit/runtime.d.ts +14 -0
- package/src/toolkit/runtime.mjs +54 -0
- package/src/toolkit/text.mjs +12 -0
- package/src/toolkit/tokens.mjs +36 -0
- package/src/viewer-cache.mjs +85 -0
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
const locatorKeys = ['scope', 'group', 'asset', 'frame', 'element'];
|
|
2
|
+
|
|
3
|
+
export function viewerBase(pathname) {
|
|
4
|
+
return pathname.match(/^\/(?:p|i)\/[A-Za-z0-9_-]+\//)?.[0] ?? '/';
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export function isViewPath(pathname) {
|
|
8
|
+
return pathname.startsWith('/view/');
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function readViewRoute(url) {
|
|
12
|
+
const query = url.searchParams;
|
|
13
|
+
const base=query.has('base')?{base:query.get('base')}:{};
|
|
14
|
+
const path = url.pathname.slice(viewerBase(url.pathname).length);
|
|
15
|
+
const explicitScope = query.get('scope');
|
|
16
|
+
const asset = query.get('asset'), group = query.get('group');
|
|
17
|
+
if (explicitScope || asset || group) {
|
|
18
|
+
return {
|
|
19
|
+
...base,
|
|
20
|
+
scope: explicitScope ?? (asset ? `asset:${asset}` : `group:${group}`),
|
|
21
|
+
target: asset || group ? { path: asset, group, form: query.get('frame'), element: query.has('element') ? { id: query.get('element') } : null } : null,
|
|
22
|
+
onlyFrame: asset && !explicitScope ? query.get('frame') : null,
|
|
23
|
+
isolated: true,
|
|
24
|
+
strict: !explicitScope,
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
if (path.startsWith('view/')) {
|
|
28
|
+
const match = /^view\/(?:all|layer\/([^/]+))(?:\/(group|asset)\/([^/]+)(?:\/frame\/([^/]+)(?:\/element\/([^/]+))?)?)?\/?$/.exec(path);
|
|
29
|
+
if (!match) throw Error('Invalid design path. Use a link generated by ADG.');
|
|
30
|
+
const [layer, kind, key, frame, element] = match.slice(1).map(value => value === undefined ? null : decodeURIComponent(value));
|
|
31
|
+
if (kind !== 'asset' && frame) throw Error('A frame needs an asset path.');
|
|
32
|
+
return {
|
|
33
|
+
...base,
|
|
34
|
+
scope: layer ? `layer:${layer}` : 'all',
|
|
35
|
+
target: kind ? { path: kind === 'asset' ? key : null, group: kind === 'group' ? key : null, form: frame, element: element ? { id: element } : null } : null,
|
|
36
|
+
strict: true,
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
return { ...base, scope: 'default', target: null };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function viewURL(base, scope, target = {}, { isolated = false, onlyFrame = null } = {}) {
|
|
43
|
+
const url = new URL(base);
|
|
44
|
+
url.pathname = viewerBase(url.pathname);
|
|
45
|
+
for (const key of locatorKeys) url.searchParams.delete(key);
|
|
46
|
+
const { path, group, form, element } = target;
|
|
47
|
+
if (onlyFrame) {
|
|
48
|
+
url.searchParams.set('asset', path);
|
|
49
|
+
url.searchParams.set('frame', onlyFrame);
|
|
50
|
+
if (element?.id != null) url.searchParams.set('element', element.id);
|
|
51
|
+
} else if (isolated || !['all', 'layer'].includes(scope.split(':', 1)[0])) {
|
|
52
|
+
url.searchParams.set('scope', scope);
|
|
53
|
+
if (path) url.searchParams.set('asset', path);
|
|
54
|
+
else if (group) url.searchParams.set('group', group);
|
|
55
|
+
if (path && form) url.searchParams.set('frame', form);
|
|
56
|
+
if (path && form && element?.id != null) url.searchParams.set('element', element.id);
|
|
57
|
+
} else {
|
|
58
|
+
const segments = ['view', ...(scope === 'all' ? ['all'] : ['layer', scope.slice('layer:'.length)])];
|
|
59
|
+
if (path) segments.push('asset', path);
|
|
60
|
+
else if (group) segments.push('group', group);
|
|
61
|
+
if (path && form) segments.push('frame', form);
|
|
62
|
+
if (path && form && element?.id != null) segments.push('element', element.id);
|
|
63
|
+
url.pathname += segments.map(encodeURIComponent).join('/');
|
|
64
|
+
}
|
|
65
|
+
return url;
|
|
66
|
+
}
|
package/src/cli.mjs
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { parseArgs } from 'node:util';
|
|
4
|
+
import { pathToFileURL } from 'node:url';
|
|
5
|
+
import { realpathSync } from 'node:fs';
|
|
6
|
+
import { VERSION, loadConfig } from './toolkit/config.mjs';
|
|
7
|
+
|
|
8
|
+
export const commands = ['open', 'link', 'serve', 'root', 'service', 'migrate', 'init', 'check', 'render', 'compare'];
|
|
9
|
+
const targetOptions = '[--asset=<path> [--frame=<name>] | --group=<name> | --layer=<name> | --tokens] [--mode=query|path] [--base=<rev>]';
|
|
10
|
+
const usage = {
|
|
11
|
+
open: `[directory] [--port=<n>] [--no-open] [--state-dir=<path>] ${targetOptions}`,
|
|
12
|
+
link: `<viewer-url> ${targetOptions}`,
|
|
13
|
+
serve: '[--port=4310] [--state-dir=<path>] [--print-key | --rotate-key]',
|
|
14
|
+
service: 'install|uninstall|status|logs|migrate [--state-dir=<path>] [--port=4310]',
|
|
15
|
+
root: 'add <dir> [--depth=2] | remove <dir> | list | scan [dir] [--state-dir=<path>]',
|
|
16
|
+
migrate: '[project]', init: '', check: '[source...] [--read-only]', render: '[source...] [--frame=<name>] [--theme=both|light|dark] [--scale=2] [--out-dir=<path>] [--json] [--base=<rev>]',
|
|
17
|
+
compare: '<source> --frame=<name> [--fixture=<name>] [--region=<name> | --selector=<css> | --page] [--origin="<x> <y>"] [--click=<name>...] [--viewport=<w>x<h>] | --all',
|
|
18
|
+
};
|
|
19
|
+
const details = {
|
|
20
|
+
migrate: 'Rename a project configuration and runtime imports, update editor paths and ignore entries, remove old generated files and regenerate declarations. Refuses mixed config names; safe to run again.',
|
|
21
|
+
serve: 'Run the resident multi-project hub on 127.0.0.1. Projects build on viewer access and idle viewers stop after five minutes. --print-key prints the key and exits; --rotate-key rotates the running hub key and exits. Forwarded data requests require a header or query key; direct-local requests are exempt.',
|
|
22
|
+
service: 'Manage the macOS resident hub LaunchAgent. install starts it with RunAtLoad and KeepAlive, recording absolute Node/CLI paths. --port applies only to install. status prints JSON; logs prints the last 200 lines per log. Uninstall retains state and logs. migrate moves old hub state and replaces its LaunchAgent, then lists other agents referencing the old state path. --state-dir selects the migration destination. Other platforms are unsupported.',
|
|
23
|
+
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
|
+
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
|
+
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
|
+
compare: 'Compare fixture text positions. Flags override Frame fixture and capture. --all writes a summary for every fixture frame.',
|
|
28
|
+
};
|
|
29
|
+
export function help(command) {
|
|
30
|
+
if (command) return `Usage: adg ${command} ${usage[command]}\n\n${details[command]}\n\n-h, --help Show help\nExit codes: 0 success, 1 check/compare problems, 2 usage/configuration/environment error.`;
|
|
31
|
+
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
|
+
export function parseCli(args) {
|
|
34
|
+
const explicit = commands.includes(args[0]), command = explicit ? args[0] : 'open';
|
|
35
|
+
const options = { help: { type: 'boolean', short: 'h' }, version: { type: 'boolean', short: 'v' } };
|
|
36
|
+
const locators = ['asset', 'frame', 'group', 'layer', 'mode', 'base'];
|
|
37
|
+
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
|
+
for (const name of strings[command] ?? []) options[name] = { type: 'string' };
|
|
39
|
+
if (command === 'serve') for (const name of ['print-key', 'rotate-key']) options[name] = { type: 'boolean' };
|
|
40
|
+
if (command === 'open') options['no-open'] = { type: 'boolean' };
|
|
41
|
+
if (command === 'open' || command === 'link') options.tokens = { type: 'boolean' };
|
|
42
|
+
if (command === 'render') options.json = { type: 'boolean' };
|
|
43
|
+
if (command === 'check') options['read-only'] = { type: 'boolean' };
|
|
44
|
+
if (command === 'compare') { options.all = { type: 'boolean' }; options.page = { type: 'boolean' }; }
|
|
45
|
+
if (command === 'compare') options.click = { type: 'string', multiple: true };
|
|
46
|
+
let parsed;
|
|
47
|
+
try { parsed = parseArgs({ args: explicit ? args.slice(1) : args, options, allowPositionals: true }); }
|
|
48
|
+
catch (error) { throw new Error(`${error.message}; run adg ${command} --help`); }
|
|
49
|
+
const { values, positionals } = parsed;
|
|
50
|
+
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`);
|
|
52
|
+
}
|
|
53
|
+
return { command, values, positionals, explicit };
|
|
54
|
+
}
|
|
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);
|
|
61
|
+
if (command === 'link') {
|
|
62
|
+
if (positionals.length !== 1) throw Error('Expected one viewer URL. Run adg link --help.');
|
|
63
|
+
const { previewTarget, previewURL } = await import('./link.mjs');
|
|
64
|
+
console.log(previewURL(positionals[0], previewTarget(values)).href);
|
|
65
|
+
return 0;
|
|
66
|
+
}
|
|
67
|
+
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);
|
|
70
|
+
}
|
|
71
|
+
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');
|
|
74
|
+
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;
|
|
80
|
+
}
|
|
81
|
+
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;
|
|
93
|
+
}
|
|
94
|
+
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);
|
|
98
|
+
}
|
|
99
|
+
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
|
+
});
|
|
105
|
+
}
|
package/src/http.mjs
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import { isViewPath } from '../public/view-route.js';
|
|
3
|
+
|
|
4
|
+
export function directLocal(request) {
|
|
5
|
+
return /^(?:localhost|127\.0\.0\.1|\[::1\])(?::\d+)?$|^::1$/i.test(request.headers.host ?? '') &&
|
|
6
|
+
!Object.keys(request.headers).some(name => name.toLowerCase() === 'forwarded' || name.toLowerCase().startsWith('x-forwarded-'));
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export const viewerFiles = {
|
|
10
|
+
'/access.css': 'access.css', '/switcher.js': 'switcher.js', '/switcher.css': 'switcher.css', '/instance-actions.js': 'instance-actions.js',
|
|
11
|
+
'/': 'index.html', '/index.html': 'index.html', '/app.js': 'app.js', '/auth.js': 'auth.js', '/favicon.svg': 'favicon.svg',
|
|
12
|
+
'/assets.js': 'assets.js', '/icons.js': 'icons.js', '/layout.js': 'layout.js', '/labels.js': 'labels.js',
|
|
13
|
+
'/relationships.js': 'relationships.js', '/selection.js': 'selection.js', '/style.css': 'style.css', '/tokens.css': 'tokens.css',
|
|
14
|
+
'/token-catalog.js': 'token-catalog.js',
|
|
15
|
+
'/view-route.js': 'view-route.js',
|
|
16
|
+
};
|
|
17
|
+
export const viewerFile = pathname => isViewPath(pathname) ? 'index.html' : viewerFiles[pathname];
|
|
18
|
+
const designFiles = { 'tokens.css': 'tokens.css', 'favicon.svg': 'art/adg-mark.svg' };
|
|
19
|
+
const shellTypes = { '.html': 'text/html', '.css': 'text/css', '.svg': 'image/svg+xml' };
|
|
20
|
+
export function json(response, code, data) {
|
|
21
|
+
response.writeHead(code, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
|
|
22
|
+
response.end(JSON.stringify(data));
|
|
23
|
+
}
|
|
24
|
+
export async function shell(request, response, file, base = '/') {
|
|
25
|
+
const packaged = new URL(`../public/${file}`, import.meta.url);
|
|
26
|
+
const source = designFiles[file];
|
|
27
|
+
let content = source
|
|
28
|
+
? await readFile(new URL(`../design/${source}`, import.meta.url)).catch(() => readFile(packaged))
|
|
29
|
+
: await readFile(packaged);
|
|
30
|
+
if (file === 'index.html' && /^\/(?:p|i)\/[A-Za-z0-9_-]+\/$/.test(base)) {
|
|
31
|
+
content = content.toString('utf8').replace('<base href="/">', `<base href="${base}">`);
|
|
32
|
+
}
|
|
33
|
+
const type = shellTypes[file.slice(file.lastIndexOf('.'))] ?? 'text/javascript';
|
|
34
|
+
response.writeHead(200, { 'Content-Type': `${type}; charset=utf-8`,
|
|
35
|
+
'Cache-Control': 'no-cache', 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'no-referrer' });
|
|
36
|
+
response.end(request.method === 'HEAD' ? undefined : content);
|
|
37
|
+
}
|
package/src/hub/auth.mjs
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { randomBytes, createHash, timingSafeEqual } from 'node:crypto';
|
|
2
|
+
import { mkdir, readFile, writeFile, rename, chmod } from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { directLocal } from '../http.mjs';
|
|
5
|
+
import { defaultStateDirectory } from './registry.mjs';
|
|
6
|
+
|
|
7
|
+
export async function hubKey(stateDirectory = defaultStateDirectory, { rotate = false } = {}) {
|
|
8
|
+
const file = path.join(stateDirectory, 'hub.key');
|
|
9
|
+
if (!rotate) {
|
|
10
|
+
try {
|
|
11
|
+
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
|
+
await chmod(file, 0o600);
|
|
14
|
+
return key;
|
|
15
|
+
} catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
16
|
+
}
|
|
17
|
+
await mkdir(stateDirectory, { recursive: true });
|
|
18
|
+
const key = `adg_${randomBytes(32).toString('hex')}`;
|
|
19
|
+
if (rotate) {
|
|
20
|
+
const temporary = `${file}.${process.pid}.tmp`;
|
|
21
|
+
await writeFile(temporary, `${key}\n`, { mode: 0o600 });
|
|
22
|
+
await rename(temporary, file);
|
|
23
|
+
} else {
|
|
24
|
+
try { await writeFile(file, `${key}\n`, { flag: 'wx', mode: 0o600 }); }
|
|
25
|
+
catch (error) { if (error.code === 'EEXIST') return hubKey(stateDirectory); throw error; }
|
|
26
|
+
}
|
|
27
|
+
return key;
|
|
28
|
+
}
|
|
29
|
+
export function equalKey(actual, expected) {
|
|
30
|
+
const digest = value => createHash('sha256').update(value).digest();
|
|
31
|
+
return timingSafeEqual(digest(typeof actual === 'string' ? actual : ''), digest(expected));
|
|
32
|
+
}
|
|
33
|
+
export async function authorized(request, url, stateDirectory) {
|
|
34
|
+
if (directLocal(request)) return true;
|
|
35
|
+
const key = request.headers.authorization?.match(/^Bearer (\S+)$/i)?.[1] ?? request.headers['x-adg-key'] ?? url.searchParams.get('key');
|
|
36
|
+
// Read back on every request so CLI rotation also applies to a running service.
|
|
37
|
+
const expected = (await readFile(path.join(stateDirectory, 'hub.key'), 'utf8')).trim();
|
|
38
|
+
const equal = equalKey(key, expected);
|
|
39
|
+
return /^adg_[a-f0-9]{64}$/.test(expected) && equal;
|
|
40
|
+
}
|
|
@@ -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,28 @@
|
|
|
1
|
+
import { request as httpRequest } from 'node:http';
|
|
2
|
+
|
|
3
|
+
// Pipe through the owning server, preserving streaming and backpressure.
|
|
4
|
+
export function proxy(request, response, port, pathname, viewerBase) {
|
|
5
|
+
return new Promise(resolve => {
|
|
6
|
+
const headers = { ...request.headers, host: `127.0.0.1:${port}` };
|
|
7
|
+
for (const name of Object.keys(headers)) {
|
|
8
|
+
if (['authorization', 'x-adg-key', 'x-adg-viewer-base', 'cookie', 'forwarded', 'origin', 'connection'].includes(name) || name.startsWith('x-forwarded-')) delete headers[name];
|
|
9
|
+
}
|
|
10
|
+
if (viewerBase) headers['x-adg-viewer-base'] = viewerBase;
|
|
11
|
+
const target = new URL(pathname, 'http://localhost');
|
|
12
|
+
target.searchParams.delete('key');
|
|
13
|
+
const upstream = httpRequest({ hostname: '127.0.0.1', port, method: request.method, path: target.pathname + target.search, headers }, incoming => {
|
|
14
|
+
const outgoing = { ...incoming.headers };
|
|
15
|
+
delete outgoing['set-cookie'];
|
|
16
|
+
response.writeHead(incoming.statusCode, outgoing);
|
|
17
|
+
incoming.pipe(response);
|
|
18
|
+
incoming.on('error', () => response.destroy());
|
|
19
|
+
});
|
|
20
|
+
const done = () => { upstream.destroy(); resolve(); };
|
|
21
|
+
response.once('close', done);
|
|
22
|
+
upstream.on('error', () => {
|
|
23
|
+
if (!response.headersSent) response.writeHead(502, { 'Content-Type': 'application/json' });
|
|
24
|
+
if (!response.destroyed) response.end(JSON.stringify({ error: 'Viewer unavailable.' }));
|
|
25
|
+
});
|
|
26
|
+
request.pipe(upstream);
|
|
27
|
+
});
|
|
28
|
+
}
|
|
@@ -0,0 +1,147 @@
|
|
|
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
|
+
|
|
10
|
+
const exec = promisify(execFile);
|
|
11
|
+
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
|
+
export function projectSlug(directory) {
|
|
14
|
+
return path.basename(directory).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'project';
|
|
15
|
+
}
|
|
16
|
+
const pathHash = directory => createHash('sha256').update(directory).digest('hex');
|
|
17
|
+
function assignSlugs(data, previousRoots) {
|
|
18
|
+
const directories = [...new Set(data.roots.flatMap(root => root.projects.map(project => project.path)))].sort();
|
|
19
|
+
const current = new Set(directories);
|
|
20
|
+
const assigned = new Map(previousRoots.flatMap(root => root.projects)
|
|
21
|
+
.filter(project => current.has(project.path))
|
|
22
|
+
// Upgrade the old always-hashed format on the next explicit scan.
|
|
23
|
+
.filter(project => data.slugVersion === 1 || project.slug !== `${projectSlug(project.path)}-${pathHash(project.path).slice(0, 12)}`)
|
|
24
|
+
.map(project => [project.path, project.slug]));
|
|
25
|
+
const used = new Set(assigned.values());
|
|
26
|
+
const pending = [];
|
|
27
|
+
for (const directory of directories) {
|
|
28
|
+
if (assigned.has(directory)) continue;
|
|
29
|
+
const slug = projectSlug(directory);
|
|
30
|
+
if (used.has(slug)) { pending.push(directory); continue; }
|
|
31
|
+
assigned.set(directory, slug);
|
|
32
|
+
used.add(slug);
|
|
33
|
+
}
|
|
34
|
+
for (const directory of pending) {
|
|
35
|
+
const base = `${projectSlug(directory)}-${projectSlug(path.dirname(directory))}`;
|
|
36
|
+
let slug = base, length = 6;
|
|
37
|
+
while (used.has(slug)) slug = `${base}-${pathHash(directory).slice(0, length++)}`;
|
|
38
|
+
assigned.set(directory, slug);
|
|
39
|
+
used.add(slug);
|
|
40
|
+
}
|
|
41
|
+
for (const root of data.roots) {
|
|
42
|
+
for (const project of root.projects) project.slug = assigned.get(project.path);
|
|
43
|
+
}
|
|
44
|
+
data.slugVersion = 1;
|
|
45
|
+
}
|
|
46
|
+
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}`); }
|
|
49
|
+
}
|
|
50
|
+
async function save(data, stateDirectory) {
|
|
51
|
+
await mkdir(stateDirectory, { recursive: true });
|
|
52
|
+
const destination = path.join(stateDirectory, 'registry.json'), temporary = `${destination}.${process.pid}.tmp`;
|
|
53
|
+
await writeFile(temporary, JSON.stringify(data, null, 2) + '\n');
|
|
54
|
+
await rename(temporary, destination);
|
|
55
|
+
}
|
|
56
|
+
async function scan(root) {
|
|
57
|
+
const projects = [];
|
|
58
|
+
async function visit(directory, depth) {
|
|
59
|
+
if (path.basename(directory).startsWith('.') || path.basename(directory) === 'node_modules') return;
|
|
60
|
+
let entries;
|
|
61
|
+
try {
|
|
62
|
+
if ((await stat(path.join(directory, '.git')).catch(() => null))?.isFile()) return;
|
|
63
|
+
entries = await readdir(directory, { withFileTypes: true });
|
|
64
|
+
} catch (error) {
|
|
65
|
+
if (directory === root.path) throw error;
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
if (configFile(directory) || legacyConfigFile(directory)) {
|
|
69
|
+
projects.push({ path: directory });
|
|
70
|
+
try {
|
|
71
|
+
await loadConfig(directory, { checkVersion: false });
|
|
72
|
+
} catch (error) {
|
|
73
|
+
console.error(`adg: ${directory}: ${error.message.replace(/\s*\n\s*/g, ' ')}; fix the project config and rescan.`);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
if (depth >= root.depth) return;
|
|
77
|
+
for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
|
|
78
|
+
if (!entry.isDirectory() || entry.name.startsWith('.') || entry.name === 'node_modules') continue;
|
|
79
|
+
await visit(path.join(directory, entry.name), depth + 1);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
await visit(root.path, 0);
|
|
83
|
+
return { ...root, projects, scannedAt: new Date().toISOString() };
|
|
84
|
+
}
|
|
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 });
|
|
90
|
+
const previousRoots = data.roots;
|
|
91
|
+
data.roots = [...data.roots.filter(item => item.path !== root), entry].sort((a, b) => a.path.localeCompare(b.path));
|
|
92
|
+
assignSlugs(data, previousRoots);
|
|
93
|
+
await save(data, stateDirectory);
|
|
94
|
+
return listRoots(stateDirectory);
|
|
95
|
+
}
|
|
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()));
|
|
99
|
+
throw error;
|
|
100
|
+
});
|
|
101
|
+
const data = await registry(stateDirectory);
|
|
102
|
+
if (!data.roots.some(item => item.path === root)) throw new Error(`Root is not registered: ${directory}`);
|
|
103
|
+
data.roots = data.roots.filter(item => item.path !== root);
|
|
104
|
+
await save(data, stateDirectory);
|
|
105
|
+
return listRoots(stateDirectory);
|
|
106
|
+
}
|
|
107
|
+
export async function listRoots(stateDirectory = defaultStateDirectory) {
|
|
108
|
+
return (await registry(stateDirectory)).roots.map(({ projects, ...root }) => ({ ...root, projectCount: projects.length }));
|
|
109
|
+
}
|
|
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}`);
|
|
113
|
+
const previousRoots = [...data.roots];
|
|
114
|
+
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]);
|
|
116
|
+
}
|
|
117
|
+
assignSlugs(data, previousRoots);
|
|
118
|
+
await save(data, stateDirectory);
|
|
119
|
+
return listRoots(stateDirectory);
|
|
120
|
+
}
|
|
121
|
+
const git = async (directory, args) => {
|
|
122
|
+
try { return (await exec('git', ['-C', directory, ...args], { maxBuffer: 1024 * 1024 })).stdout.trim(); }
|
|
123
|
+
catch { return null; }
|
|
124
|
+
};
|
|
125
|
+
export async function projectMetadata(record) {
|
|
126
|
+
const base = { ...record, name: path.basename(record.path), design: null, branch: null, head: null,
|
|
127
|
+
lastDesignChange: { committedAt: null, dirty: false }, sourceCount: null, frameCount: null,
|
|
128
|
+
compatibility: { version: VERSION, requires: null, compatible: null } };
|
|
129
|
+
try {
|
|
130
|
+
requireMigration(record.path);
|
|
131
|
+
if (!configFile(record.path)) throw new Error('Project config is missing; rescan registered roots.');
|
|
132
|
+
const config = await loadConfig(record.path, { checkVersion: false });
|
|
133
|
+
const relative = path.relative(record.path, config.design) || '.';
|
|
134
|
+
const [branch, head, committedAt, dirty] = await Promise.all([
|
|
135
|
+
git(record.path, ['symbolic-ref', '--short', 'HEAD']), git(record.path, ['rev-parse', '--short', 'HEAD']),
|
|
136
|
+
git(record.path, ['log', '-1', '--format=%cI', '--', relative]), git(record.path, ['status', '--porcelain', '--untracked-files=all', '--', relative]),
|
|
137
|
+
]);
|
|
138
|
+
return { ...base, name: config.name, design: config.design, branch, head,
|
|
139
|
+
lastDesignChange: { committedAt: committedAt || null, dirty: !!dirty }, sourceCount: listSources(config.design, config.sources).length + archFiles(config.arch).length,
|
|
140
|
+
compatibility: { version: VERSION, requires: config.requires, compatible: config.compatible } };
|
|
141
|
+
} catch (error) { return { ...base, error: error.message }; }
|
|
142
|
+
}
|
|
143
|
+
export async function listProjects(stateDirectory = defaultStateDirectory) {
|
|
144
|
+
const records = (await registry(stateDirectory)).roots.flatMap(root => root.projects);
|
|
145
|
+
const unique = [...new Map(records.map(project => [project.path, project])).values()].sort((a, b) => a.path.localeCompare(b.path));
|
|
146
|
+
return Promise.all(unique.map(projectMetadata));
|
|
147
|
+
}
|
package/src/hub.mjs
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
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
|
+
|
|
11
|
+
export async function startHub({ port = 4310, stateDirectory = defaultStateDirectory, idleTimeout = 300_000 } = {}) {
|
|
12
|
+
await hubKey(stateDirectory);
|
|
13
|
+
let closing = false;
|
|
14
|
+
const id = randomUUID(), viewers = new Map(), streams = new Set();
|
|
15
|
+
const stopping = new Map();
|
|
16
|
+
const projects = async () => (await listProjects(stateDirectory)).map(project => ({ ...project, ...viewers.get(project.slug)?.viewer?.stats(), url: `/p/${project.slug}/` }));
|
|
17
|
+
const server = createServer(async (request, response) => {
|
|
18
|
+
try {
|
|
19
|
+
if (closing) return json(response, 503, { error: 'Hub is stopping.' });
|
|
20
|
+
const url = new URL(request.url, 'http://localhost');
|
|
21
|
+
const read = ['GET', 'HEAD'].includes(request.method);
|
|
22
|
+
const projectRoute = url.pathname.match(/^\/p\/([A-Za-z0-9_-]+)(\/.*)?$/);
|
|
23
|
+
const instanceRoute = url.pathname.match(/^\/i\/([A-Za-z0-9_-]+)(\/.*)?$/);
|
|
24
|
+
const stopRoute = url.pathname.match(/^\/api\/instances\/([A-Za-z0-9_-]+)\/stop$/);
|
|
25
|
+
const route = projectRoute ?? instanceRoute;
|
|
26
|
+
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]);
|
|
27
|
+
// Project shells do not discover, build, watch, or embed any project data.
|
|
28
|
+
// The switcher manages hub destinations, including in viewers started before this hub version.
|
|
29
|
+
if (publicFile && (!instanceRoute || ['switcher.js', 'switcher.css', 'instance-actions.js'].includes(publicFile))) {
|
|
30
|
+
if (route && !route[2]) { response.writeHead(302, { Location: `${url.pathname}/${url.search}` }); response.end(); return; }
|
|
31
|
+
return await shell(request, response, publicFile, projectRoute && `/p/${projectRoute[1]}/`);
|
|
32
|
+
}
|
|
33
|
+
if (!publicFile && !await authorized(request, url, stateDirectory)) return json(response, 401, { error: 'Unauthorized' });
|
|
34
|
+
if (request.method === 'POST' && request.headers.origin && ![`http://${request.headers.host}`, `https://${request.headers.host}`].includes(request.headers.origin))
|
|
35
|
+
return json(response, 403, { error: 'Cross-origin request refused.' });
|
|
36
|
+
if (url.pathname === '/api/health' && request.method === 'GET') return json(response, 200, { id });
|
|
37
|
+
if (url.pathname === '/api/projects' && request.method === 'GET') return json(response, 200, await projects());
|
|
38
|
+
if (url.pathname === '/api/instances' && request.method === 'GET') return json(response, 200, await listInstances(stateDirectory));
|
|
39
|
+
if (stopRoute && request.method === 'POST') {
|
|
40
|
+
const instanceId = stopRoute[1];
|
|
41
|
+
if (!stopping.has(instanceId))
|
|
42
|
+
stopping.set(instanceId, stopInstance(instanceId, stateDirectory).finally(() => stopping.delete(instanceId)));
|
|
43
|
+
const status = await stopping.get(instanceId);
|
|
44
|
+
if (status === 200) return json(response, 200, { ok: true });
|
|
45
|
+
const error = { 404: 'Instance is no longer live.', 409: 'Cannot verify that this viewer can be stopped.',
|
|
46
|
+
503: 'The viewer is still shutting down.' }[status];
|
|
47
|
+
return json(response, status, { error });
|
|
48
|
+
}
|
|
49
|
+
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));
|
|
51
|
+
if (route) {
|
|
52
|
+
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
|
+
if (instanceRoute) {
|
|
54
|
+
const instance = (await listInstances(stateDirectory)).find(item => item.id === instanceRoute[1]);
|
|
55
|
+
if (!instance) return json(response, 404, { error: 'Instance is no longer live.' });
|
|
56
|
+
if (!instance.proxyable) return json(response, 409, { error: 'Instance viewer does not support authenticated proxying.' });
|
|
57
|
+
if (!route[2]) { response.writeHead(302, { Location: `${url.pathname}/${url.search}` }); response.end(); return; }
|
|
58
|
+
streams.add(response);
|
|
59
|
+
try { await proxy(request, response, instance.port, route[2] + url.search, `/i/${instance.id}/`); }
|
|
60
|
+
finally { streams.delete(response); }
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
const slug = projectRoute[1];
|
|
64
|
+
let entry = viewers.get(slug);
|
|
65
|
+
if (!entry) {
|
|
66
|
+
entry = { active: 0, last: Date.now() };
|
|
67
|
+
entry.pending = (async () => {
|
|
68
|
+
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) });
|
|
71
|
+
return entry.viewer;
|
|
72
|
+
})();
|
|
73
|
+
viewers.set(slug, entry);
|
|
74
|
+
}
|
|
75
|
+
try { await entry.pending; }
|
|
76
|
+
catch (error) { if (viewers.get(slug) === entry) viewers.delete(slug); throw error; }
|
|
77
|
+
entry.active++;
|
|
78
|
+
try { await proxy(request, response, entry.viewer.port, route[2] + url.search); }
|
|
79
|
+
finally { entry.active--; entry.last = Date.now(); }
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
json(response, read ? 404 : 405, { error: 'Not found.' });
|
|
83
|
+
} catch (error) {
|
|
84
|
+
if (response.headersSent) response.destroy();
|
|
85
|
+
else json(response, 400, { error: error.message });
|
|
86
|
+
}
|
|
87
|
+
});
|
|
88
|
+
const reap = setInterval(() => {
|
|
89
|
+
for (const [slug, entry] of viewers) {
|
|
90
|
+
if (!entry.active && entry.viewer && Date.now() - entry.last > idleTimeout) {
|
|
91
|
+
viewers.delete(slug);
|
|
92
|
+
entry.viewer.close().catch(() => {});
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
}, Math.min(idleTimeout, 30_000));
|
|
96
|
+
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
|
+
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
|
+
},
|
|
112
|
+
};
|
|
113
|
+
}
|