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
refactor(anytype): extract collection/property logic into collection.ts
Elian Doran7f1f99e993e1
diff --git a/packages/trilium-core/src/services/import/anytype/collection.spec.ts b/packages/trilium-core/src/services/import/anytype/collection.spec.tsnew file mode 100644index 0000000000..08593d728b--- /dev/null+++ b/packages/trilium-core/src/services/import/anytype/collection.spec.ts@@ -0,0 +1,241 @@+import { describe, expect, it } from "vitest";++import { buildColumnDefinition, toAttributeName } from "./collection.js";+import type { RelationInfo } from "./collection.js";+import { isCollectionObject, isPage, parseObject } from "./importer.js";+import type { AnytypeBlock, AnytypeMark, AnytypeSnapshot } from "./importer.js";++/** Wraps blocks + details into the export's snapshot shape. Details accepts arbitrary relation-key entries+ * (property values are keyed by the relation's hex `relationKey`). */+function snapshot(+ blocks: AnytypeBlock[],+ details: { id?: string; name?: string; layout?: number; resolvedLayout?: number; createdDate?: number; lastModifiedDate?: number; links?: string[]; [key: string]: unknown },+ sbType = "Page"+): AnytypeSnapshot {+ return { sbType, snapshot: { data: { blocks, details } } };+}++/** Builds a relation map (relationKey → info) from `[key, name, format, includeTime?]` tuples. */+function relationMap(entries: [string, string, number, boolean?][]): Map<string, RelationInfo> {+ return new Map(entries.map(([key, name, format, includeTime]) => [key, { name, format, includeTime }]));+}++/** The local-time `YYYY-MM-DD[THH:mm]` an epoch (seconds) should format to — computed via native Date+ * getters so the assertion is timezone-independent (the importer uses dayjs local formatting). */+function localDate(epochSeconds: number, withTime = false): string {+ const d = new Date(epochSeconds * 1000);+ const pad = (n: number) => String(n).padStart(2, "0");+ const date = `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;+ return withTime ? `${date}T${pad(d.getHours())}:${pad(d.getMinutes())}` : date;+}++/** A text block with the given style (defaults to Paragraph), optional children and optional marks. */+function textBlock(id: string, text: string, style = "Paragraph", childrenIds: string[] = [], marks: AnytypeMark[] = []): AnytypeBlock {+ return { id, text: { text, style, marks: { marks } }, childrenIds };+}++/** A typical page: a root block pointing at the header chrome plus the given content block ids. */+function page(name: string, contentBlocks: AnytypeBlock[], layout = 0): AnytypeSnapshot {+ return snapshot(+ [+ { id: "obj", childrenIds: ["header", ...contentBlocks.map((b) => b.id)] },+ { id: "header", childrenIds: ["title"] },+ textBlock("title", "", "Title"),+ ...contentBlocks+ ],+ { id: "obj", name, layout }+ );+}++describe("collection properties", () => {+ // Supported formats: 0 text, 2 number, 3 select, 4 date/date-time, 6 checkbox, 7 url, 8 email, 9 phone, 11 multi-select.+ const rels = relationMap([+ ["6a3e29d5cafa6953a4661c15", "Text property", 0],+ ["6a3e29e1cafa6953a4661c16", "Number prop", 2],+ ["6a3e29e8cafa6953a4661c17", "Select property", 3], // single-select (option-backed)+ ["6a3e330acafa6953a4661c6b", "Date", 4, false], // date (no time)+ ["6a3e3317cafa6953a4661c6e", "Date & Time", 4, true], // date-time (includeTime)+ ["6a3e3354cafa6953a4661c73", "Checkbox", 6],+ ["6a3e335dcafa6953a4661c74", "URL", 7],+ ["6a3e336dcafa6953a4661c75", "Email", 8],+ ["6a3e337dcafa6953a4661c76", "Phone", 9],+ ["6a3e2a01cafa6953a4661c1c", "Multi-select", 11], // multi-select (option-backed)+ ["6a3e3323cafa6953a4661c6f", "File", 5] // an unsupported format (skipped for now)+ ]);++ // Maps a select/multi-select option id to its display name.+ const options = new Map<string, string>([+ ["opt-first-cap", "First"],+ ["opt-second-cap", "Second"],+ ["opt-first", "first"],+ ["opt-second", "second"]+ ]);++ describe("toAttributeName", () => {+ it("camel-cases a column name into a valid attribute name", () => {+ expect(toAttributeName("URL")).toBe("url");+ expect(toAttributeName("Text property")).toBe("textProperty");+ expect(toAttributeName("Number prop")).toBe("numberProp");+ expect(toAttributeName("Date & Time")).toBe("dateTime");+ expect(toAttributeName(" ")).toBe("unnamed");+ });+ });++ describe("buildColumnDefinition", () => {+ it("builds a single-valued promoted definition keeping the original name as the alias", () => {+ expect(buildColumnDefinition("url", "URL")).toBe("promoted,single,url,alias=URL");+ expect(buildColumnDefinition("text", "Text property")).toBe("promoted,single,text,alias=Text property");+ });++ it("neutralizes commas, equals and control chars in the alias so the definition can't be corrupted", () => {+ expect(buildColumnDefinition("text", "a,b=c")).toBe("promoted,single,text,alias=a b c");+ });++ it("emits the column's multiplicity (multi for a multi-select)", () => {+ expect(buildColumnDefinition("text", "Multi-select", "multi")).toBe("promoted,multi,text,alias=Multi-select");+ });+ });++ describe("parseObject — property values", () => {+ it("maps supported property values to labels, schemes email/phone with mailto:/tel:", () => {+ const details = {+ id: "obj",+ name: "Row",+ "6a3e29d5cafa6953a4661c15": "hello",+ "6a3e29e1cafa6953a4661c16": 42,+ "6a3e330acafa6953a4661c6b": 1782461197, // Date (epoch seconds) → date only+ "6a3e3317cafa6953a4661c6e": 1782461208, // Date & Time → datetime+ "6a3e3354cafa6953a4661c73": true, // Checkbox → boolean+ "6a3e335dcafa6953a4661c74": "https://triliumnotes.org",+ "6a3e336dcafa6953a4661c75": "[email protected]",+ "6a3e337dcafa6953a4661c76": "12345",+ "6a3e3323cafa6953a4661c6f": ["log"] // File — unsupported, skipped+ };+ const result = parseObject(snapshot([{ id: "obj", childrenIds: [] }], details), undefined, rels);+ expect(result.properties).toEqual([+ { name: "textProperty", value: "hello" },+ { name: "numberProp", value: "42" },+ { name: "date", value: localDate(1782461197) },+ { name: "dateTime", value: localDate(1782461208, true) },+ { name: "checkbox", value: "true" },+ { name: "url", value: "https://triliumnotes.org" },+ { name: "email", value: "mailto:[email protected]" },+ { name: "phone", value: "tel:12345" }+ ]);+ });++ it("renders a false checkbox as boolean false (an unset value, not present, contributes nothing)", () => {+ const details = { id: "obj", "6a3e3354cafa6953a4661c73": false };+ expect(parseObject(snapshot([{ id: "obj", childrenIds: [] }], details), undefined, rels).properties).toEqual([{ name: "checkbox", value: "false" }]);+ });++ it("resolves select / multi-select option ids to text labels (a multi-select yields one label per option)", () => {+ const details = {+ id: "obj",+ "6a3e29e8cafa6953a4661c17": ["opt-first-cap"], // Select → single value+ "6a3e2a01cafa6953a4661c1c": ["opt-first", "opt-second"] // Multi-select → two values+ };+ const result = parseObject(snapshot([{ id: "obj", childrenIds: [] }], details), undefined, rels, options);+ expect(result.properties).toEqual([+ { name: "selectProperty", value: "First" },+ { name: "multiSelect", value: "first" },+ { name: "multiSelect", value: "second" }+ ]);+ });++ it("drops select / multi-select options that can't be resolved to a name", () => {+ const details = { id: "obj", "6a3e2a01cafa6953a4661c1c": ["opt-first", "unknown-option"] };+ const result = parseObject(snapshot([{ id: "obj", childrenIds: [] }], details), undefined, rels, options);+ expect(result.properties).toEqual([{ name: "multiSelect", value: "first" }]);+ });++ it("collects a file property's values as file references, not labels", () => {+ const details = { id: "obj", "6a3e3323cafa6953a4661c6f": ["file-cid-1", "file-cid-2"] };+ const result = parseObject(snapshot([{ id: "obj", childrenIds: [] }], details), undefined, rels);+ // Files become attachments (resolved at import time), so they're surfaced separately, never as labels.+ expect(result.fileRefs).toEqual(["file-cid-1", "file-cid-2"]);+ expect(result.properties).toEqual([]);+ });++ it("ignores system relations (non-hex keys), unset values and an existing scheme", () => {+ const details = {+ id: "obj",+ name: "Named", // the title, not a property+ description: "a system longtext", // system relation, non-hex key → not a property+ "6a3e335dcafa6953a4661c74": "", // unset url → skipped+ "6a3e336dcafa6953a4661c75": "mailto:[email protected]" // keeps its existing scheme+ };+ const result = parseObject(snapshot([{ id: "obj", childrenIds: [] }], details), undefined, rels);+ expect(result.properties).toEqual([{ name: "email", value: "mailto:[email protected]" }]);+ });++ it("returns no properties when no relation map is supplied", () => {+ const details = { id: "obj", name: "Row", "6a3e335dcafa6953a4661c74": "https://x" };+ expect(parseObject(snapshot([{ id: "obj", childrenIds: [] }], details)).properties).toEqual([]);+ });+ });++ describe("isCollectionObject", () => {+ const collectionDoc = (resolvedLayout: number, isCollection: boolean) =>+ snapshot([{ id: "obj", childrenIds: ["dv"] }, { id: "dv", childrenIds: [], dataview: { isCollection } }], { id: "obj", name: "Coll", resolvedLayout });++ it("accepts a collection (a Page with an isCollection dataview) even though its layout isn't basic", () => {+ // A real collection carries the collection layout (14), so isPage rejects it — isCollectionObject must not.+ expect(isCollectionObject(collectionDoc(14, true))).toBe(true);+ expect(isPage(collectionDoc(14, true))).toBe(false);+ });++ it("rejects a query set (dataview without isCollection) and a plain page", () => {+ expect(isCollectionObject(collectionDoc(3, false))).toBe(false);+ expect(isCollectionObject(page("Plain", [textBlock("b1", "body")]))).toBe(false);+ });+ });++ describe("parseObject — collection", () => {+ it("parses members from links and visible supported columns in view order", () => {+ const dv: AnytypeBlock = {+ id: "dv",+ childrenIds: [],+ dataview: {+ isCollection: true,+ views: [+ {+ relations: [+ { key: "6a3e335dcafa6953a4661c74", isVisible: true }, // URL → column+ { key: "name", isVisible: true }, // system column (non-hex key) → excluded+ { key: "6a3e3323cafa6953a4661c6f", isVisible: true }, // File (format 5) unsupported → excluded+ { key: "6a3e336dcafa6953a4661c75", isVisible: false } // Email hidden → excluded+ ]+ }+ ]+ }+ };+ const doc = snapshot([{ id: "obj", childrenIds: ["dv"] }, dv], { id: "obj", name: "My collection", links: ["m1", "m2"] });+ const result = parseObject(doc, undefined, rels);+ expect(result.collection).toEqual({+ memberIds: ["m1", "m2"],+ columns: [{ name: "url", labelType: "url", alias: "URL", multiplicity: "single" }]+ });+ });++ it("carries each column's multiplicity (multi for a multi-select)", () => {+ const dv: AnytypeBlock = {+ id: "dv",+ childrenIds: [],+ dataview: {+ isCollection: true,+ views: [{ relations: [{ key: "6a3e29e8cafa6953a4661c17", isVisible: true }, { key: "6a3e2a01cafa6953a4661c1c", isVisible: true }] }]+ }+ };+ const doc = snapshot([{ id: "obj", childrenIds: ["dv"] }, dv], { id: "obj", name: "C", links: [] });+ expect(parseObject(doc, undefined, rels).collection?.columns).toEqual([+ { name: "selectProperty", labelType: "text", alias: "Select property", multiplicity: "single" },+ { name: "multiSelect", labelType: "text", alias: "Multi-select", multiplicity: "multi" }+ ]);+ });++ it("leaves collection undefined for a regular (non-dataview) page", () => {+ expect(parseObject(page("Plain", [textBlock("b1", "body")]), undefined, rels).collection).toBeUndefined();+ });+ });+});diff --git a/packages/trilium-core/src/services/import/anytype/collection.ts b/packages/trilium-core/src/services/import/anytype/collection.tsnew file mode 100644index 0000000000..6c7e023618--- /dev/null+++ b/packages/trilium-core/src/services/import/anytype/collection.ts@@ -0,0 +1,376 @@+/**+ * Anytype collection & property handling: turns a collection's dataview into a Trilium table and an object's+ * custom relations into attributes/attachments.+ *+ * An Anytype collection is a `Page` whose dataview is flagged `isCollection`; its columns are the visible+ * relations of its first view and its members are `details.links`. This module reads the supporting metadata+ * — relation definitions ({@link buildRelationMap}), select/multi-select options ({@link buildOptionMap}) and+ * file objects ({@link buildFileObjectMap}) — then parses each object's property values+ * ({@link parseProperties}), file references ({@link parseFiles}) and collection schema+ * ({@link parseCollection}), and applies them to notes: a collection container ({@link createCollectionNote}),+ * a row's labels ({@link applyProperties}) and its file attachments ({@link applyFiles}). The structure+ * importer (importer.ts) owns page parsing and the note tree; it calls into here. Mirrors the Notion+ * importer's `collection.ts`.+ */++import { dayjs } from "@triliumnext/commons";++import type BNote from "../../../becca/entities/bnote.js";+import noteService from "../../notes.js";+import { escapeHtml } from "../../utils/index.js";+import { basename } from "../../utils/path.js";+import mimeService from "../mime.js";+import type { AnytypeBlock, AnytypeDetails, AnytypeSnapshot, ParsedObject } from "./importer.js";++/** Normalizes a zip entry / file path to forward slashes and lower case (Windows exports use backslashes),+ * so a file property's `source` matches the key its bytes were stored under. */+export function normalizePath(fileName: string): string {+ return fileName.replace(/\\/g, "/").toLowerCase();+}++/** Indexes the relation definitions by their `relationKey` (the key under which objects carry the value). */+export function buildRelationMap(relations: AnytypeSnapshot[]): Map<string, RelationInfo> {+ const map = new Map<string, RelationInfo>();+ for (const snapshot of relations) {+ const details = snapshot.snapshot?.data?.details;+ if (details?.relationKey) {+ map.set(details.relationKey, { name: details.name ?? "", format: details.relationFormat ?? -1, includeTime: !!details.relationFormatIncludeTime });+ }+ }+ return map;+}++/** Indexes the select / multi-select option values by id, so an object's stored option id resolves to its name. */+export function buildOptionMap(options: AnytypeSnapshot[]): Map<string, string> {+ const map = new Map<string, string>();+ for (const snapshot of options) {+ const details = snapshot.snapshot?.data?.details;+ if (details?.id) {+ map.set(details.id, details.name ?? "");+ }+ }+ return map;+}++/** Indexes the file objects by id, resolving each to the title, MIME and bytes-path a file property needs. */+export function buildFileObjectMap(fileObjects: AnytypeSnapshot[]): Map<string, FileObjectInfo> {+ const map = new Map<string, FileObjectInfo>();+ for (const snapshot of fileObjects) {+ const details = snapshot.snapshot?.data?.details;+ if (!details?.id) {+ continue;+ }+ const source = details.source ?? "";+ // The attachment title is the file's name: the source's base name, or the name + extension.+ const title = basename(normalizePath(source)) || `${details.name ?? "file"}${details.fileExt ? `.${details.fileExt}` : ""}`;+ map.set(details.id, { title, mime: details.fileMimeType ?? "", source });+ }+ return map;+}++/** The Anytype relation format for a file/object value — handled as an attachment, not a label/column. */+const FILE_FORMAT = 5;++/**+ * Maps an Anytype relation to how its values import, or undefined for a format not yet supported (file, …).+ * Date and date-time share format 4, told apart by the relation's `includeTime` flag; email and phone reuse+ * the `url` type with a `mailto:`/`tel:` scheme. Select and multi-select are `optionBacked` (their value is+ * a list of option ids resolved to names) and follow the Notion importer's single/multi text mapping.+ */+function propertyMapping(info: RelationInfo): PropertyMapping | undefined {+ switch (info.format) {+ case 0: // longtext+ case 1: // shorttext+ return { labelType: "text", multiplicity: "single" };+ case 2: // number+ return { labelType: "number", multiplicity: "single" };+ case 3: // status / single-select+ return { labelType: "text", multiplicity: "single", optionBacked: true };+ case 4: // date / date-time+ return { labelType: info.includeTime ? "datetime" : "date", multiplicity: "single" };+ case 6: // checkbox+ return { labelType: "boolean", multiplicity: "single" };+ case 7: // url+ return { labelType: "url", multiplicity: "single" };+ case 8: // email+ return { labelType: "url", scheme: "mailto:", multiplicity: "single" };+ case 9: // phone+ return { labelType: "url", scheme: "tel:", multiplicity: "single" };+ case 11: // tag / multi-select+ return { labelType: "text", multiplicity: "multi", optionBacked: true };+ default:+ return undefined;+ }+}++/** A custom (user-defined) relation key is a hex id; system relations (name, type, createdDate, …) are+ * plain words, and must not be imported as properties. */+function isCustomRelationKey(key: string): boolean {+ return /^[0-9a-f]{16,}$/.test(key);+}++/**+ * Reads an object's custom property values as `{ attributeName, value }` pairs. Only the supported formats+ * (see {@link propertyMapping}) of user-defined relations are taken; unset values are dropped, and email /+ * phone values gain a `mailto:`/`tel:` scheme so they stay clickable as url labels. A select / multi-select+ * value is a list of option ids, each resolved to its display name via `options` (a multi-select yields one+ * label per option; an unresolvable option is skipped).+ */+export function parseProperties(details: AnytypeDetails, relations: Map<string, RelationInfo>, options: Map<string, string>): ParsedProperty[] {+ const properties: ParsedProperty[] = [];+ for (const [key, raw] of Object.entries(details as Record<string, unknown>)) {+ if (!isCustomRelationKey(key)) {+ continue;+ }+ const info = relations.get(key);+ const mapping = info ? propertyMapping(info) : undefined;+ if (!info || !mapping) {+ continue;+ }+ const name = toAttributeName(info.name);+ if (mapping.optionBacked) {+ for (const optionId of Array.isArray(raw) ? raw : []) {+ const optionName = typeof optionId === "string" ? options.get(optionId) : undefined;+ if (optionName && optionName.trim()) {+ properties.push({ name, value: optionName });+ }+ }+ } else {+ const value = formatPropertyValue(raw, mapping.labelType, mapping.scheme);+ if (value !== undefined) {+ properties.push({ name, value });+ }+ }+ }+ return properties;+}++/**+ * Reads an object's file-property values as a flat list of file-object ids (a file relation's value is a+ * list of `FileObject` ids). They become `role:"file"` attachments at import time (see {@link applyFiles}),+ * not labels — the same as the Notion importer — so they're collected separately from {@link parseProperties}.+ */+export function parseFiles(details: AnytypeDetails, relations: Map<string, RelationInfo>): string[] {+ const refs: string[] = [];+ for (const [key, raw] of Object.entries(details as Record<string, unknown>)) {+ if (!isCustomRelationKey(key) || relations.get(key)?.format !== FILE_FORMAT) {+ continue;+ }+ for (const fileId of Array.isArray(raw) ? raw : []) {+ if (typeof fileId === "string") {+ refs.push(fileId);+ }+ }+ }+ return refs;+}++/**+ * Reads a collection's table schema and membership, or undefined when the page isn't a collection. The+ * members are its `details.links`; the columns are the *visible*, supported, custom relations of its first+ * dataview view, in their stored order, de-duplicated by attribute name.+ */+export function parseCollection(blocks: AnytypeBlock[], details: AnytypeDetails, relations: Map<string, RelationInfo>): ParsedCollection | undefined {+ const dataview = blocks.find((block) => block.dataview)?.dataview;+ if (!dataview?.isCollection) {+ return undefined;+ }++ const columns: ParsedColumn[] = [];+ const seen = new Set<string>();+ for (const relation of dataview.views?.[0]?.relations ?? []) {+ const key = relation.key;+ if (!relation.isVisible || !key || !isCustomRelationKey(key)) {+ continue;+ }+ const info = relations.get(key);+ const mapping = info ? propertyMapping(info) : undefined;+ if (!info || !mapping) {+ continue;+ }+ const name = toAttributeName(info.name);+ if (!seen.has(name)) {+ seen.add(name);+ columns.push({ name, labelType: mapping.labelType, alias: info.name, multiplicity: mapping.multiplicity });+ }+ }++ return { memberIds: details.links ?? [], columns };+}++/**+ * Converts a property value to its Trilium label string, or undefined when it should be dropped. A boolean+ * becomes `"true"`/`"false"`; a date (Anytype stores an epoch in *seconds*) becomes a local `YYYY-MM-DD` or+ * `YYYY-MM-DDTHH:mm` string the promoted date/datetime inputs round-trip; a number is stringified (a+ * non-numeric value rejected); a text/url value is trimmed-checked for emptiness; an email/phone value is+ * given its `mailto:`/`tel:` scheme unless it already carries one.+ */+function formatPropertyValue(raw: unknown, labelType: PropertyLabelType, scheme: string | undefined): string | undefined {+ if (raw === null || raw === undefined) {+ return undefined;+ }+ if (labelType === "boolean") {+ if (raw === true || raw === "true") {+ return "true";+ }+ return raw === false || raw === "false" ? "false" : undefined;+ }+ if (labelType === "date" || labelType === "datetime") {+ const seconds = typeof raw === "number" ? raw : Number(raw);+ if (!Number.isFinite(seconds)) {+ return undefined;+ }+ // Anytype stores the instant; format it in local time (like the Notion importer) so the date/time+ // matches the wall-clock the user saw in Anytype, in the format the promoted date/datetime inputs use.+ const local = dayjs(new Date(seconds * 1000));+ return labelType === "datetime" ? local.format("YYYY-MM-DD[T]HH:mm") : local.format("YYYY-MM-DD");+ }+ if (labelType === "number") {+ const num = typeof raw === "number" ? raw : Number(String(raw));+ return Number.isFinite(num) ? String(num) : undefined;+ }+ const value = typeof raw === "string" ? raw : String(raw);+ if (!value.trim()) {+ return undefined;+ }+ if (scheme) {+ return value.startsWith(scheme) ? value : `${scheme}${value}`;+ }+ return value;+}++/**+ * Converts an Anytype property name to a camelCase Trilium attribute name (e.g. `Text property` →+ * `textProperty`, `URL` → `url`, `Date & Time` → `dateTime`). The original name is kept as the promoted+ * alias (see {@link buildColumnDefinition}). A name with no alphanumeric content falls back to `unnamed`.+ */+export function toAttributeName(name: string): string {+ const words = name.match(/[\p{L}\p{N}]+/gu);+ if (!words) {+ return "unnamed";+ }+ return words.map((word, index) => (index === 0 ? word.toLowerCase() : word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())).join("");+}++/**+ * Builds a promoted-attribute definition for a collection column (e.g. `promoted,single,url,alias=URL`, or+ * `promoted,multi,text,alias=Multi-select`). The original column name is kept verbatim as the alias so its+ * spacing and casing still show in the UI; commas, equals and control characters are neutralized so they+ * can't corrupt the comma/`=`-delimited definition string.+ */+export function buildColumnDefinition(labelType: PropertyLabelType, alias: string, multiplicity: Multiplicity = "single"): string {+ const safeAlias = alias.replace(/[\x00-\x1f,=]/g, " ").trim();+ return `promoted,${multiplicity},${labelType},alias=${safeAlias}`;+}++/**+ * Creates a collection's container note: an empty `book` with a `table` view whose columns are the+ * collection's supported properties, each an *inheritable* promoted-attribute definition (so the table+ * renders the column and every member row inherits the field, showing its own value or blank). Mirrors the+ * Notion importer's database mapping.+ */+export function createCollectionNote(parentNoteId: string, page: ParsedObject, collection: ParsedCollection, noteId: string | undefined, isProtected: boolean | undefined): BNote {+ const { note } = noteService.createNewNote({ noteId, parentNoteId, title: page.title, content: "", type: "book", mime: "", isProtected, utcDateCreated: page.dateCreated });+ note.addLabel("viewType", "table");++ // Increasing positions keep the columns in their Anytype view order (the promoted-attributes UI sorts by+ // position, and equal positions aren't ordered deterministically).+ let position = 0;+ for (const column of collection.columns) {+ position += 10;+ note.addAttribute("label", `label:${column.name}`, buildColumnDefinition(column.labelType, column.alias, column.multiplicity), true, position);+ }+ return note;+}++/** Applies a page's custom property values to its note as labels. */+export function applyProperties(note: BNote, properties: ParsedProperty[]) {+ for (const property of properties) {+ note.addLabel(property.name, property.value);+ }+}++/**+ * Saves each of a page's file-property files as a `role:"file"` attachment and prepends a reference link to+ * the body — the same as the Notion importer, so the files are reachable from the note's content as well as+ * its attachments list. A file object missing from the export (no metadata, or bytes absent) is skipped.+ */+export function applyFiles(note: BNote, page: ParsedObject, fileObjects: Map<string, FileObjectInfo>, files: Map<string, Uint8Array>) {+ const fileLinks: string[] = [];+ for (const fileId of page.fileRefs) {+ const info = fileObjects.get(fileId);+ const bytes = info ? files.get(normalizePath(info.source)) : undefined;+ if (!info || !bytes) {+ continue;+ }+ const attachment = note.saveAttachment({+ role: "file",+ mime: info.mime || mimeService.getMime(info.title) || "application/octet-stream",+ title: info.title,+ content: bytes+ });+ if (attachment.attachmentId) {+ fileLinks.push(`<p><a class="reference-link" href="#root/${note.noteId}?viewMode=attachments&attachmentId=${attachment.attachmentId}">${escapeHtml(info.title)}</a></p>`);+ }+ }++ if (fileLinks.length > 0) {+ // The note already holds its body (page content, or "" for a collection); prepend the file links.+ note.setContent(fileLinks.join("") + (page.collection ? "" : page.content));+ }+}++// #region Model+/** A relation definition resolved from the `relations/` folder: its display name, Anytype format code and+ * (for date formats) whether the value carries a time component. */+export interface RelationInfo {+ name: string;+ format: number;+ includeTime?: boolean;+}++/** A file object resolved from the `filesObjects/` folder: the attachment title, MIME and the `files/` path+ * its raw bytes live at. */+export interface FileObjectInfo {+ title: string;+ mime: string;+ source: string;+}++/** The Trilium label types a supported Anytype property maps to (email/phone reuse `url`). */+export type PropertyLabelType = "text" | "number" | "url" | "date" | "datetime" | "boolean";++/** Whether a property holds a single value or several (a multi-select). */+export type Multiplicity = "single" | "multi";++/** How a relation's values import: its Trilium label type, value count, an optional clickable scheme+ * (email/phone), and whether the value is option-backed (a select / multi-select, resolved via the options+ * map). */+interface PropertyMapping {+ labelType: PropertyLabelType;+ multiplicity: Multiplicity;+ scheme?: string;+ optionBacked?: boolean;+}++/** One custom property value on an object: the Trilium attribute name and its (already formatted) value. */+export interface ParsedProperty {+ name: string;+ value: string;+}++/** One collection table column: its attribute name, Trilium label type, original (alias) name and value count. */+export interface ParsedColumn {+ name: string;+ labelType: PropertyLabelType;+ alias: string;+ multiplicity: Multiplicity;+}++/** A collection's table schema and membership. `memberIds` are Anytype object ids (its `details.links`);+ * `columns` are the visible, supported columns from its dataview, in order. */+export interface ParsedCollection {+ memberIds: string[];+ columns: ParsedColumn[];+}+// #endregiondiff --git a/packages/trilium-core/src/services/import/anytype/importer.spec.ts b/packages/trilium-core/src/services/import/anytype/importer.spec.tsindex 907ce25a6c..2a01c794d6 100644--- a/packages/trilium-core/src/services/import/anytype/importer.spec.ts+++ b/packages/trilium-core/src/services/import/anytype/importer.spec.ts@@ -1,7 +1,7 @@import { describe, expect, it } from "vitest";-import { anytypeDate, buildColumnDefinition, isCollectionObject, isPage, parseObject, renderCodeBlock, renderInlineText, toAttributeName } from "./importer.js";-import type { AnytypeBlock, AnytypeMark, AnytypeSnapshot, LinkResolver, RelationInfo } 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. Details accepts arbitrary relation-key entries* (property values are keyed by the relation's hex `relationKey`). */@@ -13,20 +13,6 @@ function snapshot(return { sbType, snapshot: { data: { blocks, details } } };}-/** Builds a relation map (relationKey → info) from `[key, name, format, includeTime?]` tuples. */-function relationMap(entries: [string, string, number, boolean?][]): Map<string, RelationInfo> {- return new Map(entries.map(([key, name, format, includeTime]) => [key, { name, format, includeTime }]));-}--/** The local-time `YYYY-MM-DD[THH:mm]` an epoch (seconds) should format to — computed via native Date- * getters so the assertion is timezone-independent (the importer uses dayjs local formatting). */-function localDate(epochSeconds: number, withTime = false): string {- const d = new Date(epochSeconds * 1000);- const pad = (n: number) => String(n).padStart(2, "0");- const date = `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;- return withTime ? `${date}T${pad(d.getHours())}:${pad(d.getMinutes())}` : date;-}-/** A text block with the given style (defaults to Paragraph), optional children and optional marks. */function textBlock(id: string, text: string, style = "Paragraph", childrenIds: string[] = [], marks: AnytypeMark[] = []): AnytypeBlock {return { id, text: { text, style, marks: { marks } }, childrenIds };@@ -339,199 +325,6 @@ describe("dates", () => {});});-describe("collection properties", () => {- // Supported formats: 0 text, 2 number, 3 select, 4 date/date-time, 6 checkbox, 7 url, 8 email, 9 phone, 11 multi-select.- const rels = relationMap([- ["6a3e29d5cafa6953a4661c15", "Text property", 0],- ["6a3e29e1cafa6953a4661c16", "Number prop", 2],- ["6a3e29e8cafa6953a4661c17", "Select property", 3], // single-select (option-backed)- ["6a3e330acafa6953a4661c6b", "Date", 4, false], // date (no time)- ["6a3e3317cafa6953a4661c6e", "Date & Time", 4, true], // date-time (includeTime)- ["6a3e3354cafa6953a4661c73", "Checkbox", 6],- ["6a3e335dcafa6953a4661c74", "URL", 7],- ["6a3e336dcafa6953a4661c75", "Email", 8],- ["6a3e337dcafa6953a4661c76", "Phone", 9],- ["6a3e2a01cafa6953a4661c1c", "Multi-select", 11], // multi-select (option-backed)- ["6a3e3323cafa6953a4661c6f", "File", 5] // an unsupported format (skipped for now)- ]);-- // Maps a select/multi-select option id to its display name.- const options = new Map<string, string>([- ["opt-first-cap", "First"],- ["opt-second-cap", "Second"],- ["opt-first", "first"],- ["opt-second", "second"]- ]);-- describe("toAttributeName", () => {- it("camel-cases a column name into a valid attribute name", () => {- expect(toAttributeName("URL")).toBe("url");- expect(toAttributeName("Text property")).toBe("textProperty");- expect(toAttributeName("Number prop")).toBe("numberProp");- expect(toAttributeName("Date & Time")).toBe("dateTime");- expect(toAttributeName(" ")).toBe("unnamed");- });- });-- describe("buildColumnDefinition", () => {- it("builds a single-valued promoted definition keeping the original name as the alias", () => {- expect(buildColumnDefinition("url", "URL")).toBe("promoted,single,url,alias=URL");- expect(buildColumnDefinition("text", "Text property")).toBe("promoted,single,text,alias=Text property");- });-- it("neutralizes commas, equals and control chars in the alias so the definition can't be corrupted", () => {- expect(buildColumnDefinition("text", "a,b=c")).toBe("promoted,single,text,alias=a b c");- });-- it("emits the column's multiplicity (multi for a multi-select)", () => {- expect(buildColumnDefinition("text", "Multi-select", "multi")).toBe("promoted,multi,text,alias=Multi-select");- });- });-- describe("parseObject — property values", () => {- it("maps supported property values to labels, schemes email/phone with mailto:/tel:", () => {- const details = {- id: "obj",- name: "Row",- "6a3e29d5cafa6953a4661c15": "hello",- "6a3e29e1cafa6953a4661c16": 42,- "6a3e330acafa6953a4661c6b": 1782461197, // Date (epoch seconds) → date only- "6a3e3317cafa6953a4661c6e": 1782461208, // Date & Time → datetime- "6a3e3354cafa6953a4661c73": true, // Checkbox → boolean- "6a3e335dcafa6953a4661c74": "https://triliumnotes.org",- "6a3e336dcafa6953a4661c75": "[email protected]",- "6a3e337dcafa6953a4661c76": "12345",- "6a3e3323cafa6953a4661c6f": ["log"] // File — unsupported, skipped- };- const result = parseObject(snapshot([{ id: "obj", childrenIds: [] }], details), undefined, rels);- expect(result.properties).toEqual([- { name: "textProperty", value: "hello" },- { name: "numberProp", value: "42" },- { name: "date", value: localDate(1782461197) },- { name: "dateTime", value: localDate(1782461208, true) },- { name: "checkbox", value: "true" },- { name: "url", value: "https://triliumnotes.org" },- { name: "email", value: "mailto:[email protected]" },- { name: "phone", value: "tel:12345" }- ]);- });-- it("renders a false checkbox as boolean false (an unset value, not present, contributes nothing)", () => {- const details = { id: "obj", "6a3e3354cafa6953a4661c73": false };- expect(parseObject(snapshot([{ id: "obj", childrenIds: [] }], details), undefined, rels).properties).toEqual([{ name: "checkbox", value: "false" }]);- });-- it("resolves select / multi-select option ids to text labels (a multi-select yields one label per option)", () => {- const details = {- id: "obj",- "6a3e29e8cafa6953a4661c17": ["opt-first-cap"], // Select → single value- "6a3e2a01cafa6953a4661c1c": ["opt-first", "opt-second"] // Multi-select → two values- };- const result = parseObject(snapshot([{ id: "obj", childrenIds: [] }], details), undefined, rels, options);- expect(result.properties).toEqual([- { name: "selectProperty", value: "First" },- { name: "multiSelect", value: "first" },- { name: "multiSelect", value: "second" }- ]);- });-- it("drops select / multi-select options that can't be resolved to a name", () => {- const details = { id: "obj", "6a3e2a01cafa6953a4661c1c": ["opt-first", "unknown-option"] };- const result = parseObject(snapshot([{ id: "obj", childrenIds: [] }], details), undefined, rels, options);- expect(result.properties).toEqual([{ name: "multiSelect", value: "first" }]);- });-- it("collects a file property's values as file references, not labels", () => {- const details = { id: "obj", "6a3e3323cafa6953a4661c6f": ["file-cid-1", "file-cid-2"] };- const result = parseObject(snapshot([{ id: "obj", childrenIds: [] }], details), undefined, rels);- // Files become attachments (resolved at import time), so they're surfaced separately, never as labels.- expect(result.fileRefs).toEqual(["file-cid-1", "file-cid-2"]);- expect(result.properties).toEqual([]);- });-- it("ignores system relations (non-hex keys), unset values and an existing scheme", () => {- const details = {- id: "obj",- name: "Named", // the title, not a property- description: "a system longtext", // system relation, non-hex key → not a property- "6a3e335dcafa6953a4661c74": "", // unset url → skipped- "6a3e336dcafa6953a4661c75": "mailto:[email protected]" // keeps its existing scheme- };- const result = parseObject(snapshot([{ id: "obj", childrenIds: [] }], details), undefined, rels);- expect(result.properties).toEqual([{ name: "email", value: "mailto:[email protected]" }]);- });-- it("returns no properties when no relation map is supplied", () => {- const details = { id: "obj", name: "Row", "6a3e335dcafa6953a4661c74": "https://x" };- expect(parseObject(snapshot([{ id: "obj", childrenIds: [] }], details)).properties).toEqual([]);- });- });-- describe("isCollectionObject", () => {- const collectionDoc = (resolvedLayout: number, isCollection: boolean) =>- snapshot([{ id: "obj", childrenIds: ["dv"] }, { id: "dv", childrenIds: [], dataview: { isCollection } }], { id: "obj", name: "Coll", resolvedLayout });-- it("accepts a collection (a Page with an isCollection dataview) even though its layout isn't basic", () => {- // A real collection carries the collection layout (14), so isPage rejects it — isCollectionObject must not.- expect(isCollectionObject(collectionDoc(14, true))).toBe(true);- expect(isPage(collectionDoc(14, true))).toBe(false);- });-- it("rejects a query set (dataview without isCollection) and a plain page", () => {- expect(isCollectionObject(collectionDoc(3, false))).toBe(false);- expect(isCollectionObject(page("Plain", [textBlock("b1", "body")]))).toBe(false);- });- });-- describe("parseObject — collection", () => {- it("parses members from links and visible supported columns in view order", () => {- const dv: AnytypeBlock = {- id: "dv",- childrenIds: [],- dataview: {- isCollection: true,- views: [- {- relations: [- { key: "6a3e335dcafa6953a4661c74", isVisible: true }, // URL → column- { key: "name", isVisible: true }, // system column (non-hex key) → excluded- { key: "6a3e3323cafa6953a4661c6f", isVisible: true }, // File (format 5) unsupported → excluded- { key: "6a3e336dcafa6953a4661c75", isVisible: false } // Email hidden → excluded- ]- }- ]- }- };- const doc = snapshot([{ id: "obj", childrenIds: ["dv"] }, dv], { id: "obj", name: "My collection", links: ["m1", "m2"] });- const result = parseObject(doc, undefined, rels);- expect(result.collection).toEqual({- memberIds: ["m1", "m2"],- columns: [{ name: "url", labelType: "url", alias: "URL", multiplicity: "single" }]- });- });-- it("carries each column's multiplicity (multi for a multi-select)", () => {- const dv: AnytypeBlock = {- id: "dv",- childrenIds: [],- dataview: {- isCollection: true,- views: [{ relations: [{ key: "6a3e29e8cafa6953a4661c17", isVisible: true }, { key: "6a3e2a01cafa6953a4661c1c", isVisible: true }] }]- }- };- const doc = snapshot([{ id: "obj", childrenIds: ["dv"] }, dv], { id: "obj", name: "C", links: [] });- expect(parseObject(doc, undefined, rels).collection?.columns).toEqual([- { name: "selectProperty", labelType: "text", alias: "Select property", multiplicity: "single" },- { name: "multiSelect", labelType: "text", alias: "Multi-select", multiplicity: "multi" }- ]);- });-- it("leaves collection undefined for a regular (non-dataview) page", () => {- expect(parseObject(page("Plain", [textBlock("b1", "body")]), undefined, rels).collection).toBeUndefined();- });- });-});-describe("renderInlineText", () => {it("returns escaped plain text when there are no marks", () => {expect(renderInlineText("a < b & c > d", [])).toBe("a < b & c > d");diff --git a/packages/trilium-core/src/services/import/anytype/importer.ts b/packages/trilium-core/src/services/import/anytype/importer.tsindex f92a16a5b0..f79df39a6a 100644--- a/packages/trilium-core/src/services/import/anytype/importer.ts+++ b/packages/trilium-core/src/services/import/anytype/importer.ts@@ -9,16 +9,18 @@* 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). 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).+ * backlinks resolve). Each page keeps its original creation and modification timestamps.+ *+ * Collections and their properties are handled in {@link ./collection.js}: a collection becomes a `book`+ * with a `table` view whose columns are promoted-attribute definitions, its members nest beneath it, and an+ * object's custom relations become labels / file attachments. Pages without a collection land as flat+ * children of a fresh "Anytype import" root. Types and templates are still deferred.** 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 —* this service just builds the tree and returns its root note, like the zip/notion importers.*/-import { dayjs } from "@triliumnext/commons";import { getMimeTypeFromMarkdownName, MIME_TYPE_AUTO, normalizeMimeTypeForCKEditor } from "@triliumnext/commons/src/lib/mime_type.js";import { t } from "i18next";@@ -29,9 +31,9 @@ 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 { basename } from "../../utils/path.js";import { getZipProvider } from "../../zip_provider.js";-import mimeService from "../mime.js";+import { applyFiles, applyProperties, buildFileObjectMap, buildOptionMap, buildRelationMap, createCollectionNote, normalizePath, parseCollection, parseFiles, parseProperties } from "./collection.js";+import type { FileObjectInfo, ParsedCollection, ParsedProperty, RelationInfo } from "./collection.js";async function importAnytype(taskContext: TaskContext<"importNotes">, fileBuffer: Uint8Array, importRootNote: BNote): Promise<BNote> {const { objects, relations, options, fileObjects, files } = await parseZip(fileBuffer);@@ -131,51 +133,6 @@ function isJsonEntryUnder(fileName: string, folder: string): boolean {return normalized.startsWith(folder) && normalized.endsWith(".pb.json");}-/** Normalizes a zip entry path to forward slashes and lower case (Windows exports use backslashes). */-function normalizePath(fileName: string): string {- return fileName.replace(/\\/g, "/").toLowerCase();-}--/** Indexes the relation definitions by their `relationKey` (the key under which objects carry the value). */-function buildRelationMap(relations: AnytypeSnapshot[]): Map<string, RelationInfo> {- const map = new Map<string, RelationInfo>();- for (const snapshot of relations) {- const details = snapshot.snapshot?.data?.details;- if (details?.relationKey) {- map.set(details.relationKey, { name: details.name ?? "", format: details.relationFormat ?? -1, includeTime: !!details.relationFormatIncludeTime });- }- }- return map;-}--/** Indexes the select / multi-select option values by id, so an object's stored option id resolves to its name. */-function buildOptionMap(options: AnytypeSnapshot[]): Map<string, string> {- const map = new Map<string, string>();- for (const snapshot of options) {- const details = snapshot.snapshot?.data?.details;- if (details?.id) {- map.set(details.id, details.name ?? "");- }- }- return map;-}--/** Indexes the file objects by id, resolving each to the title, MIME and bytes-path a file property needs. */-function buildFileObjectMap(fileObjects: AnytypeSnapshot[]): Map<string, FileObjectInfo> {- const map = new Map<string, FileObjectInfo>();- for (const snapshot of fileObjects) {- const details = snapshot.snapshot?.data?.details;- if (!details?.id) {- continue;- }- const source = details.source ?? "";- // The attachment title is the file's name: the source's base name, or the name + extension.- const title = basename(normalizePath(source)) || `${details.name ?? "file"}${details.fileExt ? `.${details.fileExt}` : ""}`;- map.set(details.id, { title, mime: details.fileMimeType ?? "", source });- }- return map;-}-/*** Whether a snapshot is a page we should import. A page is a `Page` smartblock with the basic layout (0);* this excludes sets/collections (layout 3) and system objects like the participant, workspace and@@ -237,203 +194,6 @@ function pageTitle(details: AnytypeDetails | undefined): string {return (details?.name ?? "").trim() || "Untitled";}-// #region Collection properties-/** The Anytype relation format for a file/object value — handled as an attachment, not a label/column. */-const FILE_FORMAT = 5;--/**- * Maps an Anytype relation to how its values import, or undefined for a format not yet supported (file, …).- * Date and date-time share format 4, told apart by the relation's `includeTime` flag; email and phone reuse- * the `url` type with a `mailto:`/`tel:` scheme. Select and multi-select are `optionBacked` (their value is- * a list of option ids resolved to names) and follow the Notion importer's single/multi text mapping.- */-function propertyMapping(info: RelationInfo): PropertyMapping | undefined {- switch (info.format) {- case 0: // longtext- case 1: // shorttext- return { labelType: "text", multiplicity: "single" };- case 2: // number- return { labelType: "number", multiplicity: "single" };- case 3: // status / single-select- return { labelType: "text", multiplicity: "single", optionBacked: true };- case 4: // date / date-time- return { labelType: info.includeTime ? "datetime" : "date", multiplicity: "single" };- case 6: // checkbox- return { labelType: "boolean", multiplicity: "single" };- case 7: // url- return { labelType: "url", multiplicity: "single" };- case 8: // email- return { labelType: "url", scheme: "mailto:", multiplicity: "single" };- case 9: // phone- return { labelType: "url", scheme: "tel:", multiplicity: "single" };- case 11: // tag / multi-select- return { labelType: "text", multiplicity: "multi", optionBacked: true };- default:- return undefined;- }-}--/** A custom (user-defined) relation key is a hex id; system relations (name, type, createdDate, …) are- * plain words, and must not be imported as properties. */-function isCustomRelationKey(key: string): boolean {- return /^[0-9a-f]{16,}$/.test(key);-}--/**- * Reads an object's custom property values as `{ attributeName, value }` pairs. Only the supported formats- * (see {@link propertyMapping}) of user-defined relations are taken; unset values are dropped, and email /- * phone values gain a `mailto:`/`tel:` scheme so they stay clickable as url labels. A select / multi-select- * value is a list of option ids, each resolved to its display name via `options` (a multi-select yields one- * label per option; an unresolvable option is skipped).- */-function parseProperties(details: AnytypeDetails, relations: Map<string, RelationInfo>, options: Map<string, string>): ParsedProperty[] {- const properties: ParsedProperty[] = [];- for (const [key, raw] of Object.entries(details as Record<string, unknown>)) {- if (!isCustomRelationKey(key)) {- continue;- }- const info = relations.get(key);- const mapping = info ? propertyMapping(info) : undefined;- if (!info || !mapping) {- continue;- }- const name = toAttributeName(info.name);- if (mapping.optionBacked) {- for (const optionId of Array.isArray(raw) ? raw : []) {- const optionName = typeof optionId === "string" ? options.get(optionId) : undefined;- if (optionName && optionName.trim()) {- properties.push({ name, value: optionName });- }- }- } else {- const value = formatPropertyValue(raw, mapping.labelType, mapping.scheme);- if (value !== undefined) {- properties.push({ name, value });- }- }- }- return properties;-}--/**- * Reads an object's file-property values as a flat list of file-object ids (a file relation's value is a- * list of `FileObject` ids). They become `role:"file"` attachments at import time (see {@link createNotes}),- * not labels — the same as the Notion importer — so they're collected separately from {@link parseProperties}.- */-function parseFiles(details: AnytypeDetails, relations: Map<string, RelationInfo>): string[] {- const refs: string[] = [];- for (const [key, raw] of Object.entries(details as Record<string, unknown>)) {- if (!isCustomRelationKey(key) || relations.get(key)?.format !== FILE_FORMAT) {- continue;- }- for (const fileId of Array.isArray(raw) ? raw : []) {- if (typeof fileId === "string") {- refs.push(fileId);- }- }- }- return refs;-}--/**- * Reads a collection's table schema and membership, or undefined when the page isn't a collection. The- * members are its `details.links`; the columns are the *visible*, supported, custom relations of its first- * dataview view, in their stored order, de-duplicated by attribute name.- */-function parseCollection(blocks: AnytypeBlock[], details: AnytypeDetails, relations: Map<string, RelationInfo>): ParsedCollection | undefined {- const dataview = blocks.find((block) => block.dataview)?.dataview;- if (!dataview?.isCollection) {- return undefined;- }-- const columns: ParsedColumn[] = [];- const seen = new Set<string>();- for (const relation of dataview.views?.[0]?.relations ?? []) {- const key = relation.key;- if (!relation.isVisible || !key || !isCustomRelationKey(key)) {- continue;- }- const info = relations.get(key);- const mapping = info ? propertyMapping(info) : undefined;- if (!info || !mapping) {- continue;- }- const name = toAttributeName(info.name);- if (!seen.has(name)) {- seen.add(name);- columns.push({ name, labelType: mapping.labelType, alias: info.name, multiplicity: mapping.multiplicity });- }- }-- return { memberIds: details.links ?? [], columns };-}--/**- * Converts a property value to its Trilium label string, or undefined when it should be dropped. A boolean- * becomes `"true"`/`"false"`; a date (Anytype stores an epoch in *seconds*) becomes a local `YYYY-MM-DD` or- * `YYYY-MM-DDTHH:mm` string the promoted date/datetime inputs round-trip; a number is stringified (a- * non-numeric value rejected); a text/url value is trimmed-checked for emptiness; an email/phone value is- * given its `mailto:`/`tel:` scheme unless it already carries one.- */-function formatPropertyValue(raw: unknown, labelType: PropertyLabelType, scheme: string | undefined): string | undefined {- if (raw === null || raw === undefined) {- return undefined;- }- if (labelType === "boolean") {- if (raw === true || raw === "true") {- return "true";- }- return raw === false || raw === "false" ? "false" : undefined;- }- if (labelType === "date" || labelType === "datetime") {- const seconds = typeof raw === "number" ? raw : Number(raw);- if (!Number.isFinite(seconds)) {- return undefined;- }- // Anytype stores the instant; format it in local time (like the Notion importer) so the date/time- // matches the wall-clock the user saw in Anytype, in the format the promoted date/datetime inputs use.- const local = dayjs(new Date(seconds * 1000));- return labelType === "datetime" ? local.format("YYYY-MM-DD[T]HH:mm") : local.format("YYYY-MM-DD");- }- if (labelType === "number") {- const num = typeof raw === "number" ? raw : Number(String(raw));- return Number.isFinite(num) ? String(num) : undefined;- }- const value = typeof raw === "string" ? raw : String(raw);- if (!value.trim()) {- return undefined;- }- if (scheme) {- return value.startsWith(scheme) ? value : `${scheme}${value}`;- }- return value;-}--/**- * Converts an Anytype property name to a camelCase Trilium attribute name (e.g. `Text property` →- * `textProperty`, `URL` → `url`, `Date & Time` → `dateTime`). The original name is kept as the promoted- * alias (see {@link buildColumnDefinition}). A name with no alphanumeric content falls back to `unnamed`.- */-export function toAttributeName(name: string): string {- const words = name.match(/[\p{L}\p{N}]+/gu);- if (!words) {- return "unnamed";- }- return words.map((word, index) => (index === 0 ? word.toLowerCase() : word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())).join("");-}--/**- * Builds a promoted-attribute definition for a collection column (e.g. `promoted,single,url,alias=URL`, or- * `promoted,multi,text,alias=Multi-select`). The original column name is kept verbatim as the alias so its- * spacing and casing still show in the UI; commas, equals and control characters are neutralized so they- * can't corrupt the comma/`=`-delimited definition string.- */-export function buildColumnDefinition(labelType: PropertyLabelType, alias: string, multiplicity: Multiplicity = "single"): string {- const safeAlias = alias.replace(/[\x00-\x1f,=]/g, " ").trim();- return `promoted,${multiplicity},${labelType},alias=${safeAlias}`;-}-// #endregion-/*** 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@@ -865,63 +625,6 @@ function createNotes(importRootNote: BNote, pages: ParsedObject[], targets: Map<return rootNote;}-/**- * Creates a collection's container note: an empty `book` with a `table` view whose columns are the- * collection's supported properties, each an *inheritable* promoted-attribute definition (so the table- * renders the column and every member row inherits the field, showing its own value or blank). Mirrors the- * Notion importer's database mapping.- */-function createCollectionNote(parentNoteId: string, page: ParsedObject, collection: ParsedCollection, noteId: string | undefined, isProtected: boolean | undefined): BNote {- const { note } = noteService.createNewNote({ noteId, parentNoteId, title: page.title, content: "", type: "book", mime: "", isProtected, utcDateCreated: page.dateCreated });- note.addLabel("viewType", "table");-- // Increasing positions keep the columns in their Anytype view order (the promoted-attributes UI sorts by- // position, and equal positions aren't ordered deterministically).- let position = 0;- for (const column of collection.columns) {- position += 10;- note.addAttribute("label", `label:${column.name}`, buildColumnDefinition(column.labelType, column.alias, column.multiplicity), true, position);- }- return note;-}--/** Applies a page's custom property values to its note as labels. */-function applyProperties(note: BNote, properties: ParsedProperty[]) {- for (const property of properties) {- note.addLabel(property.name, property.value);- }-}--/**- * Saves each of a page's file-property files as a `role:"file"` attachment and prepends a reference link to- * the body — the same as the Notion importer, so the files are reachable from the note's content as well as- * its attachments list. A file object missing from the export (no metadata, or bytes absent) is skipped.- */-function applyFiles(note: BNote, page: ParsedObject, fileObjects: Map<string, FileObjectInfo>, files: Map<string, Uint8Array>) {- const fileLinks: string[] = [];- for (const fileId of page.fileRefs) {- const info = fileObjects.get(fileId);- const bytes = info ? files.get(normalizePath(info.source)) : undefined;- if (!info || !bytes) {- continue;- }- const attachment = note.saveAttachment({- role: "file",- mime: info.mime || mimeService.getMime(info.title) || "application/octet-stream",- title: info.title,- content: bytes- });- if (attachment.attachmentId) {- fileLinks.push(`<p><a class="reference-link" href="#root/${note.noteId}?viewMode=attachments&attachmentId=${attachment.attachmentId}">${escapeHtml(info.title)}</a></p>`);- }- }-- if (fileLinks.length > 0) {- // The note already holds its body (page content, or "" for a collection); prepend the file links.- note.setContent(fileLinks.join("") + (page.collection ? "" : page.content));- }-}-/*** Restores a page's 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@@ -1072,59 +775,6 @@ export interface ResolvedLink {/** Resolves an Anytype object id (CID) to the Trilium note it was imported as, or undefined when the* target wasn't imported (a set/collection, or an object missing from the export). */export type LinkResolver = (targetCid: string) => ResolvedLink | undefined;--/** A relation definition resolved from the `relations/` folder: its display name, Anytype format code and- * (for date formats) whether the value carries a time component. */-export interface RelationInfo {- name: string;- format: number;- includeTime?: boolean;-}--/** A file object resolved from the `filesObjects/` folder: the attachment title, MIME and the `files/` path- * its raw bytes live at. */-export interface FileObjectInfo {- title: string;- mime: string;- source: string;-}--/** The Trilium label types a supported Anytype property maps to (email/phone reuse `url`). */-export type PropertyLabelType = "text" | "number" | "url" | "date" | "datetime" | "boolean";--/** Whether a property holds a single value or several (a multi-select). */-export type Multiplicity = "single" | "multi";--/** How a relation's values import: its Trilium label type, value count, an optional clickable scheme- * (email/phone), and whether the value is option-backed (a select / multi-select, resolved via the options- * map). */-interface PropertyMapping {- labelType: PropertyLabelType;- multiplicity: Multiplicity;- scheme?: string;- optionBacked?: boolean;-}--/** One custom property value on an object: the Trilium attribute name and its (already formatted) value. */-export interface ParsedProperty {- name: string;- value: string;-}--/** One collection table column: its attribute name, Trilium label type, original (alias) name and value count. */-export interface ParsedColumn {- name: string;- labelType: PropertyLabelType;- alias: string;- multiplicity: Multiplicity;-}--/** A collection's table schema and membership. `memberIds` are Anytype object ids (its `details.links`);- * `columns` are the visible, supported columns from its dataview, in order. */-export interface ParsedCollection {- memberIds: string[];- columns: ParsedColumn[];-}// #endregionexport default { importAnytype };