web.atob.js 2.2 KB

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