base64url.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. import { encoder, decoder } from '../lib/buffer_utils.js';
  2. export const encodeBase64 = (input) => {
  3. let unencoded = input;
  4. if (typeof unencoded === 'string') {
  5. unencoded = encoder.encode(unencoded);
  6. }
  7. const CHUNK_SIZE = 0x8000;
  8. const arr = [];
  9. for (let i = 0; i < unencoded.length; i += CHUNK_SIZE) {
  10. arr.push(String.fromCharCode.apply(null, unencoded.subarray(i, i + CHUNK_SIZE)));
  11. }
  12. return btoa(arr.join(''));
  13. };
  14. export const encode = (input) => {
  15. return encodeBase64(input).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_');
  16. };
  17. export const decodeBase64 = (encoded) => {
  18. const binary = atob(encoded);
  19. const bytes = new Uint8Array(binary.length);
  20. for (let i = 0; i < binary.length; i++) {
  21. bytes[i] = binary.charCodeAt(i);
  22. }
  23. return bytes;
  24. };
  25. export const decode = (input) => {
  26. let encoded = input;
  27. if (encoded instanceof Uint8Array) {
  28. encoded = decoder.decode(encoded);
  29. }
  30. encoded = encoded.replace(/-/g, '+').replace(/_/g, '/').replace(/\s/g, '');
  31. try {
  32. return decodeBase64(encoded);
  33. }
  34. catch (_a) {
  35. throw new TypeError('The input to be decoded is not correctly encoded.');
  36. }
  37. };