Skip to content

VaultMD / serializeFrontmatter

Function: serializeFrontmatter()

serializeFrontmatter(frontmatter): string

Defined in: src/frontmatter/serialize.ts:94

Serialize a frontmatter map to a fenced YAML block ready to prepend to a markdown note. The output is byte-identical to the fresh frontmatter block createNote / editFrontmatter emit when a note has no existing block (they preserve an existing block's styling, which this does not reproduce). parseFrontmatter is its inverse: every accepted input round-trips, and reports the result as 'flat'.

An empty map yields the empty string (no block), matching what createNote / editFrontmatter write for empty frontmatter. Non-empty arrays serialize as block sequences; an empty array serializes as flow [].

Folding is off, so a value stays on its key's line however long it is. A value that contains a newline is the exception — it has to span lines to carry them — and is emitted as a double-quoted scalar broken at its own line breaks, not at a column limit.

Parameters

frontmatter

Record<string, unknown>

Flat key-value map: scalars (string, a finite number, boolean, null) and arrays of scalars. Nesting is refused — this package does not author a shape editFrontmatter cannot then rewrite one key at a time. A nested block written by something else is still read and indexed; see FrontmatterValidity.

Returns

string

A string of the form ---\n<yaml>\n---\n, or '' for an empty map.

Throws

MdVaultError with code FRONTMATTER_INVALID, naming the offending keys, when a value is a nested map or array, an array of non-scalars, a Date, a class instance, a non-finite number, or undefined. Binding one array to two keys is fine: it is written out twice rather than as a YAML anchor.

Example

ts
const header = serializeFrontmatter({ title: 'Hello', tags: ['a', 'b'] });
// "---\ntitle: Hello\ntags:\n  - a\n  - b\n---\n"

Released under the MIT License.