Skip to content
Myr

encode.ts

This file

Path

src/utils/encode.ts

29 lines · 1.0 KiB · TypeScript

Last changed by

Not known.

History of this file

Take it

The walk stopped after 200 commits: lines older than e070191 point at it.

feat: introduce "Helpers" (#1353)Yusuke Wadabefore adoptione070191

lines 1–29why, one step back
1export const decodeBase64Url = (str: string): Uint8Array => {
2 return decodeBase64(str.replace(/_|-/g, (m) => ({ _: '/', '-': '+' }[m] ?? m)))3}45export const encodeBase64Url = (buf: ArrayBufferLike): string =>6 encodeBase64(buf).replace(/\/|\+/g, (m) => ({ '/': '_', '+': '-' }[m] ?? m))78// This approach is written in MDN.9// btoa does not support utf-8 characters. So we need a little bit hack.10export const encodeBase64 = (buf: ArrayBufferLike): string => {11 let binary = ''12 const bytes = new Uint8Array(buf)13 for (let i = 0; i < bytes.length; i++) {14 binary += String.fromCharCode(bytes[i])15 }16 return btoa(binary)17}1819// atob does not support utf-8 characters. So we need a little bit hack.20export const decodeBase64 = (str: string): Uint8Array => {21 const binary = atob(str)22 const bytes = new Uint8Array(new ArrayBuffer(binary.length))23 const half = binary.length / 224 for (let i = 0, j = binary.length - 1; i <= half; i++, j--) {25 bytes[i] = binary.charCodeAt(i)26 bytes[j] = binary.charCodeAt(j)27 }28 return bytes29}