Skip to content

Build your personal knowledge base with Trilium Notes

Detect Notion exports made without "Create folders for subpages"

Elian Doran8bbe7532daae
diff --git a/packages/trilium-core/src/services/import/notion/collection.ts b/packages/trilium-core/src/services/import/notion/collection.ts
index 9cb2c11e84..ca4a1e1b40 100644
--- a/packages/trilium-core/src/services/import/notion/collection.ts
+++ b/packages/trilium-core/src/services/import/notion/collection.ts
@@ -55,6 +55,7 @@ export function resolveDatabaseContainers(pages: ParsedPage[], csvPaths: string[
title: stripNotionId(removeExtension(baseName(csvPath))) || "Database",
path: csvPath,
content: "",
+ linkedPageIds: [],
properties: [],
isDatabase: true
});
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 7f07c5ac1b..c84e687fd2 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
@@ -80,6 +80,67 @@ describe("Notion importer — integration", () => {
expect(importRoot.getChildNotes().map((note) => note.title)).toEqual(["Notes"]);
});
+ it("rejects an HTML export made without 'Create folders for subpages' (flat pages still linked as subpages)", async () => {
+ // With the option off, the child sits at the archive root (no `Parent/` folder), yet the parent
+ // still references it via a flat link-to-page block. The folder structure is gone, so the nesting
+ // can't be reconstructed — fail with guidance instead of silently flattening the tree.
+ const parentId = "11111111111111111111111111111111";
+ const childId = "22222222222222222222222222222222";
+ const childFigure = `<figure class="link-to-page"><a href="Child ${childId}.html">Child</a></figure>`;
+ await expect(
+ importNotion({
+ [`Parent ${parentId}.html`]: `<html><head><title>Parent</title></head><body><div id="${parentId}"><div class="page-body">${childFigure}</div></div></body></html>`,
+ [`Child ${childId}.html`]: pageHtml("Child", childId)
+ })
+ ).rejects.toThrow(/Create folders for subpages/i);
+ });
+
+ it("imports a single-page export (no folders) without flagging it as a flattened hierarchy", async () => {
+ // The folders-disabled guard must never catch a legitimate single page, which also has no folders.
+ const importRoot = await importNotion({
+ "Solo 2c6c5eca1b8b80f7b9eaf4f396b755dc.html": pageHtml("Solo", "2c6c5eca1b8b80f7b9eaf4f396b755dc")
+ });
+
+ expect(importRoot.getChildNotes().map((note) => note.title)).toEqual(["Solo"]);
+ });
+
+ it("rejects a folders-disabled export whose database rows were flattened to the root", async () => {
+ // A CSV-only database with the folders option off: the row pages sit at the archive root with titles
+ // matching the CSV's first column, instead of nesting under the database. Detect via that title match.
+ await expect(
+ importNotion({
+ "Tasks 08d361c59a9940c2a9d7237a4e6cd09a.csv": "Name,Status\nFirst task,Done\nSecond task,Todo",
+ "First task 4f195d8c55fb44f4b94a063e643b0297.html": pageHtml("First task", "4f195d8c55fb44f4b94a063e643b0297"),
+ "Second task 388c5eca1b8b80929a78da7c68154bd7.html": pageHtml("Second task", "388c5eca1b8b80929a78da7c68154bd7")
+ })
+ ).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")
+ });
+
+ 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 () => {
+ // Several root-level pages with an inline cross-link — but no `link-to-page` subpage blocks — is a
+ // legitimately flat export (e.g. a whole workspace), not a flattened hierarchy. It must import.
+ const idA = "33333333333333333333333333333333";
+ const idB = "44444444444444444444444444444444";
+ 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)
+ });
+
+ expect(importRoot.getChildNotes().map((note) => note.title).sort()).toEqual(["Page A", "Page B"]);
+ });
+
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.ts
index 02dc905cc3..477a969527 100644
--- a/packages/trilium-core/src/services/import/notion/importer.ts
+++ b/packages/trilium-core/src/services/import/notion/importer.ts
@@ -33,7 +33,7 @@ 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, markdownFileCount } = await parseZip(fileBuffer);
+ const { pages, resources, csvPaths, csvColumnsByFolder, markdownFileCount, csvRowTitles } = 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,
@@ -41,6 +41,22 @@ async function importNotion(taskContext: TaskContext<"importNotes">, fileBuffer:
// an empty tree (or orphaning every page as a `.md` attachment).
throw new Error(t("notion_import.markdown-export-unsupported"));
}
+ // Notion's "Create folders for subpages" export option, when disabled, drops every page to the archive
+ // root with no per-page folders. Cross-page links survive (they carry the page id), but the folder
+ // structure is the only thing that conveys nesting and database-row membership — so the hierarchy would
+ // silently collapse. Detect it (every page at the root, yet a page still references another imported page
+ // as a subpage) and fail with guidance. A single-page export has no such references and is never caught.
+ if (pages.length > 1 && pages.every((page) => !page.path.includes("/"))) {
+ const pageIds = new Set(pages.map((page) => page.id));
+ const hasFlattenedSubpage = pages.some((page) => page.linkedPageIds.some((id) => id !== page.id && pageIds.has(id)));
+ // A flattened database: its row pages sit at the root with titles matching the CSV's first column,
+ // rather than nesting under the database. A folders-on database keeps its rows in folders, so it
+ // never reaches here (some page would carry a "/"); an empty database has no row titles to match.
+ const hasFlattenedDatabaseRow = pages.some((page) => csvRowTitles.has(page.title));
+ if (hasFlattenedSubpage || hasFlattenedDatabaseRow) {
+ throw new Error(t("notion_import.subpage-folders-disabled"));
+ }
+ }
resolveDatabaseContainers(pages, csvPaths);
reconcileDateColumns(pages);
taskContext.setTotalCount(pages.length);
@@ -58,7 +74,7 @@ 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[]>; markdownFileCount: number }> {
+async function parseZip(fileBuffer: Uint8Array): Promise<{ pages: ParsedPage[]; resources: Map<string, Uint8Array>; csvPaths: string[]; csvColumnsByFolder: Map<string, string[]>; markdownFileCount: number; csvRowTitles: Set<string> }> {
const provider = getZipProvider();
const pages: ParsedPage[] = [];
const resources = new Map<string, Uint8Array>();
@@ -68,6 +84,9 @@ async function parseZip(fileBuffer: Uint8Array): Promise<{ pages: ParsedPage[];
// 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;
+ // Title of every database row (a CSV's first column), used to detect a "Create folders for subpages"-
+ // disabled export, where row pages are flattened to the root instead of nesting under the database.
+ const csvRowTitles = new Set<string>();
const readArchive = async (buffer: Uint8Array, depth: number): Promise<void> => {
const filenameEncoding = await provider.detectFilenameEncoding(buffer);
@@ -92,10 +111,18 @@ async function parseZip(fileBuffer: Uint8Array): Promise<{ pages: ParsedPage[];
// A Notion database exports as a CSV: its path reconstructs the hierarchy (a database with no
// own page), and its header row lists every column in the database's order.
csvPaths.push(path);
- const [header = []] = parseCsv(new TextDecoder().decode(await readContent()));
+ const [header = [], ...rows] = parseCsv(new TextDecoder().decode(await readContent()));
// Trim before sanitizing so a padded CSV header (`Name, Age , …`) still matches the HTML
// property `<th>` text, which is trimmed on extraction.
csvColumnsByFolder.set(ownedFolderKey(path), header.map((column) => toAttributeName(column.trim())));
+ // The first column is each row's title; collect them so a flattened database (rows at the
+ // root, matching these titles, rather than nested under the database) can be detected.
+ for (const row of rows) {
+ const rowTitle = row[0]?.trim();
+ if (rowTitle) {
+ csvRowTitles.add(rowTitle);
+ }
+ }
} 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.
@@ -109,7 +136,7 @@ async function parseZip(fileBuffer: Uint8Array): Promise<{ pages: ParsedPage[];
await readArchive(fileBuffer, 0);
- return { pages, resources, csvPaths, csvColumnsByFolder, markdownFileCount };
+ return { pages, resources, csvPaths, csvColumnsByFolder, markdownFileCount, csvRowTitles };
}
function parsePage(path: string, html: string): ParsedPage | null {
@@ -128,11 +155,23 @@ function parsePage(path: string, html: string): ParsedPage | null {
const pageBody = root.querySelector(".page-body");
const content = pageBody ? sanitizeHtml(convertNotionHtml(pageBody.innerHTML)) : "";
+ // Capture subpage references from the raw HTML (before conversion rewrites them): a `link-to-page` block
+ // is a child page or explicit page link, and a collection table's cells link to the database's rows.
+ // Inline page mentions are deliberately excluded — only these structural references signal nesting.
+ const linkedPageIds: string[] = [];
+ for (const anchor of root.querySelectorAll("figure.link-to-page a, .collection-content a")) {
+ const linkedId = internalPageId(anchor.getAttribute("href"));
+ if (linkedId) {
+ linkedPageIds.push(linkedId);
+ }
+ }
+
return {
id,
title,
path,
content,
+ linkedPageIds,
properties: extractProperties(root),
utcDateCreated: extractDate(root, "property-row-created_time"),
utcDateModified: extractDate(root, "property-row-last_edited_time")
diff --git a/packages/trilium-core/src/services/import/notion/model.ts b/packages/trilium-core/src/services/import/notion/model.ts
index e078181bd9..e185cd06a1 100644
--- a/packages/trilium-core/src/services/import/notion/model.ts
+++ b/packages/trilium-core/src/services/import/notion/model.ts
@@ -26,6 +26,12 @@ export interface ParsedPage {
path: string;
/** The page's body HTML, sanitized; empty when the body could not be located. */
content: string;
+ /**
+ * Notion ids this page references as subpages — from its `link-to-page` blocks and rendered collection
+ * table. These survive a "Create folders for subpages"-disabled export even though the folder structure
+ * that conveys nesting does not, so they let the importer detect that flattened export.
+ */
+ linkedPageIds: string[];
/** Database properties from the page's Notion properties table, mapped to Trilium labels on import. */
properties: NotionProperty[];
/**