npm package: @synaptia/toolbelt
Description: Official JavaScript/TypeScript SDK for ToolBelt API - A utility API for AI agents
Author: Synaptia Lab
Latest version: 1.0.1

# ToolBelt JavaScript/TypeScript SDK

[![npm version](https://badge.fury.io/js/synaptialab%2Ftoolbelt.svg)](https://www.npmjs.com/package/toolbelt)
[![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue.svg)](https://www.typescriptlang.org/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

Official JavaScript/TypeScript SDK for [ToolBelt API](https://github.com/synaptialab/toolbelt-api) - A utility API for AI agents.

## Installation

```bash
npm install toolbelt
```

or

```bash
yarn add toolbelt
```

or

```bash
pnpm add toolbelt
```

## Quick Start

### Modular API (Recommended)

The SDK now features a modular API for better organization and discoverability:

```typescript
import { ToolBelt } from "toolbelt";

const client = new ToolBelt({ apiKey: "your-api-key" });

// Security module
const password = await client.security.passwordGenerate({ 
  length: 16,
  include_symbols: true 
});
console.log(password.password);

const decoded = await client.security.jwtDecode("eyJhbGciOiJIUzI1NiIs...");
console.log(decoded.payload);

// Utils module
const encoded = await client.utils.base64Encode("Hello World");
console.log(encoded.encoded); // "SGVsbG8gV29ybGQ="

const decoded = await client.utils.base64Decode("SGVsbG8gV29ybGQ=");
console.log(decoded.decoded); // "Hello World"

// Image module
const qr = await client.image.qrGenerate("https://example.com");
console.log(qr.qr_code); // Base64 encoded QR code

const text = await client.image.ocr(imageBase64);
console.log(text.text); // Extracted text from image

// Accessibility module
const altText = await client.a11y.altText({ image: "https://example.com/image.jpg" });
console.log(altText.alt_text); // "A beautiful sunset over mountains"
console.log(altText.confidence); // 0.95

const contrast = await client.a11y.contrast({
  foreground: "#000000",
  background: "#ffffff",
  level: "AA"
});
console.log(contrast.result.ratio); // 21
console.log(contrast.result.passes_aa); // true

const a11yAudit = await client.a11y.audit({
  html: "<!DOCTYPE html>...",
  url: "https://example.com"
});
console.log(a11yAudit.score); // 85
console.log(a11yAudit.passes_wcag_aa); // true
console.log(a11yAudit.sections); // Detailed audit results

// System monitoring module
const health = await client.system.health();
console.log(health.status); // "healthy" | "warning" | "critical"
console.log(health.checks.cpu.usage);
console.log(health.uptime_seconds);

const resources = await client.system.resources();
console.log(resources.cpu.usage_percent);
console.log(resources.memory.percent);
console.log(resources.disk.usage_percent);

// Compression module
const compressed = await client.compress.gzip({
  data: "Hello World! This is some text to compress.",
  level: 6
});
console.log(compressed.compression_ratio); // e.g., 0.45
console.log(compressed.original_size, compressed.compressed_size);

const comparison = await client.compress.compare();
console.log(comparison.best_compression);
console.log(comparison.fastest);
console.log(comparison.recommendations);

// Communication module
const email = await client.comm.emailFormat({
  to: ["user@example.com"],
  subject: "Welcome",
  body: "Hello there!"
});
console.log(email.valid);
console.log(email.mailto_link);
console.log(email.estimated_size_bytes);

const sms = await client.comm.smsFormat({
  phone: "+1234567890",
  message: "Hello World!"
});
console.log(sms.segments);
console.log(sms.estimated_cost_usd);

const template = await client.comm.templateRender({
  template: "Hello {{name}}!",
  variables: { name: "John" }
});
console.log(template.rendered); // "Hello John!"

// Export module
const wordDoc = await client.export.word({
  title: "Sales Report",
  data: [{ name: "John", sales: 100 }, { name: "Jane", sales: 200 }],
  table_headers: ["Name", "Sales"]
});
console.log(wordDoc.file_base64); // Base64-encoded .docx file
console.log(wordDoc.row_count);

const excel = await client.export.excel({
  title: "Sales Report",
  data: [{ name: "John", sales: 100 }, { name: "Jane", sales: 200 }]
});
console.log(excel.sheet_name);

const pdf = await client.export.pdf({
  title: "Invoice #123",
  html_content: "<html><body><h1>Invoice</h1>...</body></html>"
});
console.log(pdf.size_bytes);

const hash = await client.export.hashText({
  text: "Hello World",
  algorithms: ["sha256", "md5"]
});
console.log(hash.hashes);

const coords = await client.export.geocode({
  address: "1600 Pennsylvania Avenue, Washington, DC"
});
console.log(coords.latitude, coords.longitude);

// Advanced Text module
const sentiment = await client.text.sentiment({
  text: "I love this amazing product!"
});
console.log(sentiment.label); // "positive"
console.log(sentiment.polarity);

const complexity = await client.text.complexity({
  text: "This is a sample text to analyze..."
});
console.log(complexity.reading_level);
console.log(complexity.reading_time_minutes);

const translated = await client.text.translate({
  text: "Hello World",
  source_lang: "auto",
  target_lang: "es"
});
console.log(translated.translated_text); // "Hola Mundo"

// Code module
const highlighted = await client.code.syntaxHighlight({
  code: "function hello() { return 'World'; }",
  language: "javascript",
  theme: "github-dark",
  line_numbers: true
});
console.log(highlighted.html);

const formattedSQL = await client.code.sqlFormat({
  sql: "SELECT name FROM users WHERE age>18",
  keyword_case: "upper"
});
console.log(formattedSQL.formatted);

const minifiedJS = await client.code.jsMinify({
  js_code: "function hello() { return 'World'; }",
  remove_comments: true
});
console.log(minifiedJS.minified);

// Utilities module
const time = await client.util.timeNow();
console.log(time.iso8601);
console.log(time.unix_timestamp);
console.log(time.timezone);

const screenshot = await client.util.webScreenshot({
  url: "https://example.com",
  width: 1920,
  height: 1080
});
console.log(screenshot.image_base64);

const pdfText = await client.util.extractPDF({
  file_base64: "JVBERi0xLjQK...",
  extract_images: true
});
console.log(pdfText.text);
console.log(pdfText.page_count);

const batchResult = await client.util.batch({
  operations: [
    { endpoint: "/api/v1/fake/name" },
    { endpoint: "/api/v1/fake/email" }
  ],
  stop_on_error: false
});
console.log(batchResult.results);

const apiInfo = await client.util.info();
console.log(apiInfo.version);
console.log(apiInfo.endpoints_count);
```

### Legacy API (Still Supported)

```javascript
const { ToolBelt } = require("toolbelt");

// Initialize the client with your API key
const client = new ToolBelt({ apiKey: "your-api-key" });

// Extract content from a URL
async function main() {
  try {
    const result = await client.extractUrl("https://example.com");
    console.log(`Title: ${result.title}`);
    console.log(`Content: ${result.text}`);
  } catch (error) {
    console.error("Error:", error.message);
  }
}

main();
```

### TypeScript

```typescript
import { ToolBelt } from "toolbelt";

// Initialize the client
const client = new ToolBelt({
  apiKey: "your-api-key",
});

// Extract content from a URL
const result = await client.extractUrl("https://example.com");
console.log(`Title: ${result.title}`);

// Use with async/await
async function run() {
  const health = await client.health();
  console.log(`Status: ${health.status}`);

  const registration = await client.register("your-email@example.com");
  console.log(`API Key: ${registration.api_key}`);
}

run();
```

## Getting an API Key

Register to get your free API key (1,000 requests/day):

```typescript
import { ToolBelt } from "toolbelt";

// Create a client without an API key to register
const client = new ToolBelt();

// Register a new user
const registration = await client.register("your-email@example.com");
const apiKey = registration.api_key;

console.log(`Your API key: ${apiKey}`);
console.log(`Tier: ${registration.tier}`);
console.log(`Daily limit: ${registration.daily_limit}`);
```

## API Methods

### System Endpoints

#### Health Check
```typescript
import { ToolBelt } from "toolbelt";

const client = new ToolBelt({ apiKey: "your-api-key" });
const health = await client.health();

console.log(`Status: ${health.status}`);
console.log(`Version: ${health.version}`);
```

#### Register
```typescript
import { ToolBelt } from "toolbelt";

const client = new ToolBelt();
const registration = await client.register("test@example.com");

console.log(`API Key: ${registration.api_key}`);
console.log(`Tier: ${registration.tier}`);
console.log(`Daily limit: ${registration.daily_limit}`);
```

### Extraction Endpoints

#### Extract URL Content
```typescript
import { ToolBelt } from "toolbelt";

const client = new ToolBelt({ apiKey: "your-api-key" });
const result = await client.extractUrl("https://example.com");

console.log(`Title: ${result.title}`);
console.log(`Content: ${result.text}`);
console.log(`Word count: ${result.word_count}`);
```

### Text Processing Endpoints

#### Summarize Text
```typescript
import { ToolBelt } from "toolbelt";

const client = new ToolBelt({ apiKey: "your-api-key" });
const result = await client.summarizeText(
  "ToolBelt API provides utility endpoints for AI agents to perform common tasks efficiently.",
  100 // Optional: maximum summary length
);

console.log(`Summary: ${result.summary}`);
console.log(`Key points: ${result.key_points?.join(", ")}`);
```

#### Extract Keywords
```typescript
import { ToolBelt } from "toolbelt";

const client = new ToolBelt({ apiKey: "your-api-key" });
const result = await client.extractKeywords(
  "Machine learning is transforming AI and data science.",
  5 // Optional: number of keywords to extract
);

result.keywords.forEach((kw) => {
  console.log(`${kw.keyword}: ${kw.score}`);
});
```

#### Analyze Sentiment
```typescript
import { ToolBelt } from "toolbelt";

const client = new ToolBelt({ apiKey: "your-api-key" });
const result = await client.analyzeSentiment("I love this amazing product!");

console.log(`Sentiment: ${result.sentiment}`);
console.log(`Score: ${result.score}`);
console.log(`Confidence: ${result.confidence}`);
console.log(`Label: ${result.label}`);
```

### Format Conversion Endpoints

#### Convert HTML to Markdown
```typescript
import { ToolBelt } from "toolbelt";

const client = new ToolBelt({ apiKey: "your-api-key" });
const html = "<h1>Title</h1><p>This is a <b>paragraph</b>.</p>";
const result = await client.convertHtmlToMarkdown(html);

console.log(result.markdown);
// Output:
// # Title
// This is a **paragraph**.
```

### Validation Endpoints

#### Validate Email
```typescript
import { ToolBelt } from "toolbelt";

const client = new ToolBelt({ apiKey: "your-api-key" });
const result = await client.validateEmail("test@example.com");

console.log(`Valid: ${result.valid}`);
console.log(`Disposable: ${result.disposable}`);
console.log(`MX found: ${result.mx_found}`);
console.log(`Domain: ${result.domain}`);
```

### Utilities Endpoints

#### Compare Texts (Diff)
```typescript
import { ToolBelt } from "toolbelt";

const client = new ToolBelt({ apiKey: "your-api-key" });
const result = await client.diffText(
  "The quick brown fox jumps over the lazy dog.",
  "The quick brown dog jumps over the lazy fox."
);

console.log(`Diff: ${result.diff}`);
console.log(`Similarity: ${result.similarity}`);
```

## Configuration

```typescript
import { ToolBelt } from "toolbelt";

// Custom configuration
const client = new ToolBelt({
  apiKey: "your-api-key",
  baseUrl: "https://toolbelt-api-webservice.onrender.com", // Production (default)
  // baseUrl: "http://localhost:8000", // Local development
  timeout: 30000, // Request timeout in milliseconds (default: 30000)
  maxRetries: 3, // Max retries for rate-limited requests (default: 3)
  retryDelay: 1000, // Base retry delay in milliseconds (default: 1000)
});
```

## Error Handling

The SDK provides custom exceptions for different error types:

```typescript
import { ToolBelt } from "toolbelt";
import {
  AuthenticationError,
  RateLimitError,
  InvalidRequestError,
  ServerError,
  NetworkError,
  ToolBeltError,
} from "toolbelt";

const client = new ToolBelt({ apiKey: "your-api-key" });

try {
  const result = await client.extractUrl("https://example.com");
} catch (error) {
  if (error instanceof AuthenticationError) {
    console.error("Authentication failed:", error.message);
  } else if (error instanceof RateLimitError) {
    console.error("Rate limit exceeded:", error.message);
    if (error.retryAfter) {
      console.error(`Retry after ${error.retryAfter} seconds`);
    }
  } else if (error instanceof InvalidRequestError) {
    console.error("Invalid request:", error.message);
    if (error.field) {
      console.error("Field:", error.field);
    }
  } else if (error instanceof ServerError) {
    console.error("Server error:", error.message);
  } else if (error instanceof NetworkError) {
    console.error("Network error:", error.message);
  } else if (error instanceof ToolBeltError) {
    console.error("ToolBelt error:", error.message);
  }
}
```

## TypeScript Support

The SDK is TypeScript-first and provides full type definitions:

```typescript
import { ToolBelt, URLExtractionResponse } from "toolbelt";

const client = new ToolBelt({ apiKey: "your-api-key" });
const result: URLExtractionResponse = await client.extractUrl("https://example.com");

// Full type safety for result properties
console.log(result.url);
console.log(result.title);
console.log(result.text);
console.log(result.word_count);
```

Type definitions are automatically included when you install the package.

## Rate Limiting

The SDK automatically handles rate limiting with exponential backoff:

```typescript
import { ToolBelt } from "toolbelt";

// Configure retry behavior
const client = new ToolBelt({
  apiKey: "your-api-key",
  maxRetries: 3, // Retry up to 3 times on rate limit
  retryDelay: 1000, // Base delay (exponential: 1s, 2s, 4s)
});

// If rate limited, SDK will automatically retry
const result = await client.extractUrl("https://example.com");
```

## Development Mode

For local development with the ToolBelt API running locally:

```typescript
import { ToolBelt } from "toolbelt";

// Use local API
const client = new ToolBelt({
  apiKey: "your-api-key",
  baseUrl: "http://localhost:8000",
});
```

## Pricing

| Endpoint | Cost |
|----------|------|
| extract/url | $0.002/request |
| text/summarize | $0.002/request |
| text/extract-keywords | $0.001/request |
| text/sentiment | $0.001/request |
| convert/html-to-markdown | $0.001/request |
| validate/email | $0.001/request |
| utils/diff | $0.001/request |

**Tiers:**
- **Free**: 1,000 requests/day
- **Starter**: $9/month (10,000 requests/day)
- **Pro**: $29/month (50,000 requests/day)
- **Business**: $99/month (200,000 requests/day)

## Requirements

- Node.js >= 14.0.0
- TypeScript >= 5.0.0 (if using TypeScript)
- Fetch API (built-in in Node.js 18+)

## Building from Source

```bash
# Clone the repository
git clone https://github.com/synaptialab/toolbelt-js.git
cd toolbelt-js

# Install dependencies
npm install

# Build the project
npm run build

# Run tests
npm test

# Watch mode for development
npm run watch
```

## License

MIT License - see [LICENSE](LICENSE) file.

## Support

- GitHub Issues: https://github.com/synaptialab/toolbelt-js/issues
- Documentation: https://github.com/synaptialab/toolbelt-api
- Email: contact@synaptia.dev

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.



## Version 1.0.0 Release Notes (2026-03-30)

**Major Milestone:** 118 REST API endpoints across 15 modules

### What's New
- **Complete Modular Architecture**: 15 fully typed modules (Security, Utils, Image, Extract, Fake, SEO, Scrape, Accessibility, System, Compression, Communication, Export, Text, Code, Utilities)
- **TypeScript Strict Mode**: Full type safety with comprehensive type definitions
- **Comprehensive Documentation**: JSDoc examples for all endpoints
- **Enhanced README**: Usage examples for all modules, installation instructions, and pricing table
- **Test Suite**: Jest + ts-jest configuration (work in progress)

### Breaking Changes
- **Modular API**: Reorganized from monolithic to 15 separate modules
- **Legacy API**: 9 endpoints retained for backward compatibility (marked as deprecated)

### Known Issues
- Test suite has TypeScript configuration issues (tests created but not yet passing)


## Changelog

### 0.1.0 (2026-03-15)
- Initial release
- All 8 endpoints supported
- Full TypeScript support
- Automatic retry with exponential backoff
- Comprehensive error handling
- Production-ready documentation
- Compatible with Node.js 14+