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
fix(import): address Greptile/Gemini review of Notion & Keep importers
Elian Doran4fc0861a1f5e
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.tsindex 84fe43d64b..5dd4495909 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@@ -28,7 +28,7 @@ async function importSingleNote(files: Record<string, string>): Promise<BNote> {const taskContext = TaskContext.getInstance("keep-integration", "importNotes", { safeImport: true });return new Promise<BNote>((resolve, reject) => {- getContext().init(async () => {+ void getContext().init(async () => {try {const root = becca.getNoteOrThrow("root");const importRoot = await keepImporter.importKeep(taskContext, new Uint8Array(buffer), root);@@ -57,4 +57,18 @@ describe("Google Keep importer — integration", () => {expect(note.utcDateCreated).toBe("2025-11-13 21:39:26.429Z");expect(note.utcDateModified).toBe("2026-06-21 08:14:14.353Z");});++ it("falls the creation date back to the modification date when only the latter is present", async () => {+ const note = await importSingleNote({+ "Takeout/Keep/note.json": JSON.stringify({+ title: "Edited only",+ textContent: "hi",+ userEditedTimestampUsec: 1782029654353000 // 2026-06-21 08:14:14.353Z+ })+ });++ // No created timestamp: rather than leaving the "now" stamp, the modification date is used for both.+ expect(note.utcDateCreated).toBe("2026-06-21 08:14:14.353Z");+ expect(note.utcDateModified).toBe("2026-06-21 08:14:14.353Z");+ });});diff --git a/packages/trilium-core/src/services/import/keep/importer.spec.ts b/packages/trilium-core/src/services/import/keep/importer.spec.tsindex 07b1796fe6..f2e7a41fdc 100644--- a/packages/trilium-core/src/services/import/keep/importer.spec.ts+++ b/packages/trilium-core/src/services/import/keep/importer.spec.ts@@ -74,6 +74,22 @@ describe("Google Keep importer — parseNote", () => {expect(note?.content).toBe("<p><strong>Bold</strong></p>");});+ it("keeps a checklist item that has only rich text (textHtml, no plain text field)", () => {+ const json = JSON.stringify({+ listContent: [{ textHtml: `<p><span style="font-weight:700;">bold item</span></p>`, isChecked: false }]+ });++ const note = parseNote("list.json", json);++ expect(note?.content).toContain(`<span class="todo-list__label__description"><strong>bold item</strong></span>`);+ });++ it("treats an epoch (0) timestamp as a real date, not a missing one", () => {+ const note = parseNote("n.json", JSON.stringify({ createdTimestampUsec: 0 }));++ expect(note?.utcDateCreated).toBe("1970-01-01 00:00:00.000Z");+ });+it("prefers a checklist item's rich-text (textHtml over text)", () => {const json = JSON.stringify({listContent: [{ text: "done", textHtml: `<p><span style="font-style:italic;">done</span></p>`, isChecked: true }]diff --git a/packages/trilium-core/src/services/import/keep/importer.ts b/packages/trilium-core/src/services/import/keep/importer.tsindex bb3e98cb13..23c096568b 100644--- a/packages/trilium-core/src/services/import/keep/importer.ts+++ b/packages/trilium-core/src/services/import/keep/importer.ts@@ -118,7 +118,7 @@ export function parseNote(path: string, json: string): ParsedNote | null {function buildContent(note: KeepNote): string {if (note.listContent?.length) {const items = note.listContent- .filter((item) => item.text)+ .filter((item) => item.text || item.textHtml).map((item) => {// Match the canonical CKEditor task-list serialization (checked before disabled).const attributes = item.isChecked ? ` checked="checked" disabled="disabled"` : ` disabled="disabled"`;@@ -171,7 +171,7 @@ function createNotes(importRootNote: BNote, notes: ParsedNote[], taskContext: Ta// Preserve Keep's original timestamps. Must run after createNewNote's content save, which would// otherwise re-stamp the modification date with "now".if (parsed.utcDateCreated || parsed.utcDateModified) {- note.setDateCreatedAndModified(parsed.utcDateCreated, parsed.utcDateModified ?? parsed.utcDateCreated);+ note.setDateCreatedAndModified(parsed.utcDateCreated ?? parsed.utcDateModified, parsed.utcDateModified ?? parsed.utcDateCreated);}taskContext.increaseProgressCount();@@ -205,7 +205,7 @@ function keepColorToHex(color: string | undefined): string | undefined {/** Converts a Keep microsecond-epoch timestamp to Trilium's UTC DB format, or undefined if absent/invalid. */function usecToUtc(usec: number | undefined): string | undefined {- if (!usec) {+ if (usec == null) {return undefined;}const date = new Date(usec / 1000);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 962450fa9c..57e61fbe75 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@@ -49,4 +49,19 @@ describe("Notion importer — integration", () => {expect(importRoot.getChildNotes().map((note) => note.title)).toContain("Inner page");});++ it("descends into a nested export zip even when it sits inside a top-level wrapper folder", async () => {+ const innerZip = await createZipBuffer({ "Inner page 386c5eca1b8b80439520cad27a0d2749.html": pageHtml("Wrapped page") });+ const importRoot = await importNotion({ "My Export/Export-Part-1.zip": innerZip });++ expect(importRoot.getChildNotes().map((note) => note.title)).toContain("Wrapped page");+ });++ it("descends through two levels of nested export zips", async () => {+ const innermost = await createZipBuffer({ "Inner page 386c5eca1b8b80439520cad27a0d2749.html": pageHtml("Deep page") });+ const middle = await createZipBuffer({ "Export-Part-1.zip": innermost });+ const importRoot = await importNotion({ "Export.zip": middle });++ expect(importRoot.getChildNotes().map((note) => note.title)).toContain("Deep page");+ });});diff --git a/packages/trilium-core/src/services/import/notion/importer.spec.ts b/packages/trilium-core/src/services/import/notion/importer.spec.tsindex 7e52e704fa..3f474f3120 100644--- a/packages/trilium-core/src/services/import/notion/importer.spec.ts+++ b/packages/trilium-core/src/services/import/notion/importer.spec.ts@@ -1,6 +1,7 @@+import { parse } from "node-html-parser";import { describe, expect, it } from "vitest";-import { type LinkTarget, resolveResourcePath, rewriteLinks } from "./importer.js";+import { firstChildNotionId, type LinkTarget, resolveResourcePath, rewriteLinks } from "./importer.js";describe("resolveResourcePath", () => {it("resolves an image path relative to the page's directory in the zip", () => {@@ -43,4 +44,24 @@ describe("rewriteLinks", () => {const unknown = `<p><a href="Other%20ffffffffffffffffffffffffffffffff.html">Other</a></p>`;expect(rewriteLinks(unknown, resolveSubpage)).toBe(unknown);});++ it("ignores a 32-hex id that appears only in the query/hash, not the page path", () => {+ // The path ('Page.html') carries no id; the id only appears in a query parameter.+ const input = `<p><a href="Page.html?ref=386c5eca1b8b802a90d8d891c7e62cd5">x</a></p>`;+ expect(rewriteLinks(input, resolveSubpage)).toBe(input);+ });+});++describe("firstChildNotionId", () => {+ const bodyOf = (inner: string) => parse(`<body>${inner}</body>`).querySelector("body");++ it("returns the id of body's direct page-wrapper child", () => {+ expect(firstChildNotionId(bodyOf(`<div id="386c5eca1b8b80439520cad27a0d2749" class="page"><p>x</p></div>`)))+ .toBe("386c5eca1b8b80439520cad27a0d2749");+ });++ it("does not pick up a 32-hex id on a nested (non-direct) element", () => {+ expect(firstChildNotionId(bodyOf(`<div class="page"><p id="386c5eca1b8b80439520cad27a0d2749">x</p></div>`)))+ .toBeUndefined();+ });});diff --git a/packages/trilium-core/src/services/import/notion/importer.ts b/packages/trilium-core/src/services/import/notion/importer.tsindex 4add4f01e2..ae7008589c 100644--- a/packages/trilium-core/src/services/import/notion/importer.ts+++ b/packages/trilium-core/src/services/import/notion/importer.ts@@ -13,7 +13,7 @@*/import { t } from "i18next";-import { type HTMLElement, parse } from "node-html-parser";+import { HTMLElement, parse } from "node-html-parser";import type BNote from "../../../becca/entities/bnote.js";import imageService from "../../image.js";@@ -51,24 +51,29 @@ async function importNotion(taskContext: TaskContext<"importNotes">, fileBuffer:* Reads the zip: HTML entries become parsed pages; every other file (images, attachments) is kept by its* normalized path so page content can later reference it. The `index.html` summary is skipped.*- * A Notion workspace export wraps its content in one (or more) nested zips at the archive root — the part- * you'd otherwise have to extract by hand — so root-level `.zip` entries are descended into. Nested zips- * sitting inside a page folder are treated as ordinary attachments, not export structure.+ * A Notion workspace export wraps its content in a nested zip at the archive root — the part you'd+ * otherwise have to extract by hand — so export-level `.zip` entries are descended into. A zip is+ * "export-level" when no ancestor folder carries a Notion id; a zip inside a page folder (which does) is+ * a user's attachment and kept as-is. Recursion is depth-bounded as a guard against pathological archives.*/+const MAX_NESTED_ZIP_DEPTH = 2;+async function parseZip(fileBuffer: Uint8Array): Promise<{ pages: ParsedPage[]; resources: Map<string, Uint8Array> }> {const provider = getZipProvider();const pages: ParsedPage[] = [];const resources = new Map<string, Uint8Array>();- const readArchive = async (buffer: Uint8Array): Promise<void> => {+ const readArchive = async (buffer: Uint8Array, depth: number): Promise<void> => {const filenameEncoding = await provider.detectFilenameEncoding(buffer);await provider.readZipFile(buffer, async (entry, readContent) => {const path = entry.fileName;if (isDirectory(path)) {return;}- if (path.toLowerCase().endsWith(".zip") && !path.includes("/")) {- await readArchive(await readContent());+ if (path.toLowerCase().endsWith(".zip") && parseParentIds(path).length === 0) {+ if (depth < MAX_NESTED_ZIP_DEPTH) {+ await readArchive(await readContent(), depth + 1);+ }} else if (path.toLowerCase().endsWith(".html")) {if (baseName(path) === "index.html") {return;@@ -83,7 +88,7 @@ async function parseZip(fileBuffer: Uint8Array): Promise<{ pages: ParsedPage[];}, filenameEncoding);};- await readArchive(fileBuffer);+ await readArchive(fileBuffer, 0);return { pages, resources };}@@ -164,7 +169,7 @@ function createNotes(importRootNote: BNote, pages: ParsedPage[], resources: Map<// Preserve Notion's original timestamps. Must run after the content save above, which would// otherwise re-stamp the modification date with "now".if (page.utcDateCreated || page.utcDateModified) {- note.setDateCreatedAndModified(page.utcDateCreated, page.utcDateModified ?? page.utcDateCreated);+ note.setDateCreatedAndModified(page.utcDateCreated ?? page.utcDateModified, page.utcDateModified ?? page.utcDateCreated);}}@@ -252,7 +257,8 @@ function internalPageId(href: string | undefined): string | null {if (!path.toLowerCase().endsWith(".html")) {return null;}- return getNotionId(decoded) ?? null;+ // Match against the path only: a 32-hex sequence in a query/hash must not be mistaken for the page id.+ return getNotionId(path) ?? null;}/**@@ -287,15 +293,20 @@ function normalizePath(path: string): string {return parts.join("/");}-/** Returns the Notion id of the first child element of `body` that carries one (Notion's page wrapper). */-function firstChildNotionId(body: HTMLElement | null): string | undefined {+/**+ * Returns the Notion id of `body`'s page-wrapper child. Only `body`'s direct children are considered: a+ * nested block whose id happens to match the 32-hex pattern must not be taken for the page id.+ */+export function firstChildNotionId(body: HTMLElement | null): string | undefined {if (!body) {return undefined;}- for (const child of body.querySelectorAll("*")) {- const id = getNotionId(child.getAttribute("id") ?? "");- if (id) {- return id;+ for (const child of body.childNodes) {+ if (child instanceof HTMLElement) {+ const id = getNotionId(child.getAttribute("id") ?? "");+ if (id) {+ return id;+ }}}return undefined;