web.atob.js 2.2 KB

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