web.atob.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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_ENCODING_CHECK = !fails(function () {
  21. $atob('a');
  22. });
  23. var NO_ARG_RECEIVING_CHECK = !NO_SPACES_IGNORE && !NO_ENCODING_CHECK && !fails(function () {
  24. $atob();
  25. });
  26. var WRONG_ARITY = !NO_SPACES_IGNORE && !NO_ENCODING_CHECK && $atob.length !== 1;
  27. // `atob` method
  28. // https://html.spec.whatwg.org/multipage/webappapis.html#dom-atob
  29. $({ global: true, enumerable: true, forced: NO_SPACES_IGNORE || NO_ENCODING_CHECK || NO_ARG_RECEIVING_CHECK || WRONG_ARITY }, {
  30. atob: function atob(data) {
  31. validateArgumentsLength(arguments.length, 1);
  32. if (NO_ARG_RECEIVING_CHECK || WRONG_ARITY) return $atob(data);
  33. var string = replace(toString(data), whitespaces, '');
  34. var output = '';
  35. var position = 0;
  36. var bc = 0;
  37. var chr, bs;
  38. if (string.length % 4 == 0) {
  39. string = replace(string, finalEq, '');
  40. }
  41. if (string.length % 4 == 1 || exec(disallowed, string)) {
  42. throw new (getBuiltIn('DOMException'))('The string is not correctly encoded', 'InvalidCharacterError');
  43. }
  44. while (chr = charAt(string, position++)) {
  45. if (hasOwn(ctoi, chr)) {
  46. bs = bc % 4 ? bs * 64 + ctoi[chr] : ctoi[chr];
  47. if (bc++ % 4) output += fromCharCode(255 & bs >> (-2 * bc & 6));
  48. }
  49. } return output;
  50. }
  51. });