unist-util-position

5.0.0 · active · verified Sun Apr 19

unist-util-position is a crucial utility within the unified (unist) ecosystem, designed to robustly extract positional information from Unist (Universal Syntax Tree) nodes. This includes `start` and `end` points, along with `line`, `column`, and `offset` details. It's particularly valuable when processing trees that might have inconsistent or incomplete positional data due to user modifications or external plugins, acting as a safeguard against malformed data. The current stable version is 5.0.0, which mandates Node.js 16 or newer and operates exclusively as an ES module. New major versions are typically released to align with Node.js EOL policies and introduce significant breaking changes, while minor releases provide features and fixes. Its key differentiator is its focus on providing reliable positional data, returning `undefined` for invalid inputs rather than potentially throwing errors or returning partial, incorrect data, making it safer for robust plugin development compared to directly accessing `node.position` properties.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to parse Markdown into a unist tree and extract its overall position, start point, and end point using the utility functions, including handling potentially undefined results from v5+.

import {fromMarkdown} from 'mdast-util-from-markdown'
import {pointEnd, pointStart, position} from 'unist-util-position'

const markdown = '# Hello\n\n* World\n'
const tree = fromMarkdown(markdown)

// Get the full position of the tree
const fullPosition = position(tree)
console.log('Full Position:', fullPosition)
// Expected: { start: { line: 1, column: 1, offset: 0 }, end: { line: 4, column: 1, offset: 13 } }

// Get the starting point of the tree
const startPoint = pointStart(tree)
console.log('Start Point:', startPoint)
// Expected: { line: 1, column: 1, offset: 0 }

// Get the ending point of the tree
const endPoint = pointEnd(tree)
console.log('End Point:', endPoint)
// Expected: { line: 4, column: 1, offset: 13 }

// Example of handling undefined for invalid nodes (v5+ behavior)
const invalidNode = null
const invalidPosition = position(invalidNode)
console.log('Invalid Position:', invalidPosition)
// Expected: undefined - always check for undefined with v5+

view raw JSON →