@translated/lara 1.6.5 → 2.0.0-beta.0

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.
Files changed (72) hide show
  1. package/README.md +360 -2
  2. package/lib/Documents.d.ts +12 -0
  3. package/lib/Documents.js +71 -0
  4. package/lib/Glossaries.d.ts +17 -0
  5. package/lib/Glossaries.js +68 -0
  6. package/lib/Memories.d.ts +18 -0
  7. package/lib/Memories.js +95 -0
  8. package/lib/Translator.d.ts +24 -0
  9. package/lib/Translator.js +152 -0
  10. package/lib/index.d.ts +2 -6
  11. package/lib/index.js +2 -17
  12. package/lib/models/Authentication.d.ts +12 -0
  13. package/lib/models/Authentication.js +1 -0
  14. package/lib/models/UploadableFile.d.ts +1 -0
  15. package/lib/models/UploadableFile.js +1 -0
  16. package/lib/models/documents.d.ts +51 -0
  17. package/lib/{translator/models.js → models/documents.js} +2 -6
  18. package/lib/models/glossaries.d.ts +19 -0
  19. package/lib/models/glossaries.js +1 -0
  20. package/lib/models/index.d.ts +6 -0
  21. package/lib/models/index.js +6 -0
  22. package/lib/models/memories.d.ts +19 -0
  23. package/lib/models/memories.js +1 -0
  24. package/lib/models/translator.d.ts +48 -0
  25. package/lib/models/translator.js +1 -0
  26. package/lib/sdk-version.d.ts +1 -1
  27. package/lib/sdk-version.js +1 -4
  28. package/lib/utils/errors.js +12 -0
  29. package/lib/utils/formdata/browser.d.ts +2 -0
  30. package/lib/utils/formdata/browser.js +15 -0
  31. package/lib/utils/formdata/index.d.ts +4 -0
  32. package/lib/utils/formdata/index.js +10 -0
  33. package/lib/utils/formdata/node.d.ts +5 -0
  34. package/lib/utils/formdata/node.js +16 -0
  35. package/lib/utils/sleep.d.ts +2 -0
  36. package/lib/utils/sleep.js +1 -0
  37. package/lib/utils/toCamelCase.d.ts +2 -0
  38. package/lib/utils/toCamelCase.js +16 -0
  39. package/lib/utils/toSnakeCase.d.ts +2 -0
  40. package/lib/utils/toSnakeCase.js +16 -0
  41. package/package.json +23 -13
  42. package/lib/credentials.d.ts +0 -5
  43. package/lib/credentials.js +0 -10
  44. package/lib/crypto/browser-crypto.d.ts +0 -11
  45. package/lib/crypto/browser-crypto.js +0 -28
  46. package/lib/crypto/index.d.ts +0 -3
  47. package/lib/crypto/index.js +0 -15
  48. package/lib/crypto/node-crypto.d.ts +0 -6
  49. package/lib/crypto/node-crypto.js +0 -55
  50. package/lib/crypto/portable-crypto.d.ts +0 -5
  51. package/lib/crypto/portable-crypto.js +0 -2
  52. package/lib/errors.js +0 -18
  53. package/lib/net/browser-client.d.ts +0 -8
  54. package/lib/net/browser-client.js +0 -59
  55. package/lib/net/client.d.ts +0 -34
  56. package/lib/net/client.js +0 -108
  57. package/lib/net/index.d.ts +0 -3
  58. package/lib/net/index.js +0 -23
  59. package/lib/net/node-client.d.ts +0 -10
  60. package/lib/net/node-client.js +0 -100
  61. package/lib/net/s3/browser-client.d.ts +0 -9
  62. package/lib/net/s3/browser-client.js +0 -28
  63. package/lib/net/s3/client.d.ts +0 -9
  64. package/lib/net/s3/client.js +0 -10
  65. package/lib/net/s3/index.d.ts +0 -3
  66. package/lib/net/s3/index.js +0 -13
  67. package/lib/net/s3/node-client.d.ts +0 -10
  68. package/lib/net/s3/node-client.js +0 -47
  69. package/lib/translator/models.d.ts +0 -99
  70. package/lib/translator/translator.d.ts +0 -80
  71. package/lib/translator/translator.js +0 -260
  72. /package/lib/{errors.d.ts → utils/errors.d.ts} +0 -0
