Skip to content

Build your personal knowledge base with Trilium Notes

feat(import): parse Markdown YAML front matter into labels

Elian Doranfd061e55ad0a
diff --git a/packages/trilium-core/package.json b/packages/trilium-core/package.json
index 116468e035..050d118c9c 100644
--- a/packages/trilium-core/package.json
+++ b/packages/trilium-core/package.json
@@ -14,6 +14,7 @@
"chardet": "2.2.0",
"escape-html": "1.0.3",
"i18next": "26.3.1",
+ "js-yaml": "5.1.0",
"mime-types": "3.0.2",
"node-html-parser": "8.0.3",
"sanitize-filename": "1.6.4",
diff --git a/packages/trilium-core/src/services/import/frontmatter.spec.ts b/packages/trilium-core/src/services/import/frontmatter.spec.ts
new file mode 100644
index 0000000000..52dcb572dd
--- /dev/null
+++ b/packages/trilium-core/src/services/import/frontmatter.spec.ts
@@ -0,0 +1,51 @@
+import { describe, expect, it } from "vitest";
+
+import { extractFrontmatter } from "./frontmatter.js";
+
+describe("extractFrontmatter", () => {
+ it("parses scalar properties into camelCased labels and strips the block from the body", () => {
+ const { body, attributes } = extractFrontmatter("---\nfirst: First value\nDate Time: 2026-06-27T15:10:00\n---\nBody text.");
+ expect(body).toBe("Body text.");
+ expect(attributes).toEqual([
+ { name: "first", value: "First value" },
+ { name: "dateTime", value: "2026-06-27T15:10:00" }
+ ]);
+ });
+
+ it("expands a list property into one label per item", () => {
+ const { attributes } = extractFrontmatter("---\ntags:\n - Tag\n - AnotherTag\n---\n");
+ expect(attributes).toEqual([
+ { name: "tags", value: "Tag" },
+ { name: "tags", value: "AnotherTag" }
+ ]);
+ });
+
+ it("stringifies booleans/numbers and keeps an empty property as an empty-valued label", () => {
+ const { attributes } = extractFrontmatter("---\nCheckbox prop: true\nNumber: 5\nfirst:\n---\n");
+ expect(attributes).toEqual([
+ { name: "checkboxProp", value: "true" },
+ { name: "number", value: "5" },
+ { name: "first", value: "" }
+ ]);
+ });
+
+ it("leaves a note without front matter untouched", () => {
+ const { body, attributes } = extractFrontmatter("# Title\n\nNo front matter here.");
+ expect(body).toBe("# Title\n\nNo front matter here.");
+ expect(attributes).toEqual([]);
+ });
+
+ it("ignores a --- divider that isn't at the very start of the file", () => {
+ const md = "Intro\n\n---\nkey: value\n---\n";
+ const { body, attributes } = extractFrontmatter(md);
+ expect(body).toBe(md);
+ expect(attributes).toEqual([]);
+ });
+
+ it("keeps the note intact when the front matter YAML is malformed", () => {
+ const md = "---\nkey: [unclosed\n---\nBody.";
+ const { body, attributes } = extractFrontmatter(md);
+ expect(body).toBe(md);
+ expect(attributes).toEqual([]);
+ });
+});
diff --git a/packages/trilium-core/src/services/import/frontmatter.ts b/packages/trilium-core/src/services/import/frontmatter.ts
new file mode 100644
index 0000000000..80b03b9361
--- /dev/null
+++ b/packages/trilium-core/src/services/import/frontmatter.ts
@@ -0,0 +1,92 @@
+/**
+ * Generic YAML front matter parsing for Markdown imports.
+ *
+ * A Markdown file may begin with a `---\n…\n---` YAML block — the de-facto convention shared by Obsidian,
+ * Jekyll, Hugo, Foam and others. This module splits that block off the body and turns each property into a
+ * Trilium label: the name is sanitized to a camelCase attribute name with the same {@link toAttributeName}
+ * helper the structured importers (Notion, Anytype) use, and the value is stringified (a list yields one
+ * label per item). It is deliberately format-agnostic and infers no semantic types — date/number/checkbox
+ * typing and special keys (tags, aliases) layer on top of this in the format-specific importer.
+ */
+
+import { load } from "js-yaml";
+
+import { toAttributeName } from "./collection_utils.js";
+
+export interface FrontmatterAttribute {
+ name: string;
+ value: string;
+}
+
+export interface ParsedFrontmatter {
+ /** The Markdown with the leading front matter block removed. */
+ body: string;
+ /** One label per scalar property, or per item of a list property. */
+ attributes: FrontmatterAttribute[];
+}
+
+export function extractFrontmatter(markdown: string): ParsedFrontmatter {
+ const block = matchFrontmatter(markdown);
+ if (!block) {
+ return { body: markdown, attributes: [] };
+ }
+
+ let data: unknown;
+ try {
+ data = load(block.yaml);
+ } catch {
+ // Malformed YAML isn't something we can trust, so leave the note untouched — body and block alike.
+ return { body: markdown, attributes: [] };
+ }
+ // A structurally-valid (possibly empty) block is stripped either way; only a key/value mapping yields
+ // attributes (a scalar/list block carries no named properties).
+ if (!isRecord(data)) {
+ return { body: block.body, attributes: [] };
+ }
+
+ const attributes: FrontmatterAttribute[] = [];
+ for (const [key, value] of Object.entries(data)) {
+ const name = toAttributeName(key);
+ for (const scalar of toValues(value)) {
+ attributes.push({ name, value: scalar });
+ }
+ }
+ return { body: block.body, attributes };
+}
+
+/** Splits a leading `---\n…\n---` block (front matter must start at the very first line) from the body. */
+function matchFrontmatter(markdown: string): { yaml: string; body: string } | null {
+ const match = /^---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/.exec(markdown);
+ if (!match) {
+ return null;
+ }
+ return { yaml: match[1], body: markdown.slice(match[0].length) };
+}
+
+/** Flattens a YAML value into the string label values it maps to (a list yields one per item). */
+function toValues(value: unknown): string[] {
+ if (value === null || value === undefined) {
+ return [""];
+ }
+ if (Array.isArray(value)) {
+ return value.flatMap(toValues);
+ }
+ if (typeof value === "boolean") {
+ return [value ? "true" : "false"];
+ }
+ if (typeof value === "number") {
+ return [String(value)];
+ }
+ if (typeof value === "string") {
+ return [value];
+ }
+ if (value instanceof Date) {
+ return [value.toISOString()];
+ }
+ // A nested mapping has no flat label representation, so it's skipped.
+ return [];
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
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 eecaf78edc..b85f0d10cb 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
@@ -69,6 +69,27 @@ describe("Obsidian importer — integration", () => {
expect(decodeUtf8(welcome?.getContent() ?? "")).toBe("<p>This is your new <em>vault</em>.</p>");
});
+ it("imports front matter properties as camelCased labels and strips the block from the note body", async () => {
+ // Modeled on the vault's "Files with properties" note.
+ const importRoot = await importObsidian({
+ "Note.md": "---\nfirst: First value\ntags:\n - Tag\n - AnotherTag\nCheckbox prop: true\nList:\n - a\n - b\n---\nThe body."
+ });
+
+ const note = importRoot.getChildNotes().find((n) => n.title === "Note");
+ if (!note) {
+ throw new Error("note was not imported");
+ }
+
+ // The block is gone from the content; only the rendered body remains.
+ expect(decodeUtf8(note.getContent())).toBe("<p>The body.</p>");
+
+ // Properties become labels with camelCased names; a list yields one label per item.
+ expect(note.getOwnedLabelValue("first")).toBe("First value");
+ expect(note.getOwnedLabelValues("tags")).toEqual(["Tag", "AnotherTag"]);
+ expect(note.getOwnedLabelValue("checkboxProp")).toBe("true");
+ expect(note.getOwnedLabelValues("list")).toEqual(["a", "b"]);
+ });
+
it("converts ==highlights== to a coloured span and %%comments%% to dropped HTML comments", async () => {
const importRoot = await importObsidian({
"Note.md": "A ==highlight== and a %%hidden%% comment."
diff --git a/packages/trilium-core/src/services/import/obsidian/importer.ts b/packages/trilium-core/src/services/import/obsidian/importer.ts
index ea30330bd0..6f8728e38b 100644
--- a/packages/trilium-core/src/services/import/obsidian/importer.ts
+++ b/packages/trilium-core/src/services/import/obsidian/importer.ts
@@ -13,8 +13,9 @@
* Obsidian-specific inline syntax is handled during Markdown rendering (gated by the `obsidian` flag):
* `==highlight==` becomes `<mark>` and `%% comment %%` becomes an HTML comment.
*
- * Deferred to later passes (so they currently render as literal text or placeholder links): frontmatter →
- * labels, tags, and callouts.
+ * Front matter is parsed generically (see {@link ../frontmatter.js}) into camelCased labels. Obsidian's
+ * property typing (date/number/checkbox via `.obsidian/types.json`), special keys (tags, aliases) and
+ * callouts are deferred to later passes.
*
* Invoked from the shared file-import dispatcher (routes/api/import.ts) when the upload is tagged
* `format=obsidian`, so progress, completion and failure are reported by that dispatcher's TaskContext —
@@ -30,6 +31,7 @@ import type TaskContext from "../../task_context.js";
import { decodeUtf8 } from "../../utils/binary.js";
import { basename } from "../../utils/path.js";
import { getZipProvider } from "../../zip_provider.js";
+import { extractFrontmatter } from "../frontmatter.js";
import markdownService from "../markdown.js";
import { applyAttachments, buildAttachmentIndex } from "./attachments.js";
import { buildNoteIndex, resolveLinks } from "./links.js";
@@ -117,9 +119,16 @@ function createNotes(importRootNote: BNote, notes: VaultNote[], attachments: Map
// attachments saved. Content is persisted once, in the link pass, to avoid a second write per note.
for (const vaultNote of notes) {
const parent = ensureFolder(parentFolder(vaultNote.path), rootNote, folderNotes, isProtected);
- const rendered = markdownService.renderToHtml(vaultNote.markdown, vaultNote.title, { obsidian: true });
+ const { body, attributes } = extractFrontmatter(vaultNote.markdown);
+ const rendered = markdownService.renderToHtml(body, vaultNote.title, { obsidian: true });
const { note } = noteService.createNewNote({ parentNoteId: parent.noteId, title: vaultNote.title, content: rendered, type: "text", mime: "text/html", isProtected });
+ // Front matter properties become labels, their names camelCased like the other importers. Obsidian's
+ // typing (date/number/checkbox) and special keys (tags, aliases) layer on in a later pass.
+ for (const attribute of attributes) {
+ note.addLabel(attribute.name, attribute.value);
+ }
+
// 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);
diff --git a/packages/trilium-core/src/services/import/single.spec.ts b/packages/trilium-core/src/services/import/single.spec.ts
index 8e6f939fb6..66464c8b52 100644
--- a/packages/trilium-core/src/services/import/single.spec.ts
+++ b/packages/trilium-core/src/services/import/single.spec.ts
@@ -109,6 +109,14 @@ describe("processNoteContent", () => {
expect(importedNote.getContent().toString()).toBe("<h2>Hello world</h2><p>Plain text goes here.</p>");
});
+ it("imports YAML front matter as labels and strips it from a Markdown note", async () => {
+ const md = "---\nfirst: First value\ntags:\n - Tag\n - AnotherTag\n---\nThe body.";
+ const { importedNote } = await testImport("Frontmatter.md", "text/markdown", Buffer.from(md));
+ expect(importedNote.getContent().toString()).toBe("<p>The body.</p>");
+ expect(importedNote.getOwnedLabelValue("first")).toBe("First value");
+ expect(importedNote.getOwnedLabelValues("tags")).toEqual(["Tag", "AnotherTag"]);
+ });
+
it("supports excalidraw note", async () => {
const { importedNote } = await testImport("New note.excalidraw", "application/json");
expect(importedNote.mime).toBe("application/json");
diff --git a/packages/trilium-core/src/services/import/single.ts b/packages/trilium-core/src/services/import/single.ts
index e03dedeefd..90a21f168e 100644
--- a/packages/trilium-core/src/services/import/single.ts
+++ b/packages/trilium-core/src/services/import/single.ts
@@ -6,6 +6,7 @@ import noteService from "../../services/notes.js";
import protectedSessionService from "../protected_session.js";
import type TaskContext from "../task_context.js";
import type { File } from "./common.js";
+import { extractFrontmatter } from "./frontmatter.js";
import markdownService from "./markdown.js";
import mimeService from "./mime.js";
import importUtils from "./utils.js";
@@ -208,7 +209,9 @@ function importMarkdown(taskContext: TaskContext<"importNotes">, file: File, par
const title = getNoteTitle(file.originalname, !!taskContext.data?.replaceUnderscoresWithSpaces);
const markdownContent = processStringOrBuffer(file.buffer);
- let htmlContent = markdownService.renderToHtml(markdownContent, title);
+ // YAML front matter (Obsidian/Jekyll/Hugo/…) is lifted into labels and stripped before rendering.
+ const { body, attributes } = extractFrontmatter(markdownContent);
+ let htmlContent = markdownService.renderToHtml(body, title);
if (taskContext.data?.safeImport) {
htmlContent = sanitizeHtml(htmlContent);
@@ -223,6 +226,10 @@ function importMarkdown(taskContext: TaskContext<"importNotes">, file: File, par
isProtected: parentNote.isProtected && protectedSessionService.isProtectedSessionAvailable()
});
+ for (const attribute of attributes) {
+ note.addLabel(attribute.name, attribute.value);
+ }
+
taskContext.increaseProgressCount();
return note;
diff --git a/packages/trilium-core/src/services/import/zip.spec.ts b/packages/trilium-core/src/services/import/zip.spec.ts
index e794c223b9..ab556d0a0f 100644
--- a/packages/trilium-core/src/services/import/zip.spec.ts
+++ b/packages/trilium-core/src/services/import/zip.spec.ts
@@ -65,6 +65,18 @@ describe("processNoteContent", () => {
await sql_init.dbReady;
});
+ it("imports YAML front matter from a generic Markdown file in a ZIP as labels", async () => {
+ const buffer = await createZipBuffer({
+ "Note.md": "---\nfirst: First value\ntags:\n - Tag\n - AnotherTag\n---\nThe body."
+ });
+ const { importedNote } = await testImportBuffer(buffer, "import-frontmatter-zip");
+
+ expect(importedNote.title).toBe("Note");
+ expect(importedNote.getContent().toString()).toBe("<p>The body.</p>");
+ expect(importedNote.getOwnedLabelValue("first")).toBe("First value");
+ expect(importedNote.getOwnedLabelValues("tags")).toEqual(["Tag", "AnotherTag"]);
+ });
+
it("treats single MDX as Markdown in ZIP as text note", async () => {
const { importedNote } = await testImport("mdx.zip");
expect(importedNote.mime).toBe("text/mdx");
diff --git a/packages/trilium-core/src/services/import/zip.ts b/packages/trilium-core/src/services/import/zip.ts
index 43b064d04c..8cc13c481d 100644
--- a/packages/trilium-core/src/services/import/zip.ts
+++ b/packages/trilium-core/src/services/import/zip.ts
@@ -20,6 +20,7 @@ import mimeService from "./mime.js";
import { AttributeMeta, NoteMeta } from "../../meta.js";
import { isMarkdownCodeNote } from "../export/rewrite_links.js";
import { sanitizeHtml } from "../sanitizer.js";
+import { extractFrontmatter, type FrontmatterAttribute } from "./frontmatter.js";
// Source mimes that import as editable spreadsheet notes (parsed to Univer workbook JSON),
// mirroring the single-file importer. As resolved by `mime-types` from the entry extension.
@@ -27,6 +28,9 @@ const CSV_MIME = "text/csv";
const XLSX_MIME = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
const SPREADSHEET_MIME = "text/x-spreadsheet";
+// Source mimes rendered from Markdown to HTML on import.
+const MARKDOWN_MIMES = ["text/markdown", "text/x-markdown", "text/mdx"];
+
interface MetaFile {
files: NoteMeta[];
}
@@ -410,7 +414,7 @@ async function importZip(taskContext: TaskContext<"importNotes">, fileBuffer: Ui
}
function processNoteContent(noteMeta: NoteMeta | undefined, type: string, mime: string, content: string | Uint8Array, noteTitle: string, filePath: string) {
- if ((noteMeta?.format === "markdown" || (!noteMeta && taskContext.data?.textImportedAsText && ["text/markdown", "text/x-markdown", "text/mdx"].includes(mime))) && typeof content === "string") {
+ if ((noteMeta?.format === "markdown" || (!noteMeta && taskContext.data?.textImportedAsText && MARKDOWN_MIMES.includes(mime))) && typeof content === "string") {
content = markdownService.renderToHtml(content, noteTitle);
}
@@ -559,6 +563,15 @@ async function importZip(taskContext: TaskContext<"importNotes">, fileBuffer: Ui
const noteTitle = getNoteTitle(filePath, taskContext.data?.replaceUnderscoresWithSpaces || false, noteMeta);
+ // Generic Markdown (not a Trilium export, which carries its attributes in !!!meta.json) may begin
+ // with a YAML front matter block; lift it into labels and strip it before the body is rendered.
+ let frontmatterAttributes: FrontmatterAttribute[] = [];
+ if (!noteMeta && typeof content === "string" && taskContext.data?.textImportedAsText && MARKDOWN_MIMES.includes(mime)) {
+ const parsed = extractFrontmatter(content);
+ content = parsed.body;
+ frontmatterAttributes = parsed.attributes;
+ }
+
content = processNoteContent(noteMeta, type, mime, content, noteTitle || "", filePath);
let note = becca.getNote(noteId);
@@ -632,6 +645,9 @@ async function importZip(taskContext: TaskContext<"importNotes">, fileBuffer: Ui
createdNoteIds.add(note.noteId);
saveAttributes(note, noteMeta);
+ for (const attribute of frontmatterAttributes) {
+ note.addLabel(attribute.name, attribute.value);
+ }
firstNote = firstNote || note;
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 39c162b102..e6d01cec73 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1629,6 +1629,9 @@ importers:
i18next:
specifier: 26.3.1
version: 26.3.1([email protected])
+ js-yaml:
+ specifier: 5.1.0
+ version: 5.1.0
mime-types:
specifier: 3.0.2
version: 3.0.2