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 importer edge cases for enex and anytype
Elian Doranc41f0b65c1d7
diff --git a/packages/trilium-core/src/services/import/anytype/collection.spec.ts b/packages/trilium-core/src/services/import/anytype/collection.spec.tsindex 1734f6906c..dfdbc68a19 100644--- a/packages/trilium-core/src/services/import/anytype/collection.spec.ts+++ b/packages/trilium-core/src/services/import/anytype/collection.spec.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";-import { mapViewType, synthesizeColumns } from "./collection.js";+import { buildFileObjectMap, mapViewType, synthesizeColumns } from "./collection.js";import { isCollectionObject, isPage, parseObject } from "./importer.js";import type { AnytypeBlock, AnytypeMark, AnytypeSnapshot, RelationInfo } from "./model.js";@@ -147,6 +147,26 @@ describe("collection properties", () => {const details = { id: "obj", name: "Row", "6a3e335dcafa6953a4661c74": "https://x" };expect(parseObject(snapshot([{ id: "obj", childrenIds: [] }], details)).properties).toEqual([]);});++ it("drops a property whose value is null", () => {+ // A supported relation carrying an explicit null contributes no label.+ const details = { id: "obj", "6a3e29d5cafa6953a4661c15": null };+ expect(parseObject(snapshot([{ id: "obj", childrenIds: [] }], details), undefined, rels).properties).toEqual([]);+ });++ it("drops a date property whose value isn't a finite number", () => {+ const details = { id: "obj", "6a3e330acafa6953a4661c6b": "not-a-date" };+ expect(parseObject(snapshot([{ id: "obj", childrenIds: [] }], details), undefined, rels).properties).toEqual([]);+ });+ });++ describe("buildFileObjectMap", () => {+ it("skips a file object that has no id", () => {+ const withId = snapshot([], { id: "file-1", name: "doc", fileExt: "pdf", source: "files/doc.pdf" }, "FileObject");+ const withoutId = snapshot([], { name: "orphan" }, "FileObject");+ const map = buildFileObjectMap([withId, withoutId]);+ expect([...map.keys()]).toEqual(["file-1"]);+ });});describe("isCollectionObject", () => {diff --git a/packages/trilium-core/src/services/import/anytype/content.spec.ts b/packages/trilium-core/src/services/import/anytype/content.spec.tsindex 0be04b0cd8..f05e602dab 100644--- a/packages/trilium-core/src/services/import/anytype/content.spec.ts+++ b/packages/trilium-core/src/services/import/anytype/content.spec.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";-import { renderCodeBlock, renderInlineText, renderLatexBlock, renderTable } from "./content.js";+import { extractContent, renderCodeBlock, renderInlineText, renderLatexBlock, renderTable } from "./content.js";import { parseObject } from "./importer.js";import type { AnytypeBlock, AnytypeMark, AnytypeSnapshot, LinkResolver } from "./model.js";@@ -251,6 +251,17 @@ describe("inline files", () => {});});+describe("extractContent", () => {+ it("returns empty output when the block tree has no resolvable root", () => {+ expect(extractContent([], "missing", () => undefined)).toEqual({ html: "", linkTargetIds: [], fileTargetIds: [] });+ });++ it("ignores an inline mark of an unrenderable type, leaving the text plain", () => {+ // Not a structural mark, a known colour, or a Mention — so it contributes no formatting.+ expect(renderInlineText("x", [mark(0, 1, "Emoji")])).toBe("x");+ });+});+describe("renderInlineText", () => {it("returns escaped plain text when there are no marks", () => {expect(renderInlineText("a < b & c > d", [])).toBe("a < b & c > d");@@ -474,4 +485,15 @@ describe("tables", () => {]);expect(renderTable(byId.get("tbl") ?? { id: "x" }, byId)).toBe("");});++ it("skips a row whose block is missing from the export", () => {+ // The rows layout references "r-missing", for which no block exists — that row is dropped.+ const byId = new Map<string, AnytypeBlock>([+ ["tbl", { id: "tbl", table: {}, childrenIds: ["cols", "rows"] }],+ ["cols", { id: "cols", childrenIds: ["c1"] }],+ ["c1", { id: "c1", childrenIds: [] }],+ ["rows", { id: "rows", childrenIds: ["r-missing"] }]+ ]);+ expect(renderTable(byId.get("tbl") ?? { id: "x" }, byId)).toBe('<figure class="table"><table></table></figure>');+ });});diff --git a/packages/trilium-core/src/services/import/anytype/importer.integration.spec.ts b/packages/trilium-core/src/services/import/anytype/importer.integration.spec.tsindex 02922f186b..e77ca7ac46 100644--- a/packages/trilium-core/src/services/import/anytype/importer.integration.spec.ts+++ b/packages/trilium-core/src/services/import/anytype/importer.integration.spec.ts@@ -789,6 +789,21 @@ describe("Anytype importer — integration", () => {expect(fileNote.getOwnedLabelValue("originalFileName")).toBe("report.pdf");});+ it("skips a collection's file member whose bytes are missing from the export", async () => {+ // The collection lists a FileObject as a member and its metadata ships, but the raw bytes under files/+ // are absent — so no note can be created for it and it's left out rather than failing the import.+ const fileCid = "bafyreimissingbytes";+ const importRoot = await importAnytype({+ "objects/coll.pb.json": collectionObject("coll", "Docs", [fileCid], []),+ "filesObjects/f1.pb.json": fileObjectJson(fileCid, "report", "pdf", "application/pdf", "files\\report.pdf")+ // No files/report.pdf entry — the bytes are missing.+ });++ const collection = importRoot.getChildNotes()[0];+ expect(collection.title).toBe("Docs");+ expect(collection.getChildNotes()).toHaveLength(0);+ });+it("imports an image object that's a collection member as an image note", async () => {const imgCid = "bafyreiimagemember";const importRoot = await importAnytype({@@ -917,6 +932,49 @@ describe("Anytype importer — integration", () => {expect(content).toBe("<p>Body</p>");});+ it("strips the bare-id link of an inline non-image file whose bytes are missing, keeping its text", async () => {+ // The anytype-file placeholder can't be resolved (no metadata/bytes), so its class and bare-id href are+ // dropped, leaving the file name as plain (non-linking) text rather than a broken attachment link.+ const page = JSON.stringify({+ sbType: "Page",+ snapshot: {+ data: {+ blocks: [+ { id: "pg", childrenIds: ["header", "file"] },+ { id: "header", childrenIds: ["title"] },+ { id: "title", text: { text: "", style: "Title" } },+ { id: "file", file: { type: "PDF", name: "gone.pdf", targetObjectId: "bafyreimissingfile", state: "Done", style: "Link" } }+ ],+ details: { id: "pg", name: "Missing file", resolvedLayout: 0 }+ }+ }+ });+ const importRoot = await importAnytype({ "objects/pg.pb.json": page });++ const note = importRoot.getChildNotes().find((n) => n.title === "Missing file");+ expect(note?.getAttachmentsByRole("file")).toHaveLength(0);+ const content = decodeUtf8(note?.getContent() ?? "");+ expect(content).toBe("<p><a>gone.pdf</a></p>");+ });++ it("skips a file property whose file object's bytes are missing, leaving no attachment or link", async () => {+ // The file property references a FileObject, but its bytes are absent — so no attachment is created and+ // the body keeps no reference link to it.+ const fileKey = "6a3e3323cafa6953a4661c6f";+ const fileCid = "bafyreimissingprop";+ const importRoot = await importAnytype({+ "objects/coll.pb.json": collectionObject("coll", "Files", ["m1"], [fileKey]),+ "objects/m1.pb.json": memberObject("m1", { [fileKey]: [fileCid] }),+ "relations/file.pb.json": relationObject(fileKey, "File", 5),+ "filesObjects/f1.pb.json": fileObjectJson(fileCid, "log", "csv", "text/csv", "files\\log.csv")+ // No files/log.csv entry — the bytes are missing.+ });++ const row = importRoot.getChildNotes()[0].getChildNotes()[0];+ expect(row.getAttachmentsByRole("file")).toHaveLength(0);+ expect(decodeUtf8(row.getContent() ?? "")).not.toContain("reference-link");+ });+it("imports a collection-scoped export (no wrapper) as a named table whose columns are synthesized from members", async () => {// Exporting a single collection omits the collection object itself, so its members all carry the same// absent createdInContext — the signal to recover the collection (name from the file, columns from members).diff --git a/packages/trilium-core/src/services/import/anytype/importer.ts b/packages/trilium-core/src/services/import/anytype/importer.tsindex 93102bd368..13feab944b 100644--- a/packages/trilium-core/src/services/import/anytype/importer.ts+++ b/packages/trilium-core/src/services/import/anytype/importer.ts@@ -480,6 +480,7 @@ function applyInlineFiles(note: BNote, fileObjects: Map<string, FileObjectInfo>,if (parent?.tagName?.toLowerCase() === "figure") {parent.remove();} else {+ /* v8 ignore next -- content.ts always wraps an inline image in a <figure>, so a bare (non-figure) <img> never reaches here; kept as a defensive fallback */img.remove();}changed = true;diff --git a/packages/trilium-core/src/services/import/enex.spec.ts b/packages/trilium-core/src/services/import/enex.spec.tsindex 6e11fcf9db..1947600335 100644--- a/packages/trilium-core/src/services/import/enex.spec.ts+++ b/packages/trilium-core/src/services/import/enex.spec.ts@@ -9,6 +9,7 @@ import { getContext } from "../context.js";import sql_init from "../sql_init.js";import TaskContext from "../task_context.js";import { decodeUtf8 } from "../utils/binary.js";+import imageService from "../image.js";import enex from "./enex.js";const scriptDir = dirname(fileURLToPath(import.meta.url));@@ -216,6 +217,45 @@ describe("importEnex", () => {expect(linker.getRelations("internalLink").some(r => r.value === padded.noteId)).toBe(true);});+ it("imports note metadata (source-url, tags) as labels and appends an unreferenced image resource", async () => {+ const { importedNote } = await testImport("Note metadata.enex");++ const note = importedNote.getChildNotes().find(n => n.title === "Metadata Note");+ if (!note) {+ throw new Error("'Metadata Note' note was not imported");+ }++ // A note-attributes source-url becomes a "pageUrl" label; each tag becomes an empty label.+ expect(note.getLabelValue("pageUrl")).toBe("https://triliumnotes.org/page");+ expect(note.getOwnedAttributes("label").map(a => a.name)).toEqual(expect.arrayContaining(["pageUrl", "important", "archive"]));++ // The image resource isn't referenced by an <en-media> in the body, so it's appended as an attachment+ // rather than dropped; the empty (data-less) resource is skipped without failing the import.+ const content = decodeUtf8(note.getContent());+ expect(content).toContain("<img");+ // The data-less "empty.bin" resource contributes no attachment.+ expect(note.getAttachmentsByRole("file").some(a => a.title === "empty.bin")).toBe(false);+ });++ it("falls back to a file attachment when saving an image resource throws", async () => {+ // If image processing fails (e.g. a corrupt image), the resource is preserved as a plain file+ // attachment rather than being lost.+ const saveImage = vi.spyOn(imageService, "saveImageToAttachment").mockImplementation(() => {+ throw new Error("simulated image processing failure");+ });+ try {+ const { importedNote } = await testImport("Note metadata.enex");+ const note = importedNote.getChildNotes().find(n => n.title === "Metadata Note");+ if (!note) {+ throw new Error("'Metadata Note' note was not imported");+ }+ // The image couldn't be saved as an image, so it lands as a role:"file" attachment instead.+ expect(note.getAttachmentsByRole("file").map(a => a.title)).toContain("orphan.png");+ } finally {+ saveImage.mockRestore();+ }+ });+it("converts legacy <en-todo> checkboxes into a real todo-list, not literal ballot boxes", async () => {const { importedNote } = await testImport("Legacy checkboxes.enex");diff --git a/packages/trilium-core/src/services/import/enex_converter.spec.ts b/packages/trilium-core/src/services/import/enex_converter.spec.tsindex 2f19a12a70..8577aec173 100644--- a/packages/trilium-core/src/services/import/enex_converter.spec.ts+++ b/packages/trilium-core/src/services/import/enex_converter.spec.ts@@ -238,6 +238,44 @@ describe("convertEnexContent — composition and inertness", () => {});});+describe("convertEnexContent — edge cases", () => {+ it("injects a custom callout emoji as leading text when the body has no block child to merge into", () => {+ // A callout whose first child isn't a <div>/<p> (here bare text) takes the leading-text branch.+ const input = `<div style="--en-callout:true; --en-emoji:🤖;">Plain text</div>`;+ expect(convertEnexContent(input)).toBe(`<aside class="admonition note">🤖 Plain text</aside>`);+ });++ it("keeps a toggle's bare-text content (a non-element child) as the collapsible body", () => {+ const input = `<div style="--en-toggle:true; --en-isCollapsed:true;"><div style="--en-toggleSummary:true;">S</div><div style="--en-toggleContent:true;">Bare text</div></div>`;+ expect(convertEnexContent(input)).toBe(`<details class="trilium-collapsible"><summary>S</summary>Bare text</details>`);+ });++ it("ignores stray text nodes between checkbox items when building the todo-list", () => {+ const input = `<ul style="--en-todo:true;"><li style="--en-checked:false;"><div>A</div></li> <li style="--en-checked:false;"><div>B</div></li></ul>`;+ expect(convertEnexContent(input)).toBe(todoList(todoItem("A"), todoItem("B")));+ });++ it("nests a leading sub-list under an empty item when no checkbox item precedes it", () => {+ const input = `<ul style="--en-todo:true;"><ul style="--en-todo:true;"><li style="--en-checked:false;"><div>Sub</div></li></ul></ul>`;+ expect(convertEnexContent(input)).toBe(todoList(todoItem("", { nested: todoList(todoItem("Sub")) })));+ });++ it("uses the raw item content as the description when a checkbox item has no single <div> wrapper", () => {+ const input = `<ul style="--en-todo:true;"><li style="--en-checked:true;">Direct text</li></ul>`;+ expect(convertEnexContent(input)).toBe(todoList(todoItem("Direct text", { checked: true })));+ });++ it("reads a code block's text directly when its lines aren't wrapped in <div>s", () => {+ const input = `<div style="--en-codeblock:true; --en-syntaxLanguage:c;">inline code</div>`;+ expect(convertEnexContent(input)).toBe(`<pre><code class="language-text-x-csrc">inline code</code></pre>`);+ });++ it("maps a code block whose syntax language is 'mermaid' to a language-mermaid block", () => {+ const input = `<div style="--en-codeblock:true; --en-syntaxLanguage:mermaid;"><div>graph TD</div></div>`;+ expect(convertEnexContent(input)).toBe(`<pre><code class="language-mermaid">graph TD</code></pre>`);+ });+});+describe("rewriteEvernoteLinks — internal note references", () => {// Evernote renders an inline-richlink with the target note's title as its text, so the target is// resolved by that text. The map mirrors a title -> imported noteId lookup built during import.diff --git a/packages/trilium-core/src/services/import/samples/Note metadata.enex b/packages/trilium-core/src/services/import/samples/Note metadata.enexnew file mode 100644index 0000000000..d8b6b51bdf--- /dev/null+++ b/packages/trilium-core/src/services/import/samples/Note metadata.enex@@ -0,0 +1,7 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE en-export SYSTEM "http://xml.evernote.com/pub/evernote-export2.dtd">+<en-export export-date="20260417T081355Z" application="Evernote/Windows" version="6.x">+<note><title>Metadata Note</title><content><![CDATA[<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">+<en-note><div>Body text</div></en-note>]]></content><created>20260417T081156Z</created><updated>20260417T081307Z</updated><note-attributes><source>desktop.win</source><source-url>https://triliumnotes.org/page</source-url></note-attributes><tag>important</tag><tag>archive</tag><resource><data encoding="base64">iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==</data><mime>image/png</mime><resource-attributes><file-name>orphan.png</file-name></resource-attributes></resource><resource><mime>application/octet-stream</mime><resource-attributes><file-name>empty.bin</file-name></resource-attributes></resource></note>+</en-export>