Open History to see the last commit
1import { videoMimeType } from "./video.ts";
2
3export type FilePreviewKind =
4 | "image"
5 | "video"
6 | "audio"
7 | "pdf"
8 | "html"
9 | "markdown"
10 | "text"
11 | "unsupported";
12
13/** Content classification is identical for captured attachments and workspace references. */
14export function filePreviewKind(file: {
15 readonly name: string;
16 readonly mimeType?: string;
17}): FilePreviewKind {
18 const mime = file.mimeType?.split(";", 1)[0]?.trim().toLowerCase() ?? "";
19 const name = file.name.toLowerCase();
20 const extension = name.slice(name.lastIndexOf("."));
21 const generic = !mime || mime === "application/octet-stream" || mime === "text/plain";
22 if (mime === "application/pdf") return "pdf";
23 if (mime === "text/html") return "html";
24 if (mime === "text/markdown" || mime === "text/x-markdown") return "markdown";
25 if (mime.startsWith("image/")) return "image";
26 if (mime.startsWith("video/")) return "video";
27 if (mime.startsWith("audio/")) return "audio";
28 if (generic) {
29 if (extension === ".pdf") return "pdf";
30 if (/^\.html?$/.test(extension)) return "html";
31 if (/^\.(md|markdown|mdown|mkd|mdx)$/.test(extension)) return "markdown";
32 const media = mediaMimeTypeFromExtension(extension);
33 if (media?.startsWith("image/")) return "image";
34 if (media?.startsWith("video/")) return "video";
35 if (audioMimeTypeFromExtension(extension) !== null) return "audio";
36 if (
37 /^\.(txt|log|json|jsonc|jsonl|ndjson|yaml|yml|toml|ini|conf|config|env|csv|tsv|xml|css|scss|sass|less|js|jsx|mjs|cjs|ts|tsx|mts|cts|py|pyi|rb|go|rs|swift|kt|kts|java|c|h|cc|cpp|hpp|cs|php|sh|bash|zsh|fish|sql|graphql|gql|vue|svelte|r|lua|ex|exs|erl|hs|clj|dart|diff|patch|lock|properties|gradle)$/.test(
38 extension,
39 ) ||
40 /^(dockerfile|makefile|gemfile|rakefile|license|readme|\.gitignore|\.gitattributes|\.editorconfig|\.env)(\.|$)/i.test(
41 name.split(/[\\/]/).at(-1) ?? "",
42 )
43 )
44 return "text";
45 }
46 if (
47 mime.startsWith("text/") ||
48 /^(application\/(json|.*\+json|xml|.*\+xml|javascript|x-javascript|yaml|x-yaml|toml|sql))$/.test(
49 mime,
50 )
51 )
52 return "text";
53 return "unsupported";
54}
55
56export const FILE_TEXT_PREVIEW_MAX_BYTES = 1024 * 1024;
57
58/** Reject binary data rather than displaying replacement characters as a document. */
59export function decodeFilePreviewText(bytes: Uint8Array, truncated = false) {
60 const bounded = bytes.subarray(0, FILE_TEXT_PREVIEW_MAX_BYTES);
61 if (bounded.some((byte) => byte === 0))
62 throw new Error("This file contains binary data and cannot be shown as text.");
63 const decoder = new TextDecoder("utf-8", { fatal: true });
64 try {
65 return {
66 text: decoder.decode(bounded, { stream: truncated || bytes.length > bounded.length }),
67 truncated: truncated || bytes.length > bounded.length,
68 };
69 } catch {
70 throw new Error("This file is not UTF-8 text. Open it in another app to view its contents.");
71 }
72}
73
74export const WORKSPACE_BROWSER_PREVIEW_EXTENSIONS = [".htm", ".html", ".pdf"] as const;
75
76export const WORKSPACE_IMAGE_PREVIEW_EXTENSIONS = [
77 ".avif",
78 ".gif",
79 ".ico",
80 ".jpeg",
81 ".jpg",
82 ".png",
83 ".svg",
84 ".webp",
85] as const;
86
87const IMAGE_MIME_TYPE_BY_EXTENSION = new Map([
88 [".avif", "image/avif"],
89 [".gif", "image/gif"],
90 [".ico", "image/x-icon"],
91 [".jpeg", "image/jpeg"],
92 [".jpg", "image/jpeg"],
93 [".png", "image/png"],
94 [".svg", "image/svg+xml"],
95 [".webp", "image/webp"],
96]);
97
98const BROWSER_MIME_TYPE_BY_EXTENSION = new Map([
99 [".htm", "text/html"],
100 [".html", "text/html"],
101 [".pdf", "application/pdf"],
102]);
103
104const AUDIO_MIME_TYPE_BY_EXTENSION = new Map([
105 [".mp3", "audio/mpeg"],
106 [".wav", "audio/wav"],
107 [".ogg", "audio/ogg"],
108 [".oga", "audio/ogg"],
109 [".flac", "audio/flac"],
110 [".aac", "audio/aac"],
111 [".m4a", "audio/mp4"],
112 [".opus", "audio/ogg"],
113 [".aiff", "audio/aiff"],
114]);
115
116/** Audio a player can request inline; the server serves these with byte ranges like video. */
117export function audioMimeTypeFromExtension(extension: string): string | null {
118 if (!/^\.[a-z0-9]+$/i.test(extension)) return null;
119 return AUDIO_MIME_TYPE_BY_EXTENSION.get(extension.toLowerCase()) ?? null;
120}
121
122/** Classifies a literal filesystem extension, without URL decoding or suffix removal. */
123export function mediaMimeTypeFromExtension(extension: string): string | null {
124 if (!/^\.[a-z0-9]+$/i.test(extension)) return null;
125 return (
126 IMAGE_MIME_TYPE_BY_EXTENSION.get(extension.toLowerCase()) ??
127 videoMimeType({ name: `media${extension}`, mimeType: "" })
128 );
129}
130
131/** Files the server serves in place from anywhere on its host: media, audio and browser documents. */
132export function hostPreviewMimeTypeFromExtension(extension: string): string | null {
133 if (!/^\.[a-z0-9]+$/i.test(extension)) return null;
134 return (
135 mediaMimeTypeFromExtension(extension) ??
136 audioMimeTypeFromExtension(extension) ??
137 BROWSER_MIME_TYPE_BY_EXTENSION.get(extension.toLowerCase()) ??
138 null
139 );
140}
141
142/** Classifies an authored media path or URL. Filesystem validation uses the literal extension. */
143export function mediaMimeType(path: string): string | null {
144 const trimmed = path.trim();
145 const source = trimmed.startsWith("<") && trimmed.endsWith(">") ? trimmed.slice(1, -1) : trimmed;
146 const dataMimeType = /^data:((?:image|video)\/[\w.+-]+)[;,]/i.exec(source)?.[1];
147 if (dataMimeType) return dataMimeType.toLowerCase();
148
149 let sourcePath = source.split(/[?#]/, 1)[0] ?? "";
150 if (/^(?:https?:|file:|\/\/)/i.test(source)) {
151 try {
152 sourcePath = new URL(source, "https://media.invalid").pathname;
153 } catch {
154 return null;
155 }
156 }
157 try {
158 sourcePath = decodeURIComponent(sourcePath);
159 } catch {
160 // A literal percent character is valid in a filename.
161 }
162 const basename = sourcePath.split(/[\\/]/).at(-1) ?? "";
163 const extensionIndex = basename.lastIndexOf(".");
164 return extensionIndex < 0 ? null : mediaMimeTypeFromExtension(basename.slice(extensionIndex));
165}
166
167export function mediaKindFromPath(path: string): "image" | "video" | null {
168 const mimeType = mediaMimeType(path);
169 if (mimeType === null) return null;
170 return mimeType.startsWith("video/") ? "video" : "image";
171}
172
173function hasPreviewExtension(path: string, extensions: ReadonlyArray<string>): boolean {
174 const pathWithoutQuery = path.split(/[?#]/, 1)[0]?.toLowerCase() ?? "";
175 return extensions.some((extension) => pathWithoutQuery.endsWith(extension));
176}
177
178export function isWorkspaceBrowserPreviewPath(path: string): boolean {
179 return hasPreviewExtension(path, WORKSPACE_BROWSER_PREVIEW_EXTENSIONS);
180}
181
182export function isWorkspaceImagePreviewPath(path: string): boolean {
183 return hasPreviewExtension(path, WORKSPACE_IMAGE_PREVIEW_EXTENSIONS);
184}
185
186/** File viewers receive literal filesystem paths, not Markdown URLs. */
187export function isWorkspaceVideoPreviewPath(path: string): boolean {
188 return videoMimeType({ name: path, mimeType: "" }) !== null;
189}
190
191export function isWorkspaceAudioPreviewPath(path: string): boolean {
192 const extensionIndex = path.lastIndexOf(".");
193 return extensionIndex >= 0 && audioMimeTypeFromExtension(path.slice(extensionIndex)) !== null;
194}
195
196export function isWorkspacePreviewEntryPath(path: string): boolean {
197 return isWorkspaceBrowserPreviewPath(path) || isWorkspaceImagePreviewPath(path);
198}