polyfill.js 1.86 KB

if (typeof TextEncoder === 'undefined') {
  class TextEncoder {
    encode(str) {
      const len = str.length;
      const res = [];
      for (let i = 0; i < len; i++) {
        let point = str.charCodeAt(i);
        if (point <= 0x007f) {
          res.push(point);
        } else if (point <= 0x07ff) {
          res.push(0xc0 | (point >>> 6));
          res.push(0x80 | (0x3f & point));
        } else if (point <= 0xffff) {
          res.push(0xe0 | (point >>> 12));
          res.push(0x80 | (0x3f & (point >>> 6)));
          res.push(0x80 | (0x3f & point));
        } else {
          point = 0x10000 + ((point - 0xd800) << 10) + (str.charCodeAt(++i) - 0xdc00);
          res.push(0xf0 | (point >>> 18));
          res.push(0x80 | (0x3f & (point >>> 12)));
          res.push(0x80 | (0x3f & (point >>> 6)));
          res.push(0x80 | (0x3f & point));
        }
      }
      return new Uint8Array(res);
    }
  }

  if (typeof globalThis !== 'undefined') {
    globalThis.TextEncoder = TextEncoder;
  }
  if (typeof global !== 'undefined') {
    global.TextEncoder = TextEncoder;
  }
  if (typeof window !== 'undefined') {
    window.TextEncoder = TextEncoder;
  }
}

if (typeof TextDecoder === 'undefined') {
  class TextDecoder {
    decode(view, options) {
      if (!view) {
        return '';
      }
      let string = '';
      const arr = new Uint8Array(view);
      for (let i = 0; i < arr.length; i++) {
        string += String.fromCharCode(arr[i]);
      }
      try {
          // 简单的 UTF-8 解码尝试
          return decodeURIComponent(escape(string));
      } catch (e) {
          return string;
      }
    }
  }
  if (typeof globalThis !== 'undefined') {
    globalThis.TextDecoder = TextDecoder;
  }
  if (typeof global !== 'undefined') {
    global.TextDecoder = TextDecoder;
  }
  if (typeof window !== 'undefined') {
    window.TextDecoder = TextDecoder;
  }
}