Skip to content

Commit

Permalink
fix(base64): always use utf8 safe encoding and decoding
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed May 1, 2024
1 parent f5264c6 commit 8771f99
Show file tree
Hide file tree
Showing 3 changed files with 6 additions and 20 deletions.
6 changes: 2 additions & 4 deletions src/data-types/_utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,10 @@ export function assertType<T>(
}

export function _base64Encode(
data: Uint8Array | string,
data: Uint8Array,
base64Options?: Base64Options,
): Base64 {
let encoded = btoa(
typeof data === "string" ? data : String.fromCodePoint(...data),
);
let encoded = btoa(String.fromCodePoint(...data));
if (base64Options?.urlSafe) {
encoded = encoded
.replace(/\+/g, "-")
Expand Down
11 changes: 2 additions & 9 deletions src/data-types/base64.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,15 +40,8 @@ export const assertBase64 = (input: unknown, opts?: Base64Options) =>
* @param encoding - The encoding to use. Default is `utf8`.
* @group Base64
*/
export function base64ToText(
string: Base64,
opts?: Base64Options & { encoding?: "utf8" },
): string {
if (opts?.encoding === "utf8") {
return new TextDecoder().decode(base64ToUint8Array(string, opts));
}
assertBase64(string, opts);
return globalThis.atob(opts?.urlSafe ? _decodeURLSafe(string) : string);
export function base64ToText(string: Base64, opts?: Base64Options): string {
return new TextDecoder().decode(base64ToUint8Array(string, opts));
}

/**
Expand Down
9 changes: 2 additions & 7 deletions src/data-types/text.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,12 +86,7 @@ export function textToUint8Array(string: string): Uint8Array {
* @param encoding - The encoding to use. Default is `utf8`.
* @group Text
*/
export function textToBase64(
string: string,
opts?: Base64Options & { encoding?: "utf8" },
): Base64 {
export function textToBase64(string: string, opts?: Base64Options): Base64 {
assertText(string);
return opts?.encoding === "utf8"
? _base64Encode(new TextEncoder().encode(string), opts)
: _base64Encode(string, opts);
return _base64Encode(new TextEncoder().encode(string), opts);
}

0 comments on commit 8771f99

Please sign in to comment.