'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var base64_config = require('./config.js');

/* eslint-disable */
var re_btou = /[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g;
var _tidyB64 = function _tidyB64(s) {
  return s.replace(/[^A-Za-z0-9\+\/]/g, '');
};
var cb_btou = function cb_btou(cccc) {
  switch (cccc.length) {
    case 4:
      var cp = (0x07 & cccc.charCodeAt(0)) << 18 | (0x3f & cccc.charCodeAt(1)) << 12 | (0x3f & cccc.charCodeAt(2)) << 6 | 0x3f & cccc.charCodeAt(3);
      var offset = cp - 0x10000;
      return base64_config._fromCC((offset >>> 10) + 0xD800) + base64_config._fromCC((offset & 0x3FF) + 0xDC00);
    case 3:
      return base64_config._fromCC((0x0f & cccc.charCodeAt(0)) << 12 | (0x3f & cccc.charCodeAt(1)) << 6 | 0x3f & cccc.charCodeAt(2));
    default:
      return base64_config._fromCC((0x1f & cccc.charCodeAt(0)) << 6 | 0x3f & cccc.charCodeAt(1));
  }
};
var btou = function btou(b) {
  return b.replace(re_btou, cb_btou);
};
var _unURI = function _unURI(a) {
  return _tidyB64(a.replace(/[-_]/g, function (m0) {
    return m0 == '-' ? '+' : '/';
  }));
};
/**
 * 将 Base64 编码的字符串解码为原始字符串
 * 支持 Unicode 字符（包括中文、emoji 等），兼容小程序环境
 * @param str - Base64 编码的字符串
 * @returns 解码后的原始字符串
 * @example
 * ```ts
 * decode('SGVsbG8gV29ybGQ='); // 'Hello World'
 * decode('5L2g5aW95LiW55WM'); // '你好世界'
 * decode('8J+YgA=='); // '😀'
 * ```
 */
var decode = function decode(str) {
  return btou(innerDecode(_unURI(str)));
};
/**
 * Base64 解码的内部实现（小程序版本的 atob）
 * 将 Base64 编码的字符串解码为 Latin1 字符串
 * @param string - Base64 编码的字符串
 * @returns 解码后的字符串
 * @throws {TypeError} 当输入不是有效的 Base64 字符串时抛出错误
 * @example
 * ```ts
 * innerDecode('SGVsbG8='); // 'Hello'
 * ```
 */
var innerDecode = function innerDecode(string) {
  string = String(string).replace(/[\t\n\f\r ]+/g, '');
  if (!base64_config.B64RE.test(string)) throw new TypeError('Failed to execute \'atob\' on \'Window\': The string to be decoded is not correctly encoded.');
  string += '=='.slice(2 - (string.length & 3));
  var bitmap;
  var result = '';
  var r1;
  var r2;
  var i = 0;
  for (; i < string.length;) {
    bitmap = base64_config.B64.indexOf(string.charAt(i++)) << 18 | base64_config.B64.indexOf(string.charAt(i++)) << 12 | (r1 = base64_config.B64.indexOf(string.charAt(i++))) << 6 | (r2 = base64_config.B64.indexOf(string.charAt(i++)));
    result += r1 === 64 ? String.fromCharCode(bitmap >> 16 & 255) : r2 === 64 ? String.fromCharCode(bitmap >> 16 & 255, bitmap >> 8 & 255) : String.fromCharCode(bitmap >> 16 & 255, bitmap >> 8 & 255, bitmap & 255);
  }
  return result;
};

exports.decode = decode;
exports.innerDecode = innerDecode;
