base64.js 988 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  4. "use strict";
  5. module.metadata = {
  6. "stability": "unstable"
  7. };
  8. const { Cu } = require("chrome");
  9. // Passing an empty object as second argument to avoid scope's pollution
  10. const { atob, btoa } = Cu.import("resource://gre/modules/Services.jsm", {});
  11. function isUTF8(charset) {
  12. let type = typeof charset;
  13. if (type === "undefined")
  14. return false;
  15. if (type === "string" && charset.toLowerCase() === "utf-8")
  16. return true;
  17. throw new Error("The charset argument can be only 'utf-8'");
  18. }
  19. exports.decode = function (data, charset) {
  20. if (isUTF8(charset))
  21. return decodeURIComponent(escape(atob(data)))
  22. return atob(data);
  23. }
  24. exports.encode = function (data, charset) {
  25. if (isUTF8(charset))
  26. return btoa(unescape(encodeURIComponent(data)))
  27. return btoa(data);
  28. }