1 |
|
2 |
|
3 | const fromBase64 = (base64) => {
|
4 | return base64.replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_')
|
5 | }
|
6 |
|
7 | const encode = (input, encoding = 'utf8') => {
|
8 | return fromBase64(Buffer.from(input, encoding).toString('base64'))
|
9 | }
|
10 |
|
11 | const encodeBuffer = (buf) => {
|
12 | return fromBase64(buf.toString('base64'))
|
13 | }
|
14 |
|
15 | const decodeToBuffer = (input) => {
|
16 | return Buffer.from(input, 'base64')
|
17 | }
|
18 |
|
19 | const decode = (input, encoding = 'utf8') => {
|
20 | return decodeToBuffer(input).toString(encoding)
|
21 | }
|
22 |
|
23 | const 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 |
|
32 | b64uJSON.decode.try = (input, encoding = 'utf8') => {
|
33 | try {
|
34 | return b64uJSON.decode(input, encoding)
|
35 | } catch (err) {
|
36 | return decode(input, encoding)
|
37 | }
|
38 | }
|
39 |
|
40 | const 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 |
|
60 | const encodeBigInt = (bn) => encodeBuffer(Buffer.from(bnToBuf(bn)))
|
61 |
|
62 | module.exports.decode = decode
|
63 | module.exports.decodeToBuffer = decodeToBuffer
|
64 | module.exports.encode = encode
|
65 | module.exports.encodeBuffer = encodeBuffer
|
66 | module.exports.JSON = b64uJSON
|
67 | module.exports.encodeBigInt = encodeBigInt
|