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
Detect Notion "Markdown & CSV" exports and fail with guidance
Elian Doranaefdc21a1dbb
diff --git a/apps/server/src/assets/translations/en/server.json b/apps/server/src/assets/translations/en/server.jsonindex f3430aa8d3..55bf194439 100644--- a/apps/server/src/assets/translations/en/server.json+++ b/apps/server/src/assets/translations/en/server.json@@ -320,7 +320,8 @@"root-title": "OneNote import"},"notion_import": {- "root-title": "Notion import"+ "root-title": "Notion import",+ "markdown-export-unsupported": "This looks like a Notion \"Markdown & CSV\" export, which Trilium cannot import. Please re-export your Notion workspace using the \"HTML\" export format and import that instead."},"keep_import": {"root-title": "Google Keep import"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 94cea02937..7f07c5ac1b 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@@ -56,6 +56,30 @@ describe("Notion importer — integration", () => {expect(examples?.getChildNotes().map((note) => note.title).sort()).toEqual(["Hello world", "Quick Note"]);});+ it("rejects a Notion 'Markdown & CSV' export, guiding the user to re-export as HTML", async () => {+ // A Markdown export has no `.html` pages — pages are `.md` and databases are `.csv`. This importer+ // only understands the HTML export, so it must fail loudly rather than building an empty tree or+ // orphaning every page as a `.md` attachment.+ await expect(+ importNotion({+ "Workout tracker 644acbf2ec344e1eae705a8b33d186b3.md":+ "# Workout tracker\n\n[Workout Schedule](workout%20tracker/Workout%20Schedule%20644acbf2ec344e1eae705a8b33d186b3.csv)",+ "workout tracker/Workout Schedule 644acbf2ec344e1eae705a8b33d186b3.csv": "Name,Day\nSquats,Monday"+ })+ ).rejects.toThrow(/re-export.*HTML/i);+ });++ it("still imports an HTML export that happens to bundle a `.md` attachment", async () => {+ // A stray `.md` file (a real attachment) inside a valid HTML export must not trip the guard:+ // the export has `.html` pages, so it's clearly the right format.+ const importRoot = await importNotion({+ "Notes 2c6c5eca1b8b80f7b9eaf4f396b755dc.html": pageHtml("Notes", "2c6c5eca1b8b80f7b9eaf4f396b755dc"),+ "Notes/readme.md": "# bundled attachment"+ });++ expect(importRoot.getChildNotes().map((note) => note.title)).toEqual(["Notes"]);+ });+it("groups a CSV-only database's rows under a container note, instead of orphaning them to the root", async () => {// A Notion inline/linked database exports as a `.csv` with no sibling `.html`; its rows live in a// folder named after the database. Nothing owns that folder, so without a container they'd be flat.diff --git a/packages/trilium-core/src/services/import/notion/importer.ts b/packages/trilium-core/src/services/import/notion/importer.tsindex 1505624554..02dc905cc3 100644--- a/packages/trilium-core/src/services/import/notion/importer.ts+++ b/packages/trilium-core/src/services/import/notion/importer.ts@@ -33,7 +33,14 @@ import { getNotionId, stripNotionId } from "./notion_id.js";import { baseName, firstChildNotionId, folderDepth, internalPageId, isDirectory, normalizePath, ownedFolderKey, parentFolderKey, removeExtension, resolveResourcePath } from "./paths.js";async function importNotion(taskContext: TaskContext<"importNotes">, fileBuffer: Uint8Array, importRootNote: BNote): Promise<BNote> {- const { pages, resources, csvPaths, csvColumnsByFolder } = await parseZip(fileBuffer);+ const { pages, resources, csvPaths, csvColumnsByFolder, markdownFileCount } = await parseZip(fileBuffer);+ if (pages.length === 0 && markdownFileCount > 0) {+ // The user exported from Notion as "Markdown & CSV", but this importer only understands the HTML+ // export — it reconstructs databases by correlating each `.csv` with the surrounding `.html` pages,+ // which a Markdown export doesn't have. Fail with actionable guidance rather than silently producing+ // an empty tree (or orphaning every page as a `.md` attachment).+ throw new Error(t("notion_import.markdown-export-unsupported"));+ }resolveDatabaseContainers(pages, csvPaths);reconcileDateColumns(pages);taskContext.setTotalCount(pages.length);@@ -51,13 +58,16 @@ async function importNotion(taskContext: TaskContext<"importNotes">, fileBuffer:*/const MAX_NESTED_ZIP_DEPTH = 2;-async function parseZip(fileBuffer: Uint8Array): Promise<{ pages: ParsedPage[]; resources: Map<string, Uint8Array>; csvPaths: string[]; csvColumnsByFolder: Map<string, string[]> }> {+async function parseZip(fileBuffer: Uint8Array): Promise<{ pages: ParsedPage[]; resources: Map<string, Uint8Array>; csvPaths: string[]; csvColumnsByFolder: Map<string, string[]>; markdownFileCount: number }> {const provider = getZipProvider();const pages: ParsedPage[] = [];const resources = new Map<string, Uint8Array>();const csvPaths: string[] = [];// Database folder key → its columns (sanitized), in the CSV export's order — the authoritative column order.const csvColumnsByFolder = new Map<string, string[]>();+ // Notion's "Markdown & CSV" export emits pages as `.md`; the HTML export this importer is built around+ // never does. Counting them lets importNotion detect that wrong export format and fail with guidance.+ let markdownFileCount = 0;const readArchive = async (buffer: Uint8Array, depth: number): Promise<void> => {const filenameEncoding = await provider.detectFilenameEncoding(buffer);@@ -87,6 +97,11 @@ async function parseZip(fileBuffer: Uint8Array): Promise<{ pages: ParsedPage[];// property `<th>` text, which is trimmed on extraction.csvColumnsByFolder.set(ownedFolderKey(path), header.map((column) => toAttributeName(column.trim())));} else {+ // Keep the file as a resource so a genuine `.md` attachment inside an HTML export survives,+ // but tally markdown pages so the wrong export format can be detected.+ if (path.toLowerCase().endsWith(".md")) {+ markdownFileCount++;+ }resources.set(normalizePath(path), await readContent());}}, filenameEncoding);@@ -94,7 +109,7 @@ async function parseZip(fileBuffer: Uint8Array): Promise<{ pages: ParsedPage[];await readArchive(fileBuffer, 0);- return { pages, resources, csvPaths, csvColumnsByFolder };+ return { pages, resources, csvPaths, csvColumnsByFolder, markdownFileCount };}function parsePage(path: string, html: string): ParsedPage | null {