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): stop preserving the "root" note ID on ZIP import
Elian Doran5dbc5aa6cbb8
diff --git a/apps/server/spec/etapi/import-zip.spec.ts b/apps/server/spec/etapi/import-zip.spec.tsindex c42623b765..7c7adc4d16 100644--- a/apps/server/spec/etapi/import-zip.spec.ts+++ b/apps/server/spec/etapi/import-zip.spec.ts@@ -3,6 +3,7 @@ import { beforeAll, describe, expect, it } from "vitest";import supertest from "supertest";import { login } from "./utils.js";import config from "../../src/services/config.js";+import { becca } from "@triliumnext/core";import { readFileSync } from "fs";import { join } from "path";@@ -19,7 +20,7 @@ describe("etapi/import", () => {token = await login(app);});- it("demo zip can be imported", async () => {+ it("demo zip (a whole-database export) imports under root as a 'root' wrapper note", async () => {const buffer = readFileSync(join(__dirname, "../../src/assets/db/demo.zip"));const response = await supertest(app).post("/etapi/notes/root/import")@@ -28,7 +29,18 @@ describe("etapi/import", () => {.set("Content-Transfer-Encoding", "binary").send(buffer).expect(201);- expect(response.body.note.title).toStrictEqual("Journal");++ // A Trilium root-export (its top note is "root") imported into root is nested under a "root"+ // wrapper note rather than being remapped onto / merged into the system root - that would+ // create a self-referential root->root branch that breaks loading. Whole-database *restore*+ // (the demo content on first run) instead passes the restoreAsRoot import option, which maps+ // the archive's root onto the destination root - see trilium-core import/zip.spec.ts.+ expect(response.body.note.title).toStrictEqual("root");expect(response.body.branch.parentNoteId).toStrictEqual("root");++ // the demo's top-level notes live under that wrapper, and no corrupt root->root branch exists+ const wrapper = becca.getNote(response.body.note.noteId);+ expect(wrapper?.getChildNotes().map((n) => n.title)).toEqual(expect.arrayContaining(["Journal", "Trilium Demo", "Miscellaneous"]));+ expect(becca.getBranchFromChildAndParent("root", "root")).toBeFalsy();});});diff --git a/packages/trilium-core/src/services/import/zip.spec.ts b/packages/trilium-core/src/services/import/zip.spec.tsindex a3fe7937de..3e319c2653 100644--- a/packages/trilium-core/src/services/import/zip.spec.ts+++ b/packages/trilium-core/src/services/import/zip.spec.ts@@ -19,7 +19,7 @@ async function testImport(fileName: string) {return testImportBuffer(buffer);}-async function testImportBuffer(buffer: Buffer, taskId = "import-mdx", taskData: Record<string, unknown> = { textImportedAsText: true }) {+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) => {@@ -30,7 +30,7 @@ async function testImportBuffer(buffer: Buffer, taskId = "import-mdx", taskData:return;}- const importedNote = await zip.importZip(taskContext, buffer, rootNote as BNote);+ const importedNote = await zip.importZip(taskContext, buffer, rootNote as BNote, opts);resolve({importedNote,rootNote@@ -289,6 +289,138 @@ describe("processNoteContent", () => {expect(setTotalSpy.mock.calls.map((call) => call[0])).toEqual([3, 3]);});+ it("imports an exported root note as a regular note instead of corrupting the system root", async () => {+ // Exporting a root note that has its own content yields a meta entry with noteId "root" AND a+ // data file. The "root" id must be remapped on import (like any other note) so the archived root+ // lands as an ordinary note under the import target - rather than overwriting the destination's+ // real root note and creating a self-referential root->root branch that breaks loading.+ const metaFile = {+ formatVersion: 2,+ appVersion: "0.0.0",+ files: [{+ noteId: "root",+ title: "root",+ type: "text",+ mime: "text/html",+ format: "html",+ dataFileName: "root.html",+ dirFileName: "root",+ attributes: [],+ attachments: [],+ children: [{+ noteId: "1giO9zlsdvT6",+ title: "Hi",+ type: "text",+ mime: "text/html",+ format: "html",+ dataFileName: "Hi.html",+ attributes: [],+ attachments: []+ }]+ }]+ };++ const zipBuffer = await createZipBuffer({+ "!!!meta.json": JSON.stringify(metaFile),+ "root.html": "<p>archived root content</p>",+ "root/Hi.html": "<p>hi content</p>"+ });++ const { importedNote, rootNote } = await testImportBuffer(zipBuffer, "import-root-note");++ // The archived root becomes a fresh, ordinary note placed under the import target - not the system root.+ expect(importedNote.noteId).not.toBe("root");+ expect(importedNote.title).toBe("root");+ expect(importedNote.getContent().toString()).toContain("archived root content");+ expect(rootNote.getChildNotes().map((n) => n.noteId)).toContain(importedNote.noteId);++ // Its child came along under the new note.+ const hi = importedNote.getChildNotes().find((n) => n.title === "Hi");+ expect(hi?.getContent().toString()).toContain("hi content");++ // No corruption: the system root keeps its own content and gains no self-referential branch.+ expect(rootNote.getContent().toString()).not.toContain("archived root content");+ expect(becca.getBranchFromChildAndParent("root", "root")).toBeFalsy();+ });++ it("restoreAsRoot maps the archived root onto the destination root instead of wrapping it (demo-content shape)", async () => {+ // The demo archive (and a whole-database restore) is an export whose top note IS "root" with no+ // own content - just children. With restoreAsRoot those children must land directly under the+ // destination root, not inside a redundant "root" wrapper note (which produced "two root folders").+ const metaFile = {+ formatVersion: 2,+ appVersion: "0.0.0",+ files: [{+ noteId: "root",+ title: "root",+ type: "text",+ mime: "text/html",+ format: "html",+ dirFileName: "root",+ attributes: [],+ attachments: [],+ children: [+ { noteId: "demoChildA", title: "Journal", type: "text", mime: "text/html", format: "html", dataFileName: "Journal.html", attributes: [], attachments: [] },+ { noteId: "demoChildB", title: "Miscellaneous", type: "text", mime: "text/html", format: "html", dataFileName: "Miscellaneous.html", attributes: [], attachments: [] }+ ]+ }]+ };++ const zipBuffer = await createZipBuffer({+ "!!!meta.json": JSON.stringify(metaFile),+ "root/Journal.html": "<p>journal</p>",+ "root/Miscellaneous.html": "<p>misc</p>"+ });++ const { rootNote } = await testImportBuffer(zipBuffer, "import-restore-as-root", { textImportedAsText: true }, { restoreAsRoot: true });++ // The archived root's children are DIRECT children of the destination root - a "root" wrapper note+ // would interpose itself as their parent instead (the "two root folders" regression).+ const journal = rootNote.getChildNotes().find((n) => n.title === "Journal");+ const misc = rootNote.getChildNotes().find((n) => n.title === "Miscellaneous");+ expect(journal?.getParentNotes().map((n) => n.noteId)).toEqual(["root"]);+ expect(misc?.getParentNotes().map((n) => n.noteId)).toEqual(["root"]);+ // And no self-referential root branch.+ expect(becca.getBranchFromChildAndParent("root", "root")).toBeFalsy();+ });++ it("restoreAsRoot merges an archived root that has its own content into the destination root", async () => {+ const metaFile = {+ formatVersion: 2,+ appVersion: "0.0.0",+ files: [{+ noteId: "root",+ title: "root",+ type: "text",+ mime: "text/html",+ format: "html",+ dataFileName: "root.html",+ dirFileName: "root",+ attributes: [],+ attachments: [],+ children: [+ { noteId: "restoreChild1", title: "Restored Child", type: "text", mime: "text/html", format: "html", dataFileName: "Restored Child.html", attributes: [], attachments: [] }+ ]+ }]+ };++ const zipBuffer = await createZipBuffer({+ "!!!meta.json": JSON.stringify(metaFile),+ "root.html": "<p>restored root content</p>",+ "root/Restored Child.html": "<p>child content</p>"+ });++ const { rootNote } = await testImportBuffer(zipBuffer, "import-restore-root-content", { textImportedAsText: true }, { restoreAsRoot: true });++ // The archived root's content is written onto the real root, and its child attaches directly to+ // root - no wrapper note, no self-referential branch.+ expect(rootNote.getContent().toString()).toContain("restored root content");+ const child = rootNote.getChildNotes().find((n) => n.title === "Restored Child");+ expect(child?.getParentNotes().map((n) => n.noteId)).toEqual(["root"]);+ expect(child?.getContent().toString()).toContain("child content");+ expect(becca.getBranchFromChildAndParent("root", "root")).toBeFalsy();+ });+it("imports a CSV entry as a plain file note when the spreadsheet option is off", async () => {const zipBuffer = await createZipBuffer({ "csv_as_file_sample.csv": "a,b\r\n1,2" });const { rootNote } = await testImportBuffer(zipBuffer, "import-csv-off", { spreadsheetImportedAsSpreadsheet: false });diff --git a/packages/trilium-core/src/services/import/zip.ts b/packages/trilium-core/src/services/import/zip.tsindex 01a6d175e4..c5850a9486 100644--- a/packages/trilium-core/src/services/import/zip.ts+++ b/packages/trilium-core/src/services/import/zip.ts@@ -51,6 +51,14 @@ interface MetaFile {interface ImportZipOpts {preserveIds?: boolean;+ /**+ * Restore a whole-database export: map the archive's "root" note onto the import target instead of+ * importing it as a new child note. The archived root's content merges into the destination and its+ * children become the destination's children - no redundant "root" wrapper note, no root->root branch.+ * Used by the demo-content import (and intended for a future "restore from ZIP" flow). Without it, an+ * archived "root" is remapped to a fresh id like any other note (see {@link getNewNoteId}).+ */+ restoreAsRoot?: boolean;}async function importZip(taskContext: TaskContext<"importNotes">, source: ZipSource, importRootNote: BNote, opts?: ImportZipOpts): Promise<BNote> {@@ -73,10 +81,15 @@ async function importZip(taskContext: TaskContext<"importNotes">, source: ZipSoureturn "empty_note_id";}- if (origNoteId === "root" || opts?.preserveIds) {+ if (opts?.preserveIds) {return origNoteId;}+ // Whole-database restore: the archived root note IS the destination root, not a new child note.+ if (opts?.restoreAsRoot && origNoteId === "root") {+ return importRootNote.noteId;+ }+if (!noteIdMap[origNoteId]) {noteIdMap[origNoteId] = newEntityId();}@@ -537,14 +550,24 @@ async function importZip(taskContext: TaskContext<"importNotes">, source: ZipSoureturn;}- const parentNoteId = getParentNoteId(filePath, parentNoteMeta);+ let parentNoteId = getParentNoteId(filePath, parentNoteMeta);if (!parentNoteId) {throw new Error(`Cannot find parentNoteId for '${filePath}'`);}+ // When restoring a whole database (restoreAsRoot), the archived "root" maps onto the import root+ // itself - it already exists with its own parentage, so we only refresh its content and never+ // create a branch for it. For any other note, guard against a self-referential branch: reserved+ // IDs like "root" are remapped on import so this shouldn't normally happen, but a malformed archive+ // could otherwise persist a root->root branch that corrupts the tree and breaks loading.+ const isImportRootNote = noteId === importRootNote.noteId;+ if (!isImportRootNote && parentNoteId === noteId) {+ parentNoteId = importRootNote.noteId;+ }+if (noteMeta?.isClone) {- if (!becca.getBranchFromChildAndParent(noteId, parentNoteId)) {+ if (!isImportRootNote && !becca.getBranchFromChildAndParent(noteId, parentNoteId)) {new BBranch({noteId,parentNoteId,@@ -605,7 +628,7 @@ async function importZip(taskContext: TaskContext<"importNotes">, source: ZipSounote.setContent(content);- if (!becca.getBranchFromChildAndParent(noteId, parentNoteId)) {+ if (!isImportRootNote && !becca.getBranchFromChildAndParent(noteId, parentNoteId)) {new BBranch({noteId,parentNoteId,@@ -615,7 +638,7 @@ async function importZip(taskContext: TaskContext<"importNotes">, source: ZipSou}).save();}- if (opts?.preserveIds) {+ if (opts?.preserveIds || isImportRootNote) {firstNote = firstNote || note;}} else {diff --git a/packages/trilium-core/src/services/sql_init.ts b/packages/trilium-core/src/services/sql_init.tsindex fd0669448e..97a6cbdbeb 100644--- a/packages/trilium-core/src/services/sql_init.ts+++ b/packages/trilium-core/src/services/sql_init.ts@@ -185,7 +185,9 @@ async function createInitialDatabase(skipDemoDb?: boolean, locale?: string) {if (demoFile) {const { default: zipImportService } = await import("./import/zip.js");const dummyTaskContext = new TaskContext("no-progress-reporting", "importNotes", null);- await zipImportService.importZip(dummyTaskContext, demoFile, rootNote);+ // The demo archive is a whole-database export whose top note IS "root"; restore it onto the+ // existing root rather than nesting it in a redundant "root" wrapper note.+ await zipImportService.importZip(dummyTaskContext, demoFile, rootNote, { restoreAsRoot: true });}}