UNPKG

@translated/lara

Version:

Official Lara SDK for JavaScript and Node.js

1 lines • 33.6 kB
!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={328(t,e,r){var s=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 i=r(725),n=s(r(821));var a,o;!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.AudioStatus=a={})),function(t){t.MALE="male",t.FEMALE="female"}(o||(e.VoiceGender=o={})),e.AudioTranslator=class{constructor(t){this.client=t,this.s3Client=(0,n.default)()}async upload(t,e,r,s,i){const{url:n,fields:a}=await this.client.get("/v2/audio/upload-url",{filename:e});await this.s3Client.upload(n,a,t,null==i?void 0:i.contentLength);const o=(null==i?void 0:i.noTrace)?{"X-No-Trace":"true"}:{};return this.client.post("/v2/audio/translate",{source:r,target:s,s3key:a.key,adapt_to:null==i?void 0:i.adaptTo,glossaries:null==i?void 0:i.glossaries,style:null==i?void 0:i.style,voice_cloning:null==i?void 0:i.voiceCloning,voice_gender:null==i?void 0:i.voiceGender},void 0,o)}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,s,n){const{id:o}=await this.upload(t,e,r,s,n),l=Date.now();for(;Date.now()-l<9e5;){await new Promise(t=>setTimeout(t,2e3));const{status:t,errorReason:e}=await this.status(o);if(t===a.TRANSLATED)return await this.download(o);if(t===a.ERROR)throw new i.LaraApiError(500,"AudioError",e)}throw new i.TimeoutError}async uploadForTranscription(t,e,r,s,i){const{url:n,fields:a}=await this.client.get("/v2/audio/upload-url",{filename:e});await this.s3Client.upload(n,a,t,null==i?void 0:i.contentLength);const o=(null==i?void 0:i.noTrace)?{"X-No-Trace":"true"}:{};return this.client.post("/v2/audio/translate-transcript",{source:r,target:s,s3key:a.key,adapt_to:null==i?void 0:i.adaptTo,glossaries:null==i?void 0:i.glossaries,style:null==i?void 0:i.style},void 0,o)}async getTranslatedTranscript(t){return await this.client.get(`/v2/audio/${t}/translated-transcript`)}async translateTranscript(t,e,r,s,n){const{id:o}=await this.uploadForTranscription(t,e,r,s,n),l=Date.now();for(;Date.now()-l<9e5;){await new Promise(t=>setTimeout(t,2e3));const{status:t,errorReason:e}=await this.status(o);if(t===a.TRANSLATED)return await this.getTranslatedTranscript(o);if(t===a.ERROR)throw new i.LaraApiError(500,"AudioError",e)}throw new i.TimeoutError}}},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}}},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 s=await this.subtle.importKey("raw",r.encode(t),{name:"hmac",hash:{name:"sha-256"}},!1,["sign"]),i=await this.subtle.sign("hmac",s,r.encode(e));return btoa(String.fromCharCode(...new Uint8Array(i)))}}},326(t,e,r){Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(){return void 0===i&&(i=new s.BrowserCrypto),i};const s=r(780);let i},50(t,e,r){var s=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 i=r(725),n=s(r(821)),a=s(r(841));var o;!function(t){t.INITIALIZED="initialized",t.ANALYZING="analyzing",t.PAUSED="paused",t.READY="ready",t.TRANSLATING="translating",t.TRANSLATED="translated",t.ERROR="error"}(o||(e.DocumentStatus=o={})),e.Documents=class{constructor(t){this.client=t,this.s3Client=(0,n.default)()}async upload(t,e,r,s,i){const{url:n,fields:o}=await this.client.get("/v2/documents/upload-url",{filename:e});await this.s3Client.upload(n,o,t,null==i?void 0:i.contentLength);const l=(null==i?void 0:i.noTrace)?{"X-No-Trace":"true"}:{};return this.client.post("/v2/documents",{source:r,target:s,s3key:o.key,adapt_to:null==i?void 0:i.adaptTo,glossaries:null==i?void 0:i.glossaries,style:null==i?void 0:i.style,password:null==i?void 0:i.password,extraction_params:(null==i?void 0:i.extractionParams)?(0,a.default)(i.extractionParams):void 0},void 0,l)}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,s,n){const a={adaptTo:null==n?void 0:n.adaptTo,glossaries:null==n?void 0:n.glossaries,noTrace:null==n?void 0:n.noTrace,style:null==n?void 0:n.style,password:null==n?void 0:n.password,extractionParams:null==n?void 0:n.extractionParams,contentLength:null==n?void 0:n.contentLength},{id:l}=await this.upload(t,e,r,s,a),u=(null==n?void 0:n.outputFormat)?{outputFormat:n.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(l);if(t===o.TRANSLATED)return await this.download(l,u);if(t===o.ERROR)throw new i.LaraApiError(500,"DocumentError",e)}throw new i.TimeoutError}async translateStream(t,e,r,s,n){const a={adaptTo:null==n?void 0:n.adaptTo,glossaries:null==n?void 0:n.glossaries,noTrace:null==n?void 0:n.noTrace,style:null==n?void 0:n.style,password:null==n?void 0:n.password,extractionParams:null==n?void 0:n.extractionParams,contentLength:null==n?void 0:n.contentLength},{id:l}=await this.upload(t,e,r,s,a),u=(null==n?void 0:n.outputFormat)?{outputFormat:n.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(l);if(t===o.TRANSLATED)return await this.downloadStream(l,u);if(t===o.ERROR)throw new i.LaraApiError(500,"DocumentError",e)}throw new i.TimeoutError}}},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,s){super(r),this.statusCode=t,this.type=e,this.message=r,this.idTransaction=s}}},514(t,e,r){Object.defineProperty(e,"__esModule",{value:!0}),e.Glossaries=void 0;const s=r(725);e.Glossaries=class{constructor(t){this.client=t,this.pollingInterval=2e3}async list(){return await this.client.get("/v2/glossaries")}async listPaginated(t){return await this.client.getCollection("/v2/glossaries",t)}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 s.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 getShares(t){return await this.client.get(`/v2/glossaries/${t}/shares`)}async addAccountShare(t,e){return await this.client.post(`/v2/glossaries/${t}/shares`,{name:e})}async revokeAccountShare(t){return await this.client.delete(`/v2/glossaries/${t}/shares`)}async renameAccountShare(t,e){return await this.client.put(`/v2/glossaries/${t}/shares`,{name:e})}async addGroupShare(t,e,r){return await this.client.post(`/v2/glossaries/${t}/shares/groups/${e}`,{name:r})}async revokeGroupShare(t,e){return await this.client.delete(`/v2/glossaries/${t}/shares/groups/${e}`)}async renameGroupShare(t,e,r){return await this.client.put(`/v2/glossaries/${t}/shares/groups/${e}`,{name:r})}async importFile(t,e,r={}){const{contentType:s="csv/table-uni",gzip:i=!1,callbackUrl:n}=r;return await this.client.post(`/v2/glossaries/${t}/import`,{compression:i?"gzip":void 0,content_type:s,callback_url:n},{csv:e})}async importCsv(t,e,r,s,i){if("string"==typeof r){if("csv/table-uni"!==r&&"csv/table-multi"!==r)throw new TypeError("importCsv only supports CSV formats; use importFile for TBX files.");const n="boolean"==typeof s?s:void 0;return await this.importFile(t,e,{contentType:r,gzip:n,callbackUrl:i})}const n="string"==typeof s?s:void 0;return await this.importFile(t,e,{gzip:r,callbackUrl:n})}async getImportStatus(t){return await this.client.get(`/v2/glossaries/imports/${t}`)}async waitForImport(t,e,r){const i=Date.now();for(;t.progress<1;){if(r&&Date.now()-i>r)throw new s.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 exportAsync(t,e,r,s){return await this.client.get(`/v2/glossaries/${t}/export/async`,{callback_url:e,content_type:r,source:s})}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})}}},731(t,e,r){var s=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),e.ImageTranslator=void 0;const i=s(r(841));e.ImageTranslator=class{constructor(t){this.client=t}async translate(t,e,r,s){var i;const n=(null==s?void 0:s.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==s?void 0:s.adaptTo),glossaries:JSON.stringify(null==s?void 0:s.glossaries),style:null==s?void 0:s.style,model:null!==(i=null==s?void 0:s.model)&&void 0!==i?i:null==s?void 0:s.textRemoval},{image:t},n,!0)}async translateText(t,e,r,s){const i=(null==s?void 0:s.noTrace)?{"X-No-Trace":"true"}:{};return i["Content-Type"]="multipart/form-data",this.client.post("/v2/images/translate-text",{source:e,target:r,adapt_to:JSON.stringify(null==s?void 0:s.adaptTo),glossaries:JSON.stringify(null==s?void 0:s.glossaries),style:null==s?void 0:s.style,verbose:JSON.stringify(null==s?void 0:s.verbose),include_layout:JSON.stringify(null==s?void 0:s.includeLayout)},{image:t},i)}async renderTranslated(t,e,r,s,n,a){const o=s.map(t=>({text:t.text,translation:t.translation,bbox:(0,i.default)(t.bbox),lines_bboxes:(0,i.default)(t.linesBboxes),text_info:(0,i.default)(t.textInfo),alignment:t.alignment}));return this.client.post("/v2/images/render-translated",{source:e,target:r,paragraphs:JSON.stringify(o),model:n},{image:t},{"Content-Type":"multipart/form-data",...a?{"X-No-Trace":"true"}:{}},!0)}}},629(t,e,r){Object.defineProperty(e,"__esModule",{value:!0}),e.Memories=void 0;const s=r(725);e.Memories=class{constructor(t){this.client=t,this.pollingInterval=2e3}async list(){return await this.client.get("/v2/memories")}async listPaginated(t){return await this.client.getCollection("/v2/memories",t)}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 s.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 getShares(t){return await this.client.get(`/v2/memories/${t}/shares`)}async addAccountShare(t,e){return await this.client.post(`/v2/memories/${t}/shares`,{name:e})}async revokeAccountShare(t){return await this.client.delete(`/v2/memories/${t}/shares`)}async renameAccountShare(t,e){return await this.client.put(`/v2/memories/${t}/shares`,{name:e})}async addGroupShare(t,e,r){return await this.client.post(`/v2/memories/${t}/shares/groups/${e}`,{name:r})}async revokeGroupShare(t,e){return await this.client.delete(`/v2/memories/${t}/shares/groups/${e}`)}async renameGroupShare(t,e,r){return await this.client.put(`/v2/memories/${t}/shares/groups/${e}`,{name:r})}async importTmx(t,e,r,s){let i,n=!1;return"boolean"==typeof r?(n=r,i=s):"string"==typeof r&&(i=r),await this.client.post(`/v2/memories/${t}/import`,{compression:n?"gzip":void 0,callback_url:i},{tmx:e})}async exportAsync(t,e,r){return await this.client.get(`/v2/memories/${t}/export/async`,{callback_url:e,format:r})}async addTranslation(t,e,r,s,i,n,a,o,l){const u={source:e,target:r,sentence:s,translation:i,tuid:n,sentence_before:a,sentence_after:o};return Array.isArray(t)?(u.ids=t,await this.client.put("/v2/memories/content",u,void 0,l)):await this.client.put(`/v2/memories/${t}/content`,u,void 0,l)}async deleteTranslation(t,e,r,s,i,n,a,o){const l={source:e,target:r,sentence:s,translation:i,tuid:n,sentence_before:a,sentence_after:o};return Array.isArray(t)?(l.ids=t,await this.client.delete("/v2/memories/content",void 0,l)):await this.client.delete(`/v2/memories/${t}/content`,void 0,l)}async getImportStatus(t){return await this.client.get(`/v2/memories/imports/${t}`)}async waitForImport(t,e,r){const i=Date.now();for(;t.progress<1;){if(r&&Date.now()-i>r)throw new s.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 s=r(725),i=r(412);class n extends i.LaraClient{constructor(t,e,r,s,i){super(e,i),this.sdkName="lara-browser";let n=`${t.secure?"https":"http"}://${t.hostname}`;var a,o;a=t.port,o=t.secure,80===a&&!o||443===a&&o||(n+=`:${t.port}`),this.baseUrl=n,this.timeout=s}async send(t,e,r,i,n){var a;let o;if(i)if("multipart/form-data"===r["Content-Type"]){delete r["Content-Type"];const t=new FormData;for(const[e,r]of Object.entries(i))if(r)if(Array.isArray(r))for(const s of r)t.append(e,s);else t.append(e,r);o=t}else o=JSON.stringify(i,void 0,0);const l=this.timeout&&this.timeout>0?AbortSignal.timeout(this.timeout):void 0;try{const s=await fetch(this.baseUrl+e,{headers:r,method:t,body:o,signal:l});if(n&&s.status>=200&&s.status<300)return{statusCode:s.status,body:s.body,headers:Object.fromEntries(s.headers)};const i=null!==(a=s.headers.get("Content-Type"))&&void 0!==a?a:"";return i.includes("text/csv")||i.includes("application/xml")?{statusCode:s.status,body:await s.text(),headers:Object.fromEntries(s.headers)}:{statusCode:s.status,body:await s.json(),headers:Object.fromEntries(s.headers)}}catch(t){if(t instanceof Error&&("AbortError"===t.name||"TimeoutError"===t.name))throw new s.TimeoutError(`Request timed out after ${this.timeout}ms`);throw t}}async*sendAndGetStream(t,e,r,i){let n;if(i)if("multipart/form-data"===r["Content-Type"]){delete r["Content-Type"];const t=new FormData;for(const[e,r]of Object.entries(i))if(r)if(Array.isArray(r))for(const s of r)t.append(e,s);else t.append(e,r);n=t}else n=JSON.stringify(i,void 0,0);const a=this.timeout&&this.timeout>0?AbortSignal.timeout(this.timeout):void 0;let o;try{o=await fetch(this.baseUrl+e,{headers:r,method:t,body:n,signal:a})}catch(t){if(t instanceof Error&&("AbortError"===t.name||"TimeoutError"===t.name))throw new s.TimeoutError(`Request timed out after ${this.timeout}ms`);throw t}if(!o.body)throw new Error("Response body is not available for streaming");const l=o.body.getReader(),u=new TextDecoder;let c="";try{for(;;){let t;try{t=await l.read()}catch(t){if(t instanceof Error&&("AbortError"===t.name||"TimeoutError"===t.name))throw new s.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||o.status,body:t.data||t,headers:Object.fromEntries(o.headers)}}catch(t){}break}c+=u.decode(r,{stream:!0});const i=c.split("\n");c=i.pop()||"";for(const t of i)if(t.trim())try{const e=JSON.parse(t);yield{statusCode:e.status||o.status,body:e.data||e,headers:Object.fromEntries(o.headers)}}catch(t){}}}finally{l.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=n;class a{static async get(t,e){return a.send("GET",t,e)}static async send(t,e,r,s){var i;let n;if(s)if(r&&"multipart/form-data"===r["Content-Type"]){delete r["Content-Type"];const t=new FormData;for(const[e,r]of Object.entries(s))if(r)if(Array.isArray(r))for(const s of r)t.append(e,s);else t.append(e,r);n=t}else n=JSON.stringify(s,void 0,0);const a=await fetch(e,{headers:r,method:t,body:n});return{statusCode:a.status,headers:Object.fromEntries(a.headers),body:(null===(i=a.headers.get("Content-Type"))||void 0===i?void 0:i.includes("application/json"))?await a.json():await a.text()}}}e.BrowserClient=a},412(t,e,r){var s=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),e.LaraClient=void 0;const i=r(414),n=s(r(326)),a=r(725),o=r(916),l=r(741),u=r(311);e.LaraClient=class{constructor(t,e){if(this.sdkName="lara-node",this.crypto=(0,n.default)(),this.extraHeaders={},t instanceof i.AccessKey)this.accessKey=t;else{if(!(t instanceof i.AuthToken))throw new Error("Invalid authentication method provided");this.authToken=t}this.authSessionId=e}setExtraHeader(t,e){this.extraHeaders[t]=e}get(t,e,r){return this.request("GET",this.buildPathWithQuery(t,e),void 0,void 0,r)}async getCollection(t,e,r){const s=await this.requestWithMetadata("GET",this.buildPathWithQuery(t,e),void 0,void 0,r);return(0,o.toCollectionResult)(s)}delete(t,e,r,s){return this.request("DELETE",this.buildPathWithQuery(t,e),r,void 0,s)}post(t,e,r,s,i){return this.request("POST",t,e,r,s,void 0,i)}async*postAndGetStream(t,e,r,s){for await(const i of this.requestStream("POST",t,e,r,s))yield i}put(t,e,r,s){return this.request("PUT",t,e,r,s)}patch(t,e,r,s){return this.request("PATCH",t,e,r,s)}async request(t,e,r,s,i,n=0,a){return(await this.requestWithMetadata(t,e,r,s,i,n,a)).body}async requestWithMetadata(t,e,r,s,i,n=0,a){await this.ensureAuthenticated();const o=e.startsWith("/")?e:`/${e}`,u=await this.buildRequestHeaders(r,s,i),c=this.buildRequestBody(r,s);u.Authorization=`Bearer ${this.token}`;const d=await this.send(t,o,u,c,a);if(this.isSuccessResponse(d))return{...d,body:a?d.body:(0,l.parseContent)(d.body)};if(401===d.statusCode&&n<1)return this.token=void 0,await this.refreshOrReauthenticate(),this.requestWithMetadata(t,e,r,s,i,n+1,a);throw this.createApiError(d)}async*requestStream(t,e,r,s,i,n=0){await this.ensureAuthenticated();const a=e.startsWith("/")?e:`/${e}`,o=await this.buildRequestHeaders(r,s,i),u=this.buildRequestBody(r,s);o.Authorization=`Bearer ${this.token}`;for await(const c of this.sendAndGetStream(t,a,o,u)){if(401===c.statusCode&&n<1)return this.token=void 0,await this.refreshOrReauthenticate(),void(yield*this.requestStream(t,e,r,s,i,n+1));if(!this.isSuccessResponse(c))throw this.createApiError(c);yield(0,l.parseContent)(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 s="undefined"!=typeof Buffer?Buffer.from(r,"base64").toString("utf-8"):atob(r),{exp:i}=JSON.parse(s);return"number"==typeof i&&1e3*i<=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 a.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 a.LaraApiError?t:new a.LaraApiError(500,"AuthenticationError",t.message)}}}}async performAuthentication(){return this.authToken?(this.token=this.authToken.token,this.refreshToken=this.authToken.refreshToken,void(this.authToken=void 0)):this.doRefreshOrReauthenticate()}refreshOrReauthenticate(){return this.refreshPromise||(this.refreshPromise=this.doRefreshOrReauthenticate().finally(()=>{this.refreshPromise=void 0})),this.refreshPromise}async doRefreshOrReauthenticate(){if(this.refreshToken)try{return void await this.refreshTokens()}catch(t){if(this.refreshToken=void 0,!this.accessKey)throw t}if(!this.accessKey)throw new Error("No authentication method available for token renewal");await this.authenticateWithAccessKey()}async refreshTokens(){const t={Authorization:`Bearer ${this.refreshToken}`,"X-Lara-Date":(new Date).toUTCString(),...this.extraHeaders},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,...this.extraHeaders};r.Authorization=`Lara:${await this.sign("POST","/v2/auth",r)}`,this.applySessionHeader(r);const s=await this.send("POST","/v2/auth",r,t);this.handleAuthResponse(s)}applySessionHeader(t){this.authSessionId&&(t["X-Lara-Auth-Session-Id"]=this.authSessionId)}buildPathWithQuery(t,e){const r=this.filterNullish(e);return r?`${t}?${new URLSearchParams(r).toString()}`:t}async buildRequestHeaders(t,e,r){const s={"X-Lara-Date":(new Date).toUTCString(),"X-Lara-SDK-Name":this.sdkName,"X-Lara-SDK-Version":u.version,...this.filterNullish(this.extraHeaders),...this.filterNullish(r)},i=this.filterNullish(t);if(e)s["Content-Type"]="multipart/form-data";else if(i){s["Content-Type"]="application/json";const t=JSON.stringify(i,void 0,0);s["Content-Length"]=(new TextEncoder).encode(t).length.toString()}return s}buildRequestBody(t,e){const r=this.filterNullish(t);if(e){const t={};for(const[r,s]of Object.entries(e))t[r]=this.wrapMultiPartFile(s);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)){this.token=t.body.token;const e=t.headers["x-lara-refresh-token"];return void(this.refreshToken=e||void 0)}throw this.createApiError(t)}createApiError(t){const e=t.body||{};return new a.LaraApiError(t.statusCode,e.type||"UnknownError",e.message||"An unknown error occurred")}async sign(t,e,r){if(!this.accessKey)throw new Error("Access key not provided for signing");const s=r["X-Lara-Date"].trim(),i=(r["Content-MD5"]||"").trim(),n=(r["Content-Type"]||"").trim(),a=`${(r["X-HTTP-Method-Override"]||t).trim().toUpperCase()}\n${e}\n${i}\n${n}\n${s}`;return this.crypto.hmac(this.accessKey.secret,a)}}},837(t,e,r){Object.defineProperty(e,"__esModule",{value:!0}),e.HttpClient=e.LaraClient=void 0,e.default=function(t,e,r,n,a){const o=new URL(e||s.DEFAULT_BASE_URL);if("https:"!==o.protocol&&"http:"!==o.protocol)throw new TypeError(`Invalid URL (protocol): ${o.protocol}`);const l={secure:"https:"===o.protocol,hostname:o.hostname,port:o.port?parseInt(o.port,10):"https:"===o.protocol?443:80};return new i.BrowserLaraClient(l,t,null==r||r,n,a)};const s=r(221),i=r(631);var n=r(412);Object.defineProperty(e,"LaraClient",{enumerable:!0,get:function(){return n.LaraClient}});var a=r(631);Object.defineProperty(e,"HttpClient",{enumerable:!0,get:function(){return a.BrowserClient}})},343(t,e,r){Object.defineProperty(e,"__esModule",{value:!0}),e.BrowserS3Client=void 0;const s=r(364);class i extends s.S3Client{async _upload(t,e,r){const s=new FormData;for(const[t,r]of Object.entries(e))s.append(t,r);s.append("file",r),await fetch(t,{method:"POST",body:s})}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=i},364(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.S3Client=void 0,e.S3Client=class{async upload(t,e,r,s){return this._upload(t,e,this.wrapMultiPartFile(r),s)}}},821(t,e,r){Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(){return new s.BrowserS3Client};const s=r(343)},816(t,e,r){Object.defineProperty(e,"__esModule",{value:!0}),e.Styleguides=void 0;const s=r(725);e.Styleguides=class{constructor(t){this.client=t}async list(){return await this.client.get("/v2/styleguides")}async listPaginated(t){return await this.client.getCollection("/v2/styleguides",t)}async get(t){try{return await this.client.get(`/v2/styleguides/${t}`)}catch(t){if(t instanceof s.LaraApiError&&404===t.statusCode)return null;throw t}}async create(t,e){return await this.client.post("/v2/styleguides",{name:t,content:e})}async update(t,e,r){return await this.client.put(`/v2/styleguides/${t}`,{name:e,content:r})}async delete(t){return await this.client.delete(`/v2/styleguides/${t}`)}async getShares(t){return await this.client.get(`/v2/styleguides/${t}/shares`)}async addAccountShare(t,e){return await this.client.post(`/v2/styleguides/${t}/shares`,{name:e})}async revokeAccountShare(t){return await this.client.delete(`/v2/styleguides/${t}/shares`)}async renameAccountShare(t,e){return await this.client.put(`/v2/styleguides/${t}/shares`,{name:e})}async addGroupShare(t,e,r){return await this.client.post(`/v2/styleguides/${t}/shares/groups/${e}`,{name:r})}async revokeGroupShare(t,e){return await this.client.delete(`/v2/styleguides/${t}/shares/groups/${e}`)}async renameGroupShare(t,e,r){return await this.client.put(`/v2/styleguides/${t}/shares/groups/${e}`,{name:r})}}},660(t,e,r){var s,i=this&&this.__createBinding||(Object.create?function(t,e,r,s){void 0===s&&(s=r);var i=Object.getOwnPropertyDescriptor(e,r);i&&!("get"in i?!e.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,s,i)}:function(t,e,r,s){void 0===s&&(s=r),t[s]=e[r]}),n=this&&this.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),a=this&&this.__importStar||(s=function(t){return s=Object.getOwnPropertyNames||function(t){var e=[];for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[e.length]=r);return e},s(t)},function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r=s(t),a=0;a<r.length;a++)"default"!==r[a]&&i(e,t,r[a]);return n(e,t),e});Object.defineProperty(e,"__esModule",{value:!0}),e.Translator=void 0;const o=r(328),l=r(50),u=r(514),c=r(731),d=r(629),h=a(r(837)),p=r(816),y=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,null==e?void 0:e.sessionId),this.memories=new d.Memories(this.client),this.documents=new l.Documents(this.client),this.glossaries=new u.Glossaries(this.client),this.styleguides=new p.Styleguides(this.client),this.audio=new o.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,s,i){const n={};if(null==s?void 0:s.headers)for(const[t,e]of Object.entries(s.headers))n[t]=e;(null==s?void 0:s.noTrace)&&(n["X-No-Trace"]="true");const a=this.client.postAndGetStream("/v2/translate",{q:t,source:e,target:r,source_hint:null==s?void 0:s.sourceHint,content_type:null==s?void 0:s.contentType,multiline:null==s?void 0:s.multiline,adapt_to:null==s?void 0:s.adaptTo,glossaries:null==s?void 0:s.glossaries,instructions:null==s?void 0:s.instructions,timeout:null==s?void 0:s.timeoutInMillis,priority:null==s?void 0:s.priority,use_cache:null==s?void 0:s.useCache,cache_ttl:null==s?void 0:s.cacheTTLSeconds,verbose:null==s?void 0:s.verbose,style:null==s?void 0:s.style,reasoning:null==s?void 0:s.reasoning,effort:null==s?void 0:s.reasoningEffort,image_context:null==s?void 0:s.imageContext,metadata:null==s?void 0:s.metadata,profanities_detect:null==s?void 0:s.profanitiesDetect,profanities_handling:null==s?void 0:s.profanitiesHandling,styleguide_id:null==s?void 0:s.styleguideId,styleguide_reasoning:null==s?void 0:s.styleguideReasoning,styleguide_explanation_language:null==s?void 0:s.styleguideExplanationLanguage},void 0,n);let o;for await(const t of a)(null==s?void 0:s.reasoning)&&i&&i(t),o=t;if(!o)throw new Error("No translation result received.");return o}async detect(t,e,r){return await this.client.post("/v2/detect/language",{q:t,hint:e,passlist:r})}async detectProfanities(t,e,r){return await this.client.post("/v2/detect/profanities",{text:t,language:e,content_type:r})}async qualityEstimation(t,e,r,s){return await this.client.post("/v2/detect/quality-estimation",{source:t,target:e,sentence:r,translation:s})}static async getLoginUrl(t){t||(t=y.DEFAULT_BASE_URL);const{body:e}=await h.HttpClient.get(`${t.replace(/\/+$/,"")}/v2/auth/login-page`);return e}}},916(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.toCollectionResult=function(t){const e=(e,r)=>{var s;const i=null===(s=Object.entries(t.headers).find(([t])=>t.toLowerCase()===e))||void 0===s?void 0:s[1],n="string"==typeof i&&/^\d+$/.test(i)?Number(i):NaN;return Number.isSafeInteger(n)&&n>=r?n:void 0},r=e("x-total-count",0);if(void 0===r)throw new Error("Missing or invalid X-Total-Count response header");const s=e("x-page",1),i=e("x-page-size",1);return{items:t.body,total:r,...void 0!==s?{page:s}:{},...void 0!==i?{size:i}:{}}}},221(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.DEFAULT_BASE_URL=void 0,e.DEFAULT_BASE_URL="https://api.laratranslate.com"},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[s,i]of Object.entries(e))r[s.replace(/_([a-z])/g,(t,e)=>e.toUpperCase())]=t(i);return r}return e}},311(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.version=void 0,e.version="1.18.2"},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[s,i]of Object.entries(t))e[s.replace(/([A-Z])/g,"_$1").toLowerCase()]=r(i);return e}return t};e.default=r}},e={};function r(s){var i=e[s];if(void 0!==i)return i.exports;var n=e[s]={exports:{}};return t[s].call(n.exports,n,n.exports,r),n.exports}var s={};return(()=>{var t=s;Object.defineProperty(t,"__esModule",{value:!0}),t.version=t.Translator=t.Styleguides=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 i=r(414);Object.defineProperty(t,"AccessKey",{enumerable:!0,get:function(){return i.AccessKey}}),Object.defineProperty(t,"AuthToken",{enumerable:!0,get:function(){return i.AuthToken}}),Object.defineProperty(t,"Credentials",{enumerable:!0,get:function(){return i.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 a=r(725);Object.defineProperty(t,"LaraApiError",{enumerable:!0,get:function(){return a.LaraApiError}}),Object.defineProperty(t,"LaraError",{enumerable:!0,get:function(){return a.LaraError}}),Object.defineProperty(t,"TimeoutError",{enumerable:!0,get:function(){return a.TimeoutError}});var o=r(514);Object.defineProperty(t,"Glossaries",{enumerable:!0,get:function(){return o.Glossaries}});var l=r(731);Object.defineProperty(t,"ImageTranslator",{enumerable:!0,get:function(){return l.ImageTranslator}});var u=r(629);Object.defineProperty(t,"Memories",{enumerable:!0,get:function(){return u.Memories}});var c=r(816);Object.defineProperty(t,"Styleguides",{enumerable:!0,get:function(){return c.Styleguides}});var d=r(660);Object.defineProperty(t,"Translator",{enumerable:!0,get:function(){return d.Translator}});var h=r(311);Object.defineProperty(t,"version",{enumerable:!0,get:function(){return h.version}})})(),s})());