cs2inspects
Version:
openskindb inspect sdk with bulk processing capabilities
396 lines (292 loc) • 9.39 kB
Markdown
# CS2 Inspect SDK
A high-performance Counter-Strike 2 item inspection SDK that provides real-time item data including float values, pattern indexes, sticker information, and more. Supports both single item inspection and bulk processing with background queuing.
## Features
- ✅ **Single item inspection** - Inspect individual CS2 items
- ✅ **Bulk item inspection** - Process up to 50 items in a single request
- ✅ **Background processing** - Queue management with priority support
- ✅ **Worker architecture** - Multi-threaded processing capabilities
- ✅ **Statistics tracking** - Comprehensive monitoring and metrics
- ✅ **Error handling** - Robust error handling with timeouts and retries
- ✅ **TypeScript support** - Full TypeScript definitions included
## Installation
```bash
npm install cs2inspects
# or
pnpm add cs2inspects
# or
yarn add cs2inspects
```
## Quick Start
### Single Item Inspection
```typescript
import { inspect } from "cs2inspects";
// Using Steam inspect URL
const result = await inspect(
"steam://rungame/730/76561202255233023/+csgo_econ_action_preview%20S76561198023809011A40368145941D14586214085613790969"
);
// Using individual parameters
import { inspectFromParameters } from "cs2inspects";
const result = await inspectFromParameters({
s: "76561198023809011", // Steam ID
a: "40368145941", // Asset ID
d: "14586214085613790969", // Definition ID
m: "0", // Market ID (optional)
});
console.log(result);
```
### Bulk Item Inspection
```typescript
import { bulkInspect } from 'cs2inspects';
// Background processing (default)
const backgroundResult = await bulkInspect({
items: [
{
s: "76561198023809011",
a: "40368145941",
d: "14586214085613790969",
m: "0"
},
{
url: "steam://rungame/730/76561202255233023/+csgo_econ_action_preview%20S76561198023809011A40368145942D14586214085613790970"
}
],
waitForAll: false, // Process in background
lowPriority: false
});
// Wait for all results
const completeResult = await bulkInspect({
items: [...],
waitForAll: true // Wait for all inspections to complete
});
```
## API Reference
### Single Inspection Functions
#### `inspect(inspectUrl: string): Promise<InspectResult>`
Inspects a single CS2 item using a Steam inspect URL.
**Parameters:**
- `inspectUrl` (string): Steam inspect URL
**Returns:** `Promise<InspectResult>` - Item data or error information
#### `inspectFromParameters(params: InspectParameters): Promise<InspectResult>`
Inspects a single CS2 item using individual parameters.
**Parameters:**
- `params` (InspectParameters): Object with `s`, `a`, `d`, `m`, or `url` properties
### Bulk Inspection Functions
#### `bulkInspect(request: BulkInspectRequest): Promise<BulkInspectResponse>`
Processes multiple CS2 items in a single request.
**Parameters:**
- `request` (BulkInspectRequest): Bulk inspection configuration
**BulkInspectRequest Interface:**
```typescript
interface BulkInspectRequest {
items: BulkInspectItem[]; // Array of items to inspect (max 50)
waitForAll?: boolean; // Wait for all results (default: false)
lowPriority?: boolean; // Use low priority processing (default: false)
password?: string; // Authentication password (optional)
}
```
**BulkInspectItem Interface:**
```typescript
interface BulkInspectItem {
s?: string; // Steam ID
a?: string; // Asset ID
d?: string; // Definition ID
m?: string; // Market ID
url?: string; // Full Steam inspect URL (alternative to s,a,d,m)
refresh?: boolean; // Force refresh cached data
}
```
### Utility Functions
#### `validateInspectUrl(url: string): { valid: boolean; error?: string }`
Validates a Steam inspect URL format.
#### `parseInspectUrl(url: string): InspectParameters | null`
Parses a Steam inspect URL into individual parameters.
#### `createInspectUrl(s: string, a: string, d: string, m?: string): string`
Creates a Steam inspect URL from individual parameters.
### Statistics and Monitoring
#### `getSimpleStats(): SimpleStats`
Returns basic service statistics.
#### `getServiceStats(): ServiceStats`
Returns detailed service statistics including queue and worker information.
#### `getQueueStats(): QueueStats`
Returns queue-specific statistics.
### Worker Management
#### `workerManager.init(): Promise<void>`
Initializes the worker system (if enabled).
#### `workerManager.getActiveWorkerCount(): number`
Returns the number of active workers.
#### `workerManager.shutdown(): Promise<void>`
Shuts down all workers gracefully.
## Response Formats
### Successful Inspection Response
```json
{
"iteminfo": {
"defindex": 7,
"paintindex": 282,
"rarity": 5,
"quality": 4,
"origin": 8,
"floatvalue": 0.15234567,
"paintseed": 661,
"wear_name": "Field-Tested",
"market_hash_name": "AK-47 | Redline (Field-Tested)",
"stickers": [
{
"slot": 0,
"wear": 0.11459143459796906,
"sticker_id": 202,
"market_hash_name": "Sticker | Cloud9 (Holo) | DreamHack 2014"
}
],
"keychains": [],
"image": "https://community.cloudflare.steamstatic.com/economy/image/...",
"type": "Weapon",
"souvenir": false,
"stattrak": false
}
}
```
### Error Response
```json
{
"error": "Invalid Steam ID",
"status": 400
}
```
### Bulk Response (Background Processing)
```json
{
"success": true,
"total": 2,
"processed": 2,
"errorCount": 0,
"waitForAll": false,
"results": [
{
"index": 0,
"success": true,
"message": "Inspection request received and being processed in background"
}
]
}
```
### Bulk Response (Complete Results)
```json
{
"success": true,
"total": 1,
"processed": 1,
"errorCount": 0,
"waitForAll": true,
"results": [
{
"index": 0,
"success": true,
"data": {
"iteminfo": {
/* item data */
}
}
}
]
}
```
## Configuration
### Environment Variables
- `WORKER_ENABLED` - Enable multi-threaded workers (default: false)
- `MAX_WORKERS` - Maximum number of worker threads (default: 4)
- `QUEUE_TIMEOUT` - Queue timeout in milliseconds (default: 10000)
- `MAX_QUEUE_SIZE` - Maximum queue size (default: 100)
### Example Configuration
```bash
# Enable workers with 8 threads
WORKER_ENABLED=true
MAX_WORKERS=8
# Increase queue limits
QUEUE_TIMEOUT=30000
MAX_QUEUE_SIZE=200
```
## Examples
### Basic Usage
```typescript
import { inspect, bulkInspect } from "cs2inspects";
// Single inspection
const singleResult = await inspect("steam://rungame/730/...");
// Bulk inspection
const bulkResult = await bulkInspect({
items: [{ s: "123", a: "456", d: "789" }, { url: "steam://rungame/730/..." }],
waitForAll: true,
});
```
### Performance Testing
```typescript
import { bulkInspect, getSimpleStats } from "cs2inspects";
// Process 50 items
const items = Array.from({ length: 50 }, (_, i) => ({
s: "76561198023809011",
a: (40368145941 + i).toString(),
d: "14586214085613790969",
}));
const startTime = Date.now();
const result = await bulkInspect({ items, waitForAll: true });
const duration = Date.now() - startTime;
console.log(`Processed ${result.total} items in ${duration}ms`);
console.log("Stats:", getSimpleStats());
```
### Error Handling
```typescript
import { inspect, InspectError } from "cs2inspects";
try {
const result = await inspect("invalid-url");
if ("error" in result) {
const error = result as InspectError;
console.error(
`Inspection failed: ${error.error} (Status: ${error.status})`
);
} else {
console.log("Success:", result.iteminfo);
}
} catch (error) {
console.error("Unexpected error:", error);
}
```
## Scripts
Run the provided scripts to test functionality:
```bash
# Build the project
pnpm build
# Run examples
pnpm example
# Test single inspection
pnpm test:single
# Test bulk inspection
pnpm test:bulk
```
## Error Codes
| Status | Description |
| ------ | -------------------------------- |
| 200 | Success |
| 400 | Bad Request - Invalid parameters |
| 503 | Service Unavailable |
| 504 | Gateway Timeout |
| 500 | Internal Server Error |
## Performance Considerations
- **Bulk Processing**: Use `waitForAll: false` for better throughput when you don't need immediate results
- **Priority Queuing**: Use `lowPriority: true` for non-urgent requests
- **Worker Threads**: Enable workers for CPU-intensive operations
- **Queue Management**: Monitor queue size to prevent memory issues
## TypeScript Support
This package includes full TypeScript definitions. All interfaces and types are exported:
```typescript
import {
InspectResponse,
InspectError,
BulkInspectRequest,
BulkInspectResponse,
ServiceStats,
} from "cs2inspects";
```
## License
MIT
## Contributing
Contributions are welcome! Please feel free to submit issues and pull requests.