@auto-mas/auto-mas-plugin-maafw-projects 0.0.0-stage → 0.2.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/dist/LICENSE +661 -0
- package/dist/index.js +1 -0
- package/dist/server/builtin-plugins/maafw-projects.js +60 -0
- package/dist/server/download.js +15 -0
- package/dist/server/emulator-managers.js +219 -0
- package/dist/server/execution.js +364 -0
- package/dist/server/features.js +31 -0
- package/dist/server/maa/agent-environment.js +130 -0
- package/dist/server/maa/index.js +97 -0
- package/dist/server/maa/managed-project-path.js +34 -0
- package/dist/server/maa/managed-projects.js +133 -0
- package/dist/server/maa/native-runtime.js +80 -0
- package/dist/server/maa/native-worker-source.js +198 -0
- package/dist/server/maa/node-agent-environment.js +133 -0
- package/dist/server/maa/node-agent-path.js +55 -0
- package/dist/server/maa/process.js +34 -0
- package/dist/server/maa/project.js +502 -0
- package/dist/server/maa/release-projects.js +213 -0
- package/dist/server/maa/worker.js +361 -0
- package/dist/server/run-lifecycle.js +1 -0
- package/dist/server/schema.js +353 -0
- package/dist/server/storage.js +76 -0
- package/dist/server/ui.js +171 -0
- package/dist/server/updates.js +183 -0
- package/package.json +36 -6
- package/README.md +0 -3
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
// Runs with the project's chosen Python binding and native libraries, in a separate process.
|
|
2
|
+
export const nativeWorkerSource = String.raw `
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import re
|
|
6
|
+
import subprocess
|
|
7
|
+
import sys
|
|
8
|
+
from importlib.metadata import version
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def say(message):
|
|
13
|
+
print(message, flush=True)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def require(job, label):
|
|
17
|
+
if not job.wait().succeeded:
|
|
18
|
+
raise RuntimeError(label)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def executable(command, directory, agent_python=None):
|
|
22
|
+
if agent_python and re.fullmatch(r'python3?(?:\.exe)?', command, re.IGNORECASE):
|
|
23
|
+
return agent_python
|
|
24
|
+
expanded = command.replace('{PROJECT_DIR}', directory)
|
|
25
|
+
candidate = Path(directory, expanded)
|
|
26
|
+
if Path(expanded).is_absolute() or '/' in expanded or '\\' in expanded or candidate.is_file():
|
|
27
|
+
return str(candidate)
|
|
28
|
+
if sys.platform == 'win32' and Path(str(candidate) + '.exe').is_file():
|
|
29
|
+
return str(candidate) + '.exe'
|
|
30
|
+
return expanded
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def launch(command, args, directory, env, agent_python):
|
|
34
|
+
program = executable(command['executable'], directory, agent_python)
|
|
35
|
+
return subprocess.Popen([program, *args], cwd=directory, env=env, stdin=subprocess.DEVNULL)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def methods(enum, value, default):
|
|
39
|
+
names = value if isinstance(value, list) else value.split('|') if isinstance(value, str) else [default]
|
|
40
|
+
result = 0
|
|
41
|
+
for name in names:
|
|
42
|
+
result |= int(enum[name.strip()])
|
|
43
|
+
return result
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def make_controller(job):
|
|
47
|
+
from maa.controller import AdbController, Win32Controller
|
|
48
|
+
from maa.define import MaaWin32ScreencapMethodEnum, MaaWin32InputMethodEnum
|
|
49
|
+
from maa.toolkit import Toolkit
|
|
50
|
+
|
|
51
|
+
definition = job['controller']
|
|
52
|
+
selection = job['input']
|
|
53
|
+
if definition['type'] == 'Adb':
|
|
54
|
+
adb = selection.get('adbPath')
|
|
55
|
+
address = selection.get('address')
|
|
56
|
+
if adb:
|
|
57
|
+
adb = executable(adb, job['directory'])
|
|
58
|
+
devices = [item for item in Toolkit.find_adb_devices(adb) if not address or item.address == address]
|
|
59
|
+
if len(devices) > 1:
|
|
60
|
+
raise RuntimeError('发现多个 ADB 设备,请选择设备地址')
|
|
61
|
+
if devices:
|
|
62
|
+
device = devices[0]
|
|
63
|
+
return AdbController(device.adb_path, device.address, device.screencap_methods, device.input_methods, device.config)
|
|
64
|
+
if adb and address:
|
|
65
|
+
return AdbController(adb, address)
|
|
66
|
+
raise RuntimeError('原生运行器未发现所选 ADB 设备')
|
|
67
|
+
|
|
68
|
+
if definition['type'] != 'Win32' or sys.platform != 'win32':
|
|
69
|
+
raise RuntimeError('原生运行器仅支持 ADB 和 Windows Win32 控制器')
|
|
70
|
+
config = definition.get('win32') or {}
|
|
71
|
+
handle = selection.get('windowHandle')
|
|
72
|
+
if handle is None:
|
|
73
|
+
class_filter = config.get('class_regex')
|
|
74
|
+
window_filter = config.get('window_regex')
|
|
75
|
+
if not class_filter and not window_filter:
|
|
76
|
+
raise RuntimeError('请选择 Win32 窗口或声明窗口过滤条件')
|
|
77
|
+
windows = [item for item in Toolkit.find_desktop_windows()
|
|
78
|
+
if (not class_filter or re.search(class_filter, item.class_name))
|
|
79
|
+
and (not window_filter or re.search(window_filter, item.window_name))]
|
|
80
|
+
if len(windows) != 1:
|
|
81
|
+
raise RuntimeError('Win32 窗口匹配数为 ' + str(len(windows)) + ',请选择唯一窗口')
|
|
82
|
+
handle = windows[0].hwnd
|
|
83
|
+
elif not isinstance(handle, int) or handle <= 0:
|
|
84
|
+
raise RuntimeError('Win32 窗口句柄必须是正整数')
|
|
85
|
+
|
|
86
|
+
return Win32Controller(handle,
|
|
87
|
+
methods(MaaWin32ScreencapMethodEnum, config.get('screencap'), 'Background'),
|
|
88
|
+
methods(MaaWin32InputMethodEnum, config.get('mouse'), 'PostMessage'),
|
|
89
|
+
methods(MaaWin32InputMethodEnum, config.get('keyboard'), 'PostMessage'))
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def configure_display(controller, definition):
|
|
93
|
+
if definition.get('display_raw') is True:
|
|
94
|
+
controller.set_screenshot_use_raw_size(True)
|
|
95
|
+
elif isinstance(definition.get('display_expand'), list) and len(definition['display_expand']) == 2:
|
|
96
|
+
controller.set_screenshot_target_expand(*definition['display_expand'])
|
|
97
|
+
elif isinstance(definition.get('display_long_side'), int):
|
|
98
|
+
controller.set_screenshot_target_long_side(definition['display_long_side'])
|
|
99
|
+
else:
|
|
100
|
+
controller.set_screenshot_target_short_side(definition.get('display_short_side') or 720)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def run(job, framework_version):
|
|
104
|
+
from maa.agent_client import AgentClient
|
|
105
|
+
from maa.resource import Resource
|
|
106
|
+
from maa.tasker import Tasker
|
|
107
|
+
|
|
108
|
+
directory = job['directory']
|
|
109
|
+
agent_python = job['input'].get('agentPython')
|
|
110
|
+
env = dict(os.environ, **job['agentEnvironment'], PI_CLIENT_MAAFW_VERSION=framework_version)
|
|
111
|
+
# Agent executables own their libraries. Apply the override only to this worker.
|
|
112
|
+
env.pop('MAAFW_BINARY_PATH', None)
|
|
113
|
+
for index, pretask in enumerate(job['pretasks'], 1):
|
|
114
|
+
say(f'执行前置任务 {index}')
|
|
115
|
+
cwd = pretask.get('directory', directory)
|
|
116
|
+
args = [arg.replace('{PROJECT_DIR}', cwd) for arg in pretask['args']]
|
|
117
|
+
if pretask.get('optionArgument'):
|
|
118
|
+
args.append(pretask['optionArgument'])
|
|
119
|
+
if launch(pretask, args, cwd, env, agent_python).wait() != 0:
|
|
120
|
+
raise RuntimeError(f'前置任务 {index} 执行失败')
|
|
121
|
+
|
|
122
|
+
resource = Resource()
|
|
123
|
+
for path in [*job['resourcePaths'], *job['attachedPaths']]:
|
|
124
|
+
require(resource.post_bundle(path), '原生运行器无法加载资源:' + path)
|
|
125
|
+
controller = make_controller(job)
|
|
126
|
+
configure_display(controller, job['controller'])
|
|
127
|
+
require(controller.post_connection(), '原生运行器无法连接控制目标')
|
|
128
|
+
tasker = Tasker()
|
|
129
|
+
if not tasker.bind(resource, controller):
|
|
130
|
+
raise RuntimeError('原生运行器无法绑定资源及控制器')
|
|
131
|
+
agents = []
|
|
132
|
+
try:
|
|
133
|
+
for index, agent in enumerate(job['agents'], 1):
|
|
134
|
+
say(f'启动 Agent {index}')
|
|
135
|
+
client = AgentClient(agent.get('identifier'))
|
|
136
|
+
if not client.identifier or not client.bind(resource) or not client.register_sink(resource, controller, tasker):
|
|
137
|
+
raise RuntimeError(f'Agent {index} 无法绑定 MaaFramework')
|
|
138
|
+
client.set_timeout(15_000)
|
|
139
|
+
cwd = agent.get('directory', directory)
|
|
140
|
+
args = [arg.replace('{PROJECT_DIR}', cwd) for arg in agent['args']] + [client.identifier]
|
|
141
|
+
process = launch(agent, args, cwd, env, agent_python)
|
|
142
|
+
agents.append((client, process))
|
|
143
|
+
if not client.connect():
|
|
144
|
+
raise RuntimeError(f'Agent {index} 无法连接')
|
|
145
|
+
for task in job['tasks']:
|
|
146
|
+
say('开始任务 ' + task['name'])
|
|
147
|
+
require(tasker.post_task(task['entry'], task['override']), '任务执行失败:' + task['name'])
|
|
148
|
+
if any(process.poll() is not None for _, process in agents):
|
|
149
|
+
raise RuntimeError('Agent 提前退出')
|
|
150
|
+
say('完成任务 ' + task['name'])
|
|
151
|
+
finally:
|
|
152
|
+
for client, process in reversed(agents):
|
|
153
|
+
try:
|
|
154
|
+
if client.connected:
|
|
155
|
+
client.disconnect()
|
|
156
|
+
finally:
|
|
157
|
+
if process.poll() is None:
|
|
158
|
+
process.terminate()
|
|
159
|
+
try:
|
|
160
|
+
process.wait(timeout=2)
|
|
161
|
+
except subprocess.TimeoutExpired:
|
|
162
|
+
process.kill()
|
|
163
|
+
process.wait()
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def main():
|
|
167
|
+
if len(sys.argv) > 1:
|
|
168
|
+
request = json.loads(Path(sys.argv[1]).read_text(encoding='utf-8'))
|
|
169
|
+
else:
|
|
170
|
+
request = json.load(sys.stdin)
|
|
171
|
+
path = request['nativeLibraries']
|
|
172
|
+
os.environ['MAAFW_BINARY_PATH'] = path
|
|
173
|
+
dll_directory = os.add_dll_directory(path) if sys.platform == 'win32' else None
|
|
174
|
+
try:
|
|
175
|
+
from maa.library import Library
|
|
176
|
+
binding_version = version('maafw')
|
|
177
|
+
framework_version = Library.version()
|
|
178
|
+
number = lambda value: re.match(r'^v?(\d+\.\d+\.\d+)', value)
|
|
179
|
+
binding_number = number(binding_version)
|
|
180
|
+
library_number = number(framework_version)
|
|
181
|
+
if not binding_number or not library_number or binding_number.group(1) != library_number.group(1):
|
|
182
|
+
raise RuntimeError(f'MaaFramework 原生库 {framework_version} 与 Python 绑定 {binding_version} 不匹配')
|
|
183
|
+
if request.get('job') is not None:
|
|
184
|
+
say('MaaFramework 项目原生运行库 ' + framework_version)
|
|
185
|
+
run(request['job'], framework_version)
|
|
186
|
+
say('MAS_MAA_NATIVE_DONE ' + framework_version)
|
|
187
|
+
finally:
|
|
188
|
+
if dll_directory:
|
|
189
|
+
dll_directory.close()
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
if __name__ == '__main__':
|
|
193
|
+
try:
|
|
194
|
+
main()
|
|
195
|
+
except Exception as error:
|
|
196
|
+
say('MAS_MAA_NATIVE_ERROR ' + str(error).replace('\n', ' ')[:400])
|
|
197
|
+
sys.exit(1)
|
|
198
|
+
`;
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { cp, lstat, mkdir, realpath, rename, rm, stat, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { basename, delimiter, dirname, isAbsolute, join, relative, resolve } from 'node:path';
|
|
4
|
+
import { runProcess } from '../execution.js';
|
|
5
|
+
import { withinProject } from './managed-project-path.js';
|
|
6
|
+
import { nodeAgentLock, nodeAgentManifest } from './node-agent-path.js';
|
|
7
|
+
import { isNodeCommand } from './process.js';
|
|
8
|
+
import { loadProject, projectPath } from './project.js';
|
|
9
|
+
const skipped = new Set(['.git', 'node_modules', '.venv', nodeAgentManifest]);
|
|
10
|
+
async function nodeTools() {
|
|
11
|
+
const windows = process.platform === 'win32';
|
|
12
|
+
const paths = (process.env.PATH ?? '').split(delimiter).map(path => path.replace(/^"|"$/gu, '')).filter(isAbsolute);
|
|
13
|
+
async function find(entries) {
|
|
14
|
+
for (const entry of entries) {
|
|
15
|
+
if (await stat(entry).then(info => info.isFile(), () => false))
|
|
16
|
+
return realpath(entry);
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
const node = await find(paths.map(path => join(path, windows ? 'node.exe' : 'node')));
|
|
20
|
+
if (!node)
|
|
21
|
+
throw new Error('请在后端主机安装 Node.js 和 npm 以准备 Agent 环境');
|
|
22
|
+
const npmCli = await find([
|
|
23
|
+
join(dirname(node), 'node_modules', 'npm', 'bin', 'npm-cli.js'),
|
|
24
|
+
resolve(dirname(node), '..', 'lib', 'node_modules', 'npm', 'bin', 'npm-cli.js'),
|
|
25
|
+
...paths.map(path => join(path, 'node_modules', 'npm', 'bin', 'npm-cli.js')),
|
|
26
|
+
]);
|
|
27
|
+
if (!npmCli && windows)
|
|
28
|
+
throw new Error('无法找到系统 npm 命令,请检查 Node.js 安装');
|
|
29
|
+
return { node, command: npmCli ? node : 'npm', args: npmCli ? [npmCli] : [] };
|
|
30
|
+
}
|
|
31
|
+
async function packageForProject(path) {
|
|
32
|
+
const project = await loadProject(path);
|
|
33
|
+
const root = await realpath(project.directory);
|
|
34
|
+
const commands = [...project.agents, ...project.pretasks].filter(item => isNodeCommand(item.executable));
|
|
35
|
+
if (!commands.length)
|
|
36
|
+
throw new Error('项目未声明由 Node.js 启动的 Agent 或前置任务');
|
|
37
|
+
const directories = new Set([root]);
|
|
38
|
+
for (const command of commands) {
|
|
39
|
+
for (const argument of command.args) {
|
|
40
|
+
if (argument.startsWith('-') || !/\.[cm]?js$/iu.test(argument))
|
|
41
|
+
continue;
|
|
42
|
+
const script = projectPath(root, argument);
|
|
43
|
+
if (!withinProject(root, script))
|
|
44
|
+
continue;
|
|
45
|
+
for (let directory = dirname(script); withinProject(root, directory); directory = dirname(directory)) {
|
|
46
|
+
directories.add(directory);
|
|
47
|
+
if (directory === root)
|
|
48
|
+
break;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
const packages = (await Promise.all([...directories].map(async (directory) => {
|
|
53
|
+
const realDirectory = await realpath(directory).catch(error => {
|
|
54
|
+
if (error.code === 'ENOENT')
|
|
55
|
+
return undefined;
|
|
56
|
+
throw error;
|
|
57
|
+
});
|
|
58
|
+
if (!realDirectory || !withinProject(root, realDirectory))
|
|
59
|
+
return;
|
|
60
|
+
const lock = await nodeAgentLock(realDirectory);
|
|
61
|
+
return lock ? { packageRoot: relative(root, realDirectory), lock } : undefined;
|
|
62
|
+
}))).filter(item => item !== undefined);
|
|
63
|
+
if (!packages.length)
|
|
64
|
+
throw new Error('Node Agent 项目需要 package.json 和 package-lock.json');
|
|
65
|
+
if (packages.length > 1)
|
|
66
|
+
throw new Error('项目包含多个 npm 锁文件,无法选择同一个 Node Agent 环境');
|
|
67
|
+
return { source: root, ...packages[0] };
|
|
68
|
+
}
|
|
69
|
+
export class MaaNodeAgentEnvironments {
|
|
70
|
+
directory;
|
|
71
|
+
preparing = new Set();
|
|
72
|
+
constructor(dataDir) {
|
|
73
|
+
this.directory = resolve(dataDir, 'maafw-node-agent-env');
|
|
74
|
+
}
|
|
75
|
+
async prepare(path) {
|
|
76
|
+
if (!isAbsolute(path))
|
|
77
|
+
throw new Error('请选择项目的绝对路径');
|
|
78
|
+
const { source, packageRoot, lock } = await packageForProject(path);
|
|
79
|
+
if (this.preparing.has(source))
|
|
80
|
+
throw new Error('此项目的 Node Agent 环境正在准备');
|
|
81
|
+
this.preparing.add(source);
|
|
82
|
+
try {
|
|
83
|
+
return await this.copyAndInstall(source, packageRoot, lock);
|
|
84
|
+
}
|
|
85
|
+
finally {
|
|
86
|
+
this.preparing.delete(source);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
async copyAndInstall(source, packageRoot, lock) {
|
|
90
|
+
const tools = await nodeTools();
|
|
91
|
+
await mkdir(this.directory, { recursive: true });
|
|
92
|
+
const base = await realpath(this.directory);
|
|
93
|
+
if (withinProject(source, base) || withinProject(base, source))
|
|
94
|
+
throw new Error('请选择 Node Agent 环境目录以外的项目');
|
|
95
|
+
const id = randomUUID();
|
|
96
|
+
const directory = join(base, id);
|
|
97
|
+
const ready = join(directory, nodeAgentManifest);
|
|
98
|
+
const temporary = `${ready}.tmp`;
|
|
99
|
+
let published = false;
|
|
100
|
+
try {
|
|
101
|
+
await cp(source, directory, { recursive: true, errorOnExist: true, force: false, filter: async (path) => {
|
|
102
|
+
if (path !== source && skipped.has(basename(path)))
|
|
103
|
+
return false;
|
|
104
|
+
const entry = await lstat(path);
|
|
105
|
+
if (!entry.isFile() && !entry.isDirectory())
|
|
106
|
+
throw new Error('Node Agent 项目含链接或其他特殊文件,无法复制');
|
|
107
|
+
return true;
|
|
108
|
+
} });
|
|
109
|
+
const cwd = join(directory, packageRoot);
|
|
110
|
+
if (await nodeAgentLock(cwd) !== lock)
|
|
111
|
+
throw new Error('复制时 Node Agent 锁文件已变化,请重试');
|
|
112
|
+
await runProcess({
|
|
113
|
+
id: 'maafw-node-agent-env', name: 'MaaFramework Node Agent', adapter: 'general',
|
|
114
|
+
command: tools.command, args: [...tools.args, 'ci', '--omit=dev', '--ignore-scripts', '--no-audit', '--no-fund'],
|
|
115
|
+
cwd, env: { npm_config_cache: join(base, 'cache') },
|
|
116
|
+
}, { signal: AbortSignal.timeout(10 * 60_000), log: () => { } }).catch(error => {
|
|
117
|
+
throw new Error('Node Agent npm ci 失败,请检查项目锁文件与 npm 来源', { cause: error });
|
|
118
|
+
});
|
|
119
|
+
const prepared = new Date().toISOString();
|
|
120
|
+
// npm may create Windows junctions that embed the final installation path.
|
|
121
|
+
await writeFile(temporary, JSON.stringify({ schema: 1, source, packageRoot, lock, node: tools.node, prepared }), {
|
|
122
|
+
flag: 'wx', mode: 0o600,
|
|
123
|
+
});
|
|
124
|
+
await rename(temporary, ready);
|
|
125
|
+
published = true;
|
|
126
|
+
return { source, node: tools.node, directory, prepared };
|
|
127
|
+
}
|
|
128
|
+
finally {
|
|
129
|
+
if (!published)
|
|
130
|
+
await rm(directory, { recursive: true, force: true });
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { lstat, readFile, realpath, stat } from 'node:fs/promises';
|
|
3
|
+
import { isAbsolute, join, relative, resolve } from 'node:path';
|
|
4
|
+
import { withinProject } from './managed-project-path.js';
|
|
5
|
+
import { isNodeCommand } from './process.js';
|
|
6
|
+
export const nodeAgentManifest = '.automasc-maafw-node-agent.json';
|
|
7
|
+
export async function nodeAgentLock(path) {
|
|
8
|
+
async function read(file, limit) {
|
|
9
|
+
const name = join(path, file);
|
|
10
|
+
const info = await lstat(name).catch(error => {
|
|
11
|
+
if (error.code === 'ENOENT')
|
|
12
|
+
return undefined;
|
|
13
|
+
throw error;
|
|
14
|
+
});
|
|
15
|
+
if (!info)
|
|
16
|
+
return undefined;
|
|
17
|
+
if (!info.isFile() || info.size > limit)
|
|
18
|
+
throw new Error('Node Agent 的描述文件或 npm 锁文件无法读取');
|
|
19
|
+
return readFile(name);
|
|
20
|
+
}
|
|
21
|
+
const [definition, lock] = await Promise.all([
|
|
22
|
+
read('package.json', 1024 ** 2),
|
|
23
|
+
read('package-lock.json', 16 * 1024 ** 2),
|
|
24
|
+
]);
|
|
25
|
+
return definition && lock
|
|
26
|
+
? createHash('sha256').update(definition).update('\0').update(lock).digest('hex')
|
|
27
|
+
: undefined;
|
|
28
|
+
}
|
|
29
|
+
export async function readNodeAgentEnvironment(path, projectDirectory) {
|
|
30
|
+
if (!isAbsolute(path))
|
|
31
|
+
throw new Error('请选择已准备的 Node Agent 环境绝对目录');
|
|
32
|
+
const directory = await realpath(path).catch(() => { throw new Error('Node Agent 环境目录不存在'); });
|
|
33
|
+
const record = await readFile(join(directory, nodeAgentManifest), 'utf8').then(JSON.parse, () => undefined);
|
|
34
|
+
if (record?.schema !== 1 || typeof record.source !== 'string' || typeof record.packageRoot !== 'string' ||
|
|
35
|
+
typeof record.lock !== 'string' || typeof record.node !== 'string' || !isAbsolute(record.node)) {
|
|
36
|
+
throw new Error('请选择在项目管理中准备的 Node Agent 环境');
|
|
37
|
+
}
|
|
38
|
+
const source = await realpath(projectDirectory);
|
|
39
|
+
if (record.source !== source)
|
|
40
|
+
throw new Error('Node Agent 环境属于不同项目或版本,请为当前版本重新准备');
|
|
41
|
+
const packageDir = resolve(source, record.packageRoot);
|
|
42
|
+
if (!withinProject(source, packageDir) || await nodeAgentLock(packageDir) !== record.lock) {
|
|
43
|
+
throw new Error('Node Agent 锁文件已变化,请重新准备环境');
|
|
44
|
+
}
|
|
45
|
+
if (!await stat(record.node).then(info => info.isFile(), () => false))
|
|
46
|
+
throw new Error('Node Agent 的 Node.js 解释器已失效,请重新准备环境');
|
|
47
|
+
return { node: record.node, directory };
|
|
48
|
+
}
|
|
49
|
+
export function bindNodeAgent(command, projectDirectory, env) {
|
|
50
|
+
if (!env || !isNodeCommand(command.executable))
|
|
51
|
+
return { ...command, directory: projectDirectory };
|
|
52
|
+
const args = command.args.map(arg => isAbsolute(arg) && withinProject(projectDirectory, arg)
|
|
53
|
+
? join(env.directory, relative(projectDirectory, arg)) : arg);
|
|
54
|
+
return { ...command, executable: env.node, args, directory: env.directory };
|
|
55
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process';
|
|
2
|
+
import { createInterface } from 'node:readline';
|
|
3
|
+
export function isPythonCommand(command) {
|
|
4
|
+
return /^python3?(?:\.exe)?$/iu.test(command);
|
|
5
|
+
}
|
|
6
|
+
export function isNodeCommand(command) {
|
|
7
|
+
return /^node(?:\.exe)?$/iu.test(command);
|
|
8
|
+
}
|
|
9
|
+
export function readLines(stream, onLine) {
|
|
10
|
+
if (stream)
|
|
11
|
+
createInterface({ input: stream }).on('line', (line) => { if (line)
|
|
12
|
+
onLine(line); });
|
|
13
|
+
}
|
|
14
|
+
export async function terminateTree(pid) {
|
|
15
|
+
if (process.platform !== 'win32') {
|
|
16
|
+
// The worker and project processes each start a new process group.
|
|
17
|
+
try {
|
|
18
|
+
process.kill(-pid, 'SIGKILL');
|
|
19
|
+
}
|
|
20
|
+
catch { }
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
23
|
+
await new Promise((done) => {
|
|
24
|
+
execFile('taskkill.exe', ['/pid', String(pid), '/t', '/f'], { timeout: 1_500, windowsHide: true }, (error) => {
|
|
25
|
+
if (error) {
|
|
26
|
+
try {
|
|
27
|
+
process.kill(pid, 'SIGKILL');
|
|
28
|
+
}
|
|
29
|
+
catch { }
|
|
30
|
+
}
|
|
31
|
+
done();
|
|
32
|
+
});
|
|
33
|
+
});
|
|
34
|
+
}
|