@kevlns/art-workshop 0.5.1 → 0.5.2
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/AGENTS.md +25 -25
- package/LICENSE +21 -21
- package/README.md +63 -63
- package/art-workshop.mjs +174 -174
- package/docs/configuration.md +82 -82
- package/docs/core-guidance.md +50 -50
- package/docs/data-formats.md +85 -85
- package/docs/deployment.md +32 -32
- package/docs/local-models/qwen-image-2.1.json +73 -73
- package/docs/local-models/qwen-image-2.1.md +33 -33
- package/docs/model-architecture.md +78 -78
- package/docs/modes.md +67 -67
- package/lib/agent.mjs +32 -32
- package/lib/analysis-worker.mjs +32 -32
- package/lib/analyze.mjs +85 -85
- package/lib/asset-profile.mjs +23 -23
- package/lib/candidates.mjs +103 -103
- package/lib/comfy-recovery.mjs +17 -17
- package/lib/conversation.mjs +77 -77
- package/lib/core.mjs +75 -75
- package/lib/deployment-guide.mjs +12 -12
- package/lib/design.mjs +29 -29
- package/lib/dimensions.mjs +22 -22
- package/lib/edit.mjs +41 -41
- package/lib/environment-operations.mjs +49 -49
- package/lib/environment-runtime.mjs +99 -99
- package/lib/environments.mjs +55 -55
- package/lib/executor.mjs +107 -107
- package/lib/generate.mjs +58 -58
- package/lib/heartbeat.mjs +16 -16
- package/lib/images.mjs +1 -1
- package/lib/lifecycle.mjs +53 -53
- package/lib/migration.mjs +154 -154
- package/lib/process-identity.mjs +22 -14
- package/lib/project.mjs +39 -39
- package/lib/refs.mjs +26 -26
- package/lib/runtime.mjs +25 -25
- package/lib/service.mjs +134 -126
- package/lib/settings.mjs +50 -50
- package/lib/shared.mjs +67 -67
- package/lib/style-bundle.mjs +85 -85
- package/lib/style-contract.mjs +74 -74
- package/lib/style-lifecycle.mjs +125 -125
- package/lib/style-review.mjs +14 -14
- package/lib/task-contract.mjs +93 -93
- package/lib/tasks.mjs +497 -497
- package/lib/templates.mjs +80 -80
- package/lib/vision.mjs +56 -56
- package/lib/worker-process.mjs +6 -6
- package/lib/workspace.mjs +292 -292
- package/package.json +1 -1
- package/rules/core-guidance.json +22 -22
- package/skills/art-workshop/SKILL.md +17 -17
- package/skills/art-workshop/references/conversation.md +11 -11
- package/skills/art-workshop/references/expression.md +27 -27
- package/skills/art-workshop/references/project.md +109 -109
- package/v-cli.plugin.json +2747 -2747
package/lib/service.mjs
CHANGED
|
@@ -1,126 +1,134 @@
|
|
|
1
|
-
import {processIdentity} from './process-identity.mjs';
|
|
2
|
-
export {processIdentity} from './process-identity.mjs';
|
|
3
|
-
import {homedir} from 'node:os';
|
|
4
|
-
import {spawn,execFileSync} from 'node:child_process';
|
|
5
|
-
import {openSync,closeSync,existsSync,readdirSync} from 'node:fs';
|
|
6
|
-
import {createServer} from 'node:net';
|
|
7
|
-
import {join,resolve} from 'node:path';
|
|
8
|
-
import {writeJson,hash} from './shared.mjs';
|
|
9
|
-
import {http,sleep,locked,stateRead,alive} from './runtime.mjs';
|
|
10
|
-
import {inspectEnvironment,workflowError} from './diagnostics.mjs';
|
|
11
|
-
|
|
12
|
-
export async function stopIdentity(identity,{timeout=10000}={}) {
|
|
13
|
-
const current=
|
|
14
|
-
if(
|
|
15
|
-
if(
|
|
16
|
-
if(
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
const
|
|
24
|
-
|
|
25
|
-
if(
|
|
26
|
-
if(
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
if(
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
if(
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
1
|
+
import {processIdentity,inspectProcess} from './process-identity.mjs';
|
|
2
|
+
export {processIdentity} from './process-identity.mjs';
|
|
3
|
+
import {homedir} from 'node:os';
|
|
4
|
+
import {spawn,execFileSync} from 'node:child_process';
|
|
5
|
+
import {openSync,closeSync,existsSync,readdirSync} from 'node:fs';
|
|
6
|
+
import {createServer} from 'node:net';
|
|
7
|
+
import {join,resolve} from 'node:path';
|
|
8
|
+
import {writeJson,hash} from './shared.mjs';
|
|
9
|
+
import {http,sleep,locked,stateRead,alive} from './runtime.mjs';
|
|
10
|
+
import {inspectEnvironment,workflowError} from './diagnostics.mjs';
|
|
11
|
+
|
|
12
|
+
export async function stopIdentity(identity,{timeout=10000,inspect=inspectProcess}={}) {
|
|
13
|
+
const current=inspect(identity.pid);
|
|
14
|
+
if(current.state==='missing')return;
|
|
15
|
+
if(current.state!=='running')throw new Error('服务进程身份未知,无法确认停止');
|
|
16
|
+
if(hash(current.identity)!==hash(identity))throw new Error('服务进程身份已变化,拒绝终止复用的 PID');
|
|
17
|
+
try {
|
|
18
|
+
if(process.platform==='win32')execFileSync('taskkill.exe',['/PID',String(identity.pid),'/T','/F'],{windowsHide:true,timeout,stdio:['ignore','pipe','pipe']});
|
|
19
|
+
else process.kill(identity.pid,'SIGTERM');
|
|
20
|
+
}catch(error){if(inspect(identity.pid).state!=='missing')throw error;return;}
|
|
21
|
+
const deadline=Date.now()+timeout;
|
|
22
|
+
while(true){
|
|
23
|
+
const result=inspect(identity.pid);
|
|
24
|
+
if(result.state==='missing'||result.state==='running'&&hash(result.identity)!==hash(identity))return;
|
|
25
|
+
if(result.state==='unknown')throw new Error('服务进程停止结果未知');
|
|
26
|
+
if(Date.now()>deadline)throw new Error('服务进程未停止');await sleep(100);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
export async function healthy(endpoint,backend) {
|
|
30
|
+
try {
|
|
31
|
+
const stats=await http(endpoint,'/system_stats',{timeout:2000});if(!stats.system?.comfyui_version)return false;
|
|
32
|
+
const [major,minor]=stats.system.comfyui_version.split('.').map(Number);
|
|
33
|
+
if(major===0&&minor<39)return false;
|
|
34
|
+
if(backend.template){const nodes=await http(endpoint,'/object_info',{timeout:4000});for(const n of Object.values(backend.template))if(!nodes[n.class_type])return false;}
|
|
35
|
+
return stats;
|
|
36
|
+
}catch{return false;}
|
|
37
|
+
}
|
|
38
|
+
export const serviceRoot=()=>join(process.env.VANT_HOME??join(homedir(),'.vant'),'state','art-services');
|
|
39
|
+
function serviceFile(root,endpoint){return join(serviceRoot(),'services',hash(endpoint)+'.json');}
|
|
40
|
+
export function externalIdentity(endpoint,launch) {
|
|
41
|
+
if(process.platform!=='win32'||!launch)return null;
|
|
42
|
+
const port=Number(new URL(endpoint).port||80);
|
|
43
|
+
const script=`Get-NetTCPConnection -State Listen -LocalPort ${port} -ErrorAction SilentlyContinue | Select-Object -ExpandProperty OwningProcess -Unique | ConvertTo-Json -Compress`;
|
|
44
|
+
let pids;try{pids=JSON.parse(execFileSync('powershell.exe',['-NoProfile','-NonInteractive','-Command',script],{encoding:'utf8',windowsHide:true}).trim()||'null');}catch{return null;}
|
|
45
|
+
for(const pid of [].concat(pids??[])) {
|
|
46
|
+
const p=processIdentity(pid);
|
|
47
|
+
if(!p?.exe||resolve(p.exe).toLowerCase()!==resolve(launch.executable).toLowerCase())continue;
|
|
48
|
+
// Require the configured entrypoint, not just a Python interpreter or an occupied port.
|
|
49
|
+
const entry=launch.args.find(x=>/main\.py$|\.mjs$|\.js$/.test(x));
|
|
50
|
+
if(!entry||!p.command.toLowerCase().includes(entry.toLowerCase()))continue;
|
|
51
|
+
return p;
|
|
52
|
+
}
|
|
53
|
+
return null;
|
|
54
|
+
}
|
|
55
|
+
export async function ensureService(backend,root,{cancelled=()=>false}={}) {
|
|
56
|
+
root=serviceRoot();
|
|
57
|
+
return locked(root,'services',async()=>{
|
|
58
|
+
if(stateRead(join(root,'shutdown.json')))throw new Error('服务正在 shutdown');
|
|
59
|
+
const incompatible=[];
|
|
60
|
+
for(const endpoint of backend.endpoints) {
|
|
61
|
+
let report;try{report=await inspectEnvironment(endpoint,backend);}catch{continue;}
|
|
62
|
+
if(!report.ok){incompatible.push(report);continue;}
|
|
63
|
+
const file=serviceFile(root,endpoint),previous=stateRead(file);
|
|
64
|
+
const identity=previous?.identity&&hash(processIdentity(previous.identity.pid))===hash(previous.identity)?previous.identity:externalIdentity(endpoint,backend.launch);
|
|
65
|
+
const sameOwner=!!(identity&&previous?.owned&&hash(previous.identity)===hash(identity));
|
|
66
|
+
writeJson(file,{endpoint,backend:backend.id,identity,owned:sameOwner,...(sameOwner&&previous.owner?{owner:previous.owner}:{}),observedAt:new Date().toISOString()});
|
|
67
|
+
return endpoint;
|
|
68
|
+
}
|
|
69
|
+
if(incompatible.length){const error=workflowError('现有 ComfyUI 环境无法执行工作流',backend,{stage:'environment'});error.diagnostic.environments=incompatible;throw error;}
|
|
70
|
+
if(!backend.launch)throw new Error('没有可用 ComfyUI,也未配置 launch');
|
|
71
|
+
if(cancelled())throw new Error('任务已取消');
|
|
72
|
+
const endpoint=backend.endpoints[0],file=serviceFile(root,endpoint),previous=stateRead(file);
|
|
73
|
+
if(previous?.identity&&hash(processIdentity(previous.identity.pid))===hash(previous.identity))throw new Error('现有服务不健康,请先 shutdown;不重复启动');
|
|
74
|
+
const logPath=join(root,'comfyui-'+hash(endpoint).slice(0,8)+'.log'),fd=openSync(logPath,'a');
|
|
75
|
+
const child=spawn(backend.launch.executable,backend.launch.args,{cwd:backend.launch.cwd,detached:true,windowsHide:true,stdio:['ignore',fd,fd]});closeSync(fd);
|
|
76
|
+
let spawnError;child.once('error',error=>{spawnError=error;});child.unref();
|
|
77
|
+
await sleep(100);
|
|
78
|
+
if(spawnError||!child.pid)throw spawnError??new Error('服务启动失败');
|
|
79
|
+
const identity=processIdentity(child.pid);if(!identity)throw new Error('无法记录服务进程身份');
|
|
80
|
+
writeJson(file,{endpoint,backend:backend.id,identity,owned:true,...(process.env.VANT_SERVICE_INSTANCE?{owner:{application:'vant',instanceId:process.env.VANT_SERVICE_INSTANCE}}:{}),logPath});
|
|
81
|
+
const deadline=Date.now()+(backend.launch.startupTimeoutSeconds??120)*1000;
|
|
82
|
+
try {
|
|
83
|
+
while(Date.now()<deadline){if(cancelled())throw new Error('任务已取消');let report;try{report=await inspectEnvironment(endpoint,backend);}catch{};if(report?.ok)return endpoint;if(report){const error=workflowError('启动后的 ComfyUI 环境无法执行工作流,查看 '+logPath,backend,{stage:'environment'});error.diagnostic.environments=[report];throw error;}if(!alive(child.pid))throw new Error('ComfyUI 进程提前退出,查看 '+logPath);await sleep(300);}
|
|
84
|
+
throw new Error('ComfyUI 启动超时,查看 '+logPath);
|
|
85
|
+
}catch(error){await stopIdentity(identity);throw error;}
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
export function rememberedService(root,endpoint){return stateRead(serviceFile(root,endpoint));}
|
|
89
|
+
// Application exit never adopts an external process as a termination target.
|
|
90
|
+
export async function shutdownOwnedServices() {
|
|
91
|
+
return locked(serviceRoot(),'control',async()=>{
|
|
92
|
+
const folder=join(serviceRoot(),'services'),results=[],failures=[];
|
|
93
|
+
for(const name of existsSync(folder)?readdirSync(folder):[]) {
|
|
94
|
+
if(!name.endsWith('.json'))continue;
|
|
95
|
+
const file=join(folder,name),record=stateRead(file);
|
|
96
|
+
if(record?.owned!==true||record.owner?.application!=='vant'||record.stopped)continue;
|
|
97
|
+
try {
|
|
98
|
+
if(!record.identity)throw new Error('缺少服务进程身份,不能确认停止');
|
|
99
|
+
const url=new URL(record.endpoint);
|
|
100
|
+
if(url.protocol!=='http:'||!['127.0.0.1','localhost'].includes(url.hostname)||url.pathname!=='/'||url.search||url.hash||url.username||url.password)throw new Error('服务地址不是本机回环地址');
|
|
101
|
+
if(name!==hash(record.endpoint)+'.json')throw new Error('服务记录身份不匹配');
|
|
102
|
+
await stopIdentity(record.identity);
|
|
103
|
+
const deadline=Date.now()+15000;
|
|
104
|
+
while(true){
|
|
105
|
+
try {
|
|
106
|
+
await new Promise((resolve,reject)=>{
|
|
107
|
+
const probe=createServer();probe.once('error',reject);
|
|
108
|
+
probe.listen({host:'127.0.0.1',port:Number(url.port||80),exclusive:true},()=>probe.close(error=>error?reject(error):resolve()));
|
|
109
|
+
});
|
|
110
|
+
break;
|
|
111
|
+
}catch(error){if(error.code!=='EADDRINUSE'||Date.now()>deadline)throw error;await sleep(200);}
|
|
112
|
+
}
|
|
113
|
+
writeJson(file,{...record,owned:false,stopped:true,stoppedAt:new Date().toISOString()});
|
|
114
|
+
results.push({endpoint:record.endpoint,stopped:true,portReleased:true});
|
|
115
|
+
}catch(error){failures.push(record.endpoint+': '+error.message);}
|
|
116
|
+
}
|
|
117
|
+
if(failures.length)throw new Error('本机服务清理未确认:'+failures.join('; '));
|
|
118
|
+
return results;
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
export async function closeService(root,endpoint,backend) {
|
|
122
|
+
return locked(serviceRoot(),'queue-'+new URL(endpoint).port,()=>closeSharedService(serviceRoot(),endpoint,backend));
|
|
123
|
+
}
|
|
124
|
+
async function closeSharedService(root,endpoint,backend) {
|
|
125
|
+
if(await healthy(endpoint,backend)){const queue=await http(endpoint,'/queue');if((queue.queue_running??[]).length||(queue.queue_pending??[]).length)throw new Error('共享服务仍有其他任务,保留服务');}
|
|
126
|
+
const remembered=rememberedService(root,endpoint);
|
|
127
|
+
const previous=remembered?.identity;
|
|
128
|
+
const identity=previous&&hash(processIdentity(previous.pid))===hash(previous)?previous:externalIdentity(endpoint,backend.launch);
|
|
129
|
+
if(!identity){if(await healthy(endpoint,backend))throw new Error('无法验证服务进程身份:'+endpoint);return {endpoint,stopped:false};}
|
|
130
|
+
await stopIdentity(identity);
|
|
131
|
+
if(await healthy(endpoint,backend))throw new Error('关闭进程后服务仍可访问:'+endpoint);
|
|
132
|
+
writeJson(serviceFile(root,endpoint),{endpoint,stopped:true,stoppedAt:new Date().toISOString()});
|
|
133
|
+
return {endpoint,stopped:true};
|
|
134
|
+
}
|
package/lib/settings.mjs
CHANGED
|
@@ -1,50 +1,50 @@
|
|
|
1
|
-
import {existsSync,readFileSync,realpathSync} from 'node:fs';
|
|
2
|
-
import {execFileSync} from 'node:child_process';
|
|
3
|
-
import {homedir} from 'node:os';
|
|
4
|
-
import {dirname,basename,join,resolve,relative,isAbsolute} from 'node:path';
|
|
5
|
-
import {fileURLToPath} from 'node:url';
|
|
6
|
-
import {readJson,writeJson,keys,text,id} from './shared.mjs';
|
|
7
|
-
import {execution} from './plan.mjs';
|
|
8
|
-
import {generationConfig} from './backends.mjs';
|
|
9
|
-
export const TOOL_ROOT=dirname(dirname(fileURLToPath(import.meta.url)));
|
|
10
|
-
export function downloadsDirectory({platform=process.platform,home=homedir(),env=process.env,knownFolder}={}) {
|
|
11
|
-
if(platform==='win32') {
|
|
12
|
-
try {
|
|
13
|
-
const read=knownFolder??(()=>JSON.parse(execFileSync('powershell.exe',['-NoProfile','-NonInteractive','-Command',"[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new(); $downloadPath = (Get-ItemProperty -LiteralPath 'HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders').'{374DE290-123F-4565-9164-39C4925E467B}'; $downloadPath | ConvertTo-Json -Compress"],{encoding:'utf8',windowsHide:true}).trim()));
|
|
14
|
-
const value=read();if(typeof value==='string'&&value.trim()){const expanded=value.replace(/%([^%]+)%/g,(_,name)=>Object.entries(env).find(([key])=>key.toLowerCase()===name.toLowerCase())?.[1]??'%'+name+'%');if(!expanded.includes('%'))return expanded;}
|
|
15
|
-
}catch{}
|
|
16
|
-
}
|
|
17
|
-
if(platform==='linux') {
|
|
18
|
-
const file=join(env.XDG_CONFIG_HOME??join(home,'.config'),'user-dirs.dirs');
|
|
19
|
-
if(existsSync(file)){const match=readFileSync(file,'utf8').match(/^XDG_DOWNLOAD_DIR="([^"]+)"/m);if(match){const value=match[1].replace(/\$\{HOME\}|\$HOME/g,home);if(!value.includes('$')&&isAbsolute(value))return resolve(value);}}
|
|
20
|
-
}
|
|
21
|
-
return join(home,'Downloads');
|
|
22
|
-
}
|
|
23
|
-
export function externalPath(value,label='路径') {
|
|
24
|
-
text(value,label,2048);const path=resolve(value);
|
|
25
|
-
let ancestor=path;const tail=[];while(!existsSync(ancestor)){const parent=dirname(ancestor);if(parent===ancestor)break;tail.unshift(basename(ancestor));ancestor=parent;}
|
|
26
|
-
const actual=existsSync(ancestor)?join(realpathSync(ancestor),...tail):path;
|
|
27
|
-
const rel=relative(realpathSync(TOOL_ROOT),actual);
|
|
28
|
-
if(rel===''||!isAbsolute(rel)&&rel!=='..'&&!rel.startsWith('..\\')&&!rel.startsWith('../'))throw new Error(`${label} 必须在工具目录之外:${path}`);
|
|
29
|
-
return path;
|
|
30
|
-
}
|
|
31
|
-
export function configFile(env=process.env,home=homedir(),platform=process.platform) {
|
|
32
|
-
return externalPath(env.ART_WORKSHOP_CONFIG??join(env.VANT_HOME??join(home,'.vant'),'tools','art-workshop','config.json'),'本地配置');
|
|
33
|
-
}
|
|
34
|
-
export function loadSettings({file=configFile(),workspace,output,refs,cache}={}) {
|
|
35
|
-
const base=join(process.env.VANT_HOME??join(homedir(),'.vant'),'tools','art-workshop','workspace');
|
|
36
|
-
const local=existsSync(file)?readJson(file):{};
|
|
37
|
-
keys(local,['paths','execution','generation','analysisModel','defaultProject','autoSyncSkills'],'config');
|
|
38
|
-
keys(local.paths??{},['workspace','output','refs','cache'],'config.paths');
|
|
39
|
-
execution({execution:{}},{},local.execution??{});
|
|
40
|
-
if(local.analysisModel!==undefined&&local.analysisModel!==null)text(local.analysisModel,'analysisModel');
|
|
41
|
-
if(local.defaultProject!==undefined&&local.defaultProject!==null)id(local.defaultProject,'defaultProject');
|
|
42
|
-
if(local.autoSyncSkills!==undefined&&typeof local.autoSyncSkills!=='boolean')throw new Error('autoSyncSkills 必须为布尔值');
|
|
43
|
-
const overrides={workspace,output,refs,cache},defaults={workspace:base,output:base,refs:join(base,'refs'),cache:join(base,'.cache')};
|
|
44
|
-
const paths=Object.fromEntries(Object.keys(defaults).map(key=>[key,externalPath(overrides[key]??local.paths?.[key]??defaults[key],key)]));
|
|
45
|
-
return {file:externalPath(file,'本地配置'),paths,execution:local.execution??{},generation:generationConfig(local.generation??{}),analysisModel:local.analysisModel??null,defaultProject:local.defaultProject??null};
|
|
46
|
-
}
|
|
47
|
-
export function initSettings(file=configFile()) {
|
|
48
|
-
externalPath(file,'本地配置');if(existsSync(file))return loadSettings({file});
|
|
49
|
-
const {file:ignored,...config}=loadSettings({file});writeJson(file,config);return loadSettings({file});
|
|
50
|
-
}
|
|
1
|
+
import {existsSync,readFileSync,realpathSync} from 'node:fs';
|
|
2
|
+
import {execFileSync} from 'node:child_process';
|
|
3
|
+
import {homedir} from 'node:os';
|
|
4
|
+
import {dirname,basename,join,resolve,relative,isAbsolute} from 'node:path';
|
|
5
|
+
import {fileURLToPath} from 'node:url';
|
|
6
|
+
import {readJson,writeJson,keys,text,id} from './shared.mjs';
|
|
7
|
+
import {execution} from './plan.mjs';
|
|
8
|
+
import {generationConfig} from './backends.mjs';
|
|
9
|
+
export const TOOL_ROOT=dirname(dirname(fileURLToPath(import.meta.url)));
|
|
10
|
+
export function downloadsDirectory({platform=process.platform,home=homedir(),env=process.env,knownFolder}={}) {
|
|
11
|
+
if(platform==='win32') {
|
|
12
|
+
try {
|
|
13
|
+
const read=knownFolder??(()=>JSON.parse(execFileSync('powershell.exe',['-NoProfile','-NonInteractive','-Command',"[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new(); $downloadPath = (Get-ItemProperty -LiteralPath 'HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders').'{374DE290-123F-4565-9164-39C4925E467B}'; $downloadPath | ConvertTo-Json -Compress"],{encoding:'utf8',windowsHide:true}).trim()));
|
|
14
|
+
const value=read();if(typeof value==='string'&&value.trim()){const expanded=value.replace(/%([^%]+)%/g,(_,name)=>Object.entries(env).find(([key])=>key.toLowerCase()===name.toLowerCase())?.[1]??'%'+name+'%');if(!expanded.includes('%'))return expanded;}
|
|
15
|
+
}catch{}
|
|
16
|
+
}
|
|
17
|
+
if(platform==='linux') {
|
|
18
|
+
const file=join(env.XDG_CONFIG_HOME??join(home,'.config'),'user-dirs.dirs');
|
|
19
|
+
if(existsSync(file)){const match=readFileSync(file,'utf8').match(/^XDG_DOWNLOAD_DIR="([^"]+)"/m);if(match){const value=match[1].replace(/\$\{HOME\}|\$HOME/g,home);if(!value.includes('$')&&isAbsolute(value))return resolve(value);}}
|
|
20
|
+
}
|
|
21
|
+
return join(home,'Downloads');
|
|
22
|
+
}
|
|
23
|
+
export function externalPath(value,label='路径') {
|
|
24
|
+
text(value,label,2048);const path=resolve(value);
|
|
25
|
+
let ancestor=path;const tail=[];while(!existsSync(ancestor)){const parent=dirname(ancestor);if(parent===ancestor)break;tail.unshift(basename(ancestor));ancestor=parent;}
|
|
26
|
+
const actual=existsSync(ancestor)?join(realpathSync(ancestor),...tail):path;
|
|
27
|
+
const rel=relative(realpathSync(TOOL_ROOT),actual);
|
|
28
|
+
if(rel===''||!isAbsolute(rel)&&rel!=='..'&&!rel.startsWith('..\\')&&!rel.startsWith('../'))throw new Error(`${label} 必须在工具目录之外:${path}`);
|
|
29
|
+
return path;
|
|
30
|
+
}
|
|
31
|
+
export function configFile(env=process.env,home=homedir(),platform=process.platform) {
|
|
32
|
+
return externalPath(env.ART_WORKSHOP_CONFIG??join(env.VANT_HOME??join(home,'.vant'),'tools','art-workshop','config.json'),'本地配置');
|
|
33
|
+
}
|
|
34
|
+
export function loadSettings({file=configFile(),workspace,output,refs,cache}={}) {
|
|
35
|
+
const base=join(process.env.VANT_HOME??join(homedir(),'.vant'),'tools','art-workshop','workspace');
|
|
36
|
+
const local=existsSync(file)?readJson(file):{};
|
|
37
|
+
keys(local,['paths','execution','generation','analysisModel','defaultProject','autoSyncSkills'],'config');
|
|
38
|
+
keys(local.paths??{},['workspace','output','refs','cache'],'config.paths');
|
|
39
|
+
execution({execution:{}},{},local.execution??{});
|
|
40
|
+
if(local.analysisModel!==undefined&&local.analysisModel!==null)text(local.analysisModel,'analysisModel');
|
|
41
|
+
if(local.defaultProject!==undefined&&local.defaultProject!==null)id(local.defaultProject,'defaultProject');
|
|
42
|
+
if(local.autoSyncSkills!==undefined&&typeof local.autoSyncSkills!=='boolean')throw new Error('autoSyncSkills 必须为布尔值');
|
|
43
|
+
const overrides={workspace,output,refs,cache},defaults={workspace:base,output:base,refs:join(base,'refs'),cache:join(base,'.cache')};
|
|
44
|
+
const paths=Object.fromEntries(Object.keys(defaults).map(key=>[key,externalPath(overrides[key]??local.paths?.[key]??defaults[key],key)]));
|
|
45
|
+
return {file:externalPath(file,'本地配置'),paths,execution:local.execution??{},generation:generationConfig(local.generation??{}),analysisModel:local.analysisModel??null,defaultProject:local.defaultProject??null};
|
|
46
|
+
}
|
|
47
|
+
export function initSettings(file=configFile()) {
|
|
48
|
+
externalPath(file,'本地配置');if(existsSync(file))return loadSettings({file});
|
|
49
|
+
const {file:ignored,...config}=loadSettings({file});writeJson(file,config);return loadSettings({file});
|
|
50
|
+
}
|
package/lib/shared.mjs
CHANGED
|
@@ -1,67 +1,67 @@
|
|
|
1
|
-
import {ContractError} from './errors.mjs';
|
|
2
|
-
import { createHash, randomUUID } from 'node:crypto';
|
|
3
|
-
import { readFileSync, writeFileSync, mkdirSync, renameSync, rmSync } from 'node:fs';
|
|
4
|
-
import { dirname } from 'node:path';
|
|
5
|
-
|
|
6
|
-
export function hash(value) {
|
|
7
|
-
const ordered = v => Array.isArray(v) ? v.map(ordered) : v && typeof v === 'object'
|
|
8
|
-
? Object.fromEntries(Object.keys(v).sort().map(k => [k, ordered(v[k])])) : v;
|
|
9
|
-
return createHash('sha256').update(JSON.stringify(ordered(value))).digest('hex');
|
|
10
|
-
}
|
|
11
|
-
export function readJson(path) {
|
|
12
|
-
try { return JSON.parse(readFileSync(path, 'utf8')); }
|
|
13
|
-
catch (e) { throw new Error(`读取 ${path} 失败:${e.message}`); }
|
|
14
|
-
}
|
|
15
|
-
export function renameWithRetry(source,target) {
|
|
16
|
-
for(let attempt=0;;attempt++) {
|
|
17
|
-
try {renameSync(source,target);return;}
|
|
18
|
-
catch(error) {
|
|
19
|
-
if(process.platform!=='win32'||!['EPERM','EACCES','EBUSY'].includes(error.code)||attempt>=50)throw error;
|
|
20
|
-
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,20);
|
|
21
|
-
}
|
|
22
|
-
}
|
|
23
|
-
}
|
|
24
|
-
export function writeJson(path, data) {
|
|
25
|
-
mkdirSync(dirname(path), { recursive: true });
|
|
26
|
-
const temporary = path + '.tmp-' + randomUUID();
|
|
27
|
-
writeFileSync(temporary, JSON.stringify(data, null, 2) + '\n', 'utf8');
|
|
28
|
-
// Windows readers and antivirus can temporarily deny replacement of a state file.
|
|
29
|
-
// Keep the previous complete document until rename succeeds; never truncate it.
|
|
30
|
-
try {
|
|
31
|
-
renameWithRetry(temporary,path);
|
|
32
|
-
} finally {try{rmSync(temporary,{force:true});}catch{}}
|
|
33
|
-
}
|
|
34
|
-
export function keys(value, allowed, label) {
|
|
35
|
-
if (!value || typeof value !== 'object' || Array.isArray(value)) throw new ContractError(`${label} 必须为对象`);
|
|
36
|
-
for (const key of Object.keys(value)) if (!allowed.includes(key)) throw new ContractError(`${label} 不支持字段 ${key}`);
|
|
37
|
-
}
|
|
38
|
-
export function text(value, label, max = 160) {
|
|
39
|
-
if (typeof value !== 'string' || !value.trim() || value.length > max) throw new ContractError(Number.isFinite(max) ? `${label} 必须是 1~${max} 字的精炼文本` : `${label} 必须是非空文本`);
|
|
40
|
-
if (/\bTODO\b|<[^>]+>|待填写/.test(value)) throw new ContractError(`${label} 有未完成的占位符`);
|
|
41
|
-
return value;
|
|
42
|
-
}
|
|
43
|
-
export function id(value, label = 'id') {
|
|
44
|
-
if (typeof value !== 'string' || !/^[a-z0-9][a-z0-9-]{0,63}$/.test(value)
|
|
45
|
-
|| /^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/.test(value)) throw new ContractError(`${label} 必须使用小写字母、数字、连字符`);
|
|
46
|
-
return value;
|
|
47
|
-
}
|
|
48
|
-
export function integer(value, label, min = 0, max = 2147483647) {
|
|
49
|
-
if (!Number.isSafeInteger(value) || value < min || value > max) throw new ContractError(`${label} 必须为 ${min}~${max} 的整数`);
|
|
50
|
-
return value;
|
|
51
|
-
}
|
|
52
|
-
export function choice(value, values, label) {
|
|
53
|
-
if (!values.includes(value)) throw new ContractError(`${label} 必须为 ${values.join('/')}`);
|
|
54
|
-
return value;
|
|
55
|
-
}
|
|
56
|
-
export function texts(value, label, { empty = false, max = 160 } = {}) {
|
|
57
|
-
if (!Array.isArray(value) || (!empty && !value.length)) throw new ContractError(`${label} 必须为${empty ? '' : '非空'}数组`);
|
|
58
|
-
value.forEach(x => text(x, label, max)); return value;
|
|
59
|
-
}
|
|
60
|
-
export function hex(value, label) {
|
|
61
|
-
if (typeof value !== 'string' || !/^#[0-9a-f]{6}$/i.test(value)) throw new ContractError(`${label} 必须为 #RRGGBB`);
|
|
62
|
-
return value.toUpperCase();
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
/** User-authored art requirements are not limited by character count. */
|
|
66
|
-
export const description = (value, label) => text(value, label, Infinity);
|
|
67
|
-
export const descriptions = (value, label) => texts(value, label, {max: Infinity});
|
|
1
|
+
import {ContractError} from './errors.mjs';
|
|
2
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
3
|
+
import { readFileSync, writeFileSync, mkdirSync, renameSync, rmSync } from 'node:fs';
|
|
4
|
+
import { dirname } from 'node:path';
|
|
5
|
+
|
|
6
|
+
export function hash(value) {
|
|
7
|
+
const ordered = v => Array.isArray(v) ? v.map(ordered) : v && typeof v === 'object'
|
|
8
|
+
? Object.fromEntries(Object.keys(v).sort().map(k => [k, ordered(v[k])])) : v;
|
|
9
|
+
return createHash('sha256').update(JSON.stringify(ordered(value))).digest('hex');
|
|
10
|
+
}
|
|
11
|
+
export function readJson(path) {
|
|
12
|
+
try { return JSON.parse(readFileSync(path, 'utf8')); }
|
|
13
|
+
catch (e) { throw new Error(`读取 ${path} 失败:${e.message}`); }
|
|
14
|
+
}
|
|
15
|
+
export function renameWithRetry(source,target) {
|
|
16
|
+
for(let attempt=0;;attempt++) {
|
|
17
|
+
try {renameSync(source,target);return;}
|
|
18
|
+
catch(error) {
|
|
19
|
+
if(process.platform!=='win32'||!['EPERM','EACCES','EBUSY'].includes(error.code)||attempt>=50)throw error;
|
|
20
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,20);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
export function writeJson(path, data) {
|
|
25
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
26
|
+
const temporary = path + '.tmp-' + randomUUID();
|
|
27
|
+
writeFileSync(temporary, JSON.stringify(data, null, 2) + '\n', 'utf8');
|
|
28
|
+
// Windows readers and antivirus can temporarily deny replacement of a state file.
|
|
29
|
+
// Keep the previous complete document until rename succeeds; never truncate it.
|
|
30
|
+
try {
|
|
31
|
+
renameWithRetry(temporary,path);
|
|
32
|
+
} finally {try{rmSync(temporary,{force:true});}catch{}}
|
|
33
|
+
}
|
|
34
|
+
export function keys(value, allowed, label) {
|
|
35
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) throw new ContractError(`${label} 必须为对象`);
|
|
36
|
+
for (const key of Object.keys(value)) if (!allowed.includes(key)) throw new ContractError(`${label} 不支持字段 ${key}`);
|
|
37
|
+
}
|
|
38
|
+
export function text(value, label, max = 160) {
|
|
39
|
+
if (typeof value !== 'string' || !value.trim() || value.length > max) throw new ContractError(Number.isFinite(max) ? `${label} 必须是 1~${max} 字的精炼文本` : `${label} 必须是非空文本`);
|
|
40
|
+
if (/\bTODO\b|<[^>]+>|待填写/.test(value)) throw new ContractError(`${label} 有未完成的占位符`);
|
|
41
|
+
return value;
|
|
42
|
+
}
|
|
43
|
+
export function id(value, label = 'id') {
|
|
44
|
+
if (typeof value !== 'string' || !/^[a-z0-9][a-z0-9-]{0,63}$/.test(value)
|
|
45
|
+
|| /^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/.test(value)) throw new ContractError(`${label} 必须使用小写字母、数字、连字符`);
|
|
46
|
+
return value;
|
|
47
|
+
}
|
|
48
|
+
export function integer(value, label, min = 0, max = 2147483647) {
|
|
49
|
+
if (!Number.isSafeInteger(value) || value < min || value > max) throw new ContractError(`${label} 必须为 ${min}~${max} 的整数`);
|
|
50
|
+
return value;
|
|
51
|
+
}
|
|
52
|
+
export function choice(value, values, label) {
|
|
53
|
+
if (!values.includes(value)) throw new ContractError(`${label} 必须为 ${values.join('/')}`);
|
|
54
|
+
return value;
|
|
55
|
+
}
|
|
56
|
+
export function texts(value, label, { empty = false, max = 160 } = {}) {
|
|
57
|
+
if (!Array.isArray(value) || (!empty && !value.length)) throw new ContractError(`${label} 必须为${empty ? '' : '非空'}数组`);
|
|
58
|
+
value.forEach(x => text(x, label, max)); return value;
|
|
59
|
+
}
|
|
60
|
+
export function hex(value, label) {
|
|
61
|
+
if (typeof value !== 'string' || !/^#[0-9a-f]{6}$/i.test(value)) throw new ContractError(`${label} 必须为 #RRGGBB`);
|
|
62
|
+
return value.toUpperCase();
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** User-authored art requirements are not limited by character count. */
|
|
66
|
+
export const description = (value, label) => text(value, label, Infinity);
|
|
67
|
+
export const descriptions = (value, label) => texts(value, label, {max: Infinity});
|