@auto-mas/auto-mas-plugin-adapter-maaend 0.0.0-stage → 0.1.1

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.
@@ -0,0 +1,251 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { createHash, randomUUID } from 'node:crypto';
3
+ import { lstat, open, readdir, realpath, rename, unlink, writeFile } from 'node:fs/promises';
4
+ import { isAbsolute, join, relative, sep } from 'node:path';
5
+ import { CredentialVault } from '../community/vault.js';
6
+ import { field, store, text, ui } from '../features.js';
7
+ import { assertWindowsProgramIdle, windowsOnly } from './native.js';
8
+ const collection = 'native-config-backups';
9
+ const maxFiles = 256;
10
+ const maxBytes = 8 * 1024 * 1024;
11
+ const fileName = /^[^/\\:*?"<>|\u0000-\u001f]+\.json$/iu;
12
+ const explicitFileName = /^[^/\\:*?"<>|\u0000-\u001f]+\.(?:json|yaml|yml)$/iu;
13
+ function contained(root, candidate) {
14
+ const rel = relative(root, candidate);
15
+ if (!rel || rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel))
16
+ throw new Error('原生配置目录必须位于已保存的安装目录内');
17
+ return rel;
18
+ }
19
+ async function configDirectory(source, allowMissing = false) {
20
+ const root = await realpath(source.root);
21
+ const rel = contained(root, source.directory);
22
+ let location = root;
23
+ for (const part of rel.split(sep)) {
24
+ location = join(location, part);
25
+ const info = await lstat(location).catch(error => {
26
+ if (allowMissing && error.code === 'ENOENT')
27
+ return undefined;
28
+ throw error;
29
+ });
30
+ if (!info)
31
+ return undefined;
32
+ if (!info.isDirectory() || info.isSymbolicLink())
33
+ throw new Error('原生配置目录路径无效或含重定向');
34
+ }
35
+ return location;
36
+ }
37
+ function validateName(name, targets) {
38
+ if (!(targets ? explicitFileName : fileName).test(name) || name.length > 160 || name.startsWith('.')
39
+ || name.startsWith(' ') || name !== name.trim() || (targets && !targets.includes(name)))
40
+ throw new Error('原生配置备份的文件名无效');
41
+ }
42
+ function targetsFor(source) { return source.files ?? (source.file ? [source.file] : undefined); }
43
+ async function configFiles(directory, targets) {
44
+ const entries = await readdir(directory, { withFileTypes: true });
45
+ return entries.filter(entry => targets ? targets.includes(entry.name) : fileName.test(entry.name));
46
+ }
47
+ async function readContent(directory, targets) {
48
+ for (const filename of targets ?? [])
49
+ validateName(filename, targets);
50
+ const files = await configFiles(directory, targets);
51
+ if (files.length > maxFiles)
52
+ throw new Error('原生配置文件数量超过可备份范围');
53
+ const content = Object.create(null);
54
+ let total = 0;
55
+ for (const entry of files) {
56
+ validateName(entry.name, targets);
57
+ if (!entry.isFile() || entry.isSymbolicLink())
58
+ throw new Error('原生配置含非普通文件');
59
+ const path = join(directory, entry.name);
60
+ const info = await lstat(path);
61
+ if (info.isSymbolicLink() || !info.isFile() || info.size > maxBytes - total)
62
+ throw new Error('原生配置含链接或超过可备份大小');
63
+ const handle = await open(path, 'r');
64
+ try {
65
+ const body = await handle.readFile();
66
+ total += body.length;
67
+ if (total > maxBytes)
68
+ throw new Error('原生配置超过可备份大小');
69
+ content[entry.name] = body.toString('base64');
70
+ }
71
+ finally {
72
+ await handle.close();
73
+ }
74
+ }
75
+ return content;
76
+ }
77
+ export async function readNativeConfigurationFile(source) {
78
+ const directory = await configDirectory(source);
79
+ const content = directory && (await readContent(directory, [source.file]))[source.file];
80
+ if (content === undefined)
81
+ throw new Error('原生配置文件不存在');
82
+ return Buffer.from(content, 'base64').toString('utf8');
83
+ }
84
+ function decode(snapshot, targets) {
85
+ const parsed = JSON.parse(snapshot);
86
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
87
+ throw new Error('原生配置备份格式无效');
88
+ const entries = Object.entries(parsed);
89
+ if (entries.length > maxFiles)
90
+ throw new Error('原生配置备份文件数量无效');
91
+ let total = 0;
92
+ for (const [name, value] of entries) {
93
+ validateName(name, targets);
94
+ if (typeof value !== 'string' || !/^[A-Za-z0-9+/]*={0,2}$/u.test(value) || value.length % 4 !== 0)
95
+ throw new Error('原生配置备份内容无效');
96
+ total += Buffer.byteLength(value, 'base64');
97
+ if (total > maxBytes)
98
+ throw new Error('原生配置备份大小无效');
99
+ }
100
+ return Object.fromEntries(entries);
101
+ }
102
+ async function replaceFile(directory, name, content) {
103
+ const destination = join(directory, name);
104
+ const temp = join(directory, `.masc-${randomUUID()}.tmp`);
105
+ const current = await lstat(destination).catch(error => {
106
+ if (error.code === 'ENOENT')
107
+ return undefined;
108
+ throw error;
109
+ });
110
+ if (current && (!current.isFile() || current.isSymbolicLink()))
111
+ throw new Error('目标配置不是普通文件');
112
+ await writeFile(temp, Buffer.from(content, 'base64'), { flag: 'wx', mode: current?.mode ?? 0o600 });
113
+ try {
114
+ await rename(temp, destination);
115
+ }
116
+ catch (error) {
117
+ await unlink(temp).catch(() => { });
118
+ throw error;
119
+ }
120
+ }
121
+ export function nativeConfigurationComponents(adapter, script, options = {}) {
122
+ const fixed = { scriptId: script.id };
123
+ return [
124
+ { type: 'metrics', title: '检测原生配置', query: `${adapter}.native.info`, queryInput: fixed },
125
+ ...(options.open === false ? [] : [{ type: 'form', title: '原生配置', action: `${adapter}.native.open`, fixed,
126
+ fields: options.confirmOpen ? [field('confirmed', options.confirmOpen, { kind: 'boolean' })] : [], submitLabel: '打开原生配置窗口', result: true }]),
127
+ { type: 'form', title: '备份原生配置', action: `${adapter}.native.backup`, fixed, fields: [], submitLabel: '保存原生配置备份', result: true },
128
+ { type: 'form', title: '恢复原生配置', action: `${adapter}.native.restore`, fixed, submitLabel: '恢复所选备份', result: true,
129
+ fields: [field('backupId', '备份', { kind: 'select', required: true, source: `${adapter}.native.snapshots`, sourceBy: 'scriptId' }),
130
+ field('confirmed', '确认覆盖所选备份中的同名配置文件', { kind: 'boolean' })] },
131
+ ];
132
+ }
133
+ export function registerNativeConfiguration(ctx, dataDir, adapter, resolve) {
134
+ const vault = new CredentialVault(dataDir, 'plugin');
135
+ ctx.inject(['mas.ui', 'mas.scripts', 'mas.runner', 'mas.store'], scope => {
136
+ const scripts = scope.get('mas.scripts');
137
+ const runner = scope.get('mas.runner');
138
+ const db = store(scope);
139
+ const sourceFor = (input) => {
140
+ const script = scripts.get(text(input, 'scriptId', '托管 ID'));
141
+ if (!script || script.adapter !== adapter)
142
+ throw new Error('未找到对应专项托管');
143
+ return resolve(script.adapterConfig ?? {});
144
+ };
145
+ async function ownerFor(source) {
146
+ const root = await realpath(source.root);
147
+ const location = contained(root, source.directory);
148
+ const key = JSON.stringify([adapter, root.toLowerCase(), location.toLowerCase(), targetsFor(source) ?? []]);
149
+ return createHash('sha256').update(key).digest('hex');
150
+ }
151
+ async function writeSnapshot(owner, content) {
152
+ const id = randomUUID();
153
+ const date = new Date().toISOString();
154
+ const secret = await vault.seal(`${collection}:${id}`, JSON.stringify(content));
155
+ return db.put(collection, { id, owner, date, count: Object.keys(content).length, secret });
156
+ }
157
+ async function ensureIdle(source) {
158
+ const reason = windowsOnly();
159
+ if (reason)
160
+ throw new Error(reason);
161
+ for (const command of new Set([source.command, ...source.additionalPrograms ?? []])) {
162
+ await assertWindowsProgramIdle(command, AbortSignal.timeout(10_000));
163
+ }
164
+ }
165
+ async function useSource(input, action) {
166
+ const source = await sourceFor(input);
167
+ const release = runner.claimInstallation(source.root);
168
+ try {
169
+ await ensureIdle(source);
170
+ return await action(source);
171
+ }
172
+ finally {
173
+ release();
174
+ }
175
+ }
176
+ ui(scope).scope(scope, undefined, { [`${adapter}.native.info`]: async (input) => {
177
+ const source = await sourceFor(input);
178
+ const directory = await configDirectory(source, true);
179
+ const files = directory ? await configFiles(directory, targetsFor(source)) : [];
180
+ return [{ label: '配置目录', value: source.directory }, { label: '配置文件', value: files.length,
181
+ detail: files.length ? files.slice(0, 8).map(entry => entry.name).join('、') : '等待在原生程序中首次保存配置' }];
182
+ }, [`${adapter}.native.snapshots`]: async (input) => {
183
+ const owner = await ownerFor(await sourceFor(input));
184
+ return db.list(collection).filter(entry => entry.owner === owner && entry.count > 0).reverse()
185
+ .map(entry => ({ value: entry.id, label: `${entry.date.replace('T', ' ').replace(/\.\d+Z$/u, ' UTC')} · ${entry.count} 项` }));
186
+ } }, {
187
+ [`${adapter}.native.open`]: async (input) => {
188
+ const source = await sourceFor(input);
189
+ if (source.open === false)
190
+ throw new Error('此专项没有独立的原生配置窗口入口');
191
+ if (source.confirmOpen && input.confirmed !== true)
192
+ throw new Error('请确认允许按原生设置启动程序');
193
+ const release = runner.claimInstallation(source.root);
194
+ try {
195
+ await ensureIdle(source);
196
+ const directory = await configDirectory(source, true);
197
+ if (directory) {
198
+ const content = await readContent(directory, targetsFor(source));
199
+ if (Object.keys(content).length)
200
+ await writeSnapshot(await ownerFor(source), content);
201
+ }
202
+ const child = spawn(source.command, source.args ?? [], { cwd: source.cwd ?? source.root, shell: false,
203
+ detached: true, stdio: 'ignore' });
204
+ child.once('close', release);
205
+ await new Promise((accept, reject) => { child.once('spawn', accept); child.once('error', reject); });
206
+ child.unref();
207
+ return { message: '已在后端主机打开原生配置,关闭窗口后可恢复调度' };
208
+ }
209
+ catch (error) {
210
+ release();
211
+ throw error;
212
+ }
213
+ },
214
+ [`${adapter}.native.backup`]: input => useSource(input, async (source) => {
215
+ const directory = await configDirectory(source);
216
+ const content = await readContent(directory, targetsFor(source));
217
+ if (!Object.keys(content).length)
218
+ throw new Error('未找到可备份的原生配置,请先通过原生窗口保存设置');
219
+ const snapshot = await writeSnapshot(await ownerFor(source), content);
220
+ return { 备份时间: snapshot.date, 配置项: snapshot.count };
221
+ }),
222
+ [`${adapter}.native.restore`]: input => useSource(input, async (source) => {
223
+ if (input.confirmed !== true)
224
+ throw new Error('请确认覆盖所选备份中的同名配置文件');
225
+ const owner = await ownerFor(source);
226
+ const backup = db.get(collection, text(input, 'backupId', '备份'));
227
+ if (!backup || backup.owner !== owner || !backup.count)
228
+ throw new Error('该备份不属于当前原生配置目录');
229
+ const directory = (await configDirectory(source));
230
+ const before = await readContent(directory, targetsFor(source));
231
+ const snapshot = decode(await vault.reveal(`${collection}:${backup.id}`, backup.secret), targetsFor(source));
232
+ const preserved = await writeSnapshot(owner, before);
233
+ const published = [];
234
+ try {
235
+ for (const [name, content] of Object.entries(snapshot)) {
236
+ await replaceFile(directory, name, content);
237
+ published.push(name);
238
+ }
239
+ }
240
+ catch (error) {
241
+ const rolledBack = await Promise.allSettled(published.map(name => Object.hasOwn(before, name)
242
+ ? replaceFile(directory, name, before[name]) : unlink(join(directory, name))));
243
+ if (rolledBack.some(result => result.status === 'rejected'))
244
+ throw new Error(`恢复中断,部分配置未能回退。操作前备份时间为 ${preserved.date}`);
245
+ throw new Error('恢复失败,已撤回本次写入', { cause: error });
246
+ }
247
+ return { 已恢复: published.length, 操作前备份时间: preserved.date };
248
+ }),
249
+ });
250
+ });
251
+ }
@@ -0,0 +1,207 @@
1
+ import { open, readdir, realpath, stat } from 'node:fs/promises';
2
+ import { basename, dirname, isAbsolute, join } from 'node:path';
3
+ import { StringDecoder } from 'node:string_decoder';
4
+ import { execFile, spawn } from 'node:child_process';
5
+ import { runProcess } from '../execution.js';
6
+ export const executableField = (label) => ({ key: 'command', label, kind: 'hostpath', required: true });
7
+ export const directoryField = (key, label) => ({ key, label, kind: 'hostpath', directory: true, required: true });
8
+ export const windowsOnly = () => process.platform === 'win32' ? undefined : '此执行器需要 Windows 桌面会话';
9
+ export function optionalText(input, key) {
10
+ const value = input[key];
11
+ if (value === undefined || value === null)
12
+ return '';
13
+ if (typeof value !== 'string' || /[\u0000-\u001f]/u.test(value))
14
+ throw new Error(`${key} 必须是单行文本`);
15
+ return value.trim();
16
+ }
17
+ export function requiredText(input, key, label) {
18
+ const value = optionalText(input, key);
19
+ if (!value)
20
+ throw new Error(`请填写${label}`);
21
+ return value;
22
+ }
23
+ export function configName(value, label) {
24
+ if (!value || value.startsWith('-') || value.endsWith('.') || /[/\\:*?"<>|]/u.test(value)) {
25
+ throw new Error(`${label}必须是配置名称`);
26
+ }
27
+ return value;
28
+ }
29
+ export async function existingPath(path, label, directory = false) {
30
+ if (!isAbsolute(path))
31
+ throw new Error(`${label}必须是绝对路径`);
32
+ const resolved = await realpath(path).catch(error => {
33
+ if (error.code === 'ENOENT' || error.code === 'ENOTDIR')
34
+ throw new Error(`${label}不存在`);
35
+ throw error;
36
+ });
37
+ const info = await stat(resolved);
38
+ if (directory ? !info.isDirectory() : !info.isFile())
39
+ throw new Error(`${label}类型有误`);
40
+ return resolved;
41
+ }
42
+ export async function prepareExecutable(input, label, names) {
43
+ const command = await existingPath(requiredText(input, 'command', label), label);
44
+ if (!names.includes(basename(command).toLowerCase()))
45
+ throw new Error(`请选择 ${names.join(' 或 ')} 文件`);
46
+ return { command, installRoot: dirname(command) };
47
+ }
48
+ export async function assertWindowsProgramIdle(command, signal) {
49
+ signal.throwIfAborted();
50
+ const pidList = await new Promise((resolve, reject) => execFile('powershell.exe', [
51
+ '-NoProfile', '-NonInteractive', '-Command', [
52
+ '$ErrorActionPreference = "Stop"',
53
+ '$name = [System.IO.Path]::GetFileNameWithoutExtension($env:MAS_NATIVE_PROGRAM)',
54
+ 'Get-Process | Where-Object { $_.ProcessName -eq $name -and (!$_.Path -or $_.Path -eq $env:MAS_NATIVE_PROGRAM) } | Select-Object -ExpandProperty Id',
55
+ ].join('\n'),
56
+ ], { env: { ...process.env, MAS_NATIVE_PROGRAM: command }, windowsHide: true, signal, timeout: 8000 }, (error, stdout) => {
57
+ if (error)
58
+ reject(new Error(`无法检查 ${basename(command)} 是否已打开`, { cause: error }));
59
+ else
60
+ resolve(stdout);
61
+ }));
62
+ if (pidList.trim())
63
+ throw new Error(`请先关闭正在运行的 ${basename(command)}`);
64
+ }
65
+ export async function openNativeEditor(command, cwd, close) {
66
+ const unavailable = windowsOnly();
67
+ if (unavailable)
68
+ throw new Error(unavailable);
69
+ await assertWindowsProgramIdle(command, AbortSignal.timeout(10_000));
70
+ const process = spawn(command, [], { cwd, detached: true, stdio: 'ignore', shell: false });
71
+ if (close)
72
+ process.once('close', close);
73
+ await new Promise((resolve, reject) => {
74
+ process.once('spawn', resolve);
75
+ process.once('error', reject);
76
+ });
77
+ process.unref();
78
+ }
79
+ async function followLogs(spec, consume) {
80
+ const cursors = new Map();
81
+ async function scan(baseline) {
82
+ const entries = await readdir(spec.directory, { withFileTypes: true }).catch(error => {
83
+ if (error.code === 'ENOENT')
84
+ return [];
85
+ throw error;
86
+ });
87
+ for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
88
+ if (!entry.isFile() || !spec.filenames.test(entry.name))
89
+ continue;
90
+ const handle = await open(join(spec.directory, entry.name), 'r').catch(error => {
91
+ if (error.code === 'ENOENT')
92
+ return undefined;
93
+ throw error;
94
+ });
95
+ if (!handle)
96
+ continue;
97
+ try {
98
+ const { dev, ino, size } = await handle.stat();
99
+ const id = `${dev}:${ino}`;
100
+ const previous = cursors.get(entry.name);
101
+ const cursor = previous?.id === id && previous.offset <= size ? previous : {
102
+ id, offset: baseline ? size : 0, decoder: new StringDecoder('utf8'), partial: '',
103
+ };
104
+ cursors.set(entry.name, cursor);
105
+ const buffer = Buffer.allocUnsafe(64 * 1024);
106
+ while (cursor.offset < size) {
107
+ const { bytesRead } = await handle.read(buffer, 0, Math.min(buffer.length, size - cursor.offset), cursor.offset);
108
+ if (!bytesRead)
109
+ break;
110
+ cursor.offset += bytesRead;
111
+ const lines = (cursor.partial + cursor.decoder.write(buffer.subarray(0, bytesRead))).split('\n');
112
+ cursor.partial = (lines.pop() ?? '').slice(-16000);
113
+ for (const line of lines)
114
+ consume(line.replace(/\r$/u, ''));
115
+ }
116
+ }
117
+ finally {
118
+ await handle.close();
119
+ }
120
+ }
121
+ }
122
+ await scan(true);
123
+ return async (final = false) => {
124
+ await scan(false);
125
+ if (final)
126
+ for (const cursor of cursors.values()) {
127
+ const remainder = cursor.partial + cursor.decoder.end();
128
+ if (remainder)
129
+ consume(remainder.replace(/\r$/u, ''));
130
+ }
131
+ };
132
+ }
133
+ export async function runObservedProcess(script, options, files, observation, closeOnCompletion = false) {
134
+ let completedAt;
135
+ const completion = new AbortController();
136
+ const signal = closeOnCompletion ? AbortSignal.any([options.signal, completion.signal]) : options.signal;
137
+ const consume = (line, source) => {
138
+ options.log(line);
139
+ observation.consume(line, source);
140
+ if (observation.complete)
141
+ completedAt ??= Date.now();
142
+ };
143
+ const scan = await followLogs(files, line => consume(line, 'file'));
144
+ let pending;
145
+ let logError;
146
+ const interval = setInterval(() => {
147
+ if (pending || logError)
148
+ return;
149
+ pending = scan().then(() => {
150
+ if (closeOnCompletion && completedAt !== undefined && Date.now() - completedAt >= 1500) {
151
+ completion.abort(new Error('上游任务已结束'));
152
+ }
153
+ }).catch(error => { logError = error; }).finally(() => { pending = undefined; });
154
+ }, 500);
155
+ let processError;
156
+ try {
157
+ await runProcess(script, { ...options, signal, log: line => consume(line, 'process') });
158
+ }
159
+ catch (error) {
160
+ processError = error;
161
+ }
162
+ finally {
163
+ clearInterval(interval);
164
+ await pending;
165
+ }
166
+ options.signal.throwIfAborted();
167
+ if (logError)
168
+ throw logError;
169
+ await scan(true);
170
+ observation.finish(processError === completion.signal.reason ? undefined : processError);
171
+ }
172
+ export function nativeAdapter(builder) {
173
+ return async (script, options) => {
174
+ options.signal.throwIfAborted();
175
+ const launch = await builder(script.adapterConfig ?? {}, script.accountConfig ?? {});
176
+ const { logs, ...command } = launch;
177
+ const processScript = { ...script, ...command, env: { ...script.env, ...command.env } };
178
+ if (!logs)
179
+ return runProcess(processScript, options);
180
+ let success = false;
181
+ let terminal = !logs.terminal;
182
+ let failure;
183
+ return runObservedProcess(processScript, options, logs, {
184
+ consume(line, source) {
185
+ if (source !== 'file')
186
+ return;
187
+ if (logs.success.test(line)) {
188
+ success = true;
189
+ if (logs.successClearsFailure)
190
+ failure = undefined;
191
+ }
192
+ terminal ||= Boolean(logs.terminal?.test(line));
193
+ if (logs.failure?.test(line))
194
+ failure = line.slice(0, 400);
195
+ },
196
+ get complete() { return success && terminal; },
197
+ finish(processError) {
198
+ if (failure)
199
+ throw new Error(failure);
200
+ if (processError)
201
+ throw processError;
202
+ if (!success || !terminal)
203
+ throw new Error('上游日志未报告完成,请查看上游配置与本次运行日志');
204
+ },
205
+ }, logs.closeOnCompletion);
206
+ };
207
+ }
@@ -0,0 +1,38 @@
1
+ import { readdir } from 'node:fs/promises';
2
+ import { extname } from 'node:path';
3
+ export function profileOption(key, label, source, scope, required = false) {
4
+ return { key, label, kind: 'select', source, sourceBy: scope, required };
5
+ }
6
+ export function scopedProfileOptions(ctx, adapter, name, find) {
7
+ ctx.inject(['mas.ui', 'mas.scripts'], scope => {
8
+ const scripts = scope.get('mas.scripts');
9
+ const ui = scope.get('mas.ui');
10
+ ui.scope(scope, undefined, { [name]: input => {
11
+ if (typeof input.scriptId !== 'string')
12
+ return find(input);
13
+ const script = scripts.get(input.scriptId);
14
+ if (!script || script.adapter !== adapter)
15
+ throw new Error('未找到对应专项托管');
16
+ return find(script.adapterConfig ?? {});
17
+ } });
18
+ });
19
+ }
20
+ export async function profilesIn(directory, extensions = ['.json']) {
21
+ const profiles = new Map();
22
+ const entries = await readdir(directory, { withFileTypes: true }).catch(error => {
23
+ if (error.code === 'ENOENT')
24
+ return [];
25
+ throw error;
26
+ });
27
+ for (const entry of entries) {
28
+ const ext = extname(entry.name);
29
+ if (!entry.isFile() || !extensions.includes(ext))
30
+ continue;
31
+ const name = entry.name.slice(0, -ext.length);
32
+ if (!name.trim() || name !== name.trim() || name.startsWith('-') || name.endsWith('.') || /[\u0000-\u001f/\\:*?"<>|]/u.test(name))
33
+ continue;
34
+ profiles.set(name, (profiles.get(name) ?? 0) + 1);
35
+ }
36
+ return [...profiles].filter(([, count]) => count === 1).sort(([a], [b]) => a.localeCompare(b))
37
+ .map(([name]) => ({ value: name, label: name }));
38
+ }
@@ -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
+ }
@@ -0,0 +1,97 @@
1
+ import { fork } from 'node:child_process';
2
+ import { fileURLToPath } from 'node:url';
3
+ import { adbEnvironment } from '../emulator-managers.js';
4
+ import { readLines, terminateTree } from './process.js';
5
+ export { inspectProject } from './project.js';
6
+ const workerPath = fileURLToPath(new URL('./worker.js', import.meta.url));
7
+ export async function runMaa(input, options) {
8
+ const { signal, log, started, launchProcess } = options;
9
+ signal.throwIfAborted();
10
+ const env = { ...adbEnvironment(input.adbServerPort), ...(process.versions.electron ? { ELECTRON_RUN_AS_NODE: '1' } : {}) };
11
+ if (launchProcess) {
12
+ await launchProcess({ command: process.execPath, args: [workerPath, '--mas-stdio'], env,
13
+ stdin: JSON.stringify({ type: 'run', input }) }, options);
14
+ return;
15
+ }
16
+ await new Promise((resolve, reject) => {
17
+ const worker = fork(workerPath, [], {
18
+ detached: process.platform !== 'win32',
19
+ env: { ...process.env, ...env },
20
+ execArgv: [],
21
+ windowsHide: true,
22
+ stdio: ['ignore', 'pipe', 'pipe', 'ipc'],
23
+ });
24
+ const processes = new Set();
25
+ let result;
26
+ let workerError;
27
+ let stopTimer;
28
+ let deadline;
29
+ let settled = false;
30
+ function abort() {
31
+ if (worker.connected)
32
+ worker.send({ type: 'stop' }, () => undefined);
33
+ stopTimer = setTimeout(() => {
34
+ log('MaaFramework stop deadline reached. Terminating the worker and its project processes.');
35
+ if (worker.pid)
36
+ void terminateTree(worker.pid);
37
+ for (const pid of processes)
38
+ void terminateTree(pid);
39
+ deadline = setTimeout(() => {
40
+ if (worker.connected)
41
+ worker.disconnect();
42
+ worker.stdout?.destroy();
43
+ worker.stderr?.destroy();
44
+ worker.unref();
45
+ void finish(null, null);
46
+ }, 2_000);
47
+ }, 5_000);
48
+ }
49
+ async function finish(code, exitSignal) {
50
+ if (settled)
51
+ return;
52
+ settled = true;
53
+ clearTimeout(stopTimer);
54
+ clearTimeout(deadline);
55
+ signal.removeEventListener('abort', abort);
56
+ await Promise.all([...processes].map(terminateTree));
57
+ if (signal.aborted)
58
+ reject(signal.reason);
59
+ else if (result?.error)
60
+ reject(result.error);
61
+ else if (workerError)
62
+ reject(workerError);
63
+ else if (code === 0 && result)
64
+ resolve();
65
+ else
66
+ reject(new Error(`MaaFramework worker exited before completing (${exitSignal ?? code ?? 'unknown status'}).`));
67
+ }
68
+ readLines(worker.stdout, log);
69
+ readLines(worker.stderr, (line) => log(`[MaaFramework stderr] ${line}`));
70
+ worker.on('message', (message) => {
71
+ if (message.type === 'process-started')
72
+ processes.add(message.pid);
73
+ if (message.type === 'process-exited')
74
+ processes.delete(message.pid);
75
+ if (message.type === 'failed')
76
+ result = { error: new Error(message.error) };
77
+ if (message.type === 'done')
78
+ result = {};
79
+ });
80
+ worker.once('error', (error) => { workerError = error; });
81
+ worker.once('spawn', () => {
82
+ try {
83
+ started?.('MaaFramework Worker 已启动');
84
+ }
85
+ catch (error) {
86
+ workerError = error instanceof Error ? error : new Error(String(error));
87
+ abort();
88
+ }
89
+ });
90
+ worker.once('close', (code, exitSignal) => void finish(code, exitSignal));
91
+ worker.send({ type: 'run', input }, (error) => {
92
+ if (error)
93
+ workerError = error;
94
+ });
95
+ signal.addEventListener('abort', abort, { once: true });
96
+ });
97
+ }