From f8f1caa0d1ba41abdb4e3c0cb26bdec2e5dd2f65 Mon Sep 17 00:00:00 2001 From: diegodelrieue Date: Thu, 9 Nov 2023 15:05:54 +0100 Subject: [PATCH] fix: remove buffer --- __tests__/utils/encode.test.ts | 34 ++++++++++++++++++++++++++++++++++ src/utils/encode.ts | 6 ++++-- 2 files changed, 38 insertions(+), 2 deletions(-) create mode 100644 __tests__/utils/encode.test.ts diff --git a/__tests__/utils/encode.test.ts b/__tests__/utils/encode.test.ts new file mode 100644 index 000000000..c0d3df623 --- /dev/null +++ b/__tests__/utils/encode.test.ts @@ -0,0 +1,34 @@ +import { atobUniversal, btoaUniversal } from '../../src/utils/encode'; + +describe('atobUniversal and btoaUniversal functions', () => { + test('atobUniversal should decode base64 string to Uint8Array', () => { + const base64 = 'SGVsbG8sIFdvcmxkIQ=='; // "Hello, World!" in base64 + const expected = new Uint8Array([72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33]); + const result = atobUniversal(base64); + expect(result).toEqual(expected); + }); + + test('btoaUniversal should encode ArrayBuffer to base64 string', () => { + const { buffer } = new Uint8Array([72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33]); + + const expected = 'SGVsbG8sIFdvcmxkIQ=='; // "Hello, World!" in base64 + const result = btoaUniversal(buffer); + expect(result).toBe(expected); + }); + + test('should round trip encode/decode correctly', () => { + const originalString = 'Hello, World!'; + const { buffer } = new TextEncoder().encode(originalString); + const encoded = btoaUniversal(buffer); + const decoded = new TextDecoder().decode(atobUniversal(encoded)); + expect(decoded).toBe(originalString); + }); + + test('should handle empty string', () => { + const emptyBuffer = new ArrayBuffer(0); + const encoded = btoaUniversal(emptyBuffer); + expect(encoded).toBe(''); + const decoded = atobUniversal(encoded); + expect(decoded).toEqual(new Uint8Array([])); + }); +}); diff --git a/src/utils/encode.ts b/src/utils/encode.ts index 4ae7d6ca7..705d45d12 100644 --- a/src/utils/encode.ts +++ b/src/utils/encode.ts @@ -1,3 +1,5 @@ +import { base64 } from '@scure/base'; + /* eslint-disable no-param-reassign */ export const IS_BROWSER = typeof window !== 'undefined'; @@ -39,14 +41,14 @@ export function stringToArrayBuffer(str: string): Uint8Array { * Convert string to array buffer (browser and node compatible) */ export function atobUniversal(a: string): Uint8Array { - return IS_BROWSER ? utf8ToArray(atob(a)) : Buffer.from(a, 'base64'); + return base64.decode(a); } /** * Convert array buffer to string (browser and node compatible) */ export function btoaUniversal(b: ArrayBuffer): string { - return IS_BROWSER ? btoa(arrayBufferToString(b)) : Buffer.from(b).toString('base64'); + return base64.encode(new Uint8Array(b)); } /**