Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

image.ts

36 lines1.2 KB

1// Match PROVIDER_SEND_TURN_SUPPORTED_IMAGE_MIME_TYPES so unsupported images remain sendable as files.
2const IMAGE_MIME_TYPE_BY_EXTENSION = new Map([
3 ["gif", "image/gif"],
4 ["jpeg", "image/jpeg"],
5 ["jpg", "image/jpeg"],
6 ["png", "image/png"],
7 ["webp", "image/webp"],
8]);
9​
10const SUPPORTED_IMAGE_MIME_TYPES = new Set(IMAGE_MIME_TYPE_BY_EXTENSION.values());
11​
12export const GENERIC_MIME_TYPES = new Set([
13 "application/octet-stream",
14 "binary/octet-stream",
15 "application/unknown",
16]);
17​
18export function imageMimeType(attachment: {
19 readonly name: string;
20 readonly mimeType: string;
21}): string | null {
22 const mimeType = attachment.mimeType.split(";", 1)[0]?.trim().toLowerCase() ?? "";
23 if (SUPPORTED_IMAGE_MIME_TYPES.has(mimeType)) return mimeType;
24 if (mimeType.startsWith("image/")) return null;
25 // Infer from filenames only for missing or generic MIME types; extensions must not override a definite type.
26 if (mimeType !== "" && !GENERIC_MIME_TYPES.has(mimeType)) return null;
27 const dotIndex = attachment.name.lastIndexOf(".");
28 return dotIndex < 0
29 ? null
30 : (IMAGE_MIME_TYPE_BY_EXTENSION.get(
31 attachment.name
32 .slice(dotIndex + 1)
33 .trim()
34 .toLowerCase(),
35 ) ?? null);