@pyrokine/mcp-ssh 1.1.2 → 1.1.3

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.
@@ -39,18 +39,10 @@ export declare function listDir(alias: string, remotePath: string, showHidden?:
39
39
  * 获取文件信息
40
40
  */
41
41
  export declare function getFileInfo(alias: string, remotePath: string): Promise<FileInfo>;
42
- /**
43
- * 检查文件是否存在
44
- */
45
- export declare function fileExists(alias: string, remotePath: string): Promise<boolean>;
46
42
  /**
47
43
  * 创建目录
48
44
  */
49
45
  export declare function mkdir(alias: string, remotePath: string, recursive?: boolean): Promise<boolean>;
50
- /**
51
- * 删除文件
52
- */
53
- export declare function removeFile(alias: string, remotePath: string): Promise<boolean>;
54
46
  /**
55
47
  * 检查远程是否安装 rsync
56
48
  */
@@ -69,10 +61,15 @@ export declare function syncFiles(alias: string, localPath: string, remotePath:
69
61
  dryRun?: boolean;
70
62
  exclude?: string[];
71
63
  recursive?: boolean;
72
- }): Promise<{
64
+ }): Promise<SyncResult>;
65
+ /**
66
+ * 使用 SFTP 同步文件
67
+ */
68
+ type SyncResult = {
73
69
  success: boolean;
74
70
  method: 'rsync' | 'sftp';
75
71
  filesTransferred?: number;
76
72
  bytesTransferred?: number;
77
73
  output?: string;
78
- }>;
74
+ };
75
+ export {};
package/dist/file-ops.js CHANGED
@@ -5,19 +5,30 @@ import { execSync } from 'child_process';
5
5
  import * as fs from 'fs';
6
6
  import * as path from 'path';
7
7
  import { sessionManager } from './session-manager.js';
8
+ // 文件类型 mode 常量
9
+ const S_IFDIR = 0o40000;
10
+ const S_IFREG = 0o100000;
11
+ const S_IFLNK = 0o120000;
8
12
  /**
9
- * 上传文件
13
+ * sftp.stat 的 Promise 包装
10
14
  */
