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