npm package: @skywu/translator
Description: AI-powered translation library with automatic language detection, intelligent caching, and React components
Author: SkyWu
Latest version: 1.1.1

# @skywu/translator

AI-powered translation library with automatic language detection, intelligent caching, and React components.

⚠️ **SECURITY WARNING**: Never expose OpenAI API keys in the browser! Always use a server proxy for production applications.

## Features

- 🌐 **40+ Languages** - Support for major world languages
- 🤖 **Auto Detection** - Intelligent source language detection
- ⚡ **Persistent Caching** - LevelDB-powered caching for lightning-fast responses
- 💾 **Local Storage** - Cache persists across application restarts
- 📱 **React Components** - Ready-to-use UI components
- 🔧 **TypeScript** - Full type safety and IntelliSense support
- 🔒 **Server-First** - Designed for secure server-side usage

## Quick Start

### Installation

```bash
npm install @skywu/translator
```

### Server-Side Usage (Recommended)

```javascript
import { configure, t } from '@skywu/translator';

// Configure with your OpenAI API key (server-side only!)
configure({
  apiKey: process.env.OPENAI_API_KEY,
  defaultLanguage: 'zh'
});

// Simple translation
const result = await t('Hello World');
console.log(result); // "你好世界"

// With options
const result2 = await t('Hello', {
  to: 'fr',
  fallback: 'Bonjour'
});
```

### React Integration (With Server Proxy)

For browser usage, create a server proxy to protect your API keys:

**Backend (Express.js example):**
```javascript
import { configure, translate } from '@skywu/translator';
import express from 'express';

// Configure server-side
configure({
  apiKey: process.env.OPENAI_API_KEY
});

const app = express();

app.post('/api/translate', async (req, res) => {
  const { text, options } = req.body;
  try {
    const result = await translate(text, options);
    res.json(result);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});
```

**Frontend:**
```jsx
import { TranslationProvider, useTranslation, LanguageSelector } from '@skywu/translator/react';

function App() {
  // Point to your server proxy, NOT directly to OpenAI
  const config = {
    apiKey: 'not-needed-for-proxy',
    baseURL: '/api'  // Your server endpoint
  };

  return (
    <TranslationProvider config={config}>
      <MyComponent />
    </TranslationProvider>
  );
}

function MyComponent() {
  const { t } = useTranslation();
  const [text, setText] = useState('');
  
  const handleTranslate = async () => {
    const result = await t('Hello World');
    setText(result);
  };

  return (
    <div>
      <LanguageSelector />
      <button onClick={handleTranslate}>Translate</button>
      <p>{text}</p>
    </div>
  );
}
```

## API Reference

### Core Functions

- `configure(config)` - Configure the translator
- `translate(text, options)` - Full translation with metadata
- `t(text, options)` - Simple translation shortcut
- `getSupportedLanguages()` - Get list of supported languages
- `getCacheStats()` - Get cache performance statistics
- `clearCache()` - Clear translation cache

#### Instance Methods (TranslatorClient)

- `getPlaceholderStats(text)` - Analyze placeholder patterns in text
- `addPlaceholderPatterns(patterns)` - Add custom placeholder patterns  
- `setPlaceholderProtection(enabled)` - Enable/disable placeholder protection

### React Components

Available via separate import: `@skywu/translator/react`

- `<TranslationProvider>` - Context provider for React apps
- `<LanguageSelector>` - Language selection dropdown
- `<TranslationDemo>` - Full-featured translation demo
- `useTranslation()` - Hook for accessing translation functions

## Configuration

```javascript
configure({
  apiKey: 'your-openai-api-key',  // Required - keep server-side only!
  baseURL: 'https://api.openai.com/v1',  // Optional - or your proxy URL
  model: 'gpt-4o-mini',  // Optional - valid OpenAI model
  defaultLanguage: 'en',  // Optional
  cacheEnabled: true,  // Optional - enable persistent caching
  cachePath: './my-cache',  // Optional - custom cache directory
  preservePlaceholders: true,  // Optional - protect placeholders (default: true)
  placeholderPatterns: []  // Optional - custom placeholder patterns
});
```

## Placeholder Protection 🛡️

**New in v1.1.0**: Automatic placeholder protection keeps your variables, URLs, and code snippets safe during translation!

### What Gets Protected Automatically

