UNPKG

cerevox

Version:

TypeScript SDK for browser automation and secure command execution in highly available and scalable micro computer environments

548 lines (410 loc) 14.3 kB
# Cerevox > TypeScript SDK for browser automation and secure command execution in highly available and scalable cloud environments [![npm version](https://badge.fury.io/js/cerevox.svg)](https://badge.fury.io/js/cerevox) [![TypeScript](https://img.shields.io/badge/TypeScript-5.8+-blue.svg)](https://www.typescriptlang.org/) [![Node.js](https://img.shields.io/badge/Node.js-18+-green.svg)](https://nodejs.org/) [![License: ISC](https://img.shields.io/badge/License-ISC-yellow.svg)](https://opensource.org/licenses/ISC) ## 🎯 项目概述 Cerevox 是一个基于 TypeScript 的浏览器自动化和安全命令执行 SDK,专为高可用和可扩展的云浏览器环境设计。它提供了完整的沙箱环境管理、浏览器控制、文件系统操作和终端命令执行功能。 ### 核心特性 - 🚀 **云浏览器自动化** - 基于 E2B 和 Playwright 的高性能浏览器控制 - 🔒 **安全沙箱环境** - 隔离的命令执行环境,确保安全性 - 📁 **文件系统操作** - 完整的文件上传、下载、读写功能 - 💻 **终端命令执行** - 实时流式输出的命令执行 - 🤖 **AI 功能集成** - 图像生成、视频制作、背景音乐生成等 AI 能力 - 📝 **多语言代码执行** - 支持 TypeScript、JavaScript、Python、Shell 脚本执行 - 📊 **高性能日志** - 基于 Pino 的结构化日志系统 - 🎨 **TypeScript 严格模式** - 完整的类型安全保障 - 🔧 **模块化设计** - 高内聚低耦合的架构设计 ## 📦 安装 ```bash # 使用 pnpm (推荐) pnpm add cerevox # 使用 npm npm install cerevox # 使用 yarn yarn add cerevox ``` ## 🚀 快速开始 ### 基础使用 ```typescript import { Cerevox } from 'cerevox'; import { chromium } from 'playwright'; async function main() { // 初始化 Cerevox 实例 const cerevox = new Cerevox({ apiKey: 'your-api-key', // 或通过环境变量 CEREVOX_API_KEY debug: true }); // 启动云浏览器会话 const session = await cerevox.launch({ browser: { type: 'chrome-stable', headless: false, liveview: true } }); // 连接到浏览器 const browser = await chromium.connectOverCDP(session.browser.endpoint); const page = await browser.newPage(); // 执行浏览器操作 await page.goto('https://example.com'); await page.screenshot({ path: './screenshot.png' }); // 清理资源 await page.close(); await browser.close(); await session.close(); } main().catch(console.error); ``` ### 文件系统操作 ```typescript import { Cerevox } from 'cerevox'; async function fileOperations() { const cerevox = new Cerevox(); const session = await cerevox.launch(); // 写入文件 await session.files.write('/home/user/test.txt', 'Hello World!'); // 读取文件 const content = await session.files.read('/home/user/test.txt'); console.log(content); // "Hello World!" // 上传本地文件 await session.files.upload('./local-file.txt', '/home/user/remote-file.txt'); // 下载远程文件 await session.files.download('/home/user/remote-file.txt', './downloaded-file.txt'); // 列出目录内容 const files = await session.files.listFiles('/home/user'); console.log(files); await session.close(); } ``` ### 终端命令执行 ```typescript import { Cerevox } from 'cerevox'; async function runCommands() { const cerevox = new Cerevox(); const session = await cerevox.launch(); // 执行命令并获取结果 const result = await session.terminal.run('ls -la'); console.log(await result.json()); // 流式输出 const process = await session.terminal.run('npm install'); process.stdout.pipe(process.stdout); process.stderr.pipe(process.stderr); await process.end(); await session.close(); } ``` ### 代码执行 ```typescript import { Cerevox } from 'cerevox'; async function runCode() { const cerevox = new Cerevox(); const session = await cerevox.launch(); // 执行 Python 代码 const pythonCode = ` print("Hello from Python!") import requests response = requests.get("https://api.github.com") print(f"Status: {response.status_code}") `; const pythonResult = await session.codeRunner.run(pythonCode); console.log(await pythonResult); // 执行 Shell 脚本 const shellCode = `#!/bin/bash echo "Hello from Shell!" ls -la pwd `; const shellResult = await session.codeRunner.run(shellCode); console.log(await shellResult); // 执行 TypeScript 代码 const tsCode = ` import { chromium } from 'playwright'; async function main() { const browser = await chromium.launch(); const page = await browser.newPage(); await page.goto('https://example.com'); const title = await page.title(); console.log('Page title:', title); await browser.close(); } main(); `; const tsResult = await session.codeRunner.run(tsCode, { inject: true }); console.log(await tsResult); await session.close(); } ``` ### AI 功能 ```typescript import { Cerevox } from 'cerevox'; async function useAI() { const cerevox = new Cerevox(); const session = await cerevox.launch(); // 获取可用的 AI 模型 const models = await session.ai.getModels(); console.log('Available models:', models); // 生成图像 const imageResult = await session.ai.generateImage({ prompt: '一只可爱的橘猫在阳光下睡觉', size: '1024x1024' }); console.log('Generated image:', imageResult); // 帧到视频转换 const videoResult = await session.ai.framesToVideo({ prompt: '让这只猫动起来', start_frame: '/path/to/start_frame.jpg', end_frame: '/path/to/end_frame.jpg', duration: 5, resolution: '720p' }); console.log('Generated video:', videoResult); // 生成背景音乐 const bgmResult = await session.ai.generateBGM({ Text: '轻松愉快的背景音乐', Duration: 30 }); console.log('Generated BGM:', bgmResult); await session.close(); } ``` ## 🏗️ 架构设计 ### 核心模块 - **Cerevox** - 主入口类,负责会话管理和配置 - **Session** - 会话管理,提供统一的资源访问接口 - **Browser** - 浏览器控制,基于 Playwright 的浏览器操作 - **FileSystem** - 文件系统操作,支持本地和远程文件管理 - **Terminal** - 终端命令执行,支持实时流式输出 - **CodeRunner** - 代码执行引擎,支持 TypeScript、JavaScript、Python、Shell 脚本 - **AI** - AI 功能集成,提供图像生成、视频制作、背景音乐生成等能力 - **Logger** - 高性能日志系统,基于 Pino 实现 ### 技术栈 - **语言**: TypeScript 5.8+ (严格模式) - **运行时**: Node.js 18+ - **模块系统**: CommonJS - **包管理**: pnpm - **浏览器引擎**: Playwright Core - **沙箱环境**: E2B - **日志系统**: Pino - **构建工具**: TypeScript Compiler + esbuild ## 📚 API 文档 ### Cerevox 类 #### 构造函数 ```typescript const cerevox = new Cerevox({ apiKey?: string; // API 密钥,默认从环境变量读取 debug?: boolean; // 调试模式,默认 false logLevel?: 'debug' | 'info' | 'warn' | 'error' | 'fatal'; // 日志级别 }); ``` #### 方法 - `launch(config?: ILaunchConfig): Promise<Session>` - 启动新的浏览器会话 - `connect(sandboxId: string): Promise<Session>` - 连接到现有沙箱 ### Session 类 #### 属性 - `browser: Browser` - 浏览器控制实例 - `files: FileSystem` - 文件系统操作实例 - `terminal: Terminal` - 终端操作实例 - `codeRunner: CodeRunner` - 代码执行引擎实例 - `ai: AI` - AI 功能实例 #### 方法 - `getHost(): string` - 获取会话主机地址 - `close(force?: boolean): Promise<void>` - 关闭会话 ### CodeRunner 类 #### 方法 - `run(code: string, options?: RunOptions): Promise<ExecutionResult>` - 执行代码 - `code` - 要执行的代码字符串 - `options.inject?` - 是否注入浏览器启动参数(仅 TypeScript/JavaScript) - `options.timeout?` - 执行超时时间(毫秒) #### 支持的代码类型 - **TypeScript** - 自动检测 ES 模块语法 - **JavaScript** - 支持 CommonJS 和 ES 模块 - **Python** - 自动检测 Python 语法特征 - **Shell** - 检测 `#!/bin/bash` 开头的脚本 ### AI 类 #### 方法 - `getModels(): Promise<string[]>` - 获取可用的 AI 模型列表 - `generateImage(params: ImageGenerationParams): Promise<ImageResult>` - 生成图像 - `framesToVideo(params: VideoGenerationParams): Promise<VideoResult>` - 帧到视频转换 - `generateBGM(params: BGMGenerationParams): Promise<BGMResult>` - 生成背景音乐 #### 接口定义 ```typescript interface ImageGenerationParams { prompt: string; size?: string; quality?: string; style?: string; } interface VideoGenerationParams { prompt: string; start_frame: string; end_frame: string; duration: number; resolution?: string; } interface BGMGenerationParams { Text: string; Duration: number; Style?: string; } ``` ### 配置接口 ```typescript interface IBrowserConfig { type?: 'chromium' | 'chrome-stable'; // 浏览器类型 args?: string[]; // 浏览器启动参数 headless?: boolean; // 无头模式 liveview?: boolean; // 实时预览 adblock?: boolean; // 广告拦截 webgl?: boolean; // WebGL 支持 } interface ILaunchConfig { browser?: IBrowserConfig; // 浏览器配置 timeoutMS?: number; // 超时时间 keepAliveMS?: number; // 保活时间 metadata?: Record<string, string>; // 元数据 } interface RunOptions { inject?: boolean; timeout?: number; } ``` ## 🔧 开发指南 ### 环境要求 - Node.js 18+ - pnpm 8+ - TypeScript 5.8+ ### 本地开发 ```bash # 克隆项目 git clone https://github.com/liubei-ai/cerevox.git cd cerevox # 安装依赖 pnpm install # 构建项目 pnpm build # 运行示例 pnpm dev # 代码检查 pnpm lint # 代码格式化 pnpm format ``` ### 项目结构 ``` cerevox/ ├── src/ # 核心源码 │ ├── index.ts # 主入口文件 │ ├── core/ # 核心模块 │ │ ├── cerevox.ts # 主类 │ │ ├── session.ts # 会话管理 │ │ ├── browser.ts # 浏览器控制 │ │ ├── file-system.ts # 文件系统 │ │ ├── terminal.ts # 终端操作 │ │ ├── code-runner.ts # 代码执行引擎 │ │ └── ai.ts # AI 功能集成 │ └── utils/ # 工具函数 │ ├── logger.ts # 日志系统 │ ├── detect-code.ts # 代码类型检测 │ └── volc-signv4.ts # 火山引擎签名工具 ├── sandbox/ # 沙箱环境代码 ├── examples/ # 使用示例 ├── scripts/ # 构建脚本 └── dist/ # 编译输出 ``` ## 🧪 测试 ```bash # 运行测试 pnpm test # 运行测试并生成覆盖率报告 pnpm test:coverage ``` ## 🛠️ Template 构建 Cerevox 支持构建自定义的 E2B 沙盒模板,提供预配置的浏览器环境: ### 构建 Chromium Template ```bash # 构建 Chromium 模板 pnpm run deploy:chromium ``` 这将创建一个名为 `cerevox-chromium` 的模板,包含: - Chromium 浏览器 - 4GB 内存,4核 CPU - 预配置的沙盒环境 ### 构建 Chrome Stable Template ```bash # 构建 Chrome Stable 模板 pnpm run deploy:chrome ``` 这将创建一个名为 `cerevox-chrome-stable` 的模板,包含: - Chrome 稳定版浏览器 - 4GB 内存,4核 CPU - 预配置的沙盒环境 ### Template 配置 模板配置文件位于: - `chromium.toml` - Chromium 模板配置 - `chrome-stable.toml` - Chrome Stable 模板配置 ## 🖥️ CLI 工具 - cerevox-run Cerevox 提供了一个强大的 CLI 工具,可以直接运行 TypeScript/JavaScript 文件在沙盒环境中: ### 安装和使用 ```bash # 通过 npx 直接运行(推荐) npx cerevox-run your-script.ts # 或者全局安装 npm install -g cerevox cerevox-run your-script.ts ``` ### CLI 选项 ```bash cerevox-run [options] <file> 参数: file 要运行的 JavaScript 或 TypeScript 文件 选项: -V, --version 显示版本号 -k, --key <string> Cerevox API 密钥(可选,如果设置了 CEREVOX_API_KEY 环境变量) -l, --listen <number> 监听端口号 -h, --help 显示帮助信息 ``` ### 使用示例 ```bash # 基础使用 npx cerevox-run script.ts # 指定 API 密钥 npx cerevox-run -k your-api-key script.ts # 指定监听端口 npx cerevox-run -l 3000 web-server.ts ``` ### 环境变量配置 创建 `.env.cerevox` 文件: ```bash CEREVOX_API_KEY=your-api-key-here ``` ### CLI 特性 - **自动代码转换**:自动将 Playwright 的 `launch()` 方法替换为 `connectOverCDP()` - **TypeScript 支持**:原生支持 TypeScript 文件 - **实时预览**:非 headless 模式下自动打开浏览器预览 - **智能打包**:使用 esbuild 进行代码打包和优化 - **环境管理**:自动创建和管理 API 密钥配置文件 - **代码执行**:支持 TypeScript、JavaScript、Python、Shell 脚本执行 - **AI 功能**:集成图像生成、视频制作、背景音乐生成等 AI 能力 - **文件管理**:支持文件上传下载和目录操作 - **命令执行**:实时执行终端命令 ## 📄 许可证 ISC License - 详见 [LICENSE](LICENSE) 文件 ## 🤝 贡献 欢迎提交 Issue 和 Pull Request! ### 开发规范 - 遵循 TypeScript 严格模式 - 使用 ESLint + Prettier 代码规范 - 所有函数必须包含类型注解 - 提交前运行 `pnpm lint` 检查代码 ## 📞 支持 - 📧 Email: support@cerevox.io - 🐛 Issues: [GitHub Issues](https://github.com/liubei-ai/cerevox/issues) - 📖 文档: [官方文档](https://github.com/liubei-ai/cerevox#readme) ## 🔗 相关链接 - [E2B Platform](https://e2b.dev/) - 云沙箱环境 - [Playwright](https://playwright.dev/) - 浏览器自动化 - [Pino](https://getpino.io/) - 高性能日志 --- **Cerevox** - 让浏览器自动化更简单、更安全、更高效 🚀