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

image.ts

50 lines1.7 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 // macOS and Windows label TypeScript `.ts` files as MPEG transport streams, which browsers can't play.
17 "video/mp2t",
18 "video/vnd.dlna.mpeg-tts",
19]);
20​
21export function isSvgAttachment(attachment: {
22 readonly name: string;
23 readonly mimeType: string;
24}): boolean {
25 const mimeType = attachment.mimeType.split(";", 1)[0]?.trim().toLowerCase() ?? "";
26 return (
27 mimeType === "image/svg+xml" ||
28 ((mimeType === "" || GENERIC_MIME_TYPES.has(mimeType)) && /\.svg$/i.test(attachment.name))
29 );
31​
32export function imageMimeType(attachment: {
33 readonly name: string;
34 readonly mimeType: string;
35}): string | null {
36 const mimeType = attachment.mimeType.split(";", 1)[0]?.trim().toLowerCase() ?? "";
37 if (SUPPORTED_IMAGE_MIME_TYPES.has(mimeType)) return mimeType;
38 if (mimeType.startsWith("image/")) return null;
39 // Infer from filenames only for missing or generic MIME types; extensions must not override a definite type.
40 if (mimeType !== "" && !GENERIC_MIME_TYPES.has(mimeType)) return null;
41 const dotIndex = attachment.name.lastIndexOf(".");
42 return dotIndex < 0
43 ? null
44 : (IMAGE_MIME_TYPE_BY_EXTENSION.get(
45 attachment.name
46 .slice(dotIndex + 1)
47 .trim()
48 .toLowerCase(),
49 ) ?? null);