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

image.ts

66 lines2.4 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);
51​
52// Providers reject an image whose declared type disagrees with its bytes, and the image stays in thread history.
53export function imageMimeTypeFromBytes(bytes: Uint8Array): string | null {
54 const startsWith = (signature: readonly number[], offset = 0) =>
55 signature.every((byte, index) => bytes[offset + index] === byte);
56 if (startsWith([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) return "image/png";
57 if (startsWith([0xff, 0xd8, 0xff])) return "image/jpeg";
58 if (
59 startsWith([0x47, 0x49, 0x46, 0x38, 0x37, 0x61]) ||
60 startsWith([0x47, 0x49, 0x46, 0x38, 0x39, 0x61])
61 )
62 return "image/gif";
63 if (startsWith([0x52, 0x49, 0x46, 0x46]) && startsWith([0x57, 0x45, 0x42, 0x50], 8))
64 return "image/webp";
65 return null;