aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/internal/base64.ts24
-rw-r--r--src/modules/image/index.ts5
2 files changed, 26 insertions, 3 deletions
diff --git a/src/internal/base64.ts b/src/internal/base64.ts
new file mode 100644
index 00000000..b346538a
--- /dev/null
+++ b/src/internal/base64.ts
@@ -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');
diff --git a/src/modules/image/index.ts b/src/modules/image/index.ts
index babfa2dc..76aa759e 100644
--- a/src/modules/image/index.ts
+++ b/src/modules/image/index.ts
@@ -1,3 +1,4 @@
+import { toBase64 } from '../../internal/base64';
import { deprecated } from '../../internal/deprecated';
import { ModuleBase } from '../../internal/module-base';
@@ -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)}`;
}
}