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): take the core import service to 100% line and function coverage
Elian Doran08690d2916eb
diff --git a/packages/trilium-core/src/services/import/anytype/collection.spec.ts b/packages/trilium-core/src/services/import/anytype/collection.spec.tsindex dfdbc68a19..cc2a35529d 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 { buildFileObjectMap, mapViewType, synthesizeColumns } from "./collection.js";+import { buildFileObjectMap, buildOptionMap, buildRelationMap, mapViewType, synthesizeColumns } from "./collection.js";import { isCollectionObject, isPage, parseObject } from "./importer.js";import type { AnytypeBlock, AnytypeMark, AnytypeSnapshot, RelationInfo } from "./model.js";@@ -160,13 +160,66 @@ describe("collection properties", () => {});});- describe("buildFileObjectMap", () => {+ describe("parseObject — loosely-typed property values", () => {+ it("accepts a string-encoded checkbox / number and a non-string text value", () => {+ const details = {+ id: "obj",+ "6a3e3354cafa6953a4661c73": "false", // Checkbox stored as a string+ "6a3e29e1cafa6953a4661c16": "17", // Number stored as a string+ "6a3e29d5cafa6953a4661c15": 12 // Text stored as a number+ };+ expect(parseObject(snapshot([{ id: "obj", childrenIds: [] }], details), undefined, rels).properties).toEqual([+ { name: "checkbox", value: "false" },+ { name: "numberProp", value: "17" },+ { name: "textProperty", value: "12" }+ ]);+ });++ it("drops a checkbox that isn't boolean-ish and a number that isn't numeric", () => {+ const parse = (details: Record<string, unknown>) =>+ parseObject(snapshot([{ id: "obj", childrenIds: [] }], { id: "obj", ...details }), undefined, rels).properties;+ expect(parse({ "6a3e3354cafa6953a4661c73": "maybe" })).toEqual([]);+ expect(parse({ "6a3e29e1cafa6953a4661c16": "abc" })).toEqual([]);+ });++ it("drops select / file values that aren't a list of ids", () => {+ const parse = (details: Record<string, unknown>) =>+ parseObject(snapshot([{ id: "obj", childrenIds: [] }], { id: "obj", ...details }), undefined, rels, options);+ // A select's value is always a list of option ids, a file's a list of file-object ids; anything+ // else (a bare string, a non-string entry) carries no id to resolve.+ expect(parse({ "6a3e29e8cafa6953a4661c17": "opt-first-cap", "6a3e2a01cafa6953a4661c1c": [42] }).properties).toEqual([]);+ expect(parse({ "6a3e3323cafa6953a4661c6f": "file-cid" }).fileRefs).toEqual([]);+ expect(parse({ "6a3e3323cafa6953a4661c6f": [7] }).fileRefs).toEqual([]);+ });+ });++ describe("buildRelationMap / buildOptionMap / buildFileObjectMap", () => {+ it("skips a snapshot with no details, defaulting a relation's missing name and format", () => {+ const relations = buildRelationMap([snapshot([], { relationKey: "k1" }, "STRelation"), { sbType: "STRelation" }]);+ expect([...relations]).toEqual([["k1", { name: "", format: -1, includeTime: false }]]);++ const optionMap = buildOptionMap([snapshot([], { id: "opt-1" }, "STRelationOption"), { sbType: "STRelationOption" }]);+ expect([...optionMap]).toEqual([["opt-1", ""]]);+ });+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"]);});++ it("names a source-less file object from its own name and extension, keeping Anytype's MIME as a fallback", () => {+ const map = buildFileObjectMap([+ snapshot([], { id: "f1", name: "Report", fileExt: "pdf" }, "FileObject"),+ snapshot([], { id: "f2" }, "FileObject"),+ snapshot([], { id: "f3", name: "Raw", fileMimeType: "application/x-thing" }, "FileObject")+ ]);+ expect(map.get("f1")).toEqual({ title: "Report.pdf", mime: "application/pdf", source: "" });+ // Nothing to name it after and no recognizable extension: a generic title and an unknown MIME.+ expect(map.get("f2")).toEqual({ title: "file", mime: "", source: "" });+ expect(map.get("f3")).toEqual({ title: "Raw", mime: "application/x-thing", source: "" });+ });});describe("isCollectionObject", () => {@@ -179,9 +232,10 @@ describe("collection properties", () => {expect(isPage(collectionDoc(14, true))).toBe(false);});- it("rejects a query set (dataview without isCollection) and a plain page", () => {+ it("rejects a query set (dataview without isCollection), a plain page and a block-less snapshot", () => {expect(isCollectionObject(collectionDoc(3, false))).toBe(false);expect(isCollectionObject(page("Plain", [textBlock("b1", "body")]))).toBe(false);+ expect(isCollectionObject({ sbType: "Page" })).toBe(false);});});@@ -258,6 +312,22 @@ describe("collection properties", () => {]);});+ it("parses a bare collection: no views, no relations, no links", () => {+ const dv: AnytypeBlock = { id: "dv", childrenIds: [], dataview: { isCollection: true } };+ const doc = snapshot([{ id: "obj", childrenIds: ["dv"] }, dv], { id: "obj", name: "C" });+ expect(parseObject(doc, undefined, rels).collection).toEqual({ viewType: "table", memberIds: [], columns: [] });+ });++ it("drops a visible column whose relation isn't part of the export", () => {+ const dv: AnytypeBlock = {+ id: "dv",+ childrenIds: [],+ dataview: { isCollection: true, views: [{ relations: [{ key: "6a3e0000cafa6953a4661cff", isVisible: true }] }] }+ };+ const doc = snapshot([{ id: "obj", childrenIds: ["dv"] }, dv], { id: "obj", name: "C", links: [] });+ expect(parseObject(doc, undefined, rels).collection?.columns).toEqual([]);+ });+it("leaves collection undefined for a regular (non-dataview) page", () => {expect(parseObject(page("Plain", [textBlock("b1", "body")]), undefined, rels).collection).toBeUndefined();});diff --git a/packages/trilium-core/src/services/import/anytype/collection.ts b/packages/trilium-core/src/services/import/anytype/collection.tsindex 56306c12d8..fdbb1e31e0 100644--- a/packages/trilium-core/src/services/import/anytype/collection.ts+++ b/packages/trilium-core/src/services/import/anytype/collection.ts@@ -350,6 +350,7 @@ export function applyFiles(note: BNote, page: ParsedObject, fileObjects: Map<strcontinue;}const attachment = saveFileAttachment(note, info.title, bytes, info.mime);+ /* v8 ignore next -- saveAttachment always returns the id of the attachment it just created, so this guard is never false in practice */if (attachment.attachmentId) {fileLinks.push(`<p>${attachmentReferenceLink(note.noteId, attachment.attachmentId, info.title)}</p>`);}diff --git a/packages/trilium-core/src/services/import/anytype/content.spec.ts b/packages/trilium-core/src/services/import/anytype/content.spec.tsindex d4f5df82d9..cc2f38c04a 100644--- a/packages/trilium-core/src/services/import/anytype/content.spec.ts+++ b/packages/trilium-core/src/services/import/anytype/content.spec.ts@@ -320,6 +320,57 @@ describe("extractContent", () => {});});+describe("sparse block shapes", () => {+ // Every field of an exported block is optional, so the renderer has to cope with blocks carrying+ // nothing beyond their id and style.+ const noResolve: LinkResolver = () => undefined;++ it("falls back to the first block when no root id is given, and tolerates a childless root", () => {+ expect(extractContent([{ id: "obj" }], "", noResolve)).toEqual({ html: "", linkTargetIds: [], fileTargetIds: [] });+ });++ it("renders a list item carrying no text, marks or children", () => {+ expect(extractContent([{ id: "obj", childrenIds: ["m1"] }, { id: "m1", text: { style: "Marked" } }], "obj", noResolve).html)+ .toBe("<ul><li></li></ul>");+ });++ it("ends a list run at an id that repeats or is missing from the export", () => {+ const blocks: AnytypeBlock[] = [+ { id: "obj", childrenIds: ["m1", "m1", "gone"] },+ { id: "m1", text: { text: "One", style: "Marked" }, childrenIds: [] }+ ];+ expect(extractContent(blocks, "obj", noResolve).html).toBe("<ul><li>One</li></ul>");+ });++ it("drops a link block with no target and a latex block with no text", () => {+ const blocks: AnytypeBlock[] = [+ { id: "obj", childrenIds: ["l1", "x1"] },+ { id: "l1", link: {} },+ { id: "x1", latex: { processor: "Mermaid" } }+ ];+ expect(extractContent(blocks, "obj", noResolve).html).toBe("");+ });++ it("renders empty toggle / quote / callout blocks with neither body text nor children", () => {+ const blocks: AnytypeBlock[] = [+ { id: "obj", childrenIds: ["t1", "q1", "c1"] },+ { id: "t1", text: { text: "", style: "Toggle" } },+ { id: "q1", text: { text: " ", style: "Quote" } },+ { id: "c1", text: { text: "", style: "Callout" } }+ ];+ expect(extractContent(blocks, "obj", noResolve).html).toBe(+ '<details class="trilium-collapsible"><summary></summary></details>'+ + "<blockquote></blockquote>"+ + '<aside class="admonition tip"></aside>'+ );+ });++ it("ignores a mark with no range, on its own and around an inline formula", () => {+ expect(renderInlineText("x", [{ type: "Bold" }])).toBe("x");+ expect(renderInlineText("a $x$ b", [{ type: "Bold" }])).toBe('a <span class="math-tex">\\( x \\)</span> b');+ });+});+describe("renderInlineText", () => {it("returns escaped plain text when there are no marks", () => {expect(renderInlineText("a < b & c > d", [])).toBe("a < b & c > d");@@ -578,6 +629,27 @@ describe("tables", () => {expect(renderTable(byId.get("tbl") ?? { id: "x" }, byId)).toBe("");});+ it("returns empty for a table block with no children, or whose layout blocks are missing", () => {+ expect(renderTable({ id: "t" }, new Map())).toBe("");+ const byId = new Map<string, AnytypeBlock>([["t", { id: "t", table: {}, childrenIds: ["cols", "rows"] }]]);+ expect(renderTable(byId.get("t") ?? { id: "t" }, byId)).toBe("");+ });++ it("ignores a child that isn't one of the row's cells, and a cell block carrying no text", () => {+ const byId = new Map<string, AnytypeBlock>([+ ["t", { id: "t", table: {}, childrenIds: ["cols", "rows"] }],+ ["cols", { id: "cols", childrenIds: ["c1"] }],+ ["rows", { id: "rows", childrenIds: ["r1", "r2"] }],+ // "stray" isn't addressed as `${rowId}-${columnId}`, so it's no cell of r1; r2 lists no cells at all.+ ["r1", { id: "r1", childrenIds: ["stray", "r1-c1"] }],+ ["stray", { id: "stray", text: { text: "off-grid", marks: { marks: [] } } }],+ ["r1-c1", { id: "r1-c1" }],+ ["r2", { id: "r2" }]+ ]);+ expect(renderTable(byId.get("t") ?? { id: "t" }, byId))+ .toBe('<figure class="table"><table><tbody><tr><td></td></tr><tr><td></td></tr></tbody></table></figure>');+ });+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>([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 4785d3527e..dd5a619aa5 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@@ -116,6 +116,11 @@ function memberObject(id: string, props: Record<string, unknown>): string {});}+/** A bare page object carrying only the given timestamp details (Unix seconds). */+function datedObject(id: string, name: string, dates: { createdDate?: number; lastModifiedDate?: number }): string {+ return JSON.stringify({ sbType: "Page", snapshot: { data: { blocks: [{ id, childrenIds: [] }], details: { id, name, layout: 0, ...dates } } } });+}+describe("Anytype importer — integration", () => {it("imports each page as a flat child of an 'Anytype import' root, with its text content", async () => {const importRoot = await importAnytype({@@ -173,6 +178,39 @@ describe("Anytype importer — integration", () => {);});+ it("leaves a card with no favicon/preview untouched, and falls back to a generic MIME for an unrecognized one", async () => {+ const bookmarkPage = (bookmark: Record<string, unknown>) => JSON.stringify({+ sbType: "Page",+ snapshot: {+ data: {+ blocks: [+ { id: "page1", childrenIds: ["header", "bm"] },+ { id: "header", childrenIds: ["title"] },+ { id: "title", text: { text: "", style: "Title" } },+ { id: "bm", bookmark }+ ],+ details: { id: "page1", name: "Links", resolvedLayout: 0 }+ }+ }+ });++ // No favicon/preview ids at all: there's nothing to resolve, so the body is left exactly as rendered.+ const plain = await importAnytype({ "objects/page1.pb.json": bookmarkPage({ url: "https://example.com/", title: "Example" }) });+ expect(decodeUtf8(plain.getChildNotes()[0]?.getContent() ?? "")).toBe(+ '<section class="link-embed" data-url="https://example.com/" data-embed-type="opengraph" data-title="Example"></section>'+ );++ // A favicon whose file carries neither a known extension nor an exported MIME falls back to octet-stream.+ const bytes = Buffer.from([0x09]);+ const odd = await importAnytype({+ "objects/page1.pb.json": bookmarkPage({ url: "https://example.com/", faviconHash: "fav-cid" }),+ "filesObjects/fav.pb.json": fileObjectJson("fav-cid", "icon", "", "", "files\\icon.weirdext"),+ "files/icon.weirdext": bytes+ });+ expect(decodeUtf8(odd.getChildNotes()[0]?.getContent() ?? ""))+ .toContain(`data-favicon="data:application/octet-stream;base64,${bytes.toString("base64")}"`);+ });+it("drops a bookmark's favicon placeholder when the export has no bytes for it", async () => {// The card references a favicon file id, but no filesObjects/files entry backs it — the importer drops// the data-favicon attribute rather than leaving a bare id that would render as a broken image.@@ -1025,14 +1063,14 @@ describe("Anytype importer — integration", () => {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.+ it("skips a file property whose file object's metadata or bytes are missing, leaving no attachment or link", async () => {+ // One value references a FileObject whose bytes are absent, the other a file id the export carries no+ // metadata for — neither yields an attachment, and the body keeps no reference link to them.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] }),+ "objects/m1.pb.json": memberObject("m1", { [fileKey]: [fileCid, "bafyreiunknownfile"] }),"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.@@ -1043,6 +1081,65 @@ describe("Anytype importer — integration", () => {expect(decodeUtf8(row.getContent() ?? "")).not.toContain("reference-link");});+ it("falls back between created and modified when a page exports only one of them", async () => {+ const importRoot = await importAnytype({+ "objects/a.pb.json": datedObject("a", "Created only", { createdDate: 1735632037 }),+ "objects/b.pb.json": datedObject("b", "Modified only", { lastModifiedDate: 1735632353 })+ });++ const createdOnly = importRoot.getChildNotes().find((note) => note.title === "Created only");+ expect(createdOnly?.utcDateCreated).toBe("2024-12-31 08:00:37.000Z");+ expect(createdOnly?.utcDateModified).toBe("2024-12-31 08:00:37.000Z");++ // With no exported creation time the note keeps its import-time one; only modified is restored.+ const modifiedOnly = importRoot.getChildNotes().find((note) => note.title === "Modified only");+ expect(modifiedOnly?.utcDateModified).toBe("2024-12-31 08:05:53.000Z");+ expect(modifiedOnly?.utcDateCreated).not.toBe("2024-12-31 08:05:53.000Z");+ });++ it("ignores a collection member the export doesn't contain", async () => {+ // Both collections list the same absent member, so the second one reaches the membership (cloning)+ // pass for it — with no note to clone.+ const importRoot = await importAnytype({+ "objects/c1.pb.json": collectionObject("c1", "First", ["ghost"], []),+ "objects/c2.pb.json": collectionObject("c2", "Second", ["ghost"], [])+ });++ expect(importRoot.getChildNotes().map((note) => note.getChildNotes().length)).toEqual([0, 0]);+ });++ it("attaches a file property carried by the collection itself, the link becoming its whole body", async () => {+ const fileKey = "6a3e3323cafa6953a4661c6f";+ const fileCid = "bafyreicollfile";+ const collection = JSON.stringify({+ sbType: "Page",+ snapshot: {+ data: {+ blocks: [+ { id: "coll", childrenIds: ["header", "dataview"] },+ { id: "header", childrenIds: ["title"] },+ { id: "title", text: { text: "", style: "Title" } },+ { id: "dataview", dataview: { isCollection: true, views: [{ relations: [] }] } }+ ],+ details: { id: "coll", name: "Files", resolvedLayout: 14, links: [], [fileKey]: [fileCid] }+ }+ }+ });+ const importRoot = await importAnytype({+ "objects/coll.pb.json": collection,+ "relations/file.pb.json": relationObject(fileKey, "File", 5),+ "filesObjects/f1.pb.json": fileObjectJson(fileCid, "log", "csv", "text/csv", "files\\log.csv"),+ "files/log.csv": "a,b\n1,2"+ });++ const note = importRoot.getChildNotes()[0];+ const attachments = note.getAttachmentsByRole("file");+ expect(attachments.map((attachment) => attachment.title)).toEqual(["log.csv"]);+ // A collection note has no body of its own, so the reference link is all of its content.+ expect(decodeUtf8(note.getContent()))+ .toBe(`<p><a class="reference-link" href="#root/${note.noteId}?viewMode=attachments&attachmentId=${attachments[0]?.attachmentId}">log.csv</a></p>`);+ });+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.spec.ts b/packages/trilium-core/src/services/import/anytype/importer.spec.tsindex 8d7f5cf285..e51c711fdb 100644--- a/packages/trilium-core/src/services/import/anytype/importer.spec.ts+++ b/packages/trilium-core/src/services/import/anytype/importer.spec.ts@@ -109,6 +109,21 @@ describe("parseObject", () => {expect(parseObject(page("", [textBlock("b1", "body")])).title).toBe("Untitled");expect(parseObject(page(" ", [])).title).toBe("Untitled");});++ it("yields an empty page for a snapshot carrying no data at all", () => {+ expect(parseObject({})).toEqual({+ id: "",+ title: "Untitled",+ content: "",+ linkTargetIds: [],+ dateCreated: undefined,+ dateModified: undefined,+ properties: [],+ fileRefs: [],+ inlineFileIds: [],+ collection: undefined+ });+ });});describe("dates", () => {@@ -162,5 +177,7 @@ describe("single-collection export", () => {it("derives the root title from the export file name, dropping the extension", () => {expect(collectionTitleFromFileName("My custom collection.zip")).toBe("My custom collection");expect(collectionTitleFromFileName("noext")).toBe("noext");+ // Nothing but an extension: keep the name rather than titling the root with an empty string.+ expect(collectionTitleFromFileName(".zip")).toBe(".zip");});});diff --git a/packages/trilium-core/src/services/import/collection_utils.spec.ts b/packages/trilium-core/src/services/import/collection_utils.spec.tsindex 081e9a1a3f..e32eaea03a 100644--- a/packages/trilium-core/src/services/import/collection_utils.spec.ts+++ b/packages/trilium-core/src/services/import/collection_utils.spec.ts@@ -1,6 +1,7 @@-import { describe, expect, it } from "vitest";+import { describe, expect, it, vi } from "vitest";-import { buildPromotedDefinition, toAttributeName } from "./collection_utils.js";+import type BNote from "../../becca/entities/bnote.js";+import { buildPromotedDefinition, saveFileAttachment, toAttributeName } from "./collection_utils.js";describe("toAttributeName", () => {it("camelCases a multi-word name, lower-casing the first word", () => {@@ -67,3 +68,23 @@ describe("buildPromotedDefinition", () => {expect(buildPromotedDefinition({ alias: "Related", multiplicity: "multi" })).toBe("promoted,multi,alias=Related");});});++describe("saveFileAttachment", () => {+ it("prefers the given MIME, else derives it from the title, else falls back to octet-stream", () => {+ // Only the attachment payload is under test here; persisting it is covered by the importer specs.+ const saveAttachment = vi.fn();+ const note = { saveAttachment } as unknown as BNote;+ const content = new Uint8Array([1, 2, 3]);++ saveFileAttachment(note, "notes.txt", content, "application/x-custom");+ saveFileAttachment(note, "script.py", content);+ saveFileAttachment(note, "blob.unknownext", content);++ expect(saveAttachment.mock.calls.map(([attachment]) => attachment.mime)).toEqual([+ "application/x-custom",+ "text/x-python",+ "application/octet-stream"+ ]);+ expect(saveAttachment.mock.calls[0][0]).toMatchObject({ role: "file", title: "notes.txt", content });+ });+});diff --git a/packages/trilium-core/src/services/import/dispatch.spec.ts b/packages/trilium-core/src/services/import/dispatch.spec.tsindex 4208afb0eb..5896b82795 100644--- a/packages/trilium-core/src/services/import/dispatch.spec.ts+++ b/packages/trilium-core/src/services/import/dispatch.spec.ts@@ -88,6 +88,19 @@ describe("importFile (dispatch)", () => {expect(stubbed.importObsidian).toHaveBeenCalledWith(taskContext, { path: "/tmp/obs.zip" }, parentNote, "MyVault.zip");});+ it("falls back to the raw bytes for the other tagged providers too", async () => {+ const buffer = new Uint8Array([5, 5, 5]);++ await importFile(taskContext, makeFile({ originalname: "keep.zip", buffer, path: undefined }), parentNote, makeOptions(), "keep");+ expect(stubbed.importKeep).toHaveBeenCalledWith(taskContext, buffer, parentNote);++ await importFile(taskContext, makeFile({ originalname: "any.zip", buffer, path: undefined }), parentNote, makeOptions(), "anytype");+ expect(stubbed.importAnytype).toHaveBeenCalledWith(taskContext, buffer, parentNote, "any.zip");++ await importFile(taskContext, makeFile({ originalname: "obs.zip", buffer, path: undefined }), parentNote, makeOptions(), "obsidian");+ expect(stubbed.importObsidian).toHaveBeenCalledWith(taskContext, buffer, parentNote, "obs.zip");+ });+it("ignores the format tag and falls through to single import when the upload is a bare string body", async () => {// No path and a string buffer means there are no real bytes to hand a zip-reading importer, so// the provider guards short-circuit and the file is imported as a single note.diff --git a/packages/trilium-core/src/services/import/enex.spec.ts b/packages/trilium-core/src/services/import/enex.spec.tsindex 1947600335..6631f80462 100644--- a/packages/trilium-core/src/services/import/enex.spec.ts+++ b/packages/trilium-core/src/services/import/enex.spec.ts@@ -6,38 +6,39 @@ import { beforeAll, describe, expect, it, vi } from "vitest";import becca from "../../becca/becca.js";import type BNote from "../../becca/entities/bnote.js";import { getContext } from "../context.js";+import { getLog } from "../log.js";+import noteService from "../notes.js";+import protectedSessionService from "../protected_session.js";import sql_init from "../sql_init.js";import TaskContext from "../task_context.js";-import { decodeUtf8 } from "../utils/binary.js";+import { decodeUtf8, encodeUtf8 } from "../utils/binary.js";import imageService from "../image.js";import enex from "./enex.js";const scriptDir = dirname(fileURLToPath(import.meta.url));-async function testImport(fileName: string) {- const sample = fs.readFileSync(path.join(scriptDir, "samples", fileName));+interface ImportOverrides {+ /** Upload name, when it should differ from the sample's file name (e.g. a non-`.enex` extension). */+ originalname?: string;+ /** Raw body, when the sample shouldn't be read from disk (e.g. to exercise the string-body path). */+ buffer?: string | Uint8Array;+ /** Import target, defaulting to `root`. */+ parentNote?: BNote;+}++async function testImport(fileName: string, { originalname = fileName, buffer, parentNote }: ImportOverrides = {}) {const taskContext = TaskContext.getInstance("import-enex", "importNotes", {});+ const rootNote = parentNote ?? becca.getNoteOrThrow("root");- return new Promise<{ importedNote: BNote; rootNote: BNote; taskContext: TaskContext<"importNotes"> }>((resolve, reject) => {- getContext().init(async () => {- const rootNote = becca.getNote("root");- if (!rootNote) {- expect(rootNote).toBeTruthy();- return;- }+ const importedNote = await getContext().init(() =>+ enex.importEnex(taskContext, {+ originalname,+ mimetype: "application/enex+xml",+ buffer: buffer ?? fs.readFileSync(path.join(scriptDir, "samples", fileName))+ }, rootNote)+ );- const importedNote = await enex.importEnex(taskContext, {- originalname: fileName,- mimetype: "application/enex+xml",- buffer: sample- }, rootNote as BNote);- resolve({- importedNote,- rootNote,- taskContext- });- });- });+ return { importedNote, rootNote, taskContext };}describe("importEnex", () => {@@ -46,6 +47,21 @@ describe("importEnex", () => {await sql_init.dbReady;});+ // Must stay the FIRST import in this file: the parser's note accumulator is module state, so it is only+ // empty (the state a stray pre-<note> element hits) before the first note of the process is parsed.+ it("ignores note-attributes, resources and tasks that appear before the first note", async () => {+ const { importedNote } = await testImport("Stray elements.enex");++ // The stray elements belong to no note, so they are dropped and the following note imports normally.+ const note = importedNote.getChildNotes().find(n => n.title === "After strays");+ if (!note) {+ throw new Error("'After strays' note was not imported");+ }+ expect(note.getOwnedAttributes()).toHaveLength(0);+ expect(note.getAttachments()).toHaveLength(0);+ expect(decodeUtf8(note.getContent())).toContain("Body");+ });+it("imports non-image resources as attachments instead of child notes", async () => {const { importedNote } = await testImport("File with attachments.enex");@@ -276,4 +292,82 @@ describe("importEnex", () => {// The checked item ("Investigate bug") carries the checked state.expect(content).toContain(`checked="checked"`);});++ it("imports a note without an <en-note> wrapper, a creation date or a resource mime", async () => {+ const { importedNote } = await testImport("Bare note.enex");++ const note = importedNote.getChildNotes().find(n => n.title === "Bare");+ if (!note) {+ throw new Error("'Bare' note was not imported");+ }++ // The body is taken as-is when the ENML wrapper tags are missing.+ expect(decodeUtf8(note.getContent())).toContain("No en-note wrapper");++ // A resource without a <mime> falls back to a binary attachment, and without a <file-name> it keeps+ // the generic "resource" title.+ expect(note.getAttachmentsByRole("file").map(a => ({ title: a.title, mime: a.mime }))).toEqual([+ { title: "resource", mime: "application/octet-stream" }+ ]);++ // With no <created>/<updated> the note keeps the date it was created with, for both timestamps.+ expect(note.utcDateModified).toBe(note.utcDateCreated);+ });++ it("keeps a non-.enex upload name as the root title and imports an export with no notes", async () => {+ // The body is handed over as a string (the browser/WASM upload path) rather than as bytes.+ const buffer = fs.readFileSync(path.join(scriptDir, "samples", "No notes.enex")).toString();+ const setTotalCount = vi.spyOn(TaskContext.prototype, "setTotalCount");+ try {+ const { importedNote } = await testImport("No notes.enex", { originalname: "Evernote export.xml", buffer });++ // Only a ".enex" suffix is stripped from the root title.+ expect(importedNote.title).toBe("Evernote export.xml");+ expect(importedNote.getChildNotes()).toHaveLength(0);+ // Without notes there is no denominator to report, so no progress total is set.+ expect(setTotalCount).not.toHaveBeenCalled();+ } finally {+ setTotalCount.mockRestore();+ }+ });++ it("rejects a note that carries no title", async () => {+ await expect(testImport("Missing title.enex")).rejects.toThrow("Missing title or content for note.");+ });++ it("logs a malformed XML fragment and resumes parsing the remaining notes", async () => {+ const logError = vi.spyOn(getLog(), "error");+ try {+ const { importedNote } = await testImport("Broken markup.enex");++ expect(logError).toHaveBeenCalled();+ // The parser is resumed after the error, so the well-formed note still imports.+ expect(importedNote.getChildNotes().map(n => n.title)).toContain("Recovered");+ } finally {+ logError.mockRestore();+ }+ });++ it("marks the imported notes protected when the parent is protected and a session is available", async () => {+ // Protection propagates only via `parentNote.isProtected && isProtectedSessionAvailable()`, so both+ // a protected target and a data key are needed.+ protectedSessionService.setDataKey(encodeUtf8("0123456789abcdef")); // exactly 16 bytes+ try {+ const parentNote = await getContext().init(async () => noteService.createNewNote({+ parentNoteId: "root",+ title: "protected enex target",+ content: "",+ type: "text",+ mime: "text/html",+ isProtected: true+ }).note);++ const { importedNote } = await testImport("Legacy checkboxes.enex", { parentNote });++ expect(importedNote.isProtected).toBe(true);+ expect(importedNote.getChildNotes().every(n => n.isProtected)).toBe(true);+ } finally {+ protectedSessionService.resetDataKey();+ }+ });}, 60_000);diff --git a/packages/trilium-core/src/services/import/enex.ts b/packages/trilium-core/src/services/import/enex.tsindex 004b368fec..e7f7f9d0eb 100644--- a/packages/trilium-core/src/services/import/enex.ts+++ b/packages/trilium-core/src/services/import/enex.ts@@ -164,6 +164,7 @@ async function importEnex(taskContext: TaskContext<"importNotes">, file: File, plabelName = "pageUrl";}+ /* v8 ignore next -- a text event under note-attributes always has a current tag, so the "" fallback is unreachable */labelName = utils.sanitizeAttributeName(labelName || "");if (note.attributes) {@@ -285,6 +286,7 @@ async function importEnex(taskContext: TaskContext<"importNotes">, file: File, pisProtected: parentNote.isProtected && protectedSessionService.isProtectedSessionAvailable()}).note;+ /* v8 ignore next -- the note object is created with an attributes array on <note>, so the [] fallback is unreachable */for (const attr of attributes || []) {noteEntity.addAttribute(attr.type, attr.name, attr.value);}@@ -295,11 +297,13 @@ async function importEnex(taskContext: TaskContext<"importNotes">, file: File, ptaskContext.increaseProgressCount();+ /* v8 ignore next -- the note object is created with a resources array on <note>, so the [] fallback is unreachable */for (const resource of resources || []) {if (!resource.content) {continue;}+ /* v8 ignore next -- the parser only ever accumulates a resource's data as a base64 string */if (typeof resource.content === "string") {resource.content = decodeBase64(resource.content);}@@ -307,6 +311,7 @@ async function importEnex(taskContext: TaskContext<"importNotes">, file: File, pconst hash = md5(resource.content);// skip all checked/unchecked checkboxes from OneNote+ /* v8 ignore start -- hitting this needs the byte-exact OneNote checkbox images these md5 hashes were taken from */if (["74de5d3d1286f01bac98d32a09f601d9",@@ -319,6 +324,7 @@ async function importEnex(taskContext: TaskContext<"importNotes">, file: File, p) {continue;}+ /* v8 ignore stop */const mediaRegex = new RegExp(`<en-media [^>]*hash="${hash}"[^>]*>`, "g");@@ -327,18 +333,22 @@ async function importEnex(taskContext: TaskContext<"importNotes">, file: File, pconst createFileAttachment = () => {const attachment = noteEntity.saveAttachment({role: "file",+ /* v8 ignore next -- the mime is defaulted just above, so this fallback is unreachable */mime: resource.mime || "application/octet-stream",title: resource.title,+ /* v8 ignore next -- a content-less resource is skipped above, so this fallback is unreachable */content: resource.content ?? ""});const attachmentLink = `<a class="reference-link" href="#root/${noteEntity.noteId}?viewMode=attachments&attachmentId=${attachment.attachmentId}">${escapeHtml(resource.title)}</a>`;+ /* v8 ignore next -- saveNote rejects an empty content above, so the "" fallback is unreachable */content = (content || "").replace(mediaRegex, attachmentLink);};if (resource.mime && resource.mime.startsWith("image/")) {try {+ /* v8 ignore next -- a resource's title defaults to "resource", so it is never empty here */const originalName = resource.title && resource.title !== "resource" ? resource.title : `image.${resource.mime.substr(6)}`; // default if real name is not presentconst attachment = imageService.saveImageToAttachment(noteEntity.noteId, resource.content, originalName, !!taskContext.data?.shrinkImages);diff --git a/packages/trilium-core/src/services/import/enex_converter.spec.ts b/packages/trilium-core/src/services/import/enex_converter.spec.tsindex 296309c160..d0db8c35bb 100644--- a/packages/trilium-core/src/services/import/enex_converter.spec.ts+++ b/packages/trilium-core/src/services/import/enex_converter.spec.ts@@ -42,6 +42,18 @@ describe("convertEnexContent — checkboxes (--en-todo lists)", () => {const input = `<ul><li><div>Bullet</div></li></ul>`;expect(convertEnexContent(input)).toBe(input);});++ it("skips a list child that is neither an item nor a sub-list", () => {+ const input = `<ul style="--en-todo:true;"><li style="--en-checked:false;"><div>A</div></li><div>stray</div></ul>`;+ expect(convertEnexContent(input)).toBe(todoList(todoItem("A")));+ });++ it("keeps an item's text when a sub-list is nested inside the item rather than following it", () => {+ // Evernote emits sub-lists as siblings, so a list nested *inside* the item isn't folded in — it's+ // only excluded from the item's description.+ const input = `<ul style="--en-todo:true;"><li style="--en-checked:false;">Direct text<ul style="--en-todo:true;"><li style="--en-checked:false;"><div>Sub</div></li></ul></li></ul>`;+ expect(convertEnexContent(input)).toBe(todoList(todoItem("Direct text")));+ });});describe("convertEnexContent — legacy checkboxes (<en-todo>)", () => {@@ -63,8 +75,13 @@ describe("convertEnexContent — legacy checkboxes (<en-todo>)", () => {});it("falls back to a unicode ballot box for an inline <en-todo> that isn't a line's checkbox", () => {- const input = `<div>Mixed <en-todo checked="true"/>content</div>`;- expect(convertEnexContent(input)).toBe(`<p>Mixed ☑ content</p>`);+ expect(convertEnexContent(`<div>Mixed <en-todo checked="true"/>content</div>`)).toBe(`<p>Mixed ☑ content</p>`);+ expect(convertEnexContent(`<div>Mixed <en-todo checked="false"/>content</div>`)).toBe(`<p>Mixed ☐ content</p>`);+ });++ it("treats a line whose checkbox is preceded by whitespace as a to-do line", () => {+ const input = `<div>\n<en-todo checked="false"/>Task</div>`;+ expect(convertEnexContent(input)).toBe(todoList(todoItem("Task")));});});@@ -151,6 +168,15 @@ describe("convertEnexContent — tasks (--en-task-group + <task> elements)", ()const input = `<div style="--en-task-group:true; --en-id:G;"><div>placeholder</div></div>`;expect(convertEnexContent(input, [])).toBe("");});++ it("takes every remaining task when the placeholder carries no group id", () => {+ const input = `<div style="--en-task-group:true;"><div>placeholder</div></div>`;+ const tasks = [+ { title: "First", status: "open", groupId: "GROUP1" },+ { title: "Second", status: "completed", groupId: "GROUP2" }+ ];+ expect(convertEnexContent(input, tasks)).toBe(todoList(todoItem("First"), todoItem("Second", { checked: true })));+ });});describe("convertEnexContent — admonitions (--en-callout)", () => {@@ -163,6 +189,11 @@ describe("convertEnexContent — admonitions (--en-callout)", () => {const input = `<div style="--en-callout:true; --en-emoji:🤖;"><div>Callout with custom emoji.</div></div>`;expect(convertEnexContent(input)).toBe(`<aside class="admonition note"><p>🤖 Callout with custom emoji.</p></aside>`);});++ it("injects the emoji into a first block child that is a paragraph", () => {+ const input = `<div style="--en-callout:true; --en-emoji:🤖;"><p>Already a paragraph.</p></div>`;+ expect(convertEnexContent(input)).toBe(`<aside class="admonition note"><p>🤖 Already a paragraph.</p></aside>`);+ });});describe("convertEnexContent — toggles (--en-toggle)", () => {@@ -173,6 +204,11 @@ describe("convertEnexContent — toggles (--en-toggle)", () => {);});+ it("renders an empty collapsible when the toggle has neither a summary nor a content block", () => {+ const input = `<div style="--en-toggle:true;"><div>Stray body</div></div>`;+ expect(convertEnexContent(input)).toBe(`<details class="trilium-collapsible" open><summary></summary></details>`);+ });+it("preserves an expanded toggle's open state", () => {const input = `<div style="--en-toggle:true; --en-isCollapsed:false;"><div style="--en-toggleSummary:true;">S</div><div style="--en-toggleContent:true;"><div>Body</div></div></div>`;expect(convertEnexContent(input)).toBe(@@ -295,6 +331,11 @@ describe("rewriteEvernoteLinks — internal note references", () => {expect(rewriteEvernoteLinks(input, resolve)).toBe(input);});+ it("ignores an anchor without an href", () => {+ const input = `<p><a>bookmark</a> <a href="evernote://view-note/x">Orar legislație</a></p>`;+ expect(rewriteEvernoteLinks(input, resolve)).toBe(`<p><a>bookmark</a> <a href="#root/noteA" class="reference-link">Orar legislație</a></p>`);+ });+it("leaves an unresolvable internal link as-is", () => {const input = `<a href="evernote://view-note/unknown">Some other note</a>`;expect(rewriteEvernoteLinks(input, resolve)).toBe(input);diff --git a/packages/trilium-core/src/services/import/enex_converter.ts b/packages/trilium-core/src/services/import/enex_converter.tsindex 98ebb1445c..07345a121e 100644--- a/packages/trilium-core/src/services/import/enex_converter.ts+++ b/packages/trilium-core/src/services/import/enex_converter.ts@@ -105,6 +105,7 @@ function convertTaskGroups(root: HTMLElement, tasks: EnexTask[]) {used.add(index);}if (items.length > 0) {+ /* v8 ignore next -- a parsed <task> always has a (possibly empty) title, so the ?? fallback is unreachable */const list = renderTodoList(items.map(({ task }) => renderTodoItem(task.status === "completed", escapeHtml((task.title ?? "").trim()))));placeholder.insertAdjacentHTML("beforebegin", list);}@@ -177,8 +178,10 @@ function toggleBody(contentDiv: HTMLElement): string {/** True for a node carrying real content — text, or an embedded image/media — i.e. not an empty spacer block. */function isNonEmptyBlock(node: HTMLElement["childNodes"][number]): boolean {if (!(node instanceof HTMLElement)) {+ /* v8 ignore next -- node-html-parser always returns a string from textContent, so the ?? fallback is unreachable */return (node.textContent ?? "").trim() !== "";}+ /* v8 ignore next -- as above: textContent is never nullish */return (node.textContent ?? "").trim() !== "" || node.querySelectorAll("img, en-media").length > 0;}// #endregion@@ -363,11 +366,13 @@ function blockText(container: HTMLElement): string {if (lines.length > 0) {return lines.map((line) => lineText(line)).join("\n");}+ /* v8 ignore next -- node-html-parser always returns a string from textContent, so the ?? fallback is unreachable */return container.textContent ?? "";}/** A single line's text. node-html-parser renders `<br>` as a newline, so a lone-`<br>` line (Evernote's blank line) reads as empty. */function lineText(line: HTMLElement): string {+ /* v8 ignore next -- as above: textContent is never nullish */const text = line.textContent ?? "";if (text.trim() === "" && line.querySelectorAll("br").length > 0) {return "";@@ -423,6 +428,7 @@ function convertParagraphs(root: HTMLElement) {/** A blank line — an empty div, or one holding only a `<br>` — with no embedded image. */function isBlankLine(div: HTMLElement): boolean {+ /* v8 ignore next -- node-html-parser always returns a string from textContent, so the ?? fallback is unreachable */return (div.textContent ?? "").trim() === "" && div.querySelectorAll("img, en-media").length === 0;}diff --git a/packages/trilium-core/src/services/import/mime.spec.ts b/packages/trilium-core/src/services/import/mime.spec.tsindex 54707f5c5f..479dcb2399 100644--- a/packages/trilium-core/src/services/import/mime.spec.ts+++ b/packages/trilium-core/src/services/import/mime.spec.ts@@ -153,6 +153,16 @@ describe("#getType", () => {[{textImportedAsText: false}, "text/html"], "file"],+ [+ "w/ 'text/vnd.mermaid' mime type – it should return 'mermaid'",+ [{}, "text/vnd.mermaid"], "mermaid"+ ],++ [+ "w/ 'text/vnd.mermaid' mime type and codeImportedAsCode: true – it should still return 'mermaid'",+ [{codeImportedAsCode: true}, "text/vnd.mermaid"], "mermaid"+ ],+]testCases.forEach((testCase) => {diff --git a/packages/trilium-core/src/services/import/notion/collection.spec.ts b/packages/trilium-core/src/services/import/notion/collection.spec.tsnew file mode 100644index 0000000000..d46990a97a--- /dev/null+++ b/packages/trilium-core/src/services/import/notion/collection.spec.ts@@ -0,0 +1,116 @@+import { parse } from "node-html-parser";+import { describe, expect, it } from "vitest";++import { getContext } from "../../context.js";+import noteService from "../../notes.js";+import { applyDatabaseSchemas, extractProperties } from "./collection.js";+import type { NotionProperty, ParsedPage } from "./model.js";++/** One `<tr class="property-row property-row-<type>">`; the `<th>` opens with the icon span Notion emits. */+const row = (type: string, name: string, cell: string) =>+ `<tr class="property-row property-row-${type}"><th><span class="icon"></span>${name}</th>${cell}</tr>`;++/** Reads the given property rows out of the properties table Notion renders on a database row's page. */+const propertiesOf = (...rows: string[]) =>+ extractProperties(parse(`<div><table class="properties"><tbody>${rows.join("")}</tbody></table></div>`));++describe("extractProperties", () => {+ it("skips a row with a blank column name or no value cell", () => {+ expect(propertiesOf(+ `<tr class="property-row property-row-text"><th> </th><td>Value</td></tr>`,+ `<tr class="property-row property-row-text"><th>Name</th></tr>`+ )).toEqual([]);+ });++ it("contributes nothing for a blank or unusable cell, whatever the column type", () => {+ // Notion emits an empty cell for every unset value, and a formula/relation/file cell can hold markup+ // that carries no importable value at all (an external link, an href-less anchor, an avatar-only user).+ expect(propertiesOf(+ row("number", "Number", "<td> </td>"),+ row("auto_increment_id", "ID", "<td></td>"),+ row("multi_select", "Tags", `<td><span class="selected-value"> </span></td>`),+ row("url", "URL", `<td><a class="url-value">no href</a></td>`),+ row("checkbox", "Done", "<td>not a checkbox</td>"),+ row("created_by", "Created by", `<td><span class="user"><span class="user-icon">A</span></span></td>`),+ row("relation", "Related", `<td><a href="https://example.com/">External</a></td>`),+ row("file", "Files", "<td><a>no href</a></td>"),+ row("date", "Due", "<td>June 1, 2026</td>"),+ row("formula", "Computed", "<td> </td>")+ )).toEqual([]);+ });++ it("normalizes a formatted number cell and keeps a non-numeric one verbatim", () => {+ expect(propertiesOf(+ row("number", "Price", "<td>$1,200.50</td>"),+ row("number", "Range", "<td>1-2</td>"),+ row("number", "Missing", "<td>n/a</td>")+ )).toEqual([+ { name: "Price", value: "1200.50", labelType: "number", multiplicity: "single" },+ // Neither cleans up to a finite number, so the trimmed original is kept rather than dropped.+ { name: "Range", value: "1-2", labelType: "number", multiplicity: "single" },+ { name: "Missing", value: "n/a", labelType: "number", multiplicity: "single" }+ ]);+ });++ it("types a computed (formula / rollup) cell from its rendered shape", () => {+ expect(propertiesOf(+ row("formula", "Flag", `<td><div class="checkbox checkbox-on"></div></td>`),+ row("rollup", "Total", "<td>42</td>"),+ row("formula", "Version", "<td>1-2-3</td>"),+ row("formula", "When", "<td>June 24, 2026</td>")+ )).toEqual([+ { name: "Flag", value: "true", labelType: "boolean", multiplicity: "single" },+ { name: "Total", value: "42", labelType: "number", multiplicity: "single" },+ // Neither a version string nor a rendered date is a number, so both stay text.+ { name: "Version", value: "1-2-3", labelType: "text", multiplicity: "single" },+ { name: "When", value: "June 24, 2026", labelType: "text", multiplicity: "single" }+ ]);+ });++ it("drops a date cell whose <time> value can't be parsed", () => {+ expect(propertiesOf(row("date", "Start", "<td><time>whenever</time></td>"))).toEqual([]);+ });++ it("reads each user of a people cell, dropping one whose name is only an avatar", () => {+ const cell = `<td><span class="user"><span class="user-icon">E</span>Elian</span><span class="user"><span class="user-icon">A</span></span></td>`;+ expect(propertiesOf(row("person", "Assignee", cell))).toEqual([+ { name: "Assignee", value: "Elian", labelType: "text", multiplicity: "multi" }+ ]);+ });+});++describe("applyDatabaseSchemas — column order", () => {+ const property = (name: string): NotionProperty => ({ name, value: "x", labelType: "text", multiplicity: "single" });++ /** Applies one database folder's schema to a fresh container note and returns its definitions, in position order. */+ function definitionNames(properties: NotionProperty[], csvColumns?: string[]): string[] {+ return getContext().init(() => {+ const { note: container } = noteService.createNewNote({ parentNoteId: "root", title: "DB", content: "", type: "book", mime: "" });+ const page: ParsedPage = { id: "row", title: "Row", path: "DB/Row.html", content: "", linkedPageIds: [], properties };+ applyDatabaseSchemas([page], new Map([["DB", container]]), csvColumns ? new Map([["DB", csvColumns]]) : new Map());+ return [...container.getOwnedAttributes()]+ .sort((a, b) => a.position - b.position)+ .map((attribute) => attribute.name);+ });+ }++ it("follows the CSV column order, slotting a synthesized \"<name> end\" after its base column", () => {+ expect(definitionNames(+ [property("Extra"), property("Due end"), property("Status"), property("Also extra"), property("Due"), property("Ghost end")],+ ["status", "due"]+ )).toEqual([+ "label:status",+ "label:due",+ "label:dueEnd",+ // Columns the CSV doesn't list (including a "<name> end" whose base is missing too) keep their+ // discovery order at the end.+ "label:extra",+ "label:alsoExtra",+ "label:ghostEnd"+ ]);+ });++ it("keeps the discovery order when the database has no CSV column list", () => {+ expect(definitionNames([property("Second"), property("First")])).toEqual(["label:second", "label:first"]);+ });+});diff --git a/packages/trilium-core/src/services/import/notion/converter.spec.ts b/packages/trilium-core/src/services/import/notion/converter.spec.tsindex b16f2cf60c..0ea7521293 100644--- a/packages/trilium-core/src/services/import/notion/converter.spec.ts+++ b/packages/trilium-core/src/services/import/notion/converter.spec.ts@@ -158,6 +158,10 @@ describe("convertNotionHtml — toggle headings", () => {`<details open class="trilium-collapsible"><summary>Plain</summary><p>x</p></details>`);});++ it("leaves a <details> with no summary alone (there's no title to lift into a heading)", () => {+ expect(convertNotionHtml(`<details><p>Body</p></details>`)).toBe(`<details><p>Body</p></details>`);+ });});describe("convertNotionHtml — table of contents", () => {@@ -260,6 +264,20 @@ describe("convertNotionHtml — columns", () => {);});+ it("shares the row evenly between width-less columns, and survives an all-zero layout", () => {+ const bare = (text: string) => dc(`<div class="column">${dc(`<p class="">${text}</p>`)}</div>`);+ const cell = (width: string, text: string) => `<td style="border-color:transparent;width:${width}%;">${text}</td>`;+ const table = (...cells: string[]) =>+ `<figure class="table"><table style="border-color:transparent;"><tbody><tr>${cells.join("")}</tr></tbody></table></figure>`;++ // No `width:` style on either column, so each takes an equal share of the row.+ expect(convertNotionHtml(dc(`<div id="x" class="column-list">${bare("A")}${bare("B")}</div>`)))+ .toBe(table(cell("50", "A"), cell("50", "B")));+ // Widths that sum to zero would divide by zero; the row degenerates to zero-width cells instead.+ expect(convertNotionHtml(columnList(column("0%", "A"), column("0%", "B"))))+ .toBe(table(cell("0", "A"), cell("0", "B")));+ });+it("keeps a column with loose content and a nested list as one cell (nested table inside), not losing content", () => {// Left column is a pure wrapper (flattens); the right column has loose content "2/2" plus a nested// list, so it stays a single cell carrying the paragraph and the nested columns as a nested table.diff --git a/packages/trilium-core/src/services/import/notion/converter.ts b/packages/trilium-core/src/services/import/notion/converter.tsindex e54d6d887c..a76c299e97 100644--- a/packages/trilium-core/src/services/import/notion/converter.ts+++ b/packages/trilium-core/src/services/import/notion/converter.ts@@ -363,6 +363,9 @@ function isMergeableList(el: HTMLElement): boolean {*/function convertColumns(root: HTMLElement) {for (const columnList of root.querySelectorAll("div.column-list")) {+ /* v8 ignore next 4 -- defensive: guards insertAdjacentHTML from dereferencing a null parent. Unreachable+ in practice, since node-html-parser's remove() detaches only the removed node itself (a nested list+ keeps its now-detached parent), and each list from the eager querySelectorAll is removed at most once. */if (!columnList.parentNode) {continue; // a nested list, already rendered as part of its parent}@@ -392,6 +395,7 @@ function flattenColumns(columnList: HTMLElement, parentWidth: number): { width:const leaves: { width: number; content: string }[] = [];for (const [index, column] of columns.entries()) {+ /* v8 ignore next -- `widths` is `columns.map(...)`, so it always has an entry at a column's own index; the `?? 0` only satisfies noUncheckedIndexedAccess */const share = parentWidth * ((widths[index] ?? 0) / total);const wrapped = pureWrapperList(column);if (wrapped) {@@ -423,6 +427,7 @@ function round2(value: number): number {/** True for an empty `<p>` (Notion's layout spacers), which shouldn't count as a column's real content. */function isEmptyParagraph(node: HTMLElement): boolean {+ /* v8 ignore next -- node-html-parser's textContent getter always returns a string, so the `?? ""` never applies */return isTag(node, "p") && (node.textContent ?? "").trim() === "";}diff --git a/packages/trilium-core/src/services/import/notion/importer.integration.spec.ts b/packages/trilium-core/src/services/import/notion/importer.integration.spec.tsindex 27e2b57920..7c667195b2 100644--- a/packages/trilium-core/src/services/import/notion/importer.integration.spec.ts+++ b/packages/trilium-core/src/services/import/notion/importer.integration.spec.ts@@ -116,16 +116,18 @@ describe("Notion importer — integration", () => {).rejects.toThrow(/Create folders for subpages/i);});- it("imports a flat export containing an empty database (no rows) without flagging", async () => {- // An empty database (CSV header only) contributes no row titles, so a legitimately flat export that- // happens to include one isn't mistaken for a flattened hierarchy.- const importRoot = await importNotion({- "Empty DB 08d361c59a9940c2a9d7237a4e6cd09a.csv": "Name,Status",- "Note A 4f195d8c55fb44f4b94a063e643b0297.html": pageHtml("Note A", "4f195d8c55fb44f4b94a063e643b0297"),- "Note B 388c5eca1b8b80929a78da7c68154bd7.html": pageHtml("Note B", "388c5eca1b8b80929a78da7c68154bd7")- });+ it("imports a flat export containing a database with no rows, or only unnamed ones, without flagging", async () => {+ // A CSV holding only a header — or only rows with a blank first column — contributes no row titles, so+ // a legitimately flat export that happens to include one isn't mistaken for a flattened hierarchy.+ for (const csv of ["Name,Status", "Name,Status\n,Done"]) {+ const importRoot = await importNotion({+ "Empty DB 08d361c59a9940c2a9d7237a4e6cd09a.csv": csv,+ "Note A 4f195d8c55fb44f4b94a063e643b0297.html": pageHtml("Note A", "4f195d8c55fb44f4b94a063e643b0297"),+ "Note B 388c5eca1b8b80929a78da7c68154bd7.html": pageHtml("Note B", "388c5eca1b8b80929a78da7c68154bd7")+ });- expect(importRoot.getChildNotes().map((note) => note.title)).toEqual(expect.arrayContaining(["Note A", "Note B"]));+ expect(importRoot.getChildNotes().map((note) => note.title)).toEqual(expect.arrayContaining(["Note A", "Note B"]));+ }});it("imports flat top-level pages that only mention each other (no subpage blocks) without flagging", async () => {diff --git a/packages/trilium-core/src/services/import/obsidian/importer.integration.spec.ts b/packages/trilium-core/src/services/import/obsidian/importer.integration.spec.tsindex 33a8ef57ca..5ec3f8494e 100644--- a/packages/trilium-core/src/services/import/obsidian/importer.integration.spec.ts+++ b/packages/trilium-core/src/services/import/obsidian/importer.integration.spec.ts@@ -19,7 +19,8 @@ async function createZipBuffer(files: Record<string, string | Buffer>, dates: Repassthrough.on("data", (chunk: Buffer) => chunks.push(chunk));archive.pipe(passthrough);for (const [name, content] of Object.entries(files)) {- archive.append(content, { name, date: dates[name] });+ // A name ending in "/" is an explicit directory entry, which OS-created vault zips include.+ archive.append(name.endsWith("/") ? null : content, { name, date: dates[name] });}await archive.finalize();return Buffer.concat(chunks);@@ -90,6 +91,19 @@ describe("Obsidian importer — integration", () => {expect(decodeUtf8(welcome?.getContent() ?? "")).toBe("<p>This is your new <em>vault</em>.</p>");});+ it("ignores explicit directory entries and gives a folder's notes a single container", async () => {+ const importRoot = await importObsidian({+ ".obsidian/app.json": "{}",+ "Folder 1/": "",+ "Folder 1/A.md": "a",+ "Folder 1/B.md": "b"+ });++ // The directory entry contributes no note of its own, and both notes share one "Folder 1" container.+ expect(importRoot.getChildNotes().map((n) => n.title)).toEqual(["Folder 1"]);+ expect(importRoot.getChildNotes()[0]?.getChildNotes().map((n) => n.title)).toEqual(["A", "B"]);+ });+it("renders an Obsidian callout (with fold marker and custom title) as an admonition", async () => {const importRoot = await importObsidian({"Note.md": "> [!success]- Nicely done\n> It worked."@@ -173,6 +187,17 @@ describe("Obsidian importer — integration", () => {expect(note.getOwnedLabelValue("label:checkboxProp")).toBe("promoted,single,boolean,alias=Checkbox prop");});+ it("falls back to text when types.json holds no types map or a non-string type", async () => {+ const frontmatter = "---\nNumber: 5\n---\nBody.";+ const noTypes = await importObsidian({ ".obsidian/types.json": "{}", "Note.md": frontmatter });+ const badType = await importObsidian({ ".obsidian/types.json": JSON.stringify({ types: { Number: 5 } }), "Note.md": frontmatter });++ for (const importRoot of [noTypes, badType]) {+ const note = importRoot.getChildNotes().find((n) => n.title === "Note");+ expect(note?.getOwnedLabelValue("label:number")).toBe("promoted,single,text,alias=Number");+ }+ });+it("preserves a note's modification date from its zip entry, with created falling back to it", async (ctx) => {// The standalone/browser zip provider (fflate) doesn't expose entry mtimes, so there's no date to// preserve; the note keeps its import-time dates. Skip rather than assert provider-specific behavior.@@ -194,6 +219,14 @@ describe("Obsidian importer — integration", () => {expect(note.utcDateCreated).toBe(note.utcDateModified);});+ it("ignores the DOS-epoch sentinel a date-less zip entry yields", async () => {+ const importRoot = await importObsidian({ "Note.md": "Body." }, undefined, { "Note.md": new Date(1980, 0, 1) });++ const note = importRoot.getChildNotes().find((n) => n.title === "Note");+ // 1980 is the ZIP format's zero date, not a real modification time, so the import-time dates stand.+ expect(note?.utcDateModified?.startsWith("1980-")).toBe(false);+ });+it("converts ==highlights== to a coloured span and %%comments%% to dropped HTML comments", async () => {const importRoot = await importObsidian({"Note.md": "A ==highlight== and a %%hidden%% comment."@@ -241,6 +274,13 @@ describe("Obsidian importer — integration", () => {expect(importRoot.getChildNotes().map((n) => n.title)).toEqual(["Welcome"]);});+ it("uses the default root title when the zip name is nothing but an extension", async () => {+ const named = await importObsidian({ "Note.md": "x" }, ".zip");+ const unnamed = await importObsidian({ "Note.md": "x" });++ expect(named.title).toBe(unnamed.title);+ });+it("falls back to stripping a single shared wrapper folder when there is no .obsidian", async () => {const importRoot = await importObsidian({ "Wrapper/A.md": "a", "Wrapper/B.md": "b" });@@ -303,15 +343,21 @@ describe("Obsidian importer — integration", () => {const importRoot = await importObsidian({"Note.md": "Just a note, linking nothing.","Attachments/report.pdf": Buffer.from("%PDF-1.4 fake"),+ "Attachments/data.unknownext": Buffer.from("raw bytes"),".obsidian/app.json": "{}"}, "Vault.zip");const attachmentsFolder = importRoot.getChildNotes().find((n) => n.title === "Attachments");- const orphan = attachmentsFolder?.getChildNotes()[0];+ const orphan = attachmentsFolder?.getChildNotes().find((n) => n.title === "report");if (!orphan) {throw new Error("orphan file was not imported");}+ // A file whose extension has no known MIME still imports, as a generic binary keeping its full name.+ const unknown = attachmentsFolder?.getChildNotes().find((n) => n.title === "data.unknownext");+ expect(unknown?.type).toBe("file");+ expect(unknown?.mime).toBe("application/octet-stream");+// The .pdf extension is stripped from the title (Trilium convention) and preserved in a label.expect(orphan.title).toBe("report");expect(orphan.type).toBe("file");@@ -437,16 +483,22 @@ describe("Obsidian importer — integration", () => {const importRoot = await importObsidian({"Drawing.excalidraw.md": excalidrawFile({type: "excalidraw",- elements: [{ id: "img", type: "image", fileId: "abc123def456" }],+ elements: [+ { id: "img", type: "image", fileId: "abc123def456" },+ { id: "doc", type: "image", fileId: "aaa111bbb222" },+ { id: "gone", type: "image", fileId: "ccc333ddd444" }+ ],appState: {},files: {}- }, "## Embedded Files\nabc123def456: [[shot.png]]\n"),- "shot.png": Buffer.from("\x89PNG\r\n\x1a\nfake-png")+ }, "## Embedded Files\nabc123def456: [[shot.png]]\naaa111bbb222: [[doc.rtf]]\nccc333ddd444: [[missing.png]]\n"),+ "shot.png": Buffer.from("\x89PNG\r\n\x1a\nfake-png"),+ "doc.rtf": Buffer.from("{\\rtf1 hello}")});const drawing = importRoot.getChildNotes().find((n) => n.title === "Drawing");// The image is stored as an `image`-role attachment whose title is the fileId the scene references,- // matching how the canvas editor persists images so it renders on load.+ // matching how the canvas editor persists images so it renders on load. A reference the vault doesn't+ // hold, and one that resolves to a non-image, are both skipped rather than attached.const images = drawing?.getAttachmentsByRole("image");expect(images?.map((a) => a.title)).toEqual(["abc123def456"]);});diff --git a/packages/trilium-core/src/services/import/obsidian/importer.spec.ts b/packages/trilium-core/src/services/import/obsidian/importer.spec.tsindex 9ec824fe99..c004054b20 100644--- a/packages/trilium-core/src/services/import/obsidian/importer.spec.ts+++ b/packages/trilium-core/src/services/import/obsidian/importer.spec.ts@@ -29,6 +29,15 @@ describe("mapObsidianFrontmatter", () => {]);});+ it("flattens a YAML timestamp (parsed as a Date) and a false boolean into label values", () => {+ expect(mapObsidianFrontmatter({ Created: new Date("2026-06-27T15:10:00Z"), Flag: false }, new Map([["Created", "datetime"]]))).toEqual([+ { name: "created", value: "2026-06-27T15:10" },+ { name: "label:created", value: "promoted,single,datetime,alias=Created" },+ { name: "flag", value: "false" },+ { name: "label:flag", value: "promoted,single,text,alias=Flag" }+ ]);+ });+it("treats a list (or a multitext property) as a multi-valued promoted attribute", () => {expect(mapObsidianFrontmatter({ List: ["a", "b"] }, new Map([["List", "multitext"]]))).toEqual([{ name: "list", value: "a" },diff --git a/packages/trilium-core/src/services/import/opml.spec.ts b/packages/trilium-core/src/services/import/opml.spec.tsindex 768d10c551..1e3f5fb8bf 100644--- a/packages/trilium-core/src/services/import/opml.spec.ts+++ b/packages/trilium-core/src/services/import/opml.spec.ts@@ -4,9 +4,10 @@ import becca from "../../becca/becca.js";import type BNote from "../../becca/entities/bnote.js";import { getContext } from "../context.js";import noteService from "../notes.js";+import protectedSessionService from "../protected_session.js";import sql_init from "../sql_init.js";import TaskContext from "../task_context.js";-import { decodeUtf8 } from "../utils/binary.js";+import { decodeUtf8, encodeUtf8 } from "../utils/binary.js";import opml from "./opml.js";let counter = 0;@@ -108,6 +109,21 @@ describe("importOpml (real DB)", () => {expect(decodeUtf8(returnNote.getContent())).toBe("");});+ it("imports a v1 outline that has no text as an empty note", async () => {+ const parent = createParent();+ const xml = `<?xml version="1.0"?>+ <opml version="1.0">+ <body>+ <outline title="Title only" />+ </body>+ </opml>`;++ const returnNote = (await runImport(xml, parent)) as BNote;++ expect(returnNote.title).toBe("Title only");+ expect(decodeUtf8(returnNote.getContent())).toBe("");+ });+it("imports a v2.0 outline using text as title and _note as raw HTML content", async () => {const parent = createParent();const xml = `<?xml version="1.0"?>@@ -165,6 +181,36 @@ describe("importOpml (real DB)", () => {expect(parent.getChildNotes()).toHaveLength(0);});+ it("marks the imported outlines protected when the parent is protected and a session is available", async () => {+ // Protection propagates only via `parentNote.isProtected && isProtectedSessionAvailable()`, so both+ // a protected target and a data key are needed.+ protectedSessionService.setDataKey(encodeUtf8("0123456789abcdef")); // exactly 16 bytes+ try {+ const parent = getContext().init(() =>+ noteService.createNewNote({+ parentNoteId: "root",+ title: "protected opml parent",+ content: "",+ type: "text",+ isProtected: true+ }).note+ );+ const xml = `<?xml version="1.0"?>+ <opml version="2.0">+ <body>+ <outline text="Secret" _note="<p>secret body</p>" />+ </body>+ </opml>`;++ const returnNote = (await runImport(xml, parent)) as BNote;++ expect(parent.isProtected).toBe(true);+ expect(returnNote.isProtected).toBe(true);+ } finally {+ protectedSessionService.resetDataKey();+ }+ });+it("rejects malformed XML by throwing", async () => {const parent = createParent();const xml = "<opml version=\"1.0\"><body><outline></body></opml>";diff --git a/packages/trilium-core/src/services/import/opml.ts b/packages/trilium-core/src/services/import/opml.tsindex f094585f5a..1fe0005821 100644--- a/packages/trilium-core/src/services/import/opml.ts+++ b/packages/trilium-core/src/services/import/opml.ts@@ -60,9 +60,11 @@ async function importOpml(taskContext: TaskContext<"importNotes">, fileBuffer: s} else if (opmlVersion === 2) {title = outline.$.text;content = outline.$._note; // _note is already HTML+ /* v8 ignore start -- unreachable: the version check above admits only 1.0/1.1/2.0, so parseInt is always 1 or 2 */} else {throw new Error(`Unrecognized OPML version ${opmlVersion}`);}+ /* v8 ignore stop */content = sanitizeHtml(content || "");diff --git a/packages/trilium-core/src/services/import/samples/Bare note.enex b/packages/trilium-core/src/services/import/samples/Bare note.enexnew file mode 100644index 0000000000..01430d2b85--- /dev/null+++ b/packages/trilium-core/src/services/import/samples/Bare note.enex@@ -0,0 +1,9 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE en-export SYSTEM "http://xml.evernote.com/pub/evernote-export4.dtd">+<en-export export-date="20260101T000000Z" application="Evernote" version="11">+ <note>+ <title>Bare</title>+ <content><![CDATA[<div>No en-note wrapper</div>]]></content>+ <resource><data encoding="base64">MjIy</data></resource>+ </note>+</en-export>diff --git a/packages/trilium-core/src/services/import/samples/Broken markup.enex b/packages/trilium-core/src/services/import/samples/Broken markup.enexnew file mode 100644index 0000000000..ac28ad426b--- /dev/null+++ b/packages/trilium-core/src/services/import/samples/Broken markup.enex@@ -0,0 +1,11 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE en-export SYSTEM "http://xml.evernote.com/pub/evernote-export4.dtd">+<en-export export-date="20260101T000000Z" application="Evernote" version="11">+ <note>+ <title>Recovered</title>+ <created>20200101T000000Z</created>+ <content><![CDATA[<?xml version="1.0" encoding="UTF-8" standalone="no"?>+<!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd"><en-note><div>Body</div></en-note>]]></content>+ </note>+ </unopened>+</en-export>diff --git a/packages/trilium-core/src/services/import/samples/Missing title.enex b/packages/trilium-core/src/services/import/samples/Missing title.enexnew file mode 100644index 0000000000..b38a63d808--- /dev/null+++ b/packages/trilium-core/src/services/import/samples/Missing title.enex@@ -0,0 +1,8 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE en-export SYSTEM "http://xml.evernote.com/pub/evernote-export4.dtd">+<en-export export-date="20260101T000000Z" application="Evernote" version="11">+ <note>+ <created>20200101T000000Z</created>+ <content><![CDATA[<en-note><div>Body without a title</div></en-note>]]></content>+ </note>+</en-export>diff --git a/packages/trilium-core/src/services/import/samples/No notes.enex b/packages/trilium-core/src/services/import/samples/No notes.enexnew file mode 100644index 0000000000..653f12bf23--- /dev/null+++ b/packages/trilium-core/src/services/import/samples/No notes.enex@@ -0,0 +1,4 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE en-export SYSTEM "http://xml.evernote.com/pub/evernote-export4.dtd">+<en-export export-date="20260101T000000Z" application="Evernote" version="11">+</en-export>diff --git a/packages/trilium-core/src/services/import/samples/Stray elements.enex b/packages/trilium-core/src/services/import/samples/Stray elements.enexnew file mode 100644index 0000000000..d81b5a4fd1--- /dev/null+++ b/packages/trilium-core/src/services/import/samples/Stray elements.enex@@ -0,0 +1,13 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE en-export SYSTEM "http://xml.evernote.com/pub/evernote-export4.dtd">+<en-export export-date="20260101T000000Z" application="Evernote" version="11">+ <note-attributes><source-url>https://triliumnotes.org/stray</source-url></note-attributes>+ <resource><data encoding="base64">c3RyYXk=</data><mime>text/plain</mime></resource>+ <task><title>Stray task</title><taskStatus>open</taskStatus></task>+ <note>+ <title>After strays</title>+ <created>20200101T000000Z</created>+ <content><![CDATA[<?xml version="1.0" encoding="UTF-8" standalone="no"?>+<!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd"><en-note><div>Body</div></en-note>]]></content>+ </note>+</en-export>diff --git a/packages/trilium-core/src/services/import/single.spec.ts b/packages/trilium-core/src/services/import/single.spec.tsindex cd1221d4d2..8f05cb6ec2 100644--- a/packages/trilium-core/src/services/import/single.spec.ts+++ b/packages/trilium-core/src/services/import/single.spec.ts@@ -5,10 +5,13 @@ import { fileURLToPath } from "url";import { dirname } from "path";import becca from "../../becca/becca.js";import BNote from "../../becca/entities/bnote.js";+import imageService from "../image.js";+import noteService from "../notes.js";+import protectedSessionService from "../protected_session.js";import TaskContext from "../task_context.js";import sql_init from "../sql_init.js";import single from "./single.js";-import { stripBom } from "../utils/binary.js";+import { encodeUtf8, stripBom } from "../utils/binary.js";import { getContext } from "../context.js";const scriptDir = dirname(fileURLToPath(import.meta.url));@@ -52,19 +55,12 @@ async function testImport(fileName: string, mimetype: string, bufferOverride?: B});}-describe("processNoteContent", () => {- beforeAll(async () => {- // Prevent download of images.- vi.mock("../image.js", () => {- return {- default: { saveImageToAttachment: () => {} }- };- });-- sql_init.initializeDb();- await sql_init.dbReady;- });+beforeAll(async () => {+ sql_init.initializeDb();+ await sql_init.dbReady;+});+describe("processNoteContent", () => {it("treats single MDX as Markdown", async () => {const { importedNote } = await testImport("Text Note.mdx", "text/mdx");expect(importedNote.mime).toBe("text/html");@@ -192,4 +188,176 @@ describe("processNoteContent", () => {expect(sheet.cellData[0][0].v).toBe("Hello");expect(sheet.cellData[0][1].v).toBe(42);});++ it("imports .csv as a spreadsheet note", async () => {+ const { importedNote } = await testImport("Budget.csv", "text/csv", Buffer.from("a,b\r\n1,2"));++ expect(importedNote).toMatchObject({+ mime: "text/x-spreadsheet",+ type: "spreadsheet",+ title: "Budget"+ });+ expect(importedNote.getLabelValue("originalFileName")).toBe("Budget.csv");++ const parsed = JSON.parse(importedNote.getContent().toString());+ const sheet = parsed.workbook.sheets[parsed.workbook.sheetOrder[0]];+ expect(sheet.cellData[0][0].v).toBe("a");+ expect(sheet.cellData[1][1].v).toBe(2);+ });++ it("sanitizes rendered Markdown when safeImport is on", async () => {+ const md = `# Heading\n\n<img src=x onerror="alert(1)">`;+ const { importedNote } = await testImport("Unsafe.md", "text/markdown", Buffer.from(md), { safeImport: true });++ const content = importedNote.getContent().toString();+ expect(content).not.toContain("onerror");+ expect(content).toContain("Heading");+ });+}, 60_000);++describe("importSingleFile dispatch", () => {+ it("imports an unrecognized upload as a file note carrying its original filename", async () => {+ const { importedNote } = await testImport("payload.unknownext", "application/x-custom", Buffer.from([1, 2, 3]));++ // `.unknownext` has no mime-db entry, so getMime() returns false and the upload's own mimetype+ // wins; the extension isn't one importFile strips, so it stays in the title.+ expect(importedNote).toMatchObject({ type: "file", mime: "application/x-custom", title: "payload.unknownext" });+ expect(importedNote.getOwnedLabelValue("originalFileName")).toBe("payload.unknownext");+ });++ it("strips the extension and underscores from a PDF's title", async () => {+ // importFile passes `mime === "application/pdf"` as replaceUnderscoresWithSpaces, so only PDFs+ // get the underscore treatment.+ const { importedNote } = await testImport("My_Report.pdf", "application/pdf", Buffer.from("%PDF-1.4\n"));++ expect(importedNote).toMatchObject({ type: "file", mime: "application/pdf", title: "My Report" });+ });++ it("falls back to a plain file note when the matching 'import as' option is off", async () => {+ const csv = await testImport("Off.csv", "text/csv", Buffer.from("a,b\r\n1,2"), { spreadsheetImportedAsSpreadsheet: false });+ expect(csv.importedNote).toMatchObject({ type: "file", mime: "text/csv" });++ const code = await testImport("Off.py", "text/x-python", Buffer.from("print(1)"), { codeImportedAsCode: false });+ expect(code.importedNote).toMatchObject({ type: "file", mime: "text/x-python" });+ });++ it("falls back to the upload's own mimetype for a code note with an unrecognized extension", async () => {+ const { importedNote } = await testImport("script.unknownext", "text/x-python", Buffer.from("print(1)"));++ expect(importedNote).toMatchObject({ type: "code", mime: "text/x-python", title: "script.unknownext" });+ });++ it("imports HTML as a code note when textImportedAsText is off", async () => {+ // text/html is also a code MIME, so with the text option off it lands on the code branch+ // rather than dropping all the way through to a file note.+ const { importedNote } = await testImport("Raw.html", "text/html", Buffer.from("<p>hi</p>"), { textImportedAsText: false });++ expect(importedNote).toMatchObject({ type: "code", mime: "text/html" });+ });++ it("routes an image upload to the image service and returns the note it created", async () => {+ // saveImage kicks off fire-and-forget image processing that would outlive the test, so it is+ // stubbed here; single.ts only has to be shown handing the upload over with the right flags.+ const stubNote = { noteId: "stubImageNote" } as unknown as BNote;+ const saveImage = vi.spyOn(imageService, "saveImage").mockReturnValue({ note: stubNote } as never);+ const buffer = Buffer.from([0x89, 0x50, 0x4e, 0x47]);++ try {+ const { importedNote } = await testImport("Photo.png", "image/png", buffer, { shrinkImages: true });++ expect(importedNote).toBe(stubNote);+ expect(saveImage).toHaveBeenCalledWith("root", buffer, "Photo.png", true);+ } finally {+ saveImage.mockRestore();+ }+ });++ it("rejects an image whose content arrived as a string", async () => {+ const taskContext = TaskContext.getInstance("import-image-string", "importNotes", {});+ const rootNote = becca.getNoteOrThrow("root");++ await expect(+ getContext().init(() =>+ single.importSingleFile(taskContext, { originalname: "Photo.png", mimetype: "image/png", buffer: "not-a-buffer" }, rootNote)+ )+ ).rejects.toThrow("Invalid file content for image.");+ });+}, 60_000);++describe("importAttachment", () => {+ it("routes an image to the image service and saves anything else as a file attachment", async () => {+ // As in the image import test, the async processing inside saveImageToAttachment is stubbed out.+ const saveImageToAttachment = vi.spyOn(imageService, "saveImageToAttachment").mockReturnValue(undefined as never);+ const taskContext = TaskContext.getInstance("import-attachment", "importNotes", { shrinkImages: true });+ const rootNote = becca.getNoteOrThrow("root");+ const imageBuffer = Buffer.from([0x89, 0x50, 0x4e, 0x47]);++ try {+ await getContext().init(async () => {+ single.importAttachment(taskContext, { originalname: "Shot.png", mimetype: "image/png", buffer: imageBuffer }, rootNote);+ single.importAttachment(taskContext, { originalname: "notes.unknownext", mimetype: "application/x-custom", buffer: Buffer.from("data") }, rootNote);+ });++ expect(saveImageToAttachment).toHaveBeenCalledWith("root", imageBuffer, "Shot.png", true);++ const attachment = rootNote.getAttachments().find((a) => a.title === "notes.unknownext");+ expect(attachment).toMatchObject({ mime: "application/x-custom", role: "file" });+ } finally {+ saveImageToAttachment.mockRestore();+ }+ });+}, 60_000);++describe("importing under a protected parent", () => {+ const PROTECTED_KEY = encodeUtf8("0123456789abcdef"); // exactly 16 bytes++ it("marks every import type protected when a protected session is available", async () => {+ // A child inherits protection only via `parentNote.isProtected && isProtectedSessionAvailable()`,+ // so the parent must be protected AND a data key present for the flag to propagate. Each import+ // type resolves that pair independently, hence the sweep across all of them.+ protectedSessionService.setDataKey(PROTECTED_KEY);+ try {+ const parent = await getContext().init(async () => {+ const { note } = noteService.createNewNote({+ parentNoteId: "root",+ title: "protected import target",+ content: "",+ type: "text",+ mime: "text/html",+ isProtected: true+ });+ return note;+ });+ expect(parent.isProtected).toBe(true);++ const taskContext = TaskContext.getInstance("import-protected", "importNotes", {+ textImportedAsText: true,+ codeImportedAsCode: true,+ spreadsheetImportedAsSpreadsheet: true+ });++ const uploads = [+ { originalname: "Prot.bin", mimetype: "application/x-custom", buffer: Buffer.from([1]) },+ { originalname: "Prot.py", mimetype: "text/x-python", buffer: Buffer.from("print(1)") },+ { originalname: "Prot.mermaid", mimetype: "text/vnd.mermaid", buffer: Buffer.from("flowchart TD\n A --> B") },+ { originalname: "Prot.csv", mimetype: "text/csv", buffer: Buffer.from("a,b\r\n1,2") },+ { originalname: "Prot.txt", mimetype: "text/plain", buffer: Buffer.from("plain") },+ { originalname: "Prot.md", mimetype: "text/markdown", buffer: Buffer.from("# md") },+ { originalname: "Prot.html", mimetype: "text/html", buffer: Buffer.from("<p>html</p>") }+ ];++ const imported = await getContext().init(async () => {+ const notes: BNote[] = [];+ for (const upload of uploads) {+ notes.push(await single.importSingleFile(taskContext, upload, parent));+ }+ return notes;+ });++ expect(imported.map((note) => note.type)).toEqual(["file", "code", "mermaid", "spreadsheet", "text", "text", "text"]);+ expect(imported.every((note) => note.isProtected)).toBe(true);+ } finally {+ protectedSessionService.resetDataKey();+ }+ });}, 60_000);diff --git a/packages/trilium-core/src/services/import/zip.spec.ts b/packages/trilium-core/src/services/import/zip.spec.tsindex 28397c24e5..cac2d00447 100644--- a/packages/trilium-core/src/services/import/zip.spec.ts+++ b/packages/trilium-core/src/services/import/zip.spec.ts@@ -1,6 +1,7 @@import { beforeAll, describe, expect, it, vi } from "vitest";import ExcelJS from "exceljs";import { ZipArchive } from "archiver";+import { strToU8, zipSync } from "fflate";import fs from "fs";import { fileURLToPath } from "url";import { dirname } from "path";@@ -23,20 +24,12 @@ async function testImport(fileName: string) {async function testImportBuffer(buffer: Buffer, taskId = "import-mdx", taskData: Record<string, unknown> = { textImportedAsText: true }, opts?: { restoreAsRoot?: boolean; preserveIds?: boolean }) {const taskContext = TaskContext.getInstance(taskId, "importNotes", taskData);- return new Promise<{ importedNote: BNote; rootNote: BNote }>((resolve, reject) => {- getContext().init(async () => {- const rootNote = becca.getNote("root");- if (!rootNote) {- expect(rootNote).toBeTruthy();- return;- }-- const importedNote = await zip.importZip(taskContext, buffer, rootNote as BNote, opts);- resolve({- importedNote,- rootNote- });- });+ // `init` returns the callback's promise, so a failing import rejects here rather than hanging.+ return getContext().init(async () => {+ const rootNote = becca.getNoteOrThrow("root");+ const importedNote = await zip.importZip(taskContext, buffer, rootNote, opts);++ return { importedNote, rootNote };});}@@ -53,19 +46,12 @@ async function createZipBuffer(files: Record<string, string | Buffer>): Promise<return Buffer.concat(chunks);}-describe("processNoteContent", () => {- beforeAll(async () => {- // Prevent download of images.- vi.mock("../image.js", () => {- return {- default: { saveImageToAttachment: () => {} }- };- });-- sql_init.initializeDb();- await sql_init.dbReady;- });+beforeAll(async () => {+ sql_init.initializeDb();+ await sql_init.dbReady;+});+describe("processNoteContent", () => {it("imports YAML front matter from a generic Markdown file in a ZIP as labels", async () => {const buffer = await createZipBuffer({"Note.md": "---\nfirst: First value\ntags:\n - Tag\n - AnotherTag\n---\nThe body."@@ -512,6 +498,638 @@ describe("processNoteContent", () => {expect(note?.type).toBe("file");expect(note?.mime).toBe("text/csv");});++ it("skips macOS resource-fork entries and reports an archive that holds nothing else", async () => {+ // A zip zipped on macOS carries a __MACOSX/ sidecar for every real entry. With nothing but+ // those, no note is ever created and the import has no root to hand back.+ const zipBuffer = await createZipBuffer({+ "__MACOSX/._a.txt": "resource fork",+ "__MACOSX": "dir marker"+ });++ await expect(testImportBuffer(zipBuffer, "import-macosx-only")).rejects.toThrow("Unable to determine first note.");+ });++ it("normalizes backslash separators and strips a leading slash", async () => {+ // A zip written on Windows can use backslashes, and a rooted name would otherwise be read as+ // an extra empty path segment. archiver rewrites both, so the raw names are built with fflate.+ const zipBuffer = Buffer.from(zipSync({+ "\\Windows Dir\\entry.txt": strToU8("windows content"),+ "/rooted.txt": strToU8("rooted content")+ }));++ const { rootNote } = await testImportBuffer(zipBuffer, "import-raw-entry-names");++ const dirNote = rootNote.getChildNotes().find((n) => n.title === "Windows Dir");+ expect(dirNote?.getChildNotes().map((n) => n.title)).toEqual(["entry.txt"]);+ expect(rootNote.getChildNotes().map((n) => n.title)).toContain("rooted.txt");+ });++ it("flushes a batch once the entry count reaches the cap", async () => {+ // Notes are written in batches of 200 inside one transaction; an archive larger than the cap+ // must flush mid-stream rather than buffering the whole thing.+ const files: Record<string, string> = {};+ for (let i = 0; i < 205; i++) {+ files[`batched/note-${String(i).padStart(3, "0")}.txt`] = `body ${i}`;+ }+ const zipBuffer = await createZipBuffer(files);++ const { rootNote } = await testImportBuffer(zipBuffer, "import-batched");+ const batchDir = rootNote.getChildNotes().find((n) => n.title === "batched");++ expect(batchDir?.getChildNotes()).toHaveLength(205);+ });++ it("treats a data file and a same-named directory as one note", async () => {+ // "Programming.html" and the "Programming" folder that holds its children describe the same+ // note; the directory is created first (out-of-order entry) and the data file must land on it+ // rather than spawning a duplicate.+ const zipBuffer = await createZipBuffer({+ "Programming/Child.txt": "child",+ "Programming.html": "<p>parent body</p>"+ });+ const { rootNote } = await testImportBuffer(zipBuffer, "import-dir-and-file");++ const matches = rootNote.getChildNotes().filter((n) => n.title === "Programming");+ expect(matches).toHaveLength(1);+ expect(matches[0]?.getContent().toString()).toContain("parent body");+ expect(matches[0]?.getChildNotes().map((n) => n.title)).toEqual(["Child.txt"]);+ });++ it("preserves note and attachment ids when asked to", async () => {+ const metaFile = {+ formatVersion: 2,+ appVersion: "0.0.0",+ files: [{+ noteId: "keptNoteId01",+ title: "Kept",+ type: "text",+ mime: "text/html",+ format: "html",+ dataFileName: "Kept.html",+ attributes: [],+ attachments: [{+ attachmentId: "keptAttach01",+ title: "data.txt",+ role: "file",+ mime: "text/plain",+ position: 10,+ dataFileName: "Kept_data.txt"+ }]+ }]+ };++ const zipBuffer = await createZipBuffer({+ "!!!meta.json": JSON.stringify(metaFile),+ "Kept.html": "<p>kept</p>",+ "Kept_data.txt": "attachment body"+ });++ const { importedNote } = await testImportBuffer(zipBuffer, "import-preserve-ids", { textImportedAsText: true }, { preserveIds: true });++ expect(importedNote.noteId).toBe("keptNoteId01");+ expect(importedNote.getAttachments().map((a) => a.attachmentId)).toEqual(["keptAttach01"]);+ });++ it("substitutes placeholder ids for blank note and attachment ids", async () => {+ // A malformed archive can carry empty ids; they're funnelled onto fixed placeholders rather+ // than being allowed to collide with a generated id.+ const metaFile = {+ formatVersion: 2,+ appVersion: "0.0.0",+ files: [{+ noteId: "blankIdHost1",+ title: "Host",+ type: "text",+ mime: "text/html",+ format: "html",+ dataFileName: "Host.html",+ attributes: [{ type: "relation", name: "myRelation", value: " " }],+ attachments: [{+ attachmentId: " ",+ title: "blank.txt",+ role: "file",+ mime: "text/plain",+ position: 10,+ dataFileName: "Host_blank.txt"+ }]+ }]+ };++ const zipBuffer = await createZipBuffer({+ "!!!meta.json": JSON.stringify(metaFile),+ "Host.html": "<p>host</p>",+ "Host_blank.txt": "blank"+ });++ const { importedNote } = await testImportBuffer(zipBuffer, "import-blank-ids");++ expect(importedNote.getAttachments().map((a) => a.attachmentId)).toEqual(["empty_attachment_id"]);+ // The relation's blank target maps to the placeholder, which matches no note, so the relation+ // is dropped rather than saved pointing at nothing.+ expect(importedNote.getOwnedAttributes().filter((a) => a.type === "relation")).toHaveLength(0);+ });++ it("re-parents a note that a malformed archive makes its own parent", async () => {+ // Both meta levels claim the same noteId, so the child's computed parent is itself. Left alone+ // that persists a self-referential branch which corrupts the tree.+ const metaFile = {+ formatVersion: 2,+ appVersion: "0.0.0",+ files: [{+ noteId: "selfParent01",+ title: "Self",+ type: "text",+ mime: "text/html",+ format: "html",+ dirFileName: "Self",+ attributes: [],+ attachments: [],+ children: [{+ noteId: "selfParent01",+ title: "Self Child",+ type: "text",+ mime: "text/html",+ format: "html",+ dataFileName: "Self.html",+ attributes: [],+ attachments: []+ }]+ }]+ };++ const zipBuffer = await createZipBuffer({+ "!!!meta.json": JSON.stringify(metaFile),+ "Self/Self.html": "<p>self</p>"+ });++ const { importedNote, rootNote } = await testImportBuffer(zipBuffer, "import-self-parent");++ expect(importedNote.getParentNotes().map((n) => n.noteId)).toEqual([rootNote.noteId]);+ expect(becca.getBranchFromChildAndParent(importedNote.noteId, importedNote.noteId)).toBeFalsy();+ });++ it("aborts when a folder's name collides with an already-imported data file", async () => {+ // "Doc.md" is imported as a note, which registers it under the extension-less path "Doc". A+ // folder that is *literally* named "Doc.md" then resolves to that same note, so the importer+ // finds an existing note where it expected to create a parent folder and gives up.+ // NOTE: this aborts the whole import rather than degrading gracefully.+ const zipBuffer = Buffer.from(zipSync({+ "Doc.md": strToU8("body"),+ "Doc.md/child.txt": strToU8("child")+ }));++ await expect(testImportBuffer(zipBuffer, "import-name-collision")).rejects.toThrow("Cannot find parentNoteId for 'Doc.md/child.txt'");+ });++ it("aborts when a nested folder sits under such a colliding name", async () => {+ // Same collision, one level deeper: the failure now surfaces while creating the intermediate+ // folder note instead of while saving the leaf.+ const zipBuffer = Buffer.from(zipSync({+ "Nested.md": strToU8("body"),+ "Nested.md/sub/child.txt": strToU8("child")+ }));++ await expect(testImportBuffer(zipBuffer, "import-name-collision-nested")).rejects.toThrow("Missing parent note ID.");+ });++ it("restores a cloned note whose clone entry precedes its primary", async () => {+ // An export writes a clone as a stub entry carrying the same noteId as the primary. When the+ // stub is read first, its branch materialises a type-less skeleton note in becca; the primary+ // entry that follows must fill that skeleton in rather than being treated as an existing note.+ const sharedChild = { noteId: "clonedNote01", title: "Shared", type: "text", mime: "text/html", format: "html", attributes: [], attachments: [] };+ const metaFile = {+ formatVersion: 2,+ appVersion: "0.0.0",+ files: [{+ noteId: "cloneFolderB1",+ title: "Folder B",+ type: "text",+ mime: "text/html",+ format: "html",+ dataFileName: "Folder B.html",+ dirFileName: "Folder B",+ attributes: [],+ attachments: [],+ children: [{ ...sharedChild, isClone: true, dataFileName: "Shared.clone.html" }]+ }, {+ noteId: "cloneFolderA1",+ title: "Folder A",+ type: "text",+ mime: "text/html",+ format: "html",+ dataFileName: "Folder A.html",+ dirFileName: "Folder A",+ attributes: [],+ attachments: [],+ children: [{ ...sharedChild, dataFileName: "Shared.html" }]+ }]+ };++ const zipBuffer = await createZipBuffer({+ "!!!meta.json": JSON.stringify(metaFile),+ "Folder B.html": "<p>folder b</p>",+ "Folder B/Shared.clone.html": "<p>this is a clone</p>",+ "Folder A.html": "<p>folder a</p>",+ "Folder A/Shared.html": "<p>the real body</p>"+ });++ const { rootNote } = await testImportBuffer(zipBuffer, "import-clone-before-primary");+ const folderA = rootNote.getChildNotes().find((n) => n.title === "Folder A");+ const folderB = rootNote.getChildNotes().find((n) => n.title === "Folder B");+ const shared = folderA?.getChildNotes().find((n) => n.title === "Shared");++ // One note, cloned into both folders, carrying the primary entry's content and type.+ expect(shared?.type).toBe("text");+ expect(shared?.getContent().toString()).toContain("the real body");+ expect(folderB?.getChildNotes().map((n) => n.noteId)).toEqual([shared?.noteId]);+ expect(shared?.getParentNotes().map((n) => n.title).sort()).toEqual(["Folder A", "Folder B"]);+ });++ it("rejects a meta entry that declares no MIME type", async () => {+ const metaFile = {+ formatVersion: 2,+ appVersion: "0.0.0",+ files: [{ noteId: "noMime01", title: "No Mime", type: "text", dataFileName: "No Mime.html", attributes: [], attachments: [] }]+ };+ const zipBuffer = await createZipBuffer({ "!!!meta.json": JSON.stringify(metaFile), "No Mime.html": "<p>x</p>" });++ await expect(testImportBuffer(zipBuffer, "import-no-mime")).rejects.toThrow("Unable to resolve mime type.");+ });++ it("maps legacy 0.57-era note types onto their current names", async () => {+ const legacyTypes = [+ { noteId: "legacyRelMap1", title: "Legacy Rel Map", type: "relation-map", dataFileName: "Legacy Rel Map.json", expected: "relationMap" },+ { noteId: "legacyNoteMap", title: "Legacy Note Map", type: "note-map", dataFileName: "Legacy Note Map.json", expected: "noteMap" },+ { noteId: "legacyWebView", title: "Legacy Web View", type: "web-view", dataFileName: "Legacy Web View.html", expected: "webView" }+ ];+ const metaFile = {+ formatVersion: 2,+ appVersion: "0.0.0",+ files: legacyTypes.map(({ noteId, title, type, dataFileName }) => ({+ noteId, title, type, dataFileName, mime: "application/json", attributes: [], attachments: []+ }))+ };++ const zipBuffer = await createZipBuffer({+ "!!!meta.json": JSON.stringify(metaFile),+ "Legacy Rel Map.json": "{}",+ "Legacy Note Map.json": "{}",+ "Legacy Web View.html": "<p>x</p>"+ });++ const { rootNote } = await testImportBuffer(zipBuffer, "import-legacy-types");++ for (const { title, expected } of legacyTypes) {+ expect(rootNote.getChildNotes().find((n) => n.title === title)?.type).toBe(expected);+ }+ });+}, 60_000);++describe("attribute handling on import", () => {+ it("rewrites promoted-attribute definitions and drops unrecognized types", async () => {+ const metaFile = {+ formatVersion: 2,+ appVersion: "0.0.0",+ files: [{+ noteId: "attrHost0001",+ title: "Attr Host",+ type: "text",+ mime: "text/html",+ format: "html",+ dataFileName: "Attr Host.html",+ attachments: [],+ attributes: [+ { type: "label-definition", name: "priority", value: "promoted,single,text" },+ { type: "relation-definition", name: "assignee", value: "promoted,single" },+ { type: "nonsense", name: "bogus", value: "x" },+ { type: "relation", name: "internalLink", value: "attrHost0001" }+ ]+ }]+ };+ const zipBuffer = await createZipBuffer({ "!!!meta.json": JSON.stringify(metaFile), "Attr Host.html": "<p>x</p>" });++ const { importedNote } = await testImportBuffer(zipBuffer, "import-attr-definitions");+ const names = importedNote.getOwnedAttributes().map((a) => a.name);++ // Definitions are stored as `label:`/`relation:` labels ...+ expect(names).toContain("label:priority");+ expect(names).toContain("relation:assignee");+ // ... an unknown attribute type is refused ...+ expect(names).not.toContain("bogus");+ // ... and auto-generated link relations are left for the link scanner to recreate.+ expect(names).not.toContain("internalLink");+ });++ it("disables dangerous attributes and sanitizes attribute text on safe import", async () => {+ const metaFile = {+ formatVersion: 2,+ appVersion: "0.0.0",+ files: [{+ noteId: "safeAttrHost1",+ title: "Safe Attr Host",+ type: "text",+ mime: "text/html",+ format: "html",+ dataFileName: "Safe Attr Host.html",+ attachments: [],+ attributes: [+ { type: "label", name: "run", value: "frontendStartup" },+ { type: "label", name: "harmless", value: `<img src=x onerror="alert(1)">` }+ ]+ }]+ };+ const zipBuffer = await createZipBuffer({ "!!!meta.json": JSON.stringify(metaFile), "Safe Attr Host.html": "<p>x</p>" });++ const { importedNote } = await testImportBuffer(zipBuffer, "import-attr-safe", { textImportedAsText: true, safeImport: true });++ // `#run` triggers script execution, so safe import neuters it by renaming rather than dropping it.+ expect(importedNote.getOwnedLabelValue("disabled:run")).toBe("frontendStartup");+ expect(importedNote.getOwnedLabelValue("run")).toBeNull();+ expect(importedNote.getOwnedLabelValue("harmless")).not.toContain("onerror");+ });+}, 60_000);++describe("link and image rewriting on import", () => {+ /** A Trilium export of one HTML note that owns an image attachment and links to a sibling note. */+ function linkedMetaFile() {+ return {+ formatVersion: 2,+ appVersion: "0.0.0",+ files: [{+ noteId: "linkHost00001",+ title: "Link Host",+ type: "text",+ mime: "text/html",+ format: "html",+ dataFileName: "Link Host.html",+ dirFileName: "Link Host",+ attributes: [],+ attachments: [{+ attachmentId: "linkAttach001",+ title: "photo.png",+ role: "image",+ mime: "image/png",+ position: 10,+ dataFileName: "Link Host_photo.png"+ }],+ children: [{+ noteId: "linkSibling01",+ title: "Sibling",+ type: "text",+ mime: "text/html",+ format: "html",+ dataFileName: "Sibling.html",+ attributes: [],+ attachments: []+ }]+ }]+ };+ }++ it("rewrites relative src/href targets and leaves inline, absolute and undecodable ones alone", async () => {+ // The export writes an attachment out as a sibling of its owner's data file, so a "./"-prefixed+ // reference from "Link Host.html" resolves to it.+ const body = [+ `<img src="data:image/png;base64,AAAA">`,+ `<img src="https://example.com/remote.png">`,+ `<img src="./Link Host_photo.png">`,+ `<img src="%E0%A4%A">`,+ `<a href="Link Host/Sibling.html">sibling</a>`,+ `<a href="Link Host/Sibling.html/deeper">past the end of the metadata</a>`,+ `<a href="Link Host_photo.png">the photo</a>`,+ `<a href="#root/somewhere">anchor</a>`,+ `<a href="https://example.com/">remote</a>`,+ `<a href="%E0%A4%A">broken</a>`+ ].join("");++ const zipBuffer = await createZipBuffer({+ "!!!meta.json": JSON.stringify(linkedMetaFile()),+ "Link Host.html": body,+ "Link Host_photo.png": Buffer.from("fake png"),+ "Link Host/Sibling.html": "<p>sibling</p>"+ });++ const { importedNote } = await testImportBuffer(zipBuffer, "import-link-rewrite");+ const content = importedNote.getContent().toString();+ const sibling = importedNote.getChildNotes().find((n) => n.title === "Sibling");+ const attachmentId = importedNote.getAttachments().find((a) => a.title === "photo.png")?.attachmentId;++ // The inline data URI is deliberately skipped by the link rewriter and left for the note+ // service, which lifts it into an attachment of its own - so the note ends up owning one more+ // attachment than the archive declared.+ expect(content).not.toContain("data:image");+ expect(importedNote.getAttachments()).toHaveLength(2);+ // Absolute URLs and anchors are passed through untouched ...+ expect(content).toContain(`src="https://example.com/remote.png"`);+ expect(content).toContain(`href="#root/somewhere"`);+ expect(content).toContain(`href="https://example.com/"`);+ // ... a "./"-prefixed image resolves onto the attachment ...+ expect(content).toContain(`src="api/attachments/${attachmentId}/image/`);+ // ... links resolve onto the note and the attachment view respectively ...+ expect(content).toContain(`href="#root/${sibling?.noteId}"`);+ expect(content).toContain(`href="#root/${importedNote.noteId}?viewMode=attachments&attachmentId=${attachmentId}"`);+ // ... and a URL that cannot be percent-decoded is kept verbatim instead of throwing.+ expect(content).toContain(`src="%E0%A4%A"`);+ expect(content).toContain(`href="%E0%A4%A"`);+ // A link that walks past the end of the metadata still yields a note path rather than blowing up.+ expect(content).toContain(`href="#root/`);+ });++ it("remaps an includeNoteLink target inside the note's own content", async () => {+ const metaFile = {+ formatVersion: 2,+ appVersion: "0.0.0",+ files: [{+ noteId: "includeHost01",+ title: "Include Host",+ type: "text",+ mime: "text/html",+ format: "html",+ dataFileName: "Include Host.html",+ attachments: [],+ attributes: [{ type: "relation", name: "includeNoteLink", value: "includeTarget1" }]+ }, {+ noteId: "includeTarget1",+ title: "Included",+ type: "text",+ mime: "text/html",+ format: "html",+ dataFileName: "Included.html",+ attributes: [],+ attachments: []+ }]+ };+ const zipBuffer = await createZipBuffer({+ "!!!meta.json": JSON.stringify(metaFile),+ "Include Host.html": `<section class="include-note" data-note-id="includeTarget1"></section>`,+ "Included.html": "<p>included body</p>"+ });++ const { rootNote } = await testImportBuffer(zipBuffer, "import-include-note-link");+ const host = rootNote.getChildNotes().find((n) => n.title === "Include Host");+ const included = rootNote.getChildNotes().find((n) => n.title === "Included");++ // The embedded reference follows the target to its freshly generated id.+ const content = host?.getContent().toString() ?? "";+ expect(content).not.toContain("includeTarget1");+ expect(content).toContain(included?.noteId ?? "MISSING");+ });++ it("resolves a root-relative image path against the archive's single top-level folder", async () => {+ // Every entry sits under one top-level folder, so that folder is the archive root and a+ // "/"-prefixed src is resolved against it rather than against the entry's own directory.+ const zipBuffer = await createZipBuffer({+ "Export/photo.png": Buffer.from("fake png"),+ "Export/Doc.html": `<img src="/photo.png">`+ });++ const { rootNote } = await testImportBuffer(zipBuffer, "import-root-relative-src");+ const exportNote = rootNote.getChildNotes().find((n) => n.title === "Export");+ const photo = exportNote?.getChildNotes().find((n) => n.title === "photo.png");+ const doc = exportNote?.getChildNotes().find((n) => n.title === "Doc");++ expect(doc?.getContent().toString()).toContain(`src="api/images/${photo?.noteId}/photo.png"`);+ });++ it("drops an H1 that repeats the note title and demotes any other H1 to H2", async () => {+ const metaFile = {+ formatVersion: 2,+ appVersion: "0.0.0",+ files: [{+ noteId: "h1Host000001",+ title: "H1 Host",+ type: "text",+ mime: "text/html",+ format: "html",+ dataFileName: "H1 Host.html",+ attributes: [],+ attachments: []+ }]+ };+ const zipBuffer = await createZipBuffer({+ "!!!meta.json": JSON.stringify(metaFile),+ "H1 Host.html": "<h1>H1 Host</h1><h1>Another heading</h1><p>body</p>"+ });++ const { importedNote } = await testImportBuffer(zipBuffer, "import-h1");+ const content = importedNote.getContent().toString();++ expect(content).not.toContain("<h1>");+ expect(content).toContain("<h2>Another heading</h2>");+ });++ it("remaps relation map links onto the newly generated note ids", async () => {+ const metaFile = {+ formatVersion: 2,+ appVersion: "0.0.0",+ files: [{+ noteId: "relMapHost001",+ title: "Rel Map",+ type: "relationMap",+ mime: "application/json",+ dataFileName: "Rel Map.json",+ attachments: [],+ attributes: [{ type: "relation", name: "relationMapLink", value: "relMapTarget1" }]+ }, {+ noteId: "relMapTarget1",+ title: "Target",+ type: "text",+ mime: "text/html",+ format: "html",+ dataFileName: "Target.html",+ attributes: [],+ attachments: []+ }]+ };+ const zipBuffer = await createZipBuffer({+ "!!!meta.json": JSON.stringify(metaFile),+ "Rel Map.json": JSON.stringify({ notes: [{ noteId: "relMapTarget1", x: 1 }] }),+ "Target.html": "<p>target</p>"+ });++ const { rootNote } = await testImportBuffer(zipBuffer, "import-relation-map");+ const relMap = rootNote.getChildNotes().find((n) => n.title === "Rel Map");+ const target = rootNote.getChildNotes().find((n) => n.title === "Target");++ expect(relMap?.type).toBe("relationMap");+ const content = relMap?.getContent().toString() ?? "";+ expect(content).not.toContain("relMapTarget1");+ expect(content).toContain(target?.noteId ?? "MISSING");+ });++ it("rewrites relative links in a Markdown code note and leaves absolute ones alone", async () => {+ const body = [+ ``,+ ``,+ ``,+ ``,+ ``,+ `[att link](Md Host_photo.png)`,+ `[note link](Md Host/Sibling.md)`,+ `[remote link](https://example.com/)`,+ `[anchor](#section)`,+ `[already link](api/images/abc/x.png)`,+ `[broken link](%E0%A4%A)`+ ].join("\n\n");++ const metaFile = {+ formatVersion: 2,+ appVersion: "0.0.0",+ files: [{+ noteId: "mdHost000001",+ title: "Md Host",+ type: "code",+ mime: "text/x-markdown",+ dataFileName: "Md Host.md",+ dirFileName: "Md Host",+ attributes: [],+ attachments: [{+ attachmentId: "mdAttach0001",+ title: "photo.png",+ role: "image",+ mime: "image/png",+ position: 10,+ dataFileName: "Md Host_photo.png"+ }],+ children: [{+ noteId: "mdSibling0001",+ title: "Sibling",+ type: "code",+ mime: "text/x-markdown",+ dataFileName: "Sibling.md",+ attributes: [],+ attachments: []+ }]+ }]+ };++ const zipBuffer = await createZipBuffer({+ "!!!meta.json": JSON.stringify(metaFile),+ "Md Host.md": body,+ "Md Host_photo.png": Buffer.from("fake png"),+ "Md Host/Sibling.md": "sibling body"+ });++ const { importedNote } = await testImportBuffer(zipBuffer, "import-md-links");+ const content = importedNote.getContent().toString();+ const sibling = importedNote.getChildNotes().find((n) => n.title === "Sibling");+ const attachmentId = importedNote.getAttachments()[0]?.attachmentId;++ // Images: attachment target, note target, and the three that must survive untouched.+ expect(content).toContain(``);+ expect(content).toContain(``);+ expect(content).toContain(``);+ expect(content).toContain(``);+ expect(content).toContain(``);+ // Non-image links get the note-path treatment instead.+ expect(content).toContain(`[att link](#root/${importedNote.noteId}?viewMode=attachments&attachmentId=${attachmentId})`);+ expect(content).toContain(`[note link](#root/${sibling?.noteId})`);+ expect(content).toContain(`[remote link](https://example.com/)`);+ expect(content).toContain(`[anchor](#section)`);+ expect(content).toContain(`[already link](api/images/abc/x.png)`);+ expect(content).toContain(`[broken link](%E0%A4%A)`);+ });}, 60_000);/** Parses a spreadsheet note's content and returns its single (first) sheet's data. */diff --git a/packages/trilium-core/src/services/import/zip.ts b/packages/trilium-core/src/services/import/zip.tsindex 6bf3c3689d..5c1514616e 100644--- a/packages/trilium-core/src/services/import/zip.ts+++ b/packages/trilium-core/src/services/import/zip.ts@@ -415,6 +415,7 @@ async function importZip(taskContext: TaskContext<"importNotes">, source: ZipSou} else if (target.noteId) {return `src="api/images/${target.noteId}/${basename(url)}"`;}+ /* v8 ignore next -- unreachable: getEntityIdFromRelativeUrl always yields a noteId; kept so the callback returns a string on every path */return match;});@@ -441,6 +442,7 @@ async function importZip(taskContext: TaskContext<"importNotes">, source: ZipSou} else if (target.noteId) {return `href="#root/${target.noteId}"`;}+ /* v8 ignore next -- unreachable: getEntityIdFromRelativeUrl always yields a noteId; kept so the callback returns a string on every path */return match;});@@ -518,6 +520,7 @@ async function importZip(taskContext: TaskContext<"importNotes">, source: ZipSou} else if (target.noteId) {return `})`;}+ /* v8 ignore next -- unreachable: getEntityIdFromRelativeUrl always yields a noteId; kept so the callback returns a string on every path */return match;});@@ -540,6 +543,7 @@ async function importZip(taskContext: TaskContext<"importNotes">, source: ZipSou} else if (target.noteId) {return `[${text}](#root/${target.noteId})`;}+ /* v8 ignore next -- unreachable: getEntityIdFromRelativeUrl always yields a noteId; kept so the callback returns a string on every path */return match;});