@happyvertical/translator 0.74.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENT.md +33 -0
- package/LICENSE +7 -0
- package/README.md +140 -0
- package/dist/chunks/deepl-CWEP0MSh.js +216 -0
- package/dist/chunks/deepl-CWEP0MSh.js.map +1 -0
- package/dist/chunks/google-KGGP9X0w.js +215 -0
- package/dist/chunks/google-KGGP9X0w.js.map +1 -0
- package/dist/chunks/libretranslate-BeC38-0r.js +211 -0
- package/dist/chunks/libretranslate-BeC38-0r.js.map +1 -0
- package/dist/cli/claude-context.d.ts +3 -0
- package/dist/cli/claude-context.d.ts.map +1 -0
- package/dist/cli/claude-context.js +21 -0
- package/dist/cli/claude-context.js.map +1 -0
- package/dist/index.d.ts +48 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +252 -0
- package/dist/index.js.map +1 -0
- package/dist/providers/deepl.d.ts +41 -0
- package/dist/providers/deepl.d.ts.map +1 -0
- package/dist/providers/google.d.ts +39 -0
- package/dist/providers/google.d.ts.map +1 -0
- package/dist/providers/libretranslate.d.ts +37 -0
- package/dist/providers/libretranslate.d.ts.map +1 -0
- package/dist/shared/types.d.ts +231 -0
- package/dist/shared/types.d.ts.map +1 -0
- package/dist/shared/utils.d.ts +39 -0
- package/dist/shared/utils.d.ts.map +1 -0
- package/metadata.json +32 -0
- package/package.json +70 -0
package/AGENT.md
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
# @happyvertical/translator
|
|
2
|
+
|
|
3
|
+
<!-- BEGIN AGENT:GENERATED -->
|
|
4
|
+
## Purpose
|
|
5
|
+
Standardized translation interface supporting Google Translate, DeepL, and LibreTranslate
|
|
6
|
+
|
|
7
|
+
## Package Map
|
|
8
|
+
- Package: `@happyvertical/translator`
|
|
9
|
+
- Hierarchy path: `@happyvertical/sdk > packages > translator`
|
|
10
|
+
- Workspace position: `27 of 30` local packages
|
|
11
|
+
- Internal dependencies: `@happyvertical/cache`, `@happyvertical/utils`
|
|
12
|
+
- Internal dependents: none
|
|
13
|
+
- Knowledge graph files: `AGENT.md`, `metadata.json`, `ecosystem-manifest.json`
|
|
14
|
+
|
|
15
|
+
## Build & Test
|
|
16
|
+
```bash
|
|
17
|
+
pnpm --filter @happyvertical/translator build
|
|
18
|
+
pnpm --filter @happyvertical/translator test
|
|
19
|
+
pnpm --filter @happyvertical/translator clean
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
## Agent Correction Loops
|
|
23
|
+
- If module resolution or export errors mention a workspace dependency, build the dependency first (`pnpm --filter @happyvertical/cache build`, `pnpm --filter @happyvertical/utils build`) and then rerun `pnpm --filter @happyvertical/translator build`.
|
|
24
|
+
- If tests or exports fail after API, type, or bundle changes, run `pnpm --filter @happyvertical/translator clean` followed by `pnpm --filter @happyvertical/translator build` and `pnpm --filter @happyvertical/translator test`.
|
|
25
|
+
- If failures span multiple packages or Turborepo ordering looks wrong, run `pnpm build` and `pnpm typecheck` from the repo root before retrying package-scoped commands.
|
|
26
|
+
|
|
27
|
+
## Ecosystem Relationships
|
|
28
|
+
- Provides: Standardized translation interface supporting Google Translate, DeepL, and LibreTranslate
|
|
29
|
+
- Implements: none
|
|
30
|
+
- Requires: @happyvertical/cache, @happyvertical/utils, @google-cloud/translate, deepl-node
|
|
31
|
+
- Stability: stable (Primary package surface is described as implemented and production-oriented.)
|
|
32
|
+
<!-- END AGENT:GENERATED -->
|
|
33
|
+
|
package/LICENSE
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
Copyright <2025> <Happy Vertical Corporation>
|
|
2
|
+
|
|
3
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
4
|
+
|
|
5
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
6
|
+
|
|
7
|
+
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
# @happyvertical/translator
|
|
2
|
+
|
|
3
|
+
Standardized translation interface supporting Google Translate, DeepL, and LibreTranslate. Uses a factory/adapter pattern with a unified `Translator` interface across all providers. Google and DeepL providers include automatic in-memory caching via `@happyvertical/cache`.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pnpm add @happyvertical/translator
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Quick Start
|
|
12
|
+
|
|
13
|
+
### Environment Variables
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
export HAVE_TRANSLATOR_PROVIDER=deepl
|
|
17
|
+
export DEEPL_API_KEY=your_key
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
```typescript
|
|
21
|
+
import { getTranslator } from '@happyvertical/translator';
|
|
22
|
+
|
|
23
|
+
const translator = await getTranslator();
|
|
24
|
+
const result = await translator.translate('Hello, world!', 'es');
|
|
25
|
+
console.log(result.translatedText); // "¡Hola, mundo!"
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
### Explicit Options
|
|
29
|
+
|
|
30
|
+
```typescript
|
|
31
|
+
// Google Translate
|
|
32
|
+
const translator = await getTranslator({
|
|
33
|
+
provider: 'google',
|
|
34
|
+
apiKey: process.env.GOOGLE_TRANSLATE_API_KEY!,
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
// DeepL
|
|
38
|
+
const translator = await getTranslator({
|
|
39
|
+
provider: 'deepl',
|
|
40
|
+
apiKey: process.env.DEEPL_API_KEY!,
|
|
41
|
+
freeApi: true,
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
// LibreTranslate (no API key required for public instances)
|
|
45
|
+
const translator = await getTranslator({
|
|
46
|
+
provider: 'libretranslate',
|
|
47
|
+
apiUrl: 'https://libretranslate.com',
|
|
48
|
+
});
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## Template Function
|
|
52
|
+
|
|
53
|
+
Create pre-configured translation functions for repeated use:
|
|
54
|
+
|
|
55
|
+
```typescript
|
|
56
|
+
const t = translator.templateFunction('en', 'es');
|
|
57
|
+
|
|
58
|
+
const greeting = await t('Hello, world!'); // "¡Hola, mundo!"
|
|
59
|
+
const farewell = await t('Goodbye!'); // "¡Adiós!"
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
## API
|
|
63
|
+
|
|
64
|
+
### `getTranslator(options?): Promise<Translator>`
|
|
65
|
+
|
|
66
|
+
Factory function. Reads `HAVE_TRANSLATOR_*` environment variables, merged with explicit options (explicit wins).
|
|
67
|
+
|
|
68
|
+
### `Translator` Interface
|
|
69
|
+
|
|
70
|
+
```typescript
|
|
71
|
+
interface Translator {
|
|
72
|
+
translate(text: string, targetLang: string, sourceLang?: string): Promise<TranslationResult>;
|
|
73
|
+
detectLanguage(text: string): Promise<LanguageDetectionResult>;
|
|
74
|
+
getSupportedLanguages(): Promise<SupportedLanguage[]>;
|
|
75
|
+
translateBatch(texts: string[], targetLang: string, sourceLang?: string): Promise<TranslationResult[]>;
|
|
76
|
+
templateFunction(sourceLang?: string, targetLang?: string): (text: string) => Promise<string>;
|
|
77
|
+
}
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
### `TranslationResult`
|
|
81
|
+
|
|
82
|
+
```typescript
|
|
83
|
+
interface TranslationResult {
|
|
84
|
+
translatedText: string;
|
|
85
|
+
sourceText: string;
|
|
86
|
+
sourceLanguage: string;
|
|
87
|
+
targetLanguage: string;
|
|
88
|
+
confidence?: number;
|
|
89
|
+
alternatives?: string[];
|
|
90
|
+
detectedSourceLanguage: boolean;
|
|
91
|
+
raw: any;
|
|
92
|
+
}
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
### `LanguageDetectionResult`
|
|
96
|
+
|
|
97
|
+
```typescript
|
|
98
|
+
interface LanguageDetectionResult {
|
|
99
|
+
language: string;
|
|
100
|
+
confidence: number;
|
|
101
|
+
alternatives?: Array<{ language: string; confidence: number }>;
|
|
102
|
+
raw: any;
|
|
103
|
+
}
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
### Error Classes
|
|
107
|
+
|
|
108
|
+
All extend `TranslationError`:
|
|
109
|
+
|
|
110
|
+
- `TranslationError` — base error with `code` and `provider` fields
|
|
111
|
+
- `UnsupportedLanguageError` — invalid language code
|
|
112
|
+
- `QuotaExceededError` — provider quota limit hit
|
|
113
|
+
- `AuthenticationError` — bad or missing API key
|
|
114
|
+
- `InvalidTextError` — empty or invalid input text
|
|
115
|
+
|
|
116
|
+
### Environment Variables
|
|
117
|
+
|
|
118
|
+
| Variable | Description |
|
|
119
|
+
|----------|-------------|
|
|
120
|
+
| `HAVE_TRANSLATOR_PROVIDER` | `google`, `deepl`, or `libretranslate` |
|
|
121
|
+
| `HAVE_TRANSLATOR_TIMEOUT` | Request timeout in ms |
|
|
122
|
+
| `HAVE_TRANSLATOR_MAX_RETRIES` | Max retry attempts |
|
|
123
|
+
| `HAVE_TRANSLATOR_API_URL` | LibreTranslate instance URL |
|
|
124
|
+
| `HAVE_TRANSLATOR_FREE_API` | DeepL free tier (`true`/`false`) |
|
|
125
|
+
| `HAVE_TRANSLATOR_PROJECT_ID` | Google Cloud project ID |
|
|
126
|
+
| `GOOGLE_TRANSLATE_API_KEY` | Google Translate API key |
|
|
127
|
+
| `DEEPL_API_KEY` | DeepL API key |
|
|
128
|
+
|
|
129
|
+
### Utility Exports
|
|
130
|
+
|
|
131
|
+
- `LANGUAGE_NAMES` — map of ISO 639-1 codes to English names
|
|
132
|
+
- `isValidLanguageCode(code)` — validates 2-letter language codes
|
|
133
|
+
- `getLanguageName(code)` — looks up language name from code
|
|
134
|
+
- `normalizeConfidence(score)` — normalizes scores to 0–1 range
|
|
135
|
+
- `isValidText(text)` — checks text is non-empty
|
|
136
|
+
- `truncateText(text, maxLength)` — truncates with ellipsis
|
|
137
|
+
|
|
138
|
+
## License
|
|
139
|
+
|
|
140
|
+
ISC
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
import { getCache } from "@happyvertical/cache";
|
|
2
|
+
import * as deepl from "deepl-node";
|
|
3
|
+
import { isValidText, InvalidTextError, AuthenticationError, QuotaExceededError, UnsupportedLanguageError, TranslationError } from "../index.js";
|
|
4
|
+
class DeepLProvider {
|
|
5
|
+
client;
|
|
6
|
+
timeout;
|
|
7
|
+
cache = null;
|
|
8
|
+
constructor(options) {
|
|
9
|
+
this.client = new deepl.Translator(options.apiKey, {
|
|
10
|
+
serverUrl: options.freeApi ? "https://api-free.deepl.com" : void 0
|
|
11
|
+
});
|
|
12
|
+
this.timeout = options.timeout || 3e4;
|
|
13
|
+
this.initCache();
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Initializes the memory cache for translation results
|
|
17
|
+
*/
|
|
18
|
+
async initCache() {
|
|
19
|
+
try {
|
|
20
|
+
this.cache = await getCache({
|
|
21
|
+
provider: "memory",
|
|
22
|
+
namespace: "translator:deepl",
|
|
23
|
+
defaultTTL: 3600,
|
|
24
|
+
// 1 hour cache
|
|
25
|
+
maxSize: 10 * 1024 * 1024,
|
|
26
|
+
// 10MB
|
|
27
|
+
maxEntries: 1e3,
|
|
28
|
+
evictionPolicy: "lru"
|
|
29
|
+
});
|
|
30
|
+
} catch (error) {
|
|
31
|
+
console.warn("Failed to initialize translation cache:", error);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Generates a cache key for translation requests
|
|
36
|
+
*/
|
|
37
|
+
getCacheKey(type, ...parts) {
|
|
38
|
+
return `${type}:${parts.join(":")}`;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Translates text from source language to target language
|
|
42
|
+
*/
|
|
43
|
+
async translate(text, targetLanguage, sourceLanguage) {
|
|
44
|
+
if (!isValidText(text)) {
|
|
45
|
+
throw new InvalidTextError("Text cannot be empty", "deepl");
|
|
46
|
+
}
|
|
47
|
+
const cacheKey = this.getCacheKey(
|
|
48
|
+
"translate",
|
|
49
|
+
text,
|
|
50
|
+
sourceLanguage || "auto",
|
|
51
|
+
targetLanguage
|
|
52
|
+
);
|
|
53
|
+
if (this.cache) {
|
|
54
|
+
const cached = await this.cache.get(cacheKey);
|
|
55
|
+
if (cached) {
|
|
56
|
+
return cached;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
try {
|
|
60
|
+
const result = await this.client.translateText(
|
|
61
|
+
text,
|
|
62
|
+
sourceLanguage || null,
|
|
63
|
+
targetLanguage
|
|
64
|
+
);
|
|
65
|
+
const translationResult = {
|
|
66
|
+
translatedText: result.text,
|
|
67
|
+
sourceText: text,
|
|
68
|
+
sourceLanguage: result.detectedSourceLang.toLowerCase(),
|
|
69
|
+
targetLanguage: targetLanguage.toLowerCase(),
|
|
70
|
+
detectedSourceLanguage: !sourceLanguage,
|
|
71
|
+
raw: result
|
|
72
|
+
};
|
|
73
|
+
if (this.cache) {
|
|
74
|
+
await this.cache.set(cacheKey, translationResult);
|
|
75
|
+
}
|
|
76
|
+
return translationResult;
|
|
77
|
+
} catch (error) {
|
|
78
|
+
throw this.mapError(error);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Detects the language of the provided text
|
|
83
|
+
* Note: DeepL doesn't have a dedicated language detection API,
|
|
84
|
+
* so we translate to English and use the detected source language
|
|
85
|
+
*/
|
|
86
|
+
async detectLanguage(text) {
|
|
87
|
+
if (!isValidText(text)) {
|
|
88
|
+
throw new InvalidTextError("Text cannot be empty", "deepl");
|
|
89
|
+
}
|
|
90
|
+
const cacheKey = this.getCacheKey("detect", text);
|
|
91
|
+
if (this.cache) {
|
|
92
|
+
const cached = await this.cache.get(cacheKey);
|
|
93
|
+
if (cached) {
|
|
94
|
+
return cached;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
try {
|
|
98
|
+
const result = await this.client.translateText(
|
|
99
|
+
text,
|
|
100
|
+
null,
|
|
101
|
+
"en-US"
|
|
102
|
+
);
|
|
103
|
+
const detectionResult = {
|
|
104
|
+
language: result.detectedSourceLang.toLowerCase(),
|
|
105
|
+
confidence: 1,
|
|
106
|
+
// DeepL doesn't provide confidence scores
|
|
107
|
+
raw: result
|
|
108
|
+
};
|
|
109
|
+
if (this.cache) {
|
|
110
|
+
await this.cache.set(cacheKey, detectionResult);
|
|
111
|
+
}
|
|
112
|
+
return detectionResult;
|
|
113
|
+
} catch (error) {
|
|
114
|
+
throw this.mapError(error);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Gets the list of languages supported by this provider
|
|
119
|
+
*/
|
|
120
|
+
async getSupportedLanguages() {
|
|
121
|
+
const cacheKey = this.getCacheKey("languages");
|
|
122
|
+
if (this.cache) {
|
|
123
|
+
const cached = await this.cache.get(cacheKey);
|
|
124
|
+
if (cached) {
|
|
125
|
+
return cached;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
try {
|
|
129
|
+
const [sourceLanguages, targetLanguages] = await Promise.all([
|
|
130
|
+
this.client.getSourceLanguages(),
|
|
131
|
+
this.client.getTargetLanguages()
|
|
132
|
+
]);
|
|
133
|
+
const languageMap = /* @__PURE__ */ new Map();
|
|
134
|
+
for (const lang of sourceLanguages) {
|
|
135
|
+
languageMap.set(lang.code.toLowerCase(), {
|
|
136
|
+
code: lang.code.toLowerCase(),
|
|
137
|
+
name: lang.name
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
for (const lang of targetLanguages) {
|
|
141
|
+
const code = lang.code.toLowerCase();
|
|
142
|
+
if (!languageMap.has(code)) {
|
|
143
|
+
languageMap.set(code, {
|
|
144
|
+
code,
|
|
145
|
+
name: lang.name
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
const result = Array.from(languageMap.values());
|
|
150
|
+
if (this.cache) {
|
|
151
|
+
await this.cache.set(cacheKey, result, 86400);
|
|
152
|
+
}
|
|
153
|
+
return result;
|
|
154
|
+
} catch (error) {
|
|
155
|
+
throw this.mapError(error);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Translates multiple texts in a single batch operation
|
|
160
|
+
*/
|
|
161
|
+
async translateBatch(texts, targetLanguage, sourceLanguage) {
|
|
162
|
+
if (texts.length === 0) {
|
|
163
|
+
return [];
|
|
164
|
+
}
|
|
165
|
+
try {
|
|
166
|
+
const results = await this.client.translateText(
|
|
167
|
+
texts,
|
|
168
|
+
sourceLanguage || null,
|
|
169
|
+
targetLanguage
|
|
170
|
+
);
|
|
171
|
+
const resultsArray = Array.isArray(results) ? results : [results];
|
|
172
|
+
return texts.map((text, index) => {
|
|
173
|
+
const result = resultsArray[index];
|
|
174
|
+
return {
|
|
175
|
+
translatedText: result.text,
|
|
176
|
+
sourceText: text,
|
|
177
|
+
sourceLanguage: result.detectedSourceLang.toLowerCase(),
|
|
178
|
+
targetLanguage: targetLanguage.toLowerCase(),
|
|
179
|
+
detectedSourceLanguage: !sourceLanguage,
|
|
180
|
+
raw: result
|
|
181
|
+
};
|
|
182
|
+
});
|
|
183
|
+
} catch (error) {
|
|
184
|
+
throw this.mapError(error);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
/**
|
|
188
|
+
* Maps DeepL errors to standardized error types
|
|
189
|
+
*/
|
|
190
|
+
mapError(error) {
|
|
191
|
+
if (error instanceof deepl.DeepLError) {
|
|
192
|
+
if (error.message.includes("401") || error.message.includes("403")) {
|
|
193
|
+
return new AuthenticationError("deepl");
|
|
194
|
+
}
|
|
195
|
+
if (error.message.includes("429") || error.message.includes("quota")) {
|
|
196
|
+
return new QuotaExceededError("deepl");
|
|
197
|
+
}
|
|
198
|
+
if (error.message.includes("language") || error.message.includes("not supported")) {
|
|
199
|
+
const match = error.message.match(/language[:\s]+([a-z-]+)/i);
|
|
200
|
+
const language = match ? match[1] : "unknown";
|
|
201
|
+
return new UnsupportedLanguageError(language, "deepl");
|
|
202
|
+
}
|
|
203
|
+
return new TranslationError(error.message, "DEEPL_ERROR", "deepl");
|
|
204
|
+
}
|
|
205
|
+
const err = error;
|
|
206
|
+
return new TranslationError(
|
|
207
|
+
err?.message || "Translation failed",
|
|
208
|
+
err?.code || "UNKNOWN_ERROR",
|
|
209
|
+
"deepl"
|
|
210
|
+
);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
export {
|
|
214
|
+
DeepLProvider
|
|
215
|
+
};
|
|
216
|
+
//# sourceMappingURL=deepl-CWEP0MSh.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"deepl-CWEP0MSh.js","sources":["../../src/providers/deepl.ts"],"sourcesContent":["/**\n * DeepL provider implementation\n */\n\nimport type { CacheAdapter } from '@happyvertical/cache';\nimport { getCache } from '@happyvertical/cache';\nimport * as deepl from 'deepl-node';\nimport type {\n DeepLOptions,\n LanguageDetectionResult,\n SupportedLanguage,\n TranslationProvider,\n TranslationResult,\n} from '../shared/types';\nimport {\n AuthenticationError,\n InvalidTextError,\n QuotaExceededError,\n TranslationError,\n UnsupportedLanguageError,\n} from '../shared/types';\nimport { isValidText } from '../shared/utils';\n\n/**\n * DeepL provider implementation with in-memory caching\n */\nexport class DeepLProvider implements TranslationProvider {\n private client: deepl.Translator;\n private timeout: number;\n private cache: CacheAdapter | null = null;\n\n constructor(options: DeepLOptions) {\n this.client = new deepl.Translator(options.apiKey, {\n serverUrl: options.freeApi ? 'https://api-free.deepl.com' : undefined,\n });\n this.timeout = options.timeout || 30000;\n\n // Initialize memory cache asynchronously\n this.initCache();\n }\n\n /**\n * Initializes the memory cache for translation results\n */\n private async initCache(): Promise<void> {\n try {\n this.cache = await getCache({\n provider: 'memory',\n namespace: 'translator:deepl',\n defaultTTL: 3600, // 1 hour cache\n maxSize: 10 * 1024 * 1024, // 10MB\n maxEntries: 1000,\n evictionPolicy: 'lru',\n });\n } catch (error) {\n // Cache initialization failure shouldn't break the provider\n console.warn('Failed to initialize translation cache:', error);\n }\n }\n\n /**\n * Generates a cache key for translation requests\n */\n private getCacheKey(type: string, ...parts: string[]): string {\n return `${type}:${parts.join(':')}`;\n }\n\n /**\n * Translates text from source language to target language\n */\n async translate(\n text: string,\n targetLanguage: string,\n sourceLanguage?: string,\n ): Promise<TranslationResult> {\n if (!isValidText(text)) {\n throw new InvalidTextError('Text cannot be empty', 'deepl');\n }\n\n // Check cache first\n const cacheKey = this.getCacheKey(\n 'translate',\n text,\n sourceLanguage || 'auto',\n targetLanguage,\n );\n if (this.cache) {\n const cached = await this.cache.get<TranslationResult>(cacheKey);\n if (cached) {\n return cached;\n }\n }\n\n try {\n const result = await this.client.translateText(\n text,\n (sourceLanguage as any) || null,\n targetLanguage as any,\n );\n\n const translationResult: TranslationResult = {\n translatedText: result.text,\n sourceText: text,\n sourceLanguage: result.detectedSourceLang.toLowerCase(),\n targetLanguage: targetLanguage.toLowerCase(),\n detectedSourceLanguage: !sourceLanguage,\n raw: result,\n };\n\n // Cache the result\n if (this.cache) {\n await this.cache.set(cacheKey, translationResult);\n }\n\n return translationResult;\n } catch (error) {\n throw this.mapError(error);\n }\n }\n\n /**\n * Detects the language of the provided text\n * Note: DeepL doesn't have a dedicated language detection API,\n * so we translate to English and use the detected source language\n */\n async detectLanguage(text: string): Promise<LanguageDetectionResult> {\n if (!isValidText(text)) {\n throw new InvalidTextError('Text cannot be empty', 'deepl');\n }\n\n // Check cache first\n const cacheKey = this.getCacheKey('detect', text);\n if (this.cache) {\n const cached = await this.cache.get<LanguageDetectionResult>(cacheKey);\n if (cached) {\n return cached;\n }\n }\n\n try {\n // Translate to English to get source language detection\n const result = await this.client.translateText(\n text,\n null,\n 'en-US' as any,\n );\n\n const detectionResult: LanguageDetectionResult = {\n language: result.detectedSourceLang.toLowerCase(),\n confidence: 1.0, // DeepL doesn't provide confidence scores\n raw: result,\n };\n\n // Cache the result\n if (this.cache) {\n await this.cache.set(cacheKey, detectionResult);\n }\n\n return detectionResult;\n } catch (error) {\n throw this.mapError(error);\n }\n }\n\n /**\n * Gets the list of languages supported by this provider\n */\n async getSupportedLanguages(): Promise<SupportedLanguage[]> {\n // Check cache first (this data rarely changes)\n const cacheKey = this.getCacheKey('languages');\n if (this.cache) {\n const cached = await this.cache.get<SupportedLanguage[]>(cacheKey);\n if (cached) {\n return cached;\n }\n }\n\n try {\n const [sourceLanguages, targetLanguages] = await Promise.all([\n this.client.getSourceLanguages(),\n this.client.getTargetLanguages(),\n ]);\n\n // Combine source and target languages, removing duplicates\n const languageMap = new Map<string, SupportedLanguage>();\n\n for (const lang of sourceLanguages) {\n languageMap.set(lang.code.toLowerCase(), {\n code: lang.code.toLowerCase(),\n name: lang.name,\n });\n }\n\n for (const lang of targetLanguages) {\n const code = lang.code.toLowerCase();\n if (!languageMap.has(code)) {\n languageMap.set(code, {\n code,\n name: lang.name,\n });\n }\n }\n\n const result = Array.from(languageMap.values());\n\n // Cache for longer (24 hours) as language lists rarely change\n if (this.cache) {\n await this.cache.set(cacheKey, result, 86400);\n }\n\n return result;\n } catch (error) {\n throw this.mapError(error);\n }\n }\n\n /**\n * Translates multiple texts in a single batch operation\n */\n async translateBatch(\n texts: string[],\n targetLanguage: string,\n sourceLanguage?: string,\n ): Promise<TranslationResult[]> {\n if (texts.length === 0) {\n return [];\n }\n\n try {\n const results = await this.client.translateText(\n texts,\n (sourceLanguage as any) || null,\n targetLanguage as any,\n );\n\n const resultsArray = Array.isArray(results) ? results : [results];\n\n return texts.map((text, index) => {\n const result = resultsArray[index];\n return {\n translatedText: result.text,\n sourceText: text,\n sourceLanguage: result.detectedSourceLang.toLowerCase(),\n targetLanguage: targetLanguage.toLowerCase(),\n detectedSourceLanguage: !sourceLanguage,\n raw: result,\n };\n });\n } catch (error) {\n throw this.mapError(error);\n }\n }\n\n /**\n * Maps DeepL errors to standardized error types\n */\n private mapError(error: unknown): TranslationError {\n if (error instanceof deepl.DeepLError) {\n if (error.message.includes('401') || error.message.includes('403')) {\n return new AuthenticationError('deepl');\n }\n\n if (error.message.includes('429') || error.message.includes('quota')) {\n return new QuotaExceededError('deepl');\n }\n\n if (\n error.message.includes('language') ||\n error.message.includes('not supported')\n ) {\n const match = error.message.match(/language[:\\s]+([a-z-]+)/i);\n const language = match ? match[1] : 'unknown';\n return new UnsupportedLanguageError(language, 'deepl');\n }\n\n return new TranslationError(error.message, 'DEEPL_ERROR', 'deepl');\n }\n\n const err = error as any;\n return new TranslationError(\n err?.message || 'Translation failed',\n err?.code || 'UNKNOWN_ERROR',\n 'deepl',\n );\n }\n}\n"],"names":[],"mappings":";;;AA0BO,MAAM,cAA6C;AAAA,EAChD;AAAA,EACA;AAAA,EACA,QAA6B;AAAA,EAErC,YAAY,SAAuB;AACjC,SAAK,SAAS,IAAI,MAAM,WAAW,QAAQ,QAAQ;AAAA,MACjD,WAAW,QAAQ,UAAU,+BAA+B;AAAA,IAAA,CAC7D;AACD,SAAK,UAAU,QAAQ,WAAW;AAGlC,SAAK,UAAA;AAAA,EACP;AAAA;AAAA;AAAA;AAAA,EAKA,MAAc,YAA2B;AACvC,QAAI;AACF,WAAK,QAAQ,MAAM,SAAS;AAAA,QAC1B,UAAU;AAAA,QACV,WAAW;AAAA,QACX,YAAY;AAAA;AAAA,QACZ,SAAS,KAAK,OAAO;AAAA;AAAA,QACrB,YAAY;AAAA,QACZ,gBAAgB;AAAA,MAA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AS,UAAU,KACjC,MAAM,QAAQ,SAAS,eAAe,GACtC;AACA,cAAM,QAAQ,MAAM,QAAQ,MAAM,0BAA0B;AAC5D,cAAM,WAAW,QAAQ,MAAM,CAAC,IAAI;AACpC,eAAO,IAAI,yBAAyB,UAAU,OAAO;AAAA,MACvD;AAEA,aAAO,IAAI,iBAAiB,MAAM,SAAS,eAAe,OAAO;AAAA,IACnE;AAEA,UAAM,MAAM;AACZ,WAAO,IAAI;AAAA,MACT,KAAK,WAAW;AAAA,MAChB,KAAK,QAAQ;AAAA,MACb;AAAA,IAAA;AAAA,EAEJ;AACF;"}
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
import { v2 } from "@google-cloud/translate";
|
|
2
|
+
import { getCache } from "@happyvertical/cache";
|
|
3
|
+
import { isValidText, InvalidTextError, TranslationError, normalizeConfidence, getLanguageName, AuthenticationError, QuotaExceededError, UnsupportedLanguageError } from "../index.js";
|
|
4
|
+
const { Translate } = v2;
|
|
5
|
+
class GoogleTranslateProvider {
|
|
6
|
+
client;
|
|
7
|
+
timeout;
|
|
8
|
+
cache = null;
|
|
9
|
+
constructor(options) {
|
|
10
|
+
this.client = new Translate({
|
|
11
|
+
key: options.apiKey,
|
|
12
|
+
projectId: options.projectId
|
|
13
|
+
});
|
|
14
|
+
this.timeout = options.timeout || 3e4;
|
|
15
|
+
this.initCache();
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Initializes the memory cache for translation results
|
|
19
|
+
*/
|
|
20
|
+
async initCache() {
|
|
21
|
+
try {
|
|
22
|
+
this.cache = await getCache({
|
|
23
|
+
provider: "memory",
|
|
24
|
+
namespace: "translator:google",
|
|
25
|
+
defaultTTL: 3600,
|
|
26
|
+
// 1 hour cache
|
|
27
|
+
maxSize: 10 * 1024 * 1024,
|
|
28
|
+
// 10MB
|
|
29
|
+
maxEntries: 1e3,
|
|
30
|
+
evictionPolicy: "lru"
|
|
31
|
+
});
|
|
32
|
+
} catch (error) {
|
|
33
|
+
console.warn("Failed to initialize translation cache:", error);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Generates a cache key for translation requests
|
|
38
|
+
*/
|
|
39
|
+
getCacheKey(type, ...parts) {
|
|
40
|
+
return `${type}:${parts.join(":")}`;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Translates text from source language to target language
|
|
44
|
+
*/
|
|
45
|
+
async translate(text, targetLanguage, sourceLanguage) {
|
|
46
|
+
if (!isValidText(text)) {
|
|
47
|
+
throw new InvalidTextError("Text cannot be empty", "google");
|
|
48
|
+
}
|
|
49
|
+
const cacheKey = this.getCacheKey(
|
|
50
|
+
"translate",
|
|
51
|
+
text,
|
|
52
|
+
sourceLanguage || "auto",
|
|
53
|
+
targetLanguage
|
|
54
|
+
);
|
|
55
|
+
if (this.cache) {
|
|
56
|
+
const cached = await this.cache.get(cacheKey);
|
|
57
|
+
if (cached) {
|
|
58
|
+
return cached;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
try {
|
|
62
|
+
const [translation] = await this.client.translate(text, {
|
|
63
|
+
from: sourceLanguage,
|
|
64
|
+
to: targetLanguage
|
|
65
|
+
});
|
|
66
|
+
const detectedSourceLanguage = !sourceLanguage;
|
|
67
|
+
let actualSourceLanguage = sourceLanguage;
|
|
68
|
+
if (!actualSourceLanguage) {
|
|
69
|
+
const [detection] = await this.client.detect(text);
|
|
70
|
+
actualSourceLanguage = Array.isArray(detection) ? detection[0].language : detection.language;
|
|
71
|
+
}
|
|
72
|
+
const result = {
|
|
73
|
+
translatedText: translation,
|
|
74
|
+
sourceText: text,
|
|
75
|
+
sourceLanguage: actualSourceLanguage || "unknown",
|
|
76
|
+
targetLanguage,
|
|
77
|
+
detectedSourceLanguage,
|
|
78
|
+
raw: translation
|
|
79
|
+
};
|
|
80
|
+
if (this.cache) {
|
|
81
|
+
await this.cache.set(cacheKey, result);
|
|
82
|
+
}
|
|
83
|
+
return result;
|
|
84
|
+
} catch (error) {
|
|
85
|
+
throw this.mapError(error);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Detects the language of the provided text
|
|
90
|
+
*/
|
|
91
|
+
async detectLanguage(text) {
|
|
92
|
+
if (!isValidText(text)) {
|
|
93
|
+
throw new InvalidTextError("Text cannot be empty", "google");
|
|
94
|
+
}
|
|
95
|
+
const cacheKey = this.getCacheKey("detect", text);
|
|
96
|
+
if (this.cache) {
|
|
97
|
+
const cached = await this.cache.get(cacheKey);
|
|
98
|
+
if (cached) {
|
|
99
|
+
return cached;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
try {
|
|
103
|
+
const [detections] = await this.client.detect(text);
|
|
104
|
+
const detectionsArray = Array.isArray(detections) ? detections : [detections];
|
|
105
|
+
if (detectionsArray.length === 0) {
|
|
106
|
+
throw new TranslationError(
|
|
107
|
+
"No language detected",
|
|
108
|
+
"NO_DETECTION",
|
|
109
|
+
"google"
|
|
110
|
+
);
|
|
111
|
+
}
|
|
112
|
+
const primary = detectionsArray[0];
|
|
113
|
+
const result = {
|
|
114
|
+
language: primary.language,
|
|
115
|
+
confidence: normalizeConfidence(primary.confidence || 0),
|
|
116
|
+
alternatives: detectionsArray.slice(1).map((d) => ({
|
|
117
|
+
language: d.language,
|
|
118
|
+
confidence: normalizeConfidence(d.confidence || 0)
|
|
119
|
+
})),
|
|
120
|
+
raw: detections
|
|
121
|
+
};
|
|
122
|
+
if (this.cache) {
|
|
123
|
+
await this.cache.set(cacheKey, result);
|
|
124
|
+
}
|
|
125
|
+
return result;
|
|
126
|
+
} catch (error) {
|
|
127
|
+
if (error instanceof TranslationError) {
|
|
128
|
+
throw error;
|
|
129
|
+
}
|
|
130
|
+
throw this.mapError(error);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Gets the list of languages supported by this provider
|
|
135
|
+
*/
|
|
136
|
+
async getSupportedLanguages() {
|
|
137
|
+
const cacheKey = this.getCacheKey("languages");
|
|
138
|
+
if (this.cache) {
|
|
139
|
+
const cached = await this.cache.get(cacheKey);
|
|
140
|
+
if (cached) {
|
|
141
|
+
return cached;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
try {
|
|
145
|
+
const [languages] = await this.client.getLanguages();
|
|
146
|
+
const result = languages.map((lang) => ({
|
|
147
|
+
code: lang.code,
|
|
148
|
+
name: lang.name || getLanguageName(lang.code)
|
|
149
|
+
}));
|
|
150
|
+
if (this.cache) {
|
|
151
|
+
await this.cache.set(cacheKey, result, 86400);
|
|
152
|
+
}
|
|
153
|
+
return result;
|
|
154
|
+
} catch (error) {
|
|
155
|
+
throw this.mapError(error);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Translates multiple texts in a single batch operation
|
|
160
|
+
*/
|
|
161
|
+
async translateBatch(texts, targetLanguage, sourceLanguage) {
|
|
162
|
+
if (texts.length === 0) {
|
|
163
|
+
return [];
|
|
164
|
+
}
|
|
165
|
+
try {
|
|
166
|
+
const [translations] = await this.client.translate(texts, {
|
|
167
|
+
from: sourceLanguage,
|
|
168
|
+
to: targetLanguage
|
|
169
|
+
});
|
|
170
|
+
const translationsArray = Array.isArray(translations) ? translations : [translations];
|
|
171
|
+
const detectedSourceLanguage = !sourceLanguage;
|
|
172
|
+
let actualSourceLanguage = sourceLanguage;
|
|
173
|
+
if (!actualSourceLanguage && texts.length > 0) {
|
|
174
|
+
const [detection] = await this.client.detect(texts[0]);
|
|
175
|
+
actualSourceLanguage = Array.isArray(detection) ? detection[0].language : detection.language;
|
|
176
|
+
}
|
|
177
|
+
return texts.map((text, index) => ({
|
|
178
|
+
translatedText: translationsArray[index] || text,
|
|
179
|
+
sourceText: text,
|
|
180
|
+
sourceLanguage: actualSourceLanguage || "unknown",
|
|
181
|
+
targetLanguage,
|
|
182
|
+
detectedSourceLanguage,
|
|
183
|
+
raw: translationsArray[index]
|
|
184
|
+
}));
|
|
185
|
+
} catch (error) {
|
|
186
|
+
throw this.mapError(error);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* Maps Google Translate errors to standardized error types
|
|
191
|
+
*/
|
|
192
|
+
mapError(error) {
|
|
193
|
+
const err = error;
|
|
194
|
+
if (err.code === 403 || err.code === 401) {
|
|
195
|
+
return new AuthenticationError("google");
|
|
196
|
+
}
|
|
197
|
+
if (err.code === 429) {
|
|
198
|
+
return new QuotaExceededError("google");
|
|
199
|
+
}
|
|
200
|
+
if (err.code === 400 && err.message?.includes("language")) {
|
|
201
|
+
const match = err.message.match(/language[:\s]+([a-z-]+)/i);
|
|
202
|
+
const language = match ? match[1] : "unknown";
|
|
203
|
+
return new UnsupportedLanguageError(language, "google");
|
|
204
|
+
}
|
|
205
|
+
return new TranslationError(
|
|
206
|
+
err.message || "Translation failed",
|
|
207
|
+
err.code || "UNKNOWN_ERROR",
|
|
208
|
+
"google"
|
|
209
|
+
);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
export {
|
|
213
|
+
GoogleTranslateProvider
|
|
214
|
+
};
|
|
215
|
+
//# sourceMappingURL=google-KGGP9X0w.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"google-KGGP9X0w.js","sources":["../../src/providers/google.ts"],"sourcesContent":["/**\n * Google Translate provider implementation\n */\n\nimport { v2 } from '@google-cloud/translate';\nimport type { CacheAdapter } from '@happyvertical/cache';\nimport { getCache } from '@happyvertical/cache';\nimport type {\n GoogleTranslateOptions,\n LanguageDetectionResult,\n SupportedLanguage,\n TranslationProvider,\n TranslationResult,\n} from '../shared/types';\nimport {\n AuthenticationError,\n InvalidTextError,\n QuotaExceededError,\n TranslationError,\n UnsupportedLanguageError,\n} from '../shared/types';\nimport {\n getLanguageName,\n isValidText,\n normalizeConfidence,\n} from '../shared/utils';\n\nconst { Translate } = v2;\n\n/**\n * Google Translate provider implementation with in-memory caching\n */\nexport class GoogleTranslateProvider implements TranslationProvider {\n private client: InstanceType<typeof Translate>;\n private timeout: number;\n private cache: CacheAdapter | null = null;\n\n constructor(options: GoogleTranslateOptions) {\n this.client = new Translate({\n key: options.apiKey,\n projectId: options.projectId,\n });\n this.timeout = options.timeout || 30000;\n\n // Initialize memory cache asynchronously\n this.initCache();\n }\n\n /**\n * Initializes the memory cache for translation results\n */\n private async initCache(): Promise<void> {\n try {\n this.cache = await getCache({\n provider: 'memory',\n namespace: 'translator:google',\n defaultTTL: 3600, // 1 hour cache\n maxSize: 10 * 1024 * 1024, // 10MB\n maxEntries: 1000,\n evictionPolicy: 'lru',\n });\n } catch (error) {\n // Cache initialization failure shouldn't break the provider\n console.warn('Failed to initialize translation cache:', error);\n }\n }\n\n /**\n * Generates a cache key for translation requests\n */\n private getCacheKey(type: string, ...parts: string[]): string {\n return `${type}:${parts.join(':')}`;\n }\n\n /**\n * Translates text from source language to target language\n */\n async translate(\n text: string,\n targetLanguage: string,\n sourceLanguage?: string,\n ): Promise<TranslationResult> {\n if (!isValidText(text)) {\n throw new InvalidTextError('Text cannot be empty', 'google');\n }\n\n // Check cache first\n const cacheKey = this.getCacheKey(\n 'translate',\n text,\n sourceLanguage || 'auto',\n targetLanguage,\n );\n if (this.cache) {\n const cached = await this.cache.get<TranslationResult>(cacheKey);\n if (cached) {\n return cached;\n }\n }\n\n try {\n const [translation] = await this.client.translate(text, {\n from: sourceLanguage,\n to: targetLanguage,\n });\n\n // Detect if source language was auto-detected\n const detectedSourceLanguage = !sourceLanguage;\n\n // Get detected language if not provided\n let actualSourceLanguage = sourceLanguage;\n if (!actualSourceLanguage) {\n const [detection] = await this.client.detect(text);\n actualSourceLanguage = Array.isArray(detection)\n ? detection[0].language\n : detection.language;\n }\n\n const result: TranslationResult = {\n translatedText: translation,\n sourceText: text,\n sourceLanguage: actualSourceLanguage || 'unknown',\n targetLanguage,\n detectedSourceLanguage,\n raw: translation,\n };\n\n // Cache the result\n if (this.cache) {\n await this.cache.set(cacheKey, result);\n }\n\n return result;\n } catch (error) {\n throw this.mapError(error);\n }\n }\n\n /**\n * Detects the language of the provided text\n */\n async detectLanguage(text: string): Promise<LanguageDetectionResult> {\n if (!isValidText(text)) {\n throw new InvalidTextError('Text cannot be empty', 'google');\n }\n\n // Check cache first\n const cacheKey = this.getCacheKey('detect', text);\n if (this.cache) {\n const cached = await this.cache.get<LanguageDetectionResult>(cacheKey);\n if (cached) {\n return cached;\n }\n }\n\n try {\n const [detections] = await this.client.detect(text);\n const detectionsArray = Array.isArray(detections)\n ? detections\n : [detections];\n\n if (detectionsArray.length === 0) {\n throw new TranslationError(\n 'No language detected',\n 'NO_DETECTION',\n 'google',\n );\n }\n\n const primary = detectionsArray[0];\n\n const result: LanguageDetectionResult = {\n language: primary.language,\n confidence: normalizeConfidence(primary.confidence || 0),\n alternatives: detectionsArray.slice(1).map((d) => ({\n language: d.language,\n confidence: normalizeConfidence(d.confidence || 0),\n })),\n raw: detections,\n };\n\n // Cache the result\n if (this.cache) {\n await this.cache.set(cacheKey, result);\n }\n\n return result;\n } catch (error) {\n if (error instanceof TranslationError) {\n throw error;\n }\n throw this.mapError(error);\n }\n }\n\n /**\n * Gets the list of languages supported by this provider\n */\n async getSupportedLanguages(): Promise<SupportedLanguage[]> {\n // Check cache first (this data rarely changes)\n const cacheKey = this.getCacheKey('languages');\n if (this.cache) {\n const cached = await this.cache.get<SupportedLanguage[]>(cacheKey);\n if (cached) {\n return cached;\n }\n }\n\n try {\n const [languages] = await this.client.getLanguages();\n\n const result = languages.map((lang) => ({\n code: lang.code,\n name: lang.name || getLanguageName(lang.code),\n }));\n\n // Cache for longer (24 hours) as language lists rarely change\n if (this.cache) {\n await this.cache.set(cacheKey, result, 86400);\n }\n\n return result;\n } catch (error) {\n throw this.mapError(error);\n }\n }\n\n /**\n * Translates multiple texts in a single batch operation\n */\n async translateBatch(\n texts: string[],\n targetLanguage: string,\n sourceLanguage?: string,\n ): Promise<TranslationResult[]> {\n if (texts.length === 0) {\n return [];\n }\n\n try {\n const [translations] = await this.client.translate(texts, {\n from: sourceLanguage,\n to: targetLanguage,\n });\n\n const translationsArray = Array.isArray(translations)\n ? translations\n : [translations];\n\n const detectedSourceLanguage = !sourceLanguage;\n let actualSourceLanguage = sourceLanguage;\n\n // Detect source language for first text if not provided\n if (!actualSourceLanguage && texts.length > 0) {\n const [detection] = await this.client.detect(texts[0]);\n actualSourceLanguage = Array.isArray(detection)\n ? detection[0].language\n : detection.language;\n }\n\n return texts.map((text, index) => ({\n translatedText: translationsArray[index] || text,\n sourceText: text,\n sourceLanguage: actualSourceLanguage || 'unknown',\n targetLanguage,\n detectedSourceLanguage,\n raw: translationsArray[index],\n }));\n } catch (error) {\n throw this.mapError(error);\n }\n }\n\n /**\n * Maps Google Translate errors to standardized error types\n */\n private mapError(error: unknown): TranslationError {\n const err = error as any;\n\n // Check for common error codes\n if (err.code === 403 || err.code === 401) {\n return new AuthenticationError('google');\n }\n\n if (err.code === 429) {\n return new QuotaExceededError('google');\n }\n\n if (err.code === 400 && err.message?.includes('language')) {\n const match = err.message.match(/language[:\\s]+([a-z-]+)/i);\n const language = match ? match[1] : 'unknown';\n return new UnsupportedLanguageError(language, 'google');\n }\n\n return new TranslationError(\n err.message || 'Translation failed',\n err.code || 'UNKNOWN_ERROR',\n 'google',\n );\n }\n}\n"],"names":[],"mappings":";;;AA2BA,MAAM,EAAE,cAAc;AAKf,MAAM,wBAAuD;AAAA,EAC1D;AAAA,EACA;AAAA,EACA,QAA6B;AAAA,EAErC,YAAY,SAAiC;AAC3C,SAAK,SAAS,IAAI,UAAU;AAAA,MAC1B,KAAK,QAAQ;AAAA,MACb,WAAW,QAAQ;AAAA,IAAA,CACpB;AACD,SAAK,UAAU,QAAQ,WAAW;AAGlC,SAAK,UAAA;AAAA,EACP;AAAA;AAAA;AAAA;AAAA,EAKA,MAAc,YAA2B;AACvC,QAAI;AACF,WAAK,QAAQ,MAAM,SAAS;AAAA,QAC1B,UAAU;AAAA,QACV,WAAW;AAAA,QACX,Y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