-
-
Notifications
You must be signed in to change notification settings - Fork 929
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix(image): fix dataUri with type svg-base64 in browsers (#3144)
- Loading branch information
Showing
3 changed files
with
44 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
/** | ||
* This works the same as `Buffer.from(input).toString('base64')` | ||
* to work on both Node.js and browser environment. | ||
* | ||
* @internal | ||
* | ||
* @param input The string to encode to Base64. | ||
* | ||
* @returns Base64 encoded string. | ||
* | ||
* @see https://datatracker.ietf.org/doc/html/rfc4648 | ||
* | ||
* @example const encodedHeader = toBase64(JSON.stringify(header)); | ||
*/ | ||
export const toBase64: (input: string) => string = | ||
typeof Buffer === 'undefined' | ||
? (input) => { | ||
const utf8Bytes = new TextEncoder().encode(input); | ||
const binaryString = Array.from(utf8Bytes, (byte) => | ||
String.fromCodePoint(byte) | ||
).join(''); | ||
return btoa(binaryString); | ||
} | ||
: (input) => Buffer.from(input).toString('base64'); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
import { describe, expect, it } from 'vitest'; | ||
import { faker } from '../../src'; | ||
import { toBase64 } from '../../src/internal/base64'; | ||
|
||
// This test is kind of useless, because during testing the Buffer object is always available. | ||
describe('toBase64', () => { | ||
it.each( | ||
faker.helpers.multiple( | ||
() => faker.string.alphanumeric({ length: { min: 0, max: 100 } }), | ||
{ count: 5 } | ||
) | ||
)( | ||
"should behave the same as `Buffer.from(value).toString('base64')`", | ||
(value) => { | ||
expect(toBase64(value)).toBe(Buffer.from(value).toString('base64')); | ||
} | ||
); | ||
}); |