File tree Expand file tree Collapse file tree 1 file changed +18
-10
lines changed Expand file tree Collapse file tree 1 file changed +18
-10
lines changed Original file line number Diff line number Diff line change 3
3
* @param data - The data to encode.
4
4
* @returns The base64url encoded string.
5
5
*/
6
- export function toBase64Url < T extends ArrayBufferLike | string > (
6
+ export function toBase64Url < T extends string | ArrayBuffer | ArrayBufferView > (
7
7
data : T ,
8
8
) : string {
9
- const base64 = btoa (
9
+ const bytes =
10
10
typeof data === "string"
11
- ? data
12
- : String . fromCharCode ( ...new Uint8Array ( data ) ) ,
13
- ) ;
14
- const base64Url = base64
15
- . replace ( / \+ / g, "-" )
16
- . replace ( / \/ / g, "_" )
17
- . replace ( / = / g, "" ) ;
11
+ ? new TextEncoder ( ) . encode ( data ) // Convert string to Uint8Array
12
+ : data instanceof ArrayBuffer
13
+ ? new Uint8Array ( data )
14
+ : new Uint8Array ( data . buffer , data . byteOffset , data . byteLength ) ;
18
15
19
- return base64Url ;
16
+ // Convert bytes to string safely (avoiding call stack overflow)
17
+ let binaryString = "" ;
18
+ const chunkSize = 8192 ; // Process in chunks to avoid call stack limits
19
+
20
+ for ( let i = 0 ; i < bytes . length ; i += chunkSize ) {
21
+ const chunk = bytes . subarray ( i , i + chunkSize ) ;
22
+ binaryString += String . fromCharCode ( ...chunk ) ;
23
+ }
24
+
25
+ const base64 = btoa ( binaryString ) ;
26
+
27
+ return base64 . replace ( / \+ / g, "-" ) . replace ( / \/ / g, "_" ) . replace ( / = + $ / g, "" ) ;
20
28
}
21
29
22
30
/**
You can’t perform that action at this time.
0 commit comments