11
- export async function uploadFile(alias, localPath, remotePath, onProgress) {
12
- if (!fs.existsSync(localPath)) {
13
- throw new Error(`Local file not found: ${localPath}`);
14
- }
15
- const sftp = await sessionManager.getSftp(alias);
16
- const stats = fs.statSync(localPath);
17
- const totalSize = stats.size;
15
+ function sftpStat(sftp, remotePath) {
16
+ return new Promise((resolve, reject) => {
17
+ sftp.stat(remotePath, (err, stats) => {
18
+ if (err) {
19
+ reject(err);
20
+ }
21
+ else {
22
+ resolve(stats);
23
+ }
24
+ });
25
+ });
26
+ }
27
+ /**
28
+ * 带进度追踪的流传输
29
+ */
30
+ function pipeWithProgress(readStream, writeStream, sftp, totalSize, onProgress) {
18
31
  return new Promise((resolve, reject) => {
19
- const readStream = fs.createReadStream(localPath);
20
- const writeStream = sftp.createWriteStream(remotePath);
21
32
  let settled = false;
22
33
  const cleanup = (err) => {
23
34
  if (settled) {
@@ -32,13 +43,11 @@ export async function uploadFile(alias, localPath, remotePath, onProgress) {
32
43
  let transferred = 0;
33
44
  readStream.on('data', (chunk) => {
34
45
  transferred += chunk.length;
35
- if (onProgress) {
36
- onProgress({
37
- transferred,
38
- total: totalSize,
39
- percent: totalSize > 0 ? Math.round((transferred / totalSize) * 100) : 100,
40
- });
41
- }
46
+ onProgress?.({
47
+ transferred,
48
+ total: totalSize,
49
+ percent: totalSize > 0 ? Math.round((transferred / totalSize) * 100) : 100,
50
+ });
42
51
  });
43
52
  readStream.on('error', (err) => cleanup(err));
44
53
  writeStream.on('error', (err) => cleanup(err));
@@ -52,82 +61,36 @@ export async function uploadFile(alias, localPath, remotePath, onProgress) {
52
61
  readStream.pipe(writeStream);
53
62
  });
54
63
  }
64
+ /**
65
+ * 上传文件
66
+ */
67
+ export async function uploadFile(alias, localPath, remotePath, onProgress) {
68
+ if (!fs.existsSync(localPath)) {
69
+ throw new Error(`Local file not found: ${localPath}`);
70
+ }
71
+ const sftp = await sessionManager.getSftp(alias);
72
+ const totalSize = fs.statSync(localPath).size;
73
+ return pipeWithProgress(fs.createReadStream(localPath), sftp.createWriteStream(remotePath), sftp, totalSize, onProgress);
74
+ }
55
75
  /**
56
76
  * 下载文件
57
77
  */
58
78
  export async function downloadFile(alias, remotePath, localPath, onProgress) {
59
79
  const sftp = await sessionManager.getSftp(alias);
60
- // 获取远程文件大小
61
- const stats = await new Promise((resolve, reject) => {
62
- sftp.stat(remotePath, (err, stats) => {
63
- if (err) {
64
- reject(err);
65
- }
66
- else {
67
- resolve(stats);
68
- }
69
- });
70
- });
71
- const totalSize = stats.size;
80
+ const totalSize = (await sftpStat(sftp, remotePath)).size;
72
81
  // 确保本地目录存在
73
82
  const localDir = path.dirname(localPath);
74
83
  if (!fs.existsSync(localDir)) {
75
84
  fs.mkdirSync(localDir, { recursive: true });
76
85
  }
77
- return new Promise((resolve, reject) => {
78
- const readStream = sftp.createReadStream(remotePath);
79
- const writeStream = fs.createWriteStream(localPath);
80
- let settled = false;
81
- const cleanup = (err) => {
82
- if (settled) {
83
- return;
84
- }
85
- settled = true;
86
- sftp.end();
87
- if (err) {
88
- reject(err);
89
- }
90
- };
91
- let transferred = 0;
92
- readStream.on('data', (chunk) => {
93
- transferred += chunk.length;
94
- if (onProgress) {
95
- onProgress({
96
- transferred,
97
- total: totalSize,
98
- percent: totalSize > 0 ? Math.round((transferred / totalSize) * 100) : 100,
99
- });
100
- }
101
- });
102
- readStream.on('error', (err) => cleanup(err));
103
- writeStream.on('error', (err) => cleanup(err));
104
- writeStream.on('close', () => {
105
- if (!settled) {
106
- settled = true;
107
- sftp.end();
108
- resolve({ success: true, size: totalSize });
109
- }
110
- });
111
- readStream.pipe(writeStream);
112
- });
86
+ return pipeWithProgress(sftp.createReadStream(remotePath), fs.createWriteStream(localPath), sftp, totalSize, onProgress);
113
87
  }
114
88
  /**
115
89
  * 读取远程文件内容
116
90
  */
117
91
  export async function readFile(alias, remotePath, maxBytes = 1024 * 1024) {
118
92
  const sftp = await sessionManager.getSftp(alias);
119
- // 获取文件大小
120
- const stats = await new Promise((resolve, reject) => {
121
- sftp.stat(remotePath, (err, stats) => {
122
- if (err) {
123
- reject(err);
124
- }
125
- else {
126
- resolve(stats);
127
- }
128
- });
129
- });
130
- const actualSize = stats.size;
93
+ const actualSize = (await sftpStat(sftp, remotePath)).size;
131
94
  const truncated = actualSize > maxBytes;
132
95
  // 处理空文件
133
96
  if (actualSize === 0) {
@@ -197,9 +160,9 @@ export async function listDir(alias, remotePath, showHidden = false) {
197
160
  name: item.filename,
198
161
  path: path.posix.join(remotePath, item.filename),
199
162
  size: item.attrs.size,
200
- isDirectory: (item.attrs.mode & 0o40000) !== 0,
201
- isFile: (item.attrs.mode & 0o100000) !== 0,
202
- isSymlink: (item.attrs.mode & 0o120000) !== 0,
163
+ isDirectory: (item.attrs.mode & S_IFDIR) !== 0,
164
+ isFile: (item.attrs.mode & S_IFREG) !== 0,
165
+ isSymlink: (item.attrs.mode & S_IFLNK) !== 0,
203
166
  permissions: formatPermissions(item.attrs.mode),
204
167
  owner: item.attrs.uid,
205
168
  group: item.attrs.gid,
@@ -234,9 +197,9 @@ export async function getFileInfo(alias, remotePath) {
234
197
  name: path.posix.basename(remotePath),
235
198
  path: remotePath,
236
199
  size: stats.size,
237
- isDirectory: (stats.mode & 0o40000) !== 0,
238
- isFile: (stats.mode & 0o100000) !== 0,
239
- isSymlink: (stats.mode & 0o120000) !== 0,
200
+ isDirectory: (stats.mode & S_IFDIR) !== 0,
201
+ isFile: (stats.mode & S_IFREG) !== 0,
202
+ isSymlink: (stats.mode & S_IFLNK) !== 0,
240
203
  permissions: formatPermissions(stats.mode),
241
204
  owner: stats.uid,
242
205
  group: stats.gid,
@@ -246,18 +209,6 @@ export async function getFileInfo(alias, remotePath) {
246
209
  });
247
210
  });
248
211
  }
249
- /**
250
- * 检查文件是否存在
251
- */
252
- export async function fileExists(alias, remotePath) {
253
- const sftp = await sessionManager.getSftp(alias);
254
- return new Promise((resolve) => {
255
- sftp.stat(remotePath, (err) => {
256
- sftp.end();
257
- resolve(!err);
258
- });
259
- });
260
- }
261
212
  /**
262
213
  * 创建目录
263
214
  */
@@ -280,23 +231,6 @@ export async function mkdir(alias, remotePath, recursive = false) {
280
231
  });
281
232
  });
282
233
  }
283
- /**
284
- * 删除文件
285
- */
286
- export async function removeFile(alias, remotePath) {
287
- const sftp = await sessionManager.getSftp(alias);
288
- return new Promise((resolve, reject) => {
289
- sftp.unlink(remotePath, (err) => {
290
- sftp.end();
291
- if (err) {
292
- reject(err);
293
- }
294
- else {
295
- resolve(true);
296
- }
297
- });
298
- });
299
- }
300
234
  /**
301
235
  * 检查远程是否安装 rsync
302
236
  */
@@ -319,16 +253,11 @@ export async function checkRsync(alias) {
319
253
  * @param options 同步选项
320
254
  */
321
255
  export async function syncFiles(alias, localPath, remotePath, direction, options = {}) {
322
- // 检查远程 rsync
323
256
  const hasRsync = await checkRsync(alias);
324
257
  if (hasRsync) {
325
- // 使用 rsync(通过远程端执行)
326
258
  return syncWithRsync(alias, localPath, remotePath, direction, options);
327
259
  }
328
- else {
329
- // 回退到 SFTP
330
- return syncWithSftp(alias, localPath, remotePath, direction, options);
331
- }
260
+ return syncWithSftp(alias, localPath, remotePath, direction, options);
332
261
  }
333
262
  /**
334
263
  * 转义 shell 路径参数
@@ -411,11 +340,16 @@ async function syncWithRsync(alias, localPath, remotePath, direction, options) {
411
340
  return syncWithSftp(alias, localPath, remotePath, direction, options);
412
341
  }
413
342
  }
414
- /**
415
- * 使用 SFTP 同步文件
416
- */
343
+ function buildSyncResult(fileCount, totalSize, warnings) {
344
+ return {
345
+ success: true,
346
+ method: 'sftp',
347
+ filesTransferred: fileCount,
348
+ bytesTransferred: totalSize,
349
+ output: warnings.length ? `Warning: ${warnings.join('; ')}` : undefined,
350
+ };
351
+ }
417
352
  async function syncWithSftp(alias, localPath, remotePath, direction, options) {
418
- // SFTP 模式不支持 delete 选项
419
353
  const warnings = [];
420
354
  if (options.delete) {
421
355
  warnings.push('delete option is not supported in SFTP mode (requires rsync)');
@@ -429,55 +363,23 @@ async function syncWithSftp(alias, localPath, remotePath, direction, options) {
429
363
  };
430
364
  }
431
365
  try {
432
- let result;
433
366
  if (direction === 'upload') {
434
- // 检查是否是目录
435
367
  const stats = fs.statSync(localPath);
436
368
  if (stats.isDirectory() && options.recursive !== false) {
437
- result = await uploadDirectory(alias, localPath, remotePath, options.exclude);
438
- return {
439
- success: true,
440
- method: 'sftp',
441
- filesTransferred: result.fileCount,
442
- bytesTransferred: result.totalSize,
443
- output: warnings.length ? `Warning: ${warnings.join('; ')}` : undefined,
444
- };
445
- }
446
- else {
447
- result = await uploadFile(alias, localPath, remotePath);
448
- return {
449
- success: result.success,
450
- method: 'sftp',
451
- filesTransferred: 1,
452
- bytesTransferred: result.size,
453
- output: warnings.length ? `Warning: ${warnings.join('; ')}` : undefined,
454
- };
369
+ const { fileCount, totalSize } = await uploadDirectory(alias, localPath, remotePath, options.exclude);
370
+ return buildSyncResult(fileCount, totalSize, warnings);
455
371
  }
372
+ const { size } = await uploadFile(alias, localPath, remotePath);
373
+ return buildSyncResult(1, size, warnings);
456
374
  }
457
- else {
458
- // 下载
459
- const info = await getFileInfo(alias, remotePath);
460
- if (info.isDirectory && options.recursive !== false) {
461
- result = await downloadDirectory(alias, remotePath, localPath, options.exclude);
462
- return {
463
- success: true,
464
- method: 'sftp',
465
- filesTransferred: result.fileCount,
466
- bytesTransferred: result.totalSize,
467
- output: warnings.length ? `Warning: ${warnings.join('; ')}` : undefined,
468
- };
469
- }
470
- else {
471
- result = await downloadFile(alias, remotePath, localPath);
472
- return {
473
- success: result.success,
474
- method: 'sftp',
475
- filesTransferred: 1,
476
- bytesTransferred: result.size,
477
- output: warnings.length ? `Warning: ${warnings.join('; ')}` : undefined,
478
- };
479
- }
375
+ // download
376
+ const info = await getFileInfo(alias, remotePath);
377
+ if (info.isDirectory && options.recursive !== false) {
378
+ const { fileCount, totalSize } = await downloadDirectory(alias, remotePath, localPath, options.exclude);
379
+ return buildSyncResult(fileCount, totalSize, warnings);
480
380
  }
381
+ const { size } = await downloadFile(alias, remotePath, localPath);
382
+ return buildSyncResult(1, size, warnings);
481
383
  }
482
384
  catch (err) {
483
385
  return {
@@ -561,14 +463,14 @@ function matchPattern(name, pattern) {
561
463
  * 格式化权限字符串
562
464
  */
563
465
  function formatPermissions(mode) {
564
- const types = {
565
- 0o40000: 'd',
566
- 0o120000: 'l',
567
- 0o100000: '-',
568
- };
466
+ const types = [
467
+ [S_IFDIR, 'd'],
468
+ [S_IFLNK, 'l'],
469
+ [S_IFREG, '-'],
470
+ ];
569
471
  let type = '-';
570
- for (const [mask, char] of Object.entries(types)) {
571
- if ((mode & parseInt(mask)) !== 0) {
472
+ for (const [mask, char] of types) {
473
+ if ((mode & mask) !== 0) {
572
474
  type = char;
573
475
  break;
574
476
  }