All files / src base64.ts

100% Statements 14/14
100% Branches 0/0
100% Functions 6/6
100% Lines 11/11

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 317x     49x       6x       3x 3x       17x 17x 15x       17x       3x     7x  
import { Buffer } from 'buffer/';
 
function encodeUint8toBase64(uint8array: Uint8Array): string {
	return Buffer.from(uint8array).toString('base64');
}
 
function encodeBase64toUint8(base64String: string): Uint8Array {
	return Buffer.from(base64String, 'base64');
}
 
function encodeJsonToBase64(jsonObj: unknown): string {
	const jsonString = JSON.stringify(jsonObj);
	return base64urlFromBase64(Buffer.from(jsonString).toString('base64'));
}
 
function encodeBase64ToJson<T extends object>(base64String: string): T {
	const jsonString = Buffer.from(base64urlToBase64(base64String), 'base64').toString();
	const jsonObj = JSON.parse(jsonString) as T;
	return jsonObj;
}
 
function base64urlToBase64(str: string) {
	return str.replace(/-/g, '+').replace(/_/g, '/');
}
 
function base64urlFromBase64(str: string) {
	return str.replace(/\+/g, '-').replace(/\//g, '_').split('=')[0];
}
 
export { encodeUint8toBase64, encodeBase64toUint8, encodeJsonToBase64, encodeBase64ToJson };