1// @flow 2// Inspired by: https://github.com/davidchambers/Base64.js/blob/master/base64.js 3 4const chars = 5 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; 6const Base64 = { 7 btoa: (input: string = '') => { 8 let str = input; 9 let output = ''; 10 11 for ( 12 let block = 0, charCode, i = 0, map = chars; 13 str.charAt(i | 0) || ((map = '='), i % 1); 14 output += map.charAt(63 & (block >> (8 - (i % 1) * 8))) 15 ) { 16 charCode = str.charCodeAt((i += 3 / 4)); 17 18 if (charCode > 0xff) { 19 throw new Error( 20 "'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.", 21 ); 22 } 23 24 block = (block << 8) | charCode; 25 } 26 27 return output; 28 }, 29 30 atob: (input: string = '') => { 31 let str = input.replace(/[=]+$/, ''); 32 let output = ''; 33 34 if (str.length % 4 == 1) { 35 throw new Error( 36 "'atob' failed: The string to be decoded is not correctly encoded.", 37 ); 38 } 39 for ( 40 let bc = 0, bs = 0, buffer, i = 0; 41 (buffer = str.charAt(i++)); 42 ~buffer && ((bs = bc % 4 ? bs * 64 + buffer : buffer), bc++ % 4) 43 ? (output += String.fromCharCode(255 & (bs >> ((-2 * bc) & 6)))) 44 : 0 45 ) { 46 buffer = chars.indexOf(buffer); 47 } 48 49 return output; 50 }, 51}; 52 53export default Base64; 54