Skip to content

Commit

Permalink
Merge pull request #96 from commercelayer/remove-deprecated
Browse files Browse the repository at this point in the history
Remove `unescape` and `escape` since they are deprecated
  • Loading branch information
marcomontalbano authored Oct 25, 2024
2 parents 1df38ba + 2758924 commit 06fa221
Showing 1 changed file with 22 additions and 6 deletions.
28 changes: 22 additions & 6 deletions packages/js-auth/src/utils/base64.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,15 @@ export function encodeBase64URLSafe(
encoding: 'utf-8' | 'binary'
): string {
if (typeof btoa !== 'undefined') {
// Convert the string to a UTF-8 byte sequence before encoding
const utf8String =
encoding === 'utf-8'
? unescape(encodeURIComponent(stringToEncode))
: stringToEncode
let utf8String = stringToEncode

if (encoding === 'utf-8') {
// Encode the string as UTF-8
const utf8Bytes = new TextEncoder().encode(stringToEncode)

// Convert the UTF-8 bytes to a Base64 string
utf8String = String.fromCharCode(...utf8Bytes)
}

return (
btoa(utf8String)
Expand Down Expand Up @@ -54,9 +58,21 @@ export function decodeBase64URLSafe(
// Replace characters according to base64url specifications
.replaceAll('-', '+')
.replaceAll('_', '/')
// Add padding if necessary
.padEnd(encodedData.length + ((4 - (encodedData.length % 4)) % 4), '=')
)

return encoding === 'utf-8' ? decodeURIComponent(escape(decoded)) : decoded
if (encoding === 'utf-8') {
// Decode the Base64 string into bytes
const byteArray = new Uint8Array(
[...decoded].map((char) => char.charCodeAt(0))
)

// Convert the bytes back to a UTF-8 string
return new TextDecoder().decode(byteArray)
}

return decoded
}

return Buffer.from(encodedData, 'base64url').toString(encoding)
Expand Down

0 comments on commit 06fa221

Please sign in to comment.