aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorST-DDT <[email protected]>2025-02-20 00:01:02 +0100
committerGitHub <[email protected]>2025-02-19 23:01:02 +0000
commitec7c9a8e607d63a008d06747f89c9512f5b3171e (patch)
tree0688906661889441fa8d912bbc4625887250344b
parent6f1a0f8574758489b78cf7518ffe0a8b9a108e29 (diff)
downloadfaker-ec7c9a8e607d63a008d06747f89c9512f5b3171e.tar.xz
faker-ec7c9a8e607d63a008d06747f89c9512f5b3171e.zip
fix: test before using Buffers (#3400)
-rw-r--r--src/internal/base64.ts21
1 files changed, 19 insertions, 2 deletions
diff --git a/src/internal/base64.ts b/src/internal/base64.ts
index c1f309fb..13cb5c52 100644
--- a/src/internal/base64.ts
+++ b/src/internal/base64.ts
@@ -14,7 +14,7 @@
* @example const encodedHeader = toBase64(JSON.stringify(header));
*/
export const toBase64: (input: string) => string =
- typeof Buffer === 'undefined'
+ typeof Buffer === 'undefined' || !bufferFeatureCheck('base64')
? (input) => {
const utf8Bytes = new TextEncoder().encode(input);
const binaryString = Array.from(utf8Bytes, (byte) =>
@@ -39,10 +39,27 @@ export const toBase64: (input: string) => string =
* @example const encodedHeader = toBase64Url(JSON.stringify(header));
*/
export const toBase64Url: (input: string) => string =
- typeof Buffer === 'undefined'
+ typeof Buffer === 'undefined' || !bufferFeatureCheck('base64url')
? (input) =>
toBase64(input)
.replaceAll('+', '-')
.replaceAll('/', '_')
.replaceAll(/=+$/g, '')
: (input) => Buffer.from(input).toString('base64url');
+
+/**
+ * Checks whether the environment supports the given encoding on the `Buffer` class.
+ * This is required because some `Buffer` polyfills do not support all encodings.
+ *
+ * @param encoding The encoding to check.
+ *
+ * @see https://www.npmjs.com/package/buffer
+ * @see https://github.com/feross/buffer/issues/309
+ */
+function bufferFeatureCheck(encoding: BufferEncoding): boolean {
+ try {
+ return typeof Buffer.from('test').toString(encoding) === 'string';
+ } catch {
+ return false;
+ }
+}