--- title: Getting Started description: Parse markdown into an mdast-shaped tree, navigate its headings, sections and links, decode typed frontmatter, and edit a document without reformatting it with @effected/markdown. --- # Getting Started Reach for `@effected/markdown` whenever a program has to *read or rewrite* a markdown file someone else wrote — pull the newest entry out of a changelog, validate the frontmatter on a directory of agent skill files, retitle a heading in a doc site, collect every link for a link checker. The remark ecosystem can do the reading, but writing back re-serializes the whole document in remark's spelling, so hand-tuned spacing, HTML comments and blank lines come back changed. This package parses to a tree that carries byte offsets, so an edit is a splice against the original source: what you did not touch survives byte for byte. Parsing is near-total — CommonMark has no syntax errors — so the typed error channel carries hardening-guard trips only, never "malformed markdown". ## Install ```bash npm install @effected/markdown effect ``` ```bash pnpm add @effected/markdown effect ``` Requires Node.js >=24.11.0. `effect` v4 is a peer dependency; the package adds no runtime dependencies of its own and does no IO. `@effected/yaml`, `@effected/toml` and `@effected/jsonc` are **optional** peers, pulled in only by the frontmatter codec module you import — install the one format you decode, and none at all if you never touch frontmatter. ```bash npm install @effected/yaml ``` ## Your first task: read the newest entry out of a changelog Here is a concrete, everyday goal. A `CHANGELOG.md` lists releases as second-level headings, newest first, and a release script wants the notes for the version at the top — the text a GitHub release body would carry. We will build it up one step at a time. The document arrives as a string, so the first move is to parse it. `MarkdownDocument.parse` returns an `Effect` yielding a document that bundles the source, the tree, the link-definition index and the derived navigation accessors in one value: ```ts with-api import { MarkdownDocument } from "@effected/markdown"; import { Effect, Option } from "effect"; const changelog = `# Changelog ## 1.2.3 Fixed a bug in the table parser. ## 1.2.2 Initial release. `; const program = Effect.gen(function* () { // 1. Parse the file. The dialect defaults to gfm; nothing to configure. const document = yield* MarkdownDocument.parse(changelog); // 2. The newest release is the first second-level section — an Option, // because a changelog with no releases yet has none. const newest = document.firstSection({ depth: 2 }); // 3. Its body is the section without its heading — untrimmed, on purpose. return Option.match(newest, { onNone: () => "no releases yet", onSome: (section) => `${section.text}: ${section.body.trim()}`, }); }); Effect.runPromise(program).then(console.log); // 1.2.3: Fixed a bug in the table parser. ``` Three things are worth pausing on. `firstSection` and its sibling `sectionByHeading` are *finders* over `sections`, so you never scan an array of children yourself; like every lookup in the kit they return an `Option`, so the no-match case is a value you handle rather than an `undefined` you forget, and `{ depth: 2 }` restricts the search to one heading level rather than matching a `###` sub-heading by accident. A `DocumentSection` carries the heading, its `text`, and a `range` that spans the section's subsections too — which is exactly what the edit layer needs to splice a whole release out later. And `body` is deliberately untrimmed: it is exactly the bytes `bodyRange` describes, so the string and its offsets can never disagree. Call `.trim()` when you want the tidy form. To address a *named* release rather than the newest one, swap in `sectionByHeading`. It matches the exact trimmed heading text, a `RegExp`, or a predicate — exact, never a substring, so asking for `1.2.3` can never hand you `## 1.2.30`: ```ts with-api import { MarkdownDocument } from "@effected/markdown"; import { Effect, Option } from "effect"; const changelog = `# Changelog ## 1.2.30 A later release. ## 1.2.3 Fixed a bug in the table parser. `; const program = Effect.gen(function* () { const document = yield* MarkdownDocument.parse(changelog); return Option.match(document.sectionByHeading("1.2.3", { depth: 2 }), { onNone: () => "no such release", onSome: (section) => section.body.trim(), }); }); Effect.runPromise(program).then(console.log); // Fixed a bug in the table parser. ``` ## Common operations Each snippet below is a complete, runnable program built only from the package's real exports. ### Read a document's outline `headings` lists every heading in the document, wherever it sits — including inside a blockquote or a list item — each with its `depth`, its plain `text` and the `Heading` node itself: ```ts with-api import { MarkdownDocument } from "@effected/markdown"; import { Effect } from "effect"; const program = Effect.gen(function* () { const document = yield* MarkdownDocument.parse("# Guide\n\n## Install\n\n### Node\n"); return document.headings.map((heading) => `${"#".repeat(heading.depth)} ${heading.text}`); }); Effect.runPromise(program).then(console.log); // [ "# Guide", "## Install", "### Node" ] ``` ### Collect every link for a link checker `links` gathers every URL-bearing node — links, images, definitions and their reference forms — and passes `url` through exactly as written. Relative hrefs are never normalized, which is what makes the accessor usable for a bundle-relative link check: ```ts with-api import { MarkdownDocument } from "@effected/markdown"; import { Effect } from "effect"; const source = `See the [changelog](./CHANGELOG.md) and the [docs](https://example.com/docs).\n`; const program = Effect.gen(function* () { const document = yield* MarkdownDocument.parse(source); return document.links.map((link) => link.url); }); Effect.runPromise(program).then(console.log); // [ "./CHANGELOG.md", "https://example.com/docs" ] ``` ### Find any node in the tree For everything the accessors do not cover, `find` and `findAll` walk the whole tree in document pre-order. A string selector matches the node's `type` *and narrows the result* — `findAll("table")` is `ReadonlyArray`, not an array of bare nodes — and a predicate or type guard works too. Matches come back by identity, so they feed the edit layer directly: ```ts with-api import { MarkdownDocument } from "@effected/markdown"; import { Effect, Option } from "effect"; const source = `# Fixtures | lang | ext | | --- | --- | | ts | .ts | \`\`\`ts const x = 1; \`\`\` `; const program = Effect.gen(function* () { const document = yield* MarkdownDocument.parse(source); const table = document.find("table"); const fences = document.findAll("code").map((code) => code.lang); return { rows: Option.match(table, { onNone: () => 0, onSome: (node) => node.children.length }), fences }; }); Effect.runPromise(program).then(console.log); // { rows: 2, fences: [ "ts" ] } ``` ### Decode typed frontmatter Frontmatter capture is opt-in, because turning it on changes how a document opening with `---` parses — CommonMark reads that as a thematic break followed by a setext heading, and the spec-conformant reading holds unless you ask for something else. Pass `frontmatter: true`, then compose your schema with a format codec for typed gray-matter parity: ```ts with-api import { MarkdownDocument, MarkdownFrontmatter, MarkdownParseOptions, YamlFrontmatter } from "@effected/markdown"; import { Effect, Schema } from "effect"; const Skill = Schema.Struct({ name: Schema.String, description: Schema.String }); const decodeSkill = MarkdownFrontmatter.schema(Skill, YamlFrontmatter); const source = `--- name: review description: Run the review rubric. --- # Review `; const program = Effect.gen(function* () { const document = yield* MarkdownDocument.parse(source, MarkdownParseOptions.make({ frontmatter: true })); return yield* decodeSkill(document); }); Effect.runPromise(program).then(console.log); // { name: "review", description: "Run the review rubric." } ``` `YamlFrontmatter` (`---`), `TomlFrontmatter` (`+++`) and `JsonFrontmatter` (`---json`) are free-standing named exports, one module each. Naming a codec is what pulls in its format engine, so a JSON-frontmatter consumer never loads the yaml parser. Bind the decoder to a `const`, as above, when you decode many documents. ### Replace a node without reformatting the file `MarkdownFormat.modifyToString` replaces one node — matched by identity in the document's own tree — and returns the updated source. Everything the splice does not cover is byte-identical, and the replacement renders through the canonical stringifier, so the result re-parses cleanly by construction: ```ts with-api import { MarkdownDocument, MarkdownFormat } from "@effected/markdown"; import { Effect, Option } from "effect"; const source = `# Release notes See the [changelog](./CHANGELOG.md). `; const program = Effect.gen(function* () { const document = yield* MarkdownDocument.parse(source); const title = document.find("heading").pipe(Option.flatMap((heading) => Option.fromUndefinedOr(heading.children[0]))); return Option.isNone(title) ? source : yield* MarkdownFormat.modifyToString(document, title.value, "Release notes (2026)"); }); Effect.runPromise(program).then(console.log); // # Release notes (2026) // // See the [changelog](./CHANGELOG.md). ``` ### Normalize markers across a document `MarkdownFormat.format` is the other half: conservative marker normalization, never content rewriting. It converts heading style, bullet character, emphasis marker, fence character, thematic-break character and code-block style, and *skips* any conversion that would not be safe rather than attempting it cleverly. It is pure and total — no `Effect`, no error channel: ```ts with-api import { MarkdownFormat, MarkdownFormattingOptions } from "@effected/markdown"; const source = `Setext heading ============== * one * two `; const options = MarkdownFormattingOptions.make({ headingStyle: "atx", bulletChar: "-" }); console.log(MarkdownFormat.formatToString(source, undefined, options)); // # Setext heading // // - one // - two ``` ### Parse synchronously, without a runtime Every parse entry point has a pure twin returning a `Result`, so a build script, a Vite plugin or a language-server tick can call in with no Effect runtime at all: ```ts with-api import { MarkdownDocument } from "@effected/markdown"; import { Result } from "effect"; const parsed = MarkdownDocument.parseResult("# Title\n"); console.log(Result.isSuccess(parsed) ? parsed.success.headings.length : 0); // 1 ``` ## Handling errors There is no such thing as malformed markdown here. Every string is a valid CommonMark document, so `MarkdownParseError` carries only hardening-guard trips — the 256-deep nesting cap that turns a crafted nesting bomb into a typed failure instead of a `RangeError`. Recoverable oddities surface as `diagnostics` on the document rather than as failures, so a real-world file parses and tells you what it noticed. The failures you will actually route on come from frontmatter, and each stage fails separately: `FrontmatterMissingError` when there is no capture, `FrontmatterFormatMismatchError` when a codec meets the wrong fence, `FrontmatterDecodeError` when the block will not parse (carrying the format package's own positioned failure structurally), and `FrontmatterValidationError` when the data does not satisfy your schema (carrying the structured issue tree, never a stringified rendering). Because capture is opt-in, "there is no frontmatter" has two meanings, and `FrontmatterMissingError.reason` tells them apart — which matters, because one is fixed by editing the document and the other by changing a parse option: ```ts with-api import { MarkdownDocument, MarkdownFrontmatter, YamlFrontmatter } from "@effected/markdown"; import { Effect, Schema } from "effect"; const Post = Schema.Struct({ title: Schema.String }); const decodePost = MarkdownFrontmatter.schema(Post, YamlFrontmatter); const source = `--- title: Release notes --- # Release notes `; const program = Effect.gen(function* () { // Note the missing MarkdownParseOptions — capture is left off. const document = yield* MarkdownDocument.parse(source); return yield* decodePost(document); }); const safe = program.pipe( Effect.catchTag("FrontmatterMissingError", (error) => Effect.succeed(`no frontmatter (${error.reason})`)), Effect.catchTag("FrontmatterDecodeError", (error) => Effect.succeed(`undecodable ${error.format} block`)), Effect.catchTag("FrontmatterFormatMismatchError", (error) => Effect.succeed(`expected ${error.expected}`)), Effect.catchTag("FrontmatterValidationError", () => Effect.succeed("frontmatter failed the schema")), ); Effect.runPromise(safe).then(console.log); // no frontmatter (captureDisabled) ``` `"captureDisabled"` says the source opens with a block the parse ignored; `"absent"` says the document genuinely has none. `MarkdownDocument.hasFrontmatterBlock` answers the same question directly by re-running the parser's own pre-scan, so the accessor and the error can never disagree. And because the failures are tagged, dropping any one of those `catchTag` calls is a compile error until every mode is accounted for. ## Next steps - Ready for offset-splice editing, writing frontmatter back, self-describing `$schema` blocks, streaming a tree walk and mdast interop? See the [advanced guide](/markdown/advanced). - Every export, with full signatures, lives in the [API reference](/markdown/api) — start with [`MarkdownDocument`](/markdown/api/class/markdowndocument), [`Markdown`](/markdown/api/class/markdown) and [`MarkdownFrontmatter`](/markdown/api/class/markdownfrontmatter).