### Example: List All Glossaries Source: https://github.com/deeplcom/deepl-node/blob/main/_autodocs/api-reference/translator.md Example of listing all available glossaries and logging their names and entry counts. ```javascript const glossaries = await translator.listGlossaries(); glossaries.forEach(g => { console.log(`${g.name}: ${g.entryCount} entries`); }); ``` -------------------------------- ### Example: Create Glossary with Entries Source: https://github.com/deeplcom/deepl-node/blob/main/_autodocs/api-reference/translator.md Example of creating a glossary with predefined term mappings. Ensure GlossaryEntries is correctly instantiated. ```javascript const entries = new deepl.GlossaryEntries({ entries: { 'artist': 'Maler', 'prize': 'Gewinn' } }); const glossary = await translator.createGlossary( 'Art Glossary', 'en', 'de', entries ); console.log(`Created: ${glossary.glossaryId}`); ``` -------------------------------- ### Example: Download Translated Document Source: https://github.com/deeplcom/deepl-node/blob/main/_autodocs/api-reference/translator.md Example of how to download a translated document to a specified output file. ```javascript await translator.downloadDocument(handle, 'output.docx'); console.log('Document downloaded'); ``` -------------------------------- ### Install Dependencies and Run Translation Script Source: https://github.com/deeplcom/deepl-node/blob/main/examples/website-translation/index.html Install the necessary Node.js packages, set your DeepL authentication key, and run the main translation script. This prepares the environment and generates translated pages. ```bash npm install export DEEPL_AUTH_KEY= npm run main ``` -------------------------------- ### Basic DeepL Client Configuration Source: https://github.com/deeplcom/deepl-node/blob/main/_autodocs/configuration.md A simple example of initializing the DeepL client with only an authentication key. This is suitable for basic usage. ```javascript const deepl = require('deepl-node'); const client = new deepl.DeepLClient('your-auth-key'); ``` -------------------------------- ### Create and Use Glossary Source: https://github.com/deeplcom/deepl-node/blob/main/_autodocs/api-reference/glossary-entries.md Example of creating a `GlossaryEntries` object with a dictionary, then using it to create a glossary via the `DeepLClient` and applying it to a translation. ```javascript import * as deepl from 'deepl-node'; const client = new deepl.DeepLClient('auth-key'); // Create GlossaryEntries const entries = new deepl.GlossaryEntries({ entries: { 'art': 'Kunst', 'museum': 'Museum', 'gallery': 'Galerie' } }); // Create glossary via Translator const glossary = await client.createGlossary( 'Art Glossary', 'en', 'de', entries ); // Use in translation const result = await client.translateText( 'I visited the art museum and gallery.', 'en', 'de', { glossary: glossary.glossaryId } ); ``` -------------------------------- ### Install deepl-node Package Source: https://github.com/deeplcom/deepl-node/blob/main/_autodocs/README.md Install the DeepL Node.js client library using npm. Requires Node.js 14.17 or higher. ```bash npm install deepl-node ``` -------------------------------- ### Logging Example with DeepL Client Source: https://github.com/deeplcom/deepl-node/blob/main/_autodocs/configuration.md Demonstrates how to set the 'deepl' logger to 'debug' to view request and response details when using the DeepL client. Ensure the 'deepl-node' package is imported. ```javascript import log from 'loglevel'; import * as deepl from 'deepl-node'; log.getLogger('deepl').setLevel('debug'); const client = new deepl.DeepLClient('auth-key'); await client.translateText('Hello', 'en', 'de'); // Outputs: // [DEBUG] deepl: POST /v2/translate // [DEBUG] deepl: Status 200 OK ``` -------------------------------- ### Translate Text and Get Usage Source: https://github.com/deeplcom/deepl-node/blob/main/_autodocs/README.md Demonstrates how to initialize the DeepL client, translate text from English to German, and retrieve current API usage statistics. ```APIDOC ## Basic Usage ```javascript import * as deepl from 'deepl-node'; const authKey = process.env.DEEPL_AUTH_KEY; const client = new deepl.DeepLClient(authKey); // Translate text const result = await client.translateText('Hello, world!', 'en', 'de'); console.log(result.text); // 'Hallo, Welt!' // Check usage const usage = await client.getUsage(); console.log(`${usage.character.count}/${usage.character.limit} characters used`); ``` ``` -------------------------------- ### Example: Minify Document and Translate Source: https://github.com/deeplcom/deepl-node/blob/main/_autodocs/api-reference/document-minifier.md Demonstrates how to minify a document, then translate the minified version. The `cleanup` parameter is set to true to remove extracted document files after minification. ```javascript const minifier = new deepl.DocumentMinifier(); try { const minifiedPath = minifier.minifyDocument('large_presentation.pptx', true); console.log(`Minified document at: ${minifiedPath}`); // Now translate the minified document const status = await client.translateDocument( minifiedPath, 'translated.pptx', 'en', 'de' ); } catch (e) { if (e instanceof deepl.DocumentMinificationError) { console.error('Minification failed:', e.message); } } ``` -------------------------------- ### Example: Minify, Translate, and Deminify Document Source: https://github.com/deeplcom/deepl-node/blob/main/_autodocs/api-reference/document-minifier.md Shows the complete workflow of minifying a document, translating it, and then deminifying it back to its final form. The `cleanup` parameter is used in both minification and deminification steps. ```javascript const minifier = new deepl.DocumentMinifier(); try { if (deepl.DocumentMinifier.canMinifyFile('original.pptx')) { // Minify const minified = minifier.minifyDocument('original.pptx', true); // Translate await client.translateDocument( minified, 'translated_min.pptx', 'en', 'de' ); // Deminify (cleanup removes temp directory) minifier.deminifyDocument('translated_min.pptx', 'final.pptx', true); console.log('Document ready at: final.pptx'); } } catch (e) { if (e instanceof deepl.DocumentMinificationError) { console.error('Minification error:', e.message); } else if (e instanceof deepl.DocumentDeminificationError) { console.error('Deminification error:', e.message); } else if (e instanceof deepl.DocumentTranslationError) { console.error('Translation error:', e.message); } } ``` -------------------------------- ### Translate Large Presentation with Document Minifier Source: https://github.com/deeplcom/deepl-node/blob/main/_autodocs/api-reference/document-minifier.md This example demonstrates the complete workflow for translating a large presentation file using the DeepL Node.js DocumentMinifier. It includes checks for file support, minification, translation, and deminification, along with error handling for various DeepL-specific exceptions. ```javascript import * as deepl from 'deepl-node'; import * as fs from 'fs'; const client = new deepl.DeepLClient('auth-key'); const minifier = new deepl.DocumentMinifier(); async function translateLargePresentation() { const inputFile = 'large_presentation.pptx'; const outputFile = 'large_presentation_de.pptx'; try { // Check if file can be minified if (!deepl.DocumentMinifier.canMinifyFile(inputFile)) { throw new Error('File type not supported for minification'); } // Minify document (removes extracted docs after minification) console.log('Minifying document...'); const minifiedFile = minifier.minifyDocument(inputFile, true); // Translate minified document console.log('Translating document...'); const status = await client.translateDocument( minifiedFile, 'translated_temp.pptx', 'en', 'de' ); console.log(`Translated: ${status.billedCharacters} characters`); // Deminify (restore media and cleanup temp directory) console.log('Deminifying document...'); minifier.deminifyDocument('translated_temp.pptx', outputFile, true); console.log(`Done! Output saved to: ${outputFile}`); } catch (e) { if (e instanceof deepl.DocumentMinificationError) { console.error('Minification failed:', e.message); // Optionally save minified document for debugging } else if (e instanceof deepl.DocumentDeminificationError) { console.error('Deminification failed:', e.message); // Minified translated document still available } else if (e instanceof deepl.DocumentTranslationError) { console.error('Translation failed:', e.message); // Can potentially recover original document if (e.documentHandle) { console.log(`Document ID: ${e.documentHandle.documentId}`); } } else { console.error('Unexpected error:', e.message); } } } translateLargePresentation(); ``` -------------------------------- ### Translate Text with TypeScript Source: https://github.com/deeplcom/deepl-node/blob/main/README.md Provides an example of translating multiple text strings using TypeScript, specifying the target language and iterating over the results. This demonstrates type safety and handling of array inputs. ```typescript import * as deepl from 'deepl-node'; (async () => { const targetLang: deepl.TargetLanguageCode = 'fr'; const results = await deeplClient.translateText( ['Hello, world!', 'How are you?'], null, targetLang, ); results.map((result: deepl.TextResult) => { console.log(result.text); // Bonjour, le monde ! }); })(); ``` -------------------------------- ### Initialize DeepL Client with Async/Await (ES Modules) Source: https://github.com/deeplcom/deepl-node/blob/main/README.md Demonstrates how to import the DeepL package and initialize the DeepLClient using async/await syntax with ES Modules. Remember to replace the placeholder API key with your actual key and avoid hard-coding it in production. ```javascript import * as deepl from 'deepl-node'; const authKey = "f63c02c5-f056-..."; // Replace with your key const deeplClient = new deepl.DeepLClient(authKey); (async () => { const result = await deeplClient.translateText('Hello, world!', null, 'fr'); console.log(result.text); // Bonjour, le monde ! })(); ``` -------------------------------- ### Glossary Management Functions Source: https://github.com/deeplcom/deepl-node/blob/main/README.md Provides functions to get, list, and delete stored glossaries and their dictionaries. ```APIDOC ## getMultilingualGlossary() ### Description Retrieves a stored multilingual glossary by its ID. ### Method `getMultilingualGlossary(glossaryId: string | MultilingualGlossaryInfo)` ### Parameters - **glossaryId** (string | MultilingualGlossaryInfo) - The ID or object of the glossary to retrieve. ### Response - **MultilingualGlossaryInfo** - An object containing information about the stored glossary. ### Throws - Exception if no such glossary is found. ## listMultilingualGlossaries() ### Description Retrieves a list of all stored multilingual glossaries. ### Method `listMultilingualGlossaries()` ### Response - **Promise** - A promise that resolves to an array of MultilingualGlossaryInfo objects. ## deleteMultilingualGlossary() ### Description Deletes a stored multilingual glossary. ### Method `deleteMultilingualGlossary(glossaryId: string | MultilingualGlossaryInfo)` ### Parameters - **glossaryId** (string | MultilingualGlossaryInfo) - The ID or object of the glossary to delete. ### Throws - Exception if no such glossary is found. ## deleteMultilingualGlossaryDictionary() ### Description Deletes a specific dictionary within a stored multilingual glossary. ### Method `deleteMultilingualGlossaryDictionary(glossaryId: string | MultilingualGlossaryInfo, sourceLang: string, targetLang: string)` or `deleteMultilingualGlossaryDictionary(glossaryId: string | MultilingualGlossaryInfo, dictionaryInfo: MultilingualGlossaryDictionaryInfo)` ### Parameters - **glossaryId** (string | MultilingualGlossaryInfo) - The ID or object of the glossary containing the dictionary. - **sourceLang** (string) - The source language code of the dictionary to delete. - **targetLang** (string) - The target language code of the dictionary to delete. - **dictionaryInfo** (MultilingualGlossaryDictionaryInfo) - An object identifying the dictionary to delete. ### Throws - Exception if no such glossary dictionary is found. ``` -------------------------------- ### Get Target Languages Source: https://github.com/deeplcom/deepl-node/blob/main/_autodocs/api-reference/translator.md Fetches a list of target languages supported by the DeepL API, including regional variants. ```typescript async getTargetLanguages(): Promise ``` -------------------------------- ### Initialize DeepL Client (CommonJS) Source: https://github.com/deeplcom/deepl-node/blob/main/README.md Shows how to require the DeepL package and initialize the DeepLClient in a CommonJS environment. Ensure your authentication key is securely managed. ```javascript const deepl = require('deepl-node'); const deeplClient = new deepl.DeepLClient(authKey); ``` -------------------------------- ### Get Multilingual Glossary Metadata Source: https://github.com/deeplcom/deepl-node/blob/main/_autodocs/api-reference/deepl-client.md Retrieves metadata for a specific glossary by its ID. This method returns basic information about the glossary. ```typescript async getMultilingualGlossary(glossaryId: string): Promise ``` -------------------------------- ### Initialize DeepL Client with Custom Configuration Source: https://github.com/deeplcom/deepl-node/blob/main/_autodocs/README.md Instantiate the DeepL client with an authentication key and custom configuration options. This includes setting a custom server URL, retry attempts, timeouts, extra headers, proxy settings, and application identification. ```javascript const client = new deepl.DeepLClient(authKey, { serverUrl: 'https://api.deepl.com', // Custom API URL maxRetries: 5, // Max retry attempts minTimeout: 10000, // Timeout per attempt (ms) headers: { 'X-Custom': 'value' }, // Extra headers proxy: { host: 'proxy.com', port: 8080 }, // Proxy config sendPlatformInfo: true, // Include platform in User-Agent appInfo: { // Your app identification appName: 'MyApp', appVersion: '1.0.0' } }); ``` -------------------------------- ### Read Environment Variables for DeepL Client Source: https://github.com/deeplcom/deepl-node/blob/main/_autodocs/configuration.md Demonstrates how to read authentication keys and other configuration options from environment variables to initialize the DeepL client. Ensure the DEEPL_AUTH_KEY is set. ```javascript const authKey = process.env.DEEPL_AUTH_KEY; if (!authKey) { throw new Error('DEEPL_AUTH_KEY environment variable not set'); } const translator = new deepl.Translator(authKey, { serverUrl: process.env.DEEPL_SERVER_URL || undefined, maxRetries: parseInt(process.env.DEEPL_MAX_RETRIES || '5'), minTimeout: parseInt(process.env.DEEPL_MIN_TIMEOUT || '5000') }); ``` -------------------------------- ### Get Glossary Language Pairs Source: https://github.com/deeplcom/deepl-node/blob/main/_autodocs/api-reference/translator.md Retrieves language pairs that are supported for creating glossaries. Each pair specifies a source and target language code. ```typescript async getGlossaryLanguagePairs(): Promise ``` ```javascript const pairs = await translator.getGlossaryLanguagePairs(); pairs.forEach(pair => { console.log(`${pair.sourceLang} → ${pair.targetLang}`); }); ``` -------------------------------- ### Validate Glossary Term Example Source: https://github.com/deeplcom/deepl-node/blob/main/_autodocs/api-reference/glossary-entries.md Demonstrates the usage of `validateGlossaryTerm`. Valid terms pass silently, while invalid terms trigger a `DeepLError` that can be caught and logged. ```javascript deepl.GlossaryEntries.validateGlossaryTerm('hello'); // Valid ``` ```javascript try { deepl.GlossaryEntries.validateGlossaryTerm('hello\nworld'); // Contains newline } catch (e) { console.error(e.message); // Term contains invalid character } ``` ```javascript try { deepl.GlossaryEntries.validateGlossaryTerm(''); // Empty } catch (e) { console.error(e.message); // '' is not a valid term } ``` -------------------------------- ### Initialize Client with Application Info Source: https://github.com/deeplcom/deepl-node/blob/main/README.md Initializes the DeepL client with custom application information, including name and version. This is passed to the DeepL API for identification. ```javascript const options = {appInfo: { appName: 'sampleNodeTranslationApp', appVersion: '1.2.3' },}; const deepl = new deepl.DeepLClient('YOUR_AUTH_KEY', options); ``` -------------------------------- ### Configure Proxy Server for HTTP Requests Source: https://github.com/deeplcom/deepl-node/blob/main/_autodocs/configuration.md Set up a proxy server for all HTTP requests. Supports basic proxy configuration, authentication, and explicit protocol specification. ```javascript // Basic proxy const translator = new deepl.Translator(authKey, { proxy: { host: 'proxy.example.com', port: 8080 } }); ``` ```javascript // Proxy with authentication const translator = new deepl.Translator(authKey, { proxy: { host: 'proxy.example.com', port: 8080, auth: { username: 'username', password: 'password' } } }); ``` ```javascript // With explicit protocol const translator = new deepl.Translator(authKey, { proxy: { host: 'proxy.example.com', port: 443, protocol: 'https' } }); ``` -------------------------------- ### Get Multilingual Glossary Dictionary Entries Source: https://github.com/deeplcom/deepl-node/blob/main/_autodocs/api-reference/deepl-client.md Retrieves the specific entries for a language pair within a glossary. Use this to inspect or download a particular dictionary. ```typescript async getMultilingualGlossaryDictionaryEntries( glossary: GlossaryId | MultilingualGlossaryInfo, sourceLanguageCode: string, targetLanguageCode: string ): Promise ``` -------------------------------- ### Retrieve Glossary Entries Source: https://github.com/deeplcom/deepl-node/blob/main/_autodocs/api-reference/glossary-entries.md Get the internal dictionary of source-target term pairs. The returned object uses source terms as keys and their translations as values. ```javascript const entries = new deepl.GlossaryEntries({ entries: { 'hello': 'hallo' } }); const dict = entries.entries(); console.log(dict.hello); // 'hallo' console.log(Object.keys(dict)); // ['hello'] ``` -------------------------------- ### Translate Text with Options Source: https://github.com/deeplcom/deepl-node/blob/main/_autodocs/README.md Translate text with specific options like formality, sentence splitting, formatting preservation, and context. Ensure the 'deepl-node' library is installed. ```javascript const result = await client.translateText( 'How are you?', 'en', 'de', { formality: 'more', // Formal German splitSentences: 'off', // Single sentence preserveFormatting: true, // Keep formatting context: 'This is a greeting' // Additional context } ); ``` -------------------------------- ### Handle QuotaExceededError Source: https://github.com/deeplcom/deepl-node/blob/main/_autodocs/errors.md Example of catching a QuotaExceededError. This is useful when you need to inform the user about exceeding their translation limits and suggest upgrading their plan or waiting for the next billing cycle. ```javascript try { const result = await translator.translateText('Hello', 'en', 'de'); } catch (e) { if (e instanceof deepl.QuotaExceededError) { console.error('Translation limit exceeded. Upgrade your account.'); } } ``` -------------------------------- ### createStyleRuleCustomInstruction Source: https://github.com/deeplcom/deepl-node/blob/main/_autodocs/api-reference/deepl-client.md Creates a custom instruction for a style rule, allowing for specific guidance on how text should be handled. ```APIDOC ## createStyleRuleCustomInstruction ### Description Creates a custom instruction for a style rule. ### Method `createStyleRuleCustomInstruction` ### Parameters #### Path Parameters - **styleId** (StyleId) - Yes - ID of the style rule - **instruction** (CustomInstructionRequestBody) - Yes - Instruction with label and prompt ### Request Example ```javascript const instruction = await client.createStyleRuleCustomInstruction( 'style_rule_id', { label: 'Technical Terms', prompt: 'Always preserve technical terminology' } ); ``` ### Response #### Success Response - **CustomInstruction** — Created instruction with ID. ### Throws - `ArgumentError` if parameters invalid - `DeepLError` on API errors ``` -------------------------------- ### Configure Proxy for DeepL Client Source: https://github.com/deeplcom/deepl-node/blob/main/README.md Set up a proxy for the DeepL client by providing proxy options (host and port) during client instantiation. This is passed to the underlying 'axios' request. ```javascript const options = {proxy: {host: 'localhost', port: 3000}}; const deepl = new deepl.DeepLClient('YOUR_AUTH_KEY', options); ``` -------------------------------- ### Handle Document Translation Errors Source: https://github.com/deeplcom/deepl-node/blob/main/_autodocs/errors.md Example of how to catch and handle DocumentTranslationError during document translation. It demonstrates checking for the error type and accessing the documentHandle for potential recovery or status checks. ```javascript try { await translator.translateDocument('huge.pptx', 'output.pptx', 'en', 'de'); } catch (e) { if (e instanceof deepl.DocumentTranslationError) { console.error('Document translation failed:', e.message); if (e.documentHandle) { console.log('Document ID:', e.documentHandle.documentId); // Can use handle to recover or retry const status = await translator.getDocumentStatus(e.documentHandle); console.log('Status:', status.status); } } } ``` -------------------------------- ### Testing DeepL Client Configuration Source: https://github.com/deeplcom/deepl-node/blob/main/_autodocs/configuration.md Configuration for testing purposes, using a local mock server URL and reduced retry count for faster failure. Includes a fallback test key. ```javascript const client = new deepl.DeepLClient(process.env.DEEPL_AUTH_KEY || 'test-key', { serverUrl: 'http://localhost:3000', // Local mock server maxRetries: 1, // Fail fast in tests minTimeout: 2000 }); ``` -------------------------------- ### Create, List, and Delete Glossaries Source: https://github.com/deeplcom/deepl-node/blob/main/README.md Demonstrates creating a multilingual glossary, listing all available glossaries, and then deleting a specific glossary dictionary or an entire glossary. Ensure glossary IDs or objects are correctly passed for deletion operations. ```javascript const glossaryDicts = [{sourceLangCode: 'en', targetLangCode: 'de', entries: new deepl.GlossaryEntries({ entries: {'hello': 'hallo'}})}, {sourceLangCode: 'de', targetLangCode: 'en', entries: new deepl.GlossaryEntries({ entries: {'hallo': 'hello'}})}]; const createdGlossary = await deeplClient.createMultilingualGlossary('My Glossary', glossaryDicts); const glossaries = await deeplClient.listMultilingualGlossaries(); // Delete a dictionary in a glossary await deeplClient.deleteMultilingualGlossaryDictionary(createdGlossary, 'de', 'en'); // Delete a glossary by name for (const glossary of glossaries) { if (glossary.name === "Old glossary") { await deeplClient.deleteMultilingualGlossary(glossary); } } ``` -------------------------------- ### Get Style Rule Custom Instruction Source: https://github.com/deeplcom/deepl-node/blob/main/_autodocs/api-reference/deepl-client.md Retrieves a specific custom instruction associated with a style rule. You need to provide both the style rule ID and the custom instruction ID. -------------------------------- ### Get Source Languages Source: https://github.com/deeplcom/deepl-node/blob/main/_autodocs/api-reference/translator.md Fetches a list of source languages supported by the DeepL API. Each language object includes its name, ISO 639-1 code, and whether it supports formality. ```typescript async getSourceLanguages(): Promise ``` ```javascript const langs = await translator.getSourceLanguages(); langs.forEach(lang => { console.log(`${lang.name} (${lang.code})`); }); ``` -------------------------------- ### Initialize Translator with Options Source: https://github.com/deeplcom/deepl-node/blob/main/_autodocs/configuration.md Instantiate the Translator class with an authentication key and a configuration object. The options object allows customization of API server URL, headers, retry attempts, timeouts, proxy, and platform information. ```typescript const translator = new deepl.Translator(authKey, options); ``` -------------------------------- ### Retrieve All Style Rules with Details Source: https://github.com/deeplcom/deepl-node/blob/main/_autodocs/api-reference/deepl-client.md Fetches all style rules, including detailed configurations, with support for pagination. Useful for listing and inspecting existing rules. ```javascript const rules = await client.getAllStyleRules(0, 10, true); rules.forEach(rule => { console.log(`${rule.name} (${rule.styleId})`); if (rule.configuredRules?.styleAndTone) { console.log(' Style & Tone:', rule.configuredRules.styleAndTone); } }); ``` -------------------------------- ### Get Monolingual and Multilingual Glossaries Source: https://github.com/deeplcom/deepl-node/blob/main/upgrading_to_multilingual_glossaries.md Retrieve glossary information using `getGlossary` for monolingual and `getMultilingualGlossary` for multilingual glossaries. Ensure you pass the correct glossary object created previously. ```javascript // monolingual glossary example const createdGlossary = await deeplClient.createGlossary('My Glossary', 'en', 'de', new deepl.GlossaryEntries({ entries: { Hello: 'Hallo' } })); const glossaryInfo = await deeplClient.getGlossary(createdGlossary); // GlossaryInfo object ``` ```javascript // multilingual glossary example const glossaryDicts = [{sourceLangCode: 'en', targetLangCode: 'de', entries: new deepl.GlossaryEntries({ entries: { Hello: 'Hallo' } })}]; const createdGlossary = await deeplClient.createMultilingualGlossary('My Glossary', glossaryDicts); const glossaryInfo = await deeplClient.getMultilingualGlossary(createdGlossary); // MultilingualGlossaryInfo object ``` -------------------------------- ### Manage Custom Instructions for Style Rules Source: https://github.com/deeplcom/deepl-node/blob/main/README.md Manage custom instructions using `createStyleRuleCustomInstruction()`, `getStyleRuleCustomInstruction()`, `updateStyleRuleCustomInstruction()`, and `deleteStyleRuleCustomInstruction()`. ```javascript // Create a custom instruction const instruction = await deeplClient.createStyleRuleCustomInstruction( 'YOUR_STYLE_ID', 'Formal tone', 'Always use formal language'); console.log(`Created instruction: ${instruction.id}`); ``` ```javascript // Get a custom instruction const fetched = await deeplClient.getStyleRuleCustomInstruction( 'YOUR_STYLE_ID', instruction.id); ``` ```javascript // Update a custom instruction const updated = await deeplClient.updateStyleRuleCustomInstruction( 'YOUR_STYLE_ID', instruction.id, 'Updated label', 'Use very formal language'); ``` ```javascript // Delete a custom instruction await deeplClient.deleteStyleRuleCustomInstruction( 'YOUR_STYLE_ID', instruction.id); ``` -------------------------------- ### Usage Interface Source: https://github.com/deeplcom/deepl-node/blob/main/_autodocs/types.md Provides information about API usage, including character, document, and team document usage. Includes methods to check if any limit is reached and to get a string representation of the usage. ```typescript interface Usage { readonly character?: UsageDetail; readonly document?: UsageDetail; readonly teamDocument?: UsageDetail; anyLimitReached(): boolean; toString(): string; } ``` -------------------------------- ### Get Document Translation Status Source: https://github.com/deeplcom/deepl-node/blob/main/_autodocs/api-reference/translator.md Queries the current translation status of a document using a DocumentHandle obtained from uploadDocument(). Allows checking if translation is done, still in progress, or if an error occurred. ```javascript const status = await translator.getDocumentStatus(handle); if (status.done()) { console.log(`Translation complete: ${status.billedCharacters} chars`); } else if (status.ok()) { console.log(`Still translating... ${status.secondsRemaining}s remaining`); } else { console.log(`Error: ${status.errorMessage}`); } ``` -------------------------------- ### Initialize DeepLClient with Options Source: https://github.com/deeplcom/deepl-node/blob/main/_autodocs/configuration.md Instantiate the DeepLClient class, which extends Translator, using an authentication key and a configuration object. It shares the same configuration options as the Translator class. ```typescript const client = new deepl.DeepLClient(authKey, options); ``` -------------------------------- ### Development DeepL Client Configuration with Logging Source: https://github.com/deeplcom/deepl-node/blob/main/_autodocs/configuration.md Configuration for a development environment that enables debug logging for the 'deepl' library using 'loglevel'. Includes specific retry, timeout, and application info. ```javascript import log from 'loglevel'; import * as deepl from 'deepl-node'; // Enable debug logging log.getLogger('deepl').setLevel('debug'); const client = new deepl.DeepLClient(process.env.DEEPL_AUTH_KEY, { maxRetries: 3, minTimeout: 5000, appInfo: { appName: 'DevApp', appVersion: '0.0.1' } }); ``` -------------------------------- ### Get Account Usage Source: https://github.com/deeplcom/deepl-node/blob/main/_autodocs/api-reference/translator.md Queries the current billing period's account usage, including character and document counts, and checks if any limits have been reached. Provides a human-readable string representation of the usage. ```typescript async getUsage(): Promise ``` ```javascript const usage = await translator.getUsage(); if (usage.anyLimitReached()) { console.log('Quota exceeded!'); } if (usage.character) { console.log(`${usage.character.count}/${usage.character.limit} characters`); } console.log(usage.toString()); // Human-readable output ``` -------------------------------- ### Production DeepL Client Configuration Source: https://github.com/deeplcom/deepl-node/blob/main/_autodocs/configuration.md Configuration for a production environment, including authentication key from environment variables and specific retry and timeout settings. Includes application information for identification. ```javascript const client = new deepl.DeepLClient(process.env.DEEPL_AUTH_KEY, { maxRetries: 5, minTimeout: 10000, appInfo: { appName: 'ProductionApp', appVersion: '2.0.0' } }); ``` -------------------------------- ### Proxy Configuration Source: https://github.com/deeplcom/deepl-node/blob/main/README.md Configures an HTTP proxy for client requests. ```APIDOC ## Proxy Configuration ### Description Configures an HTTP proxy for client requests by specifying the `proxy` argument when constructing the `DeepLClient`. ### Method Signature `new DeepLClient(authKey: string, options?: DeepLClientOptions)` ### `DeepLClientOptions` Properties #### `proxy` - **Type**: `object` - **Properties**: - `host` (`string`): The proxy host. - `port` (`number`): The proxy port. - **Description**: Configuration for the HTTP proxy. ### Example Usage ```javascript const options = {proxy: {host: 'localhost', port: 3000}}; const deepl = new deepl.DeepLClient('YOUR_AUTH_KEY', options); ``` ``` -------------------------------- ### Translate Document with Options Source: https://github.com/deeplcom/deepl-node/blob/main/_autodocs/README.md Translate a document from one language to another, specifying input and output file paths. Optional parameters include formality and custom glossaries. Ensure the 'deepl-node' library is installed. ```javascript const status = await client.translateDocument( 'input.docx', // Input file path 'output_de.docx', // Output file path 'en', // Source language 'de', // Target language { formality: 'more', // Optional: formal German glossary: glossaryId // Optional: custom terms } ); console.log(`Translated: ${status.billedCharacters} characters`); ``` -------------------------------- ### Get Glossary Entries (Monolingual and Multilingual) Source: https://github.com/deeplcom/deepl-node/blob/main/upgrading_to_multilingual_glossaries.md Fetch glossary entries using `getGlossaryEntries` for monolingual glossaries and `getMultilingualGlossaryDictionaryEntries` for multilingual ones. The latter requires specifying the source and target language codes for the desired dictionary. ```javascript // monolingual glossary example const createdGlossary = await deeplClient.createGlossary('My Glossary', 'en', 'de', new deepl.GlossaryEntries({ entries: { Hello: 'Hallo' } })); const entries = await deeplClient.getGlossaryEntries(createdGlossary); console.log(entries.toTsv()); // 'hello hallo' ``` ```javascript // multilingual glossary example const glossaryDicts = [{sourceLangCode: 'en', targetLangCode: 'de', entries: new deepl.GlossaryEntries({ entries: { Hello: 'Hallo' } })}]; const createdGlossary = await deeplClient.createMultilingualGlossary('My Glossary', glossaryDicts); const entriesObj = await deeplClient.getMultilingualGlossaryDictionaryEntries(createdGlossary, 'en', 'de'); console.log(entriesObj.entries.toTsv()); // 'hello hallo' ``` -------------------------------- ### getAllStyleRules Source: https://github.com/deeplcom/deepl-node/blob/main/_autodocs/api-reference/deepl-client.md Lists all available style rules, with options for pagination and detailed information. ```APIDOC ## getAllStyleRules() ### Description Lists all style rules with optional pagination and detailed information. ### Method Signature ```typescript async getAllStyleRules( page?: number, pageSize?: number, detailed?: boolean ): Promise ``` ### Parameters #### Query Parameters - **page** (number) - Optional - Page number for pagination (0-indexed) - **pageSize** (number) - Optional - Items per page - **detailed** (boolean) - Optional - Include detailed rules and instructions in response ### Return Type Array of `StyleRuleInfo` objects. ### Example ```javascript const rules = await client.getAllStyleRules(0, 10, true); rules.forEach(rule => { console.log(`${rule.name} (${rule.styleId})`); if (rule.configuredRules?.styleAndTone) { console.log(' Style & Tone:', rule.configuredRules.styleAndTone); } }); ``` ``` -------------------------------- ### Translate Multiple Texts with Auto-Detection Source: https://github.com/deeplcom/deepl-node/blob/main/README.md Translates an array of text strings into a specified target language, automatically detecting the source language for each. This example shows how to process multiple translations and access details like detected source language and character counts. ```javascript // Translate multiple texts into British English: const translations = await deeplClient.translateText( ['お元気ですか?', '¿Cómo estás?'], null, 'en-GB', ); console.log(translations[0].text); // 'How are you?' console.log(translations[0].detectedSourceLang); // 'ja' console.log(translations[0].billedCharacters); // 7 - the number of characters in the source text "お元気ですか?" console.log(translations[1].text); // 'How are you?' console.log(translations[1].detectedSourceLang); // 'es' console.log(translations[1].billedCharacters); // 12 - the number of characters in the source text "¿Cómo estás?" ``` -------------------------------- ### Initialize GlossaryEntries Source: https://github.com/deeplcom/deepl-node/blob/main/_autodocs/api-reference/glossary-entries.md Construct a GlossaryEntries object using either a dictionary of term pairs or a TSV string. If neither is provided, an empty object is created. Ensure only one initialization option is used. ```javascript import * as deepl from 'deepl-node'; // From dictionary object const entries1 = new deepl.GlossaryEntries({ entries: { 'hello': 'hallo', 'goodbye': 'auf wiedersehen' } }); // From TSV string const tsvContent = 'hello\thallo\ngoodbye\tauf wiedersehen'; const entries2 = new deepl.GlossaryEntries({ tsv: tsvContent }); // Empty entries const entries3 = new deepl.GlossaryEntries(); ``` -------------------------------- ### Work with TSV Glossary Format Source: https://github.com/deeplcom/deepl-node/blob/main/_autodocs/api-reference/glossary-entries.md Demonstrates reading a glossary from a TSV file, adding new entries, and exporting the updated glossary back to TSV format using `fs/promises`. ```javascript import * as deepl from 'deepl-node'; import * as fs from 'fs/promises'; // Read TSV file const tsvContent = await fs.readFile('glossary.tsv', 'utf-8'); const entries = new deepl.GlossaryEntries({ tsv: tsvContent }); // Modify and export entries.add('new_term', 'nueva_traducción'); const updatedTsv = entries.toTsv(); await fs.writeFile('glossary_updated.tsv', updatedTsv); ``` -------------------------------- ### Retrieve and List Style Rules Source: https://github.com/deeplcom/deepl-node/blob/main/README.md Use `getStyleRule()` to fetch a single rule by ID or `getAllStyleRules()` to list all rules. The latter accepts pagination parameters and a `detailed` flag to include rule configurations. ```javascript // Get a single style rule by ID const rule = await deeplClient.getStyleRule('YOUR_STYLE_ID'); console.log(`${rule.name} (${rule.language})`); ``` ```javascript // List all style rules const styleRules = await deeplClient.getAllStyleRules(); for (const r of styleRules) { console.log(`${r.name} (${r.styleId})`); } ``` ```javascript // List with detailed configuration const detailed = await deeplClient.getAllStyleRules(undefined, undefined, true); for (const r of detailed) { if (r.configuredRules) { console.log(` Number formatting: ${JSON.stringify(r.configuredRules.numbers)}`); } } ``` -------------------------------- ### Identify Application in User-Agent Header Source: https://github.com/deeplcom/deepl-node/blob/main/_autodocs/configuration.md Provide application name and version to be included in the User-Agent header. Both `appName` and `appVersion` are required. ```javascript const translator = new deepl.Translator(authKey, { appInfo: { appName: 'MyTranslationApp', appVersion: '1.0.0' } }); ``` -------------------------------- ### Basic Text Translation and Usage Check Source: https://github.com/deeplcom/deepl-node/blob/main/_autodocs/README.md Demonstrates basic text translation and checking API usage limits. Ensure your DEEPL_AUTH_KEY environment variable is set. ```javascript import * as deepl from 'deepl-node'; const authKey = process.env.DEEPL_AUTH_KEY; const client = new deepl.DeepLClient(authKey); // Translate text const result = await client.translateText('Hello, world!', 'en', 'de'); console.log(result.text); // 'Hallo, Welt!' // Check usage const usage = await client.getUsage(); console.log(`${usage.character.count}/${usage.character.limit} characters used`); ``` -------------------------------- ### List All Glossaries Source: https://github.com/deeplcom/deepl-node/blob/main/_autodocs/api-reference/translator.md Lists all glossaries associated with the authenticated user account. Returns an array of GlossaryInfo objects. ```typescript async listGlossaries(): Promise ``` -------------------------------- ### Client Configuration Source: https://github.com/deeplcom/deepl-node/blob/main/README.md Configure the DeepL client with options such as application information, retry settings, timeouts, server URLs, custom headers, and proxy settings. ```APIDOC ## Client Configuration ### Description Configure the `DeepLClient` with various options to customize its behavior and integration. ### Constructor `new DeepLClient(authKey: string, options?: DeepLClientOptions)` ### Options (`DeepLClientOptions`) - `appInfo` (object): Information about the application using the client. - `appName` (string): The name of the application. Required. - `appVersion` (string): The version of the application. Required. - `maxRetries` (number): The maximum number of HTTP request retries. Default: 5. - `minTimeout` (number): The connection timeout in milliseconds for each HTTP request retry. Default: 10000. - `serverUrl` (string): The URL of the DeepL API. Defaults to the appropriate URL based on account type. - `headers` (object): Extra HTTP headers to include in requests. Note: Authorization and User-Agent headers are added automatically and can be overridden. - `proxy` (object): Proxy server configuration. - `hostname` (string): The proxy server hostname. - `port` (number): The proxy server port. - `protocol` (string, optional): The proxy protocol (e.g., 'http', 'https'). - `auth` (object, optional): Proxy authentication credentials. - `username` (string): The proxy username. - `password` (string): The proxy password. ### Examples #### With Application Info ```javascript const options = { appInfo: { appName: 'sampleNodeTranslationApp', appVersion: '1.2.3' } }; const deeplClient = new deepl.DeepLClient('YOUR_AUTH_KEY', options); ``` #### With Retry and Timeout Settings ```javascript const options = { maxRetries: 5, minTimeout: 10000 }; const deeplClient = new deepl.DeepLClient('YOUR_AUTH_KEY', options); ``` ``` -------------------------------- ### Create Glossary with Entries Source: https://github.com/deeplcom/deepl-node/blob/main/_autodocs/api-reference/translator.md Creates a glossary with specified entries. The entries object should map source terms to target terms. ```typescript async createGlossary( name: string, sourceLang: LanguageCode, targetLang: LanguageCode, entries: GlossaryEntries ): Promise ``` -------------------------------- ### Manage Custom Instructions Source: https://github.com/deeplcom/deepl-node/blob/main/README.md Manages custom instructions associated with a style rule, including creation, retrieval, updating, and deletion. ```APIDOC ## Manage Custom Instructions ### Description Manages custom instructions for a style rule. Operations include creating, getting, updating, and deleting custom instructions. ### Method `deeplClient.createStyleRuleCustomInstruction(styleId: string, label: string, text: string): Promise` `deeplClient.getStyleRuleCustomInstruction(styleId: string, instructionId: string): Promise` `deeplClient.updateStyleRuleCustomInstruction(styleId: string, instructionId: string, label?: string, text?: string): Promise` `deeplClient.deleteStyleRuleCustomInstruction(styleId: string, instructionId: string): Promise` ### Parameters - **createStyleRuleCustomInstruction**: - **styleId** (string) - Required - The ID of the style rule. - **label** (string) - Required - The label for the custom instruction. - **text** (string) - Required - The content of the custom instruction. - **getStyleRuleCustomInstruction**: - **styleId** (string) - Required - The ID of the style rule. - **instructionId** (string) - Required - The ID of the custom instruction. - **updateStyleRuleCustomInstruction**: - **styleId** (string) - Required - The ID of the style rule. - **instructionId** (string) - Required - The ID of the custom instruction. - **label** (string) - Optional - The new label for the custom instruction. - **text** (string) - Optional - The new content for the custom instruction. - **deleteStyleRuleCustomInstruction**: - **styleId** (string) - Required - The ID of the style rule. - **instructionId** (string) - Required - The ID of the custom instruction. ### Request Example ```javascript // Create a custom instruction const instruction = await deeplClient.createStyleRuleCustomInstruction( 'YOUR_STYLE_ID', 'Formal tone', 'Always use formal language'); console.log(`Created instruction: ${instruction.id}`); // Get a custom instruction const fetched = await deeplClient.getStyleRuleCustomInstruction( 'YOUR_STYLE_ID', instruction.id); // Update a custom instruction const updated = await deeplClient.updateStyleRuleCustomInstruction( 'YOUR_STYLE_ID', instruction.id, 'Updated label', 'Use very formal language'); // Delete a custom instruction await deeplClient.deleteStyleRuleCustomInstruction( 'YOUR_STYLE_ID', instruction.id); ``` ``` -------------------------------- ### Translate Text with Formality Options Source: https://github.com/deeplcom/deepl-node/blob/main/README.md Demonstrates how to translate text while specifying formality options ('less' or 'more') for languages that support it, such as German. This allows control over the tone of the translation. ```javascript // Translate into German with less and more Formality: console.log(await deeplClient.translateText('How are you?', null, 'de', { formality: 'less' })); // 'Wie geht es dir?' console.log(await deeplClient.translateText('How are you?', null, 'de', { formality: 'more' })); // 'Wie geht es Ihnen?' ``` -------------------------------- ### getStyleRuleCustomInstruction Source: https://github.com/deeplcom/deepl-node/blob/main/_autodocs/api-reference/deepl-client.md Retrieves a specific custom instruction associated with a given style rule. ```APIDOC ## getStyleRuleCustomInstruction ### Description Retrieves a custom instruction for a style rule. ### Method `getStyleRuleCustomInstruction` ### Parameters #### Path Parameters - **styleId** (StyleId) - Yes - ID of the style rule - **instructionId** (string) - Yes - ID of the custom instruction ### Response #### Success Response - **CustomInstruction** — The custom instruction. ### Throws - `ArgumentError` if parameters invalid - `DeepLError` on API errors ``` -------------------------------- ### Create Style Rule Custom Instruction Source: https://github.com/deeplcom/deepl-node/blob/main/_autodocs/api-reference/deepl-client.md Use this method to create a new custom instruction for a specific style rule. Requires the style rule ID and an instruction object containing a label and prompt. ```javascript const instruction = await client.createStyleRuleCustomInstruction( 'style_rule_id', { label: 'Technical Terms', prompt: 'Always preserve technical terminology' } ); ``` -------------------------------- ### Translate Text and List Glossaries with DeepL Node.js Source: https://github.com/deeplcom/deepl-node/blob/main/_autodocs/README.md Demonstrates how to use the DeepLClient to translate text and retrieve a list of multilingual glossaries. Ensure your DEEPL_AUTH_KEY environment variable is set. ```typescript import * as deepl from 'deepl-node'; const client = new deepl.DeepLClient(process.env.DEEPL_AUTH_KEY!); const result: deepl.TextResult = await client.translateText( 'Hello', 'en' as deepl.SourceLanguageCode, 'de' as deepl.TargetLanguageCode, { formality: 'more' as deepl.Formality } ); const glossaries: deepl.MultilingualGlossaryInfo[] = await client.listMultilingualGlossaries(); ``` -------------------------------- ### Instantiate DeepLClient Source: https://github.com/deeplcom/deepl-node/blob/main/_autodocs/api-reference/deepl-client.md Constructs a DeepLClient instance with an authentication key and optional configuration options like maxRetries and serverUrl. ```javascript import * as deepl from 'deepl-node'; const authKey = 'your-auth-key'; const client = new deepl.DeepLClient(authKey, { maxRetries: 5, serverUrl: 'https://api.deepl.com' }); ``` -------------------------------- ### Control Platform Info in User-Agent Header Source: https://github.com/deeplcom/deepl-node/blob/main/_autodocs/configuration.md Determine whether to include platform and Node.js version information in the User-Agent header. Defaults to true. ```javascript // Default: true (sends platform info) const translator = new deepl.Translator(authKey); ``` ```javascript // Disable to reduce User-Agent verbosity const translator = new deepl.Translator(authKey, { sendPlatformInfo: false }); ```