@translated/lara 1.8.0 → 1.8.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/audioTranslator.d.ts +5 -0
- package/lib/audioTranslator.js +8 -2
- package/lib/index.d.ts +1 -1
- package/lib/index.js +2 -1
- package/lib/net/lara/client.d.ts +1 -0
- package/lib/net/lara/client.js +26 -1
- package/lib/translator.d.ts +1 -0
- package/lib/translator.js +2 -1
- 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
package/lib/audioTranslator.d.ts
CHANGED
|
@@ -11,11 +11,16 @@ export declare enum AudioStatus {
|
|
|
11
11
|
TRANSLATED = "translated",
|
|
12
12
|
ERROR = "error"
|
|
13
13
|
}
|
|
14
|
+
export declare enum VoiceGender {
|
|
15
|
+
MALE = "male",
|
|
16
|
+
FEMALE = "female"
|
|
17
|
+
}
|
|
14
18
|
export type AudioOptions = {
|
|
15
19
|
adaptTo?: string[];
|
|
16
20
|
glossaries?: string[];
|
|
17
21
|
noTrace?: boolean;
|
|
18
22
|
style?: TranslationStyle;
|
|
23
|
+
voiceGender?: VoiceGender;
|
|
19
24
|
};
|
|
20
25
|
export type AudioUploadOptions = AudioOptions & {
|
|
21
26
|
contentLength?: number;
|
package/lib/audioTranslator.js
CHANGED
|
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
3
3
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.AudioTranslator = exports.AudioStatus = void 0;
|
|
6
|
+
exports.AudioTranslator = exports.VoiceGender = exports.AudioStatus = void 0;
|
|
7
7
|
const errors_1 = require("./errors");
|
|
8
8
|
const s3_1 = __importDefault(require("./net/s3"));
|
|
9
9
|
// biome-ignore format: keep comments aligned
|
|
@@ -17,6 +17,11 @@ var AudioStatus;
|
|
|
17
17
|
AudioStatus["TRANSLATED"] = "translated";
|
|
18
18
|
AudioStatus["ERROR"] = "error";
|
|
19
19
|
})(AudioStatus || (exports.AudioStatus = AudioStatus = {}));
|
|
20
|
+
var VoiceGender;
|
|
21
|
+
(function (VoiceGender) {
|
|
22
|
+
VoiceGender["MALE"] = "male";
|
|
23
|
+
VoiceGender["FEMALE"] = "female";
|
|
24
|
+
})(VoiceGender || (exports.VoiceGender = VoiceGender = {}));
|
|
20
25
|
class AudioTranslator {
|
|
21
26
|
constructor(client) {
|
|
22
27
|
this.client = client;
|
|
@@ -32,7 +37,8 @@ class AudioTranslator {
|
|
|
32
37
|
s3key: fields.key,
|
|
33
38
|
adapt_to: options === null || options === void 0 ? void 0 : options.adaptTo,
|
|
34
39
|
glossaries: options === null || options === void 0 ? void 0 : options.glossaries,
|
|
35
|
-
style: options === null || options === void 0 ? void 0 : options.style
|
|
40
|
+
style: options === null || options === void 0 ? void 0 : options.style,
|
|
41
|
+
voice_gender: options === null || options === void 0 ? void 0 : options.voiceGender
|
|
36
42
|
}, undefined, headers);
|
|
37
43
|
}
|
|
38
44
|
async status(id) {
|
package/lib/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { Audio, AudioStatus, AudioTranslator, AudioUploadOptions } from "./audioTranslator";
|
|
1
|
+
export { Audio, AudioStatus, AudioTranslator, AudioUploadOptions, VoiceGender } from "./audioTranslator";
|
|
2
2
|
export { AccessKey, AuthToken, Credentials } from "./credentials";
|
|
3
3
|
export { Document, DocumentDownloadOptions, DocumentStatus, Documents, DocumentTranslateOptions, DocumentUploadOptions } from "./documents";
|
|
4
4
|
export { LaraApiError, LaraError, TimeoutError } from "./errors";
|
package/lib/index.js
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.version = exports.Translator = exports.Memories = exports.ImageTranslator = exports.Glossaries = exports.TimeoutError = exports.LaraError = exports.LaraApiError = exports.Documents = exports.DocumentStatus = exports.Credentials = exports.AuthToken = exports.AccessKey = exports.AudioTranslator = exports.AudioStatus = void 0;
|
|
3
|
+
exports.version = exports.Translator = exports.Memories = exports.ImageTranslator = exports.Glossaries = exports.TimeoutError = exports.LaraError = exports.LaraApiError = exports.Documents = exports.DocumentStatus = exports.Credentials = exports.AuthToken = exports.AccessKey = exports.VoiceGender = exports.AudioTranslator = exports.AudioStatus = void 0;
|
|
4
4
|
var audioTranslator_1 = require("./audioTranslator");
|
|
5
5
|
Object.defineProperty(exports, "AudioStatus", { enumerable: true, get: function () { return audioTranslator_1.AudioStatus; } });
|
|
6
6
|
Object.defineProperty(exports, "AudioTranslator", { enumerable: true, get: function () { return audioTranslator_1.AudioTranslator; } });
|
|
7
|
+
Object.defineProperty(exports, "VoiceGender", { enumerable: true, get: function () { return audioTranslator_1.VoiceGender; } });
|
|
7
8
|
var credentials_1 = require("./credentials");
|
|
8
9
|
Object.defineProperty(exports, "AccessKey", { enumerable: true, get: function () { return credentials_1.AccessKey; } });
|
|
9
10
|
Object.defineProperty(exports, "AuthToken", { enumerable: true, get: function () { return credentials_1.AuthToken; } });
|
package/lib/net/lara/client.d.ts
CHANGED
|
@@ -34,6 +34,7 @@ export declare abstract class LaraClient {
|
|
|
34
34
|
put<T>(path: string, body?: Record<string, any>, files?: Record<string, MultiPartFile>, headers?: Record<string, string>): Promise<T>;
|
|
35
35
|
protected request<T>(method: HttpMethod, path: string, body?: Record<string, any>, files?: Record<string, MultiPartFile>, headers?: Record<string, string>, retryCount?: number, streamResponse?: boolean): Promise<T>;
|
|
36
36
|
protected requestStream<T>(method: HttpMethod, path: string, body?: Record<string, any>, files?: Record<string, MultiPartFile>, headers?: Record<string, string>, retryCount?: number): AsyncGenerator<T>;
|
|
37
|
+
private isTokenExpired;
|
|
37
38
|
private ensureAuthenticated;
|
|
38
39
|
private performAuthentication;
|
|
39
40
|
private refreshTokens;
|
package/lib/net/lara/client.js
CHANGED
|
@@ -92,9 +92,32 @@ class LaraClient {
|
|
|
92
92
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
93
93
|
// Authentication
|
|
94
94
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
95
|
+
isTokenExpired(bufferMs = 5000) {
|
|
96
|
+
if (!this.token)
|
|
97
|
+
return true;
|
|
98
|
+
try {
|
|
99
|
+
const parts = this.token.split(".");
|
|
100
|
+
if (parts.length !== 3)
|
|
101
|
+
return true;
|
|
102
|
+
let b64 = parts[1].replace(/-/g, "+").replace(/_/g, "/");
|
|
103
|
+
while (b64.length % 4)
|
|
104
|
+
b64 += "=";
|
|
105
|
+
const decoded = typeof Buffer !== "undefined"
|
|
106
|
+
? // Node solution
|
|
107
|
+
Buffer.from(b64, "base64").toString("utf-8")
|
|
108
|
+
: // Browser solution
|
|
109
|
+
atob(b64);
|
|
110
|
+
const { exp } = JSON.parse(decoded);
|
|
111
|
+
return typeof exp === "number" && exp * 1000 <= Date.now() + bufferMs;
|
|
112
|
+
}
|
|
113
|
+
catch {
|
|
114
|
+
return true;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
95
117
|
async ensureAuthenticated() {
|
|
96
|
-
if (this.token)
|
|
118
|
+
if (this.token && !this.isTokenExpired())
|
|
97
119
|
return;
|
|
120
|
+
this.token = undefined;
|
|
98
121
|
// Use existing promise if authentication is already in progress (mutex pattern)
|
|
99
122
|
if (this.authenticationPromise) {
|
|
100
123
|
return this.authenticationPromise;
|
|
@@ -103,6 +126,7 @@ class LaraClient {
|
|
|
103
126
|
this.authenticationPromise = this.performAuthentication();
|
|
104
127
|
try {
|
|
105
128
|
await this.authenticationPromise;
|
|
129
|
+
this.authenticationPromise = undefined;
|
|
106
130
|
}
|
|
107
131
|
catch (error) {
|
|
108
132
|
// Clear promise and retry once
|
|
@@ -114,6 +138,7 @@ class LaraClient {
|
|
|
114
138
|
try {
|
|
115
139
|
this.authenticationPromise = this.performAuthentication();
|
|
116
140
|
await this.authenticationPromise;
|
|
141
|
+
this.authenticationPromise = undefined;
|
|
117
142
|
}
|
|
118
143
|
catch (retryError) {
|
|
119
144
|
this.authenticationPromise = undefined;
|
package/lib/translator.d.ts
CHANGED
|
@@ -53,6 +53,7 @@ export type TranslateOptions = {
|
|
|
53
53
|
headers?: Record<string, string>;
|
|
54
54
|
style?: TranslationStyle;
|
|
55
55
|
reasoning?: boolean;
|
|
56
|
+
metadata?: string | Record<string, unknown>;
|
|
56
57
|
};
|
|
57
58
|
export type TranslationStyle = "faithful" | "fluid" | "creative";
|
|
58
59
|
export interface DetectResult {
|
package/lib/translator.js
CHANGED
|
@@ -83,7 +83,8 @@ class Translator {
|
|
|
83
83
|
cache_ttl: options === null || options === void 0 ? void 0 : options.cacheTTLSeconds,
|
|
84
84
|
verbose: options === null || options === void 0 ? void 0 : options.verbose,
|
|
85
85
|
style: options === null || options === void 0 ? void 0 : options.style,
|
|
86
|
-
reasoning: options === null || options === void 0 ? void 0 : options.reasoning
|
|
86
|
+
reasoning: options === null || options === void 0 ? void 0 : options.reasoning,
|
|
87
|
+
metadata: options === null || options === void 0 ? void 0 : options.metadata
|
|
87
88
|
}, undefined, headers);
|
|
88
89
|
let lastResult;
|
|
89
90
|
for await (const partial of response) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const version = "1.8.
|
|
1
|
+
export declare const version = "1.8.2";
|
package/lib/utils/sdk-version.js
CHANGED
package/lib_browser/lara.min.js
CHANGED
|
@@ -1 +1 @@
|
|
|
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 u=(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,u)}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:u}=await this.upload(t,e,r,o,i),l=(null==s?void 0:s.outputFormat)?{outputFormat:s.outputFormat}:void 0,c=Date.now();for(;Date.now()-c<9e5;){await new Promise(t=>setTimeout(t,2e3));const{status:t,errorReason:e}=await this.status(u);if(t===a.TRANSLATED)return await this.download(u,l);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:u}=await this.upload(t,e,r,o,i),l=(null==s?void 0:s.outputFormat)?{outputFormat:s.outputFormat}:void 0,c=Date.now();for(;Date.now()-c<9e5;){await new Promise(t=>setTimeout(t,2e3));const{status:t,errorReason:e}=await this.status(u);if(t===a.TRANSLATED)return await this.downloadStream(u,l);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"},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},328: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.AudioTranslator=e.AudioStatus=void 0;const n=r(725),s=o(r(821));var i;!function(t){t.INITIALIZED="initialized",t.ANALYZING="analyzing",t.PAUSED="paused",t.READY="ready",t.TRANSLATING="translating",t.TRANSLATED="translated",t.ERROR="error"}(i||(e.AudioStatus=i={})),e.AudioTranslator=class{constructor(t){this.client=t,this.s3Client=(0,s.default)()}async upload(t,e,r,o,n){const{url:s,fields:i}=await this.client.get("/v2/audio/upload-url",{filename:e});await this.s3Client.upload(s,i,t,null==n?void 0:n.contentLength);const a=(null==n?void 0:n.noTrace)?{"X-No-Trace":"true"}:{};return this.client.post("/v2/audio/translate",{source:r,target:o,s3key:i.key,adapt_to:null==n?void 0:n.adaptTo,glossaries:null==n?void 0:n.glossaries,style:null==n?void 0:n.style},void 0,a)}async status(t){return await this.client.get(`/v2/audio/${t}`)}async download(t){const{url:e}=await this.client.get(`/v2/audio/${t}/download-url`);return await this.s3Client.downloadStream(e)}async translate(t,e,r,o,s){const{id:a}=await this.upload(t,e,r,o,s),u=Date.now();for(;Date.now()-u<9e5;){await new Promise(t=>setTimeout(t,2e3));const{status:t,errorReason:e}=await this.status(a);if(t===i.TRANSLATED)return await this.download(a);if(t===i.ERROR)throw new n.LaraApiError(500,"AudioError",e)}throw new n.TimeoutError}}},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),u=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,n){return this.request("POST",t,e,r,o,void 0,n)}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,s=0,i){await this.ensureAuthenticated();const u=e.startsWith("/")?e:`/${e}`,l=await this.buildRequestHeaders(r,o,n),c=this.buildRequestBody(r,o);l.Authorization=`Bearer ${this.token}`;const d=await this.send(t,u,l,c,i);if(this.isSuccessResponse(d))return i?d.body:(0,a.parseContent)(d.body);if(401===d.statusCode&&s<1)return this.token=void 0,await this.refreshTokens(),this.request(t,e,r,o,n,s+1,i);throw this.createApiError(d)}async*requestStream(t,e,r,o,n,s=0){await this.ensureAuthenticated();const i=e.startsWith("/")?e:`/${e}`,u=await this.buildRequestHeaders(r,o,n),l=this.buildRequestBody(r,o);u.Authorization=`Bearer ${this.token}`;for await(const c of this.sendAndGetStream(t,i,u,l)){if(401===c.statusCode&&s<1)return this.token=void 0,await this.refreshTokens(),void(yield*this.requestStream(t,e,r,o,n,s+1));if(!this.isSuccessResponse(c))throw this.createApiError(c);yield(0,a.parseContent)(c.body.content||c.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":u.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)||t.body||{};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,o){let n=!1,s="csv/table-uni";return"boolean"==typeof r?n=r:"string"==typeof r&&(s=r,n=null!=o&&o),await this.client.post(`/v2/glossaries/${t}/import`,{compression:n?"gzip":void 0,content_type:s},{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})}async addOrReplaceEntry(t,e,r){return await this.client.put(`/v2/glossaries/${t}/content`,{terms:e,guid:r})}async deleteEntry(t,e,r){return await this.client.delete(`/v2/glossaries/${t}/content`,void 0,{term:e,guid: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,u){const l={source:e,target:r,sentence:o,translation:n,tuid:s,sentence_before:i,sentence_after:a};return Array.isArray(t)?(l.ids=t,await this.client.put("/v2/memories/content",l,void 0,u)):await this.client.put(`/v2/memories/${t}/content`,l,void 0,u)}async deleteTranslation(t,e,r,o,n,s,i,a){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.delete("/v2/memories/content",void 0,u)):await this.client.delete(`/v2/memories/${t}/content`,void 0,u)}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,s){var i;let a;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);a=t}else a=JSON.stringify(n,void 0,0);const u=this.timeout&&this.timeout>0?AbortSignal.timeout(this.timeout):void 0;try{const o=await fetch(this.baseUrl+e,{headers:r,method:t,body:a,signal:u});return s&&o.status>=200&&o.status<300?{statusCode:o.status,body:o.body,headers:Object.fromEntries(o.headers)}:(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(t){if(t instanceof Error&&("AbortError"===t.name||"TimeoutError"===t.name))throw new o.TimeoutError(`Request timed out after ${this.timeout}ms`);throw t}}async*sendAndGetStream(t,e,r,n){let s;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);const i=this.timeout&&this.timeout>0?AbortSignal.timeout(this.timeout):void 0;let a;try{a=await fetch(this.baseUrl+e,{headers:r,method:t,body:s,signal:i})}catch(t){if(t instanceof Error&&("AbortError"===t.name||"TimeoutError"===t.name))throw new o.TimeoutError(`Request timed out after ${this.timeout}ms`);throw t}if(!a.body)throw new Error("Response body is not available for streaming");const u=a.body.getReader(),l=new TextDecoder;let c="";try{for(;;){let t;try{t=await u.read()}catch(t){if(t instanceof Error&&("AbortError"===t.name||"TimeoutError"===t.name))throw new o.TimeoutError(`Request timed out after ${this.timeout}ms`);throw t}const{done:e,value:r}=t;if(e){if(c.trim())try{const t=JSON.parse(c);yield{statusCode:t.status||a.status,body:t.data||t,headers:Object.fromEntries(a.headers)}}catch(t){}break}c+=l.decode(r,{stream:!0});const n=c.split("\n");c=n.pop()||"";for(const t of n)if(t.trim())try{const e=JSON.parse(t);yield{statusCode:e.status||a.status,body:e.data||e,headers:Object.fromEntries(a.headers)}}catch(t){}}}finally{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(328),u=r(50),l=r(514),c=r(731),d=r(629),h=i(r(837)),p=r(221),f=r(311);e.Translator=class{constructor(t,e){this.client=(0,h.default)(t,null==e?void 0:e.serverUrl,null==e?void 0:e.keepAlive,null==e?void 0:e.connectionTimeoutMs),this.memories=new d.Memories(this.client),this.documents=new u.Documents(this.client),this.glossaries=new l.Glossaries(this.client),this.audio=new a.AudioTranslator(this.client),this.images=new c.ImageTranslator(this.client)}get version(){return f.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("/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)(null==o?void 0:o.reasoning)&&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=p.DEFAULT_BASE_URL);const{body:e}=await h.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}}},731:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ImageTranslator=void 0,e.ImageTranslator=class{constructor(t){this.client=t}async translate(t,e,r,o){const n=(null==o?void 0:o.noTrace)?{"X-No-Trace":"true"}:{};return n["Content-Type"]="multipart/form-data",this.client.post("/v2/images/translate",{source:e,target:r,adapt_to:JSON.stringify(null==o?void 0:o.adaptTo),glossaries:JSON.stringify(null==o?void 0:o.glossaries),style:null==o?void 0:o.style,text_removal:null==o?void 0:o.textRemoval},{image:t},n,!0)}async translateText(t,e,r,o){const n=(null==o?void 0:o.noTrace)?{"X-No-Trace":"true"}:{};return n["Content-Type"]="multipart/form-data",this.client.post("/v2/images/translate-text",{source:e,target:r,adapt_to:JSON.stringify(null==o?void 0:o.adaptTo),glossaries:JSON.stringify(null==o?void 0:o.glossaries),style:null==o?void 0:o.style,verbose:JSON.stringify(null==o?void 0:o.verbose)},{image:t},n)}}},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.ImageTranslator=t.Glossaries=t.TimeoutError=t.LaraError=t.LaraApiError=t.Documents=t.DocumentStatus=t.Credentials=t.AuthToken=t.AccessKey=t.AudioTranslator=t.AudioStatus=void 0;var e=r(328);Object.defineProperty(t,"AudioStatus",{enumerable:!0,get:function(){return e.AudioStatus}}),Object.defineProperty(t,"AudioTranslator",{enumerable:!0,get:function(){return e.AudioTranslator}});var n=r(414);Object.defineProperty(t,"AccessKey",{enumerable:!0,get:function(){return n.AccessKey}}),Object.defineProperty(t,"AuthToken",{enumerable:!0,get:function(){return n.AuthToken}}),Object.defineProperty(t,"Credentials",{enumerable:!0,get:function(){return n.Credentials}});var s=r(50);Object.defineProperty(t,"DocumentStatus",{enumerable:!0,get:function(){return s.DocumentStatus}}),Object.defineProperty(t,"Documents",{enumerable:!0,get:function(){return s.Documents}});var i=r(725);Object.defineProperty(t,"LaraApiError",{enumerable:!0,get:function(){return i.LaraApiError}}),Object.defineProperty(t,"LaraError",{enumerable:!0,get:function(){return i.LaraError}}),Object.defineProperty(t,"TimeoutError",{enumerable:!0,get:function(){return i.TimeoutError}});var a=r(514);Object.defineProperty(t,"Glossaries",{enumerable:!0,get:function(){return a.Glossaries}});var u=r(731);Object.defineProperty(t,"ImageTranslator",{enumerable:!0,get:function(){return u.ImageTranslator}});var l=r(629);Object.defineProperty(t,"Memories",{enumerable:!0,get:function(){return l.Memories}});var c=r(660);Object.defineProperty(t,"Translator",{enumerable:!0,get:function(){return c.Translator}});var d=r(311);Object.defineProperty(t,"version",{enumerable:!0,get:function(){return d.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 u=(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,u)}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:u}=await this.upload(t,e,r,o,i),l=(null==s?void 0:s.outputFormat)?{outputFormat:s.outputFormat}:void 0,c=Date.now();for(;Date.now()-c<9e5;){await new Promise(t=>setTimeout(t,2e3));const{status:t,errorReason:e}=await this.status(u);if(t===a.TRANSLATED)return await this.download(u,l);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:u}=await this.upload(t,e,r,o,i),l=(null==s?void 0:s.outputFormat)?{outputFormat:s.outputFormat}:void 0,c=Date.now();for(;Date.now()-c<9e5;){await new Promise(t=>setTimeout(t,2e3));const{status:t,errorReason:e}=await this.status(u);if(t===a.TRANSLATED)return await this.downloadStream(u,l);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.2"},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},328: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.AudioTranslator=e.VoiceGender=e.AudioStatus=void 0;const n=r(725),s=o(r(821));var i,a;!function(t){t.INITIALIZED="initialized",t.ANALYZING="analyzing",t.PAUSED="paused",t.READY="ready",t.TRANSLATING="translating",t.TRANSLATED="translated",t.ERROR="error"}(i||(e.AudioStatus=i={})),function(t){t.MALE="male",t.FEMALE="female"}(a||(e.VoiceGender=a={})),e.AudioTranslator=class{constructor(t){this.client=t,this.s3Client=(0,s.default)()}async upload(t,e,r,o,n){const{url:s,fields:i}=await this.client.get("/v2/audio/upload-url",{filename:e});await this.s3Client.upload(s,i,t,null==n?void 0:n.contentLength);const a=(null==n?void 0:n.noTrace)?{"X-No-Trace":"true"}:{};return this.client.post("/v2/audio/translate",{source:r,target:o,s3key:i.key,adapt_to:null==n?void 0:n.adaptTo,glossaries:null==n?void 0:n.glossaries,style:null==n?void 0:n.style,voice_gender:null==n?void 0:n.voiceGender},void 0,a)}async status(t){return await this.client.get(`/v2/audio/${t}`)}async download(t){const{url:e}=await this.client.get(`/v2/audio/${t}/download-url`);return await this.s3Client.downloadStream(e)}async translate(t,e,r,o,s){const{id:a}=await this.upload(t,e,r,o,s),u=Date.now();for(;Date.now()-u<9e5;){await new Promise(t=>setTimeout(t,2e3));const{status:t,errorReason:e}=await this.status(a);if(t===i.TRANSLATED)return await this.download(a);if(t===i.ERROR)throw new n.LaraApiError(500,"AudioError",e)}throw new n.TimeoutError}}},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),u=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,n){return this.request("POST",t,e,r,o,void 0,n)}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,s=0,i){await this.ensureAuthenticated();const u=e.startsWith("/")?e:`/${e}`,l=await this.buildRequestHeaders(r,o,n),c=this.buildRequestBody(r,o);l.Authorization=`Bearer ${this.token}`;const d=await this.send(t,u,l,c,i);if(this.isSuccessResponse(d))return i?d.body:(0,a.parseContent)(d.body);if(401===d.statusCode&&s<1)return this.token=void 0,await this.refreshTokens(),this.request(t,e,r,o,n,s+1,i);throw this.createApiError(d)}async*requestStream(t,e,r,o,n,s=0){await this.ensureAuthenticated();const i=e.startsWith("/")?e:`/${e}`,u=await this.buildRequestHeaders(r,o,n),l=this.buildRequestBody(r,o);u.Authorization=`Bearer ${this.token}`;for await(const c of this.sendAndGetStream(t,i,u,l)){if(401===c.statusCode&&s<1)return this.token=void 0,await this.refreshTokens(),void(yield*this.requestStream(t,e,r,o,n,s+1));if(!this.isSuccessResponse(c))throw this.createApiError(c);yield(0,a.parseContent)(c.body.content||c.body)}}isTokenExpired(t=5e3){if(!this.token)return!0;try{const e=this.token.split(".");if(3!==e.length)return!0;let r=e[1].replace(/-/g,"+").replace(/_/g,"/");for(;r.length%4;)r+="=";const o="undefined"!=typeof Buffer?Buffer.from(r,"base64").toString("utf-8"):atob(r),{exp:n}=JSON.parse(o);return"number"==typeof n&&1e3*n<=Date.now()+t}catch{return!0}}async ensureAuthenticated(){if(!this.token||this.isTokenExpired()){if(this.token=void 0,this.authenticationPromise)return this.authenticationPromise;this.authenticationPromise=this.performAuthentication();try{await this.authenticationPromise,this.authenticationPromise=void 0}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,this.authenticationPromise=void 0}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":u.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)||t.body||{};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,o){let n=!1,s="csv/table-uni";return"boolean"==typeof r?n=r:"string"==typeof r&&(s=r,n=null!=o&&o),await this.client.post(`/v2/glossaries/${t}/import`,{compression:n?"gzip":void 0,content_type:s},{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})}async addOrReplaceEntry(t,e,r){return await this.client.put(`/v2/glossaries/${t}/content`,{terms:e,guid:r})}async deleteEntry(t,e,r){return await this.client.delete(`/v2/glossaries/${t}/content`,void 0,{term:e,guid: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,u){const l={source:e,target:r,sentence:o,translation:n,tuid:s,sentence_before:i,sentence_after:a};return Array.isArray(t)?(l.ids=t,await this.client.put("/v2/memories/content",l,void 0,u)):await this.client.put(`/v2/memories/${t}/content`,l,void 0,u)}async deleteTranslation(t,e,r,o,n,s,i,a){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.delete("/v2/memories/content",void 0,u)):await this.client.delete(`/v2/memories/${t}/content`,void 0,u)}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,s){var i;let a;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);a=t}else a=JSON.stringify(n,void 0,0);const u=this.timeout&&this.timeout>0?AbortSignal.timeout(this.timeout):void 0;try{const o=await fetch(this.baseUrl+e,{headers:r,method:t,body:a,signal:u});return s&&o.status>=200&&o.status<300?{statusCode:o.status,body:o.body,headers:Object.fromEntries(o.headers)}:(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(t){if(t instanceof Error&&("AbortError"===t.name||"TimeoutError"===t.name))throw new o.TimeoutError(`Request timed out after ${this.timeout}ms`);throw t}}async*sendAndGetStream(t,e,r,n){let s;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);const i=this.timeout&&this.timeout>0?AbortSignal.timeout(this.timeout):void 0;let a;try{a=await fetch(this.baseUrl+e,{headers:r,method:t,body:s,signal:i})}catch(t){if(t instanceof Error&&("AbortError"===t.name||"TimeoutError"===t.name))throw new o.TimeoutError(`Request timed out after ${this.timeout}ms`);throw t}if(!a.body)throw new Error("Response body is not available for streaming");const u=a.body.getReader(),l=new TextDecoder;let c="";try{for(;;){let t;try{t=await u.read()}catch(t){if(t instanceof Error&&("AbortError"===t.name||"TimeoutError"===t.name))throw new o.TimeoutError(`Request timed out after ${this.timeout}ms`);throw t}const{done:e,value:r}=t;if(e){if(c.trim())try{const t=JSON.parse(c);yield{statusCode:t.status||a.status,body:t.data||t,headers:Object.fromEntries(a.headers)}}catch(t){}break}c+=l.decode(r,{stream:!0});const n=c.split("\n");c=n.pop()||"";for(const t of n)if(t.trim())try{const e=JSON.parse(t);yield{statusCode:e.status||a.status,body:e.data||e,headers:Object.fromEntries(a.headers)}}catch(t){}}}finally{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(328),u=r(50),l=r(514),c=r(731),d=r(629),h=i(r(837)),p=r(221),f=r(311);e.Translator=class{constructor(t,e){this.client=(0,h.default)(t,null==e?void 0:e.serverUrl,null==e?void 0:e.keepAlive,null==e?void 0:e.connectionTimeoutMs),this.memories=new d.Memories(this.client),this.documents=new u.Documents(this.client),this.glossaries=new l.Glossaries(this.client),this.audio=new a.AudioTranslator(this.client),this.images=new c.ImageTranslator(this.client)}get version(){return f.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("/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,metadata:null==o?void 0:o.metadata},void 0,s);let a;for await(const t of i)(null==o?void 0:o.reasoning)&&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=p.DEFAULT_BASE_URL);const{body:e}=await h.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}}},731:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ImageTranslator=void 0,e.ImageTranslator=class{constructor(t){this.client=t}async translate(t,e,r,o){const n=(null==o?void 0:o.noTrace)?{"X-No-Trace":"true"}:{};return n["Content-Type"]="multipart/form-data",this.client.post("/v2/images/translate",{source:e,target:r,adapt_to:JSON.stringify(null==o?void 0:o.adaptTo),glossaries:JSON.stringify(null==o?void 0:o.glossaries),style:null==o?void 0:o.style,text_removal:null==o?void 0:o.textRemoval},{image:t},n,!0)}async translateText(t,e,r,o){const n=(null==o?void 0:o.noTrace)?{"X-No-Trace":"true"}:{};return n["Content-Type"]="multipart/form-data",this.client.post("/v2/images/translate-text",{source:e,target:r,adapt_to:JSON.stringify(null==o?void 0:o.adaptTo),glossaries:JSON.stringify(null==o?void 0:o.glossaries),style:null==o?void 0:o.style,verbose:JSON.stringify(null==o?void 0:o.verbose)},{image:t},n)}}},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.ImageTranslator=t.Glossaries=t.TimeoutError=t.LaraError=t.LaraApiError=t.Documents=t.DocumentStatus=t.Credentials=t.AuthToken=t.AccessKey=t.VoiceGender=t.AudioTranslator=t.AudioStatus=void 0;var e=r(328);Object.defineProperty(t,"AudioStatus",{enumerable:!0,get:function(){return e.AudioStatus}}),Object.defineProperty(t,"AudioTranslator",{enumerable:!0,get:function(){return e.AudioTranslator}}),Object.defineProperty(t,"VoiceGender",{enumerable:!0,get:function(){return e.VoiceGender}});var n=r(414);Object.defineProperty(t,"AccessKey",{enumerable:!0,get:function(){return n.AccessKey}}),Object.defineProperty(t,"AuthToken",{enumerable:!0,get:function(){return n.AuthToken}}),Object.defineProperty(t,"Credentials",{enumerable:!0,get:function(){return n.Credentials}});var s=r(50);Object.defineProperty(t,"DocumentStatus",{enumerable:!0,get:function(){return s.DocumentStatus}}),Object.defineProperty(t,"Documents",{enumerable:!0,get:function(){return s.Documents}});var i=r(725);Object.defineProperty(t,"LaraApiError",{enumerable:!0,get:function(){return i.LaraApiError}}),Object.defineProperty(t,"LaraError",{enumerable:!0,get:function(){return i.LaraError}}),Object.defineProperty(t,"TimeoutError",{enumerable:!0,get:function(){return i.TimeoutError}});var a=r(514);Object.defineProperty(t,"Glossaries",{enumerable:!0,get:function(){return a.Glossaries}});var u=r(731);Object.defineProperty(t,"ImageTranslator",{enumerable:!0,get:function(){return u.ImageTranslator}});var l=r(629);Object.defineProperty(t,"Memories",{enumerable:!0,get:function(){return l.Memories}});var c=r(660);Object.defineProperty(t,"Translator",{enumerable:!0,get:function(){return c.Translator}});var d=r(311);Object.defineProperty(t,"version",{enumerable:!0,get:function(){return d.version}})})(),o})());
|