base64.mjs 10 KB

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