UNPKG

deeplx-lib

Version:

Powerful free DeepL API wrapper with no token required.

70 lines (68 loc) 1.82 kB
const DEEPL_URL = "https://www2.deepl.com/jsonrpc"; async function translate(options) { const body = getBody(options); return fetch(DEEPL_URL, { method: "POST", body, headers: { "Content-Type": "application/json" } }); } function parse2DeepLX(data) { const from = data.result.lang; const to = data.to; const texts = data.result.texts[0]; return { code: 200, id: data.id, method: "Free", from, to, source_lang: from, target_lang: data.to, data: texts.text, alternatives: texts.alternatives.map((i) => i.text) }; } function getBody({ from, to, text }) { const random = getRandomNumber(); const iCount = getICount(text); const timestamp = getTimestamp(iCount); const bodyString = JSON.stringify({ jsonrpc: "2.0", method: "LMT_handle_texts", params: { splitting: "newlines", lang: { source_lang_user_selected: from, target_lang: to }, texts: [{ text, requestAlternatives: 3 }], timestamp }, id: random }); const body = handlerBodyMethod(random, bodyString); return body; } function handlerBodyMethod(random, body) { const calc = (random + 5) % 29 === 0 || (random + 3) % 13 === 0; const method = calc ? '"method" : "' : '"method": "'; return body.replace('"method":"', method); } function getTimestamp(iCount) { const ts = Date.now(); if (iCount !== 0) { iCount = iCount + 1; return ts - ts % iCount + iCount; } else { return ts; } } function getICount(translate_text) { return translate_text.split("i").length - 1; } function getRandomNumber() { const random = Math.floor(Math.random() * 99999) + 1e5; return random * 1e3; } export { DEEPL_URL, getBody, getICount, getRandomNumber, getTimestamp, handlerBodyMethod, parse2DeepLX, translate };