base64.mjs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. /**
  2. * base64.ts
  3. *
  4. * Licensed under the BSD 3-Clause License.
  5. * http://opensource.org/licenses/BSD-3-Clause
  6. *
  7. * References:
  8. * http://en.wikipedia.org/wiki/Base64
  9. *
  10. * @author Dan Kogai (https://github.com/dankogai)
  11. */
  12. const version = '3.7.7';
  13. /**
  14. * @deprecated use lowercase `version`.
  15. */
  16. const VERSION = version;
  17. const _hasBuffer = typeof Buffer === 'function';
  18. const _TD = typeof TextDecoder === 'function' ? new TextDecoder() : undefined;
  19. const _TE = typeof TextEncoder === 'function' ? new TextEncoder() : undefined;
  20. const b64ch = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  21. const b64chs = Array.prototype.slice.call(b64ch);
  22. const b64tab = ((a) => {
  23. let tab = {};
  24. a.forEach((c, i) => tab[c] = i);
  25. return tab;
  26. })(b64chs);
  27. const b64re = /^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/;
  28. const _fromCC = String.fromCharCode.bind(String);
  29. const _U8Afrom = typeof Uint8Array.from === 'function'
  30. ? Uint8Array.from.bind(Uint8Array)
  31. : (it) => new Uint8Array(Array.prototype.slice.call(it, 0));
  32. const _mkUriSafe = (src) => src
  33. .replace(/=/g, '').replace(/[+\/]/g, (m0) => m0 == '+' ? '-' : '_');
  34. const _tidyB64 = (s) => s.replace(/[^A-Za-z0-9\+\/]/g, '');
  35. /**
  36. * polyfill version of `btoa`
  37. */
  38. const btoaPolyfill = (bin) => {
  39. // console.log('polyfilled');
  40. let u32, c0, c1, c2, asc = '';
  41. const pad = bin.length % 3;
  42. for (let i = 0; i < bin.length;) {
  43. if ((c0 = bin.charCodeAt(i++)) > 255 ||
  44. (c1 = bin.charCodeAt(i++)) > 255 ||
  45. (c2 = bin.charCodeAt(i++)) > 255)
  46. throw new TypeError('invalid character found');
  47. u32 = (c0 << 16) | (c1 << 8) | c2;
  48. asc += b64chs[u32 >> 18 & 63]
  49. + b64chs[u32 >> 12 & 63]
  50. + b64chs[u32 >> 6 & 63]
  51. + b64chs[u32 & 63];
  52. }
  53. return pad ? asc.slice(0, pad - 3) + "===".substring(pad) : asc;
  54. };
  55. /**
  56. * does what `window.btoa` of web browsers do.
  57. * @param {String} bin binary string
  58. * @returns {string} Base64-encoded string
  59. */
  60. const _btoa = typeof btoa === 'function' ? (bin) => btoa(bin)
  61. : _hasBuffer ? (bin) => Buffer.from(bin, 'binary').toString('base64')
  62. : btoaPolyfill;
  63. const _fromUint8Array = _hasBuffer
  64. ? (u8a) => Buffer.from(u8a).toString('base64')
  65. : (u8a) => {
  66. // cf. https://stackoverflow.com/questions/12710001/how-to-convert-uint8-array-to-base64-encoded-string/12713326#12713326
  67. const maxargs = 0x1000;
  68. let strs = [];
  69. for (let i = 0, l = u8a.length; i < l; i += maxargs) {
  70. strs.push(_fromCC.apply(null, u8a.subarray(i, i + maxargs)));
  71. }
  72. return _btoa(strs.join(''));
  73. };
  74. /**
  75. * converts a Uint8Array to a Base64 string.
  76. * @param {boolean} [urlsafe] URL-and-filename-safe a la RFC4648 §5
  77. * @returns {string} Base64 string
  78. */
  79. const fromUint8Array = (u8a, urlsafe = false) => urlsafe ? _mkUriSafe(_fromUint8Array(u8a)) : _fromUint8Array(u8a);
  80. // This trick is found broken https://github.com/dankogai/js-base64/issues/130
  81. // const utob = (src: string) => unescape(encodeURIComponent(src));
  82. // reverting good old fationed regexp
  83. const cb_utob = (c) => {
  84. if (c.length < 2) {
  85. var cc = c.charCodeAt(0);
  86. return cc < 0x80 ? c
  87. : cc < 0x800 ? (_fromCC(0xc0 | (cc >>> 6))
  88. + _fromCC(0x80 | (cc & 0x3f)))
  89. : (_fromCC(0xe0 | ((cc >>> 12) & 0x0f))
  90. + _fromCC(0x80 | ((cc >>> 6) & 0x3f))
  91. + _fromCC(0x80 | (cc & 0x3f)));
  92. }
  93. else {
  94. var cc = 0x10000
  95. + (c.charCodeAt(0) - 0xD800) * 0x400
  96. + (c.charCodeAt(1) - 0xDC00);
  97. return (_fromCC(0xf0 | ((cc >>> 18) & 0x07))
  98. + _fromCC(0x80 | ((cc >>> 12) & 0x3f))
  99. + _fromCC(0x80 | ((cc >>> 6) & 0x3f))
  100. + _fromCC(0x80 | (cc & 0x3f)));
  101. }
  102. };
  103. const re_utob = /[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g;
  104. /**
  105. * @deprecated should have been internal use only.
  106. * @param {string} src UTF-8 string
  107. * @returns {string} UTF-16 string
  108. */
  109. const utob = (u) => u.replace(re_utob, cb_utob);
  110. //
  111. const _encode = _hasBuffer
  112. ? (s) => Buffer.from(s, 'utf8').toString('base64')
  113. : _TE
  114. ? (s) => _fromUint8Array(_TE.encode(s))
  115. : (s) => _btoa(utob(s));
  116. /**
  117. * converts a UTF-8-encoded string to a Base64 string.
  118. * @param {boolean} [urlsafe] if `true` make the result URL-safe
  119. * @returns {string} Base64 string
  120. */
  121. const encode = (src, urlsafe = false) => urlsafe
  122. ? _mkUriSafe(_encode(src))
  123. : _encode(src);
  124. /**
  125. * converts a UTF-8-encoded string to URL-safe Base64 RFC4648 §5.
  126. * @returns {string} Base64 string
  127. */
  128. const encodeURI = (src) => encode(src, true);
  129. // This trick is found broken https://github.com/dankogai/js-base64/issues/130
  130. // const btou = (src: string) => decodeURIComponent(escape(src));
  131. // reverting good old fationed regexp
  132. const re_btou = /[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g;
  133. const cb_btou = (cccc) => {
  134. switch (cccc.length) {
  135. case 4:
  136. var cp = ((0x07 & cccc.charCodeAt(0)) << 18)
  137. | ((0x3f & cccc.charCodeAt(1)) << 12)
  138. | ((0x3f & cccc.charCodeAt(2)) << 6)
  139. | (0x3f & cccc.charCodeAt(3)), offset = cp - 0x10000;
  140. return (_fromCC((offset >>> 10) + 0xD800)
  141. + _fromCC((offset & 0x3FF) + 0xDC00));
  142. case 3:
  143. return _fromCC(((0x0f & cccc.charCodeAt(0)) << 12)
  144. | ((0x3f & cccc.charCodeAt(1)) << 6)
  145. | (0x3f & cccc.charCodeAt(2)));
  146. default:
  147. return _fromCC(((0x1f & cccc.charCodeAt(0)) << 6)
  148. | (0x3f & cccc.charCodeAt(1)));
  149. }
  150. };
  151. /**
  152. * @deprecated should have been internal use only.
  153. * @param {string} src UTF-16 string
  154. * @returns {string} UTF-8 string
  155. */
  156. const btou = (b) => b.replace(re_btou, cb_btou);
  157. /**
  158. * polyfill version of `atob`
  159. */
  160. const atobPolyfill = (asc) => {
  161. // console.log('polyfilled');
  162. asc = asc.replace(/\s+/g, '');
  163. if (!b64re.test(asc))
  164. throw new TypeError('malformed base64.');
  165. asc += '=='.slice(2 - (asc.length & 3));
  166. let u24, bin = '', r1, r2;
  167. for (let i = 0; i < asc.length;) {
  168. u24 = b64tab[asc.charAt(i++)] << 18
  169. | b64tab[asc.charAt(i++)] << 12
  170. | (r1 = b64tab[asc.charAt(i++)]) << 6
  171. | (r2 = b64tab[asc.charAt(i++)]);
  172. bin += r1 === 64 ? _fromCC(u24 >> 16 & 255)
  173. : r2 === 64 ? _fromCC(u24 >> 16 & 255, u24 >> 8 & 255)
  174. : _fromCC(u24 >> 16 & 255, u24 >> 8 & 255, u24 & 255);
  175. }
  176. return bin;
  177. };
  178. /**
  179. * does what `window.atob` of web browsers do.
  180. * @param {String} asc Base64-encoded string
  181. * @returns {string} binary string
  182. */
  183. const _atob = typeof atob === 'function' ? (asc) => atob(_tidyB64(asc))
  184. : _hasBuffer ? (asc) => Buffer.from(asc, 'base64').toString('binary')
  185. : atobPolyfill;
  186. //
  187. const _toUint8Array = _hasBuffer
  188. ? (a) => _U8Afrom(Buffer.from(a, 'base64'))
  189. : (a) => _U8Afrom(_atob(a).split('').map(c => c.charCodeAt(0)));
  190. /**
  191. * converts a Base64 string to a Uint8Array.
  192. */
  193. const toUint8Array = (a) => _toUint8Array(_unURI(a));
  194. //
  195. const _decode = _hasBuffer
  196. ? (a) => Buffer.from(a, 'base64').toString('utf8')
  197. : _TD
  198. ? (a) => _TD.decode(_toUint8Array(a))
  199. : (a) => btou(_atob(a));
  200. const _unURI = (a) => _tidyB64(a.replace(/[-_]/g, (m0) => m0 == '-' ? '+' : '/'));
  201. /**
  202. * converts a Base64 string to a UTF-8 string.
  203. * @param {String} src Base64 string. Both normal and URL-safe are supported
  204. * @returns {string} UTF-8 string
  205. */
  206. const decode = (src) => _decode(_unURI(src));
  207. /**
  208. * check if a value is a valid Base64 string
  209. * @param {String} src a value to check
  210. */
  211. const isValid = (src) => {
  212. if (typeof src !== 'string')
  213. return false;
  214. const s = src.replace(/\s+/g, '').replace(/={0,2}$/, '');
  215. return !/[^\s0-9a-zA-Z\+/]/.test(s) || !/[^\s0-9a-zA-Z\-_]/.test(s);
  216. };
  217. //
  218. const _noEnum = (v) => {
  219. return {
  220. value: v, enumerable: false, writable: true, configurable: true
  221. };
  222. };
  223. /**
  224. * extend String.prototype with relevant methods
  225. */
  226. const extendString = function () {
  227. const _add = (name, body) => Object.defineProperty(String.prototype, name, _noEnum(body));
  228. _add('fromBase64', function () { return decode(this); });
  229. _add('toBase64', function (urlsafe) { return encode(this, urlsafe); });
  230. _add('toBase64URI', function () { return encode(this, true); });
  231. _add('toBase64URL', function () { return encode(this, true); });
  232. _add('toUint8Array', function () { return toUint8Array(this); });
  233. };
  234. /**
  235. * extend Uint8Array.prototype with relevant methods
  236. */
  237. const extendUint8Array = function () {
  238. const _add = (name, body) => Object.defineProperty(Uint8Array.prototype, name, _noEnum(body));
  239. _add('toBase64', function (urlsafe) { return fromUint8Array(this, urlsafe); });
  240. _add('toBase64URI', function () { return fromUint8Array(this, true); });
  241. _add('toBase64URL', function () { return fromUint8Array(this, true); });
  242. };
  243. /**
  244. * extend Builtin prototypes with relevant methods
  245. */
  246. const extendBuiltins = () => {
  247. extendString();
  248. extendUint8Array();
  249. };
  250. const gBase64 = {
  251. version: version,
  252. VERSION: VERSION,
  253. atob: _atob,
  254. atobPolyfill: atobPolyfill,
  255. btoa: _btoa,
  256. btoaPolyfill: btoaPolyfill,
  257. fromBase64: decode,
  258. toBase64: encode,
  259. encode: encode,
  260. encodeURI: encodeURI,
  261. encodeURL: encodeURI,
  262. utob: utob,
  263. btou: btou,
  264. decode: decode,
  265. isValid: isValid,
  266. fromUint8Array: fromUint8Array,
  267. toUint8Array: toUint8Array,
  268. extendString: extendString,
  269. extendUint8Array: extendUint8Array,
  270. extendBuiltins: extendBuiltins
  271. };
  272. // makecjs:CUT //
  273. export { version };
  274. export { VERSION };
  275. export { _atob as atob };
  276. export { atobPolyfill };
  277. export { _btoa as btoa };
  278. export { btoaPolyfill };
  279. export { decode as fromBase64 };
  280. export { encode as toBase64 };
  281. export { utob };
  282. export { encode };
  283. export { encodeURI };
  284. export { encodeURI as encodeURL };
  285. export { btou };
  286. export { decode };
  287. export { isValid };
  288. export { fromUint8Array };
  289. export { toUint8Array };
  290. export { extendString };
  291. export { extendUint8Array };
  292. export { extendBuiltins };
  293. // and finally,
  294. export { gBase64 as Base64 };