@auto-mas/auto-mas-plugin-data-management 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,68 @@
1
+ import { homedir } from 'node:os';
2
+ import { readdir, realpath, stat } from 'node:fs/promises';
3
+ import { delimiter, isAbsolute, relative, sep } from 'node:path';
4
+ import { blocklyCollections } from './blockly.js';
5
+ import { Store } from './storage.js';
6
+ import { interruptWorkflowRun, readWorkflow, workflowCollections } from './workflow-model.js';
7
+ const collections = ['scripts', 'accounts', 'queues', 'plans', 'runs', 'emulators', 'games', ...workflowCollections, ...blocklyCollections];
8
+ export function makeBackup(store) {
9
+ const data = Object.fromEntries(collections.map(name => [name, store.list(name)]));
10
+ return { format: 'cordis-mas-backup', version: 1, created: new Date().toISOString(), data };
11
+ }
12
+ function importedEntry(name, row) {
13
+ if (name === 'workflows') {
14
+ const workflow = readWorkflow(row);
15
+ if (workflow.schedule)
16
+ workflow.schedule.enabled = false;
17
+ return workflow;
18
+ }
19
+ if (name === 'workflow-runs' && row.status === 'running') {
20
+ if (!Array.isArray(row.steps))
21
+ throw new Error('备份中的工作流运行记录格式无效');
22
+ return interruptWorkflowRun(row, '备份包含未结束的运行');
23
+ }
24
+ return ['scripts', 'accounts', 'queues'].includes(name) ? { ...row, enabled: false } : row;
25
+ }
26
+ export function restoreBackup(store, source) {
27
+ const backup = JSON.parse(source);
28
+ if (backup?.format !== 'cordis-mas-backup' || backup.version !== 1 || !backup.data || Array.isArray(backup.data))
29
+ throw new Error('备份格式或版本不受支持');
30
+ const incoming = new Map();
31
+ for (const name of collections) {
32
+ const entries = backup.data[name] ?? [];
33
+ if (!Array.isArray(entries) || entries.some(row => !row || typeof row !== 'object' || Array.isArray(row) || typeof row.id !== 'string' || !row.id)) {
34
+ throw new Error(`无效的备份集合: ${name}`);
35
+ }
36
+ incoming.set(name, entries);
37
+ }
38
+ return store.transaction(() => {
39
+ const counts = {};
40
+ for (const [name, rows] of incoming) {
41
+ counts[name] = 0;
42
+ for (const row of rows) {
43
+ if (store.get(name, row.id))
44
+ continue;
45
+ store.put(name, importedEntry(name, row));
46
+ counts[name]++;
47
+ }
48
+ }
49
+ return { inserted: counts };
50
+ });
51
+ }
52
+ export async function browseHost(directory) {
53
+ const configured = (process.env.MAS_WORK_ROOTS || homedir()).split(delimiter).filter(Boolean);
54
+ const roots = (await Promise.all(configured.map(root => realpath(root).catch(() => null)))).filter((root) => !!root);
55
+ if (!directory)
56
+ return { roots };
57
+ const path = await realpath(directory);
58
+ if (!roots.some(root => {
59
+ const delta = relative(root, path);
60
+ return delta !== '..' && !delta.startsWith(`..${sep}`) && !isAbsolute(delta);
61
+ }))
62
+ throw new Error('目录不在主机允许浏览的范围内');
63
+ if (!(await stat(path)).isDirectory())
64
+ throw new Error('路径不是目录');
65
+ const children = await readdir(path, { withFileTypes: true });
66
+ return { path, directories: children.filter(entry => entry.isDirectory()).slice(0, 500).map(entry => entry.name),
67
+ files: children.filter(entry => entry.isFile()).slice(0, 500).map(entry => entry.name) };
68
+ }
@@ -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,43 @@
1
+ import { makeBackup, restoreBackup } from '../backup.js';
2
+ import { field, store, text, ui } from '../features.js';
3
+ export default function createFeature({ dataDir }) {
4
+ return { id: 'data-management', name: '数据管理', description: '主机信息、旧数据导入及备份', component: { inject: ['mas.ui', 'mas.store'], apply(ctx) {
5
+ const data = store(ctx);
6
+ const migrationFields = [
7
+ field('root', '后端主机上的 MAS 安装目录', { required: true, kind: 'hostpath', directory: true }),
8
+ field('includeHistory', '同时导入旧运行历史', { kind: 'boolean', default: false }),
9
+ ];
10
+ ui(ctx).panel(ctx, 'data-management', [
11
+ { type: 'metrics', title: '执行主机', query: 'settings.host' },
12
+ { type: 'text', title: '数据备份', text: '导出托管、账号、计划、队列、模拟器、游戏配置和历史记录。', download: '/api/ui/v1/download/backup' },
13
+ { type: 'form', title: '恢复 AUTO-MASC 备份', action: 'backup.restore', result: true, fields: [field('file', '备份文件', { required: true, kind: 'file' }), field('confirmed', '确认导入', { kind: 'boolean' })] },
14
+ { type: 'form', title: '预览旧 MAS 数据', action: 'migration.preview', result: true, fields: migrationFields },
15
+ { type: 'form', title: '导入旧 MAS 数据', action: 'migration.import', result: true, fields: [...migrationFields, field('confirmed', '确认导入', { kind: 'boolean' })] },
16
+ ], {
17
+ 'settings.host': () => [{ label: '平台', value: `${process.platform} ${process.arch}` }, { label: 'Node.js', value: process.version }, { label: '数据目录', value: dataDir }],
18
+ }, {
19
+ 'backup.restore': input => {
20
+ if (input.confirmed !== true)
21
+ throw new Error('请确认恢复');
22
+ return restoreBackup(data, text(input, 'file', '备份文件'));
23
+ },
24
+ 'migration.preview': async (input) => {
25
+ const { previewMigration } = await import('../migration/index.js');
26
+ const preview = await previewMigration(text(input, 'root', '安装目录'), { includeHistory: input.includeHistory !== false });
27
+ return {
28
+ scripts: preview.scripts.length, accounts: preview.accounts.length, queues: preview.queues.length, plans: preview.plans.length,
29
+ emulators: preview.emulators.length, games: preview.games.length, history: preview.history.length, warnings: preview.warnings,
30
+ };
31
+ },
32
+ 'migration.import': async (input) => {
33
+ if (input.confirmed !== true)
34
+ throw new Error('请确认导入');
35
+ const { previewMigration, migrationBackup } = await import('../migration/index.js');
36
+ const options = { includeHistory: input.includeHistory !== false };
37
+ const preview = await previewMigration(text(input, 'root', '安装目录'), options);
38
+ return { ...restoreBackup(data, JSON.stringify(migrationBackup(preview, options))), warnings: preview.warnings };
39
+ },
40
+ });
41
+ ui(ctx).download(ctx, 'backup', () => makeBackup(data));
42
+ } } };
43
+ }
@@ -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', '结果详情']);