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ified by jsDelivr using Terser v5.39.0.\n * Original file: /npm/bing-translate-api@4.0.2/src/index.js\n *\n * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files\n */\n","/**\n * @typedef {{\n *  IG: string,\n *  IID: string,\n *  subdomain?: string,\n *  key: number,\n *  token: string,\n *  tokenTs: number,\n *  tokenExpiryInterval: number,\n *  count: number\n * }} GlobalConfig\n *\n * @typedef {import('../index').TranslationResult} TranslationResult\n *\n * @typedef {import('got').Got} Got\n * @typedef {import('got').Options} GotOptions\n * @typedef {import('got').Agents} GotAgents\n * @typedef {import('got').CancelableRequest} GotCancelableRequest\n * @typedef {import('got').Response} GotResponse\n * @typedef {import('got').RequestError} GotRequestError\n */\n\n/**\n * @type {Got}\n */\nconst got = require('got')\n\nconst lang = require('./lang')\nconst config = require('./config.json')\n\nconst TRANSLATE_API_ROOT = 'https://{s}bing.com'\nconst TRANSLATE_WEBSITE = TRANSLATE_API_ROOT + config.websiteEndpoint\nconst TRANSLATE_API = TRANSLATE_API_ROOT + config.translateEndpoint\nconst TRANSLATE_API_SPELL_CHECK = TRANSLATE_API_ROOT + config.spellCheckEndpoint\n\n// PENDING: make it configurable?\nconst MAX_RETRY_COUNT = 3\n\n/**\n * @type {GlobalConfig | undefined}\n */\nlet globalConfig\n/**\n * @type {Promise<GlobalConfig> | undefined}\n */\nlet globalConfigPromise\n\nfunction replaceSubdomain(url, subdomain) {\n  return url.replace('{s}', subdomain ? subdomain + '.' : '')\n}\n\n/**\n * refetch global config if token is expired\n * @return {boolean} whether token is expired or not\n */\nfunction isTokenExpired() {\n  if (!globalConfig) {\n    return true\n  }\n  const { tokenTs, tokenExpiryInterval } = globalConfig\n  return Date.now() - tokenTs > tokenExpiryInterval\n}\n\n/**\n * fetch global config\n *\n * @param {string?} [userAgent]\n * @param {GotAgents?} [proxyAgents]\n *\n * @returns {Promise<GlobalConfig>}\n */\nasync function fetchGlobalConfig(userAgent, proxyAgents) {\n  // use last subdomain if exists\n  let subdomain = globalConfig && globalConfig.subdomain\n\n  try {\n    const { body, request: { redirects: [redirectUrl] } } = await got(\n      replaceSubdomain(TRANSLATE_WEBSITE, subdomain),\n      {\n        headers: {\n          'user-agent': userAgent || config.userAgent\n        },\n        agent: proxyAgents,\n        retry: {\n          limit: MAX_RETRY_COUNT,\n          methods: ['GET']\n        }\n      }\n    )\n\n    // when fetching for the second time, the subdomain may be unchanged\n    if (redirectUrl) {\n      subdomain = redirectUrl.match(/^https?:\\/\\/(\\w+)\\.bing\\.com/)[1]\n    }\n\n    const IG = body.match(/IG:\"([^\"]+)\"/)[1]\n    const IID = body.match(/data-iid=\"([^\"]+)\"/)[1]\n\n    const [key, token, tokenExpiryInterval] = JSON.parse(\n      body.match(/params_AbusePreventionHelper\\s?=\\s?([^\\]]+\\])/)[1]\n    )\n\n    const requiredFields = {\n      IG,\n      IID,\n      key,\n      token,\n      tokenTs: key,\n      tokenExpiryInterval\n    }\n    // check required fields\n    Object.entries(requiredFields).forEach(([field, value]) => {\n      if (!value) {\n        throw new Error(`failed to fetch required field: \\`${field}\\``)\n      }\n    })\n\n    return globalConfig = {\n      ...requiredFields,\n      subdomain,\n      // PENDING: reset count when value is large?\n      count: 0\n    }\n  } catch (e) {\n    console.error('failed to fetch global config')\n    throw e\n  }\n}\n\n/**\n * @param {boolean} isSpellCheck\n * @param {boolean} useEPT\n */\nfunction makeRequestURL(isSpellCheck, useEPT) {\n  const { IG, IID, subdomain } = globalConfig\n  return replaceSubdomain(isSpellCheck ? TRANSLATE_API_SPELL_CHECK : TRANSLATE_API, subdomain)\n    + '&IG=' + IG\n    + '&IID=' + (IID + (isSpellCheck || useEPT ? '.' + (++globalConfig.count) : ''))\n    + (\n      isSpellCheck || !useEPT\n        ? ''\n        // PENDING: might no rate limit but some languages are not supported for now\n        // (See also the `eptLangs` field in src/config.json)\n        : '&ref=TThis' +\n          '&edgepdftranslator=1'\n    )\n}\n\n/**\n * @param {boolean} isSpellCheck\n * @param {string} text\n * @param {string} fromLang\n * @param {string} toLang\n * @returns {{\n *   fromLang: string,\n *   to?: string,\n *   text: string,\n *   token: string,\n *   key: number,\n *   tryFetchingGenderDebiasedTranslations?: true\n * }}\n */\nfunction makeRequestBody(isSpellCheck, text, fromLang, toLang) {\n  const { token, key } = globalConfig\n  const body = {\n    fromLang,\n    text,\n    token,\n    key\n  }\n  if (!isSpellCheck) {\n    toLang && (body.to = toLang)\n\n    body.tryFetchingGenderDebiasedTranslations = true\n  }\n  return body\n}\n\n/**\n * @param {GotCancelableRequest} request\n */\nasync function wrapRequest(request) {\n  /**\n   * @type {GotResponse}\n   */\n  let response\n  /**\n   * @type {GotRequestError}\n   */\n  let err\n\n  try {\n    response = await request\n  } catch (e) {\n    response = (err = e).response\n  }\n\n  /**\n   * @type {string}\n   */\n  let readableErrMsg\n\n  const body = response.body\n\n  if (body.ShowCaptcha) {\n    readableErrMsg = `Sorry that bing translator seems to be asking for the captcha, please take care not to request too frequently.`\n  }\n  else if (body.StatusCode === 401 || response.statusCode === 401) {\n    readableErrMsg = `Translation limit exceeded. Please try it again later.`\n  }\n  else if (body.statusCode) {\n    readableErrMsg = `Something went wrong!`\n  }\n\n  if (readableErrMsg) {\n    const responseMsg = `Response status: ${response.statusCode} (${response.statusMessage})\\nResponse body  : ${JSON.stringify(body)}`\n    throw new Error(readableErrMsg + '\\n' + responseMsg)\n  }\n\n  if (err) {\n    const wrappedErr = new Error(`Failed to request translation service`)\n    wrappedErr.stack += '\\n' + err.stack\n    throw wrappedErr\n  }\n\n  return body\n}\n\n/**\n * To translate\n *\n * @param {string} text content to be translated\n * @param {string} from source language code. `auto-detect` by default.\n * @param {string} to target language code. `en` by default.\n * @param {boolean} [correct] <optional> whether to correct the input text. `false` by default.\n * @param {boolean} [raw] <optional> the result contains raw response if `true`\n * @param {string} [userAgent] <optional> the expected user agent header\n * @param {GotAgents} [proxyAgents] <optional> set agents of `got` for proxy\n *\n * @returns {Promise<TranslationResult | undefined>}\n */\nasync function translate(text, from, to, correct, raw, userAgent, proxyAgents) {\n  if (!text || !(text = text.trim())) {\n    return\n  }\n\n  if (!globalConfigPromise) {\n    globalConfigPromise = fetchGlobalConfig(userAgent, proxyAgents)\n  }\n\n  await globalConfigPromise\n\n  if (isTokenExpired()) {\n    globalConfigPromise = fetchGlobalConfig(userAgent, proxyAgents)\n\n    await globalConfigPromise\n  }\n\n  from = from || 'auto-detect'\n  to = to || 'en'\n\n  const fromSupported = lang.isSupported(from)\n  const toSupported = lang.isSupported(to)\n\n  if (!fromSupported || !toSupported) {\n    throw new Error(`The language '${!fromSupported ? from : !toSupported ? to : ''}' is not supported!`)\n  }\n\n  from = lang.getLangCode(from)\n  to = lang.getLangCode(to)\n\n  to === 'auto-detect' && (to = 'en')\n\n  const canUseEPT = text.length <= config.maxEPTTextLen\n    && ([from, to].every(lang => lang === 'auto-detect' || config.eptLangs.includes(lang)))\n\n  if (!canUseEPT) {\n    // Currently 5000 is supported only in China\n    // PENDING: dynamically re-generate local config.json when initializing?\n    const maxTextLen = globalConfig.subdomain === 'cn'\n      ? config.maxTextLenCN\n      : config.maxTextLen\n\n    if (text.length > maxTextLen) {\n      throw new Error(`The supported maximum text length is ${maxTextLen}. Please shorten the text.`)\n    }\n  }\n\n  const requestURL = makeRequestURL(false, canUseEPT)\n  const requestBody = makeRequestBody(false, text, from, to)\n\n  const requestHeaders = {\n    'user-agent': userAgent || config.userAgent,\n    referer: replaceSubdomain(TRANSLATE_WEBSITE, globalConfig.subdomain)\n  }\n\n  /**\n   * @type {GotOptions['retry']}\n   */\n  const retryConfig = {\n    limit: MAX_RETRY_COUNT,\n    methods: ['POST']\n  }\n\n  const body = await wrapRequest(\n    got.post(requestURL, {\n      headers: requestHeaders,\n      // got will set CONTENT_TYPE as `application/x-www-form-urlencoded`\n      form: requestBody,\n      responseType: 'json',\n      agent: proxyAgents,\n      retry: canUseEPT ? 0 : retryConfig\n    })\n  )\n\n  const translation = body[0].translations[0]\n  const detectedLang = body[0].detectedLanguage || {}\n\n  /**\n   * @type {TranslationResult}\n   */\n  const res = {\n    text,\n    userLang: from,\n    translation: translation.text,\n    language: {\n      from: detectedLang.language,\n      to: translation.to,\n      score: detectedLang.score\n    }\n  }\n\n  if (correct) {\n    const correctLang = detectedLang.language\n    const matcher = text.match(/\"/g)\n    const len = text.length + (matcher && matcher.length || 0)\n    // currently, there is a limit of 50 characters for correction service\n    // and only parts of languages are supported\n    // otherwise, it will return status code 400\n    if (len <= config.maxCorrectableTextLen && lang.isCorrectable(correctLang)) {\n      const requestURL = makeRequestURL(true)\n      const requestBody = makeRequestBody(true, text, correctLang)\n\n      const body = await wrapRequest(\n        got.post(requestURL, {\n          headers: requestHeaders,\n          form: requestBody,\n          responseType: 'json',\n          agent: proxyAgents,\n          retry: retryConfig\n        })\n      )\n\n      res.correctedText = body && body.correctedText\n    }\n    else {\n      console.warn(`The detected language '${correctLang}' is not supported to be corrected or the length of text is more than ${config.maxCorrectableTextLen}.`)\n    }\n  }\n\n  if (raw) {\n    res.raw = body\n  }\n\n  return res\n}\n\nmodule.exports = {\n  translate,\n  lang,\n  // mount the MET module on the index entry\n  // PENDING: isolate bing module and Microsoft module?\n  MET: require('./met')\n}\n"]}