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
feat(import): import file members of collection-scoped Anytype exports
Elian Doran9b6023607af6
diff --git a/packages/trilium-core/src/services/import/anytype/content.spec.ts b/packages/trilium-core/src/services/import/anytype/content.spec.tsindex d11e13aaa2..0be04b0cd8 100644--- a/packages/trilium-core/src/services/import/anytype/content.spec.ts+++ b/packages/trilium-core/src/services/import/anytype/content.spec.ts@@ -238,6 +238,17 @@ describe("inline files", () => {const doc = listDoc(["f1"], [fileBlock("f1", { type: "Image", name: "pending.png", state: "Uploading" })]);expect(parseObject(doc).content).toBe("");});++ it("surfaces the embedded file ids (so the importer knows which files a page references)", () => {+ const doc = listDoc(+ ["f1", "f2"],+ [+ fileBlock("f1", { type: "Image", name: "pic.png", targetObjectId: "img-cid" }),+ fileBlock("f2", { type: "PDF", name: "doc.pdf", targetObjectId: "pdf-cid" })+ ]+ );+ expect(parseObject(doc).inlineFileIds).toEqual(["img-cid", "pdf-cid"]);+ });});describe("renderInlineText", () => {diff --git a/packages/trilium-core/src/services/import/anytype/content.ts b/packages/trilium-core/src/services/import/anytype/content.tsindex 20f5204606..81fd5b44c9 100644--- a/packages/trilium-core/src/services/import/anytype/content.ts+++ b/packages/trilium-core/src/services/import/anytype/content.ts@@ -25,7 +25,7 @@ import type { AnytypeBlock, AnytypeMark, LinkResolver } from "./model.js";* styles wherever they appear. The de-duplicated Trilium ids of every linked-to page are returned* alongside the HTML so the caller can record the `internalLink` relations.*/-export function extractContent(blocks: AnytypeBlock[], rootId: string, resolveLink: LinkResolver): { html: string; linkTargetIds: string[] } {+export function extractContent(blocks: AnytypeBlock[], rootId: string, resolveLink: LinkResolver): { html: string; linkTargetIds: string[]; fileTargetIds: string[] } {const byId = new Map<string, AnytypeBlock>();for (const block of blocks) {byId.set(block.id, block);@@ -33,12 +33,15 @@ export function extractContent(blocks: AnytypeBlock[], rootId: string, resolveLiconst root = (rootId ? byId.get(rootId) : undefined) ?? blocks[0];if (!root) {- return { html: "", linkTargetIds: [] };+ return { html: "", linkTargetIds: [], fileTargetIds: [] };}const visited = new Set<string>();const linkTargetIds = new Set<string>();const addLink = (noteId: string) => linkTargetIds.add(noteId);+ // The FileObject ids the body embeds inline (image/file blocks), so the importer can tell which exported+ // files a page already references — and, for a collection-scoped export, which are unreferenced members.+ const fileTargetIds = new Set<string>();// Renders a run of sibling ids, grouping consecutive same-kind list items into one list. The header// chrome and already-visited blocks (a node reachable twice) are skipped.@@ -120,6 +123,7 @@ export function extractContent(blocks: AnytypeBlock[], rootId: string, resolveLiif (!targetId) {return "";}+ fileTargetIds.add(targetId);if (block.file.type === "Image") {return `<figure class="image"><img src="${escapeHtml(targetId)}"></figure>`;}@@ -184,7 +188,7 @@ export function extractContent(blocks: AnytypeBlock[], rootId: string, resolveLi// The root block is the page container and carries no text of its own — start from its children.const html = renderSequence(root.childrenIds ?? []);- return { html, linkTargetIds: [...linkTargetIds] };+ return { html, linkTargetIds: [...linkTargetIds], fileTargetIds: [...fileTargetIds] };}/** The kind of list a block belongs to (bullet/ordered/task), or null when it isn't a list item. */diff --git a/packages/trilium-core/src/services/import/anytype/importer.integration.spec.ts b/packages/trilium-core/src/services/import/anytype/importer.integration.spec.tsindex 162f5bd482..7deb1d859a 100644--- a/packages/trilium-core/src/services/import/anytype/importer.integration.spec.ts+++ b/packages/trilium-core/src/services/import/anytype/importer.integration.spec.ts@@ -943,6 +943,64 @@ describe("Anytype importer — integration", () => {expect(rows.find((n) => n.getOwnedLabelValue("url"))?.getOwnedLabelValue("url")).toBe("https://triliumnotes.org");});+ it("imports a file member of a collection-scoped export (no membership list) as a file note under the root", async () => {+ // Exporting just the collection drops the wrapper (so no `links` membership) and the file's own+ // createdInContext points at where it was first added, not the collection — so the only signal the+ // bundled, page-unreferenced file is a member is its presence. It still becomes a file note.+ const ctx = "bafyreicollectioncontext";+ const fileCid = "bafyreiscopedfile";+ const importRoot = await importAnytype(+ {+ "objects/m1.pb.json": memberObject("m1", { createdInContext: ctx }),+ "filesObjects/f1.pb.json": fileObjectJson(fileCid, "report", "pdf", "text/plain", "files\\report.pdf"),+ "files/report.pdf": Buffer.from("%PDF-1.4 scoped")+ },+ "Ordered collection.zip"+ );++ expect(importRoot.title).toBe("Ordered collection");+ const children = importRoot.getChildNotes();+ // The page member (Untitled) plus the recovered file member.+ expect(children.map((n) => n.title).sort()).toEqual(["Untitled", "report.pdf"]);+ const fileNote = children.find((n) => n.type === "file");+ expect(fileNote?.mime).toBe("application/pdf");+ expect(decodeUtf8(fileNote?.getContent() ?? "")).toBe("%PDF-1.4 scoped");+ });++ it("does not duplicate a member page's inline file as a separate collection member", async () => {+ // In a collection-scoped export the inline image's FileObject is bundled too; it must stay the page's+ // inline attachment, not also surface as a sibling member note.+ const ctx = "bafyreicollectioncontext";+ const imgCid = "bafyreiinlineimg";+ const page = JSON.stringify({+ sbType: "Page",+ snapshot: {+ data: {+ blocks: [+ { id: "m1", childrenIds: ["header", "img"] },+ { id: "header", childrenIds: ["title"] },+ { id: "title", text: { text: "", style: "Title" } },+ { id: "img", file: { type: "Image", name: "pic.png", targetObjectId: imgCid, state: "Done", style: "Embed" } }+ ],+ details: { id: "m1", name: "Has image", resolvedLayout: 0, createdInContext: ctx }+ }+ }+ });+ const importRoot = await importAnytype(+ {+ "objects/m1.pb.json": page,+ "filesObjects/f1.pb.json": fileObjectJson(imgCid, "pic", "png", "image/png", "files\\pic.png"),+ "files/pic.png": Buffer.from("\x89PNG\r\n\x1a\nfake-png")+ },+ "Gallery.zip"+ );++ const children = importRoot.getChildNotes();+ // Only the member page — the image is its inline attachment, not a separate member note.+ expect(children.map((n) => n.title)).toEqual(["Has image"]);+ expect(children[0].getAttachmentsByRole("image")).toHaveLength(1);+ });+it("keeps the default 'Anytype import' text root for a regular multi-page export", async () => {const importRoot = await importAnytype({diff --git a/packages/trilium-core/src/services/import/anytype/importer.ts b/packages/trilium-core/src/services/import/anytype/importer.tsindex c238a5e2c6..06a4af0df7 100644--- a/packages/trilium-core/src/services/import/anytype/importer.ts+++ b/packages/trilium-core/src/services/import/anytype/importer.ts@@ -90,7 +90,7 @@ async function importAnytype(taskContext: TaskContext<"importNotes">, fileBufferconst pages = pageSnapshots.map((snapshot) => parseObject(snapshot, resolveLink, relationMap, optionMap));taskContext.setTotalCount(pages.length);- return createNotes(importRootNote, pages, targets, fileObjectMap, files, rootTitle, rootColumns, taskContext);+ return createNotes(importRootNote, pages, targets, fileObjectMap, files, rootTitle, rootColumns, collectionExport, taskContext);}/**@@ -252,7 +252,7 @@ export function parseObject(snapshot: AnytypeSnapshot, resolveLink: LinkResolverconst details = data?.details ?? {};const id = details.id ?? "";const title = pageTitle(details);- const { html, linkTargetIds } = extractContent(data?.blocks ?? [], id, resolveLink);+ const { html, linkTargetIds, fileTargetIds } = extractContent(data?.blocks ?? [], id, resolveLink);return {id,@@ -263,6 +263,7 @@ export function parseObject(snapshot: AnytypeSnapshot, resolveLink: LinkResolverdateModified: anytypeDate(details.lastModifiedDate),properties: parseProperties(details, relations, options),fileRefs: parseFiles(details, relations),+ inlineFileIds: fileTargetIds,collection: parseCollection(data?.blocks ?? [], details, relations)};}@@ -291,12 +292,15 @@ export function anytypeDate(seconds: number | undefined): string | undefined {* already baked into the content point at the real notes, and carries its own property values as labels. A* collection's members are parented under it (their first collection) — a member in further collections is* cloned into each. File-property values become `role:"file"` attachments with a reference link prepended to- * the body. Once every page exists, each page's outgoing links are recorded as `internalLink` relations,- * which Trilium uses for backlink detection ("what links here").+ * the body. A file object that's itself a collection member becomes a `file`/`image` note under the+ * collection (in a collection-scoped export, where the membership list is lost, any unreferenced bundled file+ * is treated as such a member). Once every page exists, each page's outgoing links are recorded as+ * `internalLink` relations, which Trilium uses for backlink detection ("what links here").*/-function createNotes(importRootNote: BNote, pages: ParsedObject[], targets: Map<string, ResolvedLink>, fileObjects: Map<string, FileObjectInfo>, files: Map<string, Uint8Array>, rootTitle: string | undefined, rootColumns: ParsedColumn[] | undefined, taskContext: TaskContext<"importNotes">): BNote {+function createNotes(importRootNote: BNote, pages: ParsedObject[], targets: Map<string, ResolvedLink>, fileObjects: Map<string, FileObjectInfo>, files: Map<string, Uint8Array>, rootTitle: string | undefined, rootColumns: ParsedColumn[] | undefined, collectionExport: boolean, taskContext: TaskContext<"importNotes">): BNote {/* v8 ignore next -- the protected branch needs a protected import root with an active protected session, which the in-memory test DB has no way to set up */const isProtected = importRootNote.isProtected && protectedSessionService.isProtectedSessionAvailable();+ const shrinkImages = !!taskContext.data?.shrinkImages;// A collection-scoped export's root *is* the collection: a `table`-view book carrying the synthesized// columns, with the member pages as its rows. A normal export's root is a plain container.@@ -337,7 +341,7 @@ function createNotes(importRootNote: BNote, pages: ParsedObject[], targets: Map<applyProperties(note, page.properties);applyFiles(note, page, fileObjects, files);- applyInlineFiles(note, fileObjects, files);+ applyInlineFiles(note, fileObjects, files, shrinkImages);applyDates(note, page);notesByPageId.set(page.id, note);taskContext.increaseProgressCount();@@ -355,7 +359,30 @@ function createNotes(importRootNote: BNote, pages: ParsedObject[], targets: Map<}const primaryCollectionId = primaryCollectionByMember.get(fileId);const parentNoteId = (primaryCollectionId ? notesByPageId.get(primaryCollectionId)?.noteId : undefined) ?? rootNote.noteId;- notesByPageId.set(fileId, createFileMemberNote(parentNoteId, info, bytes, isProtected));+ notesByPageId.set(fileId, createFileMemberNote(parentNoteId, info, bytes, isProtected, shrinkImages));+ }++ // A collection-scoped export omits the collection wrapper, so a file dropped into the collection loses its+ // membership signal — there's no `links`, and the file's `createdInContext` points at where it was first+ // added (a page), not the collection. Recover it: in a collection-scoped export, any bundled file the+ // member pages don't already reference (inline, or as a file property) is a member of the synthesized root+ // collection — create a `file`/`image` note for it under the root.+ if (collectionExport) {+ const referenced = new Set<string>();+ for (const page of pages) {+ for (const id of [...page.fileRefs, ...page.inlineFileIds]) {+ referenced.add(id);+ }+ }+ for (const [fileId, info] of fileObjects) {+ if (notesByPageId.has(fileId) || referenced.has(fileId)) {+ continue;+ }+ const bytes = files.get(normalizePath(info.source));+ if (bytes) {+ notesByPageId.set(fileId, createFileMemberNote(rootNote.noteId, info, bytes, isProtected, shrinkImages));+ }+ }}// Membership: clone a member into every collection that isn't already its (primary) parent.@@ -398,9 +425,9 @@ function fileMemberIds(pages: ParsedObject[], notesByPageId: Map<string, BNote>,/** Creates a Trilium note for a file dropped into a collection: an `image` note for an image (so it renders* inline), otherwise a `file` note holding the raw bytes — both children of the owning collection. */-function createFileMemberNote(parentNoteId: string, info: FileObjectInfo, bytes: Uint8Array, isProtected: boolean | undefined): BNote {+function createFileMemberNote(parentNoteId: string, info: FileObjectInfo, bytes: Uint8Array, isProtected: boolean | undefined, shrinkImages: boolean): BNote {if (info.mime.startsWith("image/")) {- return imageService.saveImage(parentNoteId, bytes, info.title, false).note;+ return imageService.saveImage(parentNoteId, bytes, info.title, shrinkImages).note;}const { note } = noteService.createNewNote({ parentNoteId, title: info.title, content: bytes, type: "file", mime: info.mime || "application/octet-stream", isProtected });note.addLabel("originalFileName", info.title);@@ -416,7 +443,7 @@ function createFileMemberNote(parentNoteId: string, info: FileObjectInfo, bytes:* placeholder whose file is missing from the export (no metadata or bytes — e.g. a still-uploading file) is* dropped (image) or left as plain text (other). Only re-saves the content when something changed.*/-function applyInlineFiles(note: BNote, fileObjects: Map<string, FileObjectInfo>, files: Map<string, Uint8Array>) {+function applyInlineFiles(note: BNote, fileObjects: Map<string, FileObjectInfo>, files: Map<string, Uint8Array>, shrinkImages: boolean) {const content = decodeUtf8(note.getContent());// Cheap guard: parse only when the body actually holds a placeholder to resolve.if (!content.includes("<img") && !content.includes('class="anytype-file"')) {@@ -437,7 +464,7 @@ function applyInlineFiles(note: BNote, fileObjects: Map<string, FileObjectInfo>,continue;}const info = fileObjects.get(targetId);- const { attachmentId, title } = imageService.saveImageToAttachment(note.noteId, bytes, info?.title || "image", false);+ const { attachmentId, title } = imageService.saveImageToAttachment(note.noteId, bytes, info?.title || "image", shrinkImages);/* v8 ignore next -- saveImageToAttachment always returns the id of the attachment it just created, so this guard is never false in practice */if (attachmentId) {img.setAttribute("src", `api/attachments/${attachmentId}/image/${encodeURIComponent(title)}`);diff --git a/packages/trilium-core/src/services/import/anytype/model.ts b/packages/trilium-core/src/services/import/anytype/model.tsindex dcbbc13dbd..d31369efeb 100644--- a/packages/trilium-core/src/services/import/anytype/model.ts+++ b/packages/trilium-core/src/services/import/anytype/model.ts@@ -167,6 +167,9 @@ export interface ParsedObject {properties: ParsedProperty[];/** File-object ids from the object's file properties; resolved to `role:"file"` attachments at import. */fileRefs: string[];+ /** File-object ids the body embeds inline (image/file blocks). Tracks which exported files a page already+ * references, so a collection-scoped export can tell its unreferenced file members apart from these. */+ inlineFileIds: string[];/** Present when the object is a collection: its table schema and membership. */collection?: ParsedCollection;}