@auto-mas/auto-mas-plugin-adapter-oknte 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/adapters.js +147 -0
- package/dist/server/builtin-plugins/adapter-oknte.js +7 -0
- package/dist/server/builtin-plugins/icons/oknte.png +0 -0
- package/dist/server/community/vault.js +65 -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/game-plugins/native-config.js +251 -0
- package/dist/server/game-plugins/native.js +207 -0
- package/dist/server/game-plugins/oknte.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/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,147 @@
|
|
|
1
|
+
import { fileURLToPath } from 'node:url';
|
|
2
|
+
import { isAbsolute } from 'node:path';
|
|
3
|
+
import { stat } from 'node:fs/promises';
|
|
4
|
+
import { Runner, runProcess } from './execution.js';
|
|
5
|
+
import { generalResultRules, withGeneralResult } from './general-result.js';
|
|
6
|
+
export function optionalText(value) { return typeof value === 'string' ? value.trim() : ''; }
|
|
7
|
+
export function textList(value) {
|
|
8
|
+
if (!value)
|
|
9
|
+
return [];
|
|
10
|
+
const list = typeof value === 'string'
|
|
11
|
+
? value.trim().startsWith('[') ? JSON.parse(value) : value.split(/[\n,]+/).map(x => x.trim()).filter(Boolean)
|
|
12
|
+
: value;
|
|
13
|
+
if (!Array.isArray(list) || list.some(item => typeof item !== 'string'))
|
|
14
|
+
throw new Error('请输入有效的字符串列表');
|
|
15
|
+
return list;
|
|
16
|
+
}
|
|
17
|
+
export class AdapterCatalog {
|
|
18
|
+
entries = new Map();
|
|
19
|
+
get(id) { return this.entries.get(id); }
|
|
20
|
+
list() { return [...this.entries.values()]; }
|
|
21
|
+
register(spec) {
|
|
22
|
+
if (this.entries.has(spec.id))
|
|
23
|
+
throw new Error(`专项已登记: ${spec.id}`);
|
|
24
|
+
this.entries.set(spec.id, spec);
|
|
25
|
+
return () => this.entries.delete(spec.id);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
export function adapterFeature(spec, options) {
|
|
29
|
+
return { id: spec.id, name: spec.title, description: spec.description, adapter: true, component: {
|
|
30
|
+
inject: ['mas.runner', 'mas.adapters', ...options?.inject ?? []],
|
|
31
|
+
provide: options?.provide,
|
|
32
|
+
apply(ctx) {
|
|
33
|
+
const catalog = ctx.get('mas.adapters');
|
|
34
|
+
const runner = ctx.get('mas.runner');
|
|
35
|
+
const file = options?.icon;
|
|
36
|
+
let icon;
|
|
37
|
+
ctx.effect(() => {
|
|
38
|
+
const deregister = catalog.register(file ? { ...spec, get icon() { return icon ?? spec.icon; } } : spec);
|
|
39
|
+
const removeRunner = runner.register(spec.id, (script, options) => {
|
|
40
|
+
const unavailable = spec.supports?.();
|
|
41
|
+
if (unavailable)
|
|
42
|
+
throw new Error(unavailable);
|
|
43
|
+
return spec.run(script, options);
|
|
44
|
+
});
|
|
45
|
+
return () => { removeRunner(); deregister(); };
|
|
46
|
+
});
|
|
47
|
+
if (file)
|
|
48
|
+
ctx.inject(['mas.ui'], scope => {
|
|
49
|
+
const ui = scope.get('mas.ui');
|
|
50
|
+
if (!ui.image)
|
|
51
|
+
return;
|
|
52
|
+
const url = ui.image(scope, `adapter-${spec.id}-icon`, fileURLToPath(file));
|
|
53
|
+
scope.effect(() => {
|
|
54
|
+
icon = url;
|
|
55
|
+
return () => { icon = undefined; };
|
|
56
|
+
});
|
|
57
|
+
});
|
|
58
|
+
options?.apply?.(ctx);
|
|
59
|
+
},
|
|
60
|
+
} };
|
|
61
|
+
}
|
|
62
|
+
const general = {
|
|
63
|
+
id: 'general', title: '通用脚本', description: '运行本机程序或命令行脚本,可为每个账号补充参数。', group: '通用',
|
|
64
|
+
scriptFields: [
|
|
65
|
+
{ key: 'command', label: '可执行文件', kind: 'hostpath', required: true },
|
|
66
|
+
{ key: 'args', label: '启动参数(JSON 数组)', kind: 'textarea', hint: '每个参数是独立项。带空格的路径请使用 JSON 字符串。' },
|
|
67
|
+
{ key: 'cwd', label: '工作目录', kind: 'hostpath', directory: true },
|
|
68
|
+
{ key: 'startupText', label: '启动确认日志(可选)', hint: '匹配一行中的固定文本后标记已启动。' },
|
|
69
|
+
{ key: 'startupTimeout', label: '启动确认时限(秒)', kind: 'number', default: 30, hint: '填写启动确认日志后生效。' },
|
|
70
|
+
{ key: 'successText', label: '成功日志(可选)', hint: '退出码为 0 且本轮日志包含该文本才算成功。' },
|
|
71
|
+
{ key: 'failureText', label: '失败日志(可选)', hint: '本轮日志出现该文本即终止并记录失败。' },
|
|
72
|
+
],
|
|
73
|
+
accountFields: [{ key: 'args', label: '账号额外参数', kind: 'textarea', hint: '附加到托管的启动参数之后。' }],
|
|
74
|
+
prepare: input => ({ command: optionalText(input.command), args: textList(input.args), cwd: optionalText(input.cwd), ...generalResultRules(input) }),
|
|
75
|
+
run: (script, options) => withGeneralResult(script, options, runProcess),
|
|
76
|
+
};
|
|
77
|
+
export const maaFields = [
|
|
78
|
+
{ key: 'projectPath', label: '项目目录', kind: 'hostpath', directory: true, required: true, hint: '包含 interface.json 的 ProjectInterface V2 项目。' },
|
|
79
|
+
{ key: 'controller', label: '控制器', kind: 'select', source: 'maafw.controllers', sourceBy: 'projectPath', hint: '留空时使用项目中首个可用控制器。' },
|
|
80
|
+
{ key: 'resource', label: '资源', kind: 'select', source: 'maafw.resources', sourceBy: 'projectPath', sourceInputs: ['controller'], hint: '留空时使用控制器的首个可用资源。' },
|
|
81
|
+
{ key: 'preset', label: '项目预设', kind: 'select', source: 'maafw.presets', sourceBy: 'projectPath', sourceInputs: ['controller', 'resource'], hint: '使用上游预设的任务顺序和任务选项。下方可自选任务队列。' },
|
|
82
|
+
{ key: 'tasks', label: '任务队列', kind: 'multiselect', source: 'maafw.tasks', sourceBy: 'projectPath', sourceInputs: ['controller', 'resource'], hint: '留空时执行所选预设的任务,或项目默认勾选的任务。' },
|
|
83
|
+
{ key: 'address', label: 'ADB 设备地址' },
|
|
84
|
+
{ key: 'adbPath', label: 'ADB 可执行文件', kind: 'hostpath' },
|
|
85
|
+
{ key: 'windowHandle', label: 'Win32 窗口句柄', kind: 'number' },
|
|
86
|
+
{ key: 'agentPython', label: 'Agent Python(可选)', kind: 'hostpath', hint: '使用默认 Python,或在 MaaFramework 项目管理中准备独立运行环境后选择其解释器。' },
|
|
87
|
+
{ key: 'agentNodeRoot', label: 'Node Agent 环境(可选)', kind: 'hostpath', directory: true, hint: '选择项目管理返回的环境目录。更新项目代码或 npm 锁文件后,请重新准备环境。' },
|
|
88
|
+
{ key: 'nativePython', label: '原生运行器 Python(可选)', kind: 'hostpath', hint: '选择装有与项目库同版本 maafw 绑定的 Python。两项留空时使用随包 Node SDK。' },
|
|
89
|
+
{ key: 'nativeLibraries', label: '项目原生库目录(可选)', kind: 'hostpath', directory: true, hint: '与上面的解释器一并设置。可在项目管理检查绑定与原生库版本。' },
|
|
90
|
+
{ key: 'projectOptions', label: 'ProjectInterface 选项', kind: 'json-object', source: 'maafw.options', sourceBy: 'projectPath', sourceInputs: ['controller', 'resource'] },
|
|
91
|
+
];
|
|
92
|
+
export function maaFieldsFor(adapter) {
|
|
93
|
+
return maaFields.map(field => field.source ? { ...field, source: field.source.replace(/^maafw\./u, `${adapter}.`) } : field);
|
|
94
|
+
}
|
|
95
|
+
export async function prepareMaa(input) {
|
|
96
|
+
const projectPath = optionalText(input.projectPath);
|
|
97
|
+
const controller = optionalText(input.controller) || undefined;
|
|
98
|
+
const resource = optionalText(input.resource) || undefined;
|
|
99
|
+
const preset = optionalText(input.preset) || undefined;
|
|
100
|
+
const tasks = textList(input.tasks);
|
|
101
|
+
const raw = input.projectOptions;
|
|
102
|
+
const agentPython = optionalText(input.agentPython) || undefined;
|
|
103
|
+
const agentNodeRoot = optionalText(input.agentNodeRoot) || undefined;
|
|
104
|
+
if (agentPython && (!isAbsolute(agentPython) || !await stat(agentPython).then(item => item.isFile(), () => false))) {
|
|
105
|
+
throw new Error('请选择可用的 Agent Python 程序绝对路径');
|
|
106
|
+
}
|
|
107
|
+
const nativePython = optionalText(input.nativePython) || undefined;
|
|
108
|
+
const nativeLibraries = optionalText(input.nativeLibraries) || undefined;
|
|
109
|
+
if (nativePython || nativeLibraries)
|
|
110
|
+
await (await import('./maa/native-runtime.js')).nativeRuntimePaths(nativePython, nativeLibraries);
|
|
111
|
+
const projectOptions = typeof raw === 'string' && raw.trim() ? JSON.parse(raw) : typeof raw === 'object' && raw ? raw : undefined;
|
|
112
|
+
if (projectOptions && Array.isArray(projectOptions))
|
|
113
|
+
throw new Error('PI 选项必须为 JSON 对象');
|
|
114
|
+
const { inspectProject, loadProject, planRun } = await import('./maa/project.js');
|
|
115
|
+
const schema = await inspectProject(projectPath);
|
|
116
|
+
if (agentNodeRoot)
|
|
117
|
+
await (await import('./maa/node-agent-path.js')).readNodeAgentEnvironment(agentNodeRoot, schema.projectPath);
|
|
118
|
+
if (projectOptions) {
|
|
119
|
+
for (const option of schema.options) {
|
|
120
|
+
const values = projectOptions[option.name];
|
|
121
|
+
if (!values || typeof values !== 'object' || Array.isArray(values))
|
|
122
|
+
continue;
|
|
123
|
+
if (option.inputs.some(input => input.password && Object.hasOwn(values, input.name)))
|
|
124
|
+
throw new Error('当前版本无法安全保存 MaaFramework 密码选项');
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
if (preset || tasks.length || schema.tasks.some(task => task.defaultCheck) || projectOptions) {
|
|
128
|
+
planRun(await loadProject(projectPath), { projectPath, controller, resource, preset, tasks: tasks.length ? tasks : undefined, options: projectOptions });
|
|
129
|
+
}
|
|
130
|
+
return { projectPath, controller, resource, preset, tasks, projectOptions, agentPython, agentNodeRoot, nativePython, nativeLibraries, address: optionalText(input.address) || undefined,
|
|
131
|
+
adbPath: optionalText(input.adbPath) || undefined, windowHandle: input.windowHandle ? Number(input.windowHandle) : undefined };
|
|
132
|
+
}
|
|
133
|
+
const runMaaProject = async (script, config) => {
|
|
134
|
+
const { runMaaSelected } = await import('./maa/native-runtime.js');
|
|
135
|
+
const tasks = script.tasks;
|
|
136
|
+
await runMaaSelected({ projectPath: optionalText(script.projectPath), controller: optionalText(script.controller) || undefined,
|
|
137
|
+
resource: optionalText(script.resource) || undefined, preset: optionalText(script.preset) || undefined, tasks: tasks?.length ? tasks : undefined,
|
|
138
|
+
adbPath: optionalText(script.adbPath) || undefined, address: optionalText(script.address) || undefined,
|
|
139
|
+
adbServerPort: typeof script.adbServerPort === 'number' ? script.adbServerPort : undefined, agentPython: optionalText(script.agentPython) || undefined,
|
|
140
|
+
agentNodeRoot: optionalText(script.agentNodeRoot) || undefined,
|
|
141
|
+
nativePython: optionalText(script.nativePython) || undefined, nativeLibraries: optionalText(script.nativeLibraries) || undefined,
|
|
142
|
+
windowHandle: script.windowHandle, options: script.projectOptions }, config);
|
|
143
|
+
};
|
|
144
|
+
export const runtimeAdapters = [general, {
|
|
145
|
+
id: 'maafw', title: 'MaaFramework', description: '通过官方 Node SDK 运行 ProjectInterface V2 项目。', group: '通用',
|
|
146
|
+
scriptFields: maaFields, usesPlan: true, prepare: prepareMaa, run: runMaaProject,
|
|
147
|
+
}];
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { adapterFeature } from '../adapters.js';
|
|
2
|
+
import { registerNativeConfiguration } from '../game-plugins/native-config.js';
|
|
3
|
+
import { oknte, oknteNativeConfiguration } from '../game-plugins/oknte.js';
|
|
4
|
+
export default function createFeature({ dataDir }) {
|
|
5
|
+
return adapterFeature(oknte, { icon: new URL('./icons/oknte.png', import.meta.url),
|
|
6
|
+
apply: ctx => registerNativeConfiguration(ctx, dataDir, oknte.id, oknteNativeConfiguration) });
|
|
7
|
+
}
|
|
Binary file
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto';
|
|
2
|
+
import { lstat, readFile, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
export class CredentialVault {
|
|
5
|
+
path;
|
|
6
|
+
namespace;
|
|
7
|
+
pending;
|
|
8
|
+
constructor(dataDir, scope = 'community') {
|
|
9
|
+
this.path = join(dataDir, scope === 'community' ? '.community-key' : '.plugin-config-key');
|
|
10
|
+
this.namespace = scope === 'community' ? 'Cordis MAS community sign-in v1:cloud-genshin' : 'AUTO-MASC plugin configuration v1';
|
|
11
|
+
}
|
|
12
|
+
async load(create) {
|
|
13
|
+
try {
|
|
14
|
+
const info = await lstat(this.path);
|
|
15
|
+
if (!info.isFile() || info.size !== 32 || (process.platform !== 'win32' && (info.mode & 0o077) !== 0)) {
|
|
16
|
+
throw new Error('本机加密密钥文件无效或权限过宽');
|
|
17
|
+
}
|
|
18
|
+
return await readFile(this.path);
|
|
19
|
+
}
|
|
20
|
+
catch (error) {
|
|
21
|
+
if (error.code !== 'ENOENT')
|
|
22
|
+
throw error;
|
|
23
|
+
if (!create)
|
|
24
|
+
throw new Error('找不到本机加密密钥,请重新配置');
|
|
25
|
+
const key = randomBytes(32);
|
|
26
|
+
try {
|
|
27
|
+
await writeFile(this.path, key, { flag: 'wx', mode: 0o600 });
|
|
28
|
+
}
|
|
29
|
+
catch (writeError) {
|
|
30
|
+
if (writeError.code !== 'EEXIST')
|
|
31
|
+
throw writeError;
|
|
32
|
+
return this.load(false);
|
|
33
|
+
}
|
|
34
|
+
return key;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
key(create) {
|
|
38
|
+
this.pending ??= this.load(create).catch(error => { this.pending = undefined; throw error; });
|
|
39
|
+
return this.pending;
|
|
40
|
+
}
|
|
41
|
+
context(id) {
|
|
42
|
+
return Buffer.from(`${this.namespace}:${id}`);
|
|
43
|
+
}
|
|
44
|
+
async seal(id, secret) {
|
|
45
|
+
const nonce = randomBytes(12);
|
|
46
|
+
const cipher = createCipheriv('aes-256-gcm', await this.key(true), nonce);
|
|
47
|
+
cipher.setAAD(this.context(id));
|
|
48
|
+
const data = Buffer.concat([cipher.update(secret, 'utf8'), cipher.final()]);
|
|
49
|
+
return { version: 1, nonce: nonce.toString('base64'), cipher: data.toString('base64'), tag: cipher.getAuthTag().toString('base64') };
|
|
50
|
+
}
|
|
51
|
+
async reveal(id, secret) {
|
|
52
|
+
const key = await this.key(false);
|
|
53
|
+
try {
|
|
54
|
+
if (secret.version !== 1)
|
|
55
|
+
throw new Error('Unrecognized credential');
|
|
56
|
+
const decipher = createDecipheriv('aes-256-gcm', key, Buffer.from(secret.nonce, 'base64'), { authTagLength: 16 });
|
|
57
|
+
decipher.setAAD(this.context(id));
|
|
58
|
+
decipher.setAuthTag(Buffer.from(secret.tag, 'base64'));
|
|
59
|
+
return Buffer.concat([decipher.update(Buffer.from(secret.cipher, 'base64')), decipher.final()]).toString('utf8');
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
throw new Error('无法解密本机配置,请重新配置');
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
@@ -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
|
+
}
|