@translated/lara 1.8.0-beta.1 → 1.8.0-beta.2
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/lib/net/lara/browser-client.d.ts +2 -2
- package/lib/net/lara/browser-client.js +63 -21
- package/lib/net/lara/client.d.ts +9 -9
- package/lib/net/lara/client.js +16 -16
- package/lib/net/lara/node-client.d.ts +2 -2
- package/lib/net/lara/node-client.js +32 -4
- package/lib/translator.js +1 -1
- package/lib_browser/lara.min.js +1 -1
- package/package.json +1 -1
|
@@ -4,8 +4,8 @@ import { type BaseURL, type ClientResponse, LaraClient, type MultiPartFile } fro
|
|
|
4
4
|
export declare class BrowserLaraClient extends LaraClient {
|
|
5
5
|
private readonly baseUrl;
|
|
6
6
|
constructor(baseUrl: BaseURL, auth: AccessKey | AuthToken);
|
|
7
|
-
protected send(method: string, path: string, headers: Record<string, string>, body?: Record<string, any
|
|
8
|
-
protected sendAndGetStream(method: string, path: string, headers: Record<string, string>, body?: Record<string, any
|
|
7
|
+
protected send(method: string, path: string, headers: Record<string, string>, body?: Record<string, any>, timeout?: number): Promise<ClientResponse>;
|
|
8
|
+
protected sendAndGetStream(method: string, path: string, headers: Record<string, string>, body?: Record<string, any>, timeout?: number): AsyncGenerator<ClientResponse>;
|
|
9
9
|
protected wrapMultiPartFile(file: MultiPartFile): File;
|
|
10
10
|
}
|
|
11
11
|
export declare class BrowserClient {
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.BrowserClient = exports.BrowserLaraClient = void 0;
|
|
4
|
+
const errors_1 = require("../../errors");
|
|
4
5
|
const client_1 = require("./client");
|
|
5
6
|
function hasDefaultPort(port, secure) {
|
|
6
7
|
return (port === 80 && !secure) || (port === 443 && secure);
|
|
@@ -14,7 +15,7 @@ class BrowserLaraClient extends client_1.LaraClient {
|
|
|
14
15
|
url += `:${baseUrl.port}`;
|
|
15
16
|
this.baseUrl = url;
|
|
16
17
|
}
|
|
17
|
-
async send(method, path, headers, body) {
|
|
18
|
+
async send(method, path, headers, body, timeout) {
|
|
18
19
|
var _a;
|
|
19
20
|
let requestBody;
|
|
20
21
|
if (body) {
|
|
@@ -38,27 +39,47 @@ class BrowserLaraClient extends client_1.LaraClient {
|
|
|
38
39
|
requestBody = JSON.stringify(body, undefined, 0);
|
|
39
40
|
}
|
|
40
41
|
}
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
42
|
+
// Set up abort controller for timeout
|
|
43
|
+
let abortController;
|
|
44
|
+
let timeoutId;
|
|
45
|
+
if (timeout && timeout > 0) {
|
|
46
|
+
abortController = new AbortController();
|
|
47
|
+
timeoutId = setTimeout(() => abortController.abort(), timeout);
|
|
48
|
+
}
|
|
49
|
+
try {
|
|
50
|
+
const response = await fetch(this.baseUrl + path, {
|
|
51
|
+
headers,
|
|
52
|
+
method,
|
|
53
|
+
body: requestBody,
|
|
54
|
+
signal: abortController === null || abortController === void 0 ? void 0 : abortController.signal
|
|
55
|
+
});
|
|
56
|
+
if (timeoutId)
|
|
57
|
+
clearTimeout(timeoutId);
|
|
58
|
+
if ((_a = response.headers.get("Content-Type")) === null || _a === void 0 ? void 0 : _a.includes("text/csv")) {
|
|
59
|
+
return {
|
|
60
|
+
statusCode: response.status,
|
|
61
|
+
body: {
|
|
62
|
+
content: await response.text()
|
|
63
|
+
},
|
|
64
|
+
headers: Object.fromEntries(response.headers)
|
|
65
|
+
};
|
|
66
|
+
}
|
|
47
67
|
return {
|
|
48
68
|
statusCode: response.status,
|
|
49
|
-
body:
|
|
50
|
-
content: await response.text()
|
|
51
|
-
},
|
|
69
|
+
body: await response.json(),
|
|
52
70
|
headers: Object.fromEntries(response.headers)
|
|
53
71
|
};
|
|
54
72
|
}
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
73
|
+
catch (err) {
|
|
74
|
+
if (timeoutId)
|
|
75
|
+
clearTimeout(timeoutId);
|
|
76
|
+
if (err instanceof Error && err.name === "AbortError") {
|
|
77
|
+
throw new errors_1.TimeoutError(`Request timed out after ${timeout}ms`);
|
|
78
|
+
}
|
|
79
|
+
throw err;
|
|
80
|
+
}
|
|
60
81
|
}
|
|
61
|
-
async *sendAndGetStream(method, path, headers, body) {
|
|
82
|
+
async *sendAndGetStream(method, path, headers, body, timeout) {
|
|
62
83
|
let requestBody;
|
|
63
84
|
if (body) {
|
|
64
85
|
if (headers["Content-Type"] === "multipart/form-data") {
|
|
@@ -81,11 +102,32 @@ class BrowserLaraClient extends client_1.LaraClient {
|
|
|
81
102
|
requestBody = JSON.stringify(body, undefined, 0);
|
|
82
103
|
}
|
|
83
104
|
}
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
105
|
+
// Set up abort controller for timeout
|
|
106
|
+
let abortController;
|
|
107
|
+
let timeoutId;
|
|
108
|
+
if (timeout && timeout > 0) {
|
|
109
|
+
abortController = new AbortController();
|
|
110
|
+
timeoutId = setTimeout(() => abortController.abort(), timeout);
|
|
111
|
+
}
|
|
112
|
+
let response;
|
|
113
|
+
try {
|
|
114
|
+
response = await fetch(this.baseUrl + path, {
|
|
115
|
+
headers,
|
|
116
|
+
method,
|
|
117
|
+
body: requestBody,
|
|
118
|
+
signal: abortController === null || abortController === void 0 ? void 0 : abortController.signal
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
catch (err) {
|
|
122
|
+
if (timeoutId)
|
|
123
|
+
clearTimeout(timeoutId);
|
|
124
|
+
if (err instanceof Error && err.name === "AbortError") {
|
|
125
|
+
throw new errors_1.TimeoutError(`Request timed out after ${timeout}ms`);
|
|
126
|
+
}
|
|
127
|
+
throw err;
|
|
128
|
+
}
|
|
129
|
+
if (timeoutId)
|
|
130
|
+
clearTimeout(timeoutId);
|
|
89
131
|
if (!response.body) {
|
|
90
132
|
throw new Error("Response body is not available for streaming");
|
|
91
133
|
}
|
package/lib/net/lara/client.d.ts
CHANGED
|
@@ -27,13 +27,13 @@ export declare abstract class LaraClient {
|
|
|
27
27
|
private authenticationPromise?;
|
|
28
28
|
protected constructor(auth: AccessKey | AuthToken);
|
|
29
29
|
setExtraHeader(name: string, value: string): void;
|
|
30
|
-
get<T>(path: string, queryParams?: Record<string, any>, headers?: Record<string, string
|
|
31
|
-
delete<T>(path: string, queryParams?: Record<string, any>, body?: Record<string, any>, headers?: Record<string, string
|
|
32
|
-
post<T>(path: string, body?: Record<string, any>, files?: Record<string, MultiPartFile>, headers?: Record<string, string
|
|
33
|
-
postAndGetStream<T>(path: string, body?: Record<string, any>, files?: Record<string, MultiPartFile>, headers?: Record<string, string
|
|
34
|
-
put<T>(path: string, body?: Record<string, any>, files?: Record<string, MultiPartFile>, headers?: Record<string, string
|
|
35
|
-
protected request<T>(method: HttpMethod, path: string, body?: Record<string, any>, files?: Record<string, MultiPartFile>, headers?: Record<string, string
|
|
36
|
-
protected requestStream<T>(method: HttpMethod, path: string, body?: Record<string, any>, files?: Record<string, MultiPartFile>, headers?: Record<string, string
|
|
30
|
+
get<T>(path: string, queryParams?: Record<string, any>, headers?: Record<string, string>, timeout?: number): Promise<T>;
|
|
31
|
+
delete<T>(path: string, queryParams?: Record<string, any>, body?: Record<string, any>, headers?: Record<string, string>, timeout?: number): Promise<T>;
|
|
32
|
+
post<T>(path: string, body?: Record<string, any>, files?: Record<string, MultiPartFile>, headers?: Record<string, string>, timeout?: number): Promise<T>;
|
|
33
|
+
postAndGetStream<T>(path: string, body?: Record<string, any>, files?: Record<string, MultiPartFile>, headers?: Record<string, string>, timeout?: number): AsyncGenerator<T>;
|
|
34
|
+
put<T>(path: string, body?: Record<string, any>, files?: Record<string, MultiPartFile>, headers?: Record<string, string>, timeout?: number): Promise<T>;
|
|
35
|
+
protected request<T>(method: HttpMethod, path: string, body?: Record<string, any>, files?: Record<string, MultiPartFile>, headers?: Record<string, string>, timeout?: number): Promise<T>;
|
|
36
|
+
protected requestStream<T>(method: HttpMethod, path: string, body?: Record<string, any>, files?: Record<string, MultiPartFile>, headers?: Record<string, string>, timeout?: number): AsyncGenerator<T>;
|
|
37
37
|
private ensureAuthenticated;
|
|
38
38
|
private performAuthentication;
|
|
39
39
|
private refreshTokens;
|
|
@@ -46,8 +46,8 @@ export declare abstract class LaraClient {
|
|
|
46
46
|
private handleAuthResponse;
|
|
47
47
|
private createApiError;
|
|
48
48
|
private sign;
|
|
49
|
-
protected abstract send(method: HttpMethod, path: string, headers: Record<string, string>, body?: Record<string, any
|
|
50
|
-
protected abstract sendAndGetStream(method: HttpMethod, path: string, headers: Record<string, string>, body?: Record<string, any
|
|
49
|
+
protected abstract send(method: HttpMethod, path: string, headers: Record<string, string>, body?: Record<string, any>, timeout?: number): Promise<ClientResponse>;
|
|
50
|
+
protected abstract sendAndGetStream(method: HttpMethod, path: string, headers: Record<string, string>, body?: Record<string, any>, timeout?: number): AsyncGenerator<ClientResponse>;
|
|
51
51
|
protected abstract wrapMultiPartFile(file: MultiPartFile): any;
|
|
52
52
|
}
|
|
53
53
|
export {};
|
package/lib/net/lara/client.js
CHANGED
|
@@ -30,33 +30,33 @@ class LaraClient {
|
|
|
30
30
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
31
31
|
// Public HTTP Methods
|
|
32
32
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
33
|
-
get(path, queryParams, headers) {
|
|
34
|
-
return this.request("GET", this.buildPathWithQuery(path, queryParams), undefined, undefined, headers);
|
|
33
|
+
get(path, queryParams, headers, timeout) {
|
|
34
|
+
return this.request("GET", this.buildPathWithQuery(path, queryParams), undefined, undefined, headers, timeout);
|
|
35
35
|
}
|
|
36
|
-
delete(path, queryParams, body, headers) {
|
|
37
|
-
return this.request("DELETE", this.buildPathWithQuery(path, queryParams), body, undefined, headers);
|
|
36
|
+
delete(path, queryParams, body, headers, timeout) {
|
|
37
|
+
return this.request("DELETE", this.buildPathWithQuery(path, queryParams), body, undefined, headers, timeout);
|
|
38
38
|
}
|
|
39
|
-
post(path, body, files, headers) {
|
|
40
|
-
return this.request("POST", path, body, files, headers);
|
|
39
|
+
post(path, body, files, headers, timeout) {
|
|
40
|
+
return this.request("POST", path, body, files, headers, timeout);
|
|
41
41
|
}
|
|
42
|
-
async *postAndGetStream(path, body, files, headers) {
|
|
43
|
-
for await (const chunk of this.requestStream("POST", path, body, files, headers)) {
|
|
42
|
+
async *postAndGetStream(path, body, files, headers, timeout) {
|
|
43
|
+
for await (const chunk of this.requestStream("POST", path, body, files, headers, timeout)) {
|
|
44
44
|
yield chunk;
|
|
45
45
|
}
|
|
46
46
|
}
|
|
47
|
-
put(path, body, files, headers) {
|
|
48
|
-
return this.request("PUT", path, body, files, headers);
|
|
47
|
+
put(path, body, files, headers, timeout) {
|
|
48
|
+
return this.request("PUT", path, body, files, headers, timeout);
|
|
49
49
|
}
|
|
50
50
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
51
51
|
// Request Handling
|
|
52
52
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
53
|
-
async request(method, path, body, files, headers) {
|
|
53
|
+
async request(method, path, body, files, headers, timeout) {
|
|
54
54
|
await this.ensureAuthenticated();
|
|
55
55
|
const normalizedPath = path.startsWith("/") ? path : `/${path}`;
|
|
56
56
|
const requestHeaders = await this.buildRequestHeaders(body, files, headers);
|
|
57
57
|
const requestBody = this.buildRequestBody(body, files);
|
|
58
58
|
requestHeaders.Authorization = `Bearer ${this.token}`;
|
|
59
|
-
const response = await this.send(method, normalizedPath, requestHeaders, requestBody);
|
|
59
|
+
const response = await this.send(method, normalizedPath, requestHeaders, requestBody, timeout);
|
|
60
60
|
if (this.isSuccessResponse(response)) {
|
|
61
61
|
return (0, parse_content_1.parseContent)(response.body);
|
|
62
62
|
}
|
|
@@ -64,22 +64,22 @@ class LaraClient {
|
|
|
64
64
|
if (response.statusCode === 401) {
|
|
65
65
|
this.token = undefined;
|
|
66
66
|
await this.refreshTokens();
|
|
67
|
-
return this.request(method, path, body, files, headers);
|
|
67
|
+
return this.request(method, path, body, files, headers, timeout);
|
|
68
68
|
}
|
|
69
69
|
throw this.createApiError(response);
|
|
70
70
|
}
|
|
71
|
-
async *requestStream(method, path, body, files, headers) {
|
|
71
|
+
async *requestStream(method, path, body, files, headers, timeout) {
|
|
72
72
|
await this.ensureAuthenticated();
|
|
73
73
|
const normalizedPath = path.startsWith("/") ? path : `/${path}`;
|
|
74
74
|
const requestHeaders = await this.buildRequestHeaders(body, files, headers);
|
|
75
75
|
const requestBody = this.buildRequestBody(body, files);
|
|
76
76
|
requestHeaders.Authorization = `Bearer ${this.token}`;
|
|
77
|
-
for await (const chunk of this.sendAndGetStream(method, normalizedPath, requestHeaders, requestBody)) {
|
|
77
|
+
for await (const chunk of this.sendAndGetStream(method, normalizedPath, requestHeaders, requestBody, timeout)) {
|
|
78
78
|
// Handle 401 - token expired, refresh and retry once
|
|
79
79
|
if (chunk.statusCode === 401) {
|
|
80
80
|
this.token = undefined;
|
|
81
81
|
await this.refreshTokens();
|
|
82
|
-
yield* this.requestStream(method, path, body, files, headers);
|
|
82
|
+
yield* this.requestStream(method, path, body, files, headers, timeout);
|
|
83
83
|
return;
|
|
84
84
|
}
|
|
85
85
|
// Handle other errors
|
|
@@ -6,8 +6,8 @@ export declare class NodeLaraClient extends LaraClient {
|
|
|
6
6
|
private readonly baseUrl;
|
|
7
7
|
private readonly agent;
|
|
8
8
|
constructor(baseUrl: BaseURL, auth: AccessKey | AuthToken);
|
|
9
|
-
protected send(method: string, path: string, headers: Record<string, string>, body?: Record<string, any
|
|
10
|
-
protected sendAndGetStream(method: string, path: string, headers: Record<string, string>, body?: Record<string, any
|
|
9
|
+
protected send(method: string, path: string, headers: Record<string, string>, body?: Record<string, any>, timeout?: number): Promise<ClientResponse>;
|
|
10
|
+
protected sendAndGetStream(method: string, path: string, headers: Record<string, string>, body?: Record<string, any>, timeout?: number): AsyncGenerator<ClientResponse>;
|
|
11
11
|
protected wrapMultiPartFile(file: MultiPartFile): Readable;
|
|
12
12
|
}
|
|
13
13
|
export declare class NodeClient {
|
|
@@ -9,6 +9,7 @@ const node_http_1 = __importDefault(require("node:http"));
|
|
|
9
9
|
const node_https_1 = __importDefault(require("node:https"));
|
|
10
10
|
const node_stream_1 = require("node:stream");
|
|
11
11
|
const form_data_1 = __importDefault(require("form-data"));
|
|
12
|
+
const errors_1 = require("../../errors");
|
|
12
13
|
const client_1 = require("./client");
|
|
13
14
|
/** @internal */
|
|
14
15
|
class NodeLaraClient extends client_1.LaraClient {
|
|
@@ -17,7 +18,7 @@ class NodeLaraClient extends client_1.LaraClient {
|
|
|
17
18
|
this.baseUrl = baseUrl;
|
|
18
19
|
this.agent = baseUrl.secure ? new node_https_1.default.Agent({ keepAlive: true }) : new node_http_1.default.Agent({ keepAlive: true });
|
|
19
20
|
}
|
|
20
|
-
async send(method, path, headers, body) {
|
|
21
|
+
async send(method, path, headers, body, timeout) {
|
|
21
22
|
let requestBody;
|
|
22
23
|
if (body) {
|
|
23
24
|
if (headers["Content-Type"] === "multipart/form-data") {
|
|
@@ -81,7 +82,21 @@ class NodeLaraClient extends client_1.LaraClient {
|
|
|
81
82
|
}
|
|
82
83
|
});
|
|
83
84
|
});
|
|
84
|
-
req.on("error",
|
|
85
|
+
req.on("error", (err) => {
|
|
86
|
+
if (err.code === "ECONNRESET" && req.__timeoutTriggered) {
|
|
87
|
+
reject(new errors_1.TimeoutError(`Request timed out after ${timeout}ms`));
|
|
88
|
+
}
|
|
89
|
+
else {
|
|
90
|
+
reject(err);
|
|
91
|
+
}
|
|
92
|
+
});
|
|
93
|
+
// Set timeout if provided and positive
|
|
94
|
+
if (timeout && timeout > 0) {
|
|
95
|
+
req.setTimeout(timeout, () => {
|
|
96
|
+
req.__timeoutTriggered = true;
|
|
97
|
+
req.destroy();
|
|
98
|
+
});
|
|
99
|
+
}
|
|
85
100
|
if (requestBody instanceof form_data_1.default) {
|
|
86
101
|
requestBody.pipe(req);
|
|
87
102
|
}
|
|
@@ -94,7 +109,7 @@ class NodeLaraClient extends client_1.LaraClient {
|
|
|
94
109
|
}
|
|
95
110
|
});
|
|
96
111
|
}
|
|
97
|
-
async *sendAndGetStream(method, path, headers, body) {
|
|
112
|
+
async *sendAndGetStream(method, path, headers, body, timeout) {
|
|
98
113
|
let requestBody;
|
|
99
114
|
if (body) {
|
|
100
115
|
if (headers["Content-Type"] === "multipart/form-data") {
|
|
@@ -182,12 +197,25 @@ class NodeLaraClient extends client_1.LaraClient {
|
|
|
182
197
|
});
|
|
183
198
|
});
|
|
184
199
|
req.on("error", (err) => {
|
|
185
|
-
|
|
200
|
+
if (err.code === "ECONNRESET" && req.__timeoutTriggered) {
|
|
201
|
+
console.log('timeout triggered');
|
|
202
|
+
streamError = new errors_1.TimeoutError(`Request timed out after ${timeout}ms`);
|
|
203
|
+
}
|
|
204
|
+
else {
|
|
205
|
+
streamError = err;
|
|
206
|
+
}
|
|
186
207
|
if (resolveChunk) {
|
|
187
208
|
resolveChunk();
|
|
188
209
|
resolveChunk = null;
|
|
189
210
|
}
|
|
190
211
|
});
|
|
212
|
+
// Set timeout if provided and positive
|
|
213
|
+
if (timeout && timeout > 0) {
|
|
214
|
+
req.setTimeout(timeout, () => {
|
|
215
|
+
req.__timeoutTriggered = true;
|
|
216
|
+
req.destroy();
|
|
217
|
+
});
|
|
218
|
+
}
|
|
191
219
|
if (requestBody instanceof form_data_1.default) {
|
|
192
220
|
requestBody.pipe(req);
|
|
193
221
|
}
|
package/lib/translator.js
CHANGED
|
@@ -80,7 +80,7 @@ class Translator {
|
|
|
80
80
|
verbose: options === null || options === void 0 ? void 0 : options.verbose,
|
|
81
81
|
style: options === null || options === void 0 ? void 0 : options.style,
|
|
82
82
|
reasoning: options === null || options === void 0 ? void 0 : options.reasoning
|
|
83
|
-
}, undefined, headers);
|
|
83
|
+
}, undefined, headers, options === null || options === void 0 ? void 0 : options.timeoutInMillis);
|
|
84
84
|
let lastResult;
|
|
85
85
|
for await (const partial of response) {
|
|
86
86
|
if (callback)
|
package/lib_browser/lara.min.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.Lara=t():e.Lara=t()}(this,()=>(()=>{"use strict";var e={50:function(e,t,r){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Documents=t.DocumentStatus=void 0;const s=r(725),o=n(r(821)),i=n(r(841));var a;!function(e){e.INITIALIZED="initialized",e.ANALYZING="analyzing",e.PAUSED="paused",e.READY="ready",e.TRANSLATING="translating",e.TRANSLATED="translated",e.ERROR="error"}(a||(t.DocumentStatus=a={})),t.Documents=class{constructor(e){this.client=e,this.s3Client=(0,o.default)()}async upload(e,t,r,n,s){const{url:o,fields:a}=await this.client.get("/v2/documents/upload-url",{filename:t});await this.s3Client.upload(o,a,e,null==s?void 0:s.contentLength);const c=(null==s?void 0:s.noTrace)?{"X-No-Trace":"true"}:{};return this.client.post("/v2/documents",{source:r,target:n,s3key:a.key,adapt_to:null==s?void 0:s.adaptTo,glossaries:null==s?void 0:s.glossaries,style:null==s?void 0:s.style,password:null==s?void 0:s.password,extraction_params:(null==s?void 0:s.extractionParams)?(0,i.default)(s.extractionParams):void 0},void 0,c)}async status(e){return await this.client.get(`/v2/documents/${e}`)}async download(e,t){const{url:r}=await this.client.get(`/v2/documents/${e}/download-url`,{output_format:null==t?void 0:t.outputFormat});return await this.s3Client.download(r)}async downloadStream(e,t){const{url:r}=await this.client.get(`/v2/documents/${e}/download-url`,{output_format:null==t?void 0:t.outputFormat});return await this.s3Client.downloadStream(r)}async translate(e,t,r,n,o){const i={adaptTo:null==o?void 0:o.adaptTo,glossaries:null==o?void 0:o.glossaries,noTrace:null==o?void 0:o.noTrace,style:null==o?void 0:o.style,password:null==o?void 0:o.password,extractionParams:null==o?void 0:o.extractionParams,contentLength:null==o?void 0:o.contentLength},{id:c}=await this.upload(e,t,r,n,i),u=(null==o?void 0:o.outputFormat)?{outputFormat:o.outputFormat}:void 0,l=Date.now();for(;Date.now()-l<9e5;){await new Promise(e=>setTimeout(e,2e3));const{status:e,errorReason:t}=await this.status(c);if(e===a.TRANSLATED)return await this.download(c,u);if(e===a.ERROR)throw new s.LaraApiError(500,"DocumentError",t)}throw new s.TimeoutError}async translateStream(e,t,r,n,o){const i={adaptTo:null==o?void 0:o.adaptTo,glossaries:null==o?void 0:o.glossaries,noTrace:null==o?void 0:o.noTrace,style:null==o?void 0:o.style,password:null==o?void 0:o.password,extractionParams:null==o?void 0:o.extractionParams,contentLength:null==o?void 0:o.contentLength},{id:c}=await this.upload(e,t,r,n,i),u=(null==o?void 0:o.outputFormat)?{outputFormat:o.outputFormat}:void 0,l=Date.now();for(;Date.now()-l<9e5;){await new Promise(e=>setTimeout(e,2e3));const{status:e,errorReason:t}=await this.status(c);if(e===a.TRANSLATED)return await this.downloadStream(c,u);if(e===a.ERROR)throw new s.LaraApiError(500,"DocumentError",t)}throw new s.TimeoutError}}},221:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DEFAULT_BASE_URL=void 0,t.DEFAULT_BASE_URL="https://api.laratranslate.com"},311:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.version=void 0,t.version="1.8.0-beta.1"},326:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(){return void 0===s&&(s=new n.BrowserCrypto),s};const n=r(780);let s},343:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BrowserS3Client=void 0;const n=r(364);class s extends n.S3Client{async _upload(e,t,r){const n=new FormData;for(const[e,r]of Object.entries(t))n.append(e,r);n.append("file",r),await fetch(e,{method:"POST",body:n})}async download(e){return(await fetch(e)).blob()}async downloadStream(e){const t=await fetch(e);if(!t.body)throw new Error("Response body is null");return t.body}wrapMultiPartFile(e){if(e instanceof File)return e;throw new TypeError(`Invalid file input in the browser. Expected an instance of File but received ${typeof e}.`)}}t.BrowserS3Client=s},364:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.S3Client=void 0,t.S3Client=class{async upload(e,t,r,n){return this._upload(e,t,this.wrapMultiPartFile(r),n)}}},412:function(e,t,r){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.LaraClient=void 0;const s=r(414),o=n(r(326)),i=r(725),a=r(741),c=r(311);t.LaraClient=class{constructor(e){if(this.crypto=(0,o.default)(),this.extraHeaders={},e instanceof s.AccessKey)this.accessKey=e;else{if(!(e instanceof s.AuthToken))throw new Error("Invalid authentication method provided");this.authToken=e}}setExtraHeader(e,t){this.extraHeaders[e]=t}get(e,t,r){return this.request("GET",this.buildPathWithQuery(e,t),void 0,void 0,r)}delete(e,t,r,n){return this.request("DELETE",this.buildPathWithQuery(e,t),r,void 0,n)}post(e,t,r,n){return this.request("POST",e,t,r,n)}async*postAndGetStream(e,t,r,n){for await(const s of this.requestStream("POST",e,t,r,n))yield s}put(e,t,r,n){return this.request("PUT",e,t,r,n)}async request(e,t,r,n,s){await this.ensureAuthenticated();const o=t.startsWith("/")?t:`/${t}`,i=await this.buildRequestHeaders(r,n,s),c=this.buildRequestBody(r,n);i.Authorization=`Bearer ${this.token}`;const u=await this.send(e,o,i,c);if(this.isSuccessResponse(u))return(0,a.parseContent)(u.body);if(401===u.statusCode)return this.token=void 0,await this.refreshTokens(),this.request(e,t,r,n,s);throw this.createApiError(u)}async*requestStream(e,t,r,n,s){await this.ensureAuthenticated();const o=t.startsWith("/")?t:`/${t}`,i=await this.buildRequestHeaders(r,n,s),c=this.buildRequestBody(r,n);i.Authorization=`Bearer ${this.token}`;for await(const u of this.sendAndGetStream(e,o,i,c)){if(401===u.statusCode)return this.token=void 0,await this.refreshTokens(),void(yield*this.requestStream(e,t,r,n,s));if(!this.isSuccessResponse(u))throw this.createApiError(u);yield(0,a.parseContent)(u.body)}}async ensureAuthenticated(){if(!this.token){if(this.authenticationPromise)return this.authenticationPromise;this.authenticationPromise=this.performAuthentication();try{await this.authenticationPromise}catch(e){if(this.authenticationPromise=void 0,e instanceof i.LaraApiError&&(401===e.statusCode||403===e.statusCode))throw e;try{this.authenticationPromise=this.performAuthentication(),await this.authenticationPromise}catch(e){throw this.authenticationPromise=void 0,e instanceof i.LaraApiError?e:new i.LaraApiError(500,"AuthenticationError",e.message)}}}}async performAuthentication(){if(this.refreshToken)return this.refreshTokens();if(this.authToken)return this.token=this.authToken.token,this.refreshToken=this.authToken.refreshToken,void(this.authToken=void 0);if(this.accessKey)return this.authenticateWithAccessKey();throw new Error("No authentication method provided")}async refreshTokens(){const e={Authorization:`Bearer ${this.refreshToken}`,"X-Lara-Date":(new Date).toUTCString()},t=await this.send("POST","/v2/auth/refresh",e);this.handleAuthResponse(t)}async authenticateWithAccessKey(){if(!this.accessKey)throw new Error("No access key provided");const e={id:this.accessKey.id},t=await this.crypto.digestBase64(JSON.stringify(e)),r={"Content-Type":"application/json","X-Lara-Date":(new Date).toUTCString(),"Content-MD5":t};r.Authorization=`Lara:${await this.sign("POST","/v2/auth",r)}`;const n=await this.send("POST","/v2/auth",r,e);this.handleAuthResponse(n)}buildPathWithQuery(e,t){const r=this.filterNullish(t);return r?`${e}?${new URLSearchParams(r).toString()}`:e}async buildRequestHeaders(e,t,r){const n={"X-Lara-Date":(new Date).toUTCString(),"X-Lara-SDK-Name":"lara-node","X-Lara-SDK-Version":c.version,...this.extraHeaders,...r},s=this.filterNullish(e);if(t)n["Content-Type"]="multipart/form-data";else if(s){n["Content-Type"]="application/json";const e=JSON.stringify(s,void 0,0);n["Content-Length"]=(new TextEncoder).encode(e).length.toString()}return n}buildRequestBody(e,t){const r=this.filterNullish(e);if(t){const e={};for(const[r,n]of Object.entries(t))e[r]=this.wrapMultiPartFile(n);return{...e,...r}}return r}filterNullish(e){if(!e)return;const t=Object.fromEntries(Object.entries(e).filter(([e,t])=>null!=t));return Object.keys(t).length>0?t:void 0}isSuccessResponse(e){return e.statusCode>=200&&e.statusCode<300}handleAuthResponse(e){if(this.isSuccessResponse(e))return this.token=e.body.token,void(this.refreshToken=e.headers["x-lara-refresh-token"]);throw this.createApiError(e)}createApiError(e){var t;const r=(null===(t=e.body)||void 0===t?void 0:t.error)||{};return new i.LaraApiError(e.statusCode,r.type||"UnknownError",r.message||"An unknown error occurred")}async sign(e,t,r){if(!this.accessKey)throw new Error("Access key not provided for signing");const n=r["X-Lara-Date"].trim(),s=(r["Content-MD5"]||"").trim(),o=(r["Content-Type"]||"").trim(),i=`${(r["X-HTTP-Method-Override"]||e).trim().toUpperCase()}\n${t}\n${s}\n${o}\n${n}`;return this.crypto.hmac(this.accessKey.secret,i)}}},414:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AuthToken=t.Credentials=t.AccessKey=void 0;class r{constructor(e,t){this.id=e,this.secret=t}}t.AccessKey=r,t.Credentials=class extends r{get accessKeyId(){return this.id}get accessKeySecret(){return this.secret}},t.AuthToken=class{constructor(e,t){this.token=e,this.refreshToken=t}}},514:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Glossaries=void 0;const n=r(725);t.Glossaries=class{constructor(e){this.client=e,this.pollingInterval=2e3}async list(){return await this.client.get("/v2/glossaries")}async create(e){return await this.client.post("/v2/glossaries",{name:e})}async get(e){try{return await this.client.get(`/v2/glossaries/${e}`)}catch(e){if(e instanceof n.LaraApiError&&404===e.statusCode)return null;throw e}}async delete(e){return await this.client.delete(`/v2/glossaries/${e}`)}async update(e,t){return await this.client.put(`/v2/glossaries/${e}`,{name:t})}async importCsv(e,t,r=!1){return await this.client.post(`/v2/glossaries/${e}/import`,{compression:r?"gzip":void 0},{csv:t})}async getImportStatus(e){return await this.client.get(`/v2/glossaries/imports/${e}`)}async waitForImport(e,t,r){const s=Date.now();for(;e.progress<1;){if(r&&Date.now()-s>r)throw new n.TimeoutError;await new Promise(e=>setTimeout(e,this.pollingInterval)),e=await this.getImportStatus(e.id),t&&t(e)}return e}async counts(e){return await this.client.get(`/v2/glossaries/${e}/counts`)}async export(e,t,r){return await this.client.get(`/v2/glossaries/${e}/export`,{content_type:t,source:r})}}},629:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Memories=void 0;const n=r(725);t.Memories=class{constructor(e){this.client=e,this.pollingInterval=2e3}async list(){return await this.client.get("/v2/memories")}async create(e,t){return await this.client.post("/v2/memories",{name:e,external_id:t})}async get(e){try{return await this.client.get(`/v2/memories/${e}`)}catch(e){if(e instanceof n.LaraApiError&&404===e.statusCode)return null;throw e}}async delete(e){return await this.client.delete(`/v2/memories/${e}`)}async update(e,t){return await this.client.put(`/v2/memories/${e}`,{name:t})}async connect(e){const t=await this.client.post("/v2/memories/connect",{ids:Array.isArray(e)?e:[e]});return Array.isArray(e)?t:t[0]}async importTmx(e,t,r=!1){return await this.client.post(`/v2/memories/${e}/import`,{compression:r?"gzip":void 0},{tmx:t})}async addTranslation(e,t,r,n,s,o,i,a,c){const u={source:t,target:r,sentence:n,translation:s,tuid:o,sentence_before:i,sentence_after:a};return Array.isArray(e)?(u.ids=e,await this.client.put("/v2/memories/content",u,void 0,c)):await this.client.put(`/v2/memories/${e}/content`,u,void 0,c)}async deleteTranslation(e,t,r,n,s,o,i,a){const c={source:t,target:r,sentence:n,translation:s,tuid:o,sentence_before:i,sentence_after:a};return Array.isArray(e)?(c.ids=e,await this.client.delete("/v2/memories/content",void 0,c)):await this.client.delete(`/v2/memories/${e}/content`,void 0,c)}async getImportStatus(e){return await this.client.get(`/v2/memories/imports/${e}`)}async waitForImport(e,t,r){const s=Date.now();for(;e.progress<1;){if(r&&Date.now()-s>r)throw new n.TimeoutError;await new Promise(e=>setTimeout(e,this.pollingInterval)),e=await this.getImportStatus(e.id),t&&t(e)}return e}}},631:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BrowserClient=t.BrowserLaraClient=void 0;const n=r(412);class s extends n.LaraClient{constructor(e,t){super(t);let r=`${e.secure?"https":"http"}://${e.hostname}`;var n,s;n=e.port,s=e.secure,80===n&&!s||443===n&&s||(r+=`:${e.port}`),this.baseUrl=r}async send(e,t,r,n){var s;let o;if(n)if("multipart/form-data"===r["Content-Type"]){delete r["Content-Type"];const e=new FormData;for(const[t,r]of Object.entries(n))if(r)if(Array.isArray(r))for(const n of r)e.append(t,n);else e.append(t,r);o=e}else o=JSON.stringify(n,void 0,0);const i=await fetch(this.baseUrl+t,{headers:r,method:e,body:o});return(null===(s=i.headers.get("Content-Type"))||void 0===s?void 0:s.includes("text/csv"))?{statusCode:i.status,body:{content:await i.text()},headers:Object.fromEntries(i.headers)}:{statusCode:i.status,body:await i.json(),headers:Object.fromEntries(i.headers)}}async*sendAndGetStream(e,t,r,n){let s;if(n)if("multipart/form-data"===r["Content-Type"]){delete r["Content-Type"];const e=new FormData;for(const[t,r]of Object.entries(n))if(r)if(Array.isArray(r))for(const n of r)e.append(t,n);else e.append(t,r);s=e}else s=JSON.stringify(n,void 0,0);const o=await fetch(this.baseUrl+t,{headers:r,method:e,body:s});if(!o.body)throw new Error("Response body is not available for streaming");const i=o.body.getReader(),a=new TextDecoder;let c="";try{for(;;){const{done:e,value:t}=await i.read();if(e){if(c.trim())try{const e=JSON.parse(c);console.log(e),yield{statusCode:e.status||o.status,body:e.data||e,headers:Object.fromEntries(o.headers)}}catch(e){}break}c+=a.decode(t,{stream:!0});const r=c.split("\n");c=r.pop()||"";for(const e of r)if(e.trim())try{const t=JSON.parse(e);yield{statusCode:t.status||o.status,body:t.data||t,headers:Object.fromEntries(o.headers)}}catch(e){}}}finally{i.releaseLock()}}wrapMultiPartFile(e){if(e instanceof File)return e;throw new TypeError(`Invalid file input in the browser. Expected an instance of File but received ${typeof e}.`)}}t.BrowserLaraClient=s;class o{static async get(e,t){return o.send("GET",e,t)}static async send(e,t,r,n){var s;let o;if(n)if(r&&"multipart/form-data"===r["Content-Type"]){delete r["Content-Type"];const e=new FormData;for(const[t,r]of Object.entries(n))if(r)if(Array.isArray(r))for(const n of r)e.append(t,n);else e.append(t,r);o=e}else o=JSON.stringify(n,void 0,0);const i=await fetch(t,{headers:r,method:e,body:o});return{statusCode:i.status,headers:Object.fromEntries(i.headers),body:(null===(s=i.headers.get("Content-Type"))||void 0===s?void 0:s.includes("application/json"))?await i.json():await i.text()}}}t.BrowserClient=o},660:function(e,t,r){var n,s=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var s=Object.getOwnPropertyDescriptor(t,r);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,s)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),i=this&&this.__importStar||(n=function(e){return n=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},n(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=n(e),i=0;i<r.length;i++)"default"!==r[i]&&s(t,e,r[i]);return o(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.Translator=void 0;const a=r(50),c=r(514),u=r(629),l=i(r(837)),d=r(221),h=r(311);t.Translator=class{constructor(e,t){this.client=(0,l.default)(e,null==t?void 0:t.serverUrl),this.memories=new u.Memories(this.client),this.documents=new a.Documents(this.client),this.glossaries=new c.Glossaries(this.client)}get version(){return h.version}async getLanguages(){return await this.client.get("/v2/languages")}async translate(e,t,r,n,s){const o={};if(null==n?void 0:n.headers)for(const[e,t]of Object.entries(n.headers))o[e]=t;(null==n?void 0:n.noTrace)&&(o["X-No-Trace"]="true");const i=this.client.postAndGetStream("/v2/translate",{q:e,source:t,target:r,source_hint:null==n?void 0:n.sourceHint,content_type:null==n?void 0:n.contentType,multiline:!1!==(null==n?void 0:n.multiline),adapt_to:null==n?void 0:n.adaptTo,glossaries:null==n?void 0:n.glossaries,instructions:null==n?void 0:n.instructions,timeout:null==n?void 0:n.timeoutInMillis,priority:null==n?void 0:n.priority,use_cache:null==n?void 0:n.useCache,cache_ttl:null==n?void 0:n.cacheTTLSeconds,verbose:null==n?void 0:n.verbose,style:null==n?void 0:n.style,reasoning:null==n?void 0:n.reasoning},void 0,o);let a;for await(const e of i)s&&s(e),a=e;if(!a)throw new Error("No translation result received.");return a}async detect(e,t,r){return await this.client.post("/v2/detect",{q:e,hint:t,passlist:r})}static async getLoginUrl(e){e||(e=d.DEFAULT_BASE_URL);const{body:t}=await l.HttpClient.get(`${e.replace(/\/+$/,"")}/v2/auth/login-page`);return t}}},725:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.LaraApiError=t.TimeoutError=t.LaraError=void 0;class r extends Error{}t.LaraError=r,t.TimeoutError=class extends r{},t.LaraApiError=class extends r{constructor(e,t,r,n){super(r),this.statusCode=e,this.type=t,this.message=r,this.idTransaction=n}}},741:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseContent=function e(t){if(null==t)return t;if(Array.isArray(t))return t.map(e);if("string"==typeof t)return t.match(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.[0-9]{3}Z$/)?new Date(t):t;if("object"==typeof t){const r={};for(const[n,s]of Object.entries(t))r[n.replace(/_([a-z])/g,(e,t)=>t.toUpperCase())]=e(s);return r}return t}},780:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BrowserCrypto=void 0,t.BrowserCrypto=class{constructor(){this.subtle=window.crypto.subtle}async digestBase64(e){const t=new TextEncoder,r=(await this.subtle.digest("sha-256",t.encode(e))).slice(0,16);return btoa(String.fromCharCode(...new Uint8Array(r)))}async hmac(e,t){const r=new TextEncoder;r.encode(t);const n=await this.subtle.importKey("raw",r.encode(e),{name:"hmac",hash:{name:"sha-256"}},!1,["sign"]),s=await this.subtle.sign("hmac",n,r.encode(t));return btoa(String.fromCharCode(...new Uint8Array(s)))}}},821:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(){return new n.BrowserS3Client};const n=r(343)},837:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HttpClient=t.LaraClient=void 0,t.default=function(e,t){const r=new URL(t||n.DEFAULT_BASE_URL);if("https:"!==r.protocol&&"http:"!==r.protocol)throw new TypeError(`Invalid URL (protocol): ${r.protocol}`);const o={secure:"https:"===r.protocol,hostname:r.hostname,port:r.port?parseInt(r.port,10):"https:"===r.protocol?443:80};return new s.BrowserLaraClient(o,e)};const n=r(221),s=r(631);var o=r(412);Object.defineProperty(t,"LaraClient",{enumerable:!0,get:function(){return o.LaraClient}});var i=r(631);Object.defineProperty(t,"HttpClient",{enumerable:!0,get:function(){return i.BrowserClient}})},841:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0});const r=e=>{if("string"==typeof e)return e;if(Array.isArray(e))return e.map(r);if("object"==typeof e&&null!==e){const t={};for(const[n,s]of Object.entries(e))t[n.replace(/([A-Z])/g,"_$1").toLowerCase()]=r(s);return t}return e};t.default=r}},t={};function r(n){var s=t[n];if(void 0!==s)return s.exports;var o=t[n]={exports:{}};return e[n].call(o.exports,o,o.exports,r),o.exports}var n={};return(()=>{var e=n;Object.defineProperty(e,"__esModule",{value:!0}),e.version=e.Translator=e.Memories=e.Glossaries=e.TimeoutError=e.LaraError=e.LaraApiError=e.Documents=e.DocumentStatus=e.Credentials=e.AuthToken=e.AccessKey=void 0;var t=r(414);Object.defineProperty(e,"AccessKey",{enumerable:!0,get:function(){return t.AccessKey}}),Object.defineProperty(e,"AuthToken",{enumerable:!0,get:function(){return t.AuthToken}}),Object.defineProperty(e,"Credentials",{enumerable:!0,get:function(){return t.Credentials}});var s=r(50);Object.defineProperty(e,"DocumentStatus",{enumerable:!0,get:function(){return s.DocumentStatus}}),Object.defineProperty(e,"Documents",{enumerable:!0,get:function(){return s.Documents}});var o=r(725);Object.defineProperty(e,"LaraApiError",{enumerable:!0,get:function(){return o.LaraApiError}}),Object.defineProperty(e,"LaraError",{enumerable:!0,get:function(){return o.LaraError}}),Object.defineProperty(e,"TimeoutError",{enumerable:!0,get:function(){return o.TimeoutError}});var i=r(514);Object.defineProperty(e,"Glossaries",{enumerable:!0,get:function(){return i.Glossaries}});var a=r(629);Object.defineProperty(e,"Memories",{enumerable:!0,get:function(){return a.Memories}});var c=r(660);Object.defineProperty(e,"Translator",{enumerable:!0,get:function(){return c.Translator}});var u=r(311);Object.defineProperty(e,"version",{enumerable:!0,get:function(){return u.version}})})(),n})());
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.Lara=t():e.Lara=t()}(this,()=>(()=>{"use strict";var e={50:function(e,t,r){var o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Documents=t.DocumentStatus=void 0;const n=r(725),s=o(r(821)),i=o(r(841));var a;!function(e){e.INITIALIZED="initialized",e.ANALYZING="analyzing",e.PAUSED="paused",e.READY="ready",e.TRANSLATING="translating",e.TRANSLATED="translated",e.ERROR="error"}(a||(t.DocumentStatus=a={})),t.Documents=class{constructor(e){this.client=e,this.s3Client=(0,s.default)()}async upload(e,t,r,o,n){const{url:s,fields:a}=await this.client.get("/v2/documents/upload-url",{filename:t});await this.s3Client.upload(s,a,e,null==n?void 0:n.contentLength);const c=(null==n?void 0:n.noTrace)?{"X-No-Trace":"true"}:{};return this.client.post("/v2/documents",{source:r,target:o,s3key:a.key,adapt_to:null==n?void 0:n.adaptTo,glossaries:null==n?void 0:n.glossaries,style:null==n?void 0:n.style,password:null==n?void 0:n.password,extraction_params:(null==n?void 0:n.extractionParams)?(0,i.default)(n.extractionParams):void 0},void 0,c)}async status(e){return await this.client.get(`/v2/documents/${e}`)}async download(e,t){const{url:r}=await this.client.get(`/v2/documents/${e}/download-url`,{output_format:null==t?void 0:t.outputFormat});return await this.s3Client.download(r)}async downloadStream(e,t){const{url:r}=await this.client.get(`/v2/documents/${e}/download-url`,{output_format:null==t?void 0:t.outputFormat});return await this.s3Client.downloadStream(r)}async translate(e,t,r,o,s){const i={adaptTo:null==s?void 0:s.adaptTo,glossaries:null==s?void 0:s.glossaries,noTrace:null==s?void 0:s.noTrace,style:null==s?void 0:s.style,password:null==s?void 0:s.password,extractionParams:null==s?void 0:s.extractionParams,contentLength:null==s?void 0:s.contentLength},{id:c}=await this.upload(e,t,r,o,i),u=(null==s?void 0:s.outputFormat)?{outputFormat:s.outputFormat}:void 0,l=Date.now();for(;Date.now()-l<9e5;){await new Promise(e=>setTimeout(e,2e3));const{status:e,errorReason:t}=await this.status(c);if(e===a.TRANSLATED)return await this.download(c,u);if(e===a.ERROR)throw new n.LaraApiError(500,"DocumentError",t)}throw new n.TimeoutError}async translateStream(e,t,r,o,s){const i={adaptTo:null==s?void 0:s.adaptTo,glossaries:null==s?void 0:s.glossaries,noTrace:null==s?void 0:s.noTrace,style:null==s?void 0:s.style,password:null==s?void 0:s.password,extractionParams:null==s?void 0:s.extractionParams,contentLength:null==s?void 0:s.contentLength},{id:c}=await this.upload(e,t,r,o,i),u=(null==s?void 0:s.outputFormat)?{outputFormat:s.outputFormat}:void 0,l=Date.now();for(;Date.now()-l<9e5;){await new Promise(e=>setTimeout(e,2e3));const{status:e,errorReason:t}=await this.status(c);if(e===a.TRANSLATED)return await this.downloadStream(c,u);if(e===a.ERROR)throw new n.LaraApiError(500,"DocumentError",t)}throw new n.TimeoutError}}},221:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DEFAULT_BASE_URL=void 0,t.DEFAULT_BASE_URL="https://api.laratranslate.com"},311:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.version=void 0,t.version="1.8.0-beta.1"},326:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(){return void 0===n&&(n=new o.BrowserCrypto),n};const o=r(780);let n},343:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BrowserS3Client=void 0;const o=r(364);class n extends o.S3Client{async _upload(e,t,r){const o=new FormData;for(const[e,r]of Object.entries(t))o.append(e,r);o.append("file",r),await fetch(e,{method:"POST",body:o})}async download(e){return(await fetch(e)).blob()}async downloadStream(e){const t=await fetch(e);if(!t.body)throw new Error("Response body is null");return t.body}wrapMultiPartFile(e){if(e instanceof File)return e;throw new TypeError(`Invalid file input in the browser. Expected an instance of File but received ${typeof e}.`)}}t.BrowserS3Client=n},364:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.S3Client=void 0,t.S3Client=class{async upload(e,t,r,o){return this._upload(e,t,this.wrapMultiPartFile(r),o)}}},412:function(e,t,r){var o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.LaraClient=void 0;const n=r(414),s=o(r(326)),i=r(725),a=r(741),c=r(311);t.LaraClient=class{constructor(e){if(this.crypto=(0,s.default)(),this.extraHeaders={},e instanceof n.AccessKey)this.accessKey=e;else{if(!(e instanceof n.AuthToken))throw new Error("Invalid authentication method provided");this.authToken=e}}setExtraHeader(e,t){this.extraHeaders[e]=t}get(e,t,r,o){return this.request("GET",this.buildPathWithQuery(e,t),void 0,void 0,r,o)}delete(e,t,r,o,n){return this.request("DELETE",this.buildPathWithQuery(e,t),r,void 0,o,n)}post(e,t,r,o,n){return this.request("POST",e,t,r,o,n)}async*postAndGetStream(e,t,r,o,n){for await(const s of this.requestStream("POST",e,t,r,o,n))yield s}put(e,t,r,o,n){return this.request("PUT",e,t,r,o,n)}async request(e,t,r,o,n,s){await this.ensureAuthenticated();const i=t.startsWith("/")?t:`/${t}`,c=await this.buildRequestHeaders(r,o,n),u=this.buildRequestBody(r,o);c.Authorization=`Bearer ${this.token}`;const l=await this.send(e,i,c,u,s);if(this.isSuccessResponse(l))return(0,a.parseContent)(l.body);if(401===l.statusCode)return this.token=void 0,await this.refreshTokens(),this.request(e,t,r,o,n,s);throw this.createApiError(l)}async*requestStream(e,t,r,o,n,s){await this.ensureAuthenticated();const i=t.startsWith("/")?t:`/${t}`,c=await this.buildRequestHeaders(r,o,n),u=this.buildRequestBody(r,o);c.Authorization=`Bearer ${this.token}`;for await(const l of this.sendAndGetStream(e,i,c,u,s)){if(401===l.statusCode)return this.token=void 0,await this.refreshTokens(),void(yield*this.requestStream(e,t,r,o,n,s));if(!this.isSuccessResponse(l))throw this.createApiError(l);yield(0,a.parseContent)(l.body)}}async ensureAuthenticated(){if(!this.token){if(this.authenticationPromise)return this.authenticationPromise;this.authenticationPromise=this.performAuthentication();try{await this.authenticationPromise}catch(e){if(this.authenticationPromise=void 0,e instanceof i.LaraApiError&&(401===e.statusCode||403===e.statusCode))throw e;try{this.authenticationPromise=this.performAuthentication(),await this.authenticationPromise}catch(e){throw this.authenticationPromise=void 0,e instanceof i.LaraApiError?e:new i.LaraApiError(500,"AuthenticationError",e.message)}}}}async performAuthentication(){if(this.refreshToken)return this.refreshTokens();if(this.authToken)return this.token=this.authToken.token,this.refreshToken=this.authToken.refreshToken,void(this.authToken=void 0);if(this.accessKey)return this.authenticateWithAccessKey();throw new Error("No authentication method provided")}async refreshTokens(){const e={Authorization:`Bearer ${this.refreshToken}`,"X-Lara-Date":(new Date).toUTCString()},t=await this.send("POST","/v2/auth/refresh",e);this.handleAuthResponse(t)}async authenticateWithAccessKey(){if(!this.accessKey)throw new Error("No access key provided");const e={id:this.accessKey.id},t=await this.crypto.digestBase64(JSON.stringify(e)),r={"Content-Type":"application/json","X-Lara-Date":(new Date).toUTCString(),"Content-MD5":t};r.Authorization=`Lara:${await this.sign("POST","/v2/auth",r)}`;const o=await this.send("POST","/v2/auth",r,e);this.handleAuthResponse(o)}buildPathWithQuery(e,t){const r=this.filterNullish(t);return r?`${e}?${new URLSearchParams(r).toString()}`:e}async buildRequestHeaders(e,t,r){const o={"X-Lara-Date":(new Date).toUTCString(),"X-Lara-SDK-Name":"lara-node","X-Lara-SDK-Version":c.version,...this.extraHeaders,...r},n=this.filterNullish(e);if(t)o["Content-Type"]="multipart/form-data";else if(n){o["Content-Type"]="application/json";const e=JSON.stringify(n,void 0,0);o["Content-Length"]=(new TextEncoder).encode(e).length.toString()}return o}buildRequestBody(e,t){const r=this.filterNullish(e);if(t){const e={};for(const[r,o]of Object.entries(t))e[r]=this.wrapMultiPartFile(o);return{...e,...r}}return r}filterNullish(e){if(!e)return;const t=Object.fromEntries(Object.entries(e).filter(([e,t])=>null!=t));return Object.keys(t).length>0?t:void 0}isSuccessResponse(e){return e.statusCode>=200&&e.statusCode<300}handleAuthResponse(e){if(this.isSuccessResponse(e))return this.token=e.body.token,void(this.refreshToken=e.headers["x-lara-refresh-token"]);throw this.createApiError(e)}createApiError(e){var t;const r=(null===(t=e.body)||void 0===t?void 0:t.error)||{};return new i.LaraApiError(e.statusCode,r.type||"UnknownError",r.message||"An unknown error occurred")}async sign(e,t,r){if(!this.accessKey)throw new Error("Access key not provided for signing");const o=r["X-Lara-Date"].trim(),n=(r["Content-MD5"]||"").trim(),s=(r["Content-Type"]||"").trim(),i=`${(r["X-HTTP-Method-Override"]||e).trim().toUpperCase()}\n${t}\n${n}\n${s}\n${o}`;return this.crypto.hmac(this.accessKey.secret,i)}}},414:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AuthToken=t.Credentials=t.AccessKey=void 0;class r{constructor(e,t){this.id=e,this.secret=t}}t.AccessKey=r,t.Credentials=class extends r{get accessKeyId(){return this.id}get accessKeySecret(){return this.secret}},t.AuthToken=class{constructor(e,t){this.token=e,this.refreshToken=t}}},514:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Glossaries=void 0;const o=r(725);t.Glossaries=class{constructor(e){this.client=e,this.pollingInterval=2e3}async list(){return await this.client.get("/v2/glossaries")}async create(e){return await this.client.post("/v2/glossaries",{name:e})}async get(e){try{return await this.client.get(`/v2/glossaries/${e}`)}catch(e){if(e instanceof o.LaraApiError&&404===e.statusCode)return null;throw e}}async delete(e){return await this.client.delete(`/v2/glossaries/${e}`)}async update(e,t){return await this.client.put(`/v2/glossaries/${e}`,{name:t})}async importCsv(e,t,r=!1){return await this.client.post(`/v2/glossaries/${e}/import`,{compression:r?"gzip":void 0},{csv:t})}async getImportStatus(e){return await this.client.get(`/v2/glossaries/imports/${e}`)}async waitForImport(e,t,r){const n=Date.now();for(;e.progress<1;){if(r&&Date.now()-n>r)throw new o.TimeoutError;await new Promise(e=>setTimeout(e,this.pollingInterval)),e=await this.getImportStatus(e.id),t&&t(e)}return e}async counts(e){return await this.client.get(`/v2/glossaries/${e}/counts`)}async export(e,t,r){return await this.client.get(`/v2/glossaries/${e}/export`,{content_type:t,source:r})}}},629:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Memories=void 0;const o=r(725);t.Memories=class{constructor(e){this.client=e,this.pollingInterval=2e3}async list(){return await this.client.get("/v2/memories")}async create(e,t){return await this.client.post("/v2/memories",{name:e,external_id:t})}async get(e){try{return await this.client.get(`/v2/memories/${e}`)}catch(e){if(e instanceof o.LaraApiError&&404===e.statusCode)return null;throw e}}async delete(e){return await this.client.delete(`/v2/memories/${e}`)}async update(e,t){return await this.client.put(`/v2/memories/${e}`,{name:t})}async connect(e){const t=await this.client.post("/v2/memories/connect",{ids:Array.isArray(e)?e:[e]});return Array.isArray(e)?t:t[0]}async importTmx(e,t,r=!1){return await this.client.post(`/v2/memories/${e}/import`,{compression:r?"gzip":void 0},{tmx:t})}async addTranslation(e,t,r,o,n,s,i,a,c){const u={source:t,target:r,sentence:o,translation:n,tuid:s,sentence_before:i,sentence_after:a};return Array.isArray(e)?(u.ids=e,await this.client.put("/v2/memories/content",u,void 0,c)):await this.client.put(`/v2/memories/${e}/content`,u,void 0,c)}async deleteTranslation(e,t,r,o,n,s,i,a){const c={source:t,target:r,sentence:o,translation:n,tuid:s,sentence_before:i,sentence_after:a};return Array.isArray(e)?(c.ids=e,await this.client.delete("/v2/memories/content",void 0,c)):await this.client.delete(`/v2/memories/${e}/content`,void 0,c)}async getImportStatus(e){return await this.client.get(`/v2/memories/imports/${e}`)}async waitForImport(e,t,r){const n=Date.now();for(;e.progress<1;){if(r&&Date.now()-n>r)throw new o.TimeoutError;await new Promise(e=>setTimeout(e,this.pollingInterval)),e=await this.getImportStatus(e.id),t&&t(e)}return e}}},631:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BrowserClient=t.BrowserLaraClient=void 0;const o=r(725),n=r(412);class s extends n.LaraClient{constructor(e,t){super(t);let r=`${e.secure?"https":"http"}://${e.hostname}`;var o,n;o=e.port,n=e.secure,80===o&&!n||443===o&&n||(r+=`:${e.port}`),this.baseUrl=r}async send(e,t,r,n,s){var i;let a,c,u;if(n)if("multipart/form-data"===r["Content-Type"]){delete r["Content-Type"];const e=new FormData;for(const[t,r]of Object.entries(n))if(r)if(Array.isArray(r))for(const o of r)e.append(t,o);else e.append(t,r);a=e}else a=JSON.stringify(n,void 0,0);s&&s>0&&(c=new AbortController,u=setTimeout(()=>c.abort(),s));try{const o=await fetch(this.baseUrl+t,{headers:r,method:e,body:a,signal:null==c?void 0:c.signal});return u&&clearTimeout(u),(null===(i=o.headers.get("Content-Type"))||void 0===i?void 0:i.includes("text/csv"))?{statusCode:o.status,body:{content:await o.text()},headers:Object.fromEntries(o.headers)}:{statusCode:o.status,body:await o.json(),headers:Object.fromEntries(o.headers)}}catch(e){if(u&&clearTimeout(u),e instanceof Error&&"AbortError"===e.name)throw new o.TimeoutError(`Request timed out after ${s}ms`);throw e}}async*sendAndGetStream(e,t,r,n,s){let i,a,c,u;if(n)if("multipart/form-data"===r["Content-Type"]){delete r["Content-Type"];const e=new FormData;for(const[t,r]of Object.entries(n))if(r)if(Array.isArray(r))for(const o of r)e.append(t,o);else e.append(t,r);i=e}else i=JSON.stringify(n,void 0,0);s&&s>0&&(a=new AbortController,c=setTimeout(()=>a.abort(),s));try{u=await fetch(this.baseUrl+t,{headers:r,method:e,body:i,signal:null==a?void 0:a.signal})}catch(e){if(c&&clearTimeout(c),e instanceof Error&&"AbortError"===e.name)throw new o.TimeoutError(`Request timed out after ${s}ms`);throw e}if(c&&clearTimeout(c),!u.body)throw new Error("Response body is not available for streaming");const l=u.body.getReader(),d=new TextDecoder;let h="";try{for(;;){const{done:e,value:t}=await l.read();if(e){if(h.trim())try{const e=JSON.parse(h);console.log(e),yield{statusCode:e.status||u.status,body:e.data||e,headers:Object.fromEntries(u.headers)}}catch(e){}break}h+=d.decode(t,{stream:!0});const r=h.split("\n");h=r.pop()||"";for(const e of r)if(e.trim())try{const t=JSON.parse(e);yield{statusCode:t.status||u.status,body:t.data||t,headers:Object.fromEntries(u.headers)}}catch(e){}}}finally{l.releaseLock()}}wrapMultiPartFile(e){if(e instanceof File)return e;throw new TypeError(`Invalid file input in the browser. Expected an instance of File but received ${typeof e}.`)}}t.BrowserLaraClient=s;class i{static async get(e,t){return i.send("GET",e,t)}static async send(e,t,r,o){var n;let s;if(o)if(r&&"multipart/form-data"===r["Content-Type"]){delete r["Content-Type"];const e=new FormData;for(const[t,r]of Object.entries(o))if(r)if(Array.isArray(r))for(const o of r)e.append(t,o);else e.append(t,r);s=e}else s=JSON.stringify(o,void 0,0);const i=await fetch(t,{headers:r,method:e,body:s});return{statusCode:i.status,headers:Object.fromEntries(i.headers),body:(null===(n=i.headers.get("Content-Type"))||void 0===n?void 0:n.includes("application/json"))?await i.json():await i.text()}}}t.BrowserClient=i},660:function(e,t,r){var o,n=this&&this.__createBinding||(Object.create?function(e,t,r,o){void 0===o&&(o=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,o,n)}:function(e,t,r,o){void 0===o&&(o=r),e[o]=t[r]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),i=this&&this.__importStar||(o=function(e){return o=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},o(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=o(e),i=0;i<r.length;i++)"default"!==r[i]&&n(t,e,r[i]);return s(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.Translator=void 0;const a=r(50),c=r(514),u=r(629),l=i(r(837)),d=r(221),h=r(311);t.Translator=class{constructor(e,t){this.client=(0,l.default)(e,null==t?void 0:t.serverUrl),this.memories=new u.Memories(this.client),this.documents=new a.Documents(this.client),this.glossaries=new c.Glossaries(this.client)}get version(){return h.version}async getLanguages(){return await this.client.get("/v2/languages")}async translate(e,t,r,o,n){const s={};if(null==o?void 0:o.headers)for(const[e,t]of Object.entries(o.headers))s[e]=t;(null==o?void 0:o.noTrace)&&(s["X-No-Trace"]="true");const i=this.client.postAndGetStream("/v2/translate",{q:e,source:t,target:r,source_hint:null==o?void 0:o.sourceHint,content_type:null==o?void 0:o.contentType,multiline:!1!==(null==o?void 0:o.multiline),adapt_to:null==o?void 0:o.adaptTo,glossaries:null==o?void 0:o.glossaries,instructions:null==o?void 0:o.instructions,timeout:null==o?void 0:o.timeoutInMillis,priority:null==o?void 0:o.priority,use_cache:null==o?void 0:o.useCache,cache_ttl:null==o?void 0:o.cacheTTLSeconds,verbose:null==o?void 0:o.verbose,style:null==o?void 0:o.style,reasoning:null==o?void 0:o.reasoning},void 0,s,null==o?void 0:o.timeoutInMillis);let a;for await(const e of i)n&&n(e),a=e;if(!a)throw new Error("No translation result received.");return a}async detect(e,t,r){return await this.client.post("/v2/detect",{q:e,hint:t,passlist:r})}static async getLoginUrl(e){e||(e=d.DEFAULT_BASE_URL);const{body:t}=await l.HttpClient.get(`${e.replace(/\/+$/,"")}/v2/auth/login-page`);return t}}},725:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.LaraApiError=t.TimeoutError=t.LaraError=void 0;class r extends Error{}t.LaraError=r,t.TimeoutError=class extends r{},t.LaraApiError=class extends r{constructor(e,t,r,o){super(r),this.statusCode=e,this.type=t,this.message=r,this.idTransaction=o}}},741:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseContent=function e(t){if(null==t)return t;if(Array.isArray(t))return t.map(e);if("string"==typeof t)return t.match(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.[0-9]{3}Z$/)?new Date(t):t;if("object"==typeof t){const r={};for(const[o,n]of Object.entries(t))r[o.replace(/_([a-z])/g,(e,t)=>t.toUpperCase())]=e(n);return r}return t}},780:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BrowserCrypto=void 0,t.BrowserCrypto=class{constructor(){this.subtle=window.crypto.subtle}async digestBase64(e){const t=new TextEncoder,r=(await this.subtle.digest("sha-256",t.encode(e))).slice(0,16);return btoa(String.fromCharCode(...new Uint8Array(r)))}async hmac(e,t){const r=new TextEncoder;r.encode(t);const o=await this.subtle.importKey("raw",r.encode(e),{name:"hmac",hash:{name:"sha-256"}},!1,["sign"]),n=await this.subtle.sign("hmac",o,r.encode(t));return btoa(String.fromCharCode(...new Uint8Array(n)))}}},821:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(){return new o.BrowserS3Client};const o=r(343)},837:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HttpClient=t.LaraClient=void 0,t.default=function(e,t){const r=new URL(t||o.DEFAULT_BASE_URL);if("https:"!==r.protocol&&"http:"!==r.protocol)throw new TypeError(`Invalid URL (protocol): ${r.protocol}`);const s={secure:"https:"===r.protocol,hostname:r.hostname,port:r.port?parseInt(r.port,10):"https:"===r.protocol?443:80};return new n.BrowserLaraClient(s,e)};const o=r(221),n=r(631);var s=r(412);Object.defineProperty(t,"LaraClient",{enumerable:!0,get:function(){return s.LaraClient}});var i=r(631);Object.defineProperty(t,"HttpClient",{enumerable:!0,get:function(){return i.BrowserClient}})},841:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0});const r=e=>{if("string"==typeof e)return e;if(Array.isArray(e))return e.map(r);if("object"==typeof e&&null!==e){const t={};for(const[o,n]of Object.entries(e))t[o.replace(/([A-Z])/g,"_$1").toLowerCase()]=r(n);return t}return e};t.default=r}},t={};function r(o){var n=t[o];if(void 0!==n)return n.exports;var s=t[o]={exports:{}};return e[o].call(s.exports,s,s.exports,r),s.exports}var o={};return(()=>{var e=o;Object.defineProperty(e,"__esModule",{value:!0}),e.version=e.Translator=e.Memories=e.Glossaries=e.TimeoutError=e.LaraError=e.LaraApiError=e.Documents=e.DocumentStatus=e.Credentials=e.AuthToken=e.AccessKey=void 0;var t=r(414);Object.defineProperty(e,"AccessKey",{enumerable:!0,get:function(){return t.AccessKey}}),Object.defineProperty(e,"AuthToken",{enumerable:!0,get:function(){return t.AuthToken}}),Object.defineProperty(e,"Credentials",{enumerable:!0,get:function(){return t.Credentials}});var n=r(50);Object.defineProperty(e,"DocumentStatus",{enumerable:!0,get:function(){return n.DocumentStatus}}),Object.defineProperty(e,"Documents",{enumerable:!0,get:function(){return n.Documents}});var s=r(725);Object.defineProperty(e,"LaraApiError",{enumerable:!0,get:function(){return s.LaraApiError}}),Object.defineProperty(e,"LaraError",{enumerable:!0,get:function(){return s.LaraError}}),Object.defineProperty(e,"TimeoutError",{enumerable:!0,get:function(){return s.TimeoutError}});var i=r(514);Object.defineProperty(e,"Glossaries",{enumerable:!0,get:function(){return i.Glossaries}});var a=r(629);Object.defineProperty(e,"Memories",{enumerable:!0,get:function(){return a.Memories}});var c=r(660);Object.defineProperty(e,"Translator",{enumerable:!0,get:function(){return c.Translator}});var u=r(311);Object.defineProperty(e,"version",{enumerable:!0,get:function(){return u.version}})})(),o})());
|