@whzxc/agent-design-gallery 0.6.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -0
- 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 +236 -0
- package/src/cli.mjs +113 -42
- 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 +8 -7
- package/src/toolkit/arch-overlay.mjs +1 -1
- package/src/toolkit/arch.mjs +62 -58
- package/src/toolkit/browser.mjs +24 -12
- package/src/toolkit/build-store.mjs +11 -3
- package/src/toolkit/build-worker.mjs +4 -1
- package/src/toolkit/build.mjs +16 -2
- package/src/toolkit/commands.mjs +158 -86
- package/src/toolkit/compare.mjs +93 -46
- package/src/toolkit/config.mjs +18 -17
- package/src/toolkit/migrate.mjs +42 -30
- package/src/toolkit/project.mjs +45 -33
- package/src/toolkit/results.mjs +44 -0
- package/src/toolkit/tokens.mjs +5 -4
package/src/service.mjs
CHANGED
|
@@ -5,6 +5,8 @@ import path from 'node:path';
|
|
|
5
5
|
import { fileURLToPath } from 'node:url';
|
|
6
6
|
import { promisify } from 'node:util';
|
|
7
7
|
import { defaultStateDirectory } from './hub/registry.mjs';
|
|
8
|
+
import { CliError } from './cli-output.mjs';
|
|
9
|
+
import { commandFailure } from './toolkit/results.mjs';
|
|
8
10
|
|
|
9
11
|
export const SERVICE_LABEL = 'org.agent-design-gallery.hub';
|
|
10
12
|
const execute = promisify(execFile);
|
|
@@ -39,58 +41,95 @@ const readOptional = async file => {
|
|
|
39
41
|
catch (error) { if (error.code !== 'ENOENT') throw error; return null; }
|
|
40
42
|
};
|
|
41
43
|
|
|
44
|
+
async function job(run, args) {
|
|
45
|
+
try { return await run('/bin/launchctl', args); }
|
|
46
|
+
catch (cause) { throw new CliError('SERVICE_FAILED', cause.message, { cause }); }
|
|
47
|
+
}
|
|
48
|
+
async function loadedJob(run, target) {
|
|
49
|
+
try { return (await run('/bin/launchctl', ['print', target])).stdout; }
|
|
50
|
+
catch (cause) {
|
|
51
|
+
if ([3, 113].includes(cause.code)) return null;
|
|
52
|
+
throw new CliError('SERVICE_FAILED', `Cannot inspect ${SERVICE_LABEL}: ${cause.stderr?.trim() || cause.message}`, { cause });
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
function statusData(status, installedPlist, agentFile, stateDirectory) {
|
|
56
|
+
return { label: SERVICE_LABEL, installed: installedPlist !== null, loaded: status !== null,
|
|
57
|
+
state: status?.match(/^\s*state = (.+)$/m)?.[1] ?? null,
|
|
58
|
+
pid: Number(status?.match(/^\s*pid = (\d+)$/m)?.[1]) || null,
|
|
59
|
+
plist: agentFile, stateDirectory,
|
|
60
|
+
logs: { stdout: path.join(stateDirectory, 'service.stdout.log'), stderr: path.join(stateDirectory, 'service.stderr.log') } };
|
|
61
|
+
}
|
|
62
|
+
|
|
42
63
|
async function migrateService(values, { home, run, nodePath, cliPath, uid, output }) {
|
|
43
64
|
const oldLabel = 'org.svg-design-gallery.hub';
|
|
44
65
|
const agents = path.join(home, 'Library', 'LaunchAgents');
|
|
45
|
-
const oldAgent = path.join(agents, `${oldLabel}.plist`);
|
|
46
|
-
const newAgent = path.join(agents, `${SERVICE_LABEL}.plist`);
|
|
66
|
+
const oldAgent = path.join(agents, `${oldLabel}.plist`), newAgent = path.join(agents, `${SERVICE_LABEL}.plist`);
|
|
47
67
|
const installed = await readOptional(oldAgent), args = launchArguments(installed);
|
|
48
68
|
const argument = flag => args.includes(flag) ? args[args.indexOf(flag) + 1] : undefined;
|
|
49
69
|
const base = process.env.XDG_STATE_HOME || path.join(home, '.local/state');
|
|
50
70
|
const oldState = path.resolve(argument('--state-dir') ?? path.join(base, 'svg-design-gallery'));
|
|
51
71
|
const newState = path.resolve(values['state-dir'] ?? path.join(base, 'agent-design-gallery'));
|
|
52
|
-
const
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
await
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
await
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
72
|
+
const data = { complete: false, from: {label:oldLabel,stateDirectory:oldState,plist:oldAgent},
|
|
73
|
+
to: {label:SERVICE_LABEL,stateDirectory:newState,plist:newAgent}, changes: [], keyPrefixUpdated:false, references:[], service:null };
|
|
74
|
+
const warnings = [];
|
|
75
|
+
try {
|
|
76
|
+
const exists = async file => (await lstat(file).catch(error => { if (error.code !== 'ENOENT') throw error; return null; })) !== null;
|
|
77
|
+
if (await exists(newState)) throw new CliError('MIGRATION_CONFLICT', `Migration target already exists: ${newState}; move it aside before running adg service migrate.`);
|
|
78
|
+
if (await exists(newAgent)) throw new CliError('MIGRATION_CONFLICT', `LaunchAgent already exists: ${newAgent}; inspect it before running adg service migrate.`);
|
|
79
|
+
let oldInfo;
|
|
80
|
+
try { oldInfo = await lstat(oldState); }
|
|
81
|
+
catch (cause) { if (['ENOENT','ENOTDIR'].includes(cause.code)) throw new CliError('DIRECTORY_NOT_FOUND', cause.message, { cause }); throw cause; }
|
|
82
|
+
if (!oldInfo.isDirectory()) throw new CliError('DIRECTORY_NOT_FOUND', `Hub state is not a directory: ${oldState}`);
|
|
83
|
+
const executable = await realpath(nodePath), entry = await realpath(cliPath);
|
|
84
|
+
const port = Number(argument('--port') ?? 4310);
|
|
85
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) throw new CliError('STATE_INVALID', 'Invalid port in the old LaunchAgent; correct it before migration.');
|
|
86
|
+
const oldKey = await readOptional(path.join(oldState, 'hub.key'));
|
|
87
|
+
if (oldKey !== null && !/^(?:sdg|adg)_[a-f0-9]{64}$/.test(oldKey.trim())) throw new CliError('STATE_INVALID', 'Invalid hub key file; correct it before migration.');
|
|
88
|
+
const domain = `gui/${uid}`, oldTarget = `${domain}/${oldLabel}`;
|
|
89
|
+
let loaded = false;
|
|
90
|
+
try { await run('/bin/launchctl', ['print', oldTarget]); loaded = true; }
|
|
91
|
+
catch (cause) { if (![3,113].includes(cause.code)) throw new CliError('SERVICE_FAILED', cause.message, { cause }); }
|
|
92
|
+
if (loaded) { await job(run, ['bootout', oldTarget]); output(`Stopped ${oldLabel}`); }
|
|
93
|
+
await mkdir(path.dirname(newState), { recursive:true });
|
|
94
|
+
await rename(oldState,newState);
|
|
95
|
+
data.changes.push({action:'renamed',path:newState,from:oldState});
|
|
96
|
+
output(`Moved ${oldState} -> ${newState}`);
|
|
97
|
+
if (oldKey?.trim().startsWith('sdg_')) {
|
|
98
|
+
await writeFile(path.join(newState,'hub.key'),oldKey.replace('sdg_','adg_'),{mode:0o600});
|
|
99
|
+
data.changes.push({action:'updated',path:path.join(newState,'hub.key'),from:null});
|
|
100
|
+
data.keyPrefixUpdated = true;
|
|
101
|
+
output('Updated hub key prefix; use adg serve --print-key when updating browser access.');
|
|
102
|
+
}
|
|
103
|
+
await mkdir(agents,{recursive:true});
|
|
104
|
+
const plist = renderLaunchAgent({nodePath:executable,cliPath:entry,stateDirectory:newState,port});
|
|
105
|
+
await writeFile(newAgent,plist);
|
|
106
|
+
data.changes.push({action:'created',path:newAgent,from:null});
|
|
107
|
+
if (installed !== null) {
|
|
108
|
+
await rm(oldAgent);
|
|
109
|
+
data.changes.push({action:'deleted',path:oldAgent,from:null});
|
|
110
|
+
output(`Removed ${oldAgent}`);
|
|
111
|
+
}
|
|
112
|
+
output(`Created ${newAgent}`);
|
|
113
|
+
await job(run,['bootstrap',domain,newAgent]);
|
|
114
|
+
output(`Started ${SERVICE_LABEL}`);
|
|
115
|
+
data.service = statusData(await loadedJob(run,`${domain}/${SERVICE_LABEL}`),plist,newAgent,newState);
|
|
116
|
+
output(`Other LaunchAgents referencing ${oldState}:`);
|
|
117
|
+
for (const name of (await readdir(agents)).sort()) {
|
|
118
|
+
if (!name.endsWith('.plist') || name === `${SERVICE_LABEL}.plist`) continue;
|
|
119
|
+
const file=path.join(agents,name),content=await readFile(file,'utf8');
|
|
120
|
+
if (unxml(content).includes(oldState)) {
|
|
121
|
+
data.references.push(file); output(file);
|
|
122
|
+
if (!warnings.length) warnings.push({code:'MIGRATION_REFERENCES_REMAIN',message:`Other LaunchAgents still reference ${oldState}.`,next:[]});
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
if (!data.references.length) output('None.');
|
|
126
|
+
data.complete = true;
|
|
127
|
+
return {data,warnings};
|
|
128
|
+
} catch (cause) {
|
|
129
|
+
if (cause instanceof CliError) cause.context.stateDirectory = newState;
|
|
130
|
+
if (!data.changes.length) throw cause;
|
|
131
|
+
throw commandFailure(cause,data,warnings);
|
|
91
132
|
}
|
|
92
|
-
if (!count) output('None.');
|
|
93
|
-
return 0;
|
|
94
133
|
}
|
|
95
134
|
|
|
96
135
|
// Overrides keep launchctl and the user's LaunchAgents directory out of contract checks.
|
|
@@ -99,65 +138,47 @@ export async function service(action, values = {}, {
|
|
|
99
138
|
nodePath = process.execPath, cliPath = fileURLToPath(new URL('./cli.mjs', import.meta.url)),
|
|
100
139
|
uid = process.getuid?.(), output = console.log,
|
|
101
140
|
} = {}) {
|
|
102
|
-
if (platform !== 'darwin') throw new
|
|
103
|
-
if (!['install',
|
|
104
|
-
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
const
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
111
|
-
const installedArgs = launchArguments(installedPlist);
|
|
112
|
-
const stateFlag = installedArgs.indexOf('--state-dir');
|
|
113
|
-
const installedStateDirectory = stateFlag >= 0 ? installedArgs[stateFlag + 1] : undefined;
|
|
114
|
-
const stateDirectory = path.resolve(values['state-dir'] ?? (action === 'install' ? undefined : installedStateDirectory) ?? defaultStateDirectory);
|
|
115
|
-
const domain = `gui/${uid}`, target = `${domain}/${SERVICE_LABEL}`;
|
|
116
|
-
const stdout = path.join(stateDirectory, 'service.stdout.log');
|
|
117
|
-
const stderr = path.join(stateDirectory, 'service.stderr.log');
|
|
118
|
-
const loaded = async () => {
|
|
119
|
-
try { return (await run('/bin/launchctl', ['print', target])).stdout; }
|
|
120
|
-
catch (error) {
|
|
121
|
-
if ([3, 113].includes(error.code)) return null;
|
|
122
|
-
throw new Error(`Cannot inspect ${SERVICE_LABEL}: ${error.stderr?.trim() || error.message}`);
|
|
123
|
-
}
|
|
124
|
-
};
|
|
141
|
+
if (platform !== 'darwin') throw new CliError('SERVICE_UNSUPPORTED','adg service is supported only on macOS (LaunchAgent).');
|
|
142
|
+
if (!['install','uninstall','status','logs','migrate'].includes(action)) throw new CliError('USAGE_INVALID','Expected adg service install|uninstall|status|logs|migrate; run adg service --help.');
|
|
143
|
+
if (action === 'migrate') return migrateService(values,{home,run,nodePath,cliPath,uid,output});
|
|
144
|
+
const agentFile=path.join(home,'Library','LaunchAgents',`${SERVICE_LABEL}.plist`);
|
|
145
|
+
const installedPlist=await readOptional(agentFile),installedArgs=launchArguments(installedPlist),stateFlag=installedArgs.indexOf('--state-dir');
|
|
146
|
+
const stateDirectory=path.resolve(values['state-dir'] ?? (action === 'install' ? undefined : stateFlag >= 0 ? installedArgs[stateFlag+1] : undefined) ?? defaultStateDirectory);
|
|
147
|
+
const domain=`gui/${uid}`,target=`${domain}/${SERVICE_LABEL}`;
|
|
148
|
+
const stdout=path.join(stateDirectory,'service.stdout.log'),stderr=path.join(stateDirectory,'service.stderr.log');
|
|
125
149
|
if (action === 'logs') {
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
output(`${file}\n${
|
|
150
|
+
const logs=[];
|
|
151
|
+
for (const [stream,file] of [['stdout',stdout],['stderr',stderr]]) {
|
|
152
|
+
const content=await readOptional(file),lines=content?.trimEnd().split('\n').slice(-200) ?? [];
|
|
153
|
+
logs.push({stream,path:file,exists:content!==null,lines:content?.trimEnd() ? lines : []});
|
|
154
|
+
if (!values.json && content !== null) output(`${file}\n${lines.join('\n')}`);
|
|
131
155
|
}
|
|
132
|
-
return
|
|
156
|
+
return {data:{label:SERVICE_LABEL,stateDirectory,logs}};
|
|
133
157
|
}
|
|
134
158
|
if (action === 'status') {
|
|
135
|
-
const
|
|
136
|
-
output(JSON.stringify(
|
|
137
|
-
|
|
138
|
-
pid: Number(status?.match(/^\s*pid = (\d+)$/m)?.[1]) || null,
|
|
139
|
-
plist: agentFile, stateDirectory, logs: { stdout, stderr } }, null, 2));
|
|
140
|
-
return 0;
|
|
159
|
+
const data=statusData(await loadedJob(run,target),installedPlist,agentFile,stateDirectory);
|
|
160
|
+
if (!values.json) output(JSON.stringify(data,null,2));
|
|
161
|
+
return {data};
|
|
141
162
|
}
|
|
142
163
|
if (action === 'uninstall') {
|
|
143
|
-
if (await
|
|
144
|
-
await rm(agentFile,
|
|
164
|
+
if (await loadedJob(run,target) !== null) await job(run,['bootout',target]);
|
|
165
|
+
await rm(agentFile,{force:true});
|
|
145
166
|
output(`Uninstalled ${SERVICE_LABEL}. State and logs retained in ${stateDirectory}.`);
|
|
146
|
-
return
|
|
167
|
+
return {data:{label:SERVICE_LABEL,plist:agentFile,stateDirectory,retained:true}};
|
|
147
168
|
}
|
|
148
|
-
const port
|
|
149
|
-
if (!Number.isInteger(port) || port < 1 || port > 65535) throw new
|
|
150
|
-
if (installedPlist !== null) throw new
|
|
151
|
-
const executable
|
|
152
|
-
await mkdir(path.dirname(agentFile), {
|
|
153
|
-
await
|
|
154
|
-
|
|
155
|
-
await writeFile(agentFile,
|
|
156
|
-
try { await run('/bin/launchctl',
|
|
157
|
-
catch (
|
|
158
|
-
await rm(agentFile,
|
|
159
|
-
throw new
|
|
169
|
+
const port=values.port===undefined ? 4310 : Number(values.port);
|
|
170
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) throw new CliError('USAGE_INVALID','--port must be an integer from 1 to 65535.');
|
|
171
|
+
if (installedPlist !== null) throw new CliError('SERVICE_ALREADY_INSTALLED',`${SERVICE_LABEL} is already installed; run adg service uninstall before reinstalling.`);
|
|
172
|
+
const executable=await realpath(nodePath),entry=await realpath(cliPath);
|
|
173
|
+
await mkdir(path.dirname(agentFile),{recursive:true});await mkdir(stateDirectory,{recursive:true});
|
|
174
|
+
await Promise.all([stdout,stderr].map(file=>writeFile(file,'',{flag:'a'})));
|
|
175
|
+
const plist=renderLaunchAgent({nodePath:executable,cliPath:entry,stateDirectory,port});
|
|
176
|
+
await writeFile(agentFile,plist);
|
|
177
|
+
try { await run('/bin/launchctl',['bootstrap',domain,agentFile]); }
|
|
178
|
+
catch (cause) {
|
|
179
|
+
await rm(agentFile,{force:true});
|
|
180
|
+
throw new CliError('SERVICE_FAILED',`Cannot install ${SERVICE_LABEL}: ${cause.stderr?.trim() || cause.message}`,{cause});
|
|
160
181
|
}
|
|
161
182
|
output(`Installed ${SERVICE_LABEL}. Logs: ${stdout} and ${stderr}.`);
|
|
162
|
-
return
|
|
183
|
+
return {data:{service:statusData(await loadedJob(run,target),plist,agentFile,stateDirectory),port}};
|
|
163
184
|
}
|
package/src/toolkit/arch-git.mjs
CHANGED
|
@@ -2,6 +2,7 @@ import { execFile } from 'node:child_process';
|
|
|
2
2
|
import { promisify } from 'node:util';
|
|
3
3
|
import path from 'node:path';
|
|
4
4
|
import { realpath } from 'node:fs/promises';
|
|
5
|
+
import { CliError } from '../cli-output.mjs';
|
|
5
6
|
const exec = promisify(execFile);
|
|
6
7
|
async function physicalPath(file) {
|
|
7
8
|
try { return await realpath(file); }
|
|
@@ -14,24 +15,24 @@ async function physicalPath(file) {
|
|
|
14
15
|
async function git(root, args) {
|
|
15
16
|
try { return (await exec('git',['-C',root,...args],{maxBuffer:16*1024*1024})).stdout; }
|
|
16
17
|
catch(error) {
|
|
17
|
-
if(error.code==='ENOENT')throw
|
|
18
|
-
throw error;
|
|
18
|
+
if(error.code==='ENOENT')throw new CliError('GIT_UNAVAILABLE', 'Git is unavailable; install Git and retry --base.', { cause: error });
|
|
19
|
+
throw new CliError('GIT_BASE_INVALID', error.message, { cause: error, context: { project: root, gitCause: 'read' } });
|
|
19
20
|
}
|
|
20
21
|
}
|
|
21
22
|
export async function resolveBase(config, rev) {
|
|
22
|
-
if(typeof rev!=='string'||!rev.trim())throw
|
|
23
|
+
if(typeof rev!=='string'||!rev.trim())throw new CliError('USAGE_INVALID', 'Set --base to a Git revision, for example HEAD.');
|
|
23
24
|
let root;
|
|
24
25
|
try { root=await realpath((await git(config.root,['rev-parse','--show-toplevel'])).trim()); }
|
|
25
26
|
catch(error) {
|
|
26
|
-
if(error.
|
|
27
|
-
throw
|
|
27
|
+
if(error.code==='GIT_UNAVAILABLE')throw error;
|
|
28
|
+
throw new CliError('GIT_BASE_INVALID', 'This project is not in a Git repository; run from a repository or initialize one before using --base.', { cause: error, context: { project: config.root, gitCause: 'repository' } });
|
|
28
29
|
}
|
|
29
30
|
try {
|
|
30
31
|
const sha=(await git(root,['rev-parse','--verify','--end-of-options',`${rev}^{commit}`])).trim();
|
|
31
32
|
return {root,rev,sha};
|
|
32
33
|
} catch(error) {
|
|
33
|
-
if(error.
|
|
34
|
-
throw
|
|
34
|
+
if(error.code==='GIT_UNAVAILABLE')throw error;
|
|
35
|
+
throw new CliError('GIT_BASE_INVALID', `Unknown Git revision ${rev}; choose an existing commit or fetch the revision and retry --base.`, { cause: error, context: { project: root, gitCause: 'revision' } });
|
|
35
36
|
}
|
|
36
37
|
}
|
|
37
38
|
export async function readBase(base, file) {
|
|
@@ -206,7 +206,7 @@ export async function buildOverlay(config,file,{base,browser,snapshot}={}) {
|
|
|
206
206
|
const old=await readBase(base,file),bytes=readFileSync(file);snapshot.set(file,bytes);
|
|
207
207
|
const text=bytes.toString('utf8');
|
|
208
208
|
const checked=inspectArch(text,Infinity);
|
|
209
|
-
if(checked.problems.length)throw Error(checked.problems.join('\n'));
|
|
209
|
+
if(checked.problems.length)throw Error(checked.problems.map(problem=>problem.message).join('\n'));
|
|
210
210
|
const overlay=overlayModels(checked.model,old.text===null?null:parse(old.text));
|
|
211
211
|
const built=await buildArch(config,file,{model:overlay.model,browser,snapshot});
|
|
212
212
|
const frame=built.frames[0],used=new Set(checked.classes);
|
package/src/toolkit/arch.mjs
CHANGED
|
@@ -2,7 +2,8 @@ import { readFileSync, existsSync, globSync, statSync } from 'node:fs';
|
|
|
2
2
|
import path from 'node:path';
|
|
3
3
|
import { parse, render } from 'pele';
|
|
4
4
|
import { parseTokens } from './tokens.mjs';
|
|
5
|
-
import { launch } from './browser.mjs';
|
|
5
|
+
import { launch, browserTask } from './browser.mjs';
|
|
6
|
+
import { cleanup } from './results.mjs';
|
|
6
7
|
|
|
7
8
|
export const phases = ['progress', 'waiting', 'done', 'stopped', 'uncertain'];
|
|
8
9
|
export const marks = ['experimental', 'temporary', 'gap'];
|
|
@@ -10,34 +11,36 @@ export const vocabulary = [...phases, ...marks];
|
|
|
10
11
|
const reserved = ['added', 'removed', 'changed'];
|
|
11
12
|
|
|
12
13
|
export function sidecar(text = '') {
|
|
13
|
-
const problems = [], owners = []; let status, body = text.trim();
|
|
14
|
+
const problems = [], owners = [], ownerLines = []; let status, body = text.trim();
|
|
15
|
+
const add = (code, message, line = null) => problems.push({code, message, line, column:null});
|
|
14
16
|
if (/^---\r?\n/.test(text)) {
|
|
15
17
|
const match = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)([\s\S]*)$/.exec(text);
|
|
16
|
-
if (!match) return {owners, body:'', problems:['Unclosed sidecar frontmatter']};
|
|
18
|
+
if (!match) return {owners, ownerLines, body:'', problems:[{code:'ARCH_SIDECAR_INVALID',message:'Unclosed sidecar frontmatter',line:1,column:null}]};
|
|
17
19
|
body = match[2].trim(); let current; const keys = new Set();
|
|
18
20
|
const scalar = value => {
|
|
19
21
|
const quoted = /^(["'])(.*)\1$/.exec(value);
|
|
20
22
|
return quoted ? quoted[2] : value;
|
|
21
23
|
};
|
|
22
|
-
for (const raw of match[1].split(/\r?\n/)) {
|
|
24
|
+
for (const [index, raw] of match[1].split(/\r?\n/).entries()) {
|
|
25
|
+
const line = index + 2;
|
|
23
26
|
if (!raw.trim()) continue;
|
|
24
27
|
const key = /^(owners|status):\s*(.*)$/.exec(raw);
|
|
25
28
|
if (key) {
|
|
26
29
|
current = key[1];
|
|
27
|
-
if (keys.has(current))
|
|
30
|
+
if (keys.has(current)) add('ARCH_SIDECAR_INVALID', `Duplicate sidecar frontmatter key ${current}`, line);
|
|
28
31
|
keys.add(current);
|
|
29
32
|
if (current === 'status' && key[2].trim()) status = scalar(key[2].trim());
|
|
30
33
|
else if (current === 'owners' && !key[2].trim()) continue;
|
|
31
|
-
else
|
|
34
|
+
else add('ARCH_SIDECAR_INVALID', `Invalid sidecar ${current}; use ${current === 'owners' ? 'an indented list' : 'a non-empty string'}`, line);
|
|
32
35
|
} else {
|
|
33
36
|
const item = /^ +-[ \t]+(.+)$/.exec(raw);
|
|
34
|
-
if (item && current === 'owners') owners.push(scalar(item[1].trim()));
|
|
35
|
-
else
|
|
37
|
+
if (item && current === 'owners') { owners.push(scalar(item[1].trim())); ownerLines.push(line); }
|
|
38
|
+
else add('ARCH_SIDECAR_INVALID', `Invalid sidecar frontmatter key or entry: ${raw.trim()}`, line);
|
|
36
39
|
}
|
|
37
40
|
}
|
|
38
41
|
}
|
|
39
|
-
for (const owner of owners) if (path.isAbsolute(owner) || owner.split('/').includes('..') || owner.includes('\\'))
|
|
40
|
-
return {owners,status,body,problems};
|
|
42
|
+
for (const [index, owner] of owners.entries()) if (path.isAbsolute(owner) || owner.split('/').includes('..') || owner.includes('\\')) add('ARCH_OWNER_INVALID', `Invalid owners path ${owner}; use project-root-relative paths or globs`, ownerLines[index] ?? null);
|
|
43
|
+
return {owners,ownerLines,status,body,problems};
|
|
41
44
|
}
|
|
42
45
|
|
|
43
46
|
// Preserve newlines and statement delimiters while masking quoted labels and comments.
|
|
@@ -61,9 +64,10 @@ function statements(text) {
|
|
|
61
64
|
}
|
|
62
65
|
export function inspectArch(text, maxEdges = 30) {
|
|
63
66
|
const problems=[], classes=new Set(), clean=statements(text);
|
|
67
|
+
const add=(code,message,line=null)=>problems.push({code,message,line,column:null});
|
|
64
68
|
for (const match of clean.matchAll(/(?:^|[;\n])\s*(classDef|style|linkStyle)\b/g)) {
|
|
65
69
|
const line=clean.slice(0,match.index+match[0].length).split('\n').length;
|
|
66
|
-
|
|
70
|
+
add('ARCH_PAINT_FORBIDDEN', `Painting statement ${match[1]} at line ${line}; paint comes from tokens`, line);
|
|
67
71
|
}
|
|
68
72
|
// Inspect configuration keys without interpreting words inside prose or values.
|
|
69
73
|
const configRegions=[...text.matchAll(/%%\{[\s\S]*?\}%%/g), ...text.matchAll(/^---\r?\n[\s\S]*?\r?\n---/g)];
|
|
@@ -74,7 +78,7 @@ export function inspectArch(text, maxEdges = 30) {
|
|
|
74
78
|
if(!/[{,]\s*$/.test(before) && !/^[ \t]*(?:-[ \t]+)?$/.test(lineStart))continue;
|
|
75
79
|
const key=token[0].replace(/^["']|["']$/g,'');
|
|
76
80
|
if(/^(?:theme\w*|[\w-]*color[\w-]*|fill|stroke|background)$/i.test(key))
|
|
77
|
-
|
|
81
|
+
add('ARCH_PAINT_FORBIDDEN', `Painting directive/frontmatter key ${key} at line ${text.slice(0,region.index+token.index).split('\n').length}; paint comes from tokens`, text.slice(0,region.index+token.index).split('\n').length);
|
|
78
82
|
}
|
|
79
83
|
let model;
|
|
80
84
|
try {
|
|
@@ -82,32 +86,32 @@ export function inspectArch(text, maxEdges = 30) {
|
|
|
82
86
|
// The state graph flattens composite states; relations contains only root edges.
|
|
83
87
|
const count=(model.type==='state' ? model.graph.edges :
|
|
84
88
|
[model.edges,model.relations,model.messages,model.relationships,model.rels,model.graph?.edges,model.links].find(Array.isArray)??[]).length;
|
|
85
|
-
if(count>maxEdges)
|
|
86
|
-
} catch(error) {
|
|
89
|
+
if(count>maxEdges) add('ARCH_EDGE_LIMIT', `${count} edges/messages exceeds check.archMaxEdges (${maxEdges})`);
|
|
90
|
+
} catch(error) { add('ARCH_SYNTAX', `Pele: ${error.message.replace(/\s+/g,' ')} (line ${error.line ?? 1})`, error.line ?? null); }
|
|
87
91
|
if(model?.type==='flowchart' || model?.type==='state') {
|
|
88
|
-
const
|
|
92
|
+
const addClass=value=>{for(const name of (Array.isArray(value)?value.join(' '):value??'').split(/[ \t,]+/).filter(Boolean))classes.add(name);};
|
|
89
93
|
if(model.type==='flowchart') {
|
|
90
|
-
for(const node of model.nodes.values())
|
|
91
|
-
for(const item of [...model.edges,...model.subgraphs])
|
|
94
|
+
for(const node of model.nodes.values())addClass(node.classes);
|
|
95
|
+
for(const item of [...model.edges,...model.subgraphs])addClass(item.classes);
|
|
92
96
|
} else {
|
|
93
97
|
const visit=statements=>{for(const stmt of statements??[]) {
|
|
94
|
-
if(stmt.stmt==='applyClass')
|
|
95
|
-
|
|
98
|
+
if(stmt.stmt==='applyClass')addClass(stmt.styleClass);
|
|
99
|
+
addClass(stmt.classes);addClass(stmt.state1?.classes);addClass(stmt.state2?.classes);
|
|
96
100
|
visit(stmt.doc);
|
|
97
101
|
}};
|
|
98
102
|
visit(model.rootDoc);
|
|
99
103
|
}
|
|
100
104
|
// Keep assignments to unresolved IDs visible to the vocabulary check, too.
|
|
101
|
-
for(const match of clean.matchAll(/(?:^|[;\n])[ \t]*class[ \t]+[^ \t;\r\n]+[ \t]+([^;\r\n]+)/g))
|
|
102
|
-
for(const name of classes)if(!vocabulary.includes(name))
|
|
105
|
+
for(const match of clean.matchAll(/(?:^|[;\n])[ \t]*class[ \t]+[^ \t;\r\n]+[ \t]+([^;\r\n]+)/g))addClass(match[1]);
|
|
106
|
+
for(const name of classes)if(!vocabulary.includes(name))add('ARCH_CLASS_INVALID', `${reserved.includes(name)?'Reserved':'Unknown'} class ${name}; vocabulary: ${vocabulary.join(', ')} (added, removed, changed are reserved)`);
|
|
103
107
|
}
|
|
104
108
|
return {model,classes:vocabulary.filter(name=>classes.has(name)),problems};
|
|
105
109
|
}
|
|
106
110
|
export function ownerProblems(config, metadata) {
|
|
107
|
-
return metadata.owners.flatMap(owner => {
|
|
111
|
+
return metadata.owners.flatMap((owner, index) => {
|
|
108
112
|
if(path.isAbsolute(owner) || owner.split('/').includes('..') || owner.includes('\\')) return [];
|
|
109
113
|
const matches=globSync(owner,{cwd:config.root,exclude:['**/node_modules/**','**/.git/**']});
|
|
110
|
-
return matches.some(file=>statSync(path.join(config.root,file),{throwIfNoEntry:false})?.isFile()) ? [] : [
|
|
114
|
+
return matches.some(file=>statSync(path.join(config.root,file),{throwIfNoEntry:false})?.isFile()) ? [] : [{code:'ARCH_OWNER_INVALID',message:`Owners entry ${owner} matches no file`,line:metadata.ownerLines?.[index]??null,column:null}];
|
|
111
115
|
});
|
|
112
116
|
}
|
|
113
117
|
|
|
@@ -137,41 +141,41 @@ export async function renderArch(model, tokenSource, {browser: suppliedBrowser}
|
|
|
137
141
|
const requests=new Map(),measured=new Map();
|
|
138
142
|
const key=(text,size,style)=>JSON.stringify([text,size,style]);
|
|
139
143
|
const browser=suppliedBrowser ?? await launch();
|
|
140
|
-
let page;
|
|
144
|
+
let page, primary;
|
|
141
145
|
try {
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
const
|
|
146
|
-
|
|
146
|
+
return await browserTask(browser, async () => {
|
|
147
|
+
page=await browser.newPage();
|
|
148
|
+
await page.setContent(`<style>${tokenSource.replace(/<\/style/gi,'<\\/style')}</style>`);
|
|
149
|
+
const fonts=await page.evaluate(()=>{
|
|
150
|
+
const style=getComputedStyle(document.documentElement);
|
|
151
|
+
return {ui:style.getPropertyValue('--font-ui').trim(),mono:style.getPropertyValue('--font-mono').trim()};
|
|
152
|
+
});
|
|
153
|
+
for(let pass=0;pass<16;pass++) {
|
|
154
|
+
const result=render(model,{fontFamily:fonts.ui,fontFamilyMono:fonts.mono,measurer:{width(text,size,style){
|
|
155
|
+
const id=key(text,size,style);
|
|
156
|
+
if(!measured.has(id))requests.set(id,{text,size,style});
|
|
157
|
+
return measured.get(id)??text.length*size*.6;
|
|
158
|
+
}}});
|
|
159
|
+
if(!requests.size)return result;
|
|
160
|
+
const widths=await page.evaluate(async requests=>{
|
|
161
|
+
const canvas=document.createElement('canvas').getContext('2d'),widths=requests.map(()=>0);
|
|
162
|
+
for(const theme of ['light','dark']) {
|
|
163
|
+
document.documentElement.dataset.theme=theme;
|
|
164
|
+
const style=getComputedStyle(document.documentElement),ui=style.getPropertyValue('--font-ui').trim(),mono=style.getPropertyValue('--font-mono').trim();
|
|
165
|
+
await document.fonts.ready;
|
|
166
|
+
requests.forEach(({text,size,style},i)=>{
|
|
167
|
+
canvas.font=`${style&2?'italic ':''}${style&1?'bold ':''}${size}px ${style&4?mono:ui}`;
|
|
168
|
+
widths[i]=Math.max(widths[i],canvas.measureText(text).width);
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
return widths;
|
|
172
|
+
},[...requests.values()]);
|
|
173
|
+
[...requests.keys()].forEach((id,i)=>measured.set(id,widths[i]));requests.clear();
|
|
174
|
+
}
|
|
175
|
+
throw Error('Pele label measurement did not settle after 16 passes');
|
|
147
176
|
});
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
const id=key(text,size,style);
|
|
151
|
-
if(!measured.has(id))requests.set(id,{text,size,style});
|
|
152
|
-
return measured.get(id)??text.length*size*.6;
|
|
153
|
-
}}});
|
|
154
|
-
if(!requests.size)return result;
|
|
155
|
-
const widths=await page.evaluate(async requests=>{
|
|
156
|
-
const canvas=document.createElement('canvas').getContext('2d'),widths=requests.map(()=>0);
|
|
157
|
-
for(const theme of ['light','dark']) {
|
|
158
|
-
document.documentElement.dataset.theme=theme;
|
|
159
|
-
const style=getComputedStyle(document.documentElement),ui=style.getPropertyValue('--font-ui').trim(),mono=style.getPropertyValue('--font-mono').trim();
|
|
160
|
-
await document.fonts.ready;
|
|
161
|
-
requests.forEach(({text,size,style},i)=>{
|
|
162
|
-
canvas.font=`${style&2?'italic ':''}${style&1?'bold ':''}${size}px ${style&4?mono:ui}`;
|
|
163
|
-
widths[i]=Math.max(widths[i],canvas.measureText(text).width);
|
|
164
|
-
});
|
|
165
|
-
}
|
|
166
|
-
return widths;
|
|
167
|
-
},[...requests.values()]);
|
|
168
|
-
[...requests.keys()].forEach((id,i)=>measured.set(id,widths[i]));requests.clear();
|
|
169
|
-
}
|
|
170
|
-
throw Error('Pele label measurement did not settle after 16 passes');
|
|
171
|
-
} finally {
|
|
172
|
-
if(suppliedBrowser) await page?.close();
|
|
173
|
-
else await browser.close();
|
|
174
|
-
}
|
|
177
|
+
} catch (cause) { primary=cause; throw cause; }
|
|
178
|
+
finally { await cleanup(() => suppliedBrowser ? page?.close() : browser.close(), primary); }
|
|
175
179
|
}
|
|
176
180
|
|
|
177
181
|
export async function buildArch(config,file,{snapshot,model:overlayModel,browser}={}) {
|
|
@@ -185,7 +189,7 @@ export async function buildArch(config,file,{snapshot,model:overlayModel,browser
|
|
|
185
189
|
parseTokens(tokenSource);
|
|
186
190
|
const checked=inspectArch(text,Infinity);
|
|
187
191
|
const problems=[...checked.problems,...metadata.problems];
|
|
188
|
-
if(problems.length)throw Error(problems.join('\n'));
|
|
192
|
+
if(problems.length)throw Error(problems.map(problem=>problem.message).join('\n'));
|
|
189
193
|
const result=await renderArch(overlayModel??checked.model,tokenSource,{browser});
|
|
190
194
|
const legend=checked.classes.length?`<div class="arch-legend">${checked.classes.map(name=>`<span class="arch-key ${name}" style="--arch-color:var(--arch-${name})"><i class="arch-swatch"></i>${name}</span>`).join('')}</div>`:'';
|
|
191
195
|
const html=`<section data-adg-arch>${legend}${result.svg}</section>`;
|
|
@@ -210,7 +214,7 @@ export function inspectArchLabels() {
|
|
|
210
214
|
const matrix=shape.getScreenCTM()?.inverse();
|
|
211
215
|
const inside=matrix && [[r.left+1,r.top+1],[r.right-1,r.top+1],[r.left+1,r.bottom-1],[r.right-1,r.bottom-1]].every(([x,y])=>shape.isPointInFill(new DOMPoint(x,y).matrixTransform(matrix)));
|
|
212
216
|
if(!inside || r.left<box.left-1||r.right>box.right+1||r.top<box.top-1||r.bottom>box.bottom+1)
|
|
213
|
-
problems.push(
|
|
217
|
+
problems.push({code:'ARCH_LABEL_OVERFLOW',message:`Label overflows node ${node.dataset.id}: ${text.textContent.trim()}`,line:null,column:null});
|
|
214
218
|
}
|
|
215
219
|
}
|
|
216
220
|
return problems;
|
package/src/toolkit/browser.mjs
CHANGED
|
@@ -1,21 +1,33 @@
|
|
|
1
1
|
import { UPDATE } from './config.mjs';
|
|
2
|
+
import { CliError } from '../cli-output.mjs';
|
|
2
3
|
|
|
3
|
-
export async function launch() {
|
|
4
|
+
export async function launch({ importPlaywright = () => import('playwright') } = {}) {
|
|
4
5
|
let chromium;
|
|
5
|
-
try { ({ chromium } = await
|
|
6
|
-
catch { throw new
|
|
6
|
+
try { ({ chromium } = await importPlaywright()); }
|
|
7
|
+
catch (error) { throw new CliError('PLAYWRIGHT_UNAVAILABLE', `Playwright is missing; run ${UPDATE}`, { cause: error }); }
|
|
7
8
|
try { return await chromium.launch(); }
|
|
8
9
|
catch (error) {
|
|
9
|
-
if (/Executable doesn't exist|playwright install/i.test(error.message)) throw new
|
|
10
|
-
throw new
|
|
10
|
+
if (/Executable doesn't exist|playwright install/i.test(error.message)) throw new CliError('CHROMIUM_UNAVAILABLE', 'Chromium is missing; run npx playwright@1.64.1 install chromium', { cause: error });
|
|
11
|
+
throw new CliError('BROWSER_FAILED', `Cannot launch Chromium: ${error.message.split('\n')[0]}; check your Playwright installation (npx playwright@1.64.1 install chromium)`, { cause: error });
|
|
11
12
|
}
|
|
12
13
|
}
|
|
13
14
|
export async function loadFrame(page, frame, theme = 'light') {
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
15
|
+
return browserTask(page.context().browser(), async () => {
|
|
16
|
+
await page.emulateMedia({ colorScheme: theme, reducedMotion: 'reduce' });
|
|
17
|
+
await page.setViewportSize({ width: Math.ceil(frame.width ?? 1600), height: Math.ceil(frame.height ?? 1200) });
|
|
18
|
+
await page.setContent(frame.document(theme));
|
|
19
|
+
await page.evaluate(() => document.fonts.ready);
|
|
20
|
+
const box = await page.locator('[data-adg-frame]').boundingBox();
|
|
21
|
+
await page.setViewportSize({ width: Math.max(1, Math.ceil(box.width)), height: Math.max(1, Math.ceil(box.height)) });
|
|
22
|
+
return box;
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Classify Playwright execution failures where the browser's connection is observable. */
|
|
27
|
+
export async function browserTask(browser, work) {
|
|
28
|
+
try { return await work(); }
|
|
29
|
+
catch (error) {
|
|
30
|
+
if (error instanceof CliError) throw error;
|
|
31
|
+
throw new CliError(browser?.isConnected() === false ? 'BROWSER_FAILED' : 'RENDER_FAILED', error.message, { cause: error });
|
|
32
|
+
}
|
|
21
33
|
}
|