web.btoa.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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 validateArgumentsLength = require('../internals/validate-arguments-length');
  10. var itoc = require('../internals/base64-map').itoc;
  11. var $btoa = getBuiltIn('btoa');
  12. var charAt = uncurryThis(''.charAt);
  13. var charCodeAt = uncurryThis(''.charCodeAt);
  14. var NO_ARG_RECEIVING_CHECK = !!$btoa && !fails(function () {
  15. $btoa();
  16. });
  17. var WRONG_ARG_CONVERSION = !!$btoa && fails(function () {
  18. return $btoa(null) !== 'bnVsbA==';
  19. });
  20. var WRONG_ARITY = !!$btoa && $btoa.length !== 1;
  21. // `btoa` method
  22. // https://html.spec.whatwg.org/multipage/webappapis.html#dom-btoa
  23. $({ global: true, bind: true, enumerable: true, forced: NO_ARG_RECEIVING_CHECK || WRONG_ARG_CONVERSION || WRONG_ARITY }, {
  24. btoa: function btoa(data) {
  25. validateArgumentsLength(arguments.length, 1);
  26. // `webpack` dev server bug on IE global methods - use call(fn, global, ...)
  27. if (NO_ARG_RECEIVING_CHECK || WRONG_ARG_CONVERSION || WRONG_ARITY) return call($btoa, global, toString(data));
  28. var string = toString(data);
  29. var output = '';
  30. var position = 0;
  31. var map = itoc;
  32. var block, charCode;
  33. while (charAt(string, position) || (map = '=', position % 1)) {
  34. charCode = charCodeAt(string, position += 3 / 4);
  35. if (charCode > 0xFF) {
  36. throw new (getBuiltIn('DOMException'))('The string contains characters outside of the Latin1 range', 'InvalidCharacterError');
  37. }
  38. block = block << 8 | charCode;
  39. output += charAt(map, 63 & block >> 8 - position % 1 * 8);
  40. } return output;
  41. }
  42. });