base64.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.base64 = void 0;
  4. exports.normalize = normalize;
  5. exports.pad = pad;
  6. exports.is = is;
  7. exports.encode = encode;
  8. exports.decode = decode;
  9. const index_js_1 = require("../bytes/index.js");
  10. const binary_js_1 = require("./binary.js");
  11. const BASE64_REGEX = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
  12. function nodeBuffer() {
  13. return globalThis.Buffer;
  14. }
  15. function normalize(text) {
  16. return text.replace(/[\n\r\t ]/g, "");
  17. }
  18. function pad(text) {
  19. const remainder = text.length % 4;
  20. return remainder ? text + "=".repeat(4 - remainder) : text;
  21. }
  22. function is(text) {
  23. if (typeof text !== "string") {
  24. return false;
  25. }
  26. const normalized = normalize(text);
  27. return normalized === "" || BASE64_REGEX.test(normalized);
  28. }
  29. function encode(data, _options) {
  30. const bytes = (0, index_js_1.toUint8Array)(data);
  31. const buffer = nodeBuffer();
  32. if (buffer) {
  33. return buffer.from(bytes).toString("base64");
  34. }
  35. return btoa((0, binary_js_1.encode)(bytes));
  36. }
  37. function decode(text, _options) {
  38. const normalized = normalize(text);
  39. if (!is(normalized)) {
  40. throw new TypeError("Input is not valid Base64 text");
  41. }
  42. const buffer = nodeBuffer();
  43. if (buffer) {
  44. return new Uint8Array(buffer.from(normalized, "base64"));
  45. }
  46. return (0, binary_js_1.decode)(atob(normalized));
  47. }
  48. exports.base64 = { encode, decode, is, normalize, pad };