Skip to content

Commit

Permalink
fix(image): fix dataUri with type svg-base64 in browsers (#3144)
Browse files Browse the repository at this point in the history
  • Loading branch information
ST-DDT authored Sep 26, 2024
1 parent d6bceb6 commit 78b2a3a
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 3 deletions.
24 changes: 24 additions & 0 deletions src/internal/base64.ts
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');
5 changes: 2 additions & 3 deletions src/modules/image/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { toBase64 } from '../../internal/base64';
import { deprecated } from '../../internal/deprecated';
import { ModuleBase } from '../../internal/module-base';

Expand Down Expand Up @@ -388,8 +389,6 @@ export class ImageModule extends ModuleBase {

return type === 'svg-uri'
? `data:image/svg+xml;charset=UTF-8,${encodeURIComponent(svgString)}`
: `data:image/svg+xml;base64,${Buffer.from(svgString).toString(
'base64'
)}`;
: `data:image/svg+xml;base64,${toBase64(svgString)}`;
}
}
18 changes: 18 additions & 0 deletions test/internal/base64.spec.ts
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'));
}
);
});

0 comments on commit 78b2a3a

Please sign in to comment.