UNPKG

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