Skip to content

Build your personal knowledge base with Trilium Notes

fix(images): name a format the way people write it, in one place

Elian Dorana0c3f8a08140
diff --git a/apps/client/src/services/image.spec.ts b/apps/client/src/services/image.spec.ts
index 34c150aedf..3413ad6740 100644
--- a/apps/client/src/services/image.spec.ts
+++ b/apps/client/src/services/image.spec.ts
@@ -132,6 +132,9 @@ describe("getFileNameFromSrc", () => {
it("derives a clean extension from a compound MIME type", () => {
expect(getFileNameFromSrc("api/images/abc/diagram", "image/svg+xml")).toBe("diagram.svg");
+ // Named the way people write it, rather than by stripping the punctuation out of the
+ // subtype — which would save a favicon as "icon.xicon".
+ expect(getFileNameFromSrc("api/images/abc/icon", "image/x-icon")).toBe("icon.ico");
});
it("falls back to the raw segment when it is a malformed URI", () => {
@@ -139,9 +142,9 @@ describe("getFileNameFromSrc", () => {
});
it("leaves the name unchanged when the MIME type yields no extension", () => {
- // "image/" -> split("/")[1] is "" -> extension is falsy, so no suffix is appended.
+ // A media type too malformed to name a format says nothing, rather than having a guessed
+ // extension appended to the file the user is about to save.
expect(getFileNameFromSrc("api/images/abc/screenshot", "image/")).toBe("screenshot");
- // A MIME type without a slash -> split("/")[1] is undefined -> optional chaining short-circuits.
expect(getFileNameFromSrc("api/images/abc/screenshot", "image")).toBe("screenshot");
});
});
diff --git a/apps/client/src/services/image.ts b/apps/client/src/services/image.ts
index bc57d86d37..8513739e49 100644
--- a/apps/client/src/services/image.ts
+++ b/apps/client/src/services/image.ts
@@ -1,3 +1,5 @@
+import { imageExtensionForMime } from "@triliumnext/commons";
+
import { t } from "./i18n.js";
import open, { getUrlForDownload } from "./open.js";
import toastService, { showError } from "./toast.js";
@@ -132,9 +134,12 @@ export function getFileNameFromSrc(src: string, mimeType?: string) {
name = lastSegment || "image";
}
- // Ensure an extension, since a blob: URL carries none: derive it from the MIME type.
+ // Ensure an extension, since a blob: URL carries none: derive it from the MIME type. No
+ // fallback — a media type too malformed to name a format is left to say nothing, rather than
+ // having a guess appended to the file the user is about to save.
if (mimeType && !name.includes(".")) {
- const extension = mimeType.split("/")[1]?.split("+")[0]; // e.g. "image/svg+xml" → "svg"
+ const extension = imageExtensionForMime(mimeType, "");
+
if (extension) {
name += `.${extension}`;
}
diff --git a/apps/client/src/services/image_upload.spec.ts b/apps/client/src/services/image_upload.spec.ts
index bbce585539..b7baf964a4 100644
--- a/apps/client/src/services/image_upload.spec.ts
+++ b/apps/client/src/services/image_upload.spec.ts
@@ -13,8 +13,12 @@ describe("parseImageDataUrl", () => {
expect(parseImageDataUrl("data:image/jpeg;base64,BBBB")?.ext).toBe("jpeg");
});
- it("maps svg+xml to a clean 'svg' extension", () => {
+ it("names a format the way people write it", () => {
expect(parseImageDataUrl("data:image/svg+xml;base64,Q0M=")?.ext).toBe("svg");
+ // A favicon used to be stored as "example.com.xicon", the subtype having had its
+ // punctuation stripped out rather than being recognised.
+ expect(parseImageDataUrl("data:image/x-icon;base64,Q0M=")?.ext).toBe("ico");
+ expect(parseImageDataUrl("data:image/vnd.microsoft.icon;base64,Q0M=")?.ext).toBe("ico");
});
it("returns null for non-base64 data URLs and plain URLs", () => {
diff --git a/apps/client/src/services/image_upload.ts b/apps/client/src/services/image_upload.ts
index e646262ba3..4cea92cf28 100644
--- a/apps/client/src/services/image_upload.ts
+++ b/apps/client/src/services/image_upload.ts
@@ -1,4 +1,4 @@
-import type { ImageAttachmentRole } from "@triliumnext/commons";
+import { type ImageAttachmentRole, imageExtensionForMime } from "@triliumnext/commons";
import server from "./server.js";
@@ -73,7 +73,6 @@ export function parseImageDataUrl(dataUrl: string): ParsedImageDataUrl | null {
const mime = match[1];
const base64 = match[2];
- const subtype = mime.split("/")[1] ?? "png";
- const ext = subtype === "svg+xml" ? "svg" : (subtype.replace(/[^a-z0-9]/gi, "") || "png");
- return { mime, base64, ext };
+
+ return { mime, base64, ext: imageExtensionForMime(mime) };
}
diff --git a/packages/commons/src/lib/image_mimes.spec.ts b/packages/commons/src/lib/image_mimes.spec.ts
index 487185d6dc..83e00a5de7 100644
--- a/packages/commons/src/lib/image_mimes.spec.ts
+++ b/packages/commons/src/lib/image_mimes.spec.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
-import { IMAGE_MIMES, IMAGE_UPLOAD_SUBTYPES, isAcceptedImageMime } from "./image_mimes.js";
+import { IMAGE_MIMES, IMAGE_UPLOAD_SUBTYPES, imageExtensionForMime, imageMimeForExtension, isAcceptedImageMime } from "./image_mimes.js";
describe("isAcceptedImageMime", () => {
it("accepts every listed type and nothing else", () => {
@@ -28,6 +28,64 @@ describe("isAcceptedImageMime", () => {
});
});
+describe("imageExtensionForMime", () => {
+ it("names a format the way people write it, not the way its subtype reads", () => {
+ // The whole reason this exists: stripping the punctuation out of a subtype turns an icon
+ // into ".xicon" and an SVG into ".svgxml", which is what a favicon attachment used to be
+ // called.
+ expect(imageExtensionForMime("image/x-icon")).toBe("ico");
+ expect(imageExtensionForMime("image/vnd.microsoft.icon")).toBe("ico");
+ expect(imageExtensionForMime("image/svg+xml")).toBe("svg");
+ });
+
+ it("takes the subtype where the subtype is the name", () => {
+ expect(imageExtensionForMime("image/png")).toBe("png");
+ expect(imageExtensionForMime("image/jpeg")).toBe("jpeg");
+ expect(imageExtensionForMime("image/webp")).toBe("webp");
+ expect(imageExtensionForMime("image/avif")).toBe("avif");
+ expect(imageExtensionForMime("image/bmp")).toBe("bmp");
+ });
+
+ it("reads a media type however it was written, and falls back where it cannot", () => {
+ expect(imageExtensionForMime("IMAGE/X-ICON")).toBe("ico");
+ expect(imageExtensionForMime(" image/x-icon ")).toBe("ico");
+ expect(imageExtensionForMime("nonsense")).toBe("png");
+ expect(imageExtensionForMime(undefined)).toBe("png");
+ expect(imageExtensionForMime("", "bin")).toBe("bin");
+ });
+
+ it("gives every accepted media type a usable extension", () => {
+ for (const mime of IMAGE_MIMES) {
+ expect(imageExtensionForMime(mime), mime).toMatch(/^[a-z0-9]+$/);
+ }
+ });
+});
+
+describe("imageMimeForExtension", () => {
+ it("reverses the overrides, naming an icon the way servers do", () => {
+ // Two media types share ".ico"; the one a reader will recognise wins.
+ expect(imageMimeForExtension("ico")).toBe("image/x-icon");
+ expect(imageMimeForExtension("svg")).toBe("image/svg+xml");
+ });
+
+ it("builds the media type from the extension otherwise", () => {
+ expect(imageMimeForExtension("png")).toBe("image/png");
+ expect(imageMimeForExtension("webp")).toBe("image/webp");
+ expect(imageMimeForExtension(".PNG")).toBe("image/png");
+ expect(imageMimeForExtension(undefined)).toBe("image/png");
+ });
+
+ it("round-trips every extension it produces back to an accepted media type", () => {
+ // What the two are for: an upload is named by its media type on the way out and stored
+ // under a media type derived from its format on the way back in, so a format that survives
+ // one direction but not the other would be stored as something the endpoints reject.
+ for (const mime of IMAGE_MIMES) {
+ const roundTripped = imageMimeForExtension(imageExtensionForMime(mime));
+ expect(isAcceptedImageMime(roundTripped), `${mime} -> ${roundTripped}`).toBe(true);
+ }
+ });
+});
+
describe("IMAGE_UPLOAD_SUBTYPES", () => {
it("is the same list with the type stripped, in the same order", () => {
expect(IMAGE_UPLOAD_SUBTYPES).toStrictEqual(IMAGE_MIMES.map((mime) => mime.replace("image/", "")));
diff --git a/packages/commons/src/lib/image_mimes.ts b/packages/commons/src/lib/image_mimes.ts
index 7778bbc325..5dd3c156ca 100644
--- a/packages/commons/src/lib/image_mimes.ts
+++ b/packages/commons/src/lib/image_mimes.ts
@@ -56,3 +56,47 @@ export function isAcceptedImageMime(mime: string | undefined | null): boolean {
* full — `svg` does not stand in for `svg+xml`.
*/
export const IMAGE_UPLOAD_SUBTYPES: readonly string[] = IMAGE_MIMES.map((mime) => mime.slice("image/".length));
+
+/**
+ * Media types whose file extension is not simply their subtype.
+ *
+ * Everything else is named by its subtype, which is right far more often than it is wrong:
+ * `image/png` is `.png`. These are the ones where deriving it that way produces something nobody
+ * has ever seen — an icon written `.xicon`, an SVG written `.svgxml` — because the subtype carries
+ * a prefix or a suffix that is not part of the name anyone uses for the format.
+ */
+const IMAGE_EXTENSION_OVERRIDES: Record<string, string> = {
+ "image/svg+xml": "svg",
+ "image/x-icon": "ico",
+ "image/vnd.microsoft.icon": "ico"
+};
+
+/** The extension a picture of this media type is written with, without the dot. */
+export function imageExtensionForMime(mime: string | undefined | null, fallback = "png"): string {
+ if (!mime) {
+ return fallback;
+ }
+
+ const normalized = mime.trim().toLowerCase();
+
+ return IMAGE_EXTENSION_OVERRIDES[normalized]
+ ?? ((normalized.split("/")[1] ?? "").replace(/[^a-z0-9]/g, "") || fallback);
+}
+
+/**
+ * The media type a picture with this extension is stored under — the reverse of
+ * {@link imageExtensionForMime}. Where two media types share an extension the first one wins, which
+ * is why `.ico` is `image/x-icon`: the registered `image/vnd.microsoft.icon` is the name, but
+ * `image/x-icon` is what servers actually send and what a reader will recognise.
+ */
+export function imageMimeForExtension(ext: string | undefined | null, fallback = "image/png"): string {
+ const normalized = (ext ?? "").trim().toLowerCase().replace(/^\./, "");
+
+ if (!normalized) {
+ return fallback;
+ }
+
+ const override = Object.entries(IMAGE_EXTENSION_OVERRIDES).find(([ , extension ]) => extension === normalized);
+
+ return override ? override[0] : `image/${normalized}`;
+}
diff --git a/packages/trilium-core/src/services/image.ts b/packages/trilium-core/src/services/image.ts
index dfedb8b513..1b159b6fe4 100644
--- a/packages/trilium-core/src/services/image.ts
+++ b/packages/trilium-core/src/services/image.ts
@@ -3,7 +3,7 @@
* Uses ImageProvider for platform-specific processing (compression, format detection).
*/
-import { type ImageAttachmentRole, isDeduplicatedAttachmentRole } from "@triliumnext/commons";
+import { type ImageAttachmentRole, imageMimeForExtension, isDeduplicatedAttachmentRole } from "@triliumnext/commons";
import sanitizeFilename from "sanitize-filename";
import becca from "../becca/becca.js";
@@ -15,19 +15,6 @@ import protectedSessionService from "./protected_session.js";
import { getSql } from "./sql/index.js";
import { sanitizeHtml } from "./sanitizer.js";
-/** Extensions whose media type is not simply `image/<ext>`. */
-const IMAGE_MIME_EXCEPTIONS: Record<string, string> = {
- svg: "image/svg+xml",
- // There is no `image/ico`: serving one under it leaves the picture to the browser's sniffing
- // rather than to the type it was told.
- ico: "image/x-icon"
-};
-
-function getImageMimeFromExtension(ext: string): string {
- ext = ext.toLowerCase();
- return IMAGE_MIME_EXCEPTIONS[ext] ?? `image/${ext}`;
-}
-
/**
* Image content that has been promised but not yet stored.
*
@@ -122,7 +109,7 @@ function updateImage(noteId: string, uploadBuffer: Uint8Array, originalName: str
trackWrite(getImageProvider().processImage(uploadBuffer, originalName, true).then(({ buffer, format }) => {
getContext().init(() => {
getSql().transactional(() => {
- note.mime = getImageMimeFromExtension(format.ext);
+ note.mime = imageMimeForExtension(format.ext);
note.save();
note.setContent(buffer);
});
@@ -164,7 +151,7 @@ function saveImage(
trackWrite(getImageProvider().processImage(uploadBuffer, originalName, shrinkImageSwitch).then(({ buffer, format }) => {
getContext().init(() => {
getSql().transactional(() => {
- note.mime = getImageMimeFromExtension(format.ext);
+ note.mime = imageMimeForExtension(format.ext);
if (!originalName.includes(".")) {
originalName += `.${format.ext}`;
@@ -264,7 +251,7 @@ function saveImageToAttachment(
return;
}
- savedAttachment.mime = getImageMimeFromExtension(format.ext);
+ savedAttachment.mime = imageMimeForExtension(format.ext);
if (!originalName.includes(".")) {
originalName += `.${format.ext}`;