base64.ts 1.2 KB

1234567891011121314151617181920212223242526272829
  1. const _b64chars: string[] = [...'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/']
  2. const _mkUriSafe = (src: string): string => src.replace(/[+/]/g, (m0: string) => (m0 === '+' ? '-' : '_')).replace(/=+\$/m, '')
  3. const fromUint8Array = (src: Uint8Array, rfc4648 = false): string => {
  4. let b64 = ''
  5. for (let i = 0, l = src.length; i < l; i += 3) {
  6. const [a0, a1, a2] = [src[i], src[i + 1], src[i + 2]]
  7. const ord = (a0 << 16) | (a1 << 8) | a2
  8. b64 += _b64chars[ord >>> 18]
  9. b64 += _b64chars[(ord >>> 12) & 63]
  10. b64 += typeof a1 !== 'undefined' ? _b64chars[(ord >>> 6) & 63] : '='
  11. b64 += typeof a2 !== 'undefined' ? _b64chars[ord & 63] : '='
  12. }
  13. return rfc4648 ? _mkUriSafe(b64) : b64
  14. }
  15. const _btoa: (s: string) => string =
  16. typeof btoa === 'function'
  17. ? (s: string) => btoa(s)
  18. : (s: string) => {
  19. if (s.charCodeAt(0) > 255) {
  20. throw new RangeError('The string contains invalid characters.')
  21. }
  22. return fromUint8Array(Uint8Array.from(s, (c: string) => c.charCodeAt(0)))
  23. }
  24. const utob = (src: string): string => unescape(encodeURIComponent(src))
  25. export default function encode(src: string, rfc4648 = false): string {
  26. const b64 = _btoa(utob(src))
  27. return rfc4648 ? _mkUriSafe(b64) : b64
  28. }