|
1 |
| -export interface ParsedDataURI { |
2 |
| - type: string; |
3 |
| - typeFull: string; |
4 |
| - charset: string; |
5 |
| - buffer: ArrayBuffer; |
6 |
| -} |
| 1 | +import { makeDataUriToBuffer } from './common'; |
| 2 | + |
| 3 | +export type { ParsedDataURI } from './common'; |
7 | 4 |
|
8 | 5 | function base64ToArrayBuffer(base64: string) {
|
9 | 6 | const chars =
|
@@ -58,55 +55,4 @@ function stringToBuffer(str: string): ArrayBuffer {
|
58 | 55 | *
|
59 | 56 | * @param {String} uri Data URI to turn into a Buffer instance
|
60 | 57 | */
|
61 |
| -export function dataUriToBuffer(uri: string | URL): ParsedDataURI { |
62 |
| - uri = String(uri); |
63 |
| - |
64 |
| - if (!/^data:/i.test(uri)) { |
65 |
| - throw new TypeError( |
66 |
| - '`uri` does not appear to be a Data URI (must begin with "data:")' |
67 |
| - ); |
68 |
| - } |
69 |
| - |
70 |
| - // strip newlines |
71 |
| - uri = uri.replace(/\r?\n/g, ''); |
72 |
| - |
73 |
| - // split the URI up into the "metadata" and the "data" portions |
74 |
| - const firstComma = uri.indexOf(','); |
75 |
| - if (firstComma === -1 || firstComma <= 4) { |
76 |
| - throw new TypeError('malformed data: URI'); |
77 |
| - } |
78 |
| - |
79 |
| - // remove the "data:" scheme and parse the metadata |
80 |
| - const meta = uri.substring(5, firstComma).split(';'); |
81 |
| - |
82 |
| - let charset = ''; |
83 |
| - let base64 = false; |
84 |
| - const type = meta[0] || 'text/plain'; |
85 |
| - let typeFull = type; |
86 |
| - for (let i = 1; i < meta.length; i++) { |
87 |
| - if (meta[i] === 'base64') { |
88 |
| - base64 = true; |
89 |
| - } else if (meta[i]) { |
90 |
| - typeFull += `;${meta[i]}`; |
91 |
| - if (meta[i].indexOf('charset=') === 0) { |
92 |
| - charset = meta[i].substring(8); |
93 |
| - } |
94 |
| - } |
95 |
| - } |
96 |
| - // defaults to US-ASCII only if type is not provided |
97 |
| - if (!meta[0] && !charset.length) { |
98 |
| - typeFull += ';charset=US-ASCII'; |
99 |
| - charset = 'US-ASCII'; |
100 |
| - } |
101 |
| - |
102 |
| - // get the encoded data portion and decode URI-encoded chars |
103 |
| - const data = unescape(uri.substring(firstComma + 1)); |
104 |
| - const buffer = base64 ? base64ToArrayBuffer(data) : stringToBuffer(data); |
105 |
| - |
106 |
| - return { |
107 |
| - type, |
108 |
| - typeFull, |
109 |
| - charset, |
110 |
| - buffer, |
111 |
| - }; |
112 |
| -} |
| 58 | +export const dataUriToBuffer = makeDataUriToBuffer({ stringToBuffer, base64ToArrayBuffer }); |
0 commit comments