Skip to content

Build your personal knowledge base with Trilium Notes

test(import): cover Keep and Notion import business logic

Elian Dorane9ea5a5784f0
diff --git a/packages/trilium-core/src/services/import/keep/converter.spec.ts b/packages/trilium-core/src/services/import/keep/converter.spec.ts
index 3911721f2e..20793a3c38 100644
--- a/packages/trilium-core/src/services/import/keep/converter.spec.ts
+++ b/packages/trilium-core/src/services/import/keep/converter.spec.ts
@@ -37,6 +37,14 @@ describe("Google Keep converter — convertKeepHtml", () => {
it("unwraps a plain span entirely, keeping only its text", () => {
expect(convertKeepHtml(`<p>${span("plain", "font-weight:400;")}</p>`)).toBe("<p>plain</p>");
});
+
+ it("treats the `font-weight:bold` keyword (no numeric weight) as bold", () => {
+ expect(convertKeepHtml(`<p>${span("bold keyword", "font-weight:bold;")}</p>`)).toBe("<p><strong>bold keyword</strong></p>");
+ });
+
+ it("unwraps a span that has no style attribute at all", () => {
+ expect(convertKeepHtml(`<p><span>no style</span></p>`)).toBe("<p>no style</p>");
+ });
});
describe("Google Keep converter — convertKeepHtmlInline", () => {
@@ -51,4 +59,12 @@ describe("Google Keep converter — convertKeepHtmlInline", () => {
expect(convertKeepHtmlInline(html)).toBe("<strong>done</strong>");
});
+
+ it("falls back to the cleaned markup when the fragment is not a single element", () => {
+ const html =
+ `<p dir="ltr" style="line-height:1.38;">${span("first", "font-weight:400;")}</p>` +
+ `<p dir="ltr" style="line-height:1.38;">${span("second", "font-weight:700;")}</p>`;
+
+ expect(convertKeepHtmlInline(html)).toBe("<p>first</p><p><strong>second</strong></p>");
+ });
});
diff --git a/packages/trilium-core/src/services/import/keep/importer.integration.spec.ts b/packages/trilium-core/src/services/import/keep/importer.integration.spec.ts
index 5dd4495909..19165828ce 100644
--- a/packages/trilium-core/src/services/import/keep/importer.integration.spec.ts
+++ b/packages/trilium-core/src/services/import/keep/importer.integration.spec.ts
@@ -23,17 +23,23 @@ async function createZipBuffer(files: Record<string, string | Buffer>): Promise<
}
/** Runs the Keep importer over `files` and returns the single imported note (child of the import root). */
-async function importSingleNote(files: Record<string, string>): Promise<BNote> {
+async function importSingleNote(files: Record<string, string | Buffer>): Promise<BNote> {
+ const [note] = await importNotes(files);
+
+ return note;
+}
+
+/** Runs the Keep importer over `files` and returns every imported note (children of the import root). */
+async function importNotes(files: Record<string, string | Buffer>): Promise<BNote[]> {
const buffer = await createZipBuffer(files);
const taskContext = TaskContext.getInstance("keep-integration", "importNotes", { safeImport: true });
- return new Promise<BNote>((resolve, reject) => {
+ return new Promise<BNote[]>((resolve, reject) => {
void getContext().init(async () => {
try {
const root = becca.getNoteOrThrow("root");
const importRoot = await keepImporter.importKeep(taskContext, new Uint8Array(buffer), root);
- const [note] = importRoot.getChildNotes();
- resolve(note);
+ resolve(importRoot.getChildNotes());
} catch (e) {
reject(e);
}
@@ -71,4 +77,49 @@ describe("Google Keep importer — integration", () => {
expect(note.utcDateCreated).toBe("2026-06-21 08:14:14.353Z");
expect(note.utcDateModified).toBe("2026-06-21 08:14:14.353Z");
});
+
+ it("falls the modification date back to the creation date when only the former is present", async () => {
+ const note = await importSingleNote({
+ "Takeout/Keep/note.json": JSON.stringify({
+ title: "Created only",
+ textContent: "hi",
+ createdTimestampUsec: 1763069966429000 // 2025-11-13 21:39:26.429Z
+ })
+ });
+
+ // No modified timestamp: the creation date is used for both.
+ expect(note.utcDateCreated).toBe("2025-11-13 21:39:26.429Z");
+ expect(note.utcDateModified).toBe("2025-11-13 21:39:26.429Z");
+ });
+
+ it("imports only the .json notes, skipping the redundant .html/.txt and Labels.txt entries", async () => {
+ const notes = await importNotes({
+ "Takeout/Keep/note.json": JSON.stringify({ title: "Real note", textContent: "hi" }),
+ "Takeout/Keep/note.html": "<html><body>redundant</body></html>",
+ "Takeout/Keep/note.txt": "redundant plain text",
+ "Takeout/Keep/Labels.txt": "Shopping\nWork",
+ "Takeout/Keep/sub/": Buffer.alloc(0)
+ });
+
+ expect(notes).toHaveLength(1);
+ expect(notes[0].title).toBe("Real note");
+ });
+
+ it("skips a malformed .json entry without failing the import", async () => {
+ const notes = await importNotes({
+ "Takeout/Keep/good.json": JSON.stringify({ title: "Good", textContent: "hi" }),
+ "Takeout/Keep/bad.json": "{ not valid json"
+ });
+
+ expect(notes).toHaveLength(1);
+ expect(notes[0].title).toBe("Good");
+ });
+
+ it("applies the Keep palette colour as a #color label on the imported note", async () => {
+ const note = await importSingleNote({
+ "Takeout/Keep/note.json": JSON.stringify({ title: "Green note", textContent: "hi", color: "GREEN" })
+ });
+
+ expect(note.getOwnedLabelValue("color")).toBe("#95d641");
+ });
});
diff --git a/packages/trilium-core/src/services/import/keep/importer.spec.ts b/packages/trilium-core/src/services/import/keep/importer.spec.ts
index f2e7a41fdc..e2dea44f45 100644
--- a/packages/trilium-core/src/services/import/keep/importer.spec.ts
+++ b/packages/trilium-core/src/services/import/keep/importer.spec.ts
@@ -137,4 +137,41 @@ describe("Google Keep importer — parseNote", () => {
it("skips a malformed JSON entry rather than throwing", () => {
expect(parseNote("broken.json", "{ not valid json")).toBeNull();
});
+
+ it("leaves the date undefined when the timestamp overflows to an Invalid Date", () => {
+ // A timestamp so large that new Date(usec / 1000) is an Invalid Date (NaN time).
+ const note = parseNote("n.json", JSON.stringify({ createdTimestampUsec: 9e18 }));
+
+ expect(note?.utcDateCreated).toBeUndefined();
+ });
+
+ it("falls back to \"Untitled\" when an untitled note's filename strips to empty", () => {
+ const note = parseNote(".json", JSON.stringify({}));
+
+ expect(note?.title).toBe("Untitled");
+ });
+
+ it("yields empty content when a checklist has only empty/filtered-out items", () => {
+ const note = parseNote("list.json", JSON.stringify({ listContent: [{ text: "" }] }));
+
+ expect(note?.content).toBe("");
+ });
+
+ it("renders a checklist mixing a rich-text item and a plain-text item", () => {
+ const json = JSON.stringify({
+ listContent: [
+ { textHtml: `<p><span style="font-weight:700;">rich</span></p>`, isChecked: false },
+ { text: "plain", isChecked: true }
+ ]
+ });
+
+ const note = parseNote("list.json", json);
+
+ expect(note?.content).toBe(
+ `<ul class="todo-list">` +
+ `<li><label class="todo-list__label"><input type="checkbox" disabled="disabled"><span class="todo-list__label__description"><strong>rich</strong></span></label></li>` +
+ `<li><label class="todo-list__label"><input type="checkbox" checked="checked" disabled="disabled"><span class="todo-list__label__description">plain</span></label></li>` +
+ `</ul>`
+ );
+ });
});
diff --git a/packages/trilium-core/src/services/import/keep/importer.ts b/packages/trilium-core/src/services/import/keep/importer.ts
index 23c096568b..ed04cb4965 100644
--- a/packages/trilium-core/src/services/import/keep/importer.ts
+++ b/packages/trilium-core/src/services/import/keep/importer.ts
@@ -122,6 +122,9 @@ function buildContent(note: KeepNote): string {
.map((item) => {
// Match the canonical CKEditor task-list serialization (checked before disabled).
const attributes = item.isChecked ? ` checked="checked" disabled="disabled"` : ` disabled="disabled"`;
+ // The `?? ""` fallback is unreachable: items with neither `text` nor `textHtml` are removed by
+ // the filter above, so reaching the `escapeHtml` branch (textHtml falsy) implies `text` is set.
+ /* v8 ignore next */
const label = item.textHtml ? convertKeepHtmlInline(item.textHtml) : escapeHtml(item.text ?? "");
return `<li><label class="todo-list__label"><input type="checkbox"${attributes}><span class="todo-list__label__description">${label}</span></label></li>`;
});
@@ -147,6 +150,9 @@ function buildContent(note: KeepNote): string {
* every note is parented directly under that root. Returns the root.
*/
function createNotes(importRootNote: BNote, notes: ParsedNote[], taskContext: TaskContext<"importNotes">): BNote {
+ // The protected-session branch requires importing into a protected root with an active protected session,
+ // which the import harness/tests don't exercise.
+ /* v8 ignore next */
const isProtected = importRootNote.isProtected && protectedSessionService.isProtectedSessionAvailable();
const rootNote = noteService.createNewNote({ parentNoteId: importRootNote.noteId, title: t("keep_import.root-title"), content: "", type: "text", mime: "text/html", isProtected }).note;
@@ -236,6 +242,9 @@ function isDirectory(path: string): boolean {
}
function baseName(path: string): string {
+ // The `?? path` fallback is unreachable: String.prototype.split always returns a non-empty array, so
+ // `pop()` here is at worst "" (never undefined).
+ /* v8 ignore next */
return path.split("/").pop() ?? path;
}
diff --git a/packages/trilium-core/src/services/import/notion/converter.spec.ts b/packages/trilium-core/src/services/import/notion/converter.spec.ts
index c061985084..ab6bcc5a70 100644
--- a/packages/trilium-core/src/services/import/notion/converter.spec.ts
+++ b/packages/trilium-core/src/services/import/notion/converter.spec.ts
@@ -109,6 +109,13 @@ describe("convertNotionHtml — toggles", () => {
);
});
+ it("appends the collapsible class to a <details> that already has a class", () => {
+ const input = `<ul class="toggle"><li><details class="existing"><summary>Title</summary></details></li></ul>`;
+ expect(convertNotionHtml(input)).toBe(
+ `<details class="existing trilium-collapsible"><summary>Title</summary></details>`
+ );
+ });
+
it("keeps a nested toggle nested rather than flattening it", () => {
const input = `<ul class="toggle"><li><details open=""><summary>Outer</summary><div style="display:contents"><ul class="toggle"><li><details open=""><summary>Inner</summary></details></li></ul></div></details></li></ul>`;
expect(convertNotionHtml(input)).toBe(
@@ -290,3 +297,115 @@ describe("convertNotionHtml — date mentions", () => {
expect(convertNotionHtml(`<p><time>June 21, 2026</time></p>`)).toBe(`<p><time>June 21, 2026</time></p>`);
});
});
+
+describe("convertNotionHtml — math edge cases", () => {
+ it("leaves an inline equation token with no annotation alone (no math-tex span)", () => {
+ const input = `<p><span class="notion-text-equation-token"><span class="katex"><span class="katex-html">e=mc2</span></span></span></p>`;
+ const output = convertNotionHtml(input);
+ expect(output).not.toContain("math-tex");
+ expect(output).toBe(input);
+ });
+
+ it("leaves a block equation figure with no annotation alone (no math-tex figure)", () => {
+ const input = `<figure class="equation"><div class="equation-container"><span class="katex-display"><span class="katex"><span class="katex-html">e=mc2</span></span></span></div></figure>`;
+ const output = convertNotionHtml(input);
+ expect(output).not.toContain("math-tex");
+ expect(output).toBe(input);
+ });
+
+ it("falls back to the first annotation when none is encoded as application/x-tex", () => {
+ const input = `<p><span class="notion-text-equation-token"><span class="katex"><math><semantics><annotation encoding="application/x-llamapun">e = mc^2</annotation></semantics></math></span></span></p>`;
+ expect(convertNotionHtml(input)).toBe(`<p><span class="math-tex">\\(e = mc^2\\)</span></p>`);
+ });
+});
+
+describe("convertNotionHtml — to-do edge cases", () => {
+ it("does not merge to-do items separated by a non-whitespace text node", () => {
+ const wrap = (text: string) => `<ul class="to-do-list"><li><div class="checkbox checkbox-off"></div> <span class="to-do-children-unchecked">${text}</span></li></ul>`;
+ const list = (text: string) => `<ul class="todo-list"><li><label class="todo-list__label"><input type="checkbox" disabled="disabled"><span class="todo-list__label__description">${text}</span></label></li></ul>`;
+ const input = `${wrap("A")}separator${wrap("B")}`;
+ expect(convertNotionHtml(input)).toBe(`${list("A")}separator${list("B")}`);
+ });
+
+ it("merges to-do items separated only by whitespace text nodes", () => {
+ const wrap = (text: string) => `<ul class="to-do-list"><li><div class="checkbox checkbox-off"></div> <span class="to-do-children-unchecked">${text}</span></li></ul>`;
+ const item = (text: string) => `<li><label class="todo-list__label"><input type="checkbox" disabled="disabled"><span class="todo-list__label__description">${text}</span></label></li>`;
+ const input = `${wrap("A")}\n \n${wrap("B")}`;
+ // Whitespace between the wrappers does not break the run, so both items merge into one list.
+ expect(convertNotionHtml(input)).toContain(`<ul class="todo-list">${item("A")}${item("B")}</ul>`);
+ });
+
+ it("defaults to unchecked and an empty label when the checkbox and label spans are missing", () => {
+ const input = `<ul class="to-do-list"><li></li></ul>`;
+ expect(convertNotionHtml(input)).toBe(
+ `<ul class="todo-list"><li><label class="todo-list__label"><input type="checkbox" disabled="disabled"><span class="todo-list__label__description"></span></label></li></ul>`
+ );
+ });
+
+ it("builds an item without a checkbox div but with a label span", () => {
+ const input = `<ul class="to-do-list"><li><span class="to-do-children-unchecked">No checkbox</span></li></ul>`;
+ expect(convertNotionHtml(input)).toBe(
+ `<ul class="todo-list"><li><label class="todo-list__label"><input type="checkbox" disabled="disabled"><span class="todo-list__label__description">No checkbox</span></label></li></ul>`
+ );
+ });
+});
+
+describe("convertNotionHtml — images edge cases", () => {
+ it("leaves an image figure with no <img> inside untouched", () => {
+ const input = `<figure class="image"><figcaption>No image here</figcaption></figure>`;
+ expect(convertNotionHtml(input)).toBe(input);
+ });
+});
+
+describe("convertNotionHtml — code block edge cases", () => {
+ it("leaves a <pre> with no <code> inside untouched (apart from id/class)", () => {
+ const input = `<pre class="code">plain text, no code element</pre>`;
+ expect(convertNotionHtml(input)).toBe(input);
+ });
+});
+
+describe("convertNotionHtml — callout edge cases", () => {
+ it("falls back to the last div for content when no width:100% div is present and there is no icon div", () => {
+ // With no icon div the emoji is empty, which is not the default light-bulb, so it maps to a note;
+ // an empty emoji means nothing is prepended to the content.
+ const input = `<figure class="callout"><div>Just the body, no icon div.</div></figure>`;
+ expect(convertNotionHtml(input)).toBe(`<aside class="admonition note">Just the body, no icon div.</aside>`);
+ });
+
+ it("produces an empty admonition when the callout has no div children at all", () => {
+ const input = `<figure class="callout"><span class="icon">💡</span></figure>`;
+ expect(convertNotionHtml(input)).toBe(`<aside class="admonition note"></aside>`);
+ });
+
+ it("maps a callout with an empty icon to a tip (empty emoji is not the default light-bulb but nothing is prepended)", () => {
+ const input = `<figure class="callout"><div style="font-size:1.5em"><span class="icon"></span></div><div style="width:100%"><p>Body</p></div></figure>`;
+ expect(convertNotionHtml(input)).toBe(`<aside class="admonition note"><p>Body</p></aside>`);
+ });
+});
+
+describe("convertNotionHtml — color edge cases", () => {
+ it("unwraps a default highlight mark to plain inner HTML", () => {
+ expect(convertNotionHtml(`<p><mark class="highlight-default">Plain <strong>text</strong></mark></p>`)).toBe(
+ `<p>Plain <strong>text</strong></p>`
+ );
+ });
+
+ it("unwraps a mark whose class is not a recognized highlight class", () => {
+ expect(convertNotionHtml(`<p><mark class="something-else">Body</mark></p>`)).toBe(`<p>Body</p>`);
+ });
+
+ it("unwraps a mark with no class attribute at all", () => {
+ expect(convertNotionHtml(`<p><mark>Body</mark></p>`)).toBe(`<p>Body</p>`);
+ });
+
+ it("unwraps a mark with an unknown color name not in the palette", () => {
+ expect(convertNotionHtml(`<p><mark class="highlight-chartreuse">Body</mark></p>`)).toBe(`<p>Body</p>`);
+ });
+});
+
+describe("convertNotionHtml — link-to-page edge cases", () => {
+ it("leaves a link-to-page figure with no anchor untouched", () => {
+ const input = `<figure class="link-to-page"><span>No link here</span></figure>`;
+ expect(convertNotionHtml(input)).toBe(input);
+ });
+});
diff --git a/packages/trilium-core/src/services/import/notion/converter.ts b/packages/trilium-core/src/services/import/notion/converter.ts
index 75afff9cc8..cae398d504 100644
--- a/packages/trilium-core/src/services/import/notion/converter.ts
+++ b/packages/trilium-core/src/services/import/notion/converter.ts
@@ -417,6 +417,7 @@ function convertBookmarks(root: HTMLElement) {
}
const section = parse(`<section></section>`).querySelector("section");
+ /* v8 ignore next 3 -- defensive: parsing a literal "<section>" always yields a matching element */
if (!section) {
continue;
}
@@ -499,9 +500,11 @@ function markStyle(className: string): string | undefined {
/** Blends an `rgba(r, g, b, a)` color over a white page into an opaque `rgb(r, g, b)` the sanitizer accepts. */
function flattenOverWhite(rgba: string): string {
const match = rgba.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*([\d.]+)\s*)?\)/);
+ /* v8 ignore next 3 -- unreachable: only fed well-formed rgba() values from the inlined Notion palette */
if (!match) {
return rgba;
}
+ /* v8 ignore next -- the Notion palette always specifies an alpha, so the no-alpha branch is unreachable */
const alpha = match[4] === undefined ? 1 : Number(match[4]);
const blend = (channel: string) => Math.round(Number(channel) * alpha + 255 * (1 - alpha));
return `rgb(${blend(match[1])}, ${blend(match[2])}, ${blend(match[3])})`;
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.ts
index 1a86a7766b..018ba7521d 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
@@ -115,4 +115,281 @@ describe("Notion importer — integration", () => {
expect(importRoot.getChildNotes().map((note) => note.title)).toContain("Deep page");
});
+
+ it("stops descending into nested zips past the depth limit, keeping the innermost as a resource", async () => {
+ // depth 0: outer.zip; depth 1: middle.zip; depth 2: innermost.zip — the innermost is at the limit
+ // and is kept as a plain resource rather than recursed into, so its page is never imported.
+ const innermost = await createZipBuffer({ "Buried 386c5eca1b8b80439520cad27a0d2749.html": pageHtml("Buried page") });
+ const middle = await createZipBuffer({ "Export-Part-1.zip": innermost });
+ const outer = await createZipBuffer({ "Export.zip": middle });
+ const importRoot = await importNotion({ "Outer.zip": outer });
+
+ expect(importRoot.getChildNotes().map((note) => note.title)).not.toContain("Buried page");
+ });
+
+ it("skips an explicit directory entry in the zip", async () => {
+ const archive = new ZipArchive();
+ const chunks: Buffer[] = [];
+ const passthrough = new PassThrough();
+ passthrough.on("data", (chunk: Buffer) => chunks.push(chunk));
+ archive.pipe(passthrough);
+ archive.append(Buffer.alloc(0), { name: "Folder/" });
+ archive.append(pageHtml("Inside", "2c6c5eca1b8b80f7b9eaf4f396b755dc"), { name: "Folder/Inside 2c6c5eca1b8b80f7b9eaf4f396b755dc.html" });
+ await archive.finalize();
+ const buffer = Buffer.concat(chunks);
+
+ const taskContext = TaskContext.getInstance("notion-dir-entry", "importNotes", { safeImport: true });
+ const importRoot = await new Promise<BNote>((resolve, reject) => {
+ void getContext().init(async () => {
+ try {
+ resolve(await notionImporter.importNotion(taskContext, new Uint8Array(buffer), becca.getNoteOrThrow("root")));
+ } catch (e) {
+ reject(e);
+ }
+ });
+ });
+
+ // The directory entry is skipped; only the real page is imported.
+ expect(importRoot.getChildNotes().map((note) => note.title)).toEqual(["Inside"]);
+ });
+
+ it("skips index.html without creating a note for it", async () => {
+ const importRoot = await importNotion({
+ "index.html": `<html><head><title>Index</title></head><body><div id="386c5eca1b8b80439520cad27a0d2749"><div class="page-body"><p>toc</p></div></div></body></html>`,
+ "Real page 2c6c5eca1b8b80f7b9eaf4f396b755dc.html": pageHtml("Real page", "2c6c5eca1b8b80f7b9eaf4f396b755dc")
+ });
+
+ expect(importRoot.getChildNotes().map((note) => note.title)).toEqual(["Real page"]);
+ });
+
+ it("drops a page with no resolvable id (no body id, no id in filename)", async () => {
+ const importRoot = await importNotion({
+ "Notes.html": `<html><head><title>Notes</title></head><body><div class="page"><div class="page-body"><p>x</p></div></div></body></html>`,
+ "Real page 2c6c5eca1b8b80f7b9eaf4f396b755dc.html": pageHtml("Real page", "2c6c5eca1b8b80f7b9eaf4f396b755dc")
+ });
+
+ expect(importRoot.getChildNotes().map((note) => note.title)).toEqual(["Real page"]);
+ });
+
+ it("falls back to the filename for the title when the page has no <title> tag", async () => {
+ const importRoot = await importNotion({
+ "My filename title 2c6c5eca1b8b80f7b9eaf4f396b755dc.html":
+ `<html><head></head><body><div id="2c6c5eca1b8b80f7b9eaf4f396b755dc"><div class="page-body"><p>x</p></div></div></body></html>`
+ });
+
+ expect(importRoot.getChildNotes().map((note) => note.title)).toEqual(["My filename title"]);
+ });
+
+ it("falls back to 'Untitled' when there is no <title> and the filename is only an id", async () => {
+ const importRoot = await importNotion({
+ "2c6c5eca1b8b80f7b9eaf4f396b755dc.html":
+ `<html><head></head><body><div id="2c6c5eca1b8b80f7b9eaf4f396b755dc"><div class="page-body"><p>x</p></div></div></body></html>`
+ });
+
+ expect(importRoot.getChildNotes().map((note) => note.title)).toEqual(["Untitled"]);
+ });
+
+ it("imports an empty content note when the page has no .page-body", async () => {
+ const importRoot = await importNotion({
+ "Empty 2c6c5eca1b8b80f7b9eaf4f396b755dc.html":
+ `<html><head><title>Empty</title></head><body><div id="2c6c5eca1b8b80f7b9eaf4f396b755dc"><p>no page-body wrapper</p></div></body></html>`
+ });
+
+ const empty = importRoot.getChildNotes().find((note) => note.title === "Empty");
+ expect(empty?.getContent()).toBe("");
+ });
+
+ it("rewrites a cross-page link to the linked note as a reference link", async () => {
+ const idA = "11111111111111111111111111111111";
+ const idB = "22222222222222222222222222222222";
+ const importRoot = await importNotion({
+ [`Page A ${idA}.html`]:
+ `<html><head><title>Page A</title></head><body><div id="${idA}"><div class="page-body"><p><a href="Page B ${idB}.html">Page B</a></p></div></div></body></html>`,
+ [`Page B ${idB}.html`]: pageHtml("Page B", idB)
+ });
+
+ const pageA = importRoot.getChildNotes().find((note) => note.title === "Page A");
+ const pageB = importRoot.getChildNotes().find((note) => note.title === "Page B");
+ if (!pageA || !pageB) {
+ throw new Error("expected both pages imported");
+ }
+ expect(pageA.getContent()).toContain(`href="#root/${pageB.noteId}"`);
+ expect(pageA.getContent()).toContain(`class="reference-link"`);
+ });
+
+ it("leaves a cross-page link to a page that wasn't imported untouched", async () => {
+ const idA = "11111111111111111111111111111111";
+ const missingId = "99999999999999999999999999999999";
+ const importRoot = await importNotion({
+ [`Page A ${idA}.html`]:
+ `<html><head><title>Page A</title></head><body><div id="${idA}"><div class="page-body"><p><a href="Ghost ${missingId}.html">Ghost</a></p></div></div></body></html>`
+ });
+
+ const pageA = importRoot.getChildNotes().find((note) => note.title === "Page A");
+ expect(pageA?.getContent()).toContain(`href="Ghost ${missingId}.html"`);
+ });
+
+ it("applies a page's single timestamp to both created and modified dates", async () => {
+ const id = "2c6c5eca1b8b80f7b9eaf4f396b755dc";
+ // Only a created_time row is present; the modified date should fall back to it.
+ const propertyTable =
+ `<table class="properties"><tbody>` +
+ `<tr class="property-row property-row-created_time"><th>Created</th><td><time>2024-01-02T03:04:05Z</time></td></tr>` +
+ `</tbody></table>`;
+ const importRoot = await importNotion({
+ "OneDate 2c6c5eca1b8b80f7b9eaf4f396b755dc.html":
+ `<html><head><title>OneDate</title></head><body><div id="${id}">${propertyTable}<div class="page-body"><p>x</p></div></div></body></html>`
+ });
+
+ const note = importRoot.getChildNotes().find((n) => n.title === "OneDate");
+ expect(note?.utcDateCreated).toBe("2024-01-02 03:04:05.000Z");
+ expect(note?.utcDateModified).toBe("2024-01-02 03:04:05.000Z");
+ });
+
+ it("uses a page's only last-edited timestamp for its creation date too", async () => {
+ const id = "2c6c5eca1b8b80f7b9eaf4f396b755dc";
+ // Only a last_edited_time row is present; the created date should fall back to it.
+ const propertyTable =
+ `<table class="properties"><tbody>` +
+ `<tr class="property-row property-row-last_edited_time"><th>Edited</th><td><time>2024-05-06T07:08:09Z</time></td></tr>` +
+ `</tbody></table>`;
+ const importRoot = await importNotion({
+ "EditedOnly 2c6c5eca1b8b80f7b9eaf4f396b755dc.html":
+ `<html><head><title>EditedOnly</title></head><body><div id="${id}">${propertyTable}<div class="page-body"><p>x</p></div></div></body></html>`
+ });
+
+ const note = importRoot.getChildNotes().find((n) => n.title === "EditedOnly");
+ expect(note?.utcDateCreated).toBe("2024-05-06 07:08:09.000Z");
+ expect(note?.utcDateModified).toBe("2024-05-06 07:08:09.000Z");
+ });
+
+ it("falls back to the file basename for an attachment anchor that has no href", async () => {
+ const id = "2c6c5eca1b8b80f7b9eaf4f396b755dc";
+ // The converter marks any <figure><div class="source"><a>…</a> as a notion-attachment, even when
+ // the anchor carries no href; the importer then resolves an empty path (no bundled file).
+ const figure = `<figure id="aaa"><div class="source"><a>orphan</a></div></figure>`;
+ const importRoot = await importNotion({
+ "NoHref 2c6c5eca1b8b80f7b9eaf4f396b755dc.html":
+ `<html><head><title>NoHref</title></head><body><div id="${id}"><div class="page-body"><div style="display:contents" dir="ltr">${figure}</div></div></div></body></html>`
+ });
+
+ const note = importRoot.getChildNotes().find((n) => n.title === "NoHref");
+ // No bundled file resolved, so the anchor loses its marker class and stays a plain link.
+ expect(note?.getContent()).not.toContain("notion-attachment");
+ expect(note?.getAttachmentsByRole("file")).toHaveLength(0);
+ });
+
+ it("preserves Notion's created/last-edited timestamps from the property table", async () => {
+ const id = "2c6c5eca1b8b80f7b9eaf4f396b755dc";
+ const propertyTable =
+ `<table class="properties"><tbody>` +
+ `<tr class="property-row property-row-created_time"><th>Created</th><td><time>2024-01-02T03:04:05Z</time></td></tr>` +
+ `<tr class="property-row property-row-last_edited_time"><th>Edited</th><td><time>2024-05-06T07:08:09Z</time></td></tr>` +
+ `</tbody></table>`;
+ const importRoot = await importNotion({
+ "Dated 2c6c5eca1b8b80f7b9eaf4f396b755dc.html":
+ `<html><head><title>Dated</title></head><body><div id="${id}">${propertyTable}<div class="page-body"><p>x</p></div></div></body></html>`
+ });
+
+ const dated = importRoot.getChildNotes().find((note) => note.title === "Dated");
+ expect(dated?.utcDateCreated).toBe("2024-01-02 03:04:05.000Z");
+ expect(dated?.utcDateModified).toBe("2024-05-06 07:08:09.000Z");
+ });
+
+ it("ignores property-row dates that are blank or unparseable", async () => {
+ const id = "2c6c5eca1b8b80f7b9eaf4f396b755dc";
+ const propertyTable =
+ `<table class="properties"><tbody>` +
+ `<tr class="property-row property-row-created_time"><th>Created</th><td><time></time></td></tr>` +
+ `<tr class="property-row property-row-last_edited_time"><th>Edited</th><td><time>not a date</time></td></tr>` +
+ `</tbody></table>`;
+ const importRoot = await importNotion({
+ "Undated 2c6c5eca1b8b80f7b9eaf4f396b755dc.html":
+ `<html><head><title>Undated</title></head><body><div id="${id}">${propertyTable}<div class="page-body"><p>x</p></div></div></body></html>`
+ });
+
+ // No timestamps were applied, so the note keeps a fresh (recent) creation date, not 2024.
+ const undated = importRoot.getChildNotes().find((note) => note.title === "Undated");
+ expect(undated?.utcDateCreated.startsWith("2024-01-02")).toBe(false);
+ });
+
+ it("saves a bundled image as an attachment and rewrites its src; leaves external/srcless images alone", async () => {
+ const id = "2c6c5eca1b8b80f7b9eaf4f396b755dc";
+ const pngBytes = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
+ const body =
+ `<div class="page-body">` +
+ `<figure class="image"><img src="pic.png"></figure>` +
+ `<figure class="image"><img></figure>` +
+ `<figure class="image"><img src="https://external/x.png"></figure>` +
+ `</div>`;
+ const importRoot = await importNotion({
+ "Img 2c6c5eca1b8b80f7b9eaf4f396b755dc.html":
+ `<html><head><title>Img</title></head><body><div id="${id}">${body}</div></body></html>`,
+ "pic.png": pngBytes
+ });
+
+ const note = importRoot.getChildNotes().find((n) => n.title === "Img");
+ if (!note) {
+ throw new Error("expected 'Img' page imported");
+ }
+ const attachment = note.getAttachments().find((a) => a.role === "image");
+ expect(attachment).toBeDefined();
+ expect(note.getContent()).toContain("api/attachments/");
+ expect(note.getContent()).toContain("https://external/x.png");
+ });
+
+ it("handles attachment edge cases: missing file, empty text, unknown extension", async () => {
+ const id = "2c6c5eca1b8b80f7b9eaf4f396b755dc";
+ // The converter turns <figure><div class="source"><a href=…>…</a></div></figure> into a
+ // notion-attachment anchor. Three figures: a missing file, an empty-text anchor, an unknown ext.
+ const figures =
+ `<figure id="aaa"><div class="source"><a href="missing.bin">x</a></div></figure>` +
+ `<figure id="bbb"><div class="source"><a href="empty.weird"></a></div></figure>` +
+ `<figure id="ccc"><div class="source"><a href="data.weird">label</a></div></figure>`;
+ const importRoot = await importNotion({
+ "Files 2c6c5eca1b8b80f7b9eaf4f396b755dc.html":
+ `<html><head><title>Files</title></head><body><div id="${id}"><div class="page-body"><div style="display:contents" dir="ltr">${figures}</div></div></div></body></html>`,
+ "empty.weird": Buffer.from("e"),
+ "data.weird": Buffer.from("d")
+ });
+
+ const note = importRoot.getChildNotes().find((n) => n.title === "Files");
+ if (!note) {
+ throw new Error("expected 'Files' page imported");
+ }
+ const fileAttachments = note.getAttachmentsByRole("file");
+ // Missing file: stays a plain link, no attachment; empty-text + unknown-ext: two attachments.
+ expect(fileAttachments.map((a) => a.title).sort()).toEqual(["empty.weird", "label"]);
+ const octetStream = fileAttachments.find((a) => a.title === "label");
+ expect(octetStream?.mime).toBe("application/octet-stream");
+ // The missing-file anchor lost its marker class but is still a plain link.
+ expect(note.getContent()).toContain(`href="missing.bin"`);
+ expect(note.getContent()).not.toContain("notion-attachment");
+ });
+
+ it("synthesizes a 'Database' container for a CSV whose name strips to an empty title", async () => {
+ // A CSV named with only a Notion id strips to an empty title and has no owning page, so the
+ // container falls back to the "Database" name. Its rows live in the id-named sibling folder.
+ const dbId = "08d361c59a9940c2a9d7237a4e6cd09a";
+ const importRoot = await importNotion({
+ [`${dbId}.csv`]: "a,b\n1,2",
+ [`${dbId}/Row 4f195d8c55fb44f4b94a063e643b0297.html`]: pageHtml("Row", "4f195d8c55fb44f4b94a063e643b0297")
+ });
+
+ const container = importRoot.getChildNotes().find((note) => note.title === "Database");
+ expect(container).toBeDefined();
+ expect(container?.getChildNotes().map((note) => note.title)).toEqual(["Row"]);
+ });
+
+ it("synthesizes a container named after a CSV that carries no Notion id", async () => {
+ // A CSV with no id at all keeps its (non-empty) filename as the container title and an empty id.
+ const importRoot = await importNotion({
+ "Inventory.csv": "a,b\n1,2",
+ "Inventory/Widget 4f195d8c55fb44f4b94a063e643b0297.html": pageHtml("Widget", "4f195d8c55fb44f4b94a063e643b0297")
+ });
+
+ const container = importRoot.getChildNotes().find((note) => note.title === "Inventory");
+ expect(container).toBeDefined();
+ expect(container?.getChildNotes().map((note) => note.title)).toEqual(["Widget"]);
+ });
});
diff --git a/packages/trilium-core/src/services/import/notion/importer.spec.ts b/packages/trilium-core/src/services/import/notion/importer.spec.ts
index b77948078f..cf09d15e13 100644
--- a/packages/trilium-core/src/services/import/notion/importer.spec.ts
+++ b/packages/trilium-core/src/services/import/notion/importer.spec.ts
@@ -17,6 +17,11 @@ describe("resolveResourcePath", () => {
expect(resolveResourcePath("a/b/Page.html", "../c/img%20with%20space.png"))
.toBe("a/c/img with space.png");
});
+
+ it("does not throw on a malformed percent-encoded src and returns it", () => {
+ expect(() => resolveResourcePath("Page.html", "%E0%A4%A.png")).not.toThrow();
+ expect(resolveResourcePath("Page.html", "%E0%A4%A.png")).toBe("%E0%A4%A.png");
+ });
});
describe("rewriteLinks", () => {
@@ -50,6 +55,18 @@ describe("rewriteLinks", () => {
const input = `<p><a href="Page.html?ref=386c5eca1b8b802a90d8d891c7e62cd5">x</a></p>`;
expect(rewriteLinks(input, resolveSubpage)).toBe(input);
});
+
+ it("leaves an anchor without an href untouched", () => {
+ const input = `<p><a>plain</a></p>`;
+ expect(rewriteLinks(input, resolveSubpage)).toBe(input);
+ });
+
+ it("does not throw on a malformed percent-encoded href", () => {
+ const input = `<p><a href="%E0%A4%A.html">broken</a></p>`;
+ expect(() => rewriteLinks(input, resolveSubpage)).not.toThrow();
+ // Malformed encoding can't carry a resolvable id, so the link is left as-is.
+ expect(rewriteLinks(input, resolveSubpage)).toBe(input);
+ });
});
describe("folder-based parenting keys", () => {
@@ -86,4 +103,14 @@ describe("firstChildNotionId", () => {
expect(firstChildNotionId(bodyOf(`<div class="page"><p id="386c5eca1b8b80439520cad27a0d2749">x</p></div>`)))
.toBeUndefined();
});
+
+ it("returns undefined for a null body", () => {
+ expect(firstChildNotionId(null)).toBeUndefined();
+ });
+
+ it("skips non-element child nodes when locating the page wrapper", () => {
+ // The body opens with a text node before the id-bearing wrapper; the text node must be skipped.
+ expect(firstChildNotionId(bodyOf(`leading text<div id="386c5eca1b8b80439520cad27a0d2749">x</div>`)))
+ .toBe("386c5eca1b8b80439520cad27a0d2749");
+ });
});
diff --git a/packages/trilium-core/src/services/import/notion/importer.ts b/packages/trilium-core/src/services/import/notion/importer.ts
index d4f57a5db7..3a0db997cd 100644
--- a/packages/trilium-core/src/services/import/notion/importer.ts
+++ b/packages/trilium-core/src/services/import/notion/importer.ts
@@ -153,6 +153,7 @@ function parsePage(path: string, html: string): ParsedPage | null {
* Pages are created shallowest-first, so a parent's note exists before its children. Returns the root.
*/
function createNotes(importRootNote: BNote, pages: ParsedPage[], resources: Map<string, Uint8Array>, taskContext: TaskContext<"importNotes">): BNote {
+ /* v8 ignore next -- the protected branch needs a protected import root with an active protected session, which the in-memory test DB has no way to set up */
const isProtected = importRootNote.isProtected && protectedSessionService.isProtectedSessionAvailable();
const rootNote = noteService.createNewNote({ parentNoteId: importRootNote.noteId, title: t("notion_import.root-title"), content: "", type: "text", mime: "text/html", isProtected }).note;
@@ -223,6 +224,7 @@ function rewriteImages(note: BNote, content: string, pagePath: string, resources
continue;
}
const { attachmentId, title } = imageService.saveImageToAttachment(note.noteId, bytes, baseName(resourcePath), false);
+ /* v8 ignore next -- saveImageToAttachment always returns the id of the attachment it just created, so this guard is never false in practice */
if (attachmentId) {
img.setAttribute("src", `api/attachments/${attachmentId}/image/${encodeURIComponent(title)}`);
changed = true;
@@ -423,6 +425,7 @@ function isDirectory(path: string): boolean {
}
function baseName(path: string): string {
+ /* v8 ignore next -- String.split always yields at least one element (""), so pop() is never undefined and the `?? path` fallback is unreachable */
return path.split("/").pop() ?? path;
}