UNPKG

1.46 kBJavaScriptView Raw
1/* global BigInt */
2
3const fromBase64 = (base64) => {
4 return base64.replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_')
5}
6
7const encode = (input, encoding = 'utf8') => {
8 return fromBase64(Buffer.from(input, encoding).toString('base64'))
9}
10
11const encodeBuffer = (buf) => {
12 return fromBase64(buf.toString('base64'))
13}
14
15const decodeToBuffer = (input) => {
16 return Buffer.from(input, 'base64')
17}
18
19const decode = (input, encoding = 'utf8') => {
20 return decodeToBuffer(input).toString(encoding)
21}
22
23const b64uJSON = {
24 encode: (input) => {
25 return encode(JSON.stringify(input))
26 },
27 decode: (input, encoding = 'utf8') => {
28 return JSON.parse(decode(input, encoding))
29 }
30}
31
32b64uJSON.decode.try = (input, encoding = 'utf8') => {
33 try {
34 return b64uJSON.decode(input, encoding)
35 } catch (err) {
36 return decode(input, encoding)
37 }
38}
39
40const bnToBuf = (bn) => {
41 let hex = BigInt(bn).toString(16)
42 if (hex.length % 2) {
43 hex = `0${hex}`
44 }
45
46 const len = hex.length / 2
47 const u8 = new Uint8Array(len)
48
49 let i = 0
50 let j = 0
51 while (i < len) {
52 u8[i] = parseInt(hex.slice(j, j + 2), 16)
53 i += 1
54 j += 2
55 }
56
57 return u8
58}
59
60const encodeBigInt = (bn) => encodeBuffer(Buffer.from(bnToBuf(bn)))
61
62module.exports.decode = decode
63module.exports.decodeToBuffer = decodeToBuffer
64module.exports.encode = encode
65module.exports.encodeBuffer = encodeBuffer
66module.exports.JSON = b64uJSON
67module.exports.encodeBigInt = encodeBigInt