npm package: @mixxtor/translader
Description: Modern TypeScript translation service with type inference and multiple providers. Framework agnostic with clean architecture.
Author: Mixxtor
Latest version: 1.0.3

<div align="center">

# TransladerJS

> A powerful, type-safe translation library for JavaScript and TypeScript

[![npm version](https://badge.fury.io/js/@mixxtor%2Ftranslader.svg)](https://www.npmjs.com/package/@mixxtor/translader)
![Node.js](https://img.shields.io/badge/Node.js-%3E%3D20.6.0-green)
![TypeScript](https://img.shields.io/badge/TypeScript-5.x-blue)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

</div>

<p align="center">
  <a href="#features">Features</a> •
  <a href="#installation">Installation</a> •
  <a href="#quick-start">Quick Start</a> •
  <a href="#documentation">Documentation</a> •
  <a href="#api-reference">API</a>
</p>

---

## Features

✨ **Multiple Translation Providers** - Support for Google Translate (Free & Paid), with easy extensibility for DeepL, OpenAI, and more

🔒 **Type-Safe** - Full TypeScript support with intelligent type inference

🎯 **Provider Switching** - Dynamically switch between translation providers at runtime

📦 **Zero Config** - Works out of the box with sensible defaults

🚀 **Modern** - Built with ESM, works in Node.js 18+

🧪 **Well Tested** - Comprehensive test coverage

🔌 **Framework Agnostic** - Use with any JavaScript framework or vanilla JS

## Installation

```bash
npm install @mixxtor/translader
```

```bash
yarn add @mixxtor/translader
```

```bash
pnpm add @mixxtor/translader
```

## Quick Start

### Basic Usage

```typescript
import { createTranslator, providers } from '@mixxtor/translader'

const translator = createTranslator({
  default: 'google-free',
  providers: {
    'google-free': providers.googleFree(),
  },
})

// Translate text
const result = await translator.translateText('Hello, world!', 'en', 'es')
console.log(result.translation) // ¡Hola Mundo!
```

### Using Google Cloud Translation API

```typescript
import { createTranslator, providers } from '@mixxtor/translader'

const translator = createTranslator({
  default: 'google-paid',
  providers: {
    'google-paid': providers.googlePaid({
      apiKey: process.env.GOOGLE_TRANSLATE_API_KEY,
    }),
  },
})

const result = await translator.translateText('Hello', 'en', 'ja')
console.log(result.translation) // こんにちは
```

**Need help getting an API key?** See our [Google Cloud Setup Guide](./GOOGLE-CLOUD-SETUP.md) for detailed instructions.

### Multiple Providers with Switching

```typescript
const translator = createTranslator({
  default: 'google-free',
  providers: {
    'google-free': providers.googleFree(),
    'google-cloud': providers.googlePaid({ apiKey: 'YOUR_API_KEY' }),
  },
})

// Use free provider
let result = await translator.translateText('Hello', 'en', 'es')

// Switch to paid provider
translator.use('google-cloud')
result = await translator.translateText('Hello', 'en', 'fr')
```

## Core Concepts

### Providers

Providers are the backbone of Translader. Each provider implements translation functionality for a specific service:

- **Google Translate Free** - No API key required, good for development
- **Google Cloud Translation** - Official Google Cloud API, requires API key

### Configuration

Use the `defineConfig` helper for type-safe configuration:

```typescript
import { defineConfig, providers } from '@mixxtor/translader'

const config = defineConfig({
  default: 'google-free',
  providers: {
    'google-free': providers.googleFree({
      timeout: 5000,
    }),
  },
})

const translator = createTranslator(config)
```

### Type Safety

Translader provides full type inference based on your configuration:

```typescript
const translator = createTranslator({
  default: 'primary',
  providers: {
    'primary': providers.googleFree(),
    'backup': providers.googlePaid({ apiKey: 'key' }),
  },
})

// TypeScript knows about 'primary' and 'backup'
translator.use('primary') // ✅ Valid
translator.use('backup')  // ✅ Valid
translator.use('invalid') // ❌ TypeScript error
```

## API Reference

### `createTranslator(config)`

Creates a new translator instance.

```typescript
const translator = createTranslator({
  default: 'provider-name',
  providers: {
    'provider-name': providers.googleFree(),
  },
})
```

### Translation Methods

#### `translateText(text, from, to)`

Simple text translation.

```typescript
const result = await translator.translateText('Hello', 'en', 'es')
// Returns: TranslationResult
```

#### `translate(params)`

Full translation with all options.

```typescript
const result = await translator.translate({
  text: 'Hello, world!',
  from: 'en',
  to: 'es',
})
// Returns: TranslationResult
```

#### `translateBatch(params)`

Translate multiple texts at once.

```typescript
const result = await translator.translateBatch({
  texts: ['Hello', 'Goodbye'],
  from: 'en',
  to: 'es',
})
// Returns: BatchTranslationResult
```

#### `detect(text)`

Detect the language of text.

```typescript
const result = await translator.detect('Bonjour')
// Returns: DetectionResult with language 'fr'
```

### Provider Management

#### `use(providerName)`

Switch to a different provider.

```typescript
translator.use('google-cloud')
```

#### `getCurrentProvider()`

Get the name of the current provider.

```typescript
const current = translator.getCurrentProvider()
// Returns: string
```

#### `getAvailableProviders()`

Get a list of all configured providers.

```typescript
const providers = translator.getAvailableProviders()
// Returns: string[]
```

#### `getSupportedLanguages()`

Get supported languages for the current provider.

```typescript
const result = await translator.getSupportedLanguages()
// Returns: SupportedLanguagesResult
```

#### `getSupportedLanguagesFor(providerName)`

Get supported languages for a specific provider.

```typescript
const result = await translator.getSupportedLanguagesFor('google-free')
// Returns: SupportedLanguagesResult
```

## Provider Configuration

### Google Translate Free

```typescript
providers.googleFree({
  timeout: 5000,        // Request timeout in ms (optional)
  retries: 3,           // Number of retries (optional)
})
```

### Google Cloud Translation

```typescript
providers.googlePaid({
  apiKey: 'YOUR_API_KEY',  // Required
  timeout: 10000,           // Request timeout in ms (optional)
  retries: 3,               // Number of retries (optional)
})
```

## Language Codes

Translader uses ISO 639-1 language codes:

```typescript
type LanguageCode = 
  | 'en' // English
  | 'es' // Spanish
  | 'fr' // French
  | 'de' // German
  | 'it' // Italian
  | 'ja' // Japanese
  | 'ko' // Korean
  | 'zh' // Chinese
  // ... and many more
```

## Response Types

### TranslationResult

```typescript
interface TranslationResult {
  success: boolean
  translation?: string
  query: {
    text: string
    from: LanguageCode
    to: LanguageCode
  }
  provider?: string  // Name of the provider that performed the translation
  info?: {
    detectedSourceLanguage?: LanguageCode
    metadata?: Record<string, unknown>
  }
  error?: {
    code?: number
    info: string
    type?: string
  }
}
```

### BatchTranslationResult

```typescript
interface BatchTranslationResult {
  success: boolean
  translations?: string[]
  query: {
    from: LanguageCode
    to: LanguageCode
    count: number
  }
  provider?: string  // Name of the provider that performed the translation
  info?: {
    detectedSourceLanguage?: LanguageCode
    metadata?: Record<string, unknown>
  }
  error?: {
    code?: number
    info: string
    type?: string
  }
}
```

### DetectionResult

```typescript
interface DetectionResult {
  success: boolean
  language?: LanguageCode
  confidence?: number
  provider?: string  // Name of the provider that performed the detection
  alternatives?: Array<{
    language: LanguageCode
    confidence: number
  }>
  error?: {
    code?: number
    info: string
    type?: string
  }
}
```

## Error Handling

All methods return results with a `success` flag:

```typescript
const result = await translator.translateText('Hello', 'en', 'es')

if (result.success) {
  console.log(result.translation)
} else {
  console.error(result.error)
}
```

## Advanced Usage

### Environment-Based Configuration

```typescript
const translator = createTranslator({
  default: process.env.NODE_ENV === 'production' ? 'google-cloud' : 'google-free',
  providers: {
    'google-free': providers.googleFree(),
    'google-cloud': providers.googlePaid({
      apiKey: process.env.GOOGLE_TRANSLATE_API_KEY!,
    }),
  },
})
```

### Fallback Strategy

```typescript
async function translateWithFallback(text: string, from: string, to: string) {
  translator.use('primary')
  let result = await translator.translateText(text, from, to)

  if (!result.success) {
    translator.use('backup')
    result = await translator.translateText(text, from, to)
  }

  return result
}
```

## Framework Integration

### Express

```typescript
import express from 'express'
import { createTranslator, providers } from '@mixxtor/translader'

const app = express()
const translator = createTranslator({
  default: 'google-free',
  providers: {
    'google-free': providers.googleFree(),
  },
})

app.get('/translate', async (req, res) => {
  const { text, from, to } = req.query
  const result = await translator.translateText(text, from, to)
  res.json(result)
})
```

### Next.js API Routes

```typescript
import { createTranslator, providers } from '@mixxtor/translader'

const translator = createTranslator({
  default: 'google-free',
  providers: {
    'google-free': providers.googleFree(),
  },
})

export default async function handler(req, res) {
  const { text, from, to } = req.query
  const result = await translator.translateText(text, from, to)
  res.json(result)
}
```

## Examples

See the [examples](./examples) directory for more usage examples:

- [basic-usage.ts](./examples/basic-usage.ts) - Basic translation examples
- [multiple-providers.ts](./examples/multiple-providers.ts) - Provider switching and management

## Documentation

- [Quick Start Guide](./QUICKSTART.md) - Get started quickly
- [Complete Overview](./OVERVIEW.md) - Comprehensive guide
- [Google Cloud Setup](./GOOGLE-CLOUD-SETUP.md) - How to set up Google Cloud Translation API
- [Contributing](./CONTRIBUTING.md) - How to contribute

## License

MIT License - see [LICENSE](./LICENSE) for details

## Contributing

Contributions are welcome! Please see [CONTRIBUTING.md](./CONTRIBUTING.md) for guidelines.

## Support

- 📖 [Documentation](./OVERVIEW.md)
- 🐛 [Issue Tracker](https://github.com/mixxtor/translader/issues)
- 💬 [Discussions](https://github.com/mixxtor/translader/discussions)

---

<p align="center">
  Made with ❤️ by the Mixxtor team
</p>