- **Variables**: `{{name}}`, `{count}`, `${value}`
- **URLs & Emails**: `https://example.com`, `user@domain.com`
- **Code**: ```npm install```, `git clone`
- **Programming**: `%s`, `%d`, `%1$s`
- **HTML Tags**: `<button>`, `</div>`
- **Tech Terms**: API, JSON, HTML, CSS, etc.
- **Files**: `.js`, `.json`, `config.yaml`
- **Versions**: `v1.2.3`, `2.0.0-beta`

### Example

```javascript
const result = await t('Hello {{user.name}}! Visit https://app.com for %d updates.', {
  to: 'zh'
});
// Result: "你好 {{user.name}}！访问 https://app.com 获取 %d 更新。"
```

### Custom Patterns

```javascript
const translator = new TranslatorClient({
  apiKey: process.env.OPENAI_API_KEY,
  placeholderPatterns: [
    /\[BRAND_NAME\]/g,  // Protect [BRAND_NAME] 
    /\$\{[A-Z_]+\}/g   // Protect ${ENV_VARS}
  ]
});

// Use instance methods for placeholder control
translator.addPlaceholderPatterns([/CUSTOM_PATTERN/g]);
translator.setPlaceholderProtection(true);
```

## Persistent Caching 💾

**New Feature**: Built-in LevelDB persistent caching for maximum performance!

### Cache Features

- **Persistent Storage**: Cache survives application restarts
- **Lightning Fast**: 2-5ms response time for cached translations
- **Automatic Management**: Smart cache cleanup and statistics
- **Custom Location**: Configure cache directory path

### Cache Configuration

```javascript
import { configure } from '@skywu/translator';

configure({
  apiKey: process.env.OPENAI_API_KEY,
  cacheEnabled: true,  // Enable persistent caching
  cachePath: './my-translator-cache'  // Custom cache directory (optional)
});

// Cache is automatically stored in:
// - Default: ~/.translator-cache (user home directory)
// - Custom: your specified path
```

### Cache Management

```javascript
import { getCacheStats, clearCache } from '@skywu/translator';

// Get cache statistics
const stats = await getCacheStats();
console.log(`Cache entries: ${stats.totalEntries}`);
console.log(`Hit rate: ${(stats.hitRate * 100).toFixed(1)}%`);

// Clear all cache
await clearCache();
```

### Performance Benefits

- **First translation**: 3-5 seconds (OpenAI API call)
- **Cached translation**: 2-5 milliseconds (1000x faster!)
- **Persistent**: Cache survives restarts and deployments

## App Localization Style 🎯

This library is optimized for in-app UI/UX copy. Translations are tailored for application interfaces.

### Guidelines

- Keep translations concise and action-oriented (buttons, labels, tooltips, dialogs)
- Preserve placeholders, variables, HTML/Markdown, and technical tokens exactly
- Use imperative mood for actions (e.g., "Save", "Continue")
- Respect platform conventions and capitalization for the target language
- Do not translate product names, brand names, or code terms
- Respond with only the translated text (no extra commentary)

No extra configuration is required; the system prompt is tuned for app localization by default.

### Example

```javascript
import { configure, t } from '@skywu/translator';

configure({
  apiKey: process.env.OPENAI_API_KEY,
  defaultLanguage: 'en',
  cacheEnabled: true
});

// Example UI strings (app-friendly tone)
await t('Save');
await t('Try again');
await t('New message from {{name}}');
await t('<b>Network error</b>. Please check your connection.');
```

## Security Best Practices

1. **Never expose API keys in the browser**
2. **Use environment variables for sensitive data**
3. **Create a server proxy for client-side usage**
4. **Validate and sanitize user inputs**
5. **Implement rate limiting on your API endpoints**

Example secure server setup:
```javascript
// server.js
configure({
  apiKey: process.env.OPENAI_API_KEY,  // From environment variable
  baseURL: process.env.OPENAI_BASE_URL  // Custom endpoint if needed
});
```

## Supported Languages

The library supports 40+ languages including:
English, Chinese, Japanese, Korean, French, German, Spanish, Italian, Portuguese, Russian, Arabic, Hindi, and many more.

## Development Notes

- The core library works in any JavaScript environment (Node.js, Bun, Deno)
- React components require React 16.8+ 
- TypeScript definitions included
- ESM module format
- Minimum Node.js 16+

## License

MIT License