@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
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { stripVTControlCharacters } from 'node:util';
|
|
3
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
4
|
+
|
|
5
|
+
/** @typedef {{argv: string[], reason: string}} NextAction */
|
|
6
|
+
/** @typedef {{code: string, message: string, next: NextAction[]}} Diagnostic */
|
|
7
|
+
/** @typedef {keyof typeof errorCatalog} ErrorCode */
|
|
8
|
+
/** @typedef {{schemaVersion: 1, command: string, ok: boolean, data: unknown, warnings: Diagnostic[], error: Diagnostic | null}} Envelope */
|
|
9
|
+
/** @typedef {{command?: string, project?: string, stateDirectory?: string, gitCause?: 'repository' | 'revision' | 'read', positionals?: string[], values?: Record<string, string | string[] | boolean>, failureCode?: ErrorCode}} ErrorContext */
|
|
10
|
+
/** @typedef {{json: boolean, command: string, revealKey?: boolean, stdout?: (text: string) => void, stderr?: (text: string) => void}} OutputOptions */
|
|
11
|
+
|
|
12
|
+
// Recovery kinds keep the catalog declarative; actions are constructed from known operands.
|
|
13
|
+
/** @satisfies {Record<string, [number, string, string]>} */
|
|
14
|
+
export const errorCatalog = {
|
|
15
|
+
USAGE_INVALID: [2, 'help', 'Read command arguments.'],
|
|
16
|
+
CONFIG_INVALID: [2, 'check', 'Recheck after fixing configuration.'],
|
|
17
|
+
TOKENS_INVALID: [2, 'check', 'Recheck after repairing tokens.css.'],
|
|
18
|
+
MIGRATION_REQUIRED: [2, 'migrate', 'Migrate the legacy project.'],
|
|
19
|
+
MIGRATION_CONFLICT: [2, 'migration', 'Inspect migration inputs before resolving the conflict.'],
|
|
20
|
+
VERSION_UNSATISFIED: [2, 'install', 'Install a version satisfying project requires.'],
|
|
21
|
+
DIRECTORY_NOT_FOUND: [2, 'help', 'Choose an existing directory.'],
|
|
22
|
+
PROJECT_NOT_FOUND: [2, 'migrate-help', 'Select the project root.'],
|
|
23
|
+
SOURCE_NOT_FOUND: [2, 'check-help', 'Choose a discovered source inside the project.'],
|
|
24
|
+
FRAME_NOT_FOUND: [2, 'render-help', 'Choose a declared frame in the selected sources.'],
|
|
25
|
+
ROOT_NOT_REGISTERED: [2, 'roots', 'Read registered roots.'],
|
|
26
|
+
LEGACY_SOURCE: [2, 'check', 'Recheck after converting the SVG source to TSX.'],
|
|
27
|
+
SOURCE_BUILD_FAILED: [2, 'check', 'Read source diagnostics after repairing the source.'],
|
|
28
|
+
GIT_UNAVAILABLE: [2, 'git-version', 'Verify Git after installing it.'],
|
|
29
|
+
GIT_BASE_INVALID: [2, 'git', 'Inspect the project repository and base revision.'],
|
|
30
|
+
DIFF_BASE_DEPENDENCIES_UNAVAILABLE: [2, 'diff', 'Restore the reported historical import or its installed dependency before retrying.'],
|
|
31
|
+
DIFF_FAILED: [1, 'diff', 'Review the reported artifacts, then repeat the comparison after resolving the differences.'],
|
|
32
|
+
DIFF_REFERENCE_INVALID: [2, 'diff', 'Repair the Frame parent reference or selector, then repeat the comparison.'],
|
|
33
|
+
DIFF_UNSETTLED: [2, 'diff', 'Stabilize the reported part or parent target, then repeat the comparison.'],
|
|
34
|
+
DIFF_SNAPSHOT_UNSUPPORTED: [2, 'diff', 'Supply a static presentation with attributable paint, then repeat the comparison.'],
|
|
35
|
+
CHECK_FAILED: [1, 'check', 'Recheck after fixing findings.'],
|
|
36
|
+
COMPARE_FAILED: [1, 'compare', 'Compare again after reviewing the reports.'],
|
|
37
|
+
PLAYWRIGHT_UNAVAILABLE: [2, 'install', 'Restore the packaged browser dependency.'],
|
|
38
|
+
CHROMIUM_UNAVAILABLE: [2, 'chromium', 'Install Chromium matching ADG\'s Playwright.'],
|
|
39
|
+
BROWSER_FAILED: [2, 'chromium', 'Repair Chromium before retrying.'],
|
|
40
|
+
RENDER_FAILED: [2, 'check', 'Inspect frame execution diagnostics.'],
|
|
41
|
+
COMPARE_TARGET_NOT_FOUND: [2, 'compare', 'Retry after repairing the fixture target.'],
|
|
42
|
+
COMPARE_ADAPTER_FAILED: [2, 'compare', 'Retry after repairing the adapter callback.'],
|
|
43
|
+
COMPARE_UNSETTLED: [2, 'compare', 'Retry after stabilizing fixture readiness.'],
|
|
44
|
+
STATE_INVALID: [2, 'help', 'Inspect the reported state file before retrying.'],
|
|
45
|
+
HUB_KEY_INVALID: [2, 'rotate', 'Replace the invalid key; existing access will expire.'],
|
|
46
|
+
SERVICE_UNSUPPORTED: [2, 'serve-help', 'Use a foreground hub on this platform.'],
|
|
47
|
+
SERVICE_ALREADY_INSTALLED: [2, 'status', 'Inspect the existing installation.'],
|
|
48
|
+
SERVICE_FAILED: [2, 'logs', 'Inspect service diagnostics before retrying.'],
|
|
49
|
+
WATCH_FAILED: [2, 'check', 'Inspect project inputs before reopening the viewer.'],
|
|
50
|
+
SHUTDOWN_FAILED: [2, 'help', 'Inspect the reported resource before retrying.'],
|
|
51
|
+
PORT_IN_USE: [2, 'help', 'Choose an unused port.'],
|
|
52
|
+
NETWORK_FAILED: [2, 'compare', 'Retry after restoring fixture connectivity.'],
|
|
53
|
+
AUTH_REQUIRED: [2, 'compare', 'Retry after providing fixture access.'],
|
|
54
|
+
IO_FAILED: [2, 'help', 'Repair access to the reported path before retrying.'],
|
|
55
|
+
INTERNAL_ERROR: [2, 'version', 'Record the runtime version with the diagnostic.'],
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
export class CliError extends Error {
|
|
59
|
+
/** @param {ErrorCode} code @param {string} message @param {{data?: unknown, cause?: unknown, context?: ErrorContext, warnings?: Diagnostic[], humanReported?: boolean}} [options] */
|
|
60
|
+
constructor(code, message, { data = null, cause, context = {}, warnings = [], humanReported = false } = {}) {
|
|
61
|
+
super(message, { cause });
|
|
62
|
+
this.name = 'CliError';
|
|
63
|
+
this.code = code;
|
|
64
|
+
this.data = data;
|
|
65
|
+
this.context = context;
|
|
66
|
+
this.warnings = warnings;
|
|
67
|
+
this.humanReported = humanReported;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const canonicalCommands = new Set([
|
|
72
|
+
'open', 'link', 'serve', 'root', 'service', 'migrate', 'init', 'check', 'render', 'compare', 'diff',
|
|
73
|
+
'root add', 'root remove', 'root list', 'root scan',
|
|
74
|
+
'service install', 'service uninstall', 'service status', 'service logs', 'service migrate',
|
|
75
|
+
'help', 'version', 'adg',
|
|
76
|
+
]);
|
|
77
|
+
const playwrightVersion = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).dependencies.playwright;
|
|
78
|
+
|
|
79
|
+
/** Sanitize strings before either diagnostic channel; never stringify raw errors/configs. @param {string} text */
|
|
80
|
+
export function sanitize(text) {
|
|
81
|
+
return stripVTControlCharacters(text)
|
|
82
|
+
.replace(/\b(?:adg|sdg)_[a-f0-9]{64}\b/gi, '[REDACTED]')
|
|
83
|
+
.replace(/(\bBearer\s+)[^\s"'<>]+/gi, '$1[REDACTED]')
|
|
84
|
+
.replace(/(\b(?:X-(?:ADG|SDG)-Key|authorization)["']?\s*[:=]\s*["']?)[^\s"',}<>]+/gi, '$1[REDACTED]')
|
|
85
|
+
.replace(/(https?:\/\/)[^\s/@]+(?::[^\s/@]*)?@/gi, '$1[REDACTED]@')
|
|
86
|
+
.replace(/([?&](?:key|token|access_token|api_key|authorization)=)[^&#\s"'<>]*/gi, '$1[REDACTED]');
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** @param {string} [command] */
|
|
90
|
+
function helpArgv(command = 'adg') {
|
|
91
|
+
return ['adg', ...(canonicalCommands.has(command) && !['adg', 'help', 'version'].includes(command) ? command.split(' ') : []), '--help', '--json'];
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** @param {ErrorCode} code @param {ErrorContext} [context] @returns {NextAction[]} */
|
|
95
|
+
export function nextActions(code, context = {}) {
|
|
96
|
+
const [, recovery, reason] = errorCatalog[code];
|
|
97
|
+
const state = context.stateDirectory ? ['--state-dir', context.stateDirectory] : [];
|
|
98
|
+
let argv;
|
|
99
|
+
switch (recovery) {
|
|
100
|
+
case 'check': argv = ['adg', 'check', '--read-only', '--json', ...(context.positionals?.length && context.command === 'check' ? ['--', ...context.positionals] : [])]; break;
|
|
101
|
+
case 'install': argv = ['npm', 'install', '-g', '@whzxc/agent-design-gallery']; break;
|
|
102
|
+
case 'migrate': argv = context.project ? ['adg', 'migrate', context.project, '--json'] : helpArgv('migrate'); break;
|
|
103
|
+
case 'migration': argv = context.command === 'service migrate' ? ['adg', 'service', 'status', ...state, '--json'] : helpArgv('migrate'); break;
|
|
104
|
+
case 'migrate-help': argv = helpArgv('migrate'); break;
|
|
105
|
+
case 'check-help': argv = helpArgv('check'); break;
|
|
106
|
+
case 'render-help': argv = helpArgv('render'); break;
|
|
107
|
+
case 'serve-help': argv = helpArgv('serve'); break;
|
|
108
|
+
case 'roots': argv = ['adg', 'root', 'list', ...state, '--json']; break;
|
|
109
|
+
case 'rotate': argv = ['adg', 'serve', '--rotate-key', ...state, '--json']; break;
|
|
110
|
+
case 'status': argv = ['adg', 'service', 'status', ...state, '--json']; break;
|
|
111
|
+
case 'logs': argv = ['adg', 'service', 'logs', ...state, '--json']; break;
|
|
112
|
+
case 'version': argv = ['adg', '--version', '--json']; break;
|
|
113
|
+
case 'git-version': argv = ['git', '--version']; break;
|
|
114
|
+
case 'git': {
|
|
115
|
+
const operation = context.gitCause === 'revision' ? ['log', '-5', '--oneline'] : context.gitCause === 'read' ? ['status', '--short'] : ['rev-parse', '--show-toplevel'];
|
|
116
|
+
argv = context.project ? ['git', '-C', context.project, ...operation] : helpArgv(context.command);
|
|
117
|
+
break;
|
|
118
|
+
}
|
|
119
|
+
case 'chromium': argv = ['npx', `playwright@${playwrightVersion}`, 'install', 'chromium']; break;
|
|
120
|
+
case 'diff': {
|
|
121
|
+
const values = context.values ?? {};
|
|
122
|
+
if (context.command !== 'diff' || typeof values.base !== 'string' || !values.base.trim()) { argv = helpArgv('diff'); break; }
|
|
123
|
+
argv = ['adg', 'diff'];
|
|
124
|
+
for (const key of ['base', 'frame', 'theme', 'scale', 'out-dir']) {
|
|
125
|
+
if (typeof values[key] === 'string') argv.push(`--${key}=${values[key]}`);
|
|
126
|
+
}
|
|
127
|
+
argv.push('--json');
|
|
128
|
+
if (context.positionals?.length) argv.push('--', ...context.positionals);
|
|
129
|
+
break;
|
|
130
|
+
}
|
|
131
|
+
case 'compare': {
|
|
132
|
+
const values = context.values ?? {}, sources = context.positionals ?? [];
|
|
133
|
+
if (context.command !== 'compare' || (!values.all && (sources.length !== 1 || typeof values.frame !== 'string' || !values.frame))) {
|
|
134
|
+
argv = helpArgv(context.command);
|
|
135
|
+
break;
|
|
136
|
+
}
|
|
137
|
+
argv = ['adg', 'compare'];
|
|
138
|
+
if (values.all) argv.push('--all');
|
|
139
|
+
else {
|
|
140
|
+
// Attached values preserve literal operands starting with '-'.
|
|
141
|
+
for (const key of ['frame', 'fixture', 'region', 'selector', 'origin', 'viewport']) {
|
|
142
|
+
if (typeof values[key] === 'string') argv.push(`--${key}=${values[key]}`);
|
|
143
|
+
}
|
|
144
|
+
if (values.page) argv.push('--page');
|
|
145
|
+
for (const click of Array.isArray(values.click) ? values.click : []) argv.push(`--click=${click}`);
|
|
146
|
+
argv.push('--json', '--', sources[0]);
|
|
147
|
+
break;
|
|
148
|
+
}
|
|
149
|
+
argv.push('--json');
|
|
150
|
+
break;
|
|
151
|
+
}
|
|
152
|
+
default: argv = helpArgv(context.command);
|
|
153
|
+
}
|
|
154
|
+
// Redacted operands are not executable corrections; offer safe help instead.
|
|
155
|
+
if (argv.some(value => sanitize(value) !== value)) return [{ argv: helpArgv(context.command), reason: 'Read command arguments without exposing credentials.' }];
|
|
156
|
+
return [{ argv, reason: String(reason) }];
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
const ioCodes = new Set(['EACCES', 'EPERM', 'ENOENT', 'ENOTDIR', 'EISDIR', 'ENOSPC', 'EROFS', 'EEXIST', 'EXDEV', 'EMFILE', 'ENFILE', 'EIO']);
|
|
160
|
+
const networkCodes = new Set(['ECONNREFUSED', 'ECONNRESET', 'ENOTFOUND', 'EAI_AGAIN', 'ETIMEDOUT', 'ERR_TLS_CERT_ALTNAME_INVALID', 'CERT_HAS_EXPIRED']);
|
|
161
|
+
|
|
162
|
+
/** @param {unknown} cause @param {ErrorContext} [context] @returns {{error: Diagnostic & {code: ErrorCode}, exitCode: number, data: unknown, warnings: Diagnostic[]}} */
|
|
163
|
+
export function classifyError(cause, context = {}) {
|
|
164
|
+
const raw = cause instanceof Error ? cause : null;
|
|
165
|
+
const rawCode = raw && 'code' in raw ? String(raw.code) : '';
|
|
166
|
+
/** @type {ErrorCode} */
|
|
167
|
+
let code = 'INTERNAL_ERROR';
|
|
168
|
+
if (raw instanceof CliError && Object.hasOwn(errorCatalog, raw.code)) code = raw.code;
|
|
169
|
+
else if (rawCode === 'EADDRINUSE') code = 'PORT_IN_USE';
|
|
170
|
+
else if (context.failureCode && Object.hasOwn(errorCatalog, context.failureCode)) code = context.failureCode;
|
|
171
|
+
else if (ioCodes.has(rawCode)) code = 'IO_FAILED';
|
|
172
|
+
else if (networkCodes.has(rawCode)) code = 'NETWORK_FAILED';
|
|
173
|
+
const message = sanitize(raw?.message ?? (typeof cause === 'string' ? cause : 'Unexpected ADG error.')).replace(/\s+/g, ' ').trim();
|
|
174
|
+
return {
|
|
175
|
+
error: { code, message, next: nextActions(code, { ...context, ...(raw instanceof CliError ? raw.context : {}) }) },
|
|
176
|
+
exitCode: Number(errorCatalog[code][0]),
|
|
177
|
+
data: raw instanceof CliError ? raw.data : null,
|
|
178
|
+
warnings: raw instanceof CliError ? raw.warnings : [],
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** @param {unknown} cause @param {ErrorCode} [fallback] */
|
|
183
|
+
export function asCliError(cause, fallback = 'INTERNAL_ERROR') {
|
|
184
|
+
if (cause instanceof CliError) return cause;
|
|
185
|
+
const classified = classifyError(cause);
|
|
186
|
+
return new CliError(classified.error.code === 'INTERNAL_ERROR' ? fallback : classified.error.code, cause instanceof Error ? cause.message : String(cause), { cause });
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** @param {unknown} value @returns {unknown} */
|
|
190
|
+
function sanitizedValue(value) {
|
|
191
|
+
if (typeof value === 'string') return sanitize(value);
|
|
192
|
+
if (Array.isArray(value)) return value.map(sanitizedValue);
|
|
193
|
+
if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, sanitizedValue(item)]));
|
|
194
|
+
return value;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** @type {AsyncLocalStorage<(text: string) => void>} */
|
|
198
|
+
const humanOutput = new AsyncLocalStorage();
|
|
199
|
+
/**
|
|
200
|
+
* Route config/module writes in this invocation without capturing the caller's output.
|
|
201
|
+
* @template T
|
|
202
|
+
* @param {() => T | Promise<T>} work
|
|
203
|
+
* @param {(text: string) => void} stderr
|
|
204
|
+
* @returns {Promise<T>}
|
|
205
|
+
*/
|
|
206
|
+
export async function withHumanOutput(work, stderr) {
|
|
207
|
+
const originals = [process.stdout.write, process.stderr.write];
|
|
208
|
+
for (const [index, stream] of [process.stdout, process.stderr].entries()) {
|
|
209
|
+
/** @param {string | Uint8Array} chunk @param {BufferEncoding | ((error?: Error | null) => void)} [encoding] @param {(error?: Error | null) => void} [callback] */
|
|
210
|
+
function redirect(chunk, encoding, callback) {
|
|
211
|
+
const sink = humanOutput.getStore();
|
|
212
|
+
const done = typeof encoding === 'function' ? encoding : callback;
|
|
213
|
+
if (!sink) return originals[index].call(stream, chunk, typeof encoding === 'string' ? encoding : undefined, done);
|
|
214
|
+
sink(sanitize(typeof chunk === 'string' ? chunk : Buffer.from(chunk).toString(typeof encoding === 'string' ? encoding : 'utf8')));
|
|
215
|
+
done?.();
|
|
216
|
+
return true;
|
|
217
|
+
}
|
|
218
|
+
stream.write = redirect;
|
|
219
|
+
}
|
|
220
|
+
try { return await humanOutput.run(stderr, work); }
|
|
221
|
+
finally { [process.stdout.write, process.stderr.write] = originals; }
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** Preserve the active output sink while translating revision-local diagnostics. */
|
|
225
|
+
export async function withHumanOutputMapping(work, transform) {
|
|
226
|
+
const sink = humanOutput.getStore() ?? process.stderr.write.bind(process.stderr);
|
|
227
|
+
return withHumanOutput(work, text => sink(transform(text)));
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/** @param {OutputOptions} options */
|
|
231
|
+
export function createOutput({ json, command, revealKey = false, stdout = text => { process.stdout.write(text); }, stderr = text => { process.stderr.write(text); } }) {
|
|
232
|
+
/** @param {Envelope} envelope */
|
|
233
|
+
const emit = envelope => {
|
|
234
|
+
const clean = /** @type {Envelope} */ (sanitizedValue(envelope));
|
|
235
|
+
const data = envelope.data;
|
|
236
|
+
if (json && revealKey && command === 'serve' && envelope.ok && data && typeof data === 'object' && 'action' in data && data.action === 'print-key' && 'key' in data && typeof data.key === 'string' && /^adg_[a-f0-9]{64}$/.test(data.key) && clean.data && typeof clean.data === 'object') {
|
|
237
|
+
// Only the explicit print-key result field is exempt; siblings and diagnostics stay sanitized.
|
|
238
|
+
Object.assign(clean.data, { key: data.key });
|
|
239
|
+
}
|
|
240
|
+
stdout(`${JSON.stringify(clean)}\n`);
|
|
241
|
+
};
|
|
242
|
+
/** @param {string} text */
|
|
243
|
+
const log = text => (json ? stderr : stdout)(`${sanitize(text)}\n`);
|
|
244
|
+
return {
|
|
245
|
+
log,
|
|
246
|
+
/** @param {string} text */
|
|
247
|
+
progress: text => stderr(`${sanitize(text)}\n`),
|
|
248
|
+
/** @param {unknown} data @param {Diagnostic[]} [warnings] */
|
|
249
|
+
success(data, warnings = []) { emit({ schemaVersion: 1, command, ok: true, data: data ?? null, warnings, error: null }); },
|
|
250
|
+
/** @param {unknown} cause @param {ErrorContext} [context] */
|
|
251
|
+
failure(cause, context = {}) {
|
|
252
|
+
const failure = classifyError(cause, { ...context, command });
|
|
253
|
+
if (json) emit({ schemaVersion: 1, command, ok: false, data: failure.data, warnings: failure.warnings, error: failure.error });
|
|
254
|
+
else if (!(cause instanceof CliError && cause.humanReported)) stderr(`adg: ${failure.error.message}\n`);
|
|
255
|
+
return failure.exitCode;
|
|
256
|
+
},
|
|
257
|
+
};
|
|
258
|
+
}
|
package/src/cli.mjs
CHANGED
|
@@ -4,8 +4,9 @@ import { parseArgs } from 'node:util';
|
|
|
4
4
|
import { pathToFileURL } from 'node:url';
|
|
5
5
|
import { realpathSync } from 'node:fs';
|
|
6
6
|
import { VERSION, loadConfig } from './toolkit/config.mjs';
|
|
7
|
+
import { CliError, createOutput, withHumanOutput } from './cli-output.mjs';
|
|
7
8
|
|
|
8
|
-
export const commands = ['open', 'link', 'serve', 'root', 'service', 'migrate', 'init', 'check', 'render', 'compare'];
|
|
9
|
+
export const commands = ['open', 'link', 'serve', 'root', 'service', 'migrate', 'init', 'check', 'render', 'compare', 'diff'];
|
|
9
10
|
const targetOptions = '[--asset=<path> [--frame=<name>] | --group=<name> | --layer=<name> | --tokens] [--mode=query|path] [--base=<rev>]';
|
|
10
11
|
const usage = {
|
|
11
12
|
open: `[directory] [--port=<n>] [--no-open] [--state-dir=<path>] ${targetOptions}`,
|
|
@@ -15,6 +16,7 @@ const usage = {
|
|
|
15
16
|
root: 'add <dir> [--depth=2] | remove <dir> | list | scan [dir] [--state-dir=<path>]',
|
|
16
17
|
migrate: '[project]', init: '', check: '[source...] [--read-only]', render: '[source...] [--frame=<name>] [--theme=both|light|dark] [--scale=2] [--out-dir=<path>] [--json] [--base=<rev>]',
|
|
17
18
|
compare: '<source> --frame=<name> [--fixture=<name>] [--region=<name> | --selector=<css> | --page] [--origin="<x> <y>"] [--click=<name>...] [--viewport=<w>x<h>] | --all',
|
|
19
|
+
diff: '[source...] --base=<rev> [--frame=<name>] [--theme=both|light|dark] [--scale=2] [--out-dir=<path>] [--json]',
|
|
18
20
|
};
|
|
19
21
|
const details = {
|
|
20
22
|
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.',
|
|
@@ -23,83 +25,156 @@ const details = {
|
|
|
23
25
|
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
26
|
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
27
|
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
|
|
28
|
+
check: 'Check import direction and every selected frame in both themes. --read-only skips generated types and build files.', render: 'Render selected frames as PNG. Defaults to both themes at 2×. --json prints a versioned result with capture geometry and absolute paths.',
|
|
27
29
|
compare: 'Compare fixture text positions. Flags override Frame fixture and capture. --all writes a summary for every fixture frame.',
|
|
30
|
+
diff: 'Compare the Git base and working-tree source/frame union. Existing frames require exact pixels and CSS/device size; added Frame parent declarations enable structural part evidence under diff.thresholds. Defaults to both themes at 2× and <configured output>/diff. Writes before, after and difference PNGs plus report.json. A structural batch requires all existing frames in both themes; source/frame/theme restrictions report partial coverage. Exit 0 identical/structural, 1 changed, 2 incomplete.',
|
|
28
31
|
};
|
|
29
32
|
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.`;
|
|
33
|
+
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/diff problems, 2 usage/configuration/environment error.`;
|
|
31
34
|
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
35
|
}
|
|
33
36
|
export function parseCli(args) {
|
|
37
|
+
let globalJson = false;
|
|
38
|
+
while (args[0] === '--json') { globalJson = true; args = args.slice(1); }
|
|
34
39
|
const explicit = commands.includes(args[0]), command = explicit ? args[0] : 'open';
|
|
35
|
-
const options = { help: { type: 'boolean', short: 'h' }, version: { type: 'boolean', short: 'v' } };
|
|
40
|
+
const options = { help: { type: 'boolean', short: 'h' }, version: { type: 'boolean', short: 'v' }, json: { type: 'boolean' } };
|
|
36
41
|
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'] };
|
|
42
|
+
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'], diff: ['base', 'frame', 'theme', 'scale', 'out-dir'], compare: ['frame', 'fixture', 'region', 'selector', 'viewport', 'origin'] };
|
|
38
43
|
for (const name of strings[command] ?? []) options[name] = { type: 'string' };
|
|
39
44
|
if (command === 'serve') for (const name of ['print-key', 'rotate-key']) options[name] = { type: 'boolean' };
|
|
40
45
|
if (command === 'open') options['no-open'] = { type: 'boolean' };
|
|
41
46
|
if (command === 'open' || command === 'link') options.tokens = { type: 'boolean' };
|
|
42
|
-
if (command === 'render') options.json = { type: 'boolean' };
|
|
43
47
|
if (command === 'check') options['read-only'] = { type: 'boolean' };
|
|
44
48
|
if (command === 'compare') { options.all = { type: 'boolean' }; options.page = { type: 'boolean' }; }
|
|
45
49
|
if (command === 'compare') options.click = { type: 'string', multiple: true };
|
|
46
50
|
let parsed;
|
|
47
51
|
try { parsed = parseArgs({ args: explicit ? args.slice(1) : args, options, allowPositionals: true }); }
|
|
48
|
-
catch (error) { throw new
|
|
52
|
+
catch (error) { throw new CliError('USAGE_INVALID', `${error.message}; run adg ${command} --help`); }
|
|
49
53
|
const { values, positionals } = parsed;
|
|
54
|
+
if (globalJson) values.json = true;
|
|
50
55
|
if (!values.help && !values.version) {
|
|
51
|
-
if (
|
|
56
|
+
if (command === 'diff' && (typeof values.base !== 'string' || !values.base.trim())) throw new CliError('USAGE_INVALID', 'Set --base to a Git revision; run adg diff --help.');
|
|
57
|
+
if ((command === 'init' && positionals.length) || (['open', 'migrate'].includes(command) && positionals.length > 1) || (command === 'compare' && (values.all ? positionals.length || values.frame : positionals.length !== 1 || !values.frame))) throw new CliError('USAGE_INVALID', `Invalid arguments; run adg ${command} --help`);
|
|
58
|
+
if (command === 'link' && positionals.length !== 1) throw new CliError('USAGE_INVALID', 'Expected one viewer URL. Run adg link --help.');
|
|
59
|
+
if (command === 'service' && (positionals.length !== 1 || !serviceActions.includes(positionals[0]) || (values.port !== undefined && positionals[0] !== 'install'))) throw new CliError('USAGE_INVALID', 'Invalid arguments; run adg service --help');
|
|
60
|
+
if (command === 'root') {
|
|
61
|
+
const [action, directory, ...extra] = positionals;
|
|
62
|
+
if (extra.length || !rootActions.includes(action) || (['add', 'remove'].includes(action) && !directory) || (action === 'list' && directory) || (values.depth !== undefined && action !== 'add')) throw new CliError('USAGE_INVALID', 'Invalid arguments; run adg root --help');
|
|
63
|
+
}
|
|
64
|
+
if (command === 'serve' && positionals.length) throw new CliError('USAGE_INVALID', 'Invalid arguments; run adg serve --help');
|
|
65
|
+
if (command === 'serve' && ((values['print-key'] && values['rotate-key']) || (values.port !== undefined && (values['print-key'] || values['rotate-key'])))) throw new CliError('USAGE_INVALID','Choose --print-key or --rotate-key without --port; run adg serve --help');
|
|
66
|
+
} else if (values.json && values.help && ['root', 'service'].includes(command) && (positionals.length > 1 || (positionals.length && !(command === 'root' ? rootActions : serviceActions).includes(positionals[0])))) {
|
|
67
|
+
throw new CliError('USAGE_INVALID', `Invalid arguments; run adg ${command} --help`);
|
|
52
68
|
}
|
|
53
69
|
return { command, values, positionals, explicit };
|
|
54
70
|
}
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
71
|
+
const rootActions = ['add', 'remove', 'list', 'scan'];
|
|
72
|
+
const serviceActions = ['install', 'uninstall', 'status', 'logs', 'migrate'];
|
|
73
|
+
|
|
74
|
+
export function commandIdentity({ command, positionals = [] }) {
|
|
75
|
+
const actions = command === 'root' ? rootActions : command === 'service' ? serviceActions : [];
|
|
76
|
+
return actions.includes(positionals[0]) ? `${command} ${positionals[0]}` : command;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function jsonRequested(args) {
|
|
80
|
+
const separator = args.indexOf('--');
|
|
81
|
+
return (separator < 0 ? args : args.slice(0, separator)).includes('--json');
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function errorCommand(args) {
|
|
85
|
+
while (args[0] === '--json') args = args.slice(1);
|
|
86
|
+
if (commands.includes(args[0])) return commandIdentity({ command: args[0], positionals: args.slice(1) });
|
|
87
|
+
return args[0] && !args[0].startsWith('-') ? 'open' : 'adg';
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async function dispatch({ command, values, positionals }, cwd, output, serviceOptions) {
|
|
91
|
+
if (command === 'migrate') return { data: await (await import('./toolkit/migrate.mjs')).migrate(positionals[0] === undefined ? cwd : path.resolve(cwd, positionals[0]), output.log) };
|
|
61
92
|
if (command === 'link') {
|
|
62
|
-
if (positionals.length !== 1) throw Error('Expected one viewer URL. Run adg link --help.');
|
|
63
93
|
const { previewTarget, previewURL } = await import('./link.mjs');
|
|
64
|
-
|
|
65
|
-
|
|
94
|
+
const data = { url: previewURL(positionals[0], previewTarget(values)).href };
|
|
95
|
+
if (!values.json) output.log(data.url);
|
|
96
|
+
return { data };
|
|
66
97
|
}
|
|
67
98
|
if (command === 'service') {
|
|
68
|
-
|
|
69
|
-
|
|
99
|
+
const options={...serviceOptions,output:output.log};
|
|
100
|
+
if (values['state-dir'] !== undefined) values={...values,'state-dir':path.resolve(cwd,values['state-dir'])};
|
|
101
|
+
return (await import('./service.mjs')).service(positionals[0], values, options);
|
|
70
102
|
}
|
|
71
103
|
if (command === 'root') {
|
|
72
|
-
const [action, directory
|
|
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');
|
|
104
|
+
const [action, directory] = positionals;
|
|
74
105
|
const registry = await import('./hub/registry.mjs');
|
|
75
|
-
const state = values['state-dir'];
|
|
76
|
-
const
|
|
77
|
-
|
|
78
|
-
: action === '
|
|
79
|
-
|
|
106
|
+
const state = path.resolve(cwd, values['state-dir'] ?? registry.defaultStateDirectory);
|
|
107
|
+
const options = { cwd, error: output.progress };
|
|
108
|
+
const result = action === 'add' ? await registry.addRoot(directory, values.depth === undefined ? 2 : Number(values.depth), state, options)
|
|
109
|
+
: action === 'remove' ? await registry.removeRoot(directory, state, options)
|
|
110
|
+
: action === 'scan' ? await registry.scanRoots(directory, state, options)
|
|
111
|
+
: { data: { stateDirectory: state, roots: await registry.listRoots(state), affected: [] } };
|
|
112
|
+
if (!values.json) output.log(JSON.stringify(result.data.roots, null, 2));
|
|
113
|
+
return result;
|
|
80
114
|
}
|
|
81
115
|
if (command === 'serve') {
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
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;
|
|
116
|
+
const {defaultStateDirectory}=await import('./hub/registry.mjs');
|
|
117
|
+
const stateDirectory=path.resolve(cwd,values['state-dir'] ?? defaultStateDirectory);
|
|
118
|
+
const key=await (await import('./hub/auth.mjs')).hubKey(stateDirectory,{rotate:!!values['rotate-key']});
|
|
119
|
+
if (!values.json && !values['print-key']) output.log('Hub key rotated.');
|
|
120
|
+
return {data:values['print-key'] ? {action:'print-key',stateDirectory,key} : {action:'rotate-key',stateDirectory,rotated:true}};
|
|
93
121
|
}
|
|
94
122
|
const config = await loadConfig(cwd);
|
|
95
|
-
if (command === 'init') return (await import('./toolkit/project.mjs'))
|
|
96
|
-
if (command === 'compare') return (await import('./toolkit/compare.mjs')).compare(config, positionals, values);
|
|
97
|
-
return (await import('./toolkit/
|
|
123
|
+
if (command === 'init') return { data: (await import('./toolkit/project.mjs')).init(config, output.log) };
|
|
124
|
+
if (command === 'compare') return (await import('./toolkit/compare.mjs')).compare(config, positionals, values, {log:output.log});
|
|
125
|
+
if (command === 'diff') return (await import('./toolkit/diff.mjs')).diff(config, positionals, values, { log: output.log });
|
|
126
|
+
const toolkit = await import('./toolkit/commands.mjs');
|
|
127
|
+
return command === 'check' ? toolkit.check(config, positionals, values, output.log, output.progress) : toolkit.render(config, positionals, values, output.log);
|
|
128
|
+
}
|
|
129
|
+
export async function main(args = process.argv.slice(2), cwd = process.cwd(), {
|
|
130
|
+
stdout = process.stdout.write.bind(process.stdout), stderr = process.stderr.write.bind(process.stderr),
|
|
131
|
+
exit = code => { process.exitCode = code; },
|
|
132
|
+
serviceOptions, openOptions, hubOptions, signals = process, stdoutEvents = process.stdout,
|
|
133
|
+
} = {}) {
|
|
134
|
+
let command = errorCommand(args), parsed;
|
|
135
|
+
const json = jsonRequested(args);
|
|
136
|
+
let output = createOutput({ json, command, stdout, stderr });
|
|
137
|
+
let code;
|
|
138
|
+
try {
|
|
139
|
+
parsed = parseCli(args);
|
|
140
|
+
command = parsed.values.help ? 'help' : parsed.values.version ? 'version' : commandIdentity(parsed);
|
|
141
|
+
output = createOutput({ json, command, stdout, stderr, revealKey:command === 'serve' && !!parsed.values['print-key'] });
|
|
142
|
+
if (command === 'help') {
|
|
143
|
+
const text = help(parsed.explicit ? parsed.command : undefined);
|
|
144
|
+
if (json) output.success({ subject: parsed.explicit ? commandIdentity(parsed) : null, usage: text.split('\n')[0], text });
|
|
145
|
+
else output.log(text);
|
|
146
|
+
code = 0;
|
|
147
|
+
} else if (command === 'version') {
|
|
148
|
+
if (json) output.success({ version: VERSION });
|
|
149
|
+
else output.log(VERSION);
|
|
150
|
+
code = 0;
|
|
151
|
+
} else if (command === 'open' || (command === 'serve' && !parsed.values['print-key'] && !parsed.values['rotate-key'])) {
|
|
152
|
+
const {defaultStateDirectory}=await import('./hub/registry.mjs');
|
|
153
|
+
const stateDirectory=path.resolve(cwd,parsed.values['state-dir'] ?? defaultStateDirectory);
|
|
154
|
+
const port=parsed.values.port === undefined ? command === 'open' ? 0 : 4310 : Number(parsed.values.port);
|
|
155
|
+
if (!Number.isInteger(port) || port < 0 || port > 65535) throw new CliError('USAGE_INVALID','--port must be an integer from 0 to 65535.');
|
|
156
|
+
const {runForeground}=await import('./lifecycle.mjs');
|
|
157
|
+
const start=command === 'open'
|
|
158
|
+
? async callbacks => (await import('./open.mjs')).open(parsed.positionals,parsed.values,{...openOptions,cwd,...callbacks})
|
|
159
|
+
: async callbacks => (await import('./hub.mjs')).startHub({...hubOptions,port,stateDirectory,...callbacks});
|
|
160
|
+
const run=()=>runForeground(command,start,{output,json,signals,stdoutEvents,context:{...parsed,command,stateDirectory}});
|
|
161
|
+
code=json ? await withHumanOutput(run,stderr) : await run();
|
|
162
|
+
} else {
|
|
163
|
+
const run=()=>dispatch(parsed,cwd,output,serviceOptions);
|
|
164
|
+
const result = json ? await withHumanOutput(run, stderr) : await run();
|
|
165
|
+
if (json) output.success(result.data, result.warnings);
|
|
166
|
+
else if (command === 'serve' && parsed.values['print-key']) stdout(`${result.data.key}\n`);
|
|
167
|
+
code = 0;
|
|
168
|
+
}
|
|
169
|
+
} catch (error) {
|
|
170
|
+
code = output.failure(error, {
|
|
171
|
+
...(parsed ?? {}), command,
|
|
172
|
+
...(parsed?.values['state-dir'] ? { stateDirectory: path.resolve(cwd, parsed.values['state-dir']) } : {}),
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
exit(code);
|
|
176
|
+
return code;
|
|
98
177
|
}
|
|
99
178
|
if (process.argv[1] && import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href) {
|
|
100
|
-
main()
|
|
101
|
-
const message = String(error.message).replace(/\s+/g, ' ').trim();
|
|
102
|
-
console.error(`adg: ${message}`);
|
|
103
|
-
process.exitCode = 2;
|
|
104
|
-
});
|
|
179
|
+
await main();
|
|
105
180
|
}
|
package/src/http.mjs
CHANGED
|
@@ -10,6 +10,7 @@ export const viewerFiles = {
|
|
|
10
10
|
'/access.css': 'access.css', '/switcher.js': 'switcher.js', '/switcher.css': 'switcher.css', '/instance-actions.js': 'instance-actions.js',
|
|
11
11
|
'/': 'index.html', '/index.html': 'index.html', '/app.js': 'app.js', '/auth.js': 'auth.js', '/favicon.svg': 'favicon.svg',
|
|
12
12
|
'/assets.js': 'assets.js', '/icons.js': 'icons.js', '/layout.js': 'layout.js', '/labels.js': 'labels.js',
|
|
13
|
+
'/arrangement.js': 'arrangement.js', '/arrangement-worker.js': 'arrangement-worker.js',
|
|
13
14
|
'/relationships.js': 'relationships.js', '/selection.js': 'selection.js', '/style.css': 'style.css', '/tokens.css': 'tokens.css',
|
|
14
15
|
'/token-catalog.js': 'token-catalog.js',
|
|
15
16
|
'/view-route.js': 'view-route.js',
|
package/src/hub/auth.mjs
CHANGED
|
@@ -3,13 +3,14 @@ import { mkdir, readFile, writeFile, rename, chmod } from 'node:fs/promises';
|
|
|
3
3
|
import path from 'node:path';
|
|
4
4
|
import { directLocal } from '../http.mjs';
|
|
5
5
|
import { defaultStateDirectory } from './registry.mjs';
|
|
6
|
+
import { CliError } from '../cli-output.mjs';
|
|
6
7
|
|
|
7
8
|
export async function hubKey(stateDirectory = defaultStateDirectory, { rotate = false } = {}) {
|
|
8
9
|
const file = path.join(stateDirectory, 'hub.key');
|
|
9
10
|
if (!rotate) {
|
|
10
11
|
try {
|
|
11
12
|
const key = (await readFile(file, 'utf8')).trim();
|
|
12
|
-
if (!/^adg_[a-f0-9]{64}$/.test(key)) throw new
|
|
13
|
+
if (!/^adg_[a-f0-9]{64}$/.test(key)) throw new CliError('HUB_KEY_INVALID', `Invalid hub key in ${file}; run adg serve --rotate-key.`, { context: {stateDirectory:path.resolve(stateDirectory)} });
|
|
13
14
|
await chmod(file, 0o600);
|
|
14
15
|
return key;
|
|
15
16
|
} catch (error) { if (error.code !== 'ENOENT') throw error; }
|
package/src/hub/proxy.mjs
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { request as httpRequest } from 'node:http';
|
|
2
|
+
import { CliError } from '../cli-output.mjs';
|
|
2
3
|
|
|
3
4
|
// Pipe through the owning server, preserving streaming and backpressure.
|
|
4
|
-
export function proxy(request, response, port, pathname, viewerBase) {
|
|
5
|
+
export function proxy(request, response, port, pathname, viewerBase, onDiagnostic) {
|
|
5
6
|
return new Promise(resolve => {
|
|
6
7
|
const headers = { ...request.headers, host: `127.0.0.1:${port}` };
|
|
7
8
|
for (const name of Object.keys(headers)) {
|
|
@@ -15,11 +16,12 @@ export function proxy(request, response, port, pathname, viewerBase) {
|
|
|
15
16
|
delete outgoing['set-cookie'];
|
|
16
17
|
response.writeHead(incoming.statusCode, outgoing);
|
|
17
18
|
incoming.pipe(response);
|
|
18
|
-
incoming.on('error', ()
|
|
19
|
+
incoming.on('error', error => { if (!response.destroyed) onDiagnostic?.(new CliError('NETWORK_FAILED',error.message,{cause:error})); response.destroy(); });
|
|
19
20
|
});
|
|
20
21
|
const done = () => { upstream.destroy(); resolve(); };
|
|
21
22
|
response.once('close', done);
|
|
22
|
-
upstream.on('error',
|
|
23
|
+
upstream.on('error', error => {
|
|
24
|
+
if (!response.destroyed) onDiagnostic?.(new CliError('NETWORK_FAILED','Viewer unavailable.',{cause:error}));
|
|
23
25
|
if (!response.headersSent) response.writeHead(502, { 'Content-Type': 'application/json' });
|
|
24
26
|
if (!response.destroyed) response.end(JSON.stringify({ error: 'Viewer unavailable.' }));
|
|
25
27
|
});
|