Skip to content

Commit

Permalink
perf: use 'base64url' encoding when available in Node.js runtime
Browse files Browse the repository at this point in the history
  • Loading branch information
panva committed Jan 18, 2021
1 parent 0294114 commit 808f06c
Showing 1 changed file with 13 additions and 4 deletions.
17 changes: 13 additions & 4 deletions src/runtime/node/base64url.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,21 @@
import { decoder } from '../../lib/buffer_utils.js'

export const encode = (input: Uint8Array | string) =>
Buffer.from(input).toString('base64').replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_')
let encodeImpl: (input: Uint8Array | string) => string

export const decode = (input: Uint8Array | string) => {
function normalize(input: string | Uint8Array) {
let encoded = input
if (encoded instanceof Uint8Array) {
encoded = decoder.decode(encoded)
}
return new Uint8Array(Buffer.from(encoded, 'base64'))
return encoded
}

if (Buffer.isEncoding('base64url')) {
encodeImpl = (input) => Buffer.from(input).toString(<BufferEncoding>'base64url')
} else {
encodeImpl = (input) =>
Buffer.from(input).toString('base64').replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_')
}

export const encode = encodeImpl
export const decode = (input: Uint8Array | string) => Buffer.from(normalize(input), 'base64')

0 comments on commit 808f06c

Please sign in to comment.