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

image.ts

47 lines1.6 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 isSvgAttachment(attachment: {
19 readonly name: string;
20 readonly mimeType: string;
21}): boolean {
22 const mimeType = attachment.mimeType.split(";", 1)[0]?.trim().toLowerCase() ?? "";
23 return (
24 mimeType === "image/svg+xml" ||
25 ((mimeType === "" || GENERIC_MIME_TYPES.has(mimeType)) && /\.svg$/i.test(attachment.name))
26 );
28​
29export function imageMimeType(attachment: {
30 readonly name: string;
31 readonly mimeType: string;
32}): string | null {
33 const mimeType = attachment.mimeType.split(";", 1)[0]?.trim().toLowerCase() ?? "";
34 if (SUPPORTED_IMAGE_MIME_TYPES.has(mimeType)) return mimeType;
35 if (mimeType.startsWith("image/")) return null;
36 // Infer from filenames only for missing or generic MIME types; extensions must not override a definite type.
37 if (mimeType !== "" && !GENERIC_MIME_TYPES.has(mimeType)) return null;
38 const dotIndex = attachment.name.lastIndexOf(".");
39 return dotIndex < 0
40 ? null
41 : (IMAGE_MIME_TYPE_BY_EXTENSION.get(
42 attachment.name
43 .slice(dotIndex + 1)
44 .trim()
45 .toLowerCase(),
46 ) ?? null);