Skip to content

Build your personal knowledge base with Trilium Notes

feat(anytype): preserve page creation and modification dates

Elian Doran1b50b5546f03
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.ts
index 29ba20f196..a8dd7cb800 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
@@ -417,6 +417,38 @@ describe("Anytype importer — integration", () => {
expect(note?.getRelations().filter((r) => r.name === "internalLink")).toHaveLength(0);
});
+ it("preserves a page's created and modified dates from Anytype's detail timestamps", async () => {
+ const page = JSON.stringify({
+ sbType: "Page",
+ snapshot: {
+ data: {
+ blocks: [
+ { id: "d", childrenIds: ["header", "d-b0"] },
+ { id: "header", childrenIds: ["title"] },
+ { id: "title", text: { text: "", style: "Title" } },
+ { id: "d-b0", text: { text: "Body", style: "Paragraph" } }
+ ],
+ // Verbatim timestamps from the "Article 6 Electronic Contracts" page (Unix seconds).
+ details: { id: "d", name: "Dated", resolvedLayout: 0, createdDate: 1735632037, lastModifiedDate: 1735632353 }
+ }
+ }
+ });
+ const importRoot = await importAnytype({ "objects/d.pb.json": page });
+
+ const note = importRoot.getChildNotes().find((n) => n.title === "Dated");
+ expect(note?.utcDateCreated).toBe("2024-12-31 08:00:37.000Z");
+ expect(note?.utcDateModified).toBe("2024-12-31 08:05:53.000Z");
+ });
+
+ it("leaves a page with no Anytype dates with valid import-time dates", async () => {
+ const importRoot = await importAnytype({ "objects/p.pb.json": pageObject("p", "Undated", ["Body"]) });
+
+ const note = importRoot.getChildNotes().find((n) => n.title === "Undated");
+ // Untouched: a date-less page keeps the import-time timestamps, still in the valid UTC format.
+ expect(note?.utcDateCreated).toMatch(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3}Z$/);
+ expect(note?.utcDateModified).toMatch(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3}Z$/);
+ });
+
it("produces an empty root when the export has no pages", async () => {
const importRoot = await importAnytype({
"types/type1.pb.json": JSON.stringify({ sbType: "STType", snapshot: { data: { details: { id: "type1", name: "Article" } } } })
diff --git a/packages/trilium-core/src/services/import/anytype/importer.spec.ts b/packages/trilium-core/src/services/import/anytype/importer.spec.ts
index c517f8d735..c05db1e416 100644
--- a/packages/trilium-core/src/services/import/anytype/importer.spec.ts
+++ b/packages/trilium-core/src/services/import/anytype/importer.spec.ts
@@ -1,10 +1,14 @@
import { describe, expect, it } from "vitest";
-import { isPage, parseObject, renderCodeBlock, renderInlineText } from "./importer.js";
+import { anytypeDate, isPage, parseObject, renderCodeBlock, renderInlineText } from "./importer.js";
import type { AnytypeBlock, AnytypeMark, AnytypeSnapshot, LinkResolver } from "./importer.js";
/** Wraps blocks + details into the export's snapshot shape. */
-function snapshot(blocks: AnytypeBlock[], details: { id?: string; name?: string; layout?: number; resolvedLayout?: number }, sbType = "Page"): AnytypeSnapshot {
+function snapshot(
+ blocks: AnytypeBlock[],
+ details: { id?: string; name?: string; layout?: number; resolvedLayout?: number; createdDate?: number; lastModifiedDate?: number },
+ sbType = "Page"
+): AnytypeSnapshot {
return { sbType, snapshot: { data: { blocks, details } } };
}
@@ -293,6 +297,33 @@ describe("links", () => {
});
});
+describe("dates", () => {
+ it("converts an Anytype detail timestamp (Unix seconds) to a Trilium UTC datetime string", () => {
+ // Verbatim createdDate from the "Article 6 Electronic Contracts" page.
+ expect(anytypeDate(1735632037)).toBe("2024-12-31 08:00:37.000Z");
+ });
+
+ it("treats a missing or non-positive timestamp as absent (system objects export 0)", () => {
+ expect(anytypeDate(undefined)).toBeUndefined();
+ expect(anytypeDate(0)).toBeUndefined();
+ expect(anytypeDate(-5)).toBeUndefined();
+ expect(anytypeDate(Number.NaN)).toBeUndefined();
+ });
+
+ it("carries a page's created and modified dates through parseObject", () => {
+ const doc = snapshot([{ id: "obj", childrenIds: [] }], { id: "obj", name: "Dated", createdDate: 1735632037, lastModifiedDate: 1735632353 });
+ const result = parseObject(doc);
+ expect(result.dateCreated).toBe("2024-12-31 08:00:37.000Z");
+ expect(result.dateModified).toBe("2024-12-31 08:05:53.000Z");
+ });
+
+ it("leaves both dates undefined when the page carries none", () => {
+ const result = parseObject(page("Undated", [textBlock("b1", "body")]));
+ expect(result.dateCreated).toBeUndefined();
+ expect(result.dateModified).toBeUndefined();
+ });
+});
+
describe("renderInlineText", () => {
it("returns escaped plain text when there are no marks", () => {
expect(renderInlineText("a < b & c > d", [])).toBe("a &lt; b &amp; c &gt; d");
diff --git a/packages/trilium-core/src/services/import/anytype/importer.ts b/packages/trilium-core/src/services/import/anytype/importer.ts
index dfc396b2a0..86eef28cbe 100644
--- a/packages/trilium-core/src/services/import/anytype/importer.ts
+++ b/packages/trilium-core/src/services/import/anytype/importer.ts
@@ -9,8 +9,9 @@
* nested), toggles (normal toggles → collapsible blocks; toggle headings → plain headings), callouts
* (→ admonitions), quotes/highlights (→ `<blockquote>`), dividers (→ `<hr>`) and cross-page links
* (Anytype's block-level "link to object" → a Trilium reference link plus an `internalLink` relation, so
- * backlinks resolve). Relations, types and collections are still deferred, and every page lands as a flat
- * child of a fresh "Anytype import" root (no hierarchy yet).
+ * backlinks resolve). Each page keeps its original creation and modification timestamps. Relations, types
+ * and collections are still deferred, and every page lands as a flat child of a fresh "Anytype import"
+ * root (no hierarchy yet).
*
* Invoked from the shared file-import dispatcher (routes/api/import.ts) when the upload is tagged
* `format=anytype`, so progress, completion and failure are reported by that dispatcher's TaskContext —
@@ -24,6 +25,7 @@ import type BNote from "../../../becca/entities/bnote.js";
import noteService from "../../notes.js";
import protectedSessionService from "../../protected_session.js";
import type TaskContext from "../../task_context.js";
+import date_utils from "../../utils/date.js";
import { escapeHtml, newEntityId } from "../../utils/index.js";
import { getZipProvider } from "../../zip_provider.js";
@@ -110,7 +112,14 @@ export function parseObject(snapshot: AnytypeSnapshot, resolveLink: LinkResolver
const title = pageTitle(details);
const { html, linkTargetIds } = extractContent(data?.blocks ?? [], id, resolveLink);
- return { id, title, content: html, linkTargetIds };
+ return {
+ id,
+ title,
+ content: html,
+ linkTargetIds,
+ dateCreated: anytypeDate(details.createdDate),
+ dateModified: anytypeDate(details.lastModifiedDate)
+ };
}
/** The note title for a page: its trimmed `details.name`, or "Untitled" when blank. */
@@ -118,6 +127,18 @@ function pageTitle(details: AnytypeDetails | undefined): string {
return (details?.name ?? "").trim() || "Untitled";
}
+/**
+ * Converts an Anytype detail date (a Unix timestamp in *seconds*) to a Trilium UTC datetime string, or
+ * undefined for a missing or non-positive value — system objects export `0`, which would otherwise become
+ * a 1970 date.
+ */
+export function anytypeDate(seconds: number | undefined): string | undefined {
+ if (typeof seconds !== "number" || !Number.isFinite(seconds) || seconds <= 0) {
+ return undefined;
+ }
+ return date_utils.utcDateTimeStr(new Date(seconds * 1000));
+}
+
/**
* Converts the page's block tree to HTML. A sequence of sibling blocks is rendered in document order, with
* consecutive list items of the same kind grouped into a single `<ul>`/`<ol>`/todo-list and a list item's
@@ -478,7 +499,16 @@ function createNotes(importRootNote: BNote, pages: ParsedObject[], targets: Map<
const notesByPageId = new Map<string, BNote>();
for (const page of pages) {
- const { note } = noteService.createNewNote({ noteId: targets.get(page.id)?.noteId, parentNoteId: rootNote.noteId, title: page.title, content: page.content, type: "text", mime: "text/html", isProtected });
+ const { note } = noteService.createNewNote({ noteId: targets.get(page.id)?.noteId, parentNoteId: rootNote.noteId, title: page.title, content: page.content, type: "text", mime: "text/html", isProtected, utcDateCreated: page.dateCreated });
+
+ // Restore the original timestamps (note creation stamps "modified" — and the blob — with now). A
+ // date-less page is left untouched, keeping its import-time dates. When only one date is present we
+ // fall back like the ENEX importer: modified defaults to created.
+ if (page.dateCreated || page.dateModified) {
+ const dateCreated = page.dateCreated ?? note.utcDateCreated;
+ note.setDateCreatedAndModified(dateCreated, page.dateModified ?? dateCreated);
+ }
+
notesByPageId.set(page.id, note);
taskContext.increaseProgressCount();
}
@@ -556,6 +586,10 @@ export interface AnytypeDetails {
name?: string;
layout?: number;
resolvedLayout?: number;
+ /** Page creation time as a Unix timestamp in seconds. Omitted/`0` for system objects. */
+ createdDate?: number;
+ /** Page last-modification time as a Unix timestamp in seconds. */
+ lastModifiedDate?: number;
}
/** One exported object file: `sbType` is the smartblock kind ("Page", "Participant", "Workspace", …) and
@@ -580,6 +614,10 @@ export interface ParsedObject {
content: string;
/** De-duplicated Trilium note ids this page links to, for recording `internalLink` relations. */
linkTargetIds: string[];
+ /** Creation time as a Trilium UTC datetime string (from Anytype's `createdDate`), if available. */
+ dateCreated?: string;
+ /** Last-modification time as a Trilium UTC datetime string (from `lastModifiedDate`), if available. */
+ dateModified?: string;
}
/** The imported note a linked-to Anytype object resolved to: its Trilium id and (fallback) title. */