codexmate 0.0.20 → 0.0.21

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.
Files changed (102) hide show
  1. package/README.en.md +349 -259
  2. package/README.md +284 -252
  3. package/cli/agents-files.js +162 -0
  4. package/cli/archive-helpers.js +446 -0
  5. package/cli/auth-profiles.js +359 -0
  6. package/cli/builtin-proxy.js +580 -0
  7. package/cli/claude-proxy.js +998 -0
  8. package/cli/config-bootstrap.js +384 -0
  9. package/cli/config-health.js +338 -338
  10. package/cli/openclaw-config.js +629 -0
  11. package/cli/skills.js +1141 -0
  12. package/cli/zip-commands.js +510 -0
  13. package/cli.js +13101 -13497
  14. package/lib/cli-file-utils.js +151 -151
  15. package/lib/cli-models-utils.js +419 -311
  16. package/lib/cli-network-utils.js +164 -164
  17. package/lib/cli-path-utils.js +69 -0
  18. package/lib/cli-session-utils.js +121 -121
  19. package/lib/cli-sessions.js +386 -0
  20. package/lib/cli-utils.js +155 -155
  21. package/lib/download-artifacts.js +77 -0
  22. package/lib/mcp-stdio.js +440 -440
  23. package/lib/task-orchestrator.js +869 -0
  24. package/lib/text-diff.js +303 -303
  25. package/lib/workflow-engine.js +340 -340
  26. package/package.json +74 -70
  27. package/res/json5.min.js +1 -1
  28. package/res/vue.global.prod.js +13 -0
  29. package/web-ui/app.js +530 -397
  30. package/web-ui/index.html +33 -30
  31. package/web-ui/logic.agents-diff.mjs +386 -386
  32. package/web-ui/logic.claude.mjs +168 -108
  33. package/web-ui/logic.mjs +5 -5
  34. package/web-ui/logic.runtime.mjs +124 -124
  35. package/web-ui/logic.sessions.mjs +581 -263
  36. package/web-ui/modules/api.mjs +90 -69
  37. package/web-ui/modules/app.computed.dashboard.mjs +113 -113
  38. package/web-ui/modules/app.computed.index.mjs +15 -13
  39. package/web-ui/modules/app.computed.main-tabs.mjs +195 -0
  40. package/web-ui/modules/app.computed.session.mjs +507 -141
  41. package/web-ui/modules/app.constants.mjs +15 -15
  42. package/web-ui/modules/app.methods.agents.mjs +493 -493
  43. package/web-ui/modules/app.methods.claude-config.mjs +174 -174
  44. package/web-ui/modules/app.methods.codex-config.mjs +640 -640
  45. package/web-ui/modules/app.methods.index.mjs +88 -86
  46. package/web-ui/modules/app.methods.install.mjs +149 -157
  47. package/web-ui/modules/app.methods.navigation.mjs +619 -478
  48. package/web-ui/modules/app.methods.openclaw-core.mjs +814 -514
  49. package/web-ui/modules/app.methods.openclaw-editing.mjs +372 -337
  50. package/web-ui/modules/app.methods.openclaw-persist.mjs +369 -251
  51. package/web-ui/modules/app.methods.providers.mjs +363 -265
  52. package/web-ui/modules/app.methods.runtime.mjs +323 -323
  53. package/web-ui/modules/app.methods.session-actions.mjs +520 -457
  54. package/web-ui/modules/app.methods.session-browser.mjs +626 -435
  55. package/web-ui/modules/app.methods.session-timeline.mjs +448 -441
  56. package/web-ui/modules/app.methods.session-trash.mjs +422 -419
  57. package/web-ui/modules/app.methods.startup-claude.mjs +412 -406
  58. package/web-ui/modules/app.methods.task-orchestration.mjs +471 -0
  59. package/web-ui/modules/config-mode.computed.mjs +126 -124
  60. package/web-ui/modules/skills.computed.mjs +107 -107
  61. package/web-ui/modules/skills.methods.mjs +481 -481
  62. package/web-ui/partials/index/layout-footer.html +13 -69
  63. package/web-ui/partials/index/layout-header.html +402 -337
  64. package/web-ui/partials/index/modal-config-template-agents.html +125 -125
  65. package/web-ui/partials/index/modal-confirm-toast.html +32 -32
  66. package/web-ui/partials/index/modal-health-check.html +72 -72
  67. package/web-ui/partials/index/modal-openclaw-config.html +280 -275
  68. package/web-ui/partials/index/modal-skills.html +184 -184
  69. package/web-ui/partials/index/modals-basic.html +156 -196
  70. package/web-ui/partials/index/panel-config-claude.html +126 -100
  71. package/web-ui/partials/index/panel-config-codex.html +237 -237
  72. package/web-ui/partials/index/panel-config-openclaw.html +78 -84
  73. package/web-ui/partials/index/panel-docs.html +130 -0
  74. package/web-ui/partials/index/panel-market.html +174 -174
  75. package/web-ui/partials/index/panel-orchestration.html +397 -0
  76. package/web-ui/partials/index/panel-sessions.html +292 -387
  77. package/web-ui/partials/index/panel-settings.html +190 -166
  78. package/web-ui/partials/index/panel-usage.html +213 -0
  79. package/web-ui/session-helpers.mjs +559 -362
  80. package/web-ui/source-bundle.cjs +233 -233
  81. package/web-ui/styles/base-theme.css +271 -373
  82. package/web-ui/styles/controls-forms.css +360 -354
  83. package/web-ui/styles/docs-panel.css +182 -0
  84. package/web-ui/styles/feedback.css +108 -108
  85. package/web-ui/styles/health-check-dialog.css +144 -144
  86. package/web-ui/styles/layout-shell.css +376 -330
  87. package/web-ui/styles/modals-core.css +464 -449
  88. package/web-ui/styles/navigation-panels.css +348 -381
  89. package/web-ui/styles/openclaw-structured.css +266 -266
  90. package/web-ui/styles/responsive.css +450 -416
  91. package/web-ui/styles/sessions-list.css +400 -414
  92. package/web-ui/styles/sessions-preview.css +411 -405
  93. package/web-ui/styles/sessions-toolbar-trash.css +243 -243
  94. package/web-ui/styles/sessions-usage.css +628 -276
  95. package/web-ui/styles/skills-list.css +296 -298
  96. package/web-ui/styles/skills-market.css +335 -335
  97. package/web-ui/styles/task-orchestration.css +776 -0
  98. package/web-ui/styles/titles-cards.css +408 -407
  99. package/web-ui/styles.css +18 -16
  100. package/web-ui.html +17 -17
  101. package/res/screenshot.png +0 -0
  102. package/res/vue.global.js +0 -18552