package/README.md CHANGED
@@ -1,7 +1,365 @@
1
- # Lara Node.js Library
1
+ # Lara Node.js SDK
2
+
3
+ [![Node Version](https://img.shields.io/badge/node-12+-blue.svg)](https://nodejs.org)
4
+ [![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)
2
5
 
3
6
  This SDK empowers you to build your own branded translation AI leveraging our translation fine-tuned language model.
4
7
 
5
8
  All major translation features are accessible, making it easy to integrate and customize for your needs.
6
9
 
7
- Lara’s SDK full documentation is available at https://developers.laratranslate.com/
10
+ ## 🌍 **Features:**
11
+ - **Text Translation**: Single strings, multiple strings, and complex text blocks
12
+ - **Document Translation**: Word, PDF, and other document formats with status monitoring
13
+ - **Translation Memory**: Store and reuse translations for consistency
14
+ - **Glossaries**: Enforce terminology standards across translations
15
+ - **Language Detection**: Automatic source language identification
16
+ - **Advanced Options**: Translation instructions and more
17
+
18
+ ## 📚 Documentation
19
+
20
+ Lara's SDK full documentation is available at [https://developers.laratranslate.com/](https://developers.laratranslate.com/)
21
+
22
+ ## 🚀 Quick Start
23
+
24
+ ### Installation
25
+
26
+ ```bash
27
+ npm install @translated/lara
28
+ ```
29
+
30
+ ### Basic Usage
31
+
32
+ ```javascript
33
+ const { Credentials, Translator } = require('@translated/lara');
34
+
35
+ // Set your credentials using environment variables (recommended)
36
+ const credentials = new Credentials(
37
+ process.env.LARA_ACCESS_KEY_ID,
38
+ process.env.LARA_ACCESS_KEY_SECRET
39
+ );
40
+
41
+ // Create translator instance
42
+ const lara = new Translator(credentials);
43
+
44
+ // Simple text translation
45
+ async function translateText() {
46
+ try {
47
+ const result = await lara.translate("Hello, world!", "en-US", "fr-FR");
48
+ console.log("Translation: " + result.translation);
49
+ // Output: Translation: Bonjour, le monde !
50
+ } catch (error) {
51
+ console.error("Translation error:", error.message);
52
+ }
53
+ }
54
+
55
+ translateText();
56
+ ```
57
+
58
+ ## 📖 Examples
59
+
60
+ The `examples/` directory contains comprehensive examples for all SDK features.
61
+
62
+ **All examples use environment variables for credentials, so set them first:**
63
+ ```bash
64
+ export LARA_ACCESS_KEY_ID="your-access-key-id"
65
+ export LARA_ACCESS_KEY_SECRET="your-access-key-secret"
66
+ ```
67
+
68
+ ### Text Translation
69
+ - **[text_translation.js](examples/text_translation.js)** - Complete text translation examples
70
+ - Single string translation
71
+ - Multiple strings translation
72
+ - Translation with instructions
73
+ - TextBlocks translation (mixed translatable/non-translatable content)
74
+ - Auto-detect source language
75
+ - Advanced translation options
76
+ - Get available languages
77
+
78
+ ```bash
79
+ cd examples
80
+ node text_translation.js
81
+ ```
82
+
83
+ ### Document Translation
84
+ - **[document_translation.js](examples/document_translation.js)** - Document translation examples
85
+ - Basic document translation
86
+ - Advanced options with memories and glossaries
87
+ - Step-by-step translation with status monitoring
88
+
89
+ ```bash
90
+ cd examples
91
+ node document_translation.js
92
+ ```
93
+
94
+ ### Translation Memory Management
95
+ - **[memories_management.js](examples/memories_management.js)** - Memory management examples
96
+ - Create, list, update, delete memories
97
+ - Add individual translations
98
+ - Multiple memory operations
99
+ - TMX file import with progress monitoring
100
+ - Translation deletion
101
+ - Translation with TUID and context
102
+
103
+ ```bash
104
+ cd examples
105
+ node memories_management.js
106
+ ```
107
+
108
+ ### Glossary Management
109
+ - **[glossaries_management.js](examples/glossaries_management.js)** - Glossary management examples
110
+ - Create, list, update, delete glossaries
111
+ - CSV import with status monitoring
112
+ - Glossary export
113
+ - Glossary terms count
114
+ - Import status checking
115
+
116
+ ```bash
117
+ cd examples
118
+ node glossaries_management.js
119
+ ```
120
+
121
+ ## 🔧 API Reference
122
+
123
+ ### Core Components
124
+
125
+ ### 🔐 Authentication
126
+
127
+ The SDK supports authentication via access key and secret:
128
+
129
+ ```javascript
130
+ const credentials = new Credentials("your-access-key-id", "your-access-key-secret");
131
+ const lara = new Translator(credentials);
132
+ ```
133
+
134
+ **Environment Variables (Recommended):**
135
+ ```bash
136
+ export LARA_ACCESS_KEY_ID="your-access-key-id"
137
+ export LARA_ACCESS_KEY_SECRET="your-access-key-secret"
138
+ ```
139
+
140
+ ```javascript
141
+ const credentials = new Credentials(
142
+ process.env.LARA_ACCESS_KEY_ID,
143
+ process.env.LARA_ACCESS_KEY_SECRET
144
+ );
145
+ ```
146
+
147
+
148
+ ### 🌍 Translator
149
+
150
+ ```javascript
151
+ // Create translator with credentials
152
+ const lara = new Translator(credentials);
153
+ ```
154
+
155
+ #### Text Translation
156
+
157
+ ```javascript
158
+ // Basic translation
159
+ const result = await lara.translate("Hello", "en-US", "fr-FR");
160
+
161
+ // Multiple strings
162
+ const result = await lara.translate(["Hello", "World"], "en-US", "fr-FR");
163
+
164
+ // TextBlocks (mixed translatable/non-translatable content)
165
+ const textBlocks = [
166
+ { text: "Translatable text", translatable: true },
167
+ { text: "<br>", translatable: false }, // Non-translatable HTML
168
+ { text: "More translatable text", translatable: true }
169
+ ];
170
+ const result = await lara.translate(textBlocks, "en-US", "fr-FR");
171
+
172
+ // With advanced options
173
+ const options = {
174
+ instructions: ["Formal tone"],
175
+ adaptTo: ["mem_1A2b3C4d5E6f7G8h9I0jKl"], // Replace with actual memory IDs
176
+ glossaries: ["gls_1A2b3C4d5E6f7G8h9I0jKl"], // Replace with actual glossary IDs
177
+ style: "fluid",
178
+ timeoutInMillis: 10000
179
+ };
180
+
181
+ const result = await lara.translate("Hello", "en-US", "fr-FR", options);
182
+ ```
183
+
184
+ ### 📖 Document Translation
185
+ #### Simple document translation
186
+
187
+ ```javascript
188
+ const fs = require('fs');
189
+
190
+ const fileStream = fs.createReadStream("/path/to/your/document.txt"); // Replace with actual file path
191
+ const translatedContent = await lara.documents.translate(fileStream, "document.txt", "en-US", "fr-FR");
192
+
193
+ // With options
194
+ const options = {
195
+ adaptTo: ["mem_1A2b3C4d5E6f7G8h9I0jKl"], // Replace with actual memory IDs
196
+ glossaries: ["gls_1A2b3C4d5E6f7G8h9I0jKl"], // Replace with actual glossary IDs
197
+ style: "fluid"
198
+ };
199
+
200
+ const translatedContent = await lara.documents.translate(fileStream, "document.txt", "en-US", "fr-FR", options);
201
+ ```
202
+ ### Document translation with status monitoring
203
+ #### Document upload
204
+ ```javascript
205
+ //Optional: upload options
206
+ const uploadOptions = {
207
+ adaptTo: ["mem_1A2b3C4d5E6f7G8h9I0jKl"], // Replace with actual memory IDs
208
+ glossaries: ["gls_1A2b3C4d5E6f7G8h9I0jKl"] // Replace with actual glossary IDs
209
+ };
210
+
211
+ const document = await lara.documents.upload(fileStream, "document.txt", "en-US", "fr-FR", uploadOptions);
212
+ ```
213
+ #### Document translation status monitoring
214
+ ```javascript
215
+ const status = await lara.documents.status(document.id);
216
+ ```
217
+ #### Download translated document
218
+ ```javascript
219
+ const translatedContent = await lara.documents.download(document.id);
220
+ ```
221
+
222
+ ### 🧠 Memory Management
223
+
224
+ ```javascript
225
+ // Create memory
226
+ const memory = await lara.memories.create("MyMemory");
227
+
228
+ // Create memory with external ID (MyMemory integration)
229
+ const memory = await lara.memories.create("Memory from MyMemory", "aabb1122"); // Replace with actual external ID
230
+
231
+ // Important: To update/overwrite a translation unit you must provide a tuid. Calls without a tuid always create a new unit and will not update existing entries.
232
+ // Add translation to single memory
233
+ const memoryImport = await lara.memories.addTranslation("mem_1A2b3C4d5E6f7G8h9I0jKl", "en-US", "fr-FR", "Hello", "Bonjour", "greeting_001");
234
+
235
+ // Add translation to multiple memories
236
+ const memoryImport = await lara.memories.addTranslation(["mem_1A2b3C4d5E6f7G8h9I0jKl", "mem_2XyZ9AbC8dEf7GhI6jKlMn"], "en-US", "fr-FR", "Hello", "Bonjour", "greeting_002");
237
+
238
+ // Add with context
239
+ const memoryImport = await lara.memories.addTranslation(
240
+ "mem_1A2b3C4d5E6f7G8h9I0jKl", "en-US", "fr-FR", "Hello", "Bonjour", "tuid",
241
+ "sentenceBefore", "sentenceAfter"
242
+ );
243
+
244
+ // TMX import from file
245
+ const tmxFileStream = fs.createReadStream("/path/to/your/memory.tmx"); // Replace with actual TMX file path
246
+ const memoryImport = await lara.memories.importTmx("mem_1A2b3C4d5E6f7G8h9I0jKl", tmxFileStream);
247
+
248
+ // Delete translation
249
+ // Important: if you omit tuid, all entries that match the provided fields will be removed
250
+ const deleteJob = await lara.memories.deleteTranslation(
251
+ "mem_1A2b3C4d5E6f7G8h9I0jKl", "en-US", "fr-FR", "Hello", "Bonjour", tuid="greeting_001"
252
+ );
253
+
254
+ // Wait for import completion
255
+ const completedImport = await lara.memories.waitForImport(memoryImport, undefined, 300000); // 5 minutes
256
+ ```
257
+
258
+ ### 📚 Glossary Management
259
+
260
+ ```javascript
261
+ // Create glossary
262
+ const glossary = await lara.glossaries.create("MyGlossary");
263
+
264
+ // Import CSV from file
265
+ const csvFileStream = fs.createReadStream("/path/to/your/glossary.csv"); // Replace with actual CSV file path
266
+ const glossaryImport = await lara.glossaries.importCsv("gls_1A2b3C4d5E6f7G8h9I0jKl", csvFileStream);
267
+
268
+ // Check import status
269
+ const importStatus = await lara.glossaries.getImportStatus("gls_1A2b3C4d5E6f7G8h9I0jKl");
270
+
271
+ // Wait for import completion
272
+ const completedImport = await lara.glossaries.waitForImport(glossaryImport, undefined, 300000); // 5 minutes
273
+
274
+ // Export glossary
275
+ const csvData = await lara.glossaries.export("gls_1A2b3C4d5E6f7G8h9I0jKl", "csv/table-uni", "en-US");
276
+
277
+ // Get glossary terms count
278
+ const counts = await lara.glossaries.counts("gls_1A2b3C4d5E6f7G8h9I0jKl");
279
+ ```
280
+
281
+ ### Translation Options
282
+
283
+ ```javascript
284
+ const TranslateOptions = {
285
+ adaptTo: ["mem_1A2b3C4d5E6f7G8h9I0jKl"], // Memory IDs to adapt to
286
+ glossaries: ["gls_1A2b3C4d5E6f7G8h9I0jKl"], // Glossary IDs to use
287
+ instructions: ["instruction"], // Translation instructions
288
+ style: "fluid", // Translation style (fluid, faithful, creative)
289
+ contentType: "text/plain", // Content type (text/plain, text/html, etc.)
290
+ multiline: true, // Enable multiline translation
291
+ timeoutInMillis: 10000, // Request timeout in milliseconds
292
+ sourceHint: "en", // Hint for source language detection
293
+ noTrace: false, // Disable request tracing
294
+ verbose: false, // Enable verbose response
295
+ };
296
+ ```
297
+
298
+ ### Language Codes
299
+
300
+ The SDK supports full language codes (e.g., `en-US`, `fr-FR`, `es-ES`) as well as simple codes (e.g., `en`, `fr`, `es`):
301
+
302
+ ```javascript
303
+ // Full language codes (recommended)
304
+ const result = await lara.translate("Hello", "en-US", "fr-FR");
305
+
306
+ // Simple language codes
307
+ const result = await lara.translate("Hello", "en", "fr");
308
+ ```
309
+
310
+ ### 🌐 Supported Languages
311
+
312
+ The SDK supports all languages available in the Lara API. Use the `getLanguages()` method to get the current list:
313
+
314
+ ```javascript
315
+ const languages = await lara.getLanguages();
316
+ console.log("Supported languages: " + languages.join(', '));
317
+ ```
318
+
319
+ ## ⚙️ Configuration
320
+
321
+ ### Error Handling
322
+
323
+ The SDK provides detailed error information:
324
+
325
+ ```javascript
326
+ try {
327
+ const result = await lara.translate("Hello", "en-US", "fr-FR");
328
+ console.log("Translation: " + result.translation);
329
+ } catch (error) {
330
+ if (error.constructor.name === 'LaraApiError') {
331
+ console.error("API Error [" + error.statusCode + "]: " + error.message);
332
+ console.error("Error type: " + error.type);
333
+ } else {
334
+ console.error("SDK Error: " + error.message);
335
+ }
336
+ }
337
+ ```
338
+
339
+ ## 📋 Requirements
340
+
341
+ - Node.js 12 or higher
342
+ - npm or yarn
343
+ - Valid Lara API credentials
344
+
345
+ ## 🧪 Testing
346
+
347
+ Run the examples to test your setup:
348
+
349
+ ```bash
350
+ # All examples use environment variables for credentials, so set them first:
351
+ export LARA_ACCESS_KEY_ID="your-access-key-id"
352
+ export LARA_ACCESS_KEY_SECRET="your-access-key-secret"
353
+ ```
354
+
355
+ ```bash
356
+ # Run basic text translation example
357
+ cd examples
358
+ node text_translation.js
359
+ ```
360
+
361
+ ## 📄 License
362
+
363
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
364
+
365
+ Happy translating! 🌍✨
@@ -0,0 +1,12 @@
1
+ import { AxiosInstance } from 'axios';
2
+ import { Document, DocumentDownloadOptions, DocumentTranslateOptions, DocumentUploadOptions, UploadableFile } from './models';
3
+ export default class Documents {
4
+ private readonly client;
5
+ private readonly pollingInterval;
6
+ private readonly maxWaitTime;
7
+ constructor(client: AxiosInstance);
8
+ upload(file: UploadableFile, filenane: string, source: string | null, target: string, options?: DocumentUploadOptions): Promise<Document>;
9
+ status(id: string): Promise<Document>;
10
+ download(id: string, options?: DocumentDownloadOptions): Promise<Blob | Buffer>;
11
+ translate(file: UploadableFile, filenane: string, source: string | null, target: string, options?: DocumentTranslateOptions): Promise<Blob | Buffer>;
12
+ }
@@ -0,0 +1,71 @@
1
+ import axios from 'axios';
2
+ import { DocumentStatus, } from './models';
3
+ import toFormData from './utils/formdata';
4
+ import toSnakeCase from './utils/toSnakeCase';
5
+ import sleep from './utils/sleep';
6
+ import { LaraApiError, TimeoutError } from './utils/errors';
7
+ export default class Documents {
8
+ constructor(client) {
9
+ this.pollingInterval = 2000;
10
+ this.maxWaitTime = 1000 * 60 * 15; // 15 minutes
11
+ this.client = client;
12
+ }
13
+ async upload(file, filenane, source, target, options) {
14
+ const { data: s3UploadUrlData } = await this.client.get(`/v2/documents/upload-url?filename=${encodeURIComponent(filenane)}`);
15
+ const { url, fields } = s3UploadUrlData;
16
+ const [formData, headers] = toFormData({
17
+ file,
18
+ ...fields,
19
+ });
20
+ await axios.post(url, formData, { headers });
21
+ const noTraceHeader = (options === null || options === void 0 ? void 0 : options.noTrace) ? { 'X-Lara-No-Trace': 'true' } : undefined;
22
+ const { data } = await this.client.post(`/v2/documents`, {
23
+ source,
24
+ target,
25
+ s3key: fields.key,
26
+ adapt_to: options === null || options === void 0 ? void 0 : options.adaptTo,
27
+ glossaries: options === null || options === void 0 ? void 0 : options.glossaries,
28
+ style: options === null || options === void 0 ? void 0 : options.style,
29
+ password: options === null || options === void 0 ? void 0 : options.password,
30
+ extraction_params: (options === null || options === void 0 ? void 0 : options.extractionParams) ? toSnakeCase(options.extractionParams) : undefined,
31
+ }, noTraceHeader ? { headers: noTraceHeader } : undefined);
32
+ return data;
33
+ }
34
+ async status(id) {
35
+ const { data } = await this.client.get(`/v2/documents/${id}`);
36
+ return data;
37
+ }
38
+ async download(id, options) {
39
+ const { data } = await this.client.get(`/v2/documents/${id}/download-url`, {
40
+ data: {
41
+ output_format: options === null || options === void 0 ? void 0 : options.outputFormat,
42
+ },
43
+ });
44
+ const { data: downloadedData } = await axios.get(data.url);
45
+ return downloadedData;
46
+ }
47
+ async translate(file, filenane, source, target, options) {
48
+ const uploadOptions = {
49
+ adaptTo: options === null || options === void 0 ? void 0 : options.adaptTo,
50
+ glossaries: options === null || options === void 0 ? void 0 : options.glossaries,
51
+ noTrace: options === null || options === void 0 ? void 0 : options.noTrace,
52
+ style: options === null || options === void 0 ? void 0 : options.style,
53
+ password: options === null || options === void 0 ? void 0 : options.password,
54
+ extractionParams: options === null || options === void 0 ? void 0 : options.extractionParams,
55
+ };
56
+ const { id } = await this.upload(file, filenane, source, target, uploadOptions);
57
+ const downloadOptions = {
58
+ outputFormat: options === null || options === void 0 ? void 0 : options.outputFormat,
59
+ };
60
+ const start = Date.now();
61
+ while (Date.now() - start < this.maxWaitTime) {
62
+ await sleep(this.pollingInterval);
63
+ const { status, errorReason } = await this.status(id);
64
+ if (status === DocumentStatus.TRANSLATED)
65
+ return await this.download(id, downloadOptions);
66
+ if (status === DocumentStatus.ERROR)
67
+ throw new LaraApiError(500, 'DocumentError', errorReason);
68
+ }
69
+ throw new TimeoutError();
70
+ }
71
+ }
@@ -0,0 +1,17 @@
1
+ import { AxiosInstance } from 'axios';
2
+ import { Glossary, GlossaryCounts, GlossaryImport, UploadableFile } from './models';
3
+ export default class Glossaries {
4
+ private readonly client;
5
+ private readonly pollingInterval;
6
+ constructor(client: AxiosInstance);
7
+ list(): Promise<Glossary[]>;
8
+ create(name: string): Promise<Glossary>;
9
+ get(id: string): Promise<Glossary>;
10
+ delete(id: string): Promise<Glossary>;
11
+ update(id: string, name: string): Promise<Glossary>;
12
+ importCsv(id: string, csv: UploadableFile, gzip?: boolean): Promise<GlossaryImport>;
13
+ getImportStatus(id: string): Promise<GlossaryImport>;
14
+ waitForImport(gImport: GlossaryImport, updateCallback?: (mImport: GlossaryImport) => void, maxWaitTime?: number): Promise<GlossaryImport>;
15
+ counts(id: string): Promise<GlossaryCounts>;
16
+ export(id: string, contentType: 'csv/table-uni', source?: string): Promise<string>;
17
+ }
@@ -0,0 +1,68 @@
1
+ import { TimeoutError } from './utils/errors';
2
+ import toFormData from './utils/formdata';
3
+ import sleep from './utils/sleep';
4
+ export default class Glossaries {
5
+ constructor(client) {
6
+ this.pollingInterval = 2000;
7
+ this.client = client;
8
+ }
9
+ async list() {
10
+ const { data } = await this.client.get('/v2/glossaries');
11
+ return data;
12
+ }
13
+ async create(name) {
14
+ const { data } = await this.client.post('/v2/glossaries', {
15
+ name,
16
+ });
17
+ return data;
18
+ }
19
+ async get(id) {
20
+ const { data } = await this.client.get(`/v2/glossaries/${id}`);
21
+ return data;
22
+ }
23
+ async delete(id) {
24
+ const { data } = await this.client.delete(`/v2/glossaries/${id}`);
25
+ return data;
26
+ }
27
+ async update(id, name) {
28
+ const { data } = await this.client.put(`/v2/glossaries/${id}`, { name });
29
+ return data;
30
+ }
31
+ async importCsv(id, csv, gzip = false) {
32
+ const [formData, headers] = toFormData({
33
+ csv,
34
+ compression: gzip ? 'gzip' : undefined,
35
+ });
36
+ const { data } = await this.client.post(`/v2/glossaries/${id}/import`, formData, { headers });
37
+ return data;
38
+ }
39
+ async getImportStatus(id) {
40
+ const { data } = await this.client.get(`/v2/glossaries/imports/${id}`);
41
+ return data;
42
+ }
43
+ async waitForImport(gImport, updateCallback, maxWaitTime) {
44
+ const start = Date.now();
45
+ while (gImport.progress < 1.0) {
46
+ if (maxWaitTime && Date.now() - start > maxWaitTime)
47
+ throw new TimeoutError();
48
+ await sleep(this.pollingInterval);
49
+ gImport = await this.getImportStatus(gImport.id);
50
+ updateCallback && updateCallback(gImport);
51
+ }
52
+ return gImport;
53
+ }
54
+ async counts(id) {
55
+ const { data } = await this.client.get(`/v2/glossaries/${id}/countes`);
56
+ return data;
57
+ }
58
+ // FIXME: this method should return a Blob or Buffer
59
+ async export(id, contentType, source) {
60
+ const { data } = await this.client.get(`/v2/glossaries/${id}/export`, {
61
+ data: {
62
+ content_type: contentType,
63
+ source: !!source ? source : undefined,
64
+ },
65
+ });
66
+ return data;
67
+ }
68
+ }
@@ -0,0 +1,18 @@
1
+ import { AxiosInstance } from 'axios';
2
+ import { Memory, MemoryImport, UploadableFile } from './models';
3
+ export default class Memories {
4
+ private readonly client;
5
+ private readonly pollingInterval;
6
+ constructor(client: AxiosInstance);
7
+ list(): Promise<Memory[]>;
8
+ create(name: string, externalId?: string): Promise<Memory>;
9
+ get(id: string): Promise<Memory>;
10
+ delete(id: string): Promise<Memory>;
11
+ update(id: string, name: string): Promise<Memory>;
12
+ addTranslation(id: string | string[], source: string, target: string, sentence: string, translation: string, tuid?: string, sentenceBefore?: string, sentenceAfter?: string, headers?: Record<string, any>): Promise<MemoryImport>;
13
+ deleteTranslation(id: string | string[], source: string, target: string, sentence?: string, translation?: string, tuid?: string, sentenceBefore?: string, sentenceAfter?: string): Promise<MemoryImport>;
14
+ importTmx(id: string, tmx: UploadableFile, gzip?: boolean): Promise<MemoryImport>;
15
+ getImportStatus(id: string): Promise<MemoryImport>;
16
+ waitForImport(mImport: MemoryImport, updateCallback?: (mImport: MemoryImport) => void, maxWaitTime?: number): Promise<MemoryImport>;
17
+ connect<T extends string | string[]>(ids: T): Promise<T extends string ? Memory : Memory[]>;
18
+ }
@@ -0,0 +1,95 @@
1
+ import { TimeoutError } from './utils/errors';
2
+ import toFormData from './utils/formdata';
3
+ import sleep from './utils/sleep';
4
+ export default class Memories {
5
+ constructor(client) {
6
+ this.pollingInterval = 2000;
7
+ this.client = client;
8
+ }
9
+ async list() {
10
+ const { data } = await this.client.get('/v2/memories');
11
+ return data;
12
+ }
13
+ async create(name, externalId) {
14
+ const { data } = await this.client.post('/v2/memories', {
15
+ name,
16
+ external_id: externalId,
17
+ });
18
+ return data;
19
+ }
20
+ async get(id) {
21
+ const { data } = await this.client.get(`/v2/memories/${id}`);
22
+ return data;
23
+ }
24
+ async delete(id) {
25
+ const { data } = await this.client.delete(`/v2/memories/${id}`);
26
+ return data;
27
+ }
28
+ async update(id, name) {
29
+ const { data } = await this.client.put(`/v2/memories/${id}`, { name });
30
+ return data;
31
+ }
32
+ async addTranslation(id, source, target, sentence, translation, tuid, sentenceBefore, sentenceAfter, headers) {
33
+ const url = Array.isArray(id) ? '/v2/memories/content' : `/v2/memories/${id}/content`;
34
+ const { data } = await this.client.put(url, {
35
+ ids: Array.isArray(id) ? id : undefined,
36
+ source,
37
+ target,
38
+ sentence,
39
+ translation,
40
+ tuid,
41
+ sentence_before: sentenceBefore,
42
+ sentence_after: sentenceAfter,
43
+ }, {
44
+ headers,
45
+ });
46
+ return data;
47
+ }
48
+ async deleteTranslation(id, source, target, sentence, translation, tuid, sentenceBefore, sentenceAfter) {
49
+ const url = Array.isArray(id) ? '/v2/memories/content' : `/v2/memories/${id}/content`;
50
+ const { data } = await this.client.delete(url, {
51
+ data: {
52
+ ids: Array.isArray(id) ? id : undefined,
53
+ source,
54
+ target,
55
+ sentence,
56
+ translation,
57
+ tuid,
58
+ sentence_before: sentenceBefore,
59
+ sentence_after: sentenceAfter,
60
+ },
61
+ });
62
+ return data;
63
+ }
64
+ async importTmx(id, tmx, gzip = false) {
65
+ const [formData, headers] = toFormData({
66
+ tmx,
67
+ compression: gzip ? 'gzip' : undefined,
68
+ });
69
+ const { data } = await this.client.post(`/v2/memories/${id}/import`, formData, {
70
+ headers,
71
+ });
72
+ return data;
73
+ }
74
+ async getImportStatus(id) {
75
+ const { data } = await this.client.get(`/v2/memories/imports/${id}`);
76
+ return data;
77
+ }
78
+ async waitForImport(mImport, updateCallback, maxWaitTime) {
79
+ const start = Date.now();
80
+ while (mImport.progress < 1.0) {
81
+ if (maxWaitTime && Date.now() - start > maxWaitTime)
82
+ throw new TimeoutError();
83
+ await sleep(this.pollingInterval);
84
+ mImport = await this.getImportStatus(mImport.id);
85
+ updateCallback && updateCallback(mImport);
86
+ }
87
+ return mImport;
88
+ }
89
+ async connect(ids) {
90
+ const { data } = await this.client.post('/v2/memories/connect', {
91
+ ids: Array.isArray(ids) ? ids : [ids],
92
+ });
93
+ return (Array.isArray(ids) ? data : data[0]);
94
+ }
95
+ }
@@ -0,0 +1,24 @@
1
+ import { AccessKey, Credentials, AuthToken, TranslatorOptions, TextBlock, TranslateOptions, TextResult } from './models';
2
+ import Memories from './Memories';
3
+ import Glossaries from './Glossaries';
4
+ import Documents from './Documents';
5
+ export declare class Translator {
6
+ private readonly accessKey?;
7
+ private readonly credentials?;
8
+ private authToken?;
9
+ readonly memories: Memories;
10
+ readonly glossaries: Glossaries;
11
+ readonly documents: Documents;
12
+ private token?;
13
+ private refreshToken?;
14
+ private readonly options?;
15
+ private readonly client;
16
+ constructor(accessKey?: AccessKey, credentials?: Credentials, authToken?: AuthToken, options?: TranslatorOptions);
17
+ private authenticate;
18
+ translate<T extends string | string[] | TextBlock[]>(text: T, source: string | null, target: string, options?: TranslateOptions): Promise<TextResult<T>>;
19
+ getLanguages(): Promise<string[]>;
20
+ static getLoginUrl(serverUrl?: string): Promise<string>;
21
+ static byAccessKey(id: string, secret: string, options?: TranslatorOptions): Translator;
22
+ static byCredentials(email: string, password: string, options?: TranslatorOptions): Translator;
23
+ static byAuthToken(token: string, refresh_token: string, options?: TranslatorOptions): Translator;
24
+ }