{"_id":"@afjs/adb-sdk","name":"@afjs/adb-sdk","dist-tags":{"latest":"1.0.0"},"versions":{"1.0.0":{"name":"@afjs/adb-sdk","version":"1.0.0","description":"A lightweight ADB SDK for Node.js","type":"module","main":"dist/index.js","types":"dist/index.d.ts","scripts":{"build":"tsdown","dev":"tsx watch src/index.ts","test":"vitest","test:watch":"vitest --watch","test:coverage":"vitest --coverage","test:ui":"vitest --ui","test:run":"vitest run","prepare":"pnpm build"},"dependencies":{"dayjs":"^1.11.18"},"devDependencies":{"@types/node":"^20.19.12","@vitest/coverage-v8":"^1.2.0","@vitest/ui":"^1.2.0","tsdown":"^0.14.2","tsx":"^4.20.5","typescript":"^5.9.2","vitest":"^1.2.0"},"keywords":["adb","android","debug","bridge","sdk"],"author":{"name":"TinsFox"},"license":"MIT","_id":"@afjs/adb-sdk@1.0.0","gitHead":"719fc41eab126895aa1f3c766f9786ef84b3a4fe","_nodeVersion":"22.14.0","_npmVersion":"10.9.2","dist":{"integrity":"sha512-8imXq4sg8eotmLetTrkLwRbJAiFgg8nLhXhsxUoPupXtrN0aNJrxGwWJL3lGJ1F3YpE/qIFUPFcPXasjPwQxLg==","shasum":"332e1582b9f1426b2ffacc1a9c2a7d1c012f8065","tarball":"https://registry.npmjs.org/@afjs/adb-sdk/-/adb-sdk-1.0.0.tgz","fileCount":36,"unpackedSize":719046,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEYCIQDc+pUKcLikQrtJsp/VE8Su7X4z5ZLowr1cCX2j3aZcewIhANLnmtoZCkUwLiWWghYu6kNlmx1oea7UFWOhJGlCP9BP"}]},"_npmUser":{"name":"tinsfox","email":"menhuluy@gmail.com"},"directories":{},"maintainers":[{"name":"tinsfox","email":"menhuluy@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/adb-sdk_1.0.0_1762158253042_0.5286696990519728"},"_hasShrinkwrap":false}},"time":{"created":"2025-11-03T08:24:12.921Z","1.0.0":"2025-11-03T08:24:13.263Z","modified":"2025-11-03T08:24:13.590Z"},"maintainers":[{"name":"tinsfox","email":"menhuluy@gmail.com"}],"description":"A lightweight ADB SDK for Node.js","keywords":["adb","android","debug","bridge","sdk"],"author":{"name":"TinsFox"},"license":"MIT","readme":"# ADB SDK\n\n[![npm version](https://badge.fury.io/js/%40afjs%2Fadb-sdk.svg)](https://badge.fury.io/js/%40afjs%2Fadb-sdk)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n[![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue.svg)](https://www.typescriptlang.org/)\n\n一个轻量级、类型安全的 Android Debug Bridge (ADB) SDK，专为 Node.js 环境设计。提供完整的 ADB 功能封装，支持设备管理、文件传输、应用安装、性能监控等功能。\n\n## 特性\n\n- 🚀 **完整的 ADB 功能**：支持设备连接、文件传输、应用管理等所有常用 ADB 操作\n- 📱 **设备信息获取**：获取详细的设备系统信息、硬件信息、性能数据\n- 🔧 **类型安全**：完整的 TypeScript 类型定义，提供优秀的开发体验\n- ⚡ **异步支持**：基于 Promise 的现代异步 API\n- 🛡️ **错误处理**：完善的错误处理和超时机制\n- 📊 **性能监控**：实时获取 CPU、内存、GPU、电池等性能数据\n- 🎯 **易于使用**：简洁的 API 设计，支持链式调用\n- 🧪 **测试覆盖**：完整的单元测试覆盖\n\n## 安装\n\n```bash\nnpm install @afjs/adb-sdk\n```\n\n或使用 yarn：\n\n```bash\nyarn add @afjs/adb-sdk\n```\n\n或使用 pnpm：\n\n```bash\npnpm add @afjs/adb-sdk\n```\n\n## 前置要求\n\n- Node.js >= 16.0.0\n- 系统中已安装 ADB 工具\n- Android 设备已开启 USB 调试或网络 ADB\n\n### 安装 ADB\n\n**macOS (使用 Homebrew):**\n```bash\nbrew install android-platform-tools\n```\n\n**Ubuntu/Debian:**\n```bash\nsudo apt-get install android-tools-adb\n```\n\n**Windows:**\n下载 [Android SDK Platform Tools](https://developer.android.com/studio/releases/platform-tools) 并添加到系统 PATH。\n\n## 快速开始\n\n### 基础用法\n\n```typescript\nimport { AdbClient, AdbService, createAdbClient } from '@afjs/adb-sdk';\n\n// 创建 ADB 客户端\nconst client = createAdbClient({\n  host: 'localhost',\n  port: 5037,\n  timeout: 30000\n});\n\n// 或者使用高级服务类\nconst service = new AdbService();\n\n// 检查 ADB 是否可用\nconst isAvailable = await client.isAvailable();\nconsole.log('ADB 可用:', isAvailable);\n\n// 获取设备列表\nconst devicesResult = await client.listDevices();\nif (devicesResult.success) {\n  console.log('连接的设备:', devicesResult.devices);\n}\n```\n\n### 设备连接\n\n```typescript\n// 连接网络设备\nconst connectResult = await client.connect('192.168.1.100:5555');\nif (connectResult.success) {\n  console.log('设备连接成功');\n}\n\n// 设置设备为 TCP/IP 模式\nawait client.tcpip('device_id', 5555);\n\n// 断开设备连接\nawait client.disconnect('192.168.1.100:5555');\n```\n\n### 执行 Shell 命令\n\n```typescript\n// 执行简单命令\nconst result = await client.shell('ls /sdcard', 'device_id');\nif (result.success) {\n  console.log('命令输出:', result.output);\n}\n\n// 获取设备属性\nconst prop = await client.getProperty('ro.build.version.release');\nconsole.log('Android 版本:', prop.output);\n\n// 获取多个属性\nconst props = await client.getProperties([\n  'ro.product.manufacturer',\n  'ro.product.model',\n  'ro.build.version.release'\n]);\n```\n\n### 文件传输\n\n```typescript\n// 推送文件到设备\nconst pushResult = await client.push(\n  '/local/path/file.txt',\n  '/sdcard/file.txt',\n  'device_id'\n);\n\n// 从设备拉取文件\nconst pullResult = await client.pull(\n  '/sdcard/file.txt',\n  '/local/path/file.txt',\n  'device_id'\n);\n```\n\n### 应用管理\n\n```typescript\n// 安装 APK\nconst installResult = await client.install('/path/to/app.apk', 'device_id', {\n  replace: true,\n  grantPermissions: true\n});\n\n// 卸载应用\nconst uninstallResult = await client.uninstall('com.example.app', 'device_id');\n```\n\n## 高级功能\n\n### 设备信息获取\n\n```typescript\nconst service = new AdbService();\n\n// 获取完整设备信息\nconst deviceInfo = await service.getDeviceInfo('device_id');\nif (deviceInfo.success) {\n  const info = deviceInfo.deviceInfo!;\n\n  console.log('设备基本信息:', info.basic);\n  console.log('系统信息:', info.system);\n  console.log('显示信息:', info.display);\n  console.log('内存信息:', info.memory);\n  console.log('CPU 信息:', info.cpu);\n  console.log('电池信息:', info.battery);\n  console.log('网络信息:', info.network);\n}\n```\n\n### 性能监控\n\n```typescript\n// 获取实时性能数据\nconst perfResult = await service.getPerformanceInfo('device_id');\nif (perfResult.success) {\n  const perf = perfResult.performanceInfo!;\n\n  console.log('CPU 使用率:', perf.cpu.usage + '%');\n  console.log('内存使用率:', perf.memory.usage + '%');\n  console.log('GPU 使用率:', perf.gpu.usage + '%');\n  console.log('电池电量:', perf.battery.level + '%');\n  console.log('CPU 温度:', perf.cpu.temperature + '°C');\n}\n```\n\n### 端口转发\n\n```typescript\n// 设置端口转发\nawait client.forward('tcp:8080', 'tcp:8080', 'device_id');\n\n// 反向端口转发\nawait client.reverse('tcp:9090', 'tcp:9090', 'device_id');\n```\n\n### 设备重启\n\n```typescript\n// 重启设备\nconst rebootResult = await client.reboot('device_id');\nif (rebootResult.success) {\n  console.log('设备重启命令已发送');\n}\n```\n\n## API 参考\n\n### AdbClient\n\n主要的 ADB 客户端类，提供底层 ADB 操作。\n\n#### 构造函数\n\n```typescript\nnew AdbClient(options?: AdbClientOptions)\n```\n\n#### 配置选项\n\n```typescript\ninterface AdbClientOptions {\n  host?: string;     // ADB 服务器地址，默认 'localhost'\n  port?: number;     // ADB 服务器端口，默认 5037\n  timeout?: number;  // 命令超时时间，默认 30000ms\n}\n```\n\n#### 主要方法\n\n| 方法 | 描述 | 返回类型 |\n|------|------|----------|\n| `isAvailable()` | 检查 ADB 是否可用 | `Promise<boolean>` |\n| `startServer()` | 启动 ADB 服务 | `Promise<AdbConnectionResult>` |\n| `killServer()` | 停止 ADB 服务 | `Promise<AdbConnectionResult>` |\n| `restartServer()` | 重启 ADB 服务 | `Promise<AdbConnectionResult>` |\n| `listDevices()` | 获取设备列表 | `Promise<AdbListDevicesResult>` |\n| `connect(address)` | 连接网络设备 | `Promise<AdbConnectionResult>` |\n| `disconnect(address)` | 断开设备连接 | `Promise<AdbConnectionResult>` |\n| `tcpip(deviceId?, port?)` | 设置 TCP/IP 模式 | `Promise<AdbConnectionResult>` |\n| `usb(deviceId?)` | 设置 USB 模式 | `Promise<AdbConnectionResult>` |\n| `shell(command, deviceId?)` | 执行 Shell 命令 | `Promise<AdbShellResult>` |\n| `push(local, remote, deviceId?)` | 推送文件 | `Promise<AdbConnectionResult>` |\n| `pull(remote, local, deviceId?)` | 拉取文件 | `Promise<AdbConnectionResult>` |\n| `install(apk, deviceId?, options?)` | 安装 APK | `Promise<AdbConnectionResult>` |\n| `uninstall(package, deviceId?)` | 卸载应用 | `Promise<AdbConnectionResult>` |\n| `forward(local, remote, deviceId?)` | 端口转发 | `Promise<AdbConnectionResult>` |\n| `reverse(remote, local, deviceId?)` | 反向端口转发 | `Promise<AdbConnectionResult>` |\n| `reboot(deviceId?)` | 重启设备 | `Promise<AdbConnectionResult>` |\n| `getProperty(prop, deviceId?)` | 获取设备属性 | `Promise<AdbShellResult>` |\n| `getProperties(props, deviceId?)` | 获取多个属性 | `Promise<AdbShellResult>` |\n| `dumpsys(service, args?, deviceId?)` | 执行 dumpsys | `Promise<AdbShellResult>` |\n\n### AdbService\n\n高级服务类，提供更便捷的设备管理功能。\n\n#### 主要方法\n\n| 方法 | 描述 | 返回类型 |\n|------|------|----------|\n| `connect(deviceIP)` | 连接设备 | `Promise<AdbServiceResult>` |\n| `listDevices()` | 获取设备列表 | `Promise<AdbServiceResult>` |\n| `executeShell(cmd, deviceIP?)` | 执行命令 | `Promise<AdbServiceResult>` |\n| `disconnect(deviceIP)` | 断开连接 | `Promise<AdbServiceResult>` |\n| `restartServer()` | 重启服务 | `Promise<AdbServiceResult>` |\n| `reconnectDevice(deviceIP)` | 重连设备 | `Promise<AdbServiceResult>` |\n| `getDeviceInfo(deviceId?, useCache?)` | 获取设备信息 | `Promise<DeviceInfoResult>` |\n| `getPerformanceInfo(deviceId?)` | 获取性能信息 | `Promise<DevicePerformanceResult>` |\n| `installApk(apk, deviceId?, options?)` | 安装应用 | `Promise<AdbServiceResult>` |\n| `uninstallApp(package, deviceId?)` | 卸载应用 | `Promise<AdbServiceResult>` |\n| `pushFile(local, remote, deviceId?)` | 推送文件 | `Promise<AdbServiceResult>` |\n| `pullFile(remote, local, deviceId?)` | 拉取文件 | `Promise<AdbServiceResult>` |\n| `rebootDevice(deviceId?)` | 重启设备 | `Promise<AdbServiceResult>` |\n\n### AdbUtils\n\n工具类，提供底层 ADB 命令执行和解析功能。\n\n#### 静态方法\n\n| 方法 | 描述 | 返回类型 |\n|------|------|----------|\n| `setAdbPath(path)` | 设置 ADB 路径 | `void` |\n| `getAdbPath()` | 获取 ADB 路径 | `string` |\n| `execute(args, timeout?)` | 执行 ADB 命令 | `Promise<AdbExecuteResult>` |\n| `executeSimple(args)` | 执行简单命令 | `Promise<string>` |\n| `parseDevices(output)` | 解析设备列表 | `AdbDevice[]` |\n| `escapeShellArg(arg)` | 转义 Shell 参数 | `string` |\n| `checkAdbAvailable()` | 检查 ADB 可用性 | `Promise<boolean>` |\n| `wait(ms)` | 等待指定时间 | `Promise<void>` |\n\n## 类型定义\n\n### 设备信息类型\n\n```typescript\ninterface AdbDevice {\n  id: string;\n  state: 'device' | 'offline' | 'unauthorized' | 'host' | 'recovery' | 'rescue' | 'sideload' | 'bootloader' | 'unknown';\n  product?: string;\n  model?: string;\n  device?: string;\n  features?: string[];\n}\n\ninterface DeviceInfo {\n  basic: {\n    deviceId: string;\n    serialNumber: string;\n    state: AdbDevice['state'];\n  };\n  system: DeviceSystemInfo;\n  display: DeviceDisplayInfo;\n  memory: DeviceMemoryInfo;\n  cpu: DeviceCpuInfo;\n  battery: DeviceBatteryInfo;\n  network: DeviceNetworkInfo;\n  lastUpdated: Date;\n}\n```\n\n### 性能信息类型\n\n```typescript\ninterface DevicePerformanceInfo {\n  cpu: {\n    usage: number;        // CPU 使用率 (%)\n    frequency: number;    // CPU 频率 (MHz)\n    temperature: number;  // CPU 温度 (°C)\n    cores: number;        // CPU 核心数\n    loadAverage: number;  // 负载平均值\n  };\n  memory: {\n    total: number;        // 总内存 (MB)\n    used: number;         // 已用内存 (MB)\n    available: number;    // 可用内存 (MB)\n    usage: number;        // 内存使用率 (%)\n    swapTotal: number;    // 总交换空间 (MB)\n    swapUsed: number;     // 已用交换空间 (MB)\n    swapAvailable: number; // 可用交换空间 (MB)\n  };\n  gpu: {\n    usage: number;        // GPU 使用率 (%)\n    frequency: number;    // GPU 频率 (MHz)\n    temperature: number;  // GPU 温度 (°C)\n    memoryTotal: number;  // GPU 总内存 (MB)\n    memoryUsed: number;   // GPU 已用内存 (MB)\n    memoryAvailable: number; // GPU 可用内存 (MB)\n  };\n  battery: {\n    level: number;        // 电池电量 (%)\n    temperature: number;  // 电池温度 (°C)\n    voltage: number;      // 电池电压 (mV)\n    health: string;       // 电池健康状态\n    status: string;       // 充电状态\n  };\n  timestamp: Date;        // 数据采集时间\n}\n```\n\n### 结果类型\n\n```typescript\ninterface AdbConnectionResult {\n  success: boolean;\n  message: string;\n  error?: Error;\n}\n\ninterface AdbShellResult {\n  success: boolean;\n  output?: string;\n  error?: Error;\n}\n\ninterface AdbServiceResult {\n  success: boolean;\n  message?: string;\n  error?: Error | string;\n  devices?: AdbDevice[];\n  result?: string;\n}\n```\n\n## 错误处理\n\nSDK 提供了完善的错误处理机制：\n\n```typescript\ntry {\n  const result = await client.connect('192.168.1.100:5555');\n  if (!result.success) {\n    console.error('连接失败:', result.message);\n    if (result.error) {\n      console.error('错误详情:', result.error.message);\n    }\n  }\n} catch (error) {\n  console.error('意外错误:', error);\n}\n```\n\n### 常见错误类型\n\n- **连接超时**：设备无响应或网络问题\n- **设备未授权**：设备未允许 USB 调试\n- **ADB 不可用**：系统未安装 ADB 或路径配置错误\n- **命令执行失败**：ADB 命令返回非零退出码\n\n## 最佳实践\n\n### 1. 错误处理\n\n```typescript\n// 总是检查操作结果\nconst result = await client.listDevices();\nif (!result.success) {\n  console.error('获取设备列表失败:', result.error?.message);\n  return;\n}\n\n// 使用 try-catch 处理异常\ntry {\n  await client.shell('some-command');\n} catch (error) {\n  console.error('命令执行异常:', error);\n}\n```\n\n### 2. 设备管理\n\n```typescript\n// 在操作前检查设备状态\nconst devices = await client.listDevices();\nconst targetDevice = devices.devices?.find(d => d.state === 'device');\nif (!targetDevice) {\n  throw new Error('没有可用的设备');\n}\n```\n\n### 3. 性能优化\n\n```typescript\n// 使用缓存避免频繁获取设备信息\nconst service = new AdbService();\nconst deviceInfo = await service.getDeviceInfo('device_id', true); // 使用缓存\n\n// 设置合适的超时时间\nconst client = new AdbClient({ timeout: 60000 }); // 60秒超时\n```\n\n### 4. 资源清理\n\n```typescript\n// 在应用结束时清理资源\nprocess.on('exit', async () => {\n  await client.killServer();\n});\n```\n\n## 示例项目\n\n### 设备监控工具\n\n```typescript\nimport { AdbService } from '@afjs/adb-sdk';\n\nclass DeviceMonitor {\n  private service = new AdbService();\n  private monitoring = false;\n\n  async startMonitoring(deviceId: string) {\n    this.monitoring = true;\n\n    while (this.monitoring) {\n      try {\n        const perfResult = await this.service.getPerformanceInfo(deviceId);\n        if (perfResult.success) {\n          const perf = perfResult.performanceInfo!;\n          console.log(`CPU: ${perf.cpu.usage}%, 内存: ${perf.memory.usage}%, 电池: ${perf.battery.level}%`);\n        }\n\n        await new Promise(resolve => setTimeout(resolve, 5000)); // 5秒间隔\n      } catch (error) {\n        console.error('监控错误:', error);\n        break;\n      }\n    }\n  }\n\n  stopMonitoring() {\n    this.monitoring = false;\n  }\n}\n\n// 使用示例\nconst monitor = new DeviceMonitor();\nmonitor.startMonitoring('192.168.1.100:5555');\n```\n\n### 批量应用安装\n\n```typescript\nimport { AdbService } from '@afjs/adb-sdk';\nimport { readdir } from 'fs/promises';\nimport { join } from 'path';\n\nasync function batchInstallApks(apkDirectory: string, deviceId: string) {\n  const service = new AdbService();\n\n  try {\n    const files = await readdir(apkDirectory);\n    const apkFiles = files.filter(file => file.endsWith('.apk'));\n\n    console.log(`找到 ${apkFiles.length} 个 APK 文件`);\n\n    for (const apkFile of apkFiles) {\n      const apkPath = join(apkDirectory, apkFile);\n      console.log(`正在安装: ${apkFile}`);\n\n      const result = await service.installApk(apkPath, deviceId, {\n        replace: true,\n        grantPermissions: true\n      });\n\n      if (result.success) {\n        console.log(`✓ ${apkFile} 安装成功`);\n      } else {\n        console.error(`✗ ${apkFile} 安装失败:`, result.message);\n      }\n    }\n  } catch (error) {\n    console.error('批量安装失败:', error);\n  }\n}\n```\n\n## 更新日志\n\n### [1.0.0] - 2024-11-03\n\n#### 新增\n- 完整的 ADB 客户端实现\n- 设备信息获取功能\n- 性能监控功能\n- 文件传输支持\n- 应用管理功能\n- 完整的 TypeScript 类型定义\n- 单元测试覆盖\n\n## 许可证\n\n本项目采用 [MIT 许可证](./LICENSE)。\n\n## 相关链接\n\n- [Android Debug Bridge (ADB) 官方文档](https://developer.android.com/studio/command-line/adb)\n- [Android SDK Platform Tools](https://developer.android.com/studio/releases/platform-tools)\n- [TypeScript 官方网站](https://www.typescriptlang.org/)\n\n---\n\n**注意**: 本 SDK 需要系统中已安装 ADB 工具。请确保 ADB 在系统 PATH 中可用，或使用 `AdbUtils.setAdbPath()` 设置自定义路径。\n","readmeFilename":"README.md","_rev":"1-9e9ef4f13c92e6d85800efd19bd36190"}