Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
test(import): cover Obsidian attachment, link and frontmatter logic
Elian Doraneb4db7945379
diff --git a/packages/trilium-core/src/services/import/frontmatter.spec.ts b/packages/trilium-core/src/services/import/frontmatter.spec.tsindex ac8efb172d..b6f15a5534 100644--- a/packages/trilium-core/src/services/import/frontmatter.spec.ts+++ b/packages/trilium-core/src/services/import/frontmatter.spec.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";-import { extractFrontmatter } from "./frontmatter.js";+import { extractFrontmatter, parseFrontmatter } from "./frontmatter.js";describe("extractFrontmatter", () => {it("parses scalar properties into camelCased labels and strips the block from the body", () => {@@ -21,9 +21,10 @@ describe("extractFrontmatter", () => {});it("stringifies booleans/numbers and keeps an empty property as an empty-valued label", () => {- const { attributes } = extractFrontmatter("---\nCheckbox prop: true\nNumber: 5\nfirst:\n---\n");+ const { attributes } = extractFrontmatter("---\nCheckbox prop: true\nDisabled: false\nNumber: 5\nfirst:\n---\n");expect(attributes).toEqual([{ name: "checkboxProp", value: "true" },+ { name: "disabled", value: "false" },{ name: "number", value: "5" },{ name: "first", value: "" }]);@@ -60,4 +61,25 @@ describe("extractFrontmatter", () => {expect(body).toBe(md);expect(attributes).toEqual([]);});++ it("skips a nested-mapping property, which has no flat label representation", () => {+ const { attributes } = extractFrontmatter("---\nscalar: kept\nnested:\n a: 1\n b: 2\n---\n");+ expect(attributes).toEqual([{ name: "scalar", value: "kept" }]);+ });+});++describe("parseFrontmatter", () => {+ it("strips a structurally-valid non-mapping block (list/scalar) but yields no data", () => {+ const list = parseFrontmatter("---\n- a\n- b\n---\nBody.");+ expect(list).toEqual({ body: "Body.", data: {} });++ const scalar = parseFrontmatter("---\njust a scalar\n---\nBody.");+ expect(scalar).toEqual({ body: "Body.", data: {} });+ });++ it("returns the raw key/value mapping for a caller to type itself", () => {+ const { body, data } = parseFrontmatter("---\nNumber: 5\nFlag: true\n---\nBody.");+ expect(body).toBe("Body.");+ expect(data).toEqual({ Number: 5, Flag: true });+ });});diff --git a/packages/trilium-core/src/services/import/frontmatter.ts b/packages/trilium-core/src/services/import/frontmatter.tsindex e0b57e29d9..81a00e07bc 100644--- a/packages/trilium-core/src/services/import/frontmatter.ts+++ b/packages/trilium-core/src/services/import/frontmatter.ts@@ -87,6 +87,7 @@ function toValues(value: unknown): string[] {if (typeof value === "string") {return [value];}+ /* v8 ignore next 3 -- defensive: js-yaml's `load` schema resolves timestamps to strings, never Date objects */if (value instanceof Date) {return [value.toISOString()];}diff --git a/packages/trilium-core/src/services/import/obsidian/attachments.spec.ts b/packages/trilium-core/src/services/import/obsidian/attachments.spec.tsnew file mode 100644index 0000000000..0c84d8cf16--- /dev/null+++ b/packages/trilium-core/src/services/import/obsidian/attachments.spec.ts@@ -0,0 +1,161 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++import type BNote from "../../../becca/entities/bnote.js";+import imageService from "../../image.js";+import { applyAttachments, type AttachmentIndex, buildAttachmentIndex, isImageMime, resolveAttachment } from "./attachments.js";++/** Spy on the shared imageService object the importer imports — `saveImageToAttachment` would otherwise hit the DB. */+const saveImageToAttachment = vi.spyOn(imageService, "saveImageToAttachment");++/** A stub note that records `saveAttachment` calls and hands back a deterministic attachment id per title. */+function fakeNote() {+ const saveAttachment = vi.fn(({ title }: { title: string }) => ({ attachmentId: `att-${title}` }));+ const note = { noteId: "note1", saveAttachment } as unknown as BNote;+ return { note, saveAttachment };+}++/** Builds an attachment index from a `path -> placeholder bytes` map (bytes content is irrelevant to resolution). */+function indexOf(...paths: string[]): AttachmentIndex {+ return buildAttachmentIndex(new Map(paths.map((p) => [p, new Uint8Array([1])])));+}++beforeEach(() => {+ saveImageToAttachment.mockReset();+ saveImageToAttachment.mockReturnValue({ attachmentId: "img1", title: "picture.png" } as ReturnType<typeof imageService.saveImageToAttachment>);+});++describe("buildAttachmentIndex", () => {+ it("groups paths under their lower-cased base name", () => {+ const index = indexOf("Folder/Picture.PNG", "Other/picture.png", "doc.pdf");+ expect(index.byBasename.get("picture.png")).toEqual(["Folder/Picture.PNG", "Other/picture.png"]);+ expect(index.byBasename.get("doc.pdf")).toEqual(["doc.pdf"]);+ });+});++describe("resolveAttachment", () => {+ it("resolves an exact vault path first", () => {+ const resolved = resolveAttachment(indexOf("Folder/doc.pdf"), "Folder/doc.pdf");+ expect(resolved).toMatchObject({ path: "Folder/doc.pdf", mime: "application/pdf" });+ });++ it("falls back to a unique base-name match (Obsidian shortest-path rule)", () => {+ const resolved = resolveAttachment(indexOf("Folder/picture.png"), "picture.png");+ expect(resolved?.path).toBe("Folder/picture.png");+ });++ it("returns null for an ambiguous base name shared by two files", () => {+ expect(resolveAttachment(indexOf("a/pic.png", "b/pic.png"), "pic.png")).toBeNull();+ });++ it("returns null when nothing matches", () => {+ expect(resolveAttachment(indexOf("doc.pdf"), "missing.png")).toBeNull();+ });++ it("falls back to application/octet-stream for an unknown extension", () => {+ expect(resolveAttachment(indexOf("data.unknownext"), "data.unknownext")?.mime).toBe("application/octet-stream");+ });+});++describe("isImageMime", () => {+ it("is true only for image/* mimes", () => {+ expect(isImageMime("image/png")).toBe(true);+ expect(isImageMime("application/pdf")).toBe(false);+ });+});++describe("applyAttachments", () => {+ it("returns the html untouched when the index is empty or there are no img/a elements", () => {+ const html = `<p><img src="/picture.png"></p>`;+ expect(applyAttachments(fakeNote().note, html, buildAttachmentIndex(new Map()), false)).toBe(html);+ expect(applyAttachments(fakeNote().note, "<p>plain text</p>", indexOf("picture.png"), false)).toBe("<p>plain text</p>");+ });++ it("saves a resolved image embed as an inline image attachment and rewrites its src", () => {+ const { note } = fakeNote();+ const consumed = new Set<string>();+ const html = applyAttachments(note, `<p><img src="/picture.png"></p>`, indexOf("picture.png"), true, consumed);++ expect(saveImageToAttachment).toHaveBeenCalledWith("note1", expect.any(Uint8Array), "picture.png", true);+ expect(html).toBe(`<p><img src="api/attachments/img1/image/picture.png"></p>`);+ expect([...consumed]).toEqual(["picture.png"]);+ });++ it("carries an Obsidian |size suffix over as the image width", () => {+ const { note } = fakeNote();+ const html = applyAttachments(note, `<p><img src="/picture.png|120"></p>`, indexOf("picture.png"), false);+ expect(html).toContain(`width="120"`);+ });++ it("falls back to a file link when saving the image attachment throws", () => {+ const { note, saveAttachment } = fakeNote();+ saveImageToAttachment.mockImplementationOnce(() => {+ throw new Error("image save failed");+ });+ const html = applyAttachments(note, `<p><img src="/picture.png"></p>`, indexOf("picture.png"), false);++ expect(saveAttachment).toHaveBeenCalledWith(expect.objectContaining({ role: "file", title: "picture.png" }));+ expect(html).toContain(`class="reference-link"`);+ expect(html).not.toContain("<img");+ });++ it("turns an embedded non-image file into a file-reference link", () => {+ const { note, saveAttachment } = fakeNote();+ const html = applyAttachments(note, `<p><img src="/report.pdf"></p>`, indexOf("report.pdf"), false);++ expect(saveAttachment).toHaveBeenCalledWith(expect.objectContaining({ role: "file", mime: "application/pdf", title: "report.pdf" }));+ expect(html).toContain(`<a class="reference-link" href="#root/note1?viewMode=attachments&attachmentId=att-report.pdf">report.pdf</a>`);+ expect(html).not.toContain("<img");+ });++ it("rewrites a link that resolves to a bundled file into a file-reference link", () => {+ const { note } = fakeNote();+ const consumed = new Set<string>();+ const html = applyAttachments(note, `<p><a href="/report.pdf">report</a></p>`, indexOf("report.pdf"), false, consumed);++ expect(html).toContain(`href="#root/note1?viewMode=attachments&attachmentId=att-report.pdf"`);+ expect(html).toContain(`class="reference-link"`);+ expect([...consumed]).toEqual(["report.pdf"]);+ });++ it("leaves img/a references that don't resolve to a bundled file untouched", () => {+ const { note, saveAttachment } = fakeNote();+ const html = `<p><img src="/missing.png"><a href="/missing.pdf">x</a></p>`;+ expect(applyAttachments(note, html, indexOf("report.pdf"), false)).toBe(html);+ expect(saveAttachment).not.toHaveBeenCalled();+ expect(saveImageToAttachment).not.toHaveBeenCalled();+ });++ it("never touches external URLs, data/mailto schemes or in-note anchors", () => {+ const { note } = fakeNote();+ const html =+ `<p><img src="https://x/y.png"><img src="data:image/png;base64,AAAA">` ++ `<a href="mailto:[email protected]">m</a><a href="#section">anchor</a></p>`;+ expect(applyAttachments(note, html, indexOf("y.png"), false)).toBe(html);+ });++ it("strips a #heading suffix, normalizes backslashes and url-decodes the reference", () => {+ const { note } = fakeNote();+ // `Sub Folder\pic.png#frag` — backslashes become slashes, the fragment is dropped, %20 decoded.+ applyAttachments(note, `<p><img src="/Sub%20Folder\\pic.png#frag"></p>`, indexOf("Sub Folder/pic.png"), false);+ expect(saveImageToAttachment).toHaveBeenCalledWith("note1", expect.any(Uint8Array), "pic.png", false);+ });++ it("ignores a non-numeric |suffix (it carries no width) and skips an empty reference", () => {+ const { note } = fakeNote();+ // `picture.png|caption` — the alias isn't a size, so no width attribute is added.+ const sized = applyAttachments(note, `<p><img src="/picture.png|caption"></p>`, indexOf("picture.png"), false);+ expect(sized).toContain(`src="api/attachments/img1/image/picture.png"`);+ expect(sized).not.toContain("width");++ // `/|100` reduces to an empty reference once the |size is peeled off, so the img is left untouched.+ const empty = `<p><img src="/|100"></p>`;+ expect(applyAttachments(fakeNote().note, empty, indexOf("picture.png"), false)).toBe(empty);+ });++ it("keeps the original value when the reference cannot be url-decoded", () => {+ const { note } = fakeNote();+ // A malformed percent-escape makes decodeURIComponent throw; the raw name is used and resolves directly.+ applyAttachments(note, `<p><img src="/%E0%A4.png"></p>`, indexOf("%E0%A4.png"), false);+ expect(saveImageToAttachment).toHaveBeenCalled();+ });+});diff --git a/packages/trilium-core/src/services/import/obsidian/excalidraw.spec.ts b/packages/trilium-core/src/services/import/obsidian/excalidraw.spec.tsindex 79bb155c37..5fa9e8b79b 100644--- a/packages/trilium-core/src/services/import/obsidian/excalidraw.spec.ts+++ b/packages/trilium-core/src/services/import/obsidian/excalidraw.spec.ts@@ -68,9 +68,27 @@ describe("parseExcalidraw", () => {expect([...drawing.embeddedFiles]).toEqual([["abc123def456", "picture.png"]]);});+ it("defaults missing elements and appState to empty in the canvas content", () => {+ const drawing = parseExcalidraw(`## Drawing\n\`\`\`json\n${JSON.stringify({ type: "excalidraw" })}\n\`\`\``);+ const content = drawing && JSON.parse(drawing.content);+ expect(content).toMatchObject({ elements: [], appState: {}, files: {} });+ expect(drawing?.embeddedFiles.size).toBe(0);+ });++ it("ignores scene elements that are null or carry no string fileId when collecting embeds", () => {+ const scene = { ...SCENE, elements: [null, { id: "x", type: "rectangle" }, { id: "img", type: "image", fileId: 42 }] };+ const embedded = "## Embedded Files\nabc123def456: [[picture.png]]\n";+ const drawing = parseExcalidraw(compressedFile(scene, embedded));+ expect(drawing?.embeddedFiles.size).toBe(0);+ });+it("returns null when there is no drawing block or the data is corrupt", () => {expect(parseExcalidraw("# Just a heading\nNo drawing here.")).toBeNull();expect(parseExcalidraw("## Drawing\n```compressed-json\nnot-valid-base64!!\n```")).toBeNull();expect(parseExcalidraw("## Drawing\n```json\n{ not json\n```")).toBeNull();+ // A structurally-valid JSON that isn't an object (a bare number) is rejected too.+ expect(parseExcalidraw("## Drawing\n```json\n42\n```")).toBeNull();+ // An empty compressed-json block decompresses to nothing rather than throwing.+ expect(parseExcalidraw("## Drawing\n```compressed-json\n\n```")).toBeNull();});});diff --git a/packages/trilium-core/src/services/import/obsidian/links.spec.ts b/packages/trilium-core/src/services/import/obsidian/links.spec.tsnew file mode 100644index 0000000000..5e5ec4ebc7--- /dev/null+++ b/packages/trilium-core/src/services/import/obsidian/links.spec.ts@@ -0,0 +1,116 @@+import { describe, expect, it } from "vitest";++import { buildNoteIndex, resolveLinks } from "./links.js";++/** Builds a note index from `path -> noteId` pairs, mirroring how the importer feeds created notes in. */+function indexOf(entries: Record<string, string>) {+ return buildNoteIndex(Object.entries(entries).map(([path, noteId]) => ({ note: { noteId }, path })));+}++describe("buildNoteIndex", () => {+ it("indexes by lower-cased path (sans .md) and by unique base name", () => {+ const index = indexOf({ "Folder/Target.md": "id1", "Other.md": "id2" });+ expect(index.byPath.get("folder/target")).toBe("id1");+ expect(index.byPath.get("other")).toBe("id2");+ expect(index.byName.get("target")).toBe("id1");+ });++ it("marks a base name shared by two notes as ambiguous (null)", () => {+ const index = indexOf({ "A/Note.md": "id1", "B/Note.md": "id2" });+ expect(index.byName.get("note")).toBeNull();+ // The fully-qualified paths still resolve unambiguously.+ expect(index.byPath.get("a/note")).toBe("id1");+ expect(index.byPath.get("b/note")).toBe("id2");+ });+});++describe("resolveLinks", () => {+ const index = indexOf({ "Folder/Target.md": "id1", "Other.md": "id2", "A/Note.md": "id3", "B/Note.md": "id4" });++ it("returns the html untouched when there is no vault-relative link or embed", () => {+ const html = `<p>plain <a class="reference-link" href="#root/x">existing</a></p>`;+ const result = resolveLinks(html, index);+ expect(result).toEqual({ html, internalLinks: [], includeLinks: [] });+ });++ it("rewrites a bare wikilink to a #root reference link and records the backlink", () => {+ const { html, internalLinks } = resolveLinks(`<p><a class="reference-link" href="/Other">Other</a></p>`, index);+ expect(html).toBe(`<p><a class="reference-link" href="#root/id2">Other</a></p>`);+ expect(internalLinks).toEqual(["id2"]);+ });++ it("resolves a path-qualified target and a #heading suffix to the same note", () => {+ expect(resolveLinks(`<a class="reference-link" href="/Folder/Target">x</a>`, index).internalLinks).toEqual(["id1"]);+ expect(resolveLinks(`<a class="reference-link" href="/Folder/Target#section">x</a>`, index).internalLinks).toEqual(["id1"]);+ });++ it("turns an aliased wikilink into a plain link carrying the alias text", () => {+ const { html, internalLinks } = resolveLinks(`<a class="reference-link" href="/Other|Display Name">x</a>`, index);+ expect(html).toBe(`<a href="#root/id2">Display Name</a>`);+ expect(internalLinks).toEqual(["id2"]);+ });++ it("unwraps an unresolved wikilink to plain text (target, or the alias when present)", () => {+ expect(resolveLinks(`<p><a class="reference-link" href="/Missing">Missing</a></p>`, index).html).toBe("<p>Missing</p>");+ expect(resolveLinks(`<p><a class="reference-link" href="/Missing|Shown">x</a></p>`, index).html).toBe("<p>Shown</p>");+ });++ it("unwraps an ambiguous base-name link (a name shared by 2+ notes is never guessed)", () => {+ const { html, internalLinks } = resolveLinks(`<p><a class="reference-link" href="/Note">Note</a></p>`, index);+ expect(html).toBe("<p>Note</p>");+ expect(internalLinks).toEqual([]);+ });++ it("unwraps a wikilink whose target is empty (e.g. a bare #heading link)", () => {+ const { html, internalLinks } = resolveLinks(`<p><a class="reference-link" href="/#section">x</a></p>`, index);+ expect(html).toBe("<p></p>");+ expect(internalLinks).toEqual([]);+ });++ it("skips embeds whose src is missing or not vault-relative even when another link forces a pass", () => {+ // A resolvable wikilink makes resolveLinks parse the html; the img loop must still skip these two.+ const html = `<a class="reference-link" href="/Other">o</a><img><img src="api/attachments/z.png">`;+ const { html: out, includeLinks } = resolveLinks(html, index);+ expect(out).toBe(`<a class="reference-link" href="#root/id2">o</a><img><img src="api/attachments/z.png">`);+ expect(includeLinks).toEqual([]);+ });++ it("leaves anchors that aren't wikilink placeholders alone", () => {+ // No reference-link class, and an already-rewritten attachment href (#root/…), are both skipped.+ const html = `<a href="/Other">plain markdown link</a><a class="reference-link" href="#root/id2">attachment</a>`;+ expect(resolveLinks(html, index)).toEqual({ html, internalLinks: [], includeLinks: [] });+ });++ it("recovers gracefully from an undecodable href and treats it as unresolved", () => {+ // A malformed percent-escape makes decodeURIComponent throw; safeDecode falls back to the raw value.+ const { html, internalLinks } = resolveLinks(`<p><a class="reference-link" href="/%E0%A4">x</a></p>`, index);+ expect(html).toBe("<p>%E0%A4</p>");+ expect(internalLinks).toEqual([]);+ });++ it("converts a resolved note embed into an include-note section and records the include", () => {+ const { html, includeLinks } = resolveLinks(`<p><img src="/Other"></p>`, index);+ expect(html).toBe(`<p><section class="include-note" data-note-id="id2" data-box-size="medium"> </section></p>`);+ expect(includeLinks).toEqual(["id2"]);+ });++ it("drops an unsupported .base/.canvas embed, removing its now-empty wrapping paragraph", () => {+ expect(resolveLinks(`<p><img src="/Database.base"></p>`, index).html).toBe("");+ expect(resolveLinks(`<p><img src="/Board.canvas"></p>`, index).html).toBe("");+ });++ it("keeps the paragraph of an unsupported embed when it still holds other content", () => {+ const { html } = resolveLinks(`<p>see <img src="/Database.base"></p>`, index);+ expect(html).toBe("<p>see </p>");+ });++ it("leaves an unresolved, non-special embed in place for a later pass", () => {+ const html = `<p><img src="/Unknown.png"></p>`;+ expect(resolveLinks(html, index)).toEqual({ html, internalLinks: [], includeLinks: [] });+ });++ it("ignores an embed whose src is already an attachment URL (not vault-relative)", () => {+ const html = `<p><img src="api/attachments/x/image/y.png"></p>`;+ expect(resolveLinks(html, index)).toEqual({ html, internalLinks: [], includeLinks: [] });+ });+});