Skip to content

Commit 78b2a3a

Browse files
authored
fix(image): fix dataUri with type svg-base64 in browsers (#3144)
1 parent d6bceb6 commit 78b2a3a

File tree

3 files changed

+44
-3
lines changed

3 files changed

+44
-3
lines changed

src/internal/base64.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/**
2+
* This works the same as `Buffer.from(input).toString('base64')`
3+
* to work on both Node.js and browser environment.
4+
*
5+
* @internal
6+
*
7+
* @param input The string to encode to Base64.
8+
*
9+
* @returns Base64 encoded string.
10+
*
11+
* @see https://datatracker.ietf.org/doc/html/rfc4648
12+
*
13+
* @example const encodedHeader = toBase64(JSON.stringify(header));
14+
*/
15+
export const toBase64: (input: string) => string =
16+
typeof Buffer === 'undefined'
17+
? (input) => {
18+
const utf8Bytes = new TextEncoder().encode(input);
19+
const binaryString = Array.from(utf8Bytes, (byte) =>
20+
String.fromCodePoint(byte)
21+
).join('');
22+
return btoa(binaryString);
23+
}
24+
: (input) => Buffer.from(input).toString('base64');

src/modules/image/index.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { toBase64 } from '../../internal/base64';
12
import { deprecated } from '../../internal/deprecated';
23
import { ModuleBase } from '../../internal/module-base';
34

@@ -388,8 +389,6 @@ export class ImageModule extends ModuleBase {
388389

389390
return type === 'svg-uri'
390391
? `data:image/svg+xml;charset=UTF-8,${encodeURIComponent(svgString)}`
391-
: `data:image/svg+xml;base64,${Buffer.from(svgString).toString(
392-
'base64'
393-
)}`;
392+
: `data:image/svg+xml;base64,${toBase64(svgString)}`;
394393
}
395394
}

test/internal/base64.spec.ts

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import { describe, expect, it } from 'vitest';
2+
import { faker } from '../../src';
3+
import { toBase64 } from '../../src/internal/base64';
4+
5+
// This test is kind of useless, because during testing the Buffer object is always available.
6+
describe('toBase64', () => {
7+
it.each(
8+
faker.helpers.multiple(
9+
() => faker.string.alphanumeric({ length: { min: 0, max: 100 } }),
10+
{ count: 5 }
11+
)
12+
)(
13+
"should behave the same as `Buffer.from(value).toString('base64')`",
14+
(value) => {
15+
expect(toBase64(value)).toBe(Buffer.from(value).toString('base64'));
16+
}
17+
);
18+
});

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy