web.btoa.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. 'use strict';
  2. var $ = require('../internals/export');
  3. var globalThis = require('../internals/global-this');
  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 i2c = require('../internals/base64-map').i2c;
  11. var $btoa = getBuiltIn('btoa');
  12. var $Array = Array;
  13. var join = uncurryThis([].join);
  14. var charAt = uncurryThis(''.charAt);
  15. var charCodeAt = uncurryThis(''.charCodeAt);
  16. var BASIC = !!$btoa && !fails(function () {
  17. return $btoa('hi') !== 'aGk=';
  18. });
  19. var NO_ARG_RECEIVING_CHECK = BASIC && !fails(function () {
  20. $btoa();
  21. });
  22. var WRONG_ARG_CONVERSION = BASIC && fails(function () {
  23. return $btoa(null) !== 'bnVsbA==';
  24. });
  25. var WRONG_ARITY = BASIC && $btoa.length !== 1;
  26. // `btoa` method
  27. // https://html.spec.whatwg.org/multipage/webappapis.html#dom-btoa
  28. $({ global: true, bind: true, enumerable: true, forced: !BASIC || NO_ARG_RECEIVING_CHECK || WRONG_ARG_CONVERSION || WRONG_ARITY }, {
  29. btoa: function btoa(data) {
  30. validateArgumentsLength(arguments.length, 1);
  31. // `webpack` dev server bug on IE global methods - use call(fn, global, ...)
  32. if (BASIC) return call($btoa, globalThis, toString(data));
  33. var string = toString(data);
  34. // (string.length + 2) / 3) and then truncating to integer
  35. // does the ceil automatically. << 2 will truncate the integer
  36. // while also doing *4. ceil(length / 3) quanta, 4 bytes output
  37. // per quanta for base64.
  38. var output = new $Array((string.length + 2) / 3 << 2);
  39. var outputIndex = 0;
  40. var position = 0;
  41. var map = i2c;
  42. var block, charCode;
  43. while (charAt(string, position) || (map = '=', position % 1)) {
  44. charCode = charCodeAt(string, position += 3 / 4);
  45. if (charCode > 0xFF) {
  46. throw new (getBuiltIn('DOMException'))('The string contains characters outside of the Latin1 range', 'InvalidCharacterError');
  47. }
  48. block = block << 8 | charCode;
  49. output[outputIndex++] = charAt(map, 63 & block >> 8 - position % 1 * 8);
  50. } return join(output, '');
  51. }
  52. });