@auto-mas/auto-mas-plugin-adapter-node-module 0.0.0-stage → 0.1.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/adapters.js +147 -0
- package/dist/server/blockly-compiler.js +277 -0
- package/dist/server/blockly.js +157 -0
- package/dist/server/builtin-plugins/adapter-node-module.js +9 -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/general-result.js +66 -0
- package/dist/server/maa/index.js +97 -0
- package/dist/server/maa/managed-project-path.js +34 -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-path.js +55 -0
- package/dist/server/maa/process.js +34 -0
- package/dist/server/maa/project.js +502 -0
- package/dist/server/maa/worker.js +361 -0
- package/dist/server/node-module-worker.js +40 -0
- package/dist/server/node-module.js +104 -0
- package/dist/server/run-lifecycle.js +1 -0
- package/dist/server/storage.js +76 -0
- package/package.json +30 -6
- package/README.md +0 -3
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
import { dirname, isAbsolute, join, win32 } from 'node:path';
|
|
2
|
+
import { stat } from 'node:fs/promises';
|
|
3
|
+
export function nativeManagerKind(kind) {
|
|
4
|
+
return kind === 'ldplayer' || kind === 'modavd';
|
|
5
|
+
}
|
|
6
|
+
export function managedEmulator(kind) {
|
|
7
|
+
return kind === 'mumu' || nativeManagerKind(kind);
|
|
8
|
+
}
|
|
9
|
+
export function instanceIndex(value) {
|
|
10
|
+
if (typeof value !== 'number' && (typeof value !== 'string' || !/^\d{1,10}$/u.test(value)))
|
|
11
|
+
return;
|
|
12
|
+
const number = Number(value);
|
|
13
|
+
if (Number.isSafeInteger(number) && number >= 0 && number <= 2147483647)
|
|
14
|
+
return String(number);
|
|
15
|
+
}
|
|
16
|
+
function integer(value, maximum = 2147483647) {
|
|
17
|
+
const number = Number(value);
|
|
18
|
+
if (Number.isSafeInteger(number) && number > 0 && number <= maximum)
|
|
19
|
+
return number;
|
|
20
|
+
}
|
|
21
|
+
function object(value) {
|
|
22
|
+
return value && typeof value === 'object' && !Array.isArray(value) ? value : {};
|
|
23
|
+
}
|
|
24
|
+
function adbAddress(value) {
|
|
25
|
+
return typeof value === 'string' && /^(?:emulator-\d+|(?:127\.0\.0\.1|localhost|\[::1\]):\d{1,5})$/u.test(value) ? value : undefined;
|
|
26
|
+
}
|
|
27
|
+
async function regularFile(path) {
|
|
28
|
+
try {
|
|
29
|
+
return (await stat(path)).isFile();
|
|
30
|
+
}
|
|
31
|
+
catch (error) {
|
|
32
|
+
if (!['ENOENT', 'ENOTDIR'].includes(error.code ?? ''))
|
|
33
|
+
throw error;
|
|
34
|
+
return false;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
export function managerCommand(kind, command) {
|
|
38
|
+
const names = kind === 'ldplayer' ? ['ldconsole.exe', 'dnconsole.exe'] : ['modavd.exe'];
|
|
39
|
+
if (!command || !isAbsolute(command) || !names.includes(win32.basename(command).toLowerCase())) {
|
|
40
|
+
throw new Error(`请选择 ${names.join(' 或 ')} 的绝对路径`);
|
|
41
|
+
}
|
|
42
|
+
return command;
|
|
43
|
+
}
|
|
44
|
+
export function parseLdInstances(stdout) {
|
|
45
|
+
const rows = [];
|
|
46
|
+
for (const line of stdout.replace(/^\uFEFF/u, '').trim().split(/\r?\n/u)) {
|
|
47
|
+
// The instance name may contain a comma. The numeric fields following it are fixed by list2.
|
|
48
|
+
const fields = /^(\d+),(.+?),(-?\d+),(-?\d+),([01]),(-?\d+),(-?\d+)(?:,\d+,\d+,\d+)?$/u.exec(line.trim());
|
|
49
|
+
const index = instanceIndex(fields?.[1]);
|
|
50
|
+
if (!fields || index === undefined)
|
|
51
|
+
continue;
|
|
52
|
+
const pid = integer(fields[7]);
|
|
53
|
+
rows.push({ index, name: fields[2], running: fields[5] === '1' || !!pid || !!integer(fields[6]), booted: fields[5] === '1', pid });
|
|
54
|
+
}
|
|
55
|
+
if (stdout.trim() && !rows.length)
|
|
56
|
+
throw new Error('雷电命令行未返回有效的实例列表');
|
|
57
|
+
return rows;
|
|
58
|
+
}
|
|
59
|
+
function modInstance(raw, connection) {
|
|
60
|
+
const item = object(raw);
|
|
61
|
+
const index = instanceIndex(item.index);
|
|
62
|
+
if (index === undefined || typeof item.running !== 'boolean')
|
|
63
|
+
throw new Error('ModAVD 未返回有效的实例信息');
|
|
64
|
+
const adbPath = typeof connection.adb_exe === 'string' && win32.isAbsolute(connection.adb_exe) ? connection.adb_exe : undefined;
|
|
65
|
+
return { index, name: typeof item.name === 'string' && item.name ? item.name : `实例 ${index}`,
|
|
66
|
+
running: item.running, booted: item.booted === true, pid: integer(item.pid), startedAt: typeof item.started_at === 'string' ? item.started_at : undefined,
|
|
67
|
+
address: adbAddress(item.serial) ?? adbAddress(item.adb_address), adbPath,
|
|
68
|
+
adbServerPort: integer(connection.script_adb_server_port, 65535) ?? integer(connection.adb_server_port, 65535),
|
|
69
|
+
version: typeof connection.version === 'string' ? connection.version : undefined };
|
|
70
|
+
}
|
|
71
|
+
export function parseModInstances(raw) {
|
|
72
|
+
const data = object(raw);
|
|
73
|
+
if (!Array.isArray(data.instances))
|
|
74
|
+
throw new Error('ModAVD 未返回实例列表');
|
|
75
|
+
return data.instances.map(item => modInstance(item, data));
|
|
76
|
+
}
|
|
77
|
+
async function runMod(host, command, args, signal, timeout = 8000) {
|
|
78
|
+
// Passing the root explicitly also prevents MODAVD_ROOT from selecting a different installation.
|
|
79
|
+
const folder = dirname(command);
|
|
80
|
+
const root = win32.basename(folder).toLowerCase() === 'tools' ? dirname(folder) : folder;
|
|
81
|
+
const result = await host.command(command, ['--root', root, '--json', ...args], signal, { timeout });
|
|
82
|
+
let envelope;
|
|
83
|
+
try {
|
|
84
|
+
envelope = object(JSON.parse(result.stdout.replace(/^\uFEFF/u, '')));
|
|
85
|
+
}
|
|
86
|
+
catch {
|
|
87
|
+
throw new Error(`ModAVD ${args[0]} 未返回有效结果,请检查包内版本`);
|
|
88
|
+
}
|
|
89
|
+
if (result.code || envelope.ok !== true) {
|
|
90
|
+
const error = object(envelope.error);
|
|
91
|
+
throw new Error(`ModAVD ${args[0]} 失败${typeof error.message === 'string' ? `:${error.message.slice(0, 240)}` : ''}`);
|
|
92
|
+
}
|
|
93
|
+
return envelope.data;
|
|
94
|
+
}
|
|
95
|
+
async function runLd(host, command, args, signal) {
|
|
96
|
+
const result = await host.command(command, args, signal);
|
|
97
|
+
if (result.code)
|
|
98
|
+
throw new Error(`雷电 ${args[0]} 命令失败`);
|
|
99
|
+
return result.stdout;
|
|
100
|
+
}
|
|
101
|
+
export function adbEnvironment(port) {
|
|
102
|
+
if (port === undefined)
|
|
103
|
+
return undefined;
|
|
104
|
+
return { ADB_SERVER_SOCKET: `tcp:127.0.0.1:${port}`, ANDROID_ADB_SERVER_ADDRESS: '127.0.0.1', ANDROID_ADB_SERVER_PORT: String(port) };
|
|
105
|
+
}
|
|
106
|
+
export class NativeEmulator {
|
|
107
|
+
kind;
|
|
108
|
+
command;
|
|
109
|
+
host;
|
|
110
|
+
constructor(kind, command, host) {
|
|
111
|
+
if (host.platform !== 'win32')
|
|
112
|
+
throw new Error('此模拟器管理方式仅适用于 Windows');
|
|
113
|
+
managerCommand(kind, command);
|
|
114
|
+
this.kind = kind;
|
|
115
|
+
this.command = command;
|
|
116
|
+
this.host = host;
|
|
117
|
+
}
|
|
118
|
+
async list(signal) {
|
|
119
|
+
if (this.kind === 'ldplayer')
|
|
120
|
+
return parseLdInstances(await runLd(this.host, this.command, ['list2'], signal));
|
|
121
|
+
return parseModInstances(await runMod(this.host, this.command, ['list'], signal));
|
|
122
|
+
}
|
|
123
|
+
async status(index, signal) {
|
|
124
|
+
const instance = (await this.list(signal)).find(item => item.index === index);
|
|
125
|
+
if (!instance)
|
|
126
|
+
throw new Error(`模拟器实例 ${index} 不存在`);
|
|
127
|
+
return instance;
|
|
128
|
+
}
|
|
129
|
+
async connection(instance, adbPath, signal) {
|
|
130
|
+
if (this.kind === 'modavd') {
|
|
131
|
+
if (!instance.adbServerPort || !instance.adbPath)
|
|
132
|
+
throw new Error('ModAVD 未报告私有 ADB 服务,请检查组件与 CLI 版本');
|
|
133
|
+
if (instance.address)
|
|
134
|
+
return { address: instance.address, adbPath: instance.adbPath, adbServerPort: instance.adbServerPort };
|
|
135
|
+
return undefined;
|
|
136
|
+
}
|
|
137
|
+
const bundled = join(dirname(this.command), 'adb.exe');
|
|
138
|
+
const adb = adbPath || (await regularFile(bundled) ? bundled : 'adb');
|
|
139
|
+
const output = await runLd(this.host, this.command, ['adb', '--index', instance.index, '--command', 'get-serialno'], signal);
|
|
140
|
+
const serials = [...new Set(output.trim().split(/\r?\n/u).map(line => adbAddress(line.trim())).filter(Boolean))];
|
|
141
|
+
if (serials.length === 1 && serials[0])
|
|
142
|
+
return { address: serials[0], adbPath: adb };
|
|
143
|
+
const port = 5555 + Number(instance.index) * 2;
|
|
144
|
+
if (port <= 65535 && instance.pid && await this.host.tcpOwner?.(`127.0.0.1:${port}`, signal) === instance.pid) {
|
|
145
|
+
return { address: `emulator-${port - 1}`, adbPath: adb };
|
|
146
|
+
}
|
|
147
|
+
return undefined;
|
|
148
|
+
}
|
|
149
|
+
async start(index, window, seconds, signal) {
|
|
150
|
+
if (this.kind === 'ldplayer')
|
|
151
|
+
return runLd(this.host, this.command, ['launch', '--index', index], signal);
|
|
152
|
+
return runMod(this.host, this.command, ['start', index, window ? '--window' : '--headless', '--timeout', String(seconds)], signal, (seconds + 10) * 1000);
|
|
153
|
+
}
|
|
154
|
+
async stop(index, signal) {
|
|
155
|
+
if (this.kind === 'ldplayer')
|
|
156
|
+
return runLd(this.host, this.command, ['quit', '--index', index], signal);
|
|
157
|
+
return runMod(this.host, this.command, ['stop', index], signal, 35000);
|
|
158
|
+
}
|
|
159
|
+
async operation(action, index, input, signal) {
|
|
160
|
+
if (this.kind === 'ldplayer') {
|
|
161
|
+
if (index === undefined)
|
|
162
|
+
throw new Error('请选择雷电实例');
|
|
163
|
+
if (action === 'install' && typeof input.apk === 'string' && isAbsolute(input.apk) && /\.apk$/iu.test(input.apk)) {
|
|
164
|
+
return runLd(this.host, this.command, ['installapp', '--index', index, '--filename', input.apk], signal);
|
|
165
|
+
}
|
|
166
|
+
if (action !== 'set')
|
|
167
|
+
throw new Error('当前操作需要 ModAVD');
|
|
168
|
+
if ((await this.status(index, signal)).running)
|
|
169
|
+
throw new Error('请先关闭雷电实例再修改性能设置');
|
|
170
|
+
const cpu = String(input.cpu);
|
|
171
|
+
const memory = String(input.memory);
|
|
172
|
+
const resolution = String(input.resolution);
|
|
173
|
+
if (!['1', '2', '3', '4'].includes(cpu) || !['512', '1024', '2048', '4096', '8192'].includes(memory)
|
|
174
|
+
|| !['1280,720,240', '1920,1080,320'].includes(resolution))
|
|
175
|
+
throw new Error('请选择雷电支持的分辨率、内存与核数');
|
|
176
|
+
return runLd(this.host, this.command, ['modify', '--index', index, '--resolution', resolution, '--cpu', cpu, '--memory', memory], signal);
|
|
177
|
+
}
|
|
178
|
+
if (action === 'check')
|
|
179
|
+
return runMod(this.host, this.command, ['check'], signal);
|
|
180
|
+
if (action === 'components')
|
|
181
|
+
return runMod(this.host, this.command, ['components', 'status'], signal);
|
|
182
|
+
if (action === 'hide' || action === 'show') {
|
|
183
|
+
if (index === undefined)
|
|
184
|
+
throw new Error('请选择带窗口启动的 ModAVD 实例');
|
|
185
|
+
return runMod(this.host, this.command, ['window', index, action], signal);
|
|
186
|
+
}
|
|
187
|
+
if (action === 'install') {
|
|
188
|
+
if (index === undefined || typeof input.apk !== 'string' || !isAbsolute(input.apk) || !/\.apk$/iu.test(input.apk)) {
|
|
189
|
+
throw new Error('请选择实例和 APK 文件的绝对路径');
|
|
190
|
+
}
|
|
191
|
+
return runMod(this.host, this.command, ['install', index, input.apk], signal, 120000);
|
|
192
|
+
}
|
|
193
|
+
if (action === 'delete') {
|
|
194
|
+
if (index === undefined || input.confirmed !== true)
|
|
195
|
+
throw new Error('请确认删除该 ModAVD 实例及其数据');
|
|
196
|
+
if ((await this.status(index, signal)).running)
|
|
197
|
+
throw new Error('请先关闭 ModAVD 实例');
|
|
198
|
+
return runMod(this.host, this.command, ['delete', index, '--yes'], signal, 120000);
|
|
199
|
+
}
|
|
200
|
+
if (action !== 'create' && action !== 'set')
|
|
201
|
+
throw new Error('不支持的实例管理操作');
|
|
202
|
+
if (action === 'set' && index === undefined)
|
|
203
|
+
throw new Error('请选择要配置的实例');
|
|
204
|
+
const args = action === 'set' ? ['set', index] : ['create', ...(index === undefined ? [] : ['--index', index])];
|
|
205
|
+
if (typeof input.title === 'string' && input.title.trim())
|
|
206
|
+
args.push('--title', input.title.trim());
|
|
207
|
+
const settings = [['memory', '--memory', ['3G', '4G', '5G', '6G']], ['cpu', '--cpu', ['2', '4', '6']],
|
|
208
|
+
['fps', '--fps', ['30', '60']], ['resolution', '--resolution', ['720', '1080']]];
|
|
209
|
+
for (const [key, flag, choices] of settings) {
|
|
210
|
+
if (input[key] === undefined || input[key] === '')
|
|
211
|
+
continue;
|
|
212
|
+
const value = String(input[key]);
|
|
213
|
+
if (!choices.includes(value))
|
|
214
|
+
throw new Error(`ModAVD 设置 ${key} 无效`);
|
|
215
|
+
args.push(flag, value);
|
|
216
|
+
}
|
|
217
|
+
return runMod(this.host, this.command, args, signal, action === 'create' ? 1220000 : 30000);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
@@ -0,0 +1,364 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import { realpathSync } from 'node:fs';
|
|
4
|
+
import { resolve, sep } from 'node:path';
|
|
5
|
+
import { createInterface } from 'node:readline';
|
|
6
|
+
import { Store } from './storage.js';
|
|
7
|
+
import { runPhases } from './run-lifecycle.js';
|
|
8
|
+
export function forAccount(store, script, account) {
|
|
9
|
+
if (account.scriptId !== script.id || account.enabled === false)
|
|
10
|
+
throw new Error('账号已停用或不属于此托管');
|
|
11
|
+
const plan = account.planId ? store.get('plans', account.planId) : undefined;
|
|
12
|
+
return { ...script, name: `${script.name} · ${account.name}`, accountId: account.id, accountConfig: account.accountConfig, loginAccount: account.loginAccount,
|
|
13
|
+
args: [...script.args ?? [], ...account.args ?? []], tasks: plan?.tasks ?? script.tasks,
|
|
14
|
+
...(account.emulatorId ? { emulatorId: account.emulatorId, emulatorInstance: account.emulatorInstance } : {}) };
|
|
15
|
+
}
|
|
16
|
+
export function targetsFor(store, script) {
|
|
17
|
+
const accounts = store.list('accounts').filter(account => account.scriptId === script.id);
|
|
18
|
+
if (!accounts.length)
|
|
19
|
+
return [script];
|
|
20
|
+
return accounts.filter(account => account.enabled !== false).map(account => forAccount(store, script, account));
|
|
21
|
+
}
|
|
22
|
+
export function stopProcess(child) {
|
|
23
|
+
if (!child.pid || child.exitCode !== null || child.signalCode !== null)
|
|
24
|
+
return;
|
|
25
|
+
if (process.platform === 'win32') {
|
|
26
|
+
const killer = spawn('taskkill.exe', ['/PID', String(child.pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' });
|
|
27
|
+
killer.on('error', () => child.kill());
|
|
28
|
+
killer.on('exit', code => { if (code)
|
|
29
|
+
child.kill(); });
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
const pid = child.pid;
|
|
33
|
+
try {
|
|
34
|
+
process.kill(-pid, 'SIGTERM');
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
child.kill('SIGTERM');
|
|
38
|
+
}
|
|
39
|
+
const deadline = setTimeout(() => {
|
|
40
|
+
try {
|
|
41
|
+
process.kill(-pid, 'SIGKILL');
|
|
42
|
+
}
|
|
43
|
+
catch { /* process group is gone */ }
|
|
44
|
+
}, 4000);
|
|
45
|
+
deadline.unref();
|
|
46
|
+
}
|
|
47
|
+
export const runProcess = async (script, options) => {
|
|
48
|
+
const { signal, log, started, launchProcess } = options;
|
|
49
|
+
if (!script.command)
|
|
50
|
+
throw new Error('请配置可执行文件');
|
|
51
|
+
signal.throwIfAborted();
|
|
52
|
+
if (launchProcess)
|
|
53
|
+
return launchProcess({ command: script.command, args: script.args, cwd: script.cwd, env: script.env }, options);
|
|
54
|
+
const child = spawn(script.command, script.args ?? [], {
|
|
55
|
+
cwd: script.cwd || undefined,
|
|
56
|
+
env: { ...process.env, ...script.env },
|
|
57
|
+
detached: process.platform !== 'win32',
|
|
58
|
+
windowsHide: true,
|
|
59
|
+
shell: false,
|
|
60
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
61
|
+
});
|
|
62
|
+
const stop = () => stopProcess(child);
|
|
63
|
+
signal.addEventListener('abort', stop, { once: true });
|
|
64
|
+
if (signal.aborted)
|
|
65
|
+
stop();
|
|
66
|
+
for (const stream of [child.stdout, child.stderr])
|
|
67
|
+
createInterface({ input: stream }).on('line', log);
|
|
68
|
+
try {
|
|
69
|
+
await new Promise((resolve, reject) => {
|
|
70
|
+
child.once('spawn', () => {
|
|
71
|
+
try {
|
|
72
|
+
started?.();
|
|
73
|
+
}
|
|
74
|
+
catch (error) {
|
|
75
|
+
stop();
|
|
76
|
+
reject(error);
|
|
77
|
+
}
|
|
78
|
+
});
|
|
79
|
+
child.once('error', reject);
|
|
80
|
+
child.once('close', (code, interruptedBy) => {
|
|
81
|
+
if (signal.aborted)
|
|
82
|
+
reject(signal.reason);
|
|
83
|
+
else if (code === 0)
|
|
84
|
+
resolve();
|
|
85
|
+
else
|
|
86
|
+
reject(new Error(`进程结束 (${code ?? interruptedBy})`));
|
|
87
|
+
});
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
finally {
|
|
91
|
+
signal.removeEventListener('abort', stop);
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
function canonicalPath(path) {
|
|
95
|
+
let result;
|
|
96
|
+
try {
|
|
97
|
+
result = realpathSync.native(path);
|
|
98
|
+
}
|
|
99
|
+
catch {
|
|
100
|
+
result = resolve(path);
|
|
101
|
+
}
|
|
102
|
+
return process.platform === 'win32' ? result.toLowerCase() : result;
|
|
103
|
+
}
|
|
104
|
+
export class Runner {
|
|
105
|
+
active = new Map();
|
|
106
|
+
claimed = new Set();
|
|
107
|
+
accepting = true;
|
|
108
|
+
startPauses = new Set();
|
|
109
|
+
owners = new Map();
|
|
110
|
+
store;
|
|
111
|
+
changed;
|
|
112
|
+
finished;
|
|
113
|
+
options;
|
|
114
|
+
lifecycle;
|
|
115
|
+
constructor(store, changed, finished = () => { }, options = {}, lifecycle = {}) {
|
|
116
|
+
this.store = store;
|
|
117
|
+
this.changed = changed;
|
|
118
|
+
this.finished = finished;
|
|
119
|
+
this.options = options;
|
|
120
|
+
this.lifecycle = lifecycle;
|
|
121
|
+
for (const run of this.store.list('runs').filter(run => run.status === 'running')) {
|
|
122
|
+
const finished = new Date().toISOString();
|
|
123
|
+
const stages = [...(run.stages ?? [])];
|
|
124
|
+
const adapter = stages[0]?.adapter ?? this.store.get('scripts', run.scriptId)?.adapter ?? 'unknown';
|
|
125
|
+
for (const stage of runPhases) {
|
|
126
|
+
const last = stages.findLast(event => event.stage === stage);
|
|
127
|
+
if (last && last.status !== 'started')
|
|
128
|
+
continue;
|
|
129
|
+
const status = last || stage === 'finish-task' ? 'failed' : 'skipped';
|
|
130
|
+
stages.push({ runId: run.id, scriptId: run.scriptId, adapter, sequence: stages.length + 1, stage, status, at: finished,
|
|
131
|
+
message: stage === 'finish-task' ? '上次运行中断,未能确认清理' : '上次运行中断' });
|
|
132
|
+
}
|
|
133
|
+
this.store.put('runs', { ...run, stages, status: 'error', error: '上次运行中断', finished });
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
register(id, execute) {
|
|
137
|
+
if (this.owners.has(id))
|
|
138
|
+
throw new Error(`执行器已注册: ${id}`);
|
|
139
|
+
const owner = Symbol(id);
|
|
140
|
+
this.owners.set(id, { execute, owner });
|
|
141
|
+
return () => { if (this.owners.get(id)?.owner === owner)
|
|
142
|
+
this.owners.delete(id); };
|
|
143
|
+
}
|
|
144
|
+
adapters() { return [...this.owners.keys()]; }
|
|
145
|
+
defaultTimeout() { return this.options.defaultTimeoutSeconds ?? 3600; }
|
|
146
|
+
conflict(key) {
|
|
147
|
+
if (this.claimed.has(key))
|
|
148
|
+
return true;
|
|
149
|
+
if (!key.startsWith('path:'))
|
|
150
|
+
return false;
|
|
151
|
+
const withSeparator = (path) => path.endsWith(sep) ? path : path + sep;
|
|
152
|
+
return [...this.claimed].some(held => held.startsWith('path:') && (held.startsWith(withSeparator(key)) || key.startsWith(withSeparator(held))));
|
|
153
|
+
}
|
|
154
|
+
claimInstallation(path) {
|
|
155
|
+
if (!this.accepting || this.startsPaused)
|
|
156
|
+
throw new Error('任务执行服务当前无法接纳维护操作');
|
|
157
|
+
const key = 'path:' + canonicalPath(path);
|
|
158
|
+
if (this.conflict(key))
|
|
159
|
+
throw new Error('安装目录已被其他操作占用');
|
|
160
|
+
this.claimed.add(key);
|
|
161
|
+
let held = true;
|
|
162
|
+
return () => {
|
|
163
|
+
if (held)
|
|
164
|
+
this.claimed.delete(key);
|
|
165
|
+
held = false;
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
start(input) {
|
|
169
|
+
if (!this.accepting)
|
|
170
|
+
throw new Error('执行服务正在退出');
|
|
171
|
+
if (this.startsPaused)
|
|
172
|
+
throw new Error('插件正在热重载,请稍后启动任务');
|
|
173
|
+
const script = this.lifecycle.snapshot?.(input) ?? structuredClone(input);
|
|
174
|
+
if (script.enabled === false)
|
|
175
|
+
throw new Error('该托管已停用');
|
|
176
|
+
const adapter = this.owners.get(script.adapter)?.execute;
|
|
177
|
+
if (!adapter)
|
|
178
|
+
throw new Error(`执行器不可用: ${script.adapter}`);
|
|
179
|
+
const config = script.adapterConfig;
|
|
180
|
+
const directory = script.projectPath || script.cwd || config?.installRoot;
|
|
181
|
+
const keys = [`script:${script.id}`];
|
|
182
|
+
if (typeof directory === 'string' && directory)
|
|
183
|
+
keys.push(`path:${canonicalPath(directory)}`);
|
|
184
|
+
if (typeof script.device === 'string' && script.device)
|
|
185
|
+
keys.push(`device:${script.device}`);
|
|
186
|
+
const address = config?.address || script.address;
|
|
187
|
+
if (typeof address === 'string' && address)
|
|
188
|
+
keys.push(`adb:${address.trim().toLowerCase()}`);
|
|
189
|
+
const handle = config?.windowHandle || script.windowHandle;
|
|
190
|
+
if (typeof handle === 'number' && handle > 0)
|
|
191
|
+
keys.push(`win32:${handle}`);
|
|
192
|
+
keys.push(...(this.lifecycle.resourceKeys?.(script) ?? []));
|
|
193
|
+
if (keys.some(key => this.conflict(key)))
|
|
194
|
+
throw new Error('脚本、工作目录或设备已被占用');
|
|
195
|
+
const run = { id: randomUUID(), name: script.name, scriptId: script.id, status: 'running', started: new Date().toISOString(), logs: [], stages: [],
|
|
196
|
+
workflow: script.workflow && Object.freeze(script.workflow), executionTarget: script.executionTarget };
|
|
197
|
+
this.store.put('runs', run);
|
|
198
|
+
keys.forEach(key => this.claimed.add(key));
|
|
199
|
+
const claimAdb = (address, serverPort) => {
|
|
200
|
+
const key = serverPort && serverPort !== 5037 ? `adb:${serverPort}:${address.trim().toLowerCase()}` : `adb:${address.trim().toLowerCase()}`;
|
|
201
|
+
if (keys.includes(key))
|
|
202
|
+
return;
|
|
203
|
+
if (this.claimed.has(key))
|
|
204
|
+
throw new Error(`ADB 设备 ${address} 已被其他任务占用`);
|
|
205
|
+
keys.push(key);
|
|
206
|
+
this.claimed.add(key);
|
|
207
|
+
};
|
|
208
|
+
const controller = new AbortController();
|
|
209
|
+
const done = Promise.resolve().then(async () => {
|
|
210
|
+
const timeout = setTimeout(() => controller.abort(new Error('运行超时')), (script.timeoutSeconds ?? this.defaultTimeout()) * 1000);
|
|
211
|
+
try {
|
|
212
|
+
await this.execute(run, script, adapter, controller.signal, claimAdb);
|
|
213
|
+
}
|
|
214
|
+
finally {
|
|
215
|
+
clearTimeout(timeout);
|
|
216
|
+
keys.forEach(key => this.claimed.delete(key));
|
|
217
|
+
this.active.delete(run.id);
|
|
218
|
+
run.finished = new Date().toISOString();
|
|
219
|
+
this.store.put('runs', run);
|
|
220
|
+
this.changed();
|
|
221
|
+
try {
|
|
222
|
+
this.finished(run);
|
|
223
|
+
}
|
|
224
|
+
catch (error) {
|
|
225
|
+
console.error('运行结束事件处理失败', error);
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
return run;
|
|
229
|
+
});
|
|
230
|
+
this.active.set(run.id, { controller, done, snapshot: run });
|
|
231
|
+
this.changed();
|
|
232
|
+
return { run, done };
|
|
233
|
+
}
|
|
234
|
+
async execute(run, original, adapter, signal, claimAdb) {
|
|
235
|
+
const stages = run.stages;
|
|
236
|
+
const log = line => {
|
|
237
|
+
run.logs.push(line.slice(0, 16000));
|
|
238
|
+
if (run.logs.length > (this.options.logLineLimit ?? 4000))
|
|
239
|
+
run.logs.shift();
|
|
240
|
+
this.changed();
|
|
241
|
+
};
|
|
242
|
+
const report = (stage, status, message) => {
|
|
243
|
+
const event = Object.freeze({ runId: run.id, scriptId: run.scriptId, adapter: original.adapter,
|
|
244
|
+
sequence: stages.length + 1, stage, status, at: new Date().toISOString(), ...(message ? { message: message.slice(0, 2000) } : {}),
|
|
245
|
+
...(run.workflow ? { workflow: run.workflow } : {}) });
|
|
246
|
+
stages.push(event);
|
|
247
|
+
this.store.put('runs', run);
|
|
248
|
+
this.changed();
|
|
249
|
+
try {
|
|
250
|
+
this.lifecycle.stage?.(event);
|
|
251
|
+
}
|
|
252
|
+
catch (error) {
|
|
253
|
+
log(`运行事件处理失败: ${String(error)}`);
|
|
254
|
+
}
|
|
255
|
+
};
|
|
256
|
+
const options = { signal, log, report };
|
|
257
|
+
let targets;
|
|
258
|
+
const progress = { phase: 'prepare-game' };
|
|
259
|
+
let invoked = false;
|
|
260
|
+
let acceptsStart = true;
|
|
261
|
+
let outcome = 'success';
|
|
262
|
+
const started = (message) => {
|
|
263
|
+
if (!acceptsStart || progress.phase !== 'start-script')
|
|
264
|
+
return;
|
|
265
|
+
report('start-script', 'completed', message);
|
|
266
|
+
progress.phase = 'complete-script';
|
|
267
|
+
report('complete-script', 'started');
|
|
268
|
+
};
|
|
269
|
+
try {
|
|
270
|
+
report(progress.phase, 'started');
|
|
271
|
+
signal.throwIfAborted();
|
|
272
|
+
targets = await this.lifecycle.prepare?.(original, { ...options, claimAdb });
|
|
273
|
+
signal.throwIfAborted();
|
|
274
|
+
report(progress.phase, this.lifecycle.prepare ? 'completed' : 'skipped');
|
|
275
|
+
const script = targets?.script ?? original;
|
|
276
|
+
progress.phase = 'start-script';
|
|
277
|
+
report(progress.phase, 'started');
|
|
278
|
+
await this.lifecycle.before?.(script, options);
|
|
279
|
+
signal.throwIfAborted();
|
|
280
|
+
invoked = true;
|
|
281
|
+
const adapterOptions = { ...options, started, output: value => {
|
|
282
|
+
const encoded = JSON.stringify(value);
|
|
283
|
+
if (encoded === undefined || Buffer.byteLength(encoded) > 64 * 1024)
|
|
284
|
+
throw new Error('运行结果必须是 64 KiB 以内的 JSON');
|
|
285
|
+
run.output = JSON.parse(encoded);
|
|
286
|
+
} };
|
|
287
|
+
if (this.lifecycle.execute)
|
|
288
|
+
await this.lifecycle.execute(script, adapterOptions, adapter);
|
|
289
|
+
else if (script.executionTarget)
|
|
290
|
+
throw new Error('任务执行位置不可用');
|
|
291
|
+
else
|
|
292
|
+
await adapter(script, adapterOptions);
|
|
293
|
+
signal.throwIfAborted();
|
|
294
|
+
started('执行器已返回结果');
|
|
295
|
+
report('complete-script', 'completed');
|
|
296
|
+
}
|
|
297
|
+
catch (error) {
|
|
298
|
+
run.error = error instanceof Error ? error.message : String(error);
|
|
299
|
+
outcome = signal.aborted && signal.reason?.message === '用户停止任务' ? 'cancelled' : 'error';
|
|
300
|
+
report(progress.phase, outcome === 'cancelled' ? 'cancelled' : 'failed', run.error);
|
|
301
|
+
if (progress.phase === 'prepare-game')
|
|
302
|
+
report('start-script', 'skipped');
|
|
303
|
+
if (progress.phase !== 'complete-script')
|
|
304
|
+
report('complete-script', 'skipped');
|
|
305
|
+
}
|
|
306
|
+
finally {
|
|
307
|
+
acceptsStart = false;
|
|
308
|
+
const failures = [];
|
|
309
|
+
try {
|
|
310
|
+
report('finish-task', 'started');
|
|
311
|
+
if (invoked)
|
|
312
|
+
await this.lifecycle.after?.(targets?.script ?? original, options, outcome);
|
|
313
|
+
}
|
|
314
|
+
catch (error) {
|
|
315
|
+
failures.push(error instanceof Error ? error.message : String(error));
|
|
316
|
+
}
|
|
317
|
+
try {
|
|
318
|
+
await targets?.close();
|
|
319
|
+
}
|
|
320
|
+
catch (error) {
|
|
321
|
+
failures.push(error instanceof Error ? error.message : String(error));
|
|
322
|
+
}
|
|
323
|
+
if (failures.length) {
|
|
324
|
+
const message = failures.join('。');
|
|
325
|
+
log(`运行收尾失败: ${message}`);
|
|
326
|
+
report('finish-task', 'failed', message);
|
|
327
|
+
if (outcome === 'success') {
|
|
328
|
+
outcome = 'error';
|
|
329
|
+
run.error = message;
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
else
|
|
333
|
+
report('finish-task', 'completed');
|
|
334
|
+
run.status = outcome;
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
get(id) { return this.active.get(id)?.snapshot ?? this.store.get('runs', id); }
|
|
338
|
+
list() {
|
|
339
|
+
return this.store.recentRuns().map(run => this.active.get(run.id)?.snapshot ?? run);
|
|
340
|
+
}
|
|
341
|
+
summary() {
|
|
342
|
+
return this.list().map(({ logs, stages, output, ...summary }) => summary);
|
|
343
|
+
}
|
|
344
|
+
stop(id) {
|
|
345
|
+
const task = this.active.get(id);
|
|
346
|
+
if (!task)
|
|
347
|
+
throw new Error('任务当前未在运行');
|
|
348
|
+
task.controller.abort(new Error('用户停止任务'));
|
|
349
|
+
}
|
|
350
|
+
busy() { return this.active.size > 0 || this.claimed.size > 0; }
|
|
351
|
+
get startsPaused() { return this.startPauses.size > 0 || this.lifecycle.startsPaused?.() === true; }
|
|
352
|
+
pauseStarts() {
|
|
353
|
+
const pause = Symbol();
|
|
354
|
+
this.startPauses.add(pause);
|
|
355
|
+
return () => { this.startPauses.delete(pause); };
|
|
356
|
+
}
|
|
357
|
+
async close() {
|
|
358
|
+
this.accepting = false;
|
|
359
|
+
const active = [...this.active.values()];
|
|
360
|
+
for (const task of active)
|
|
361
|
+
task.controller.abort(new Error('用户停止任务'));
|
|
362
|
+
await Promise.allSettled(active.map(task => task.done));
|
|
363
|
+
}
|
|
364
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
export const ui = (ctx) => ctx.get('mas.ui');
|
|
2
|
+
export const store = (ctx) => ctx.get('mas.store');
|
|
3
|
+
export const runner = (ctx) => ctx.get('mas.runner');
|
|
4
|
+
export function text(input, key, label, required = true) {
|
|
5
|
+
const value = input[key];
|
|
6
|
+
if (typeof value === 'string' && value.trim())
|
|
7
|
+
return value.trim();
|
|
8
|
+
if (required)
|
|
9
|
+
throw new Error(`请输入${label}`);
|
|
10
|
+
return '';
|
|
11
|
+
}
|
|
12
|
+
export function strings(value) {
|
|
13
|
+
if (!value)
|
|
14
|
+
return [];
|
|
15
|
+
if (Array.isArray(value) && value.every(item => typeof item === 'string'))
|
|
16
|
+
return value;
|
|
17
|
+
if (typeof value === 'string') {
|
|
18
|
+
if (value.trim().startsWith('[')) {
|
|
19
|
+
const parsed = JSON.parse(value);
|
|
20
|
+
if (Array.isArray(parsed) && parsed.every(item => typeof item === 'string'))
|
|
21
|
+
return parsed;
|
|
22
|
+
throw new Error('JSON 必须是字符串数组');
|
|
23
|
+
}
|
|
24
|
+
return value.split(/[\n,]+/).map(item => item.trim()).filter(Boolean);
|
|
25
|
+
}
|
|
26
|
+
throw new Error('请输入字符串列表');
|
|
27
|
+
}
|
|
28
|
+
export const field = (key, label, extra = {}) => ({ key, label, ...extra });
|
|
29
|
+
export const columns = (...pairs) => pairs.map(([key, label]) => ({ key, label }));
|
|
30
|
+
export const action = (id, label) => ({ id, label });
|
|
31
|
+
export const runColumns = columns(['name', '托管'], ['status', '状态'], ['started', '开始时间'], ['finished', '结束时间'], ['error', '结果详情']);
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
export function generalResultRules(input) {
|
|
2
|
+
const read = (key) => {
|
|
3
|
+
const value = typeof input[key] === 'string' ? input[key].trim() : '';
|
|
4
|
+
if (value.length > 300 || /[\r\n]/u.test(value))
|
|
5
|
+
throw new Error('日志匹配内容必须是 300 字符以内的单行文本');
|
|
6
|
+
return value || undefined;
|
|
7
|
+
};
|
|
8
|
+
const startupText = read('startupText');
|
|
9
|
+
const successText = read('successText');
|
|
10
|
+
const failureText = read('failureText');
|
|
11
|
+
const startupTimeout = startupText ? Number(input.startupTimeout ?? 30) : undefined;
|
|
12
|
+
if (startupTimeout !== undefined && (!Number.isInteger(startupTimeout) || startupTimeout < 1 || startupTimeout > 300)) {
|
|
13
|
+
throw new Error('启动检查时限必须介于 1 至 300 秒');
|
|
14
|
+
}
|
|
15
|
+
return { startupText, startupTimeout, successText, failureText };
|
|
16
|
+
}
|
|
17
|
+
export async function withGeneralResult(script, options, dispatch) {
|
|
18
|
+
const source = script.adapterConfig && typeof script.adapterConfig === 'object'
|
|
19
|
+
? script.adapterConfig : script;
|
|
20
|
+
const { startupText, startupTimeout, successText, failureText } = generalResultRules(source);
|
|
21
|
+
if (!startupText && !successText && !failureText)
|
|
22
|
+
return dispatch(script, options);
|
|
23
|
+
const monitor = new AbortController();
|
|
24
|
+
let ready = false;
|
|
25
|
+
let success = false;
|
|
26
|
+
let deadline;
|
|
27
|
+
const markReady = () => {
|
|
28
|
+
if (ready || monitor.signal.aborted)
|
|
29
|
+
return;
|
|
30
|
+
ready = true;
|
|
31
|
+
clearTimeout(deadline);
|
|
32
|
+
options.started?.();
|
|
33
|
+
};
|
|
34
|
+
try {
|
|
35
|
+
await dispatch(script, {
|
|
36
|
+
...options,
|
|
37
|
+
signal: AbortSignal.any([options.signal, monitor.signal]),
|
|
38
|
+
started: () => {
|
|
39
|
+
if (!startupText)
|
|
40
|
+
return markReady();
|
|
41
|
+
if (ready || deadline)
|
|
42
|
+
return;
|
|
43
|
+
deadline = setTimeout(() => monitor.abort(new Error('启动检查超时:未检测到配置的日志文本')), startupTimeout * 1000);
|
|
44
|
+
deadline.unref();
|
|
45
|
+
},
|
|
46
|
+
log(line) {
|
|
47
|
+
options.log(line);
|
|
48
|
+
if (failureText && line.includes(failureText))
|
|
49
|
+
monitor.abort(new Error('匹配到配置的失败日志'));
|
|
50
|
+
if (successText && line.includes(successText))
|
|
51
|
+
success = true;
|
|
52
|
+
if (startupText && line.includes(startupText))
|
|
53
|
+
markReady();
|
|
54
|
+
},
|
|
55
|
+
});
|
|
56
|
+
options.signal.throwIfAborted();
|
|
57
|
+
monitor.signal.throwIfAborted();
|
|
58
|
+
if (startupText && !ready)
|
|
59
|
+
throw new Error('脚本已退出,但未检测到配置的启动日志');
|
|
60
|
+
if (successText && !success)
|
|
61
|
+
throw new Error('脚本已退出,但未检测到配置的成功日志');
|
|
62
|
+
}
|
|
63
|
+
finally {
|
|
64
|
+
clearTimeout(deadline);
|
|
65
|
+
}
|
|
66
|
+
}
|