@@ -0,0 +1,162 @@
1
+ function createAgentsFileController(deps = {}) {
2
+ const {
3
+ fs,
4
+ path,
5
+ os,
6
+ stripUtf8Bom,
7
+ detectLineEnding,
8
+ normalizeLineEnding,
9
+ ensureUtf8Bom,
10
+ buildLineDiff,
11
+ CONFIG_DIR,
12
+ AGENTS_FILE_NAME,
13
+ readOpenclawAgentsFile,
14
+ readOpenclawWorkspaceFile
15
+ } = deps;
16
+
17
+ if (!fs) throw new Error('createAgentsFileController 缺少 fs');
18
+ if (!path) throw new Error('createAgentsFileController 缺少 path');
19
+ if (!os) throw new Error('createAgentsFileController 缺少 os');
20
+ if (typeof stripUtf8Bom !== 'function') throw new Error('createAgentsFileController 缺少 stripUtf8Bom');
21
+ if (typeof detectLineEnding !== 'function') throw new Error('createAgentsFileController 缺少 detectLineEnding');
22
+ if (typeof normalizeLineEnding !== 'function') throw new Error('createAgentsFileController 缺少 normalizeLineEnding');
23
+ if (typeof ensureUtf8Bom !== 'function') throw new Error('createAgentsFileController 缺少 ensureUtf8Bom');
24
+ if (typeof buildLineDiff !== 'function') throw new Error('createAgentsFileController 缺少 buildLineDiff');
25
+ if (typeof CONFIG_DIR !== 'string' || !CONFIG_DIR) throw new Error('createAgentsFileController 缺少 CONFIG_DIR');
26
+ if (typeof AGENTS_FILE_NAME !== 'string' || !AGENTS_FILE_NAME) throw new Error('createAgentsFileController 缺少 AGENTS_FILE_NAME');
27
+ if (typeof readOpenclawAgentsFile !== 'function') throw new Error('createAgentsFileController 缺少 readOpenclawAgentsFile');
28
+ if (typeof readOpenclawWorkspaceFile !== 'function') throw new Error('createAgentsFileController 缺少 readOpenclawWorkspaceFile');
29
+
30
+ function resolveAgentsFilePath(params = {}) {
31
+ const baseDir = typeof params.baseDir === 'string' && params.baseDir.trim()
32
+ ? params.baseDir.trim()
33
+ : CONFIG_DIR;
34
+ return path.join(baseDir, AGENTS_FILE_NAME);
35
+ }
36
+
37
+ function validateAgentsBaseDir(filePath) {
38
+ const dirPath = path.dirname(filePath);
39
+ try {
40
+ const stat = fs.statSync(dirPath);
41
+ if (!stat.isDirectory()) {
42
+ return { error: `目标不是目录: ${dirPath}` };
43
+ }
44
+ } catch (e) {
45
+ return { error: `目标目录不存在: ${dirPath}` };
46
+ }
47
+ return { ok: true, dirPath };
48
+ }
49
+
50
+ function readAgentsFile(params = {}) {
51
+ const filePath = resolveAgentsFilePath(params);
52
+ const dirCheck = validateAgentsBaseDir(filePath);
53
+ if (dirCheck.error) {
54
+ return { error: dirCheck.error };
55
+ }
56
+
57
+ if (!fs.existsSync(filePath)) {
58
+ return {
59
+ exists: false,
60
+ path: filePath,
61
+ content: '',
62
+ lineEnding: os.EOL === '\r\n' ? '\r\n' : '\n'
63
+ };
64
+ }
65
+
66
+ if (params.metaOnly) {
67
+ return {
68
+ exists: true,
69
+ path: filePath,
70
+ content: '',
71
+ lineEnding: os.EOL === '\r\n' ? '\r\n' : '\n'
72
+ };
73
+ }
74
+
75
+ try {
76
+ const raw = fs.readFileSync(filePath, 'utf-8');
77
+ return {
78
+ exists: true,
79
+ path: filePath,
80
+ content: stripUtf8Bom(raw),
81
+ lineEnding: detectLineEnding(raw)
82
+ };
83
+ } catch (e) {
84
+ return { error: `读取 AGENTS.md 失败: ${e.message}` };
85
+ }
86
+ }
87
+
88
+ function applyAgentsFile(params = {}) {
89
+ const filePath = resolveAgentsFilePath(params);
90
+ const dirCheck = validateAgentsBaseDir(filePath);
91
+ if (dirCheck.error) {
92
+ return { error: dirCheck.error };
93
+ }
94
+
95
+ const content = typeof params.content === 'string' ? params.content : '';
96
+ const lineEnding = params.lineEnding === '\r\n' ? '\r\n' : '\n';
97
+ const normalized = normalizeLineEnding(content, lineEnding);
98
+ const finalContent = ensureUtf8Bom(normalized);
99
+
100
+ try {
101
+ fs.writeFileSync(filePath, finalContent, 'utf-8');
102
+ return { success: true, path: filePath };
103
+ } catch (e) {
104
+ return { error: `写入 AGENTS.md 失败: ${e.message}` };
105
+ }
106
+ }
107
+
108
+ function normalizeDiffText(input) {
109
+ const safe = typeof input === 'string' ? input : '';
110
+ return normalizeLineEnding(stripUtf8Bom(safe), '\n');
111
+ }
112
+
113
+ function buildAgentsDiff(params = {}) {
114
+ const hasBaseContent = typeof params.baseContent === 'string';
115
+ const contextRaw = typeof params.context === 'string' ? params.context.trim() : '';
116
+ const context = contextRaw || 'codex';
117
+ const metaOnly = hasBaseContent;
118
+ let readResult;
119
+ if (context === 'openclaw') {
120
+ readResult = readOpenclawAgentsFile({ metaOnly });
121
+ } else if (context === 'openclaw-workspace') {
122
+ readResult = readOpenclawWorkspaceFile({ ...params, metaOnly });
123
+ } else if (context === 'codex') {
124
+ readResult = readAgentsFile({ ...params, metaOnly });
125
+ } else {
126
+ return { error: `Unsupported agents diff context: ${context}` };
127
+ }
128
+ if (readResult && readResult.error) {
129
+ return { error: readResult.error };
130
+ }
131
+
132
+ const beforeText = normalizeDiffText(
133
+ hasBaseContent ? params.baseContent : (readResult && readResult.content ? readResult.content : '')
134
+ );
135
+ const afterText = normalizeDiffText(params.content);
136
+ const diff = buildLineDiff(beforeText, afterText);
137
+ const hasChanges = diff.truncated ? beforeText !== afterText : (diff.stats.added > 0 || diff.stats.removed > 0);
138
+ return {
139
+ diff: {
140
+ ...diff,
141
+ hasChanges
142
+ },
143
+ path: readResult && readResult.path ? readResult.path : '',
144
+ exists: !!(readResult && readResult.exists),
145
+ context,
146
+ configError: readResult && readResult.configError ? readResult.configError : ''
147
+ };
148
+ }
149
+
150
+ return {
151
+ resolveAgentsFilePath,
152
+ validateAgentsBaseDir,
153
+ readAgentsFile,
154
+ applyAgentsFile,
155
+ normalizeDiffText,
156
+ buildAgentsDiff
157
+ };
158
+ }
159
+
160
+ module.exports = {
161
+ createAgentsFileController
162
+ };
@@ -0,0 +1,446 @@
1
+ function createArchiveHelperController(deps = {}) {
2
+ const {
3
+ fs,
4
+ path,
5
+ os,
6
+ execSync,
7
+ zipLib,
8
+ yauzl,
9
+ ensureDir,
10
+ isPathInside,
11
+ commandExists,
12
+ MAX_UPLOAD_SIZE,
13
+ MAX_SKILLS_ZIP_UPLOAD_SIZE,
14
+ MAX_SKILLS_ZIP_ENTRY_COUNT,
15
+ MAX_SKILLS_ZIP_UNCOMPRESSED_BYTES
16
+ } = deps;
17
+
18
+ if (!fs) throw new Error('createArchiveHelperController 缺少 fs');
19
+ if (!path) throw new Error('createArchiveHelperController 缺少 path');
20
+ if (!os) throw new Error('createArchiveHelperController 缺少 os');
21
+ if (typeof execSync !== 'function') throw new Error('createArchiveHelperController 缺少 execSync');
22
+ if (!zipLib) throw new Error('createArchiveHelperController 缺少 zipLib');
23
+ if (!yauzl) throw new Error('createArchiveHelperController 缺少 yauzl');
24
+ if (typeof ensureDir !== 'function') throw new Error('createArchiveHelperController 缺少 ensureDir');
25
+ if (typeof isPathInside !== 'function') throw new Error('createArchiveHelperController 缺少 isPathInside');
26
+ if (typeof commandExists !== 'function') throw new Error('createArchiveHelperController 缺少 commandExists');
27
+
28
+ const ZIP_PATHS = ['zip'];
29
+
30
+ function findZipExecutable() {
31
+ for (const candidate of ZIP_PATHS) {
32
+ try {
33
+ if (candidate === 'zip') {
34
+ if (commandExists('zip', '--help')) {
35
+ return 'zip';
36
+ }
37
+ } else if (fs.existsSync(candidate)) {
38
+ return candidate;
39
+ }
40
+ } catch (_) {}
41
+ }
42
+ return null;
43
+ }
44
+
45
+ function resolveZipTool() {
46
+ const zipExe = findZipExecutable();
47
+ if (zipExe) {
48
+ return { type: 'zip', cmd: zipExe };
49
+ }
50
+ return { type: 'lib', cmd: 'zip-lib' };
51
+ }
52
+
53
+ function resolveUnzipTool() {
54
+ return { type: 'lib', cmd: 'zip-lib' };
55
+ }
56
+
57
+ async function zipWithLibrary(absPath, outputPath) {
58
+ const stat = fs.lstatSync(absPath);
59
+ if (stat.isDirectory()) {
60
+ await zipLib.archiveFolder(absPath, outputPath);
61
+ return;
62
+ }
63
+ await zipLib.archiveFile(absPath, outputPath);
64
+ }
65
+
66
+ async function unzipWithLibrary(zipPath, outputDir) {
67
+ await zipLib.extract(zipPath, outputDir);
68
+ }
69
+
70
+ function copyDirRecursive(srcDir, destDir, options = {}) {
71
+ const dereferenceSymlinks = !!(options && options.dereferenceSymlinks);
72
+ const allowedRootRealPath = (options && typeof options.allowedRootRealPath === 'string')
73
+ ? options.allowedRootRealPath
74
+ : '';
75
+ const visitedRealPaths = options && options.visitedRealPaths instanceof Set
76
+ ? options.visitedRealPaths
77
+ : new Set();
78
+ const childOptions = {
79
+ ...options,
80
+ dereferenceSymlinks,
81
+ allowedRootRealPath,
82
+ visitedRealPaths
83
+ };
84
+ ensureDir(destDir);
85
+ const entries = fs.readdirSync(srcDir, { withFileTypes: true });
86
+ for (const entry of entries) {
87
+ const srcPath = path.join(srcDir, entry.name);
88
+ const destPath = path.join(destDir, entry.name);
89
+ if (entry.isDirectory()) {
90
+ if (!dereferenceSymlinks) {
91
+ copyDirRecursive(srcPath, destPath, childOptions);
92
+ continue;
93
+ }
94
+ const realPath = fs.realpathSync(srcPath);
95
+ if (allowedRootRealPath && !isPathInside(realPath, allowedRootRealPath)) {
96
+ throw new Error(`symlink escapes skill root: ${srcPath}`);
97
+ }
98
+ if (visitedRealPaths.has(realPath)) {
99
+ continue;
100
+ }
101
+ visitedRealPaths.add(realPath);
102
+ try {
103
+ copyDirRecursive(srcPath, destPath, childOptions);
104
+ } finally {
105
+ visitedRealPaths.delete(realPath);
106
+ }
107
+ } else if (entry.isSymbolicLink()) {
108
+ if (dereferenceSymlinks) {
109
+ const realPath = fs.realpathSync(srcPath);
110
+ if (allowedRootRealPath && !isPathInside(realPath, allowedRootRealPath)) {
111
+ throw new Error(`symlink escapes skill root: ${srcPath}`);
112
+ }
113
+ const realStat = fs.statSync(realPath);
114
+ if (realStat.isDirectory()) {
115
+ if (visitedRealPaths.has(realPath)) {
116
+ continue;
117
+ }
118
+ visitedRealPaths.add(realPath);
119
+ try {
120
+ copyDirRecursive(realPath, destPath, childOptions);
121
+ } finally {
122
+ visitedRealPaths.delete(realPath);
123
+ }
124
+ } else {
125
+ fs.copyFileSync(realPath, destPath);
126
+ }
127
+ } else {
128
+ const target = fs.readlinkSync(srcPath);
129
+ fs.symlinkSync(target, destPath);
130
+ }
131
+ } else {
132
+ fs.copyFileSync(srcPath, destPath);
133
+ }
134
+ }
135
+ }
136
+
137
+ function inspectZipArchiveLimits(zipPath, options = {}) {
138
+ const maxEntryCount = Number.isFinite(options.maxEntryCount) && options.maxEntryCount > 0
139
+ ? Math.floor(options.maxEntryCount)
140
+ : MAX_SKILLS_ZIP_ENTRY_COUNT;
141
+ const maxUncompressedBytes = Number.isFinite(options.maxUncompressedBytes) && options.maxUncompressedBytes > 0
142
+ ? Math.floor(options.maxUncompressedBytes)
143
+ : MAX_SKILLS_ZIP_UNCOMPRESSED_BYTES;
144
+
145
+ return new Promise((resolve, reject) => {
146
+ yauzl.open(zipPath, { lazyEntries: true, autoClose: true }, (openErr, zipFile) => {
147
+ if (openErr) {
148
+ reject(openErr);
149
+ return;
150
+ }
151
+ if (!zipFile) {
152
+ reject(new Error('无法读取 ZIP 文件'));
153
+ return;
154
+ }
155
+ let entryCount = 0;
156
+ let totalUncompressedBytes = 0;
157
+ let settled = false;
158
+ const finish = (err, data) => {
159
+ if (settled) return;
160
+ settled = true;
161
+ try {
162
+ zipFile.close();
163
+ } catch (_) {}
164
+ if (err) {
165
+ reject(err);
166
+ } else {
167
+ resolve(data);
168
+ }
169
+ };
170
+
171
+ zipFile.on('entry', (entry) => {
172
+ if (settled) return;
173
+ entryCount += 1;
174
+ const entrySize = Number.isFinite(entry.uncompressedSize) ? entry.uncompressedSize : 0;
175
+ totalUncompressedBytes += entrySize;
176
+ if (entryCount > maxEntryCount) {
177
+ finish(new Error(`压缩包条目过多(>${maxEntryCount})`));
178
+ return;
179
+ }
180
+ if (totalUncompressedBytes > maxUncompressedBytes) {
181
+ finish(new Error(`压缩包解压总大小超限(>${Math.floor(maxUncompressedBytes / 1024 / 1024)}MB)`));
182
+ return;
183
+ }
184
+ zipFile.readEntry();
185
+ });
186
+
187
+ zipFile.on('end', () => {
188
+ finish(null, { entryCount, totalUncompressedBytes });
189
+ });
190
+
191
+ zipFile.on('error', (zipErr) => {
192
+ finish(zipErr);
193
+ });
194
+
195
+ zipFile.readEntry();
196
+ });
197
+ });
198
+ }
199
+
200
+ function writeUploadZipStream(req, prefix, originalName = '', maxSize = MAX_SKILLS_ZIP_UPLOAD_SIZE) {
201
+ return new Promise((resolve, reject) => {
202
+ const lengthHeader = parseInt(req.headers['content-length'] || '0', 10);
203
+ if (Number.isFinite(lengthHeader) && lengthHeader > maxSize) {
204
+ reject(new Error(`备份文件过大(>${Math.floor(maxSize / 1024 / 1024)}MB)`));
205
+ return;
206
+ }
207
+
208
+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), `${prefix}-`));
209
+ const rawName = originalName && typeof originalName === 'string' ? originalName : `${prefix}.zip`;
210
+ const fileName = path.basename(rawName);
211
+ const zipPath = path.join(tempDir, fileName.toLowerCase().endsWith('.zip') ? fileName : `${fileName}.zip`);
212
+ const stream = fs.createWriteStream(zipPath);
213
+ let bytesWritten = 0;
214
+ let settled = false;
215
+ let hasContent = false;
216
+
217
+ const fail = (err) => {
218
+ if (settled) return;
219
+ settled = true;
220
+ try {
221
+ stream.destroy();
222
+ } catch (_) {}
223
+ try {
224
+ fs.rmSync(tempDir, { recursive: true, force: true });
225
+ } catch (_) {}
226
+ reject(err);
227
+ };
228
+
229
+ const done = () => {
230
+ if (settled) return;
231
+ settled = true;
232
+ if (!hasContent || bytesWritten <= 0) {
233
+ try {
234
+ fs.rmSync(tempDir, { recursive: true, force: true });
235
+ } catch (_) {}
236
+ reject(new Error('备份文件为空'));
237
+ return;
238
+ }
239
+ resolve({ tempDir, zipPath });
240
+ };
241
+
242
+ req.on('error', (err) => fail(err));
243
+ req.on('aborted', () => fail(new Error('上传已中断')));
244
+ req.on('close', () => {
245
+ if (!settled && !req.complete) {
246
+ fail(new Error('上传已中断'));
247
+ }
248
+ });
249
+ stream.on('error', (err) => fail(err));
250
+ req.on('data', (chunk) => {
251
+ if (settled) return;
252
+ hasContent = true;
253
+ bytesWritten += chunk.length;
254
+ if (bytesWritten > maxSize) {
255
+ fail(new Error(`备份文件过大(>${Math.floor(maxSize / 1024 / 1024)}MB)`));
256
+ try {
257
+ req.destroy();
258
+ } catch (_) {}
259
+ return;
260
+ }
261
+ stream.write(chunk);
262
+ });
263
+ req.on('end', () => {
264
+ if (settled) return;
265
+ stream.end(() => done());
266
+ });
267
+ });
268
+ }
269
+
270
+ function writeUploadZip(base64, prefix, originalName = '') {
271
+ let buffer;
272
+ try {
273
+ buffer = Buffer.from(base64 || '', 'base64');
274
+ } catch (_) {
275
+ return { error: '备份文件内容不是有效的 base64 编码' };
276
+ }
277
+
278
+ if (!buffer || buffer.length === 0) {
279
+ return { error: '备份文件为空' };
280
+ }
281
+
282
+ if (buffer.length > MAX_UPLOAD_SIZE) {
283
+ return { error: `备份文件过大(>${Math.floor(MAX_UPLOAD_SIZE / 1024 / 1024)}MB)` };
284
+ }
285
+
286
+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), `${prefix}-`));
287
+ const fileName = path.basename(originalName && typeof originalName === 'string' ? originalName : `${prefix}.zip`);
288
+ const zipPath = path.join(tempDir, fileName.toLowerCase().endsWith('.zip') ? fileName : `${fileName}.zip`);
289
+ fs.writeFileSync(zipPath, buffer);
290
+ return { tempDir, zipPath };
291
+ }
292
+
293
+ async function extractUploadZip(zipPath, extractDir) {
294
+ resolveUnzipTool();
295
+ ensureDir(extractDir);
296
+ await unzipWithLibrary(zipPath, extractDir);
297
+ }
298
+
299
+ function findConfigSourceDir(extractedDir, markerDirName, requiredFileName) {
300
+ const markerPath = path.join(extractedDir, markerDirName);
301
+ if (fs.existsSync(markerPath) && fs.statSync(markerPath).isDirectory()) {
302
+ return markerPath;
303
+ }
304
+
305
+ const entries = fs.readdirSync(extractedDir, { withFileTypes: true }).filter((item) => item.isDirectory());
306
+ if (entries.length === 1) {
307
+ const onlyDir = path.join(extractedDir, entries[0].name);
308
+ const nestedMarker = path.join(onlyDir, markerDirName);
309
+ if (fs.existsSync(nestedMarker) && fs.statSync(nestedMarker).isDirectory()) {
310
+ return nestedMarker;
311
+ }
312
+ if (fs.existsSync(path.join(onlyDir, requiredFileName))) {
313
+ return onlyDir;
314
+ }
315
+ }
316
+
317
+ if (fs.existsSync(path.join(extractedDir, requiredFileName))) {
318
+ return extractedDir;
319
+ }
320
+
321
+ return extractedDir;
322
+ }
323
+
324
+ async function prepareDirectoryDownload(dirPath, options = {}) {
325
+ const missingMessage = typeof options.missingMessage === 'string' && options.missingMessage.trim()
326
+ ? options.missingMessage.trim()
327
+ : '目录不存在';
328
+ const fileNamePrefix = typeof options.fileNamePrefix === 'string' && options.fileNamePrefix.trim()
329
+ ? options.fileNamePrefix.trim()
330
+ : 'archive';
331
+
332
+ try {
333
+ if (!fs.existsSync(dirPath)) {
334
+ return { error: missingMessage, path: dirPath };
335
+ }
336
+
337
+ const tempDir = os.tmpdir();
338
+ const timestamp = Date.now();
339
+ const zipFileName = `${fileNamePrefix}-${timestamp}.zip`;
340
+ const zipFilePath = path.join(tempDir, zipFileName);
341
+
342
+ const zipTool = resolveZipTool();
343
+ if (zipTool.type === 'zip') {
344
+ const cmd = `"${zipTool.cmd}" -0 -q -r "${zipFilePath}" "${dirPath}"`;
345
+ execSync(cmd, { stdio: 'ignore' });
346
+ } else {
347
+ await zipWithLibrary(dirPath, zipFilePath);
348
+ }
349
+
350
+ return {
351
+ success: true,
352
+ downloadPath: zipFilePath,
353
+ fileName: zipFileName,
354
+ sourcePath: dirPath
355
+ };
356
+ } catch (e) {
357
+ return { error: `打包失败:${e.message}` };
358
+ }
359
+ }
360
+
361
+ async function backupDirectoryIfExists(dirPath, prefix) {
362
+ if (!fs.existsSync(dirPath)) {
363
+ return { backupPath: '' };
364
+ }
365
+
366
+ const tempDir = os.tmpdir();
367
+ const timestamp = Date.now();
368
+ const zipFileName = `${prefix}-${timestamp}.zip`;
369
+ const zipFilePath = path.join(tempDir, zipFileName);
370
+ const zipTool = resolveZipTool();
371
+
372
+ try {
373
+ if (zipTool.type === 'zip') {
374
+ const cmd = `"${zipTool.cmd}" -0 -q -r "${zipFilePath}" "${dirPath}"`;
375
+ execSync(cmd, { stdio: 'ignore' });
376
+ } else {
377
+ await zipWithLibrary(dirPath, zipFilePath);
378
+ }
379
+ return { backupPath: zipFilePath, fileName: zipFileName };
380
+ } catch (e) {
381
+ return { backupPath: '', warning: `备份失败: ${e.message}` };
382
+ }
383
+ }
384
+
385
+ async function restoreConfigDirectoryFromUpload(payload, options) {
386
+ const { targetDir, requiredFileName, markerDirName, tempPrefix, backupPrefix } = options;
387
+ if (!payload || typeof payload.fileBase64 !== 'string' || !payload.fileBase64.trim()) {
388
+ return { error: '缺少备份文件内容' };
389
+ }
390
+
391
+ const upload = writeUploadZip(payload.fileBase64, tempPrefix, payload.fileName);
392
+ if (upload.error) {
393
+ return { error: upload.error };
394
+ }
395
+
396
+ const tempDir = upload.tempDir;
397
+ const extractDir = path.join(tempDir, 'extract');
398
+ let backupPath = '';
399
+ try {
400
+ await extractUploadZip(upload.zipPath, extractDir);
401
+ const sourceDir = findConfigSourceDir(extractDir, markerDirName, requiredFileName);
402
+ const requiredPath = path.join(sourceDir, requiredFileName);
403
+ if (!fs.existsSync(requiredPath)) {
404
+ return { error: `无效备份,缺少 ${requiredFileName}` };
405
+ }
406
+
407
+ const backupResult = await backupDirectoryIfExists(targetDir, backupPrefix);
408
+ backupPath = backupResult.backupPath || '';
409
+
410
+ fs.rmSync(targetDir, { recursive: true, force: true });
411
+ copyDirRecursive(sourceDir, targetDir);
412
+
413
+ return {
414
+ success: true,
415
+ targetDir,
416
+ appliedFrom: payload.fileName || '',
417
+ backupPath,
418
+ backupWarning: backupResult.warning || ''
419
+ };
420
+ } catch (e) {
421
+ return { error: `导入失败:${e.message}` };
422
+ } finally {
423
+ fs.rmSync(tempDir, { recursive: true, force: true });
424
+ }
425
+ }
426
+
427
+ return {
428
+ resolveZipTool,
429
+ resolveUnzipTool,
430
+ zipWithLibrary,
431
+ unzipWithLibrary,
432
+ copyDirRecursive,
433
+ inspectZipArchiveLimits,
434
+ writeUploadZipStream,
435
+ writeUploadZip,
436
+ extractUploadZip,
437
+ findConfigSourceDir,
438
+ prepareDirectoryDownload,
439
+ backupDirectoryIfExists,
440
+ restoreConfigDirectoryFromUpload
441
+ };
442
+ }
443
+
444
+ module.exports = {
445
+ createArchiveHelperController
446
+ };