@grasplabs/grasp
Version:
TypeScript SDK for browser automation and secure command execution in highly available and scalable cloud browser environments
382 lines (291 loc) โข 12.9 kB
Markdown
# ๐ Grasp SDK
[](https://www.npmjs.com/package/@grasplabs/grasp)
[](https://pypi.org/project/grasp-sdk/)
[](https://pypi.org/project/grasp-sdk/)
[](https://opensource.org/licenses/MIT)
**Multi-language SDK for browser automation and secure command execution in highly available and scalable cloud browser environments**
Grasp SDK provides a type-safe, event-driven API for browser automation and command execution in isolated cloud environments. Available for both TypeScript/JavaScript and Python.
## โจ Features
- ๐ **Cloud Browser Automation**: Launch and control Chromium browsers in isolated cloud environments
- ๐ **CDP Integration**: Chrome DevTools Protocol support with optimized WebSocket frame parsing
- โก **Command Execution**: Execute shell commands with real-time monitoring and enhanced logging
- ๐ **Secure Execution**: Run code in isolated E2B cloud environments
- ๐งช **TypeScript Support**: Full type safety and IntelliSense with improved development environment
- ๐ ๏ธ **Developer Experience**: Enhanced debugging capabilities and error handling
## ๐ Quick Start
### Installation
```bash
# Install the package
npm install @grasplabs/grasp
# or
yarn add @grasplabs/grasp
# or
pnpm add @grasplabs/grasp
```
### Initialization
```bash
# Generate API key and initialize configuration
npx -y grasp-keygen <your-app-id>
```
This will create a `.env.grasp` file with your credentials.
### Configuration
After running `grasp-keygen`, you'll have a `.env.grasp` file with your credentials:
```env
GRASP_APP_ID=your-app-id
GRASP_APP_KEY=your-app-key
```
### Basic Usage
```typescript
// Import types if needed
import type { GraspOptions } from '@grasplabs/grasp';
import grasp from '@grasplabs/grasp';
import { chromium } from 'playwright';
async function main() {
// Launch browser in cloud environment with enhanced options
const connection = await grasp.launchBrowser({
// API key is auto-loaded from .env.grasp
type: 'chromium', // Browser type: 'chromium' or 'chrome-stable'
headless: true, // Run in headless mode
adblock: false, // Disable adblock extension
timeout: 150000, // Connection timeout in milliseconds
keepAliveMS: 5000, // Keep browser alive for 5 sec
logLevel: 'info', // Set logging level
debug: false, // Disable debug mode for production
});
// Connect to the browser using Playwright
const browser = await chromium.connectOverCDP(connection.wsUrl, {
timeout: 150000,
});
// Create a new page and navigate
const page = await browser.newPage();
await page.goto('https://getgrasp.ai/', { waitUntil: 'domcontentloaded' });
await page.screenshot({ path: 'grasp-ai.png' });
await page.close();
// Create another page with custom content
const context = browser.contexts()[0] || await browser.newContext();
const page2 = await context.newPage();
await page2.setContent('<h1>Hello Grasp</h1>', { waitUntil: 'networkidle' });
await page2.screenshot({ path: 'hello-world.png', fullPage: true });
await page2.close();
// Clean up
await context.close();
await browser.close();
}
main();
```
## ๐ API Reference
### `grasp.launchBrowser(options)`
Launches a browser instance in the cloud environment.
**Parameters:**
- `options` (object, optional):
- `key` (string): Your Grasp API key (loaded from .env.grasp by default)
- `type` (string, optional): Browser type to launch. Default: 'chromium'. Available: 'chromium', 'chrome-stable'
- `headless` (boolean, optional): Whether to run browser in headless mode. Default: true
- `adblock` (boolean, optional): Whether to enable adblock extension. Default: false
- `timeout` (number, optional): Connection timeout in milliseconds. Default: 30000
- `keepAliveMS` (number, optional): Keep-alive duration in milliseconds. Default: 0
- `logLevel` (string, optional): Logging level. Available: 'debug', 'info', 'warn', 'error'. Default: 'info'
- `debug` (boolean, optional): Enable debug mode for detailed logging. Default: false
- `launchTimeout` (number, optional): Browser launch timeout in milliseconds. Default: 30000
- `envs` (object, optional): Environment variables for the browser process
- `slowMo` (number, optional): Slows down operations by specified milliseconds
**Returns:**
- `Promise<Connection>`: Connection object with:
- `id` (string): Unique browser instance ID
- `wsUrl` (string): WebSocket URL for CDP connection (recommended)
- `httpUrl` (string): HTTP URL for CDP connection (legacy)
**Example:**
```typescript
const connection = await grasp.launchBrowser({
// key: process.env.GRASP_APP_KEY, // Loaded from .env.grasp
type: 'chromium', // Browser type: 'chromium' or 'chrome-stable'
headless: true, // Run in headless mode
adblock: false, // Enable adblock extension
timeout: 150000, // Connection timeout
keepAliveMS: 3600000, // Keep browser alive for 1 hour
logLevel: 'info', // Logging level: 'debug', 'info', 'warn', 'error'
debug: false, // Enable debug mode
launchTimeout: 30000, // Browser launch timeout
envs: { // Environment variables
'CUSTOM_VAR': 'value'
}
});
```
### Using with Playwright
After launching a browser, connect to it using Playwright's `connectOverCDP` method:
```typescript
import { chromium } from 'playwright';
const connection = await grasp.launchBrowser();
const browser = await chromium.connectOverCDP(connection.wsUrl, {
timeout: 150000
});
// Use browser as normal Playwright browser instance
const page = await browser.newPage();
// ... your automation code
await browser.close();
```
## ๐ Python SDK
Grasp also provides a Python SDK with the same powerful features for browser automation and command execution.
### Installation
```bash
# Install from PyPI (latest: v0.1.6)
pip install grasp_sdk
# Install from source
pip install -e ./py-src
# Install with development dependencies
pip install -e "./py-src[dev]"
```
### Environment Setup
Create a `.env.grasp` file or set environment variables:
```bash
# Required
GRASP_KEY=your_grasp_api_key_here
# Optional
GRASP_LOG_LEVEL=info
GRASP_TIMEOUT=3600000
```
### Basic Usage
```python
import asyncio
import os
from playwright.async_api import async_playwright
from dotenv import load_dotenv
from grasp_sdk import GraspServer
# ๅ ่ฝฝ็ฏๅขๅ้
load_dotenv(".env.grasp")
async def main():
"""ๆผ็คบ Grasp SDK ็ๅบๆฌ็จๆณ"""
# ๆฃๆฅ API key
api_key = os.getenv('GRASP_KEY')
if not api_key:
print("โ ๏ธ ่ฏท่ฎพ็ฝฎ GRASP_KEY ็ฏๅขๅ้")
return
print("๐ ๆญฃๅจๅฏๅจๆต่งๅจ...")
# ไฝฟ็จ GraspServer ไธไธๆ็ฎก็ๅจ
async with GraspServer({
'timeout': 3600000, # ๅฎนๅจๆ้ฟ่ฟ่ก1ๅฐๆถ
}) as connection:
print(f"WebSocket URL: {connection['ws_url']}")
# ไฝฟ็จ Playwright ่ฟๆฅๅฐ CDP
async with async_playwright() as p:
browser = await p.chromium.connect_over_cdp(
connection['ws_url'],
timeout=150000
)
# ๅๅปบ้กต้ขๅนถ่ฎฟ้ฎ็ฝ็ซ
page = await browser.new_page()
await page.goto('https://getgrasp.ai/', wait_until='domcontentloaded')
await page.screenshot(path='grasp-ai.png')
# ๅๅปบ่ชๅฎไนๅ
ๅฎน้กต้ข
page2 = await browser.new_page()
await page2.set_content('<h1>Hello Grasp</h1>', wait_until='networkidle')
await page2.screenshot(path='hello-world.png', full_page=True)
# ๆธ
็่ตๆบ
await page.close()
await page2.close()
await browser.close()
print('โ
ไปปๅกๅฎๆ๏ผ่ตๆบ่ชๅจๆธ
็')
if __name__ == "__main__":
asyncio.run(main())
```
### Python API Reference
#### `GraspServer(sandbox_config=None)`
Main class for browser automation and command execution.
**Parameters:**
- `sandbox_config` (dict, optional): Sandbox configuration overrides
- `template` (str): E2B template to use (default: 'python')
- `timeout` (int): Connection timeout in milliseconds (default: 30000)
- `api_key` (str): E2B API key (loaded from environment by default)
**Methods:**
- `async start()`: Start the sandbox environment
- `async execute_command(command, options=None)`: Execute shell command
- `async run_script(script_path, options=None)`: Run script file
- `async create_browser_task()`: Create browser automation task
- `async close()`: Clean up and close connections
**Example with Browser Automation:**
```python
import asyncio
from grasp_sdk import GraspServer
async def browser_example():
server = GraspServer()
try:
await server.start()
# Launch browser
browser = await server.launch_browser({
"headless": True,
"timeout": 150000
})
# Navigate and interact
await browser.navigate("https://getgrasp.ai/")
await browser.screenshot("grasp-ai.png")
# Execute JavaScript
title = await browser.evaluate("document.title")
print(f"Page title: {title}")
finally:
await server.close()
asyncio.run(browser_example())
```
### Features
- ๐ **Secure Execution**: Run commands in isolated E2B cloud environments
- ๐ **Browser Automation**: Control Chromium browsers with async/await
- โก **Real-time Communication**: WebSocket-based command execution
- ๐งช **Type Safety**: Complete type hints with Pydantic models
- ๐ **Async/Await**: Full async support for modern Python development
- ๐ ๏ธ **Developer Experience**: Enhanced debugging and error handling
## ๐ Language Support
Grasp SDK is available in multiple languages:
- **TypeScript/JavaScript**: `@grasplabs/grasp` (this package)
- **Python**: `grasp_sdk` (see Python SDK section above)
Both SDKs provide the same core functionality with language-specific optimizations and idioms.
## ๐ Release History
### Python SDK (`grasp_sdk`)
#### v0.1.8 (2025-01-27)
- ๐ Latest release with file path handling feature
- ๐ง Added support for file paths starting with '/home/user/' in run_script
- โก Aligned Python SDK behavior with Node.js SDK runScript function
- ๐ฆ Enhanced backward compatibility and flexibility
#### v0.1.7 (2025-01-27)
- ๐ Configuration simplification release
- ๐ง Removed templateId configuration for simplified setup
- โก Code structure optimization and cleanup
- ๐ฆ Enhanced package stability and maintainability
#### v0.1.6 (2025-01-27)
- ๐ Version synchronization release
- ๐ง Continuous improvements and optimizations
- โก Enhanced stability and performance
- ๐ฆ Updated package metadata
#### v0.1.5 (2025-01-27)
- ๐ Latest release with continuous improvements
- ๐ Enhanced documentation and examples
- ๐ง Stability improvements and optimizations
- ๐ฆ Updated package metadata
#### v0.1.4 (2025-01-27)
- โ
Version synchronization with project metadata
- ๐ฆ Updated package metadata and documentation
- ๐ง Enhanced build and publishing workflow
- ๐ Improved README with version badges and installation instructions
#### v0.1.0 (2025-01-27)
- ๐ Initial release of Python SDK
- ๐ Core browser automation functionality
- ๐ Secure command execution in E2B environments
- ๐งช Full async/await support with type hints
- ๐ Complete API compatibility with TypeScript version
### TypeScript/JavaScript SDK (`@grasplabs/grasp`)
#### v0.1.3 (2025-01-27)
- ๐ Latest release with enhanced stability
- ๐ฆ Updated package metadata and build process
- ๐ง Improved configuration and error handling
- ๐ Enhanced documentation and examples
#### Latest Updates (v0.1.1+)
- ๐ Enhanced browser automation capabilities with new configuration options
- โก Improved CDP integration and WebSocket frame parsing
- ๐ ๏ธ Better developer experience with enhanced debugging and logging
- ๐ง Added new parameters:
- `keepAliveMS`: Configure browser keep-alive duration
- `logLevel`: Granular logging control ('debug', 'info', 'warn', 'error')
- `adblock`: Built-in adblock extension support
- `launchTimeout`: Configurable browser launch timeout
- `envs`: Environment variables for browser process
- ๐ฏ Optimized performance and error handling
- ๐ Updated documentation with comprehensive parameter examples
- ๐ Enhanced graceful shutdown and resource cleanup