npm package: @mixxtor/adonisjs-translader
Description: AdonisJS integration for TransladerJS - Multi-provider translation service
Author: Mixxtor
Latest version: 1.0.2

<div align="center">

# Translader AdonisJS

> AdonisJS integration for Translader.js - Multi-provider translation service with Google Translate, DeepL, and more.

[![npm version](https://badge.fury.io/js/@mixxtor%2Fadonisjs-translader.svg)](https://badge.fury.io/js/@mixxtor%2Fadonisjs-translader)
[![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue.svg)](https://www.typescriptlang.org/)
[![AdonisJS](https://img.shields.io/badge/AdonisJS-v6-purple.svg)](https://adonisjs.com/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

</div>

## ✨ Features

- 🚀 **AdonisJS Integration** - Seamless integration with AdonisJS v6 framework
- 🌐 **Multi-Provider** - Google Translate (Free & Paid), with future support for DeepL, OpenAI, and more
- 💉 **Dependency Injection** - Registered as AdonisJS service for easy injection
- 🎯 **Type Safety** - Full TypeScript support with intelligent type inference
- 🔄 **Provider Switching** - Switch between providers at runtime with auto-complete
- 📦 **Easy Setup** - Simple configuration and installation via `node ace configure`
- 🔧 **Extensible** - Easy to add custom translation providers
- 💡 **IntelliSense** - Auto-completion for configured providers using type augmentation

## 📦 Installation

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

## 🚀 Setup

### 1. Configure the package

```bash
node ace configure @mixxtor/adonisjs-translader
```

This will:
- Create `config/translation.ts` configuration file
- Register the service provider in `adonisrc.ts`

### 2. Configure environment variables

Add to your `.env` file:

```env
# Default translation provider
TRANSLATION_PROVIDER=google-free

# Google Cloud Translation API (for paid provider)
GOOGLE_TRANSLATE_API_KEY=your_api_key_here

# OR use service account credentials
# GOOGLE_CLOUD_PROJECT_ID=your_project_id
# GOOGLE_CLOUD_PRIVATE_KEY=your_private_key
# GOOGLE_CLOUD_CLIENT_EMAIL=your_service_account_email
```

### 3. Configure providers

Edit `config/translation.ts`:

```typescript
import env from '#start/env'
import { defineConfig } from '@mixxtor/adonisjs-translader'
import type { InferProviders } from '@mixxtor/adonisjs-translader'
import { GoogleTranslateFreeProvider, GoogleTranslatePaidProvider } from '@mixxtor/translader'

const translationConfig = defineConfig({
  /*
  |--------------------------------------------------------------------------
  | Default Provider
  |--------------------------------------------------------------------------
  */
  default: env.get('TRANSLATION_PROVIDER', 'google-free') as 'google-free' | 'google-paid',

  /*
  |--------------------------------------------------------------------------
  | Provider Configurations
  |--------------------------------------------------------------------------
  */
  providers: {
    /*
    | Google Translate Free - No API key required
    */
    'google-free': new GoogleTranslateFreeProvider(),

    /*
    | Google Cloud Translation API - Requires API key or credentials
    */
    'google-paid': new GoogleTranslatePaidProvider({
      apiKey: env.get('GOOGLE_TRANSLATE_API_KEY'),
      // OR use service account:
      // credentials: {
      //   projectId: env.get('GOOGLE_CLOUD_PROJECT_ID'),
      //   privateKey: env.get('GOOGLE_CLOUD_PRIVATE_KEY'),
      //   clientEmail: env.get('GOOGLE_CLOUD_CLIENT_EMAIL'),
      // }
    }),
  },
})

export default translationConfig

/*
|--------------------------------------------------------------------------
| Type Augmentation
|--------------------------------------------------------------------------
|
| Augment the module types to enable IntelliSense for configured providers.
| This allows auto-completion when using translation.use('provider-name')
|
*/
declare module '@mixxtor/adonisjs-translader/types' {
  interface TranslationProviders extends InferProviders<typeof translationConfig> {}
}
```

## 💡 Usage

### Basic Translation in Controllers

```typescript
// app/controllers/translation_controller.ts
import { inject } from '@adonisjs/core'
import type { HttpContext } from '@adonisjs/core/http'
import translation from '@mixxtor/adonisjs-translader/services/main'

@inject()
export default class TranslationController {
  constructor(private translation: typeof translation) {}

  async translate({ request, response }: HttpContext) {
    const { text, from, to } = request.only(['text', 'from', 'to'])

    const result = await this.translation.translate({
      text,
      from,
      to,
    })

    if (result.success) {
      return response.json({
        success: true,
        data: {
          original: text,
          translated: result.text,
          from: result.from,
          to: result.to,
          provider: result.provider,
        },
      })
    }

    return response.status(400).json({
      success: false,
      error: result.error,
    })
  }

  async batchTranslate({ request, response }: HttpContext) {
    const { texts, from, to } = request.only(['texts', 'from', 'to'])

    const result = await this.translation.translateBatch({
      texts,
      from,
      to,
    })

    if (result.success) {
      return response.json({
        success: true,
        data: result.translations,
      })
    }

    return response.status(400).json({
      success: false,
      error: result.error,
    })
  }

  async detectLanguage({ request, response }: HttpContext) {
    const { text } = request.only(['text'])

    const result = await this.translation.detectLanguage({ text })

    if (result.success) {
      return response.json({
        success: true,
        language: result.language,
        confidence: result.confidence,
      })
    }

    return response.status(400).json({
      success: false,
      error: result.error,
    })
  }

  async getSupportedLanguages({ response }: HttpContext) {
    const result = await this.translation.getSupportedLanguages()

    if (result.success) {
      return response.json({
        success: true,
        languages: result.languages,
      })
    }

    return response.status(400).json({
      success: false,
      error: result.error,
    })
  }
}
```

### Provider Switching

```typescript
// Switch to different provider at runtime
const googleFree = this.translation.use('google-free')
const freeResult = await googleFree.translate({
  text: 'Hello, world!',
  from: 'en',
  to: 'es',
})

const googlePaid = this.translation.use('google-paid')
const paidResult = await googlePaid.translate({
  text: 'Hello, world!',
  from: 'en',
  to: 'es',
})
```

### Using in Services

```typescript
// app/services/content_translation_service.ts
import { inject } from '@adonisjs/core'
import translation from '@mixxtor/adonisjs-translader/services/main'

@inject()
export default class ContentTranslationService {
  constructor(private translation: typeof translation) {}

  async translateContent(content: string, targetLanguage: string) {
    // Auto-detect source language
    const detection = await this.translation.detectLanguage({ text: content })
    
    if (!detection.success) {
      throw new Error('Failed to detect language')
    }

    // Translate to target language
    const result = await this.translation.translate({
      text: content,
      from: detection.language,
      to: targetLanguage,
    })

    if (!result.success) {
      throw new Error('Translation failed')
    }

    return {
      original: content,
      translated: result.text,
      sourceLanguage: detection.language,
      targetLanguage,
    }
  }
}
```

## 📚 API Reference

The AdonisJS integration provides the same API as the core Translader.js package:

### Core Methods

#### `translate(params: TranslateParams): Promise<TranslationResult>`
Translate text from one language to another.

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

#### `translateBatch(params: BatchTranslateParams): Promise<BatchTranslationResult>`
Translate multiple texts at once.

```typescript
const result = await translation.translateBatch({
  texts: ['Hello', 'Goodbye', 'Thank you'],
  from: 'en',
  to: 'es',
})
```

#### `detectLanguage(params: DetectLanguageParams): Promise<DetectionResult>`
Detect the language of a text.

```typescript
const result = await translation.detectLanguage({
  text: 'Bonjour le monde',
})
// result.language === 'fr'
```

#### `getSupportedLanguages(params?: GetSupportedLanguagesParams): Promise<SupportedLanguagesResult>`
Get list of supported languages.

```typescript
const result = await translation.getSupportedLanguages()
// result.languages: [{ code: 'en', name: 'English' }, ...]
```

### Provider Management

#### `use(provider: string): TranslationService`
Switch to a different provider.

```typescript
const googlePaid = translation.use('google-paid')
const result = await googlePaid.translate({ text: 'Hello', from: 'en', to: 'es' })
```

## ⚙️ Configuration

### Environment Variables

```env
# Default provider
TRANSLATION_PROVIDER=google-free

# Google Cloud Translation API
GOOGLE_TRANSLATE_API_KEY=your_api_key_here

# OR Service Account (recommended for production)
GOOGLE_CLOUD_PROJECT_ID=your_project_id
GOOGLE_CLOUD_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\n..."
GOOGLE_CLOUD_CLIENT_EMAIL=your-service-account@project.iam.gserviceaccount.com
```

### Provider Configuration

#### Google Translate Free
```typescript
'google-free': new GoogleTranslateFreeProvider()
```
- No API key required
- Rate limited
- Unofficial API (may break)

#### Google Translate Paid (Cloud Translation API)
```typescript
'google-paid': new GoogleTranslatePaidProvider({
  apiKey: 'your-api-key',
  // OR
  credentials: {
    projectId: 'your-project-id',
    privateKey: '-----BEGIN PRIVATE KEY-----...',
    clientEmail: 'service-account@project.iam.gserviceaccount.com',
  }
})
```
- Requires Google Cloud project
- Higher rate limits
- Official API with SLA
- Better quality translations

For detailed Google Cloud setup instructions, see: [GOOGLE-CLOUD-SETUP.md](https://github.com/mixxtor/translader-js/blob/main/packages/translader/docs/GOOGLE-CLOUD-SETUP.md)

## 🛡️ Error Handling

All methods return result objects with success indicators:

```typescript
const result = await translation.translate({
  text: 'Hello',
  from: 'en',
  to: 'es',
})

if (result.success) {
  // Handle success
  console.log(`Translated: ${result.text}`)
  console.log(`Provider: ${result.provider}`)
} else {
  // Handle error
  console.error(`Error: ${result.error}`)
}
```

## 🧪 Testing

The package includes comprehensive tests. Run them with:

```bash
npm test
```

For development testing:

```bash
npm run quick:test
```

## 📋 Requirements

- **Node.js** >= 18.0.0
- **AdonisJS** >= 6.19.0
- **@mixxtor/translader** >= 1.0.0-beta.0

## 🤝 Contributing

Contributions are welcome! Please read the contributing guidelines before submitting PRs.

## 📄 License

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

## 📦 Related Packages

- [@mixxtor/translader](https://www.npmjs.com/package/@mixxtor/translader) - Core translation library

---

<div align="center">

**[Documentation](https://github.com/mixxtor/translader-js#readme)** • **[Issues](https://github.com/mixxtor/translader-js/issues)**

Made with ❤️ by [Mixxtor](https://github.com/mixxtor)

</div>