Skip to content

Commit 0129fc7

Browse files
committed
feat: b64urlEncode() Encode to URL-safe base64
1 parent b151fc7 commit 0129fc7

2 files changed

Lines changed: 42 additions & 3 deletions

File tree

src/lib/index.ts

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import {
44
fromBuffer as browserFromBuffer,
55
} from './browser'
66
import { defaultConfig } from './config'
7-
import { isRunningInNodejs } from './helper'
7+
import { b64toURLSafe, isRunningInNodejs } from './helper'
88
import { TextDecoderFn, TextEncoderFn } from './model'
99
import {
1010
fromBuffer as nodeFromBuffer,
@@ -61,3 +61,17 @@ export function b64byteLength(base64: string): number {
6161
const placeHoldersLen = lens[1]
6262
return _byteLength(validLen, placeHoldersLen)
6363
}
64+
65+
66+
/**
67+
* Encode to URL-safe base64, source from string|number|bigint.
68+
* Replace "+" to "-" and "/" to "_", and Remove "="
69+
*/
70+
export function b64urlEncode(
71+
input: string,
72+
textEncoder?: TextEncoderFn,
73+
): string {
74+
75+
const b64 = b64encode(input, textEncoder)
76+
return b64toURLSafe(b64)
77+
}

test/10_index.test.ts

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,10 @@ import * as assert from 'power-assert'
99
import rewire = require('rewire')
1010
import { TextDecoder, TextEncoder } from 'util'
1111

12-
import { b64decode, b64encode, b64fromBuffer } from '../src/index'
12+
import { b64decode, b64encode, b64fromBuffer, b64urlEncode } from '../src/index'
1313
import { defaultConfig, ErrMsg } from '../src/lib/config'
1414

15-
import { input1, input2, input3, input4, input44, input5, input8 } from './config'
15+
import { input1, input2, input3, input4, input44, input5, input8, inputURLSafe, inputURLSafe2 } from './config'
1616

1717

1818
const filename = basename(__filename)
@@ -79,6 +79,7 @@ describe(filename, () => {
7979
})
8080
})
8181

82+
8283
describe('Should b64fromBuffer() works', () => {
8384
it('with valid input', () => {
8485
input8.forEach(row => {
@@ -90,4 +91,28 @@ describe(filename, () => {
9091
})
9192
})
9293

94+
95+
describe('Should b64urlEncode() works', () => {
96+
it('with valid input', () => {
97+
inputURLSafe.forEach(([str, b64, b64url]) => {
98+
const ret = b64urlEncode(str, TextEncoder)
99+
const b64node = Buffer.from(str).toString('base64')
100+
assert(ret === b64url, `"${ret}" !== "${b64url}"`)
101+
assert(b64 === b64node, `${b64} !== ${b64node}`)
102+
})
103+
})
104+
105+
it('with invalid input', () => {
106+
inputURLSafe2.forEach(b64 => {
107+
try {
108+
b64urlEncode(b64, TextEncoder)
109+
assert(false, 'Should throw error, but NOT')
110+
}
111+
catch (ex) {
112+
assert(true)
113+
}
114+
})
115+
})
116+
})
117+
93118
})

0 commit comments

Comments
 (0)