-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
base64.js
58 lines (50 loc) · 1.83 KB
/
base64.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
export const BASE64_DATA_URI_PATTERN = /^data:(?<mime>[a-zA-Z]+\/[\w/\-.+]+);base64,(?<data>[-A-Za-z0-9+/=]+)$/;
export async function base64Encode(thing) {
switch (typeof thing) {
case 'string':
case 'number':
return btoa(thing);
case 'object':
if (thing === null) {
throw new TypeError('Cannot base64 encode null.');
} else if (thing instanceof Blob || thing instanceof Request || thing instanceof Response) {
return await thing.bytes().then(bytes => bytes.toBase64());
} else if (thing instanceof URL) {
return btoa(thing.href);
} else if (thing instanceof Uint8Array) {
return thing.toBase64();
} else {
return btoa(thing.toString());
}
case 'undefined':
throw new TypeError('Cannot base64 encode undefined.');
default:
throw new TypeError(`Cannot base64 encode something of type ${typeof thing}.`);
}
}
export const base64Decode = atob;
export function base64URIToBlob(uri) {
if (uri instanceof URL) {
return base64URIToBlob(uri.href);
} else if (typeof uri !== 'string') {
throw new TypeError('Cannot decode from a non-string.');
} else {
const { mime, data } = uri.match(BASE64_DATA_URI_PATTERN)?.groups ?? {};
if (typeof mime === 'string' && typeof data === 'string') {
return new Blob([Uint8Array.fromBase64(data)], { type: mime });
} else {
throw new DOMException('Error parsing data URI.', 'InvalidCharacterError');
}
}
}
export async function getBase64DataURI(thing) {
if (thing instanceof Request || thing instanceof Response) {
return await getBase64DataURI(await thing.blob());
} else if (!(thing instanceof Blob)) {
throw new TypeError('Cannot create base64 URI from a non-Blob.');
} else if (thing.type === '') {
throw new TypeError('Blob is missing required type.');
} else {
return new URL(`data:${thing.type};base64,${await base64Encode(thing)}`);
}
}