@cutticat/libretranslate 1.1.0 → 2.0.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.
- package/README.md +166 -58
- package/dist/index.d.ts +298 -101
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +319 -102
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -1,99 +1,207 @@
|
|
|
1
1
|
# @cutticat/libretranslate
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
3
|
+
Typed client for the [LibreTranslate](https://libretranslate.com) API: translation of one text or
|
|
4
|
+
a batch, language detection, and the list of supported language pairs.
|
|
5
|
+
|
|
6
|
+
A bare `fetch` to LibreTranslate leaves a few traps. A rejected request resolves normally, with
|
|
7
|
+
`{ "error": "es is not supported" }` in the body and the status on the side. A batch answers with
|
|
8
|
+
parallel arrays that have to be zipped back by index. The detected language comes as
|
|
9
|
+
`{ "language": "ru", "confidence": 90 }`, where confidence is a percentage. This package turns
|
|
10
|
+
error statuses into `LibreTranslateError` with the server message, zips batches into one object
|
|
11
|
+
per text, and checks every response body against the shape the server documents.
|
|
12
|
+
|
|
13
|
+
## Contents
|
|
14
|
+
|
|
15
|
+
- [Install](#install)
|
|
16
|
+
- [Usage](#usage)
|
|
17
|
+
- [Errors](#errors)
|
|
18
|
+
- [Cancellation](#cancellation)
|
|
10
19
|
- [API](#api)
|
|
20
|
+
- [Migrating from 1.x](#migrating-from-1x)
|
|
11
21
|
- [Documentation](#documentation)
|
|
12
22
|
- [Requirements](#requirements)
|
|
13
23
|
|
|
14
|
-
##
|
|
15
|
-
|
|
16
|
-
The library provides the `translate` function for translating text via the LibreTranslate API.
|
|
17
|
-
Supports language auto-detection, alternative translations, custom baseUrl and API key. Uses Zod for
|
|
18
|
-
response validation and types from `@cutticat/types`.
|
|
19
|
-
|
|
20
|
-
## Installation
|
|
24
|
+
## Install
|
|
21
25
|
|
|
22
26
|
```bash
|
|
23
|
-
pnpm
|
|
27
|
+
pnpm add @cutticat/libretranslate
|
|
24
28
|
```
|
|
25
29
|
|
|
26
|
-
##
|
|
30
|
+
## Usage
|
|
31
|
+
|
|
32
|
+
| Task | Call |
|
|
33
|
+
| --- | --- |
|
|
34
|
+
| Translate one text | `client.translate(text, { target })` |
|
|
35
|
+
| Translate several texts in one request | `client.translateBatch(texts, { target })` |
|
|
36
|
+
| Detect the language of a text | `client.detectLanguage(text)` |
|
|
37
|
+
| Check which pairs the server supports | `client.getLanguages()` |
|
|
27
38
|
|
|
28
39
|
```typescript
|
|
29
|
-
import {
|
|
40
|
+
import { LibreTranslateClient } from "@cutticat/libretranslate"
|
|
30
41
|
|
|
31
|
-
const
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
target: "ru",
|
|
42
|
+
const client = new LibreTranslateClient({
|
|
43
|
+
baseUrl: "https://libretranslate.com",
|
|
44
|
+
apiKey: process.env.LIBRETRANSLATE_API_KEY,
|
|
35
45
|
})
|
|
36
|
-
|
|
46
|
+
|
|
47
|
+
const { text } = await client.translate("Hello, world!", { source: "en", target: "ru" })
|
|
48
|
+
// "Привет, мир!"
|
|
37
49
|
```
|
|
38
50
|
|
|
39
|
-
|
|
51
|
+
`baseUrl` has no default: the public instance at libretranslate.com needs an API key, and most
|
|
52
|
+
setups run their own server. A path in `baseUrl` is kept, so
|
|
53
|
+
`https://example.com/libretranslate` sends requests to `https://example.com/libretranslate/translate`.
|
|
54
|
+
|
|
55
|
+
`source` defaults to `"auto"`. The server then detects the language and reports it:
|
|
40
56
|
|
|
41
57
|
```typescript
|
|
42
|
-
const
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
target: "en",
|
|
46
|
-
})
|
|
47
|
-
console.log(result.translatedText) // "Hello"
|
|
48
|
-
console.log(result.detectedLanguage) // { code: "fr", confidence: 0.95 }
|
|
58
|
+
const { text, detectedLanguage } = await client.translate("Привет, мир!", { target: "en" })
|
|
59
|
+
// text: "Hello, world!"
|
|
60
|
+
// detectedLanguage: { language: "ru", confidence: 90 }
|
|
49
61
|
```
|
|
50
62
|
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
63
|
+
`detectedLanguage` is `undefined` when `source` was given. `confidence` goes from 0 to 100.
|
|
64
|
+
|
|
65
|
+
A batch is one request, and the result keeps the order of the input:
|
|
54
66
|
|
|
55
67
|
```typescript
|
|
56
|
-
const
|
|
57
|
-
|
|
58
|
-
source: "en",
|
|
59
|
-
target: "ru",
|
|
60
|
-
signal: AbortSignal.any([request.signal, AbortSignal.timeout(10_000)]),
|
|
61
|
-
})
|
|
68
|
+
const translations = await client.translateBatch(["Hello", "Goodbye"], { target: "ru" })
|
|
69
|
+
translations.map(translation => translation.text) // ["Привет", "До свидания"]
|
|
62
70
|
```
|
|
63
71
|
|
|
64
|
-
|
|
72
|
+
With `source: "auto"` the server detects one language for the whole batch, so every item gets the
|
|
73
|
+
same `detectedLanguage`. Texts in different languages need separate calls. An empty array resolves
|
|
74
|
+
to `[]` without a request.
|
|
65
75
|
|
|
66
|
-
|
|
76
|
+
`format: "html"` translates the text inside markup and keeps the tags. `alternatives: n` asks for
|
|
77
|
+
up to `n` more translations per text. The server may return fewer, or none, and never returns them
|
|
78
|
+
for HTML:
|
|
67
79
|
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
80
|
+
```typescript
|
|
81
|
+
const { text, alternatives } = await client.translate("Goodbye", { target: "ru", alternatives: 2 })
|
|
82
|
+
// text: "До свидания"
|
|
83
|
+
// alternatives: ["Прощай"]
|
|
84
|
+
```
|
|
71
85
|
|
|
72
|
-
|
|
86
|
+
Language codes go to the server as given. `getLanguages()` lists what a particular server accepts:
|
|
73
87
|
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
- `DetectedLanguage` — detected language info (`code`, `confidence`)
|
|
88
|
+
```typescript
|
|
89
|
+
const languages = await client.getLanguages()
|
|
90
|
+
const supported = languages.some(({ code, targets }) => code === "en" && targets.includes("ru"))
|
|
91
|
+
```
|
|
79
92
|
|
|
80
|
-
|
|
93
|
+
`detectLanguage` returns candidates, most confident first. When nothing is detected the server
|
|
94
|
+
answers with a single `{ language: "en", confidence: 0 }`:
|
|
81
95
|
|
|
82
|
-
|
|
96
|
+
```typescript
|
|
97
|
+
const [best] = await client.detectLanguage("Доброе утро, как дела?")
|
|
98
|
+
// { language: "ru", confidence: 43 }
|
|
99
|
+
```
|
|
83
100
|
|
|
84
|
-
|
|
101
|
+
The package covers `/translate`, `/detect` and `/languages`. File translation (`/translate_file`),
|
|
102
|
+
suggestions (`/suggest`) and the frontend settings (`/frontend/settings`) are not wrapped.
|
|
103
|
+
|
|
104
|
+
## Errors
|
|
85
105
|
|
|
86
|
-
|
|
106
|
+
| Thrown | When |
|
|
107
|
+
| --- | --- |
|
|
108
|
+
| `TypeError` | `baseUrl` is not an absolute URL (constructor) |
|
|
109
|
+
| `RangeError` | `alternatives` is not a non-negative integer; nothing is sent |
|
|
110
|
+
| `LibreTranslateError` | the server answers with an error status or a body of the wrong shape |
|
|
111
|
+
| `signal.reason` | the signal aborts, see [Cancellation](#cancellation) |
|
|
112
|
+
| the error of `fetch` | network failure, such as `TypeError: fetch failed` |
|
|
113
|
+
|
|
114
|
+
`LibreTranslateError` carries `endpoint`, `status` and `serverMessage`, the text of the `error`
|
|
115
|
+
field the server sent:
|
|
116
|
+
|
|
117
|
+
```typescript
|
|
118
|
+
import { LibreTranslateError } from "@cutticat/libretranslate"
|
|
119
|
+
|
|
120
|
+
try {
|
|
121
|
+
await client.translate(text, { target: "xx" })
|
|
122
|
+
} catch (error) {
|
|
123
|
+
if (!(error instanceof LibreTranslateError) || error.status !== 429) throw error
|
|
124
|
+
// rate limited: retry later
|
|
125
|
+
}
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
Statuses the server uses:
|
|
129
|
+
|
|
130
|
+
- `400` — missing or unsupported language, unsupported pair, missing API key on a server that
|
|
131
|
+
requires one, and a text, batch or `alternatives` over a limit the server sets (limits are off
|
|
132
|
+
by default)
|
|
133
|
+
- `403` — invalid API key, or a client banned for repeated limit violations
|
|
134
|
+
- `429` — rate limit
|
|
135
|
+
- `500` — translation failed on the server
|
|
136
|
+
|
|
137
|
+
A `2xx` status on `LibreTranslateError` means the body was not JSON or did not match the
|
|
138
|
+
documented shape; `cause` holds the parse or validation error.
|
|
139
|
+
|
|
140
|
+
## Cancellation
|
|
141
|
+
|
|
142
|
+
Every method takes `signal`. Once it aborts, the call rejects with `signal.reason`; a signal that
|
|
143
|
+
is already aborted rejects before any request. For a timeout pass `AbortSignal.timeout(ms)`, and
|
|
144
|
+
combine it with your own signal through `AbortSignal.any`:
|
|
145
|
+
|
|
146
|
+
```typescript
|
|
147
|
+
const translation = await client.translate("Hello", {
|
|
148
|
+
target: "ru",
|
|
149
|
+
signal: AbortSignal.any([request.signal, AbortSignal.timeout(10_000)]),
|
|
150
|
+
})
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
## API
|
|
154
|
+
|
|
155
|
+
- `LibreTranslateClient` — client for one server
|
|
156
|
+
- `new LibreTranslateClient({ baseUrl, apiKey?, fetch? })`
|
|
157
|
+
- `translate(text, options)` → `Promise<Translation>`
|
|
158
|
+
- `translateBatch(texts, options)` → `Promise<Translation[]>`
|
|
159
|
+
- `detectLanguage(text, { signal? })` → `Promise<LanguageDetection[]>`
|
|
160
|
+
- `getLanguages({ signal? })` → `Promise<Language[]>`
|
|
161
|
+
- `TranslateOptions` — `target`, `source?`, `format?`, `alternatives?`, `signal?`
|
|
162
|
+
- `Translation` — `text`, `alternatives`, `detectedLanguage`
|
|
163
|
+
- `LanguageDetection` — `language`, `confidence`
|
|
164
|
+
- `Language` — `code`, `name`, `targets`
|
|
165
|
+
- `TranslationFormat` — `"text"` | `"html"`
|
|
166
|
+
- `LibreTranslateError` — `endpoint`, `status`, `serverMessage`, `cause`; factories `default`,
|
|
167
|
+
`fromResponse`, `unexpectedBody`
|
|
168
|
+
- Wire schemas with inferred types, useful for a proxy or a mock server that has to speak the same
|
|
169
|
+
format:
|
|
170
|
+
- requests: `TranslateRequestSchema`, `DetectRequestSchema`
|
|
171
|
+
- responses: `TranslateResponseSchema`, `TranslateBatchResponseSchema`, `DetectResponseSchema`,
|
|
172
|
+
`LanguagesResponseSchema`, `ErrorResponseSchema`
|
|
173
|
+
- common: `LanguageDetectionSchema`, `LanguageSchema`, `TranslationFormatSchema`
|
|
174
|
+
|
|
175
|
+
JSDoc on every export has the full contract.
|
|
176
|
+
|
|
177
|
+
## Migrating from 1.x
|
|
178
|
+
|
|
179
|
+
2.0 replaces the `translate` function with a client and fixes responses with `source: "auto"`,
|
|
180
|
+
which 1.x rejected because it expected `detectedLanguage.code`.
|
|
181
|
+
|
|
182
|
+
| 1.x | 2.0 |
|
|
183
|
+
| --- | --- |
|
|
184
|
+
| `translate({ text, source, target, baseUrl, apiKey, fetch })` | `new LibreTranslateClient({ baseUrl, apiKey, fetch }).translate(text, { source, target })` |
|
|
185
|
+
| `baseUrl` defaults to `defaultBaseUrl` | `baseUrl` is required; `defaultBaseUrl` is gone |
|
|
186
|
+
| `source` is required | `source` defaults to `"auto"` |
|
|
187
|
+
| result `translatedText` | result `text` |
|
|
188
|
+
| result `alternatives` may be missing | result `alternatives` is always an array |
|
|
189
|
+
| `detectedLanguage.code` | `detectedLanguage.language`, `confidence` from 0 to 100 |
|
|
190
|
+
| `Error` with the status in the message | `LibreTranslateError` with `status` and `serverMessage` |
|
|
191
|
+
| `Error` for bad `alternatives` | `RangeError` |
|
|
192
|
+
| `TranslationOptions`, `DetectedLanguage`, `DetectedLanguageSchema` | `TranslateOptions`, `LanguageDetection`, `LanguageDetectionSchema` |
|
|
193
|
+
| `TranslateResponse` returned by `translate` | `Translation`; `TranslateResponse` is the wire type now |
|
|
194
|
+
| a path in `baseUrl` is dropped | a path in `baseUrl` is kept |
|
|
195
|
+
| one text per request | `translateBatch` sends many in one request |
|
|
196
|
+
|
|
197
|
+
## Documentation
|
|
87
198
|
|
|
88
199
|
- [Project structure](<https://gitflic.ru/project/cutticat-npm/libretranslate/blob?branch=main&file=documents/STRUCTURE.md>)
|
|
89
200
|
- [Scripts](<https://gitflic.ru/project/cutticat-npm/libretranslate/blob?branch=main&file=documents/SCRIPTS.md>)
|
|
90
201
|
- [Style guide](<https://gitflic.ru/project/cutticat-npm/libretranslate/blob?branch=main&file=documents/STYLE_GUIDE.md>)
|
|
91
202
|
- [Contributing](<https://gitflic.ru/project/cutticat-npm/libretranslate/blob?branch=main&file=documents/CONTRIBUTING.md>)
|
|
92
203
|
|
|
93
|
-
Full API documentation is available in JSDoc comments. Use IDE autocomplete to browse it.
|
|
94
|
-
|
|
95
204
|
## Requirements
|
|
96
205
|
|
|
97
206
|
- Node.js >= 24.14.0
|
|
98
|
-
-
|
|
99
|
-
- TypeScript >= 5.9.0
|
|
207
|
+
- ESM only
|
package/dist/index.d.ts
CHANGED
|
@@ -1,129 +1,326 @@
|
|
|
1
|
+
/** @cutticat/libretranslate — client for the LibreTranslate API. @packageDocumentation */
|
|
1
2
|
import { z } from "zod";
|
|
2
|
-
import {
|
|
3
|
-
/**
|
|
4
|
-
|
|
3
|
+
import { FullyUndefinable } from "@cutticat/types";
|
|
4
|
+
/**
|
|
5
|
+
* One guess of the language a text is written in, as `/translate` and `/detect` return it.
|
|
6
|
+
* `confidence` goes from `0` to `100`.
|
|
7
|
+
*/
|
|
8
|
+
export declare const LanguageDetectionSchema: z.ZodObject<{
|
|
9
|
+
language: z.ZodString;
|
|
10
|
+
confidence: z.ZodNumber;
|
|
11
|
+
}, z.core.$strip>;
|
|
12
|
+
/** Type inferred from {@link LanguageDetectionSchema}. */
|
|
13
|
+
export type LanguageDetection = z.infer<typeof LanguageDetectionSchema>;
|
|
14
|
+
/** Endpoint the client calls, relative to the base URL. */
|
|
15
|
+
export type LibreTranslateEndpoint = "/translate" | "/detect" | "/languages";
|
|
16
|
+
/** Translation of one text. */
|
|
17
|
+
export type Translation = {
|
|
18
|
+
/** Translated text. */
|
|
19
|
+
text: string;
|
|
20
|
+
/**
|
|
21
|
+
* Other translations, best first, without {@link Translation.text}. Empty unless
|
|
22
|
+
* `alternatives` was requested; the server never returns them for HTML.
|
|
23
|
+
*/
|
|
24
|
+
alternatives: string[];
|
|
25
|
+
/**
|
|
26
|
+
* Source language the server picked when `source` was `"auto"`; `undefined` when the
|
|
27
|
+
* source language was given. In a batch the server detects one language for the whole batch.
|
|
28
|
+
*/
|
|
29
|
+
detectedLanguage: LanguageDetection | undefined;
|
|
30
|
+
};
|
|
31
|
+
/** Options for {@link LibreTranslateError}. */
|
|
32
|
+
export type LibreTranslateErrorOptions = ErrorOptions & FullyUndefinable<{
|
|
33
|
+
/** Endpoint that answered, such as `/translate`. */
|
|
34
|
+
endpoint: LibreTranslateEndpoint;
|
|
35
|
+
/**
|
|
36
|
+
* HTTP status of the response: `400` for bad input, a limit the server enforces or a missing
|
|
37
|
+
* API key the server requires, `403` for an invalid API key or a banned client, `429` for a
|
|
38
|
+
* rate limit, `5xx` for server failures. A `2xx` status means the body did not parse or
|
|
39
|
+
* validate. `undefined` when a batch answer has the wrong number of items.
|
|
40
|
+
*/
|
|
41
|
+
status: number;
|
|
42
|
+
/** Message from the `error` field of the response body, such as `es is not supported`. */
|
|
43
|
+
serverMessage: string;
|
|
44
|
+
}>;
|
|
45
|
+
/**
|
|
46
|
+
* Thrown when the LibreTranslate server rejects a request or answers with a body this package
|
|
47
|
+
* cannot read.
|
|
48
|
+
*
|
|
49
|
+
* {@link LibreTranslateError.status} and {@link LibreTranslateError.serverMessage} let a caller
|
|
50
|
+
* tell a rate limit from a bad language code without parsing the message. A body that failed to
|
|
51
|
+
* parse or validate keeps that error as `cause`.
|
|
52
|
+
*/
|
|
53
|
+
export declare class LibreTranslateError extends Error {
|
|
54
|
+
/**
|
|
55
|
+
* @param options - Optional endpoint, status, server message and {@link ErrorOptions}.
|
|
56
|
+
* @returns Error with the message `LibreTranslate request failed`.
|
|
57
|
+
*/
|
|
58
|
+
static default(options?: Readonly<LibreTranslateErrorOptions>): LibreTranslateError;
|
|
59
|
+
/**
|
|
60
|
+
* Builds an error for a response with an error status.
|
|
61
|
+
*
|
|
62
|
+
* @param options - Endpoint, status, the server message when the body has one, and
|
|
63
|
+
* {@link ErrorOptions}.
|
|
64
|
+
* @returns Error such as `LibreTranslate /translate failed with HTTP 400: es is not supported`.
|
|
65
|
+
*/
|
|
66
|
+
static fromResponse(options: Readonly<LibreTranslateErrorOptions> & {
|
|
67
|
+
endpoint: LibreTranslateEndpoint;
|
|
68
|
+
status: number;
|
|
69
|
+
}): LibreTranslateError;
|
|
70
|
+
/**
|
|
71
|
+
* Builds an error for a successful response whose body is not JSON or does not have the
|
|
72
|
+
* documented shape. Pass the parse or validation error as `cause`.
|
|
73
|
+
*
|
|
74
|
+
* @param options - Endpoint, status and {@link ErrorOptions}.
|
|
75
|
+
* @returns Error such as `LibreTranslate /translate returned an unexpected body`.
|
|
76
|
+
*/
|
|
77
|
+
static unexpectedBody(options: Readonly<LibreTranslateErrorOptions> & {
|
|
78
|
+
endpoint: LibreTranslateEndpoint;
|
|
79
|
+
}): LibreTranslateError;
|
|
80
|
+
name: string;
|
|
81
|
+
/** Endpoint that answered, such as `/translate`. */
|
|
82
|
+
readonly endpoint: LibreTranslateEndpoint | undefined;
|
|
83
|
+
/** HTTP status of the response; see {@link LibreTranslateErrorOptions.status}. */
|
|
84
|
+
readonly status: number | undefined;
|
|
85
|
+
/** Message from the `error` field of the response body. */
|
|
86
|
+
readonly serverMessage: string | undefined;
|
|
87
|
+
/**
|
|
88
|
+
* @param message - Human-readable error message.
|
|
89
|
+
* @param options - Optional endpoint, status, server message and {@link ErrorOptions}.
|
|
90
|
+
*/
|
|
91
|
+
constructor(message: string, { endpoint, status, serverMessage, ...errorOptions }?: Readonly<LibreTranslateErrorOptions>);
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Language the server translates from, as one item of the `/languages` response: its code, its
|
|
95
|
+
* English name, and the codes of the languages it translates into.
|
|
96
|
+
*/
|
|
97
|
+
export declare const LanguageSchema: z.ZodObject<{
|
|
5
98
|
code: z.ZodString;
|
|
99
|
+
name: z.ZodString;
|
|
100
|
+
targets: z.ZodArray<z.ZodString>;
|
|
101
|
+
}, z.core.$strip>;
|
|
102
|
+
/** Type inferred from {@link LanguageSchema}. */
|
|
103
|
+
export type Language = z.infer<typeof LanguageSchema>;
|
|
104
|
+
/** Text format: `"text"` for plain text, `"html"` to keep markup and translate only its text. */
|
|
105
|
+
export declare const TranslationFormatSchema: z.ZodEnum<{
|
|
106
|
+
html: "html";
|
|
107
|
+
text: "text";
|
|
108
|
+
}>;
|
|
109
|
+
/** Type inferred from {@link TranslationFormatSchema}. */
|
|
110
|
+
export type TranslationFormat = z.infer<typeof TranslationFormatSchema>;
|
|
111
|
+
/** `/detect` request body. */
|
|
112
|
+
export declare const DetectRequestSchema: z.ZodObject<{
|
|
113
|
+
q: z.ZodString;
|
|
114
|
+
api_key: z.ZodOptional<z.ZodString>;
|
|
115
|
+
}, z.core.$strip>;
|
|
116
|
+
/** Type inferred from {@link DetectRequestSchema}. */
|
|
117
|
+
export type DetectRequest = z.infer<typeof DetectRequestSchema>;
|
|
118
|
+
/**
|
|
119
|
+
* `/translate` request body. `q` is one text or an array of texts; `source` is a language code
|
|
120
|
+
* or `"auto"`. The server treats a missing `format` as `"text"` and a missing `alternatives` as
|
|
121
|
+
* `0`.
|
|
122
|
+
*/
|
|
123
|
+
export declare const TranslateRequestSchema: z.ZodObject<{
|
|
124
|
+
q: z.ZodUnion<readonly [z.ZodString, z.ZodArray<z.ZodString>]>;
|
|
125
|
+
source: z.ZodString;
|
|
126
|
+
target: z.ZodString;
|
|
127
|
+
format: z.ZodOptional<z.ZodEnum<{
|
|
128
|
+
html: "html";
|
|
129
|
+
text: "text";
|
|
130
|
+
}>>;
|
|
131
|
+
alternatives: z.ZodOptional<z.ZodNumber>;
|
|
132
|
+
api_key: z.ZodOptional<z.ZodString>;
|
|
133
|
+
}, z.core.$strip>;
|
|
134
|
+
/** Type inferred from {@link TranslateRequestSchema}. */
|
|
135
|
+
export type TranslateRequest = z.infer<typeof TranslateRequestSchema>;
|
|
136
|
+
/** `/detect` response: candidate languages, most confident first. */
|
|
137
|
+
export declare const DetectResponseSchema: z.ZodArray<z.ZodObject<{
|
|
138
|
+
language: z.ZodString;
|
|
6
139
|
confidence: z.ZodNumber;
|
|
140
|
+
}, z.core.$strip>>;
|
|
141
|
+
/** Type inferred from {@link DetectResponseSchema}. */
|
|
142
|
+
export type DetectResponse = z.infer<typeof DetectResponseSchema>;
|
|
143
|
+
/** Body the server sends with an error status. */
|
|
144
|
+
export declare const ErrorResponseSchema: z.ZodObject<{
|
|
145
|
+
error: z.ZodString;
|
|
146
|
+
}, z.core.$strip>;
|
|
147
|
+
/** Type inferred from {@link ErrorResponseSchema}. */
|
|
148
|
+
export type ErrorResponse = z.infer<typeof ErrorResponseSchema>;
|
|
149
|
+
/** `/languages` response: every language the server translates from. */
|
|
150
|
+
export declare const LanguagesResponseSchema: z.ZodArray<z.ZodObject<{
|
|
151
|
+
code: z.ZodString;
|
|
152
|
+
name: z.ZodString;
|
|
153
|
+
targets: z.ZodArray<z.ZodString>;
|
|
154
|
+
}, z.core.$strip>>;
|
|
155
|
+
/** Type inferred from {@link LanguagesResponseSchema}. */
|
|
156
|
+
export type LanguagesResponse = z.infer<typeof LanguagesResponseSchema>;
|
|
157
|
+
/**
|
|
158
|
+
* `/translate` response for an array of texts: each field is an array with one entry per text,
|
|
159
|
+
* in the order of the request.
|
|
160
|
+
*/
|
|
161
|
+
export declare const TranslateBatchResponseSchema: z.ZodObject<{
|
|
162
|
+
translatedText: z.ZodArray<z.ZodString>;
|
|
163
|
+
alternatives: z.ZodOptional<z.ZodArray<z.ZodArray<z.ZodString>>>;
|
|
164
|
+
detectedLanguage: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
165
|
+
language: z.ZodString;
|
|
166
|
+
confidence: z.ZodNumber;
|
|
167
|
+
}, z.core.$strip>>>;
|
|
7
168
|
}, z.core.$strip>;
|
|
8
|
-
/**
|
|
9
|
-
export type
|
|
10
|
-
/**
|
|
169
|
+
/** Type inferred from {@link TranslateBatchResponseSchema}. */
|
|
170
|
+
export type TranslateBatchResponse = z.infer<typeof TranslateBatchResponseSchema>;
|
|
171
|
+
/**
|
|
172
|
+
* `/translate` response for a single text. `alternatives` comes when they were requested,
|
|
173
|
+
* `detectedLanguage` when `source` was `"auto"`.
|
|
174
|
+
*/
|
|
11
175
|
export declare const TranslateResponseSchema: z.ZodObject<{
|
|
12
176
|
translatedText: z.ZodString;
|
|
177
|
+
alternatives: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
13
178
|
detectedLanguage: z.ZodOptional<z.ZodObject<{
|
|
14
|
-
|
|
179
|
+
language: z.ZodString;
|
|
15
180
|
confidence: z.ZodNumber;
|
|
16
181
|
}, z.core.$strip>>;
|
|
17
|
-
alternatives: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
18
182
|
}, z.core.$strip>;
|
|
19
|
-
/**
|
|
183
|
+
/** Type inferred from {@link TranslateResponseSchema}. */
|
|
20
184
|
export type TranslateResponse = z.infer<typeof TranslateResponseSchema>;
|
|
21
|
-
/**
|
|
22
|
-
export type
|
|
23
|
-
/**
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
/** Target language code (e.g. "en", "ru"). */
|
|
30
|
-
target: string;
|
|
185
|
+
/** Options for the {@link LibreTranslateClient} constructor. */
|
|
186
|
+
export type LibreTranslateClientOptions = {
|
|
187
|
+
/**
|
|
188
|
+
* Root URL of the server, such as `https://libretranslate.com` or
|
|
189
|
+
* `https://example.com/libretranslate/`. Endpoints resolve under its path, with or without a
|
|
190
|
+
* trailing slash.
|
|
191
|
+
*/
|
|
192
|
+
baseUrl: string | URL;
|
|
31
193
|
} & FullyUndefinable<{
|
|
32
|
-
/**
|
|
33
|
-
format: TranslationFormat;
|
|
34
|
-
/** Number of alternative translations. */
|
|
35
|
-
alternatives: number;
|
|
36
|
-
/** Base URL of the LibreTranslate API instance. */
|
|
37
|
-
baseUrl: string;
|
|
38
|
-
/** API key (required for libretranslate.com; optional for self-hosted). */
|
|
194
|
+
/** API key, sent as `api_key`. Public instances require one; self-hosted ones may not. */
|
|
39
195
|
apiKey: string;
|
|
40
|
-
/**
|
|
196
|
+
/**
|
|
197
|
+
* `fetch` used for every request. Defaults to `globalThis.fetch`, read on each request, so
|
|
198
|
+
* mocks installed after the client is created still apply.
|
|
199
|
+
*/
|
|
41
200
|
fetch: typeof globalThis.fetch;
|
|
201
|
+
}>;
|
|
202
|
+
/** Options for {@link LibreTranslateClient.translate} and {@link LibreTranslateClient.translateBatch}. */
|
|
203
|
+
export type TranslateOptions = {
|
|
204
|
+
/** Code of the language to translate into, such as `"ru"`. */
|
|
205
|
+
target: string;
|
|
206
|
+
} & FullyUndefinable<{
|
|
207
|
+
/** Code of the source language, or `"auto"` to let the server detect it. Defaults to `"auto"`. */
|
|
208
|
+
source: string;
|
|
209
|
+
/** Format of the input. Defaults to `"text"`. */
|
|
210
|
+
format: TranslationFormat;
|
|
42
211
|
/**
|
|
43
|
-
*
|
|
44
|
-
* `
|
|
45
|
-
*
|
|
212
|
+
* How many alternative translations to return per text, a non-negative integer; the server
|
|
213
|
+
* may return fewer. Defaults to `0`. A server may cap it (`--alternatives-limit`, off by default) and answer with HTTP 400
|
|
214
|
+
* above the cap.
|
|
46
215
|
*/
|
|
216
|
+
alternatives: number;
|
|
217
|
+
/** Cancels the request; the call then rejects with `signal.reason`. */
|
|
218
|
+
signal: AbortSignal;
|
|
219
|
+
}>;
|
|
220
|
+
/** Options for {@link LibreTranslateClient.detectLanguage}. */
|
|
221
|
+
export type DetectLanguageOptions = FullyUndefinable<{
|
|
222
|
+
/** Cancels the request; the call then rejects with `signal.reason`. */
|
|
223
|
+
signal: AbortSignal;
|
|
224
|
+
}>;
|
|
225
|
+
/** Options for {@link LibreTranslateClient.getLanguages}. */
|
|
226
|
+
export type GetLanguagesOptions = FullyUndefinable<{
|
|
227
|
+
/** Cancels the request; the call then rejects with `signal.reason`. */
|
|
47
228
|
signal: AbortSignal;
|
|
48
229
|
}>;
|
|
49
|
-
/** Default URL for the LibreTranslate API. */
|
|
50
|
-
export declare const defaultBaseUrl = "https://libretranslate.com";
|
|
51
230
|
/**
|
|
52
|
-
*
|
|
53
|
-
*
|
|
54
|
-
* @param options — translation parameters
|
|
55
|
-
* @returns Promise with translation response
|
|
56
|
-
* @throws {Error} On request failure (HTTP status included in message)
|
|
57
|
-
* @throws {DOMException} When `signal` is aborted before or during the request: rejects with
|
|
58
|
-
* `signal.reason`, which is an `AbortError` or `TimeoutError` unless the caller set its own reason
|
|
59
|
-
*
|
|
60
|
-
* @example
|
|
61
|
-
* ```typescript
|
|
62
|
-
* const result = await translate({
|
|
63
|
-
* text: "Hello, world!",
|
|
64
|
-
* source: "en",
|
|
65
|
-
* target: "ru"
|
|
66
|
-
* })
|
|
67
|
-
* console.log(result.translatedText) // "Привет, мир!"
|
|
68
|
-
* ```
|
|
69
|
-
*
|
|
70
|
-
* @example
|
|
71
|
-
* ```typescript
|
|
72
|
-
* // With language auto-detection
|
|
73
|
-
* const result = await translate({
|
|
74
|
-
* text: "Bonjour",
|
|
75
|
-
* source: "auto",
|
|
76
|
-
* target: "en"
|
|
77
|
-
* })
|
|
78
|
-
* console.log(result.translatedText) // "Hello"
|
|
79
|
-
* console.log(result.detectedLanguage) // { code: "fr", confidence: 0.95 }
|
|
80
|
-
* ```
|
|
231
|
+
* Client for one LibreTranslate server.
|
|
81
232
|
*
|
|
82
|
-
* @
|
|
83
|
-
*
|
|
84
|
-
*
|
|
85
|
-
* const result = await translate({
|
|
86
|
-
* text: "Hello",
|
|
87
|
-
* source: "en",
|
|
88
|
-
* target: "es",
|
|
89
|
-
* baseUrl: "https://translate.example.com",
|
|
90
|
-
* apiKey: "your-api-key"
|
|
91
|
-
* })
|
|
92
|
-
* ```
|
|
233
|
+
* Every method rejects with {@link LibreTranslateError} when the server answers with an error
|
|
234
|
+
* status or an unexpected body, with `signal.reason` when the signal aborts, and with the error
|
|
235
|
+
* of `fetch` itself on network failures.
|
|
93
236
|
*
|
|
94
237
|
* @example
|
|
95
238
|
* ```typescript
|
|
96
|
-
*
|
|
97
|
-
*
|
|
98
|
-
*
|
|
99
|
-
* source: "en",
|
|
100
|
-
* target: "ru",
|
|
101
|
-
* fetch: myCustomFetch
|
|
239
|
+
* const client = new LibreTranslateClient({
|
|
240
|
+
* baseUrl: "https://libretranslate.com",
|
|
241
|
+
* apiKey: process.env.LIBRETRANSLATE_API_KEY,
|
|
102
242
|
* })
|
|
103
|
-
* ```
|
|
104
243
|
*
|
|
105
|
-
*
|
|
106
|
-
* ```typescript
|
|
107
|
-
* // Cancelled after 10 seconds
|
|
108
|
-
* const result = await translate({
|
|
109
|
-
* text: "Hello",
|
|
110
|
-
* source: "en",
|
|
111
|
-
* target: "ru",
|
|
112
|
-
* signal: AbortSignal.timeout(10_000)
|
|
113
|
-
* })
|
|
114
|
-
* ```
|
|
115
|
-
*
|
|
116
|
-
* @example
|
|
117
|
-
* ```typescript
|
|
118
|
-
* // With alternative translations
|
|
119
|
-
* const result = await translate({
|
|
120
|
-
* text: "Hello",
|
|
121
|
-
* source: "en",
|
|
122
|
-
* target: "ru",
|
|
123
|
-
* alternatives: 2
|
|
124
|
-
* })
|
|
125
|
-
* console.log(result.alternatives) // ["Здравствуй", "Приветствую"]
|
|
244
|
+
* const { text } = await client.translate("Hello, world!", { source: "en", target: "ru" })
|
|
126
245
|
* ```
|
|
127
246
|
*/
|
|
128
|
-
export declare
|
|
247
|
+
export declare class LibreTranslateClient {
|
|
248
|
+
#private;
|
|
249
|
+
/**
|
|
250
|
+
* @param options - Server URL, API key and `fetch`.
|
|
251
|
+
* @throws {TypeError} When `baseUrl` is not an absolute URL.
|
|
252
|
+
*/
|
|
253
|
+
constructor({ baseUrl, apiKey, fetch }: Readonly<LibreTranslateClientOptions>);
|
|
254
|
+
/**
|
|
255
|
+
* Translates one text.
|
|
256
|
+
*
|
|
257
|
+
* @param text - Text to translate. The server rejects an empty string and a text over its
|
|
258
|
+
* character limit with HTTP 400.
|
|
259
|
+
* @param options - Target and source languages, format, alternatives and signal.
|
|
260
|
+
* @returns The translation.
|
|
261
|
+
* @throws {RangeError} When `alternatives` is not a non-negative integer.
|
|
262
|
+
* @throws {LibreTranslateError} When the server rejects the request or answers with an
|
|
263
|
+
* unexpected body.
|
|
264
|
+
*
|
|
265
|
+
* @example
|
|
266
|
+
* ```typescript
|
|
267
|
+
* const { text, detectedLanguage } = await client.translate("Привет, мир!", { target: "en" })
|
|
268
|
+
* // text: "Hello, world!", detectedLanguage: { language: "ru", confidence: 90 }
|
|
269
|
+
* ```
|
|
270
|
+
*/
|
|
271
|
+
translate(text: string, options: Readonly<TranslateOptions>): Promise<Translation>;
|
|
272
|
+
/**
|
|
273
|
+
* Translates several texts in one request.
|
|
274
|
+
*
|
|
275
|
+
* With `source: "auto"` the server detects one language for the whole batch, so every item
|
|
276
|
+
* carries the same `detectedLanguage`. A server may cap the batch size (`--batch-limit`, off by
|
|
277
|
+
* default) and answer with HTTP 400 above the cap.
|
|
278
|
+
*
|
|
279
|
+
* @param texts - Texts to translate. An empty array resolves to `[]` without a request.
|
|
280
|
+
* @param options - Target and source languages, format, alternatives and signal.
|
|
281
|
+
* @returns Translations in the order of `texts`.
|
|
282
|
+
* @throws {RangeError} When `alternatives` is not a non-negative integer.
|
|
283
|
+
* @throws {LibreTranslateError} When the server rejects the request or answers with an
|
|
284
|
+
* unexpected body.
|
|
285
|
+
*
|
|
286
|
+
* @example
|
|
287
|
+
* ```typescript
|
|
288
|
+
* const translations = await client.translateBatch(["Hello", "Goodbye"], { target: "ru" })
|
|
289
|
+
* translations.map(translation => translation.text) // ["Привет", "До свидания"]
|
|
290
|
+
* ```
|
|
291
|
+
*/
|
|
292
|
+
translateBatch(texts: readonly string[], options: Readonly<TranslateOptions>): Promise<Translation[]>;
|
|
293
|
+
/**
|
|
294
|
+
* Detects the language of a text.
|
|
295
|
+
*
|
|
296
|
+
* @param text - Text to inspect. The server rejects an empty string with HTTP 400.
|
|
297
|
+
* @param options - Signal.
|
|
298
|
+
* @returns Candidate languages, most confident first. When nothing is detected the server
|
|
299
|
+
* returns a single `{ language: "en", confidence: 0 }`.
|
|
300
|
+
* @throws {LibreTranslateError} When the server rejects the request or answers with an
|
|
301
|
+
* unexpected body.
|
|
302
|
+
*
|
|
303
|
+
* @example
|
|
304
|
+
* ```typescript
|
|
305
|
+
* const [best] = await client.detectLanguage("Доброе утро, как дела?")
|
|
306
|
+
* // best: { language: "ru", confidence: 43 }
|
|
307
|
+
* ```
|
|
308
|
+
*/
|
|
309
|
+
detectLanguage(text: string, { signal }?: Readonly<DetectLanguageOptions>): Promise<LanguageDetection[]>;
|
|
310
|
+
/**
|
|
311
|
+
* Lists the languages the server translates from, each with the languages it translates into.
|
|
312
|
+
*
|
|
313
|
+
* @param options - Signal.
|
|
314
|
+
* @returns Supported source languages.
|
|
315
|
+
* @throws {LibreTranslateError} When the server rejects the request or answers with an
|
|
316
|
+
* unexpected body.
|
|
317
|
+
*
|
|
318
|
+
* @example
|
|
319
|
+
* ```typescript
|
|
320
|
+
* const languages = await client.getLanguages()
|
|
321
|
+
* const canTranslate = languages.some(({ code, targets }) => code === "en" && targets.includes("ru"))
|
|
322
|
+
* ```
|
|
323
|
+
*/
|
|
324
|
+
getLanguages({ signal }?: Readonly<GetLanguagesOptions>): Promise<Language[]>;
|
|
325
|
+
}
|
|
129
326
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../lib/schemas/
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../lib/schemas/common/LanguageDetection.ts","../lib/types.ts","../lib/errors/LibreTranslateError.ts","../lib/schemas/common/Language.ts","../lib/schemas/common/TranslationFormat.ts","../lib/schemas/requests/DetectRequest.ts","../lib/schemas/requests/TranslateRequest.ts","../lib/schemas/responses/DetectResponse.ts","../lib/schemas/responses/ErrorResponse.ts","../lib/schemas/responses/LanguagesResponse.ts","../lib/schemas/responses/TranslateBatchResponse.ts","../lib/schemas/responses/TranslateResponse.ts","../lib/LibreTranslateClient.ts"],"mappings":";;;;;;;qBAMa,yBAAuB,EAAA;;;GAGlC,EAAA,KAAA;;YAGU,oBAAoB,EAAE,aAAa;;YCTnC;;YAGA;;EAEV;;;;;EAKA;;;;;EAKA,kBAAkB;;;YCdR,6BAA6B,eACvC;;EAEE,UAAU;;;;;;;EAOV;;EAEA;;;;;;;;;;qBAWS,4BAA4B;;;;;SAOhC,QAAQ,UAAU,SAAS,8BAA8B;;;;;;;;SAWzD,aACL,SAAS,SAAS;IAChB,UAAU;IACV;MAED;;;;;;;;SAiBI,eACL,SAAS,SAAS;IAAgC,UAAU;MAC3D;EASM;;WAGA,UAAU;;WAGV;;WAGA;;;;;EAQT,YACE,mBACE,UAAU,QAAQ,kBAAkB,iBAAgB,SAAS;;;;;;qBC3FtD,gBAAc,EAAA;;;;GAIzB,EAAA,KAAA;;YAGU,WAAW,EAAE,aAAa;;qBCVzB,yBAAuB,EAAA;;;;;YAGxB,oBAAoB,EAAE,aAAa;;qBCHlC,qBAAmB,EAAA;;;GAG9B,EAAA,KAAA;;YAGU,gBAAgB,EAAE,aAAa;;;;;;qBCD9B,wBAAsB,EAAA;;;;;;;;;;GAOjC,EAAA,KAAA;;YAGU,mBAAmB,EAAE,aAAa;;qBCdjC,sBAAoB,EAAA,SAAA,EAAA;;;GAAkC,EAAA,KAAA;;YAGvD,iBAAiB,EAAE,aAAa;;qBCJ/B,qBAAmB,EAAA;;GAE9B,EAAA,KAAA;;YAGU,gBAAgB,EAAE,aAAa;;qBCJ9B,yBAAuB,EAAA,SAAA,EAAA;;;;GAAyB,EAAA,KAAA;;YAGjD,oBAAoB,EAAE,aAAa;;;;;qBCAlC,8BAA4B,EAAA;;;;;;;GAIvC,EAAA,KAAA;;YAGU,yBAAyB,EAAE,aAAa;;;;;qBCPvC,yBAAuB,EAAA;;;;;;;GAIlC,EAAA,KAAA;;YAGU,oBAAoB,EAAE,aAAa;;YCKnC;;;;;;EAMV,kBAAkB;IAChB;;EAEF;;;;;EAKA,cAAc,WAAW;;;YAIf;;EAEV;IACE;;EAEF;;EAEA,QAAQ;;;;;;EAMR;;EAEA,QAAQ;;;YAIE,wBAAwB;;EAElC,QAAQ;;;YAIE,sBAAsB;;EAEhC,QAAQ;;;;;;;;;;;;;;;;;;;qBAoBG;;;;;;EAaX,cAAc,SAAS,QAAQ,SAAS,SAAS;;;;;;;;;;;;;;;;;;EAgC3C,UAAU,cAAc,SAAS,SAAS,oBAAoB,QAAQ;;;;;;;;;;;;;;;;;;;;;EAoCtE,eACJ,0BACA,SAAS,SAAS,oBACjB,QAAQ;;;;;;;;;;;;;;;;;EAqDL,eACJ,gBACE,WAAU,SAAS,yBACpB,QAAQ;;;;;;;;;;;;;;;EAmBL,eAAe,WAAU,SAAS,uBAA4B,QAAQ"}
|
package/dist/index.js
CHANGED
|
@@ -1,120 +1,337 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
-
// lib/
|
|
3
|
-
/**
|
|
4
|
-
|
|
2
|
+
// lib/errors/LibreTranslateError.ts
|
|
3
|
+
/**
|
|
4
|
+
* Thrown when the LibreTranslate server rejects a request or answers with a body this package
|
|
5
|
+
* cannot read.
|
|
6
|
+
*
|
|
7
|
+
* {@link LibreTranslateError.status} and {@link LibreTranslateError.serverMessage} let a caller
|
|
8
|
+
* tell a rate limit from a bad language code without parsing the message. A body that failed to
|
|
9
|
+
* parse or validate keeps that error as `cause`.
|
|
10
|
+
*/
|
|
11
|
+
var LibreTranslateError = class LibreTranslateError extends Error {
|
|
12
|
+
/**
|
|
13
|
+
* @param options - Optional endpoint, status, server message and {@link ErrorOptions}.
|
|
14
|
+
* @returns Error with the message `LibreTranslate request failed`.
|
|
15
|
+
*/
|
|
16
|
+
static default(options) {
|
|
17
|
+
return new LibreTranslateError("LibreTranslate request failed", options);
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Builds an error for a response with an error status.
|
|
21
|
+
*
|
|
22
|
+
* @param options - Endpoint, status, the server message when the body has one, and
|
|
23
|
+
* {@link ErrorOptions}.
|
|
24
|
+
* @returns Error such as `LibreTranslate /translate failed with HTTP 400: es is not supported`.
|
|
25
|
+
*/
|
|
26
|
+
static fromResponse(options) {
|
|
27
|
+
const { endpoint, status, serverMessage } = options;
|
|
28
|
+
const message = `LibreTranslate ${endpoint} failed with HTTP ${status}`;
|
|
29
|
+
return new LibreTranslateError(serverMessage ? `${message}: ${serverMessage}` : message, options);
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Builds an error for a successful response whose body is not JSON or does not have the
|
|
33
|
+
* documented shape. Pass the parse or validation error as `cause`.
|
|
34
|
+
*
|
|
35
|
+
* @param options - Endpoint, status and {@link ErrorOptions}.
|
|
36
|
+
* @returns Error such as `LibreTranslate /translate returned an unexpected body`.
|
|
37
|
+
*/
|
|
38
|
+
static unexpectedBody(options) {
|
|
39
|
+
return new LibreTranslateError(`LibreTranslate ${options.endpoint} returned an unexpected body`, options);
|
|
40
|
+
}
|
|
41
|
+
name = "LibreTranslateError";
|
|
42
|
+
/** Endpoint that answered, such as `/translate`. */
|
|
43
|
+
endpoint;
|
|
44
|
+
/** HTTP status of the response; see {@link LibreTranslateErrorOptions.status}. */
|
|
45
|
+
status;
|
|
46
|
+
/** Message from the `error` field of the response body. */
|
|
47
|
+
serverMessage;
|
|
48
|
+
/**
|
|
49
|
+
* @param message - Human-readable error message.
|
|
50
|
+
* @param options - Optional endpoint, status, server message and {@link ErrorOptions}.
|
|
51
|
+
*/
|
|
52
|
+
constructor(message, { endpoint, status, serverMessage, ...errorOptions } = {}) {
|
|
53
|
+
super(message, errorOptions);
|
|
54
|
+
this.endpoint = endpoint;
|
|
55
|
+
this.status = status;
|
|
56
|
+
this.serverMessage = serverMessage;
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
// lib/schemas/common/Language.ts
|
|
60
|
+
/**
|
|
61
|
+
* Language the server translates from, as one item of the `/languages` response: its code, its
|
|
62
|
+
* English name, and the codes of the languages it translates into.
|
|
63
|
+
*/
|
|
64
|
+
const LanguageSchema = z.object({
|
|
5
65
|
code: z.string(),
|
|
66
|
+
name: z.string(),
|
|
67
|
+
targets: z.string().array()
|
|
68
|
+
});
|
|
69
|
+
// lib/schemas/common/LanguageDetection.ts
|
|
70
|
+
/**
|
|
71
|
+
* One guess of the language a text is written in, as `/translate` and `/detect` return it.
|
|
72
|
+
* `confidence` goes from `0` to `100`.
|
|
73
|
+
*/
|
|
74
|
+
const LanguageDetectionSchema = z.object({
|
|
75
|
+
language: z.string(),
|
|
6
76
|
confidence: z.number()
|
|
7
77
|
});
|
|
8
|
-
// lib/schemas/
|
|
9
|
-
/**
|
|
78
|
+
// lib/schemas/common/TranslationFormat.ts
|
|
79
|
+
/** Text format: `"text"` for plain text, `"html"` to keep markup and translate only its text. */
|
|
80
|
+
const TranslationFormatSchema = z.enum(["text", "html"]);
|
|
81
|
+
// lib/schemas/requests/DetectRequest.ts
|
|
82
|
+
/** `/detect` request body. */
|
|
83
|
+
const DetectRequestSchema = z.object({
|
|
84
|
+
q: z.string(),
|
|
85
|
+
api_key: z.string().optional()
|
|
86
|
+
});
|
|
87
|
+
// lib/schemas/requests/TranslateRequest.ts
|
|
88
|
+
/**
|
|
89
|
+
* `/translate` request body. `q` is one text or an array of texts; `source` is a language code
|
|
90
|
+
* or `"auto"`. The server treats a missing `format` as `"text"` and a missing `alternatives` as
|
|
91
|
+
* `0`.
|
|
92
|
+
*/
|
|
93
|
+
const TranslateRequestSchema = z.object({
|
|
94
|
+
q: z.union([z.string(), z.string().array()]),
|
|
95
|
+
source: z.string(),
|
|
96
|
+
target: z.string(),
|
|
97
|
+
format: TranslationFormatSchema.optional(),
|
|
98
|
+
alternatives: z.number().int().nonnegative().optional(),
|
|
99
|
+
api_key: z.string().optional()
|
|
100
|
+
});
|
|
101
|
+
// lib/schemas/responses/DetectResponse.ts
|
|
102
|
+
/** `/detect` response: candidate languages, most confident first. */
|
|
103
|
+
const DetectResponseSchema = LanguageDetectionSchema.array();
|
|
104
|
+
// lib/schemas/responses/ErrorResponse.ts
|
|
105
|
+
/** Body the server sends with an error status. */
|
|
106
|
+
const ErrorResponseSchema = z.object({ error: z.string() });
|
|
107
|
+
// lib/schemas/responses/LanguagesResponse.ts
|
|
108
|
+
/** `/languages` response: every language the server translates from. */
|
|
109
|
+
const LanguagesResponseSchema = LanguageSchema.array();
|
|
110
|
+
// lib/schemas/responses/TranslateBatchResponse.ts
|
|
111
|
+
/**
|
|
112
|
+
* `/translate` response for an array of texts: each field is an array with one entry per text,
|
|
113
|
+
* in the order of the request.
|
|
114
|
+
*/
|
|
115
|
+
const TranslateBatchResponseSchema = z.object({
|
|
116
|
+
translatedText: z.string().array(),
|
|
117
|
+
alternatives: z.string().array().array().optional(),
|
|
118
|
+
detectedLanguage: LanguageDetectionSchema.array().optional()
|
|
119
|
+
});
|
|
120
|
+
// lib/schemas/responses/TranslateResponse.ts
|
|
121
|
+
/**
|
|
122
|
+
* `/translate` response for a single text. `alternatives` comes when they were requested,
|
|
123
|
+
* `detectedLanguage` when `source` was `"auto"`.
|
|
124
|
+
*/
|
|
10
125
|
const TranslateResponseSchema = z.object({
|
|
11
126
|
translatedText: z.string(),
|
|
12
|
-
|
|
13
|
-
|
|
127
|
+
alternatives: z.string().array().optional(),
|
|
128
|
+
detectedLanguage: LanguageDetectionSchema.optional()
|
|
14
129
|
});
|
|
15
|
-
// lib/
|
|
16
|
-
/** Default URL for the LibreTranslate API. */
|
|
17
|
-
const defaultBaseUrl = "https://libretranslate.com";
|
|
18
|
-
// lib/functions.ts
|
|
130
|
+
// lib/LibreTranslateClient.ts
|
|
19
131
|
/**
|
|
20
|
-
*
|
|
132
|
+
* Client for one LibreTranslate server.
|
|
21
133
|
*
|
|
22
|
-
* @
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
* @throws {DOMException} When `signal` is aborted before or during the request: rejects with
|
|
26
|
-
* `signal.reason`, which is an `AbortError` or `TimeoutError` unless the caller set its own reason
|
|
134
|
+
* Every method rejects with {@link LibreTranslateError} when the server answers with an error
|
|
135
|
+
* status or an unexpected body, with `signal.reason` when the signal aborts, and with the error
|
|
136
|
+
* of `fetch` itself on network failures.
|
|
27
137
|
*
|
|
28
138
|
* @example
|
|
29
139
|
* ```typescript
|
|
30
|
-
* const
|
|
31
|
-
*
|
|
32
|
-
*
|
|
33
|
-
* target: "ru"
|
|
140
|
+
* const client = new LibreTranslateClient({
|
|
141
|
+
* baseUrl: "https://libretranslate.com",
|
|
142
|
+
* apiKey: process.env.LIBRETRANSLATE_API_KEY,
|
|
34
143
|
* })
|
|
35
|
-
* console.log(result.translatedText) // "Привет, мир!"
|
|
36
|
-
* ```
|
|
37
144
|
*
|
|
38
|
-
*
|
|
39
|
-
* ```typescript
|
|
40
|
-
* // With language auto-detection
|
|
41
|
-
* const result = await translate({
|
|
42
|
-
* text: "Bonjour",
|
|
43
|
-
* source: "auto",
|
|
44
|
-
* target: "en"
|
|
45
|
-
* })
|
|
46
|
-
* console.log(result.translatedText) // "Hello"
|
|
47
|
-
* console.log(result.detectedLanguage) // { code: "fr", confidence: 0.95 }
|
|
48
|
-
* ```
|
|
49
|
-
*
|
|
50
|
-
* @example
|
|
51
|
-
* ```typescript
|
|
52
|
-
* // With custom API and key
|
|
53
|
-
* const result = await translate({
|
|
54
|
-
* text: "Hello",
|
|
55
|
-
* source: "en",
|
|
56
|
-
* target: "es",
|
|
57
|
-
* baseUrl: "https://translate.example.com",
|
|
58
|
-
* apiKey: "your-api-key"
|
|
59
|
-
* })
|
|
60
|
-
* ```
|
|
61
|
-
*
|
|
62
|
-
* @example
|
|
63
|
-
* ```typescript
|
|
64
|
-
* // With custom fetch (e.g. for tests or proxy)
|
|
65
|
-
* const result = await translate({
|
|
66
|
-
* text: "Hello",
|
|
67
|
-
* source: "en",
|
|
68
|
-
* target: "ru",
|
|
69
|
-
* fetch: myCustomFetch
|
|
70
|
-
* })
|
|
71
|
-
* ```
|
|
72
|
-
*
|
|
73
|
-
* @example
|
|
74
|
-
* ```typescript
|
|
75
|
-
* // Cancelled after 10 seconds
|
|
76
|
-
* const result = await translate({
|
|
77
|
-
* text: "Hello",
|
|
78
|
-
* source: "en",
|
|
79
|
-
* target: "ru",
|
|
80
|
-
* signal: AbortSignal.timeout(10_000)
|
|
81
|
-
* })
|
|
82
|
-
* ```
|
|
83
|
-
*
|
|
84
|
-
* @example
|
|
85
|
-
* ```typescript
|
|
86
|
-
* // With alternative translations
|
|
87
|
-
* const result = await translate({
|
|
88
|
-
* text: "Hello",
|
|
89
|
-
* source: "en",
|
|
90
|
-
* target: "ru",
|
|
91
|
-
* alternatives: 2
|
|
92
|
-
* })
|
|
93
|
-
* console.log(result.alternatives) // ["Здравствуй", "Приветствую"]
|
|
145
|
+
* const { text } = await client.translate("Hello, world!", { source: "en", target: "ru" })
|
|
94
146
|
* ```
|
|
95
147
|
*/
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
148
|
+
var LibreTranslateClient = class {
|
|
149
|
+
#baseUrl;
|
|
150
|
+
#apiKey;
|
|
151
|
+
#fetch;
|
|
152
|
+
/**
|
|
153
|
+
* @param options - Server URL, API key and `fetch`.
|
|
154
|
+
* @throws {TypeError} When `baseUrl` is not an absolute URL.
|
|
155
|
+
*/
|
|
156
|
+
constructor({ baseUrl, apiKey, fetch }) {
|
|
157
|
+
const url = URL.parse(String(baseUrl));
|
|
158
|
+
if (url == null) throw new TypeError(`baseUrl must be an absolute URL, got ${String(baseUrl)}`);
|
|
159
|
+
if (!url.pathname.endsWith("/")) url.pathname += "/";
|
|
160
|
+
this.#baseUrl = url;
|
|
161
|
+
this.#apiKey = apiKey;
|
|
162
|
+
this.#fetch = fetch;
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* Translates one text.
|
|
166
|
+
*
|
|
167
|
+
* @param text - Text to translate. The server rejects an empty string and a text over its
|
|
168
|
+
* character limit with HTTP 400.
|
|
169
|
+
* @param options - Target and source languages, format, alternatives and signal.
|
|
170
|
+
* @returns The translation.
|
|
171
|
+
* @throws {RangeError} When `alternatives` is not a non-negative integer.
|
|
172
|
+
* @throws {LibreTranslateError} When the server rejects the request or answers with an
|
|
173
|
+
* unexpected body.
|
|
174
|
+
*
|
|
175
|
+
* @example
|
|
176
|
+
* ```typescript
|
|
177
|
+
* const { text, detectedLanguage } = await client.translate("Привет, мир!", { target: "en" })
|
|
178
|
+
* // text: "Hello, world!", detectedLanguage: { language: "ru", confidence: 90 }
|
|
179
|
+
* ```
|
|
180
|
+
*/
|
|
181
|
+
async translate(text, options) {
|
|
182
|
+
const request = this.#translateRequest(text, options);
|
|
183
|
+
const response = await this.#send("/translate", TranslateResponseSchema, request, options.signal);
|
|
184
|
+
return {
|
|
185
|
+
text: response.translatedText,
|
|
186
|
+
alternatives: response.alternatives ?? [],
|
|
187
|
+
detectedLanguage: response.detectedLanguage
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* Translates several texts in one request.
|
|
192
|
+
*
|
|
193
|
+
* With `source: "auto"` the server detects one language for the whole batch, so every item
|
|
194
|
+
* carries the same `detectedLanguage`. A server may cap the batch size (`--batch-limit`, off by
|
|
195
|
+
* default) and answer with HTTP 400 above the cap.
|
|
196
|
+
*
|
|
197
|
+
* @param texts - Texts to translate. An empty array resolves to `[]` without a request.
|
|
198
|
+
* @param options - Target and source languages, format, alternatives and signal.
|
|
199
|
+
* @returns Translations in the order of `texts`.
|
|
200
|
+
* @throws {RangeError} When `alternatives` is not a non-negative integer.
|
|
201
|
+
* @throws {LibreTranslateError} When the server rejects the request or answers with an
|
|
202
|
+
* unexpected body.
|
|
203
|
+
*
|
|
204
|
+
* @example
|
|
205
|
+
* ```typescript
|
|
206
|
+
* const translations = await client.translateBatch(["Hello", "Goodbye"], { target: "ru" })
|
|
207
|
+
* translations.map(translation => translation.text) // ["Привет", "До свидания"]
|
|
208
|
+
* ```
|
|
209
|
+
*/
|
|
210
|
+
async translateBatch(texts, options) {
|
|
211
|
+
const request = this.#translateRequest([...texts], options);
|
|
212
|
+
if (texts.length === 0) {
|
|
213
|
+
options.signal?.throwIfAborted();
|
|
214
|
+
return [];
|
|
215
|
+
}
|
|
216
|
+
const { translatedText, alternatives, detectedLanguage } = await this.#send("/translate", TranslateBatchResponseSchema, request, options.signal);
|
|
217
|
+
if (translatedText.length !== texts.length) throw LibreTranslateError.unexpectedBody({
|
|
218
|
+
endpoint: "/translate",
|
|
219
|
+
cause: /* @__PURE__ */ new RangeError(`translatedText must have ${texts.length} items, got ${translatedText.length}`)
|
|
220
|
+
});
|
|
221
|
+
return translatedText.map((text, index) => ({
|
|
222
|
+
text,
|
|
223
|
+
alternatives: alternatives?.[index] ?? [],
|
|
224
|
+
detectedLanguage: detectedLanguage?.[index]
|
|
225
|
+
}));
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* Detects the language of a text.
|
|
229
|
+
*
|
|
230
|
+
* @param text - Text to inspect. The server rejects an empty string with HTTP 400.
|
|
231
|
+
* @param options - Signal.
|
|
232
|
+
* @returns Candidate languages, most confident first. When nothing is detected the server
|
|
233
|
+
* returns a single `{ language: "en", confidence: 0 }`.
|
|
234
|
+
* @throws {LibreTranslateError} When the server rejects the request or answers with an
|
|
235
|
+
* unexpected body.
|
|
236
|
+
*
|
|
237
|
+
* @example
|
|
238
|
+
* ```typescript
|
|
239
|
+
* const [best] = await client.detectLanguage("Доброе утро, как дела?")
|
|
240
|
+
* // best: { language: "ru", confidence: 43 }
|
|
241
|
+
* ```
|
|
242
|
+
*/
|
|
243
|
+
async detectLanguage(text, { signal } = {}) {
|
|
244
|
+
const request = {
|
|
245
|
+
q: text,
|
|
246
|
+
api_key: this.#apiKey
|
|
247
|
+
};
|
|
248
|
+
return await this.#send("/detect", DetectResponseSchema, request, signal);
|
|
249
|
+
}
|
|
250
|
+
/**
|
|
251
|
+
* Lists the languages the server translates from, each with the languages it translates into.
|
|
252
|
+
*
|
|
253
|
+
* @param options - Signal.
|
|
254
|
+
* @returns Supported source languages.
|
|
255
|
+
* @throws {LibreTranslateError} When the server rejects the request or answers with an
|
|
256
|
+
* unexpected body.
|
|
257
|
+
*
|
|
258
|
+
* @example
|
|
259
|
+
* ```typescript
|
|
260
|
+
* const languages = await client.getLanguages()
|
|
261
|
+
* const canTranslate = languages.some(({ code, targets }) => code === "en" && targets.includes("ru"))
|
|
262
|
+
* ```
|
|
263
|
+
*/
|
|
264
|
+
async getLanguages({ signal } = {}) {
|
|
265
|
+
return await this.#send("/languages", LanguagesResponseSchema, void 0, signal);
|
|
266
|
+
}
|
|
267
|
+
/**
|
|
268
|
+
* Builds the `/translate` body shared by single and batch requests.
|
|
269
|
+
*
|
|
270
|
+
* @param q - Text or texts to translate.
|
|
271
|
+
* @param options - Translation options; `signal` is ignored.
|
|
272
|
+
* @returns The request body, with the API key when the client has one.
|
|
273
|
+
* @throws {RangeError} When `alternatives` is not a non-negative integer.
|
|
274
|
+
*/
|
|
275
|
+
#translateRequest(q, { target, source = "auto", format = "text", alternatives = 0 }) {
|
|
276
|
+
const check = TranslateRequestSchema.shape.alternatives.safeParse(alternatives);
|
|
277
|
+
if (!check.success) throw new RangeError(`alternatives must be a non-negative integer, got ${alternatives}`, { cause: check.error });
|
|
278
|
+
return {
|
|
279
|
+
q,
|
|
280
|
+
source,
|
|
281
|
+
target,
|
|
282
|
+
format,
|
|
283
|
+
alternatives: alternatives > 0 ? alternatives : void 0,
|
|
284
|
+
api_key: this.#apiKey
|
|
285
|
+
};
|
|
286
|
+
}
|
|
287
|
+
/**
|
|
288
|
+
* Sends a request and reads the response.
|
|
289
|
+
*
|
|
290
|
+
* A request with a body goes as a JSON `POST`; without one, as a `GET`. Fields set to
|
|
291
|
+
* `undefined` are left out of the JSON.
|
|
292
|
+
*
|
|
293
|
+
* @param endpoint - Endpoint to call.
|
|
294
|
+
* @param schema - Schema of a successful response body.
|
|
295
|
+
* @param body - Request body, or `undefined` for a `GET`.
|
|
296
|
+
* @param signal - Cancels the request and the reading of the response.
|
|
297
|
+
* @returns The response body parsed by `schema`.
|
|
298
|
+
* @throws {LibreTranslateError} When the status is not `2xx`, or the body is not JSON or does
|
|
299
|
+
* not match `schema`.
|
|
300
|
+
*/
|
|
301
|
+
async #send(endpoint, schema, body, signal) {
|
|
302
|
+
signal?.throwIfAborted();
|
|
303
|
+
const response = await (this.#fetch ?? globalThis.fetch)(new URL(`.${endpoint}`, this.#baseUrl), body == null ? { signal: signal ?? null } : {
|
|
304
|
+
method: "POST",
|
|
305
|
+
headers: { "Content-Type": "application/json" },
|
|
306
|
+
body: JSON.stringify(body),
|
|
307
|
+
signal: signal ?? null
|
|
308
|
+
});
|
|
309
|
+
const text = await response.text();
|
|
310
|
+
signal?.throwIfAborted();
|
|
311
|
+
let json;
|
|
312
|
+
try {
|
|
313
|
+
json = JSON.parse(text);
|
|
314
|
+
} catch (error) {
|
|
315
|
+
if (response.ok) throw LibreTranslateError.unexpectedBody({
|
|
316
|
+
endpoint,
|
|
317
|
+
status: response.status,
|
|
318
|
+
cause: error
|
|
319
|
+
});
|
|
320
|
+
}
|
|
321
|
+
if (!response.ok) throw LibreTranslateError.fromResponse({
|
|
322
|
+
endpoint,
|
|
323
|
+
status: response.status,
|
|
324
|
+
serverMessage: ErrorResponseSchema.safeParse(json).data?.error
|
|
325
|
+
});
|
|
326
|
+
const result = schema.safeParse(json);
|
|
327
|
+
if (!result.success) throw LibreTranslateError.unexpectedBody({
|
|
328
|
+
endpoint,
|
|
329
|
+
status: response.status,
|
|
330
|
+
cause: result.error
|
|
331
|
+
});
|
|
332
|
+
return result.data;
|
|
333
|
+
}
|
|
334
|
+
};
|
|
335
|
+
export { DetectRequestSchema, DetectResponseSchema, ErrorResponseSchema, LanguageDetectionSchema, LanguageSchema, LanguagesResponseSchema, LibreTranslateClient, LibreTranslateError, TranslateBatchResponseSchema, TranslateRequestSchema, TranslateResponseSchema, TranslationFormatSchema };
|
|
119
336
|
|
|
120
337
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../lib/schemas/DetectedLanguage.ts","../lib/schemas/TranslateResponse.ts","../lib/constants.ts","../lib/functions.ts"],"sourcesContent":["import { z } from \"zod\"\n\n/** Detected language info schema. */\nexport const DetectedLanguageSchema = z.object({\n code: z.string(),\n confidence: z.number(),\n})\n\n/** Detected language info (when using auto-detection). */\nexport type DetectedLanguage = z.infer<typeof DetectedLanguageSchema>\n","import { z } from \"zod\"\nimport { DetectedLanguageSchema } from \"./DetectedLanguage.ts\"\n\n/** Translation response schema. */\nexport const TranslateResponseSchema = z.object({\n translatedText: z.string(),\n detectedLanguage: DetectedLanguageSchema.optional(),\n alternatives: z.array(z.string()).optional(),\n})\n\n/** Translation response from the LibreTranslate API. */\nexport type TranslateResponse = z.infer<typeof TranslateResponseSchema>\n","/** Default URL for the LibreTranslate API. */\nexport const defaultBaseUrl = \"https://libretranslate.com\"\n","import type { DeepReadonly } from \"@cutticat/types\"\nimport type { TranslationOptions } from \"./types/TranslationOptions.ts\"\nimport { TranslateResponseSchema, type TranslateResponse } from \"./schemas/TranslateResponse.ts\"\nimport { defaultBaseUrl } from \"./constants.ts\"\n\n/**\n * Translates text via the LibreTranslate API.\n *\n * @param options — translation parameters\n * @returns Promise with translation response\n * @throws {Error} On request failure (HTTP status included in message)\n * @throws {DOMException} When `signal` is aborted before or during the request: rejects with\n * `signal.reason`, which is an `AbortError` or `TimeoutError` unless the caller set its own reason\n *\n * @example\n * ```typescript\n * const result = await translate({\n * text: \"Hello, world!\",\n * source: \"en\",\n * target: \"ru\"\n * })\n * console.log(result.translatedText) // \"Привет, мир!\"\n * ```\n *\n * @example\n * ```typescript\n * // With language auto-detection\n * const result = await translate({\n * text: \"Bonjour\",\n * source: \"auto\",\n * target: \"en\"\n * })\n * console.log(result.translatedText) // \"Hello\"\n * console.log(result.detectedLanguage) // { code: \"fr\", confidence: 0.95 }\n * ```\n *\n * @example\n * ```typescript\n * // With custom API and key\n * const result = await translate({\n * text: \"Hello\",\n * source: \"en\",\n * target: \"es\",\n * baseUrl: \"https://translate.example.com\",\n * apiKey: \"your-api-key\"\n * })\n * ```\n *\n * @example\n * ```typescript\n * // With custom fetch (e.g. for tests or proxy)\n * const result = await translate({\n * text: \"Hello\",\n * source: \"en\",\n * target: \"ru\",\n * fetch: myCustomFetch\n * })\n * ```\n *\n * @example\n * ```typescript\n * // Cancelled after 10 seconds\n * const result = await translate({\n * text: \"Hello\",\n * source: \"en\",\n * target: \"ru\",\n * signal: AbortSignal.timeout(10_000)\n * })\n * ```\n *\n * @example\n * ```typescript\n * // With alternative translations\n * const result = await translate({\n * text: \"Hello\",\n * source: \"en\",\n * target: \"ru\",\n * alternatives: 2\n * })\n * console.log(result.alternatives) // [\"Здравствуй\", \"Приветствую\"]\n * ```\n */\nexport async function translate({\n text,\n source,\n target,\n format = \"text\",\n alternatives = 0,\n apiKey,\n baseUrl = defaultBaseUrl,\n fetch = globalThis.fetch,\n signal,\n}: DeepReadonly<TranslationOptions>): Promise<TranslateResponse> {\n // Validation\n\n if (alternatives < 0) throw new Error(\"Number of alternatives must be zero or positive\")\n if (!Number.isInteger(alternatives)) throw new Error(\"Number of alternatives must be an integer\")\n\n // Body creation\n\n const body: Record<string, unknown> = {\n q: text,\n source: source,\n target: target,\n }\n\n if (format != null) body.format = format\n if (alternatives > 0) body.alternatives = alternatives\n if (apiKey != null) body.api_key = apiKey\n\n // Request sending\n\n signal?.throwIfAborted()\n\n const url = new URL(\"/translate\", baseUrl)\n const response = await fetch(url, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(body),\n signal: signal ?? null,\n })\n\n // Response processing\n\n if (!response.ok)\n throw new Error(`Failed to translate text: ${response.status} ${response.statusText}`)\n\n const json = await response.json()\n const data = TranslateResponseSchema.parse(json)\n\n return data\n}\n"],"mappings":";;;AAGA,MAAa,yBAAyB,EAAE,OAAO;CAC7C,MAAM,EAAE,OAAO;CACf,YAAY,EAAE,OAAO;AACvB,CAAC;;;ACFD,MAAa,0BAA0B,EAAE,OAAO;CAC9C,gBAAgB,EAAE,OAAO;CACzB,kBAAkB,uBAAuB,SAAS;CAClD,cAAc,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,SAAS;AAC7C,CAAC;;;ACPD,MAAa,iBAAiB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACiF9B,eAAsB,UAAU,EAC9B,MACA,QACA,QACA,SAAS,QACT,eAAe,GACf,QACA,UAAU,gBACV,QAAQ,WAAW,OACnB,UAC+D;CAG/D,IAAI,eAAe,GAAG,MAAM,IAAI,MAAM,iDAAiD;CACvF,IAAI,CAAC,OAAO,UAAU,YAAY,GAAG,MAAM,IAAI,MAAM,2CAA2C;CAIhG,MAAM,OAAgC;EACpC,GAAG;EACK;EACA;CACV;CAEA,IAAI,UAAU,MAAM,KAAK,SAAS;CAClC,IAAI,eAAe,GAAG,KAAK,eAAe;CAC1C,IAAI,UAAU,MAAM,KAAK,UAAU;CAInC,QAAQ,eAAe;CAGvB,MAAM,WAAW,MAAM,MAAM,IADb,IAAI,cAAc,OACH,GAAG;EAChC,QAAQ;EACR,SAAS,EAAE,gBAAgB,mBAAmB;EAC9C,MAAM,KAAK,UAAU,IAAI;EACzB,QAAQ,UAAU;CACpB,CAAC;CAID,IAAI,CAAC,SAAS,IACZ,MAAM,IAAI,MAAM,6BAA6B,SAAS,OAAO,GAAG,SAAS,YAAY;CAEvF,MAAM,OAAO,MAAM,SAAS,KAAK;CAGjC,OAFa,wBAAwB,MAAM,IAEjC;AACZ"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../lib/errors/LibreTranslateError.ts","../lib/schemas/common/Language.ts","../lib/schemas/common/LanguageDetection.ts","../lib/schemas/common/TranslationFormat.ts","../lib/schemas/requests/DetectRequest.ts","../lib/schemas/requests/TranslateRequest.ts","../lib/schemas/responses/DetectResponse.ts","../lib/schemas/responses/ErrorResponse.ts","../lib/schemas/responses/LanguagesResponse.ts","../lib/schemas/responses/TranslateBatchResponse.ts","../lib/schemas/responses/TranslateResponse.ts","../lib/LibreTranslateClient.ts"],"sourcesContent":["import type { FullyUndefinable } from \"@cutticat/types\"\nimport type { LibreTranslateEndpoint } from \"../types.ts\"\n\n/** Options for {@link LibreTranslateError}. */\nexport type LibreTranslateErrorOptions = ErrorOptions &\n FullyUndefinable<{\n /** Endpoint that answered, such as `/translate`. */\n endpoint: LibreTranslateEndpoint\n /**\n * HTTP status of the response: `400` for bad input, a limit the server enforces or a missing\n * API key the server requires, `403` for an invalid API key or a banned client, `429` for a\n * rate limit, `5xx` for server failures. A `2xx` status means the body did not parse or\n * validate. `undefined` when a batch answer has the wrong number of items.\n */\n status: number\n /** Message from the `error` field of the response body, such as `es is not supported`. */\n serverMessage: string\n }>\n\n/**\n * Thrown when the LibreTranslate server rejects a request or answers with a body this package\n * cannot read.\n *\n * {@link LibreTranslateError.status} and {@link LibreTranslateError.serverMessage} let a caller\n * tell a rate limit from a bad language code without parsing the message. A body that failed to\n * parse or validate keeps that error as `cause`.\n */\nexport class LibreTranslateError extends Error {\n // Factories\n\n /**\n * @param options - Optional endpoint, status, server message and {@link ErrorOptions}.\n * @returns Error with the message `LibreTranslate request failed`.\n */\n static default(options?: Readonly<LibreTranslateErrorOptions>): LibreTranslateError {\n return new LibreTranslateError(\"LibreTranslate request failed\", options)\n }\n\n /**\n * Builds an error for a response with an error status.\n *\n * @param options - Endpoint, status, the server message when the body has one, and\n * {@link ErrorOptions}.\n * @returns Error such as `LibreTranslate /translate failed with HTTP 400: es is not supported`.\n */\n static fromResponse(\n options: Readonly<LibreTranslateErrorOptions> & {\n endpoint: LibreTranslateEndpoint\n status: number\n }\n ): LibreTranslateError {\n const { endpoint, status, serverMessage } = options\n const message = `LibreTranslate ${endpoint} failed with HTTP ${status}`\n\n return new LibreTranslateError(\n serverMessage ? `${message}: ${serverMessage}` : message,\n options\n )\n }\n\n /**\n * Builds an error for a successful response whose body is not JSON or does not have the\n * documented shape. Pass the parse or validation error as `cause`.\n *\n * @param options - Endpoint, status and {@link ErrorOptions}.\n * @returns Error such as `LibreTranslate /translate returned an unexpected body`.\n */\n static unexpectedBody(\n options: Readonly<LibreTranslateErrorOptions> & { endpoint: LibreTranslateEndpoint }\n ): LibreTranslateError {\n return new LibreTranslateError(\n `LibreTranslate ${options.endpoint} returned an unexpected body`,\n options\n )\n }\n\n // Fields\n\n override name = \"LibreTranslateError\"\n\n /** Endpoint that answered, such as `/translate`. */\n readonly endpoint: LibreTranslateEndpoint | undefined\n\n /** HTTP status of the response; see {@link LibreTranslateErrorOptions.status}. */\n readonly status: number | undefined\n\n /** Message from the `error` field of the response body. */\n readonly serverMessage: string | undefined\n\n // Constructor\n\n /**\n * @param message - Human-readable error message.\n * @param options - Optional endpoint, status, server message and {@link ErrorOptions}.\n */\n constructor(\n message: string,\n { endpoint, status, serverMessage, ...errorOptions }: Readonly<LibreTranslateErrorOptions> = {}\n ) {\n super(message, errorOptions)\n this.endpoint = endpoint\n this.status = status\n this.serverMessage = serverMessage\n }\n}\n","import { z } from \"zod\"\n\n/**\n * Language the server translates from, as one item of the `/languages` response: its code, its\n * English name, and the codes of the languages it translates into.\n */\nexport const LanguageSchema = z.object({\n code: z.string(),\n name: z.string(),\n targets: z.string().array(),\n})\n\n/** Type inferred from {@link LanguageSchema}. */\nexport type Language = z.infer<typeof LanguageSchema>\n","import { z } from \"zod\"\n\n/**\n * One guess of the language a text is written in, as `/translate` and `/detect` return it.\n * `confidence` goes from `0` to `100`.\n */\nexport const LanguageDetectionSchema = z.object({\n language: z.string(),\n confidence: z.number(),\n})\n\n/** Type inferred from {@link LanguageDetectionSchema}. */\nexport type LanguageDetection = z.infer<typeof LanguageDetectionSchema>\n","import { z } from \"zod\"\n\n/** Text format: `\"text\"` for plain text, `\"html\"` to keep markup and translate only its text. */\nexport const TranslationFormatSchema = z.enum([\"text\", \"html\"])\n\n/** Type inferred from {@link TranslationFormatSchema}. */\nexport type TranslationFormat = z.infer<typeof TranslationFormatSchema>\n","import { z } from \"zod\"\n\n/** `/detect` request body. */\nexport const DetectRequestSchema = z.object({\n q: z.string(),\n api_key: z.string().optional(),\n})\n\n/** Type inferred from {@link DetectRequestSchema}. */\nexport type DetectRequest = z.infer<typeof DetectRequestSchema>\n","import { z } from \"zod\"\nimport { TranslationFormatSchema } from \"../common/TranslationFormat.ts\"\n\n/**\n * `/translate` request body. `q` is one text or an array of texts; `source` is a language code\n * or `\"auto\"`. The server treats a missing `format` as `\"text\"` and a missing `alternatives` as\n * `0`.\n */\nexport const TranslateRequestSchema = z.object({\n q: z.union([z.string(), z.string().array()]),\n source: z.string(),\n target: z.string(),\n format: TranslationFormatSchema.optional(),\n alternatives: z.number().int().nonnegative().optional(),\n api_key: z.string().optional(),\n})\n\n/** Type inferred from {@link TranslateRequestSchema}. */\nexport type TranslateRequest = z.infer<typeof TranslateRequestSchema>\n","import type { z } from \"zod\"\nimport { LanguageDetectionSchema } from \"../common/LanguageDetection.ts\"\n\n/** `/detect` response: candidate languages, most confident first. */\nexport const DetectResponseSchema = LanguageDetectionSchema.array()\n\n/** Type inferred from {@link DetectResponseSchema}. */\nexport type DetectResponse = z.infer<typeof DetectResponseSchema>\n","import { z } from \"zod\"\n\n/** Body the server sends with an error status. */\nexport const ErrorResponseSchema = z.object({\n error: z.string(),\n})\n\n/** Type inferred from {@link ErrorResponseSchema}. */\nexport type ErrorResponse = z.infer<typeof ErrorResponseSchema>\n","import type { z } from \"zod\"\nimport { LanguageSchema } from \"../common/Language.ts\"\n\n/** `/languages` response: every language the server translates from. */\nexport const LanguagesResponseSchema = LanguageSchema.array()\n\n/** Type inferred from {@link LanguagesResponseSchema}. */\nexport type LanguagesResponse = z.infer<typeof LanguagesResponseSchema>\n","import { z } from \"zod\"\nimport { LanguageDetectionSchema } from \"../common/LanguageDetection.ts\"\n\n/**\n * `/translate` response for an array of texts: each field is an array with one entry per text,\n * in the order of the request.\n */\nexport const TranslateBatchResponseSchema = z.object({\n translatedText: z.string().array(),\n alternatives: z.string().array().array().optional(),\n detectedLanguage: LanguageDetectionSchema.array().optional(),\n})\n\n/** Type inferred from {@link TranslateBatchResponseSchema}. */\nexport type TranslateBatchResponse = z.infer<typeof TranslateBatchResponseSchema>\n","import { z } from \"zod\"\nimport { LanguageDetectionSchema } from \"../common/LanguageDetection.ts\"\n\n/**\n * `/translate` response for a single text. `alternatives` comes when they were requested,\n * `detectedLanguage` when `source` was `\"auto\"`.\n */\nexport const TranslateResponseSchema = z.object({\n translatedText: z.string(),\n alternatives: z.string().array().optional(),\n detectedLanguage: LanguageDetectionSchema.optional(),\n})\n\n/** Type inferred from {@link TranslateResponseSchema}. */\nexport type TranslateResponse = z.infer<typeof TranslateResponseSchema>\n","import type { z } from \"zod\"\nimport type { FullyUndefinable } from \"@cutticat/types\"\nimport { LibreTranslateError } from \"./errors/LibreTranslateError.ts\"\nimport type { DetectRequest } from \"./schemas/requests/DetectRequest.ts\"\nimport { DetectResponseSchema } from \"./schemas/responses/DetectResponse.ts\"\nimport { ErrorResponseSchema } from \"./schemas/responses/ErrorResponse.ts\"\nimport type { Language } from \"./schemas/common/Language.ts\"\nimport type { LanguageDetection } from \"./schemas/common/LanguageDetection.ts\"\nimport { LanguagesResponseSchema } from \"./schemas/responses/LanguagesResponse.ts\"\nimport { TranslateBatchResponseSchema } from \"./schemas/responses/TranslateBatchResponse.ts\"\nimport {\n type TranslateRequest,\n TranslateRequestSchema,\n} from \"./schemas/requests/TranslateRequest.ts\"\nimport { TranslateResponseSchema } from \"./schemas/responses/TranslateResponse.ts\"\nimport type { TranslationFormat } from \"./schemas/common/TranslationFormat.ts\"\nimport type { LibreTranslateEndpoint, Translation } from \"./types.ts\"\n\n/** Options for the {@link LibreTranslateClient} constructor. */\nexport type LibreTranslateClientOptions = {\n /**\n * Root URL of the server, such as `https://libretranslate.com` or\n * `https://example.com/libretranslate/`. Endpoints resolve under its path, with or without a\n * trailing slash.\n */\n baseUrl: string | URL\n} & FullyUndefinable<{\n /** API key, sent as `api_key`. Public instances require one; self-hosted ones may not. */\n apiKey: string\n /**\n * `fetch` used for every request. Defaults to `globalThis.fetch`, read on each request, so\n * mocks installed after the client is created still apply.\n */\n fetch: typeof globalThis.fetch\n}>\n\n/** Options for {@link LibreTranslateClient.translate} and {@link LibreTranslateClient.translateBatch}. */\nexport type TranslateOptions = {\n /** Code of the language to translate into, such as `\"ru\"`. */\n target: string\n} & FullyUndefinable<{\n /** Code of the source language, or `\"auto\"` to let the server detect it. Defaults to `\"auto\"`. */\n source: string\n /** Format of the input. Defaults to `\"text\"`. */\n format: TranslationFormat\n /**\n * How many alternative translations to return per text, a non-negative integer; the server\n * may return fewer. Defaults to `0`. A server may cap it (`--alternatives-limit`, off by default) and answer with HTTP 400\n * above the cap.\n */\n alternatives: number\n /** Cancels the request; the call then rejects with `signal.reason`. */\n signal: AbortSignal\n}>\n\n/** Options for {@link LibreTranslateClient.detectLanguage}. */\nexport type DetectLanguageOptions = FullyUndefinable<{\n /** Cancels the request; the call then rejects with `signal.reason`. */\n signal: AbortSignal\n}>\n\n/** Options for {@link LibreTranslateClient.getLanguages}. */\nexport type GetLanguagesOptions = FullyUndefinable<{\n /** Cancels the request; the call then rejects with `signal.reason`. */\n signal: AbortSignal\n}>\n\n/**\n * Client for one LibreTranslate server.\n *\n * Every method rejects with {@link LibreTranslateError} when the server answers with an error\n * status or an unexpected body, with `signal.reason` when the signal aborts, and with the error\n * of `fetch` itself on network failures.\n *\n * @example\n * ```typescript\n * const client = new LibreTranslateClient({\n * baseUrl: \"https://libretranslate.com\",\n * apiKey: process.env.LIBRETRANSLATE_API_KEY,\n * })\n *\n * const { text } = await client.translate(\"Hello, world!\", { source: \"en\", target: \"ru\" })\n * ```\n */\nexport class LibreTranslateClient {\n // Fields\n\n readonly #baseUrl: URL\n readonly #apiKey: string | undefined\n readonly #fetch: typeof globalThis.fetch | undefined\n\n // Constructor\n\n /**\n * @param options - Server URL, API key and `fetch`.\n * @throws {TypeError} When `baseUrl` is not an absolute URL.\n */\n constructor({ baseUrl, apiKey, fetch }: Readonly<LibreTranslateClientOptions>) {\n // A fresh URL even for a URL argument: the trailing slash below must not mutate the caller's\n const url = URL.parse(String(baseUrl))\n if (url == null) throw new TypeError(`baseUrl must be an absolute URL, got ${String(baseUrl)}`)\n if (!url.pathname.endsWith(\"/\")) url.pathname += \"/\"\n\n this.#baseUrl = url\n this.#apiKey = apiKey\n this.#fetch = fetch\n }\n\n // Methods\n\n // - Public\n\n /**\n * Translates one text.\n *\n * @param text - Text to translate. The server rejects an empty string and a text over its\n * character limit with HTTP 400.\n * @param options - Target and source languages, format, alternatives and signal.\n * @returns The translation.\n * @throws {RangeError} When `alternatives` is not a non-negative integer.\n * @throws {LibreTranslateError} When the server rejects the request or answers with an\n * unexpected body.\n *\n * @example\n * ```typescript\n * const { text, detectedLanguage } = await client.translate(\"Привет, мир!\", { target: \"en\" })\n * // text: \"Hello, world!\", detectedLanguage: { language: \"ru\", confidence: 90 }\n * ```\n */\n async translate(text: string, options: Readonly<TranslateOptions>): Promise<Translation> {\n const request = this.#translateRequest(text, options)\n const response = await this.#send(\n \"/translate\",\n TranslateResponseSchema,\n request,\n options.signal\n )\n\n return {\n text: response.translatedText,\n alternatives: response.alternatives ?? [],\n detectedLanguage: response.detectedLanguage,\n }\n }\n\n /**\n * Translates several texts in one request.\n *\n * With `source: \"auto\"` the server detects one language for the whole batch, so every item\n * carries the same `detectedLanguage`. A server may cap the batch size (`--batch-limit`, off by\n * default) and answer with HTTP 400 above the cap.\n *\n * @param texts - Texts to translate. An empty array resolves to `[]` without a request.\n * @param options - Target and source languages, format, alternatives and signal.\n * @returns Translations in the order of `texts`.\n * @throws {RangeError} When `alternatives` is not a non-negative integer.\n * @throws {LibreTranslateError} When the server rejects the request or answers with an\n * unexpected body.\n *\n * @example\n * ```typescript\n * const translations = await client.translateBatch([\"Hello\", \"Goodbye\"], { target: \"ru\" })\n * translations.map(translation => translation.text) // [\"Привет\", \"До свидания\"]\n * ```\n */\n async translateBatch(\n texts: readonly string[],\n options: Readonly<TranslateOptions>\n ): Promise<Translation[]> {\n // Request\n\n const request = this.#translateRequest([...texts], options)\n\n if (texts.length === 0) {\n options.signal?.throwIfAborted()\n return []\n }\n\n const response = await this.#send(\n \"/translate\",\n TranslateBatchResponseSchema,\n request,\n options.signal\n )\n\n // Response\n\n const { translatedText, alternatives, detectedLanguage } = response\n\n if (translatedText.length !== texts.length) {\n throw LibreTranslateError.unexpectedBody({\n endpoint: \"/translate\",\n cause: new RangeError(\n `translatedText must have ${texts.length} items, got ${translatedText.length}`\n ),\n })\n }\n\n return translatedText.map((text, index) => ({\n text,\n alternatives: alternatives?.[index] ?? [],\n detectedLanguage: detectedLanguage?.[index],\n }))\n }\n\n /**\n * Detects the language of a text.\n *\n * @param text - Text to inspect. The server rejects an empty string with HTTP 400.\n * @param options - Signal.\n * @returns Candidate languages, most confident first. When nothing is detected the server\n * returns a single `{ language: \"en\", confidence: 0 }`.\n * @throws {LibreTranslateError} When the server rejects the request or answers with an\n * unexpected body.\n *\n * @example\n * ```typescript\n * const [best] = await client.detectLanguage(\"Доброе утро, как дела?\")\n * // best: { language: \"ru\", confidence: 43 }\n * ```\n */\n async detectLanguage(\n text: string,\n { signal }: Readonly<DetectLanguageOptions> = {}\n ): Promise<LanguageDetection[]> {\n const request: DetectRequest = { q: text, api_key: this.#apiKey }\n return await this.#send(\"/detect\", DetectResponseSchema, request, signal)\n }\n\n /**\n * Lists the languages the server translates from, each with the languages it translates into.\n *\n * @param options - Signal.\n * @returns Supported source languages.\n * @throws {LibreTranslateError} When the server rejects the request or answers with an\n * unexpected body.\n *\n * @example\n * ```typescript\n * const languages = await client.getLanguages()\n * const canTranslate = languages.some(({ code, targets }) => code === \"en\" && targets.includes(\"ru\"))\n * ```\n */\n async getLanguages({ signal }: Readonly<GetLanguagesOptions> = {}): Promise<Language[]> {\n return await this.#send(\"/languages\", LanguagesResponseSchema, undefined, signal)\n }\n\n // - Private\n\n /**\n * Builds the `/translate` body shared by single and batch requests.\n *\n * @param q - Text or texts to translate.\n * @param options - Translation options; `signal` is ignored.\n * @returns The request body, with the API key when the client has one.\n * @throws {RangeError} When `alternatives` is not a non-negative integer.\n */\n #translateRequest(\n q: TranslateRequest[\"q\"],\n { target, source = \"auto\", format = \"text\", alternatives = 0 }: Readonly<TranslateOptions>\n ): TranslateRequest {\n // The server would silently truncate 1.5 to 1 and clamp -1 to 0\n const check = TranslateRequestSchema.shape.alternatives.safeParse(alternatives)\n\n if (!check.success) {\n throw new RangeError(`alternatives must be a non-negative integer, got ${alternatives}`, {\n cause: check.error,\n })\n }\n\n return {\n q,\n source,\n target,\n format,\n alternatives: alternatives > 0 ? alternatives : undefined,\n api_key: this.#apiKey,\n }\n }\n\n /**\n * Sends a request and reads the response.\n *\n * A request with a body goes as a JSON `POST`; without one, as a `GET`. Fields set to\n * `undefined` are left out of the JSON.\n *\n * @param endpoint - Endpoint to call.\n * @param schema - Schema of a successful response body.\n * @param body - Request body, or `undefined` for a `GET`.\n * @param signal - Cancels the request and the reading of the response.\n * @returns The response body parsed by `schema`.\n * @throws {LibreTranslateError} When the status is not `2xx`, or the body is not JSON or does\n * not match `schema`.\n */\n async #send<Schema extends z.ZodType>(\n endpoint: LibreTranslateEndpoint,\n schema: Schema,\n body: TranslateRequest | DetectRequest | undefined,\n signal: AbortSignal | undefined\n ): Promise<z.output<Schema>> {\n // Request\n\n signal?.throwIfAborted()\n\n // A bare call: browser fetch throws \"Illegal invocation\" when `this` is not the global object\n const fetch = this.#fetch ?? globalThis.fetch\n const url = new URL(`.${endpoint}`, this.#baseUrl)\n const response = await fetch(\n url,\n body == null\n ? { signal: signal ?? null }\n : {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(body),\n signal: signal ?? null,\n }\n )\n\n // Body: `text()` follows the signal in real runtimes; the check covers mocks that do not\n\n const text = await response.text()\n signal?.throwIfAborted()\n\n let json: unknown\n\n try {\n json = JSON.parse(text)\n } catch (error) {\n if (response.ok) {\n throw LibreTranslateError.unexpectedBody({\n endpoint,\n status: response.status,\n cause: error,\n })\n }\n }\n\n // Error status\n\n if (!response.ok) {\n throw LibreTranslateError.fromResponse({\n endpoint,\n status: response.status,\n serverMessage: ErrorResponseSchema.safeParse(json).data?.error,\n })\n }\n\n // Validation\n\n const result = schema.safeParse(json)\n\n if (!result.success) {\n throw LibreTranslateError.unexpectedBody({\n endpoint,\n status: response.status,\n cause: result.error,\n })\n }\n\n return result.data\n }\n}\n"],"mappings":"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"}
|
package/package.json
CHANGED
|
@@ -3,8 +3,8 @@
|
|
|
3
3
|
"publishConfig": {
|
|
4
4
|
"access": "public"
|
|
5
5
|
},
|
|
6
|
-
"version": "
|
|
7
|
-
"description": "
|
|
6
|
+
"version": "2.0.0",
|
|
7
|
+
"description": "Typed client for the LibreTranslate API",
|
|
8
8
|
"author": "Maksim Victorovich Fomin",
|
|
9
9
|
"repository": {
|
|
10
10
|
"type": "git",
|