Skip to content

Commit 2d6ff74

Browse files
authored
fix: recognize svg and json content-types (#603)
1 parent 17421d6 commit 2d6ff74

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

src/lib/content-type-parser.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,32 @@ import { fileTypeFromBuffer } from '@sgtpooki/file-type'
44
// default from verified-fetch is application/octect-stream, which forces a download. This is not what we want for MANY file types.
55
export const defaultMimeType = 'text/html'
66

7+
function checkForSvg (bytes: Uint8Array): boolean {
8+
return /^(<\?xml[^>]+>)?[^<^\w]+<svg/ig.test(new TextDecoder().decode(bytes.slice(0, 64)))
9+
}
10+
11+
async function checkForJson (bytes: Uint8Array): Promise<boolean> {
12+
try {
13+
JSON.parse(new TextDecoder().decode(bytes))
14+
return true
15+
} catch (err) {
16+
return false
17+
}
18+
}
19+
720
export const contentTypeParser: ContentTypeParser = async (bytes, fileName) => {
821
const detectedType = (await fileTypeFromBuffer(bytes))?.mime
922
if (detectedType != null) {
1023
return detectedType
1124
}
25+
1226
if (fileName == null) {
1327
// no other way to determine file-type.
28+
if (checkForSvg(bytes)) {
29+
return 'image/svg+xml'
30+
} else if (await checkForJson(bytes)) {
31+
return 'application/json'
32+
}
1433
return defaultMimeType
1534
}
1635

0 commit comments

Comments
 (0)