web.atob.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. var $ = require('../internals/export');
  2. var getBuiltIn = require('../internals/get-built-in');
  3. var uncurryThis = require('../internals/function-uncurry-this');
  4. var fails = require('../internals/fails');
  5. var toString = require('../internals/to-string');
  6. var hasOwn = require('../internals/has-own-property');
  7. var validateArgumentsLength = require('../internals/validate-arguments-length');
  8. var ctoi = require('../internals/base64-map').ctoi;
  9. var disallowed = /[^\d+/a-z]/i;
  10. var whitespaces = /[\t\n\f\r ]+/g;
  11. var finalEq = /[=]+$/;
  12. var $atob = getBuiltIn('atob');
  13. var fromCharCode = String.fromCharCode;
  14. var charAt = uncurryThis(''.charAt);
  15. var replace = uncurryThis(''.replace);
  16. var exec = uncurryThis(disallowed.exec);
  17. var NO_SPACES_IGNORE = fails(function () {
  18. return atob(' ') !== '';
  19. });
  20. var NO_ARG_RECEIVING_CHECK = !NO_SPACES_IGNORE && !fails(function () {
  21. $atob();
  22. });
  23. // `atob` method
  24. // https://html.spec.whatwg.org/multipage/webappapis.html#dom-atob
  25. $({ global: true, enumerable: true, forced: NO_SPACES_IGNORE || NO_ARG_RECEIVING_CHECK }, {
  26. atob: function atob(data) {
  27. validateArgumentsLength(arguments.length, 1);
  28. if (NO_ARG_RECEIVING_CHECK) return $atob(data);
  29. var string = replace(toString(data), whitespaces, '');
  30. var output = '';
  31. var position = 0;
  32. var bc = 0;
  33. var chr, bs;
  34. if (string.length % 4 == 0) {
  35. string = replace(string, finalEq, '');
  36. }
  37. if (string.length % 4 == 1 || exec(disallowed, string)) {
  38. throw new (getBuiltIn('DOMException'))('The string is not correctly encoded', 'InvalidCharacterError');
  39. }
  40. while (chr = charAt(string, position++)) {
  41. if (hasOwn(ctoi, chr)) {
  42. bs = bc % 4 ? bs * 64 + ctoi[chr] : ctoi[chr];
  43. if (bc++ % 4) output += fromCharCode(255 & bs >> (-2 * bc & 6));
  44. }
  45. } return output;
  46. }
  47. });