Skip to content

Build your personal knowledge base with Trilium Notes

feat(import): import unreferenced Obsidian vault files

Elian Doran13ac7cd0575d
diff --git a/packages/trilium-core/src/services/import/obsidian/attachments.ts b/packages/trilium-core/src/services/import/obsidian/attachments.ts
index 5572dfb67f..538a466929 100644
--- a/packages/trilium-core/src/services/import/obsidian/attachments.ts
+++ b/packages/trilium-core/src/services/import/obsidian/attachments.ts
@@ -37,7 +37,11 @@ export function buildAttachmentIndex(attachments: Map<string, Uint8Array>): Atta
return { byPath: attachments, byBasename };
}
-export function applyAttachments(note: BNote, html: string, index: AttachmentIndex, shrinkImages: boolean): string {
+/**
+ * @param consumed collects the vault paths that were materialized as attachments, so the caller can tell
+ * which bundled files are still orphaned (unreferenced) and need a standalone note instead.
+ */
+export function applyAttachments(note: BNote, html: string, index: AttachmentIndex, shrinkImages: boolean, consumed?: Set<string>): string {
if (index.byPath.size === 0 || (!html.includes("<img") && !html.includes("<a"))) {
return html;
}
@@ -50,6 +54,7 @@ export function applyAttachments(note: BNote, html: string, index: AttachmentInd
if (!ref || !resolved) {
continue;
}
+ consumed?.add(resolved.path);
if (isImageMime(resolved.mime)) {
try {
const { attachmentId, title } = imageService.saveImageToAttachment(note.noteId, resolved.bytes, basename(resolved.path), shrinkImages);
@@ -73,6 +78,7 @@ export function applyAttachments(note: BNote, html: string, index: AttachmentInd
if (!ref || !resolved) {
continue;
}
+ consumed?.add(resolved.path);
const attachment = note.saveAttachment({ role: "file", mime: resolved.mime, title: basename(resolved.path), content: resolved.bytes });
anchor.setAttribute("href", attachmentHref(note.noteId, attachment.attachmentId));
anchor.setAttribute("class", "reference-link");
diff --git a/packages/trilium-core/src/services/import/obsidian/importer.integration.spec.ts b/packages/trilium-core/src/services/import/obsidian/importer.integration.spec.ts
index dc0dc9c974..9aa615ed95 100644
--- a/packages/trilium-core/src/services/import/obsidian/importer.integration.spec.ts
+++ b/packages/trilium-core/src/services/import/obsidian/importer.integration.spec.ts
@@ -185,7 +185,7 @@ describe("Obsidian importer — integration", () => {
expect(decodeUtf8(note?.getContent() ?? "")).toBe('<p>A <span style="background-color:hsl(60, 75%, 60%)">highlight</span> and a comment.</p>');
});
- it("drops attachments, the .base/.canvas files and the .obsidian config folder", async () => {
+ it("drops the .base/.canvas files and the .obsidian config folder, but keeps an orphan attachment", async () => {
const importRoot = await importObsidian({
"Note.md": "Body.",
"Screenshot.png": Buffer.from("\x89PNG\r\n\x1a\nfake"),
@@ -195,8 +195,8 @@ describe("Obsidian importer — integration", () => {
".obsidian/workspace.json": "{}"
});
- // Only the Markdown note is imported; nothing else creates a note.
- expect(importRoot.getChildNotes().map((n) => n.title)).toEqual(["Note"]);
+ // The Markdown note and the unreferenced attachment are imported; .base/.canvas/.obsidian are not.
+ expect(importRoot.getChildNotes().map((n) => n.title)).toEqual(["Note", "Screenshot.png"]);
});
it("strips the wrapper folder and names the root after the vault when the outer folder is zipped", async () => {
@@ -279,6 +279,51 @@ describe("Obsidian importer — integration", () => {
expect(note?.getAttachmentsByRole("file")).toHaveLength(0);
});
+ it("materializes an unreferenced (orphan) vault file as a standalone file note at its folder location", async () => {
+ const importRoot = await importObsidian({
+ "Note.md": "Just a note, linking nothing.",
+ "Attachments/report.pdf": Buffer.from("%PDF-1.4 fake"),
+ ".obsidian/app.json": "{}"
+ }, "Vault.zip");
+
+ const attachmentsFolder = importRoot.getChildNotes().find((n) => n.title === "Attachments");
+ const orphan = attachmentsFolder?.getChildNotes()[0];
+ if (!orphan) {
+ throw new Error("orphan file was not imported");
+ }
+
+ // The .pdf extension is stripped from the title (Trilium convention) and preserved in a label.
+ expect(orphan.title).toBe("report");
+ expect(orphan.type).toBe("file");
+ expect(orphan.mime).toBe("application/pdf");
+ expect(orphan.getOwnedLabelValue("originalFileName")).toBe("report.pdf");
+ expect(decodeUtf8(orphan.getContent())).toBe("%PDF-1.4 fake");
+ });
+
+ it("materializes an unreferenced image as an image note", async () => {
+ const importRoot = await importObsidian({
+ "Note.md": "No embeds here.",
+ "logo.png": Buffer.from("\x89PNG\r\n\x1a\nfake-png")
+ });
+
+ const orphan = importRoot.getChildNotes().find((n) => n.type === "image");
+ expect(orphan?.title).toBe("logo.png");
+ expect(orphan?.mime).toBe("image/png");
+ expect(orphan?.getOwnedLabelValue("originalFileName")).toBe("logo.png");
+ });
+
+ it("does not also create a standalone note for a file that is embedded in a note", async () => {
+ const importRoot = await importObsidian({
+ "Note.md": "![[shot.png]]",
+ "shot.png": Buffer.from("\x89PNG\r\n\x1a\nfake")
+ });
+
+ // The image is an inline attachment of the note, not a duplicated standalone note.
+ const note = importRoot.getChildNotes().find((n) => n.title === "Note");
+ expect(note?.getAttachmentsByRole("image").map((a) => a.title)).toEqual(["shot.png"]);
+ expect(importRoot.getChildNotes().some((n) => n.type === "image")).toBe(false);
+ });
+
it("resolves a wikilink to a reference link and records an internalLink relation (backlink)", async () => {
const importRoot = await importObsidian({ "A.md": "See [[B]].", "B.md": "I am B." });
diff --git a/packages/trilium-core/src/services/import/obsidian/importer.ts b/packages/trilium-core/src/services/import/obsidian/importer.ts
index 3fc36c0efa..ba9b8daba0 100644
--- a/packages/trilium-core/src/services/import/obsidian/importer.ts
+++ b/packages/trilium-core/src/services/import/obsidian/importer.ts
@@ -4,7 +4,12 @@
* This pass reconstructs the *structure*: every `.md` file becomes a `text` note whose Markdown body is
* rendered to HTML, and the vault's folder hierarchy is mirrored as the note tree (a folder becomes an empty
* container note holding its notes). The `.obsidian/` config folder and any other dot-prefixed entry are
- * skipped, and non-Markdown files (attachments, `.canvas`, `.base`, …) are dropped for now.
+ * skipped, and `.canvas`/`.base` files are dropped for now.
+ *
+ * Other non-Markdown files are attachments: one embedded/linked from a note (`![[file]]` / `[[file]]`) is saved
+ * as an inline attachment of that note (see {@link ./attachments.js}); an unreferenced (orphan) file — dragged
+ * into the vault, or left behind after its note was deleted — becomes a standalone `file`/`image` note at its
+ * vault folder location, so no content is silently dropped.
*
* An Excalidraw-plugin drawing (`*.excalidraw.md`) is the exception to the "Markdown becomes a text note"
* rule: it's decoded into a Trilium `canvas` note instead, with its embedded images saved as attachments
@@ -35,11 +40,13 @@ import protectedSessionService from "../../protected_session.js";
import type TaskContext from "../../task_context.js";
import { decodeUtf8 } from "../../utils/binary.js";
import date_utils from "../../utils/date.js";
+import { removeFileExtension } from "../../utils/index.js";
import { basename } from "../../utils/path.js";
import { getZipProvider } from "../../zip_provider.js";
import { buildPromotedDefinition, toAttributeName } from "../collection_utils.js";
import { type FrontmatterAttribute, parseFrontmatter } from "../frontmatter.js";
import markdownService from "../markdown.js";
+import mimeService from "../mime.js";
import { applyAttachments, type AttachmentIndex, buildAttachmentIndex, isImageMime, resolveAttachment } from "./attachments.js";
import { type ExcalidrawDrawing, isExcalidrawPath, parseExcalidraw } from "./excalidraw.js";
import { buildNoteIndex, resolveLinks } from "./links.js";
@@ -129,6 +136,8 @@ function createNotes(importRootNote: BNote, notes: VaultNote[], attachments: Map
// Folder path (POSIX) -> its container note. The empty path maps to the import root.
const folderNotes = new Map<string, BNote>();
const created: { note: BNote; path: string; rendered: string; content: string; modified?: Date }[] = [];
+ // Vault paths of attachments materialized inline (embedded/linked); the rest are orphans, handled below.
+ const consumed = new Set<string>();
// First pass: create every note (so cross-note links can resolve below) with its Markdown rendered and
// attachments saved. Content is persisted once, in the link pass, to avoid a second write per note.
@@ -139,7 +148,7 @@ function createNotes(importRootNote: BNote, notes: VaultNote[], attachments: Map
// added to `created` (with empty content) so other notes can wikilink to it, but it carries no HTML
// for the link/attachment passes below. A drawing that can't be parsed falls through to text import.
if (isExcalidrawPath(vaultNote.path)) {
- const note = createExcalidrawNote(parent, vaultNote, attachmentIndex, isProtected);
+ const note = createExcalidrawNote(parent, vaultNote, attachmentIndex, isProtected, consumed);
if (note) {
created.push({ note, path: vaultNote.path.replace(/\.excalidraw\.md$/i, ""), rendered: "", content: "", modified: vaultNote.modified });
taskContext.increaseProgressCount();
@@ -160,7 +169,7 @@ function createNotes(importRootNote: BNote, notes: VaultNote[], attachments: Map
// Attachments hang off the note, so this runs after creation; it returns the content with embedded
// images/files rewritten to point at the saved attachments.
- const content = applyAttachments(note, rendered, attachmentIndex, shrinkImages);
+ const content = applyAttachments(note, rendered, attachmentIndex, shrinkImages, consumed);
created.push({ note, path: vaultNote.path, rendered, content, modified: vaultNote.modified });
taskContext.increaseProgressCount();
}
@@ -189,16 +198,44 @@ function createNotes(importRootNote: BNote, notes: VaultNote[], attachments: Map
}
}
+ // Third pass: any bundled file no note embedded or linked is an orphan (e.g. a file dragged into the
+ // vault, or one left behind after its note was deleted). Materialize it as a standalone file/image note at
+ // its vault folder location, mirroring the structure, so no vault content is silently dropped.
+ for (const path of [...attachments.keys()].sort((a, b) => a.localeCompare(b))) {
+ if (consumed.has(path)) {
+ continue;
+ }
+ const parent = ensureFolder(parentFolder(path), rootNote, folderNotes, isProtected);
+ createOrphanFileNote(parent, path, attachments.get(path), isProtected);
+ }
+
return rootNote;
}
+/**
+ * Creates a standalone note for an orphan (unreferenced) vault file: an `image` note for an image, a `file`
+ * note otherwise. The bytes become the note content, the title drops the extension (Trilium convention) which
+ * is preserved in an `originalFileName` label — matching how the generic ZIP importer treats arbitrary files.
+ */
+function createOrphanFileNote(parent: BNote, path: string, bytes: Uint8Array | undefined, isProtected: boolean): void {
+ /* v8 ignore next 3 -- defensive: `path` comes from the attachments map, so its bytes are always present */
+ if (!bytes) {
+ return;
+ }
+ const fileName = basename(path);
+ const mime = mimeService.getMime(fileName) || "application/octet-stream";
+ const type = isImageMime(mime) ? "image" : "file";
+ const { note } = noteService.createNewNote({ parentNoteId: parent.noteId, title: removeFileExtension(fileName, mime), content: bytes, type, mime, isProtected });
+ note.addLabel("originalFileName", fileName);
+}
+
/**
* Creates a `canvas` note from an Obsidian Excalidraw drawing, returning it (or `null` when the drawing can't
* be parsed, so the caller can fall back to a text note). Each image the scene embeds is resolved against the
* vault attachments and saved as an `image`-role attachment titled with its Excalidraw `fileId`, exactly how
* the canvas editor stores images, so the scene's `fileId` references render on load.
*/
-function createExcalidrawNote(parent: BNote, vaultNote: VaultNote, attachmentIndex: AttachmentIndex, isProtected: boolean): BNote | null {
+function createExcalidrawNote(parent: BNote, vaultNote: VaultNote, attachmentIndex: AttachmentIndex, isProtected: boolean, consumed: Set<string>): BNote | null {
const drawing: ExcalidrawDrawing | null = parseExcalidraw(vaultNote.markdown);
if (!drawing) {
return null;
@@ -209,6 +246,7 @@ function createExcalidrawNote(parent: BNote, vaultNote: VaultNote, attachmentInd
for (const [fileId, ref] of drawing.embeddedFiles) {
const resolved = resolveAttachment(attachmentIndex, ref);
if (resolved && isImageMime(resolved.mime)) {
+ consumed.add(resolved.path);
note.saveAttachment({ role: "image", mime: resolved.mime, title: fileId, content: resolved.bytes });
}
}