@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.
@@ -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,277 @@
1
+ export const blocklyCompilerRevision = 1;
2
+ const arithmetic = new Set(['ADD', 'MINUS', 'MULTIPLY', 'DIVIDE', 'POWER']);
3
+ const comparisons = new Set(['EQ', 'NEQ', 'LT', 'LTE', 'GT', 'GTE']);
4
+ const reservedKeys = new Set(['__proto__', 'prototype', 'constructor']);
5
+ const maxWorkspaceBytes = 256 * 1024;
6
+ const maxDepth = 40;
7
+ const maxBlocks = 300;
8
+ const maxLogLength = 16_000;
9
+ const nullValue = () => ({ kind: 'literal', value: null });
10
+ function invalid(message) { throw new Error(message); }
11
+ function record(value) {
12
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : {};
13
+ }
14
+ export function copyBlocklyWorkspace(value) {
15
+ try {
16
+ if (record(value) !== value)
17
+ throw new Error();
18
+ const encoded = JSON.stringify(value);
19
+ if (Buffer.byteLength(encoded) > maxWorkspaceBytes)
20
+ throw new Error();
21
+ return JSON.parse(encoded);
22
+ }
23
+ catch {
24
+ return invalid('Blockly 工作区必须是 256 KiB 以内的 JSON 对象');
25
+ }
26
+ }
27
+ function visitBudget() {
28
+ let count = 0;
29
+ return (depth) => {
30
+ if (depth > maxDepth || ++count > maxBlocks)
31
+ invalid('积木过多或嵌套过深');
32
+ };
33
+ }
34
+ function safeKey(value, label) {
35
+ if (typeof value !== 'string' || !value || value.length > 128 || /[\x00-\x1f\x7f]/u.test(value) || reservedKeys.has(value)) {
36
+ return invalid(`${label}无效`);
37
+ }
38
+ return value;
39
+ }
40
+ function pathParts(value) {
41
+ if (!Array.isArray(value) || value.length < 1 || value.length > 24)
42
+ return invalid('数据路径无效');
43
+ return value.map(part => safeKey(part, '数据路径'));
44
+ }
45
+ function jsonValue(value, depth = 0) {
46
+ if (depth > maxDepth)
47
+ return invalid('JSON 值嵌套过深');
48
+ if (value === null || typeof value === 'boolean' || typeof value === 'string')
49
+ return value;
50
+ if (typeof value === 'number' && Number.isFinite(value))
51
+ return value;
52
+ if (Array.isArray(value))
53
+ return value.map(item => jsonValue(item, depth + 1));
54
+ if (record(value) === value)
55
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, jsonValue(item, depth + 1)]));
56
+ return invalid('积木值必须是有效 JSON');
57
+ }
58
+ function operator(value, allowed, label) {
59
+ if (typeof value !== 'string' || !allowed.has(value))
60
+ return invalid(`${label}无效`);
61
+ return value;
62
+ }
63
+ export function compileBlocklyWorkspace(raw) {
64
+ const workspace = copyBlocklyWorkspace(raw);
65
+ const blocks = record(workspace.blocks);
66
+ if (blocks.languageVersion !== 0 || !Array.isArray(blocks.blocks) || blocks.blocks.length !== 1) {
67
+ return invalid('请连接一条完整的语句积木链');
68
+ }
69
+ const check = visitBudget();
70
+ function argument(block, name) {
71
+ const source = record(record(block.inputs)[name]);
72
+ return source.block ?? source.shadow;
73
+ }
74
+ function value(source, depth) {
75
+ if (source === undefined)
76
+ return invalid('请连接积木所需的输入');
77
+ check(depth);
78
+ const block = record(source);
79
+ const fields = record(block.fields);
80
+ const read = (name) => value(argument(block, name), depth + 1);
81
+ switch (block.type) {
82
+ case 'mas_input': return { kind: 'input' };
83
+ case 'text':
84
+ if (typeof fields.TEXT !== 'string')
85
+ return invalid('文本积木内容无效');
86
+ return { kind: 'literal', value: fields.TEXT };
87
+ case 'math_number':
88
+ if (typeof fields.NUM !== 'number' || !Number.isFinite(fields.NUM))
89
+ return invalid('数字积木内容无效');
90
+ return { kind: 'literal', value: fields.NUM };
91
+ case 'logic_boolean':
92
+ if (fields.BOOL !== 'TRUE' && fields.BOOL !== 'FALSE')
93
+ return invalid('布尔积木内容无效');
94
+ return { kind: 'literal', value: fields.BOOL === 'TRUE' };
95
+ case 'logic_null': return nullValue();
96
+ case 'mas_json': {
97
+ if (typeof fields.JSON !== 'string')
98
+ return invalid('请输入 JSON 值');
99
+ try {
100
+ return { kind: 'literal', value: jsonValue(JSON.parse(fields.JSON)) };
101
+ }
102
+ catch {
103
+ return invalid('JSON 积木内容无效');
104
+ }
105
+ }
106
+ case 'mas_path': {
107
+ const base = argument(block, 'VALUE');
108
+ const path = pathParts(typeof fields.PATH === 'string' ? fields.PATH.split('.') : undefined);
109
+ return { kind: 'path', base: base === undefined ? { kind: 'input' } : value(base, depth + 1), path };
110
+ }
111
+ case 'mas_object': {
112
+ const base = argument(block, 'BASE');
113
+ return { kind: 'object', base: base === undefined ? { kind: 'literal', value: {} } : value(base, depth + 1),
114
+ key: safeKey(fields.KEY, '对象字段名称'), value: read('VALUE') };
115
+ }
116
+ case 'lists_create_with': {
117
+ const state = record(block.extraState);
118
+ const count = state.itemCount ?? Object.keys(record(block.inputs)).length;
119
+ if (typeof count !== 'number' || !Number.isSafeInteger(count) || count < 0 || count > maxBlocks)
120
+ return invalid('列表积木大小无效');
121
+ return { kind: 'array', items: Array.from({ length: count }, (_, index) => {
122
+ const item = argument(block, `ADD${index}`);
123
+ return item === undefined ? nullValue() : value(item, depth + 1);
124
+ }) };
125
+ }
126
+ case 'math_arithmetic': return { kind: 'math', op: operator(fields.OP, arithmetic, '运算符'), left: read('A'), right: read('B') };
127
+ case 'logic_compare': return { kind: 'compare', op: operator(fields.OP, comparisons, '比较符'), left: read('A'), right: read('B') };
128
+ default: return invalid('遇到不支持的值积木');
129
+ }
130
+ }
131
+ function chain(source, depth) {
132
+ const statements = [];
133
+ for (let current = source; current !== undefined;) {
134
+ check(depth);
135
+ const block = record(current);
136
+ switch (block.type) {
137
+ case 'mas_log':
138
+ statements.push({ kind: 'log', value: value(argument(block, 'VALUE'), depth + 1) });
139
+ break;
140
+ case 'mas_return':
141
+ statements.push({ kind: 'return', value: value(argument(block, 'VALUE'), depth + 1) });
142
+ break;
143
+ case 'mas_fail':
144
+ statements.push({ kind: 'fail', value: value(argument(block, 'VALUE'), depth + 1) });
145
+ break;
146
+ case 'controls_if': {
147
+ const extra = record(block.extraState);
148
+ const elseIf = extra.elseIfCount ?? 0;
149
+ if (typeof elseIf !== 'number' || !Number.isSafeInteger(elseIf) || elseIf < 0 || elseIf > 32)
150
+ return invalid('条件积木分支数无效');
151
+ const branches = Array.from({ length: elseIf + 1 }, (_, index) => ({
152
+ condition: value(argument(block, `IF${index}`), depth + 1), body: chain(argument(block, `DO${index}`), depth + 1),
153
+ }));
154
+ statements.push({ kind: 'if', branches, otherwise: chain(argument(block, 'ELSE'), depth + 1) });
155
+ break;
156
+ }
157
+ default: return invalid('遇到不支持的语句积木');
158
+ }
159
+ current = record(block.next).block;
160
+ }
161
+ return statements;
162
+ }
163
+ return chain(blocks.blocks[0], 0);
164
+ }
165
+ export function validateBlocklyProgram(raw) {
166
+ const check = visitBudget();
167
+ function value(source, depth) {
168
+ check(depth);
169
+ const node = record(source);
170
+ const read = (key) => value(node[key], depth + 1);
171
+ switch (node.kind) {
172
+ case 'literal': return { kind: 'literal', value: jsonValue(node.value) };
173
+ case 'input': return { kind: 'input' };
174
+ case 'path': return { kind: 'path', base: read('base'), path: pathParts(node.path) };
175
+ case 'object': return { kind: 'object', base: read('base'), key: safeKey(node.key, '对象字段名称'), value: read('value') };
176
+ case 'array': return { kind: 'array', items: Array.isArray(node.items) ? node.items.map(item => value(item, depth + 1)) : invalid('节点列表无效') };
177
+ case 'math': return { kind: 'math', op: operator(node.op, arithmetic, '运算符'), left: read('left'), right: read('right') };
178
+ case 'compare': return { kind: 'compare', op: operator(node.op, comparisons, '比较符'), left: read('left'), right: read('right') };
179
+ default: return invalid('节点包含不支持的值');
180
+ }
181
+ }
182
+ function statements(source, depth) {
183
+ if (!Array.isArray(source))
184
+ return invalid('节点的语句列表无效');
185
+ return source.map(statement => {
186
+ check(depth);
187
+ const node = record(statement);
188
+ if (node.kind === 'log' || node.kind === 'return' || node.kind === 'fail')
189
+ return { kind: node.kind, value: value(node.value, depth + 1) };
190
+ if (node.kind === 'if' && Array.isArray(node.branches) && node.branches.length > 0 && node.branches.length <= 33) {
191
+ return { kind: 'if', branches: node.branches.map(source => {
192
+ const branch = record(source);
193
+ return { condition: value(branch.condition, depth + 1), body: statements(branch.body, depth + 1) };
194
+ }), otherwise: statements(node.otherwise, depth + 1) };
195
+ }
196
+ return invalid('节点包含不支持的语句');
197
+ });
198
+ }
199
+ const program = statements(raw, 0);
200
+ if (!program.length || Buffer.byteLength(JSON.stringify(program)) > maxWorkspaceBytes)
201
+ return invalid('节点程序为空或超出大小限制');
202
+ return program;
203
+ }
204
+ const helpers = {
205
+ dataAt: `function dataAt(value, keys) {
206
+ for (const key of keys) {
207
+ if (!value || typeof value !== 'object' || !Object.hasOwn(value, key)) return null;
208
+ value = value[key];
209
+ }
210
+ return value;
211
+ }`,
212
+ withField: `function withField(base, key, value) {
213
+ if (!base || typeof base !== 'object' || Array.isArray(base)) throw new Error('对象积木需要 JSON 对象');
214
+ return { ...base, [key]: value };
215
+ }`,
216
+ calculate: `function calculate(left, right, operator) {
217
+ if (!Number.isFinite(left) || !Number.isFinite(right)) throw new Error('算术积木需要数字');
218
+ const result = operator === 'ADD' ? left + right : operator === 'MINUS' ? left - right
219
+ : operator === 'MULTIPLY' ? left * right : operator === 'DIVIDE' ? left / right : left ** right;
220
+ if (!Number.isFinite(result)) throw new Error('算术结果无效');
221
+ return result;
222
+ }`,
223
+ compare: `function compare(left, right, operator) {
224
+ if (operator === 'EQ') return left === right;
225
+ if (operator === 'NEQ') return left !== right;
226
+ if (typeof left !== typeof right || !['number', 'string'].includes(typeof left)) throw new Error('比较积木需要同类型的数字或文本');
227
+ return operator === 'LT' ? left < right : operator === 'LTE' ? left <= right
228
+ : operator === 'GT' ? left > right : left >= right;
229
+ }`,
230
+ condition: `function condition(value) {
231
+ if (typeof value !== 'boolean') throw new Error('条件积木需要布尔值');
232
+ return value;
233
+ }`,
234
+ message: `function message(value) {
235
+ return typeof value === 'string' ? value : JSON.stringify(value);
236
+ }`,
237
+ };
238
+ export function emitBlocklyModule(program) {
239
+ const used = new Set();
240
+ const call = (name, ...args) => {
241
+ used.add(name);
242
+ return `${name}(${args.join(', ')})`;
243
+ };
244
+ function value(node) {
245
+ switch (node.kind) {
246
+ case 'input': return 'input';
247
+ case 'literal': return node.value && typeof node.value === 'object'
248
+ ? `JSON.parse(${JSON.stringify(JSON.stringify(node.value))})` : JSON.stringify(node.value);
249
+ case 'path': return call('dataAt', value(node.base), JSON.stringify(node.path));
250
+ case 'object': return call('withField', value(node.base), JSON.stringify(node.key), value(node.value));
251
+ case 'array': return `[${node.items.map(value).join(', ')}]`;
252
+ case 'math': return call('calculate', value(node.left), value(node.right), JSON.stringify(node.op));
253
+ case 'compare': return call('compare', value(node.left), value(node.right), JSON.stringify(node.op));
254
+ }
255
+ }
256
+ function statements(nodes, depth) {
257
+ const indent = ' '.repeat(depth);
258
+ return nodes.flatMap(node => {
259
+ if (node.kind === 'if')
260
+ return [
261
+ ...node.branches.flatMap((branch, index) => [
262
+ `${indent}${index ? '} else ' : ''}if (${call('condition', value(branch.condition))}) {`,
263
+ ...statements(branch.body, depth + 1),
264
+ ]),
265
+ ...(node.otherwise.length ? [`${indent}} else {`, ...statements(node.otherwise, depth + 1)] : []),
266
+ `${indent}}`,
267
+ ];
268
+ const expression = value(node.value);
269
+ const statement = node.kind === 'return' ? `return ${expression}` : node.kind === 'log'
270
+ ? `log(${call('message', expression)}.slice(0, ${maxLogLength}))` : `throw new Error(${call('message', expression)})`;
271
+ return [`${indent}${statement};`];
272
+ });
273
+ }
274
+ const lines = statements(program, 1);
275
+ return ['// AUTO-MASC Blockly v1', 'export default function run({ input, signal, log }) {', ' signal.throwIfAborted();',
276
+ ...lines, '}', ...[...used].flatMap(name => ['', helpers[name]]), ''].join('\n');
277
+ }
@@ -0,0 +1,157 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { link, lstat, mkdir, open, readFile, realpath, unlink } from 'node:fs/promises';
3
+ import { join, relative } from 'node:path';
4
+ import { blocklyCompilerRevision, compileBlocklyWorkspace, copyBlocklyWorkspace, emitBlocklyModule, validateBlocklyProgram } from './blockly-compiler.js';
5
+ export const blocklyDraftCollection = 'blockly-drafts';
6
+ export const publishedNodeCollection = 'published-nodes';
7
+ export const blocklyCollections = [blocklyDraftCollection, publishedNodeCollection];
8
+ function isNodeId(value) {
9
+ return typeof value === 'string' && /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/u.test(value);
10
+ }
11
+ function isVersion(value) {
12
+ return typeof value === 'number' && Number.isSafeInteger(value) && value > 0;
13
+ }
14
+ function isName(value) {
15
+ return typeof value === 'string' && !!value.trim() && value.length <= 100 && !/[\x00-\x1f\x7f]/u.test(value);
16
+ }
17
+ const recordId = (id, version) => `${id}@${version}`;
18
+ function isPublished(row) {
19
+ return !!row && isNodeId(row.nodeId) && isVersion(row.version) && row.id === recordId(row.nodeId, row.version)
20
+ && isName(row.name) && isVersion(row.draftRevision) && row.compilerRevision === blocklyCompilerRevision
21
+ && typeof row.digest === 'string' && /^[a-f0-9]{64}$/u.test(row.digest);
22
+ }
23
+ function versions(store, id) {
24
+ return store.list(publishedNodeCollection).filter(row => isPublished(row) && (id === undefined || row.nodeId === id))
25
+ .sort((left, right) => left.version - right.version);
26
+ }
27
+ function render(program) {
28
+ const validated = validateBlocklyProgram(program);
29
+ const source = emitBlocklyModule(validated);
30
+ return { program: validated, source, digest: createHash('sha256').update(source).digest('hex') };
31
+ }
32
+ function isMissing(error) { return error.code === 'ENOENT'; }
33
+ async function resolveModule(dataDir, digest, source) {
34
+ const dataRoot = await realpath(dataDir);
35
+ const expected = join(dataRoot, 'blockly-artifacts');
36
+ await mkdir(expected, { recursive: true });
37
+ const root = await realpath(expected);
38
+ if (relative(expected, root))
39
+ throw new Error('发布节点目录必须位于应用数据目录内');
40
+ const path = join(root, `${digest}.mjs`);
41
+ const size = Buffer.byteLength(source);
42
+ async function verify() {
43
+ const info = await lstat(path).catch(error => {
44
+ if (!isMissing(error))
45
+ throw error;
46
+ });
47
+ if (!info)
48
+ return false;
49
+ if (!info.isFile() || info.size !== size || await readFile(path, 'utf8') !== source) {
50
+ throw new Error('发布节点的模块文件与保存的版本不匹配');
51
+ }
52
+ return true;
53
+ }
54
+ if (await verify())
55
+ return path;
56
+ const temporary = join(root, `${randomUUID()}.tmp`);
57
+ const file = await open(temporary, 'wx', 0o600);
58
+ try {
59
+ try {
60
+ await file.writeFile(source);
61
+ }
62
+ finally {
63
+ await file.close();
64
+ }
65
+ await link(temporary, path).catch(error => {
66
+ if (error.code !== 'EEXIST')
67
+ throw error;
68
+ });
69
+ if (!await verify())
70
+ throw new Error('未能生成发布节点的模块文件');
71
+ return path;
72
+ }
73
+ finally {
74
+ await unlink(temporary);
75
+ }
76
+ }
77
+ export function createPublishedNodes(store, dataDir) {
78
+ return {
79
+ list() {
80
+ const groups = new Map();
81
+ for (const row of versions(store)) {
82
+ const group = groups.get(row.nodeId) ?? { id: row.nodeId, name: row.name, versions: [] };
83
+ group.name = row.name;
84
+ group.versions.push(row.version);
85
+ groups.set(row.nodeId, group);
86
+ }
87
+ return [...groups.values()];
88
+ },
89
+ async resolve(id, version) {
90
+ if (!isNodeId(id) || !isVersion(version))
91
+ throw new Error('发布节点或版本无效');
92
+ const row = store.get(publishedNodeCollection, recordId(id, version));
93
+ if (!isPublished(row))
94
+ throw new Error('发布节点不存在或编译版本不受支持');
95
+ const { source, digest } = render(row.program);
96
+ if (digest !== row.digest)
97
+ throw new Error('发布节点的内容校验失败');
98
+ const modulePath = await resolveModule(dataDir, digest, source);
99
+ return { modulePath, name: row.name };
100
+ },
101
+ };
102
+ }
103
+ export function createBlocklyProjects(store) {
104
+ function getDraft(id) {
105
+ if (!isNodeId(id))
106
+ throw new Error('Blockly 草稿 ID 无效');
107
+ const draft = store.get(blocklyDraftCollection, id);
108
+ if (!draft || !isName(draft.name) || !isVersion(draft.revision))
109
+ throw new Error('Blockly 草稿不存在或内容无效');
110
+ return draft;
111
+ }
112
+ function summary(draft) {
113
+ return { id: draft.id, name: draft.name, revision: draft.revision, versions: versions(store, draft.id).map(row => row.version) };
114
+ }
115
+ function describe(draft) { return { ...summary(draft), workspace: copyBlocklyWorkspace(draft.workspace) }; }
116
+ return {
117
+ list() {
118
+ return store.list(blocklyDraftCollection)
119
+ .filter(draft => isNodeId(draft.id) && isName(draft.name) && isVersion(draft.revision))
120
+ .map(summary);
121
+ },
122
+ get(id) { return describe(getDraft(id)); },
123
+ preview(workspace) { return { source: render(compileBlocklyWorkspace(workspace)).source }; },
124
+ save(input) {
125
+ const name = typeof input.name === 'string' ? input.name.trim() : '';
126
+ if (!isName(name))
127
+ throw new Error('请输入有效的 Blockly 草稿名称');
128
+ const workspace = copyBlocklyWorkspace(input.workspace);
129
+ return store.transaction(() => {
130
+ const previous = input.id === undefined ? undefined : getDraft(input.id);
131
+ if (previous && input.revision !== previous.revision)
132
+ throw new Error('草稿已修改,请重新加载当前版本');
133
+ const row = store.put(blocklyDraftCollection, { id: previous?.id ?? randomUUID(), name, workspace, revision: (previous?.revision ?? 0) + 1 });
134
+ return describe(row);
135
+ });
136
+ },
137
+ publish(input) {
138
+ return store.transaction(() => {
139
+ const draft = getDraft(input.id);
140
+ if (input.revision !== draft.revision)
141
+ throw new Error('草稿已修改,请先保存并确认当前版本');
142
+ const { program, digest } = render(compileBlocklyWorkspace(draft.workspace));
143
+ const previous = versions(store, draft.id);
144
+ const existing = previous.find(row => row.draftRevision === draft.revision && row.digest === digest);
145
+ if (existing)
146
+ return { id: draft.id, name: existing.name, version: existing.version };
147
+ const version = (previous.at(-1)?.version ?? 0) + 1;
148
+ const id = recordId(draft.id, version);
149
+ if (store.get(publishedNodeCollection, id))
150
+ throw new Error('发布节点的版本记录冲突');
151
+ store.put(publishedNodeCollection, { id, nodeId: draft.id, name: draft.name, version,
152
+ draftRevision: draft.revision, compilerRevision: blocklyCompilerRevision, digest, program });
153
+ return { id: draft.id, name: draft.name, version };
154
+ });
155
+ },
156
+ };
157
+ }
@@ -0,0 +1,9 @@
1
+ import { adapterFeature } from '../adapters.js';
2
+ import { createPublishedNodes } from '../blockly.js';
3
+ import { store } from '../features.js';
4
+ import { nodeModule } from '../node-module.js';
5
+ export default function createFeature({ dataDir }) {
6
+ return adapterFeature(nodeModule, { inject: ['mas.store'], provide: ['mas.published-nodes'], apply(ctx) {
7
+ ctx.provide('mas.published-nodes', createPublishedNodes(store(ctx), dataDir));
8
+ } });
9
+ }