the editable site (validation-lab)

This commit is contained in:
kpgarrod committed 2026-11-21 08:03:55 +01:00
commit 3ac81d5a52
13454 files changed
+2227005

No files matched your search

+18
View File
@@ -0,0 +1,18 @@
export type {Test} from 'unist-util-is'
export type {
Action,
ActionTuple,
BuildVisitor,
BuildVisitors,
// Undocumented: used in `unist-util-visit`:
InclusiveDescendant,
Index,
// Undocumented: used in `unist-util-visit`:
Matches,
Visitor,
VisitorExit,
VisitorResult,
VisitorResultExit,
Visitors
} from './lib/index.js'
export {CONTINUE, EXIT, SKIP, visitParents} from './lib/index.js'
+2
View File
@@ -0,0 +1,2 @@
// Note: types exported from `index.d.ts`
export {CONTINUE, EXIT, SKIP, visitParents} from './lib/index.js'
+10
View File
@@ -0,0 +1,10 @@
/**
* Color a string.
*
* @param {string} d
* Value.
* @returns {string}
* Colored value.
*/
export function color(d: string): string;
//# sourceMappingURL=color.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"color.d.ts","sourceRoot":"","sources":["color.js"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,yBALW,MAAM,GAEJ,MAAM,CAKlB"}
+11
View File
@@ -0,0 +1,11 @@
/**
* Color a string.
*
* @param {string} d
* Value.
* @returns {string}
* Colored value.
*/
export function color(d) {
return d
}
+10
View File
@@ -0,0 +1,10 @@
/**
* Color a string.
*
* @param {string} d
* Value.
* @returns {string}
* Colored value.
*/
export function color(d: string): string;
//# sourceMappingURL=color.node.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"color.node.d.ts","sourceRoot":"","sources":["color.node.js"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,yBALW,MAAM,GAEJ,MAAM,CAKlB"}
+11
View File
@@ -0,0 +1,11 @@
/**
* Color a string.
*
* @param {string} d
* Value.
* @returns {string}
* Colored value.
*/
export function color(d) {
return '\u001B[33m' + d + '\u001B[39m'
}
+540
View File
@@ -0,0 +1,540 @@
/**
* Visit nodes, with ancestral information.
*
* This algorithm performs *depth-first* *tree traversal* in *preorder*
* (**NLR**) or if `reverse` is given,
* in *reverse preorder* (**NRL**).
* An `exit` visitor is called in *postorder* (**LRN**)
* or if `reverse` is given, in *reverse postorder* (**RLN**).
*
* You can choose which nodes are visited by passing a `test`.
* For complex tests, you should test yourself in a visitor, as it will be
* faster and will have improved type information.
*
* Walking the tree is an intensive task.
* Make use of the return values of the visitor when possible.
* Instead of walking a tree multiple times, walk it once, use `unist-util-is`
* to check if a node matches, and then perform different operations.
*
* You can change the tree.
* Changes inside a node made when entering it are walked,
* changes made when exiting it are not.
* See `Visitor` and `VisitorExit` for more info.
*
* @overload
* @param {Tree} tree
* Tree to traverse.
* @param {Check} check
* `unist-util-is`-compatible test.
* @param {BuildVisitor<Tree, Check>} enter
* Handle each node when entering it.
* @param {boolean | null | undefined} [reverse]
* Walk children from last to first;
* for `enter`, reverse preorder (NRL) instead of preorder (NLR);
* for `exit`, reverse postorder (RLN) instead of postorder (LRN).
* @returns {undefined}
* Nothing.
*
* @overload
* @param {Tree} tree
* Tree to traverse.
* @param {Check} check
* `unist-util-is`-compatible test.
* @param {BuildVisitors<Tree, Check>} visitors
* Handle each node when exiting it, and optionally when entering it.
* @param {boolean | null | undefined} [reverse]
* Walk children from last to first;
* for `enter`, reverse preorder (NRL) instead of preorder (NLR);
* for `exit`, reverse postorder (RLN) instead of postorder (LRN).
* @returns {undefined}
* Nothing.
*
* @overload
* @param {Tree} tree
* Tree to traverse.
* @param {BuildVisitor<Tree>} enter
* Handle each node when entering it.
* @param {boolean | null | undefined} [reverse]
* Walk children from last to first;
* for `enter`, reverse preorder (NRL) instead of preorder (NLR);
* for `exit`, reverse postorder (RLN) instead of postorder (LRN).
* @returns {undefined}
* Nothing.
*
* @overload
* @param {Tree} tree
* Tree to traverse.
* @param {BuildVisitors<Tree>} visitors
* Handle each node when exiting it, and optionally when entering it.
* @param {boolean | null | undefined} [reverse]
* Walk children from last to first;
* for `enter`, reverse preorder (NRL) instead of preorder (NLR);
* for `exit`, reverse postorder (RLN) instead of postorder (LRN).
* @returns {undefined}
* Nothing.
*
* @param {UnistNode} tree
* Tree to traverse.
* @param {Visitor | Visitors | Test} testOrEnterOrVisitors
* `unist-util-is`-compatible test, `enter`, or `visitors`.
* @param {Visitor | Visitors | boolean | null | undefined} [enterOrVisitorsOrReverse]
* `enter`, `visitors`, or `reverse` after a test.
* @param {boolean | null | undefined} [reverse]
* Walk children from last to first;
* for `enter`, reverse preorder (NRL) instead of preorder (NLR);
* for `exit`, reverse postorder (RLN) instead of postorder (LRN).
* @returns {undefined}
* Nothing.
*
* @template {UnistNode} Tree
* Node type.
* @template {Test} Check
* `unist-util-is`-compatible test.
*/
export function visitParents<Tree extends UnistNode, Check extends Test>(tree: Tree, check: Check, enter: BuildVisitor<Tree, Check>, reverse?: boolean | null | undefined): undefined;
/**
* Visit nodes, with ancestral information.
*
* This algorithm performs *depth-first* *tree traversal* in *preorder*
* (**NLR**) or if `reverse` is given,
* in *reverse preorder* (**NRL**).
* An `exit` visitor is called in *postorder* (**LRN**)
* or if `reverse` is given, in *reverse postorder* (**RLN**).
*
* You can choose which nodes are visited by passing a `test`.
* For complex tests, you should test yourself in a visitor, as it will be
* faster and will have improved type information.
*
* Walking the tree is an intensive task.
* Make use of the return values of the visitor when possible.
* Instead of walking a tree multiple times, walk it once, use `unist-util-is`
* to check if a node matches, and then perform different operations.
*
* You can change the tree.
* Changes inside a node made when entering it are walked,
* changes made when exiting it are not.
* See `Visitor` and `VisitorExit` for more info.
*
* @overload
* @param {Tree} tree
* Tree to traverse.
* @param {Check} check
* `unist-util-is`-compatible test.
* @param {BuildVisitor<Tree, Check>} enter
* Handle each node when entering it.
* @param {boolean | null | undefined} [reverse]
* Walk children from last to first;
* for `enter`, reverse preorder (NRL) instead of preorder (NLR);
* for `exit`, reverse postorder (RLN) instead of postorder (LRN).
* @returns {undefined}
* Nothing.
*
* @overload
* @param {Tree} tree
* Tree to traverse.
* @param {Check} check
* `unist-util-is`-compatible test.
* @param {BuildVisitors<Tree, Check>} visitors
* Handle each node when exiting it, and optionally when entering it.
* @param {boolean | null | undefined} [reverse]
* Walk children from last to first;
* for `enter`, reverse preorder (NRL) instead of preorder (NLR);
* for `exit`, reverse postorder (RLN) instead of postorder (LRN).
* @returns {undefined}
* Nothing.
*
* @overload
* @param {Tree} tree
* Tree to traverse.
* @param {BuildVisitor<Tree>} enter
* Handle each node when entering it.
* @param {boolean | null | undefined} [reverse]
* Walk children from last to first;
* for `enter`, reverse preorder (NRL) instead of preorder (NLR);
* for `exit`, reverse postorder (RLN) instead of postorder (LRN).
* @returns {undefined}
* Nothing.
*
* @overload
* @param {Tree} tree
* Tree to traverse.
* @param {BuildVisitors<Tree>} visitors
* Handle each node when exiting it, and optionally when entering it.
* @param {boolean | null | undefined} [reverse]
* Walk children from last to first;
* for `enter`, reverse preorder (NRL) instead of preorder (NLR);
* for `exit`, reverse postorder (RLN) instead of postorder (LRN).
* @returns {undefined}
* Nothing.
*
* @param {UnistNode} tree
* Tree to traverse.
* @param {Visitor | Visitors | Test} testOrEnterOrVisitors
* `unist-util-is`-compatible test, `enter`, or `visitors`.
* @param {Visitor | Visitors | boolean | null | undefined} [enterOrVisitorsOrReverse]
* `enter`, `visitors`, or `reverse` after a test.
* @param {boolean | null | undefined} [reverse]
* Walk children from last to first;
* for `enter`, reverse preorder (NRL) instead of preorder (NLR);
* for `exit`, reverse postorder (RLN) instead of postorder (LRN).
* @returns {undefined}
* Nothing.
*
* @template {UnistNode} Tree
* Node type.
* @template {Test} Check
* `unist-util-is`-compatible test.
*/
export function visitParents<Tree extends UnistNode, Check extends Test>(tree: Tree, check: Check, visitors: BuildVisitors<Tree, Check>, reverse?: boolean | null | undefined): undefined;
/**
* Visit nodes, with ancestral information.
*
* This algorithm performs *depth-first* *tree traversal* in *preorder*
* (**NLR**) or if `reverse` is given,
* in *reverse preorder* (**NRL**).
* An `exit` visitor is called in *postorder* (**LRN**)
* or if `reverse` is given, in *reverse postorder* (**RLN**).
*
* You can choose which nodes are visited by passing a `test`.
* For complex tests, you should test yourself in a visitor, as it will be
* faster and will have improved type information.
*
* Walking the tree is an intensive task.
* Make use of the return values of the visitor when possible.
* Instead of walking a tree multiple times, walk it once, use `unist-util-is`
* to check if a node matches, and then perform different operations.
*
* You can change the tree.
* Changes inside a node made when entering it are walked,
* changes made when exiting it are not.
* See `Visitor` and `VisitorExit` for more info.
*
* @overload
* @param {Tree} tree
* Tree to traverse.
* @param {Check} check
* `unist-util-is`-compatible test.
* @param {BuildVisitor<Tree, Check>} enter
* Handle each node when entering it.
* @param {boolean | null | undefined} [reverse]
* Walk children from last to first;
* for `enter`, reverse preorder (NRL) instead of preorder (NLR);
* for `exit`, reverse postorder (RLN) instead of postorder (LRN).
* @returns {undefined}
* Nothing.
*
* @overload
* @param {Tree} tree
* Tree to traverse.
* @param {Check} check
* `unist-util-is`-compatible test.
* @param {BuildVisitors<Tree, Check>} visitors
* Handle each node when exiting it, and optionally when entering it.
* @param {boolean | null | undefined} [reverse]
* Walk children from last to first;
* for `enter`, reverse preorder (NRL) instead of preorder (NLR);
* for `exit`, reverse postorder (RLN) instead of postorder (LRN).
* @returns {undefined}
* Nothing.
*
* @overload
* @param {Tree} tree
* Tree to traverse.
* @param {BuildVisitor<Tree>} enter
* Handle each node when entering it.
* @param {boolean | null | undefined} [reverse]
* Walk children from last to first;
* for `enter`, reverse preorder (NRL) instead of preorder (NLR);
* for `exit`, reverse postorder (RLN) instead of postorder (LRN).
* @returns {undefined}
* Nothing.
*
* @overload
* @param {Tree} tree
* Tree to traverse.
* @param {BuildVisitors<Tree>} visitors
* Handle each node when exiting it, and optionally when entering it.
* @param {boolean | null | undefined} [reverse]
* Walk children from last to first;
* for `enter`, reverse preorder (NRL) instead of preorder (NLR);
* for `exit`, reverse postorder (RLN) instead of postorder (LRN).
* @returns {undefined}
* Nothing.
*
* @param {UnistNode} tree
* Tree to traverse.
* @param {Visitor | Visitors | Test} testOrEnterOrVisitors
* `unist-util-is`-compatible test, `enter`, or `visitors`.
* @param {Visitor | Visitors | boolean | null | undefined} [enterOrVisitorsOrReverse]
* `enter`, `visitors`, or `reverse` after a test.
* @param {boolean | null | undefined} [reverse]
* Walk children from last to first;
* for `enter`, reverse preorder (NRL) instead of preorder (NLR);
* for `exit`, reverse postorder (RLN) instead of postorder (LRN).
* @returns {undefined}
* Nothing.
*
* @template {UnistNode} Tree
* Node type.
* @template {Test} Check
* `unist-util-is`-compatible test.
*/
export function visitParents<Tree extends UnistNode, Check extends Test>(tree: Tree, enter: BuildVisitor<Tree>, reverse?: boolean | null | undefined): undefined;
/**
* Visit nodes, with ancestral information.
*
* This algorithm performs *depth-first* *tree traversal* in *preorder*
* (**NLR**) or if `reverse` is given,
* in *reverse preorder* (**NRL**).
* An `exit` visitor is called in *postorder* (**LRN**)
* or if `reverse` is given, in *reverse postorder* (**RLN**).
*
* You can choose which nodes are visited by passing a `test`.
* For complex tests, you should test yourself in a visitor, as it will be
* faster and will have improved type information.
*
* Walking the tree is an intensive task.
* Make use of the return values of the visitor when possible.
* Instead of walking a tree multiple times, walk it once, use `unist-util-is`
* to check if a node matches, and then perform different operations.
*
* You can change the tree.
* Changes inside a node made when entering it are walked,
* changes made when exiting it are not.
* See `Visitor` and `VisitorExit` for more info.
*
* @overload
* @param {Tree} tree
* Tree to traverse.
* @param {Check} check
* `unist-util-is`-compatible test.
* @param {BuildVisitor<Tree, Check>} enter
* Handle each node when entering it.
* @param {boolean | null | undefined} [reverse]
* Walk children from last to first;
* for `enter`, reverse preorder (NRL) instead of preorder (NLR);
* for `exit`, reverse postorder (RLN) instead of postorder (LRN).
* @returns {undefined}
* Nothing.
*
* @overload
* @param {Tree} tree
* Tree to traverse.
* @param {Check} check
* `unist-util-is`-compatible test.
* @param {BuildVisitors<Tree, Check>} visitors
* Handle each node when exiting it, and optionally when entering it.
* @param {boolean | null | undefined} [reverse]
* Walk children from last to first;
* for `enter`, reverse preorder (NRL) instead of preorder (NLR);
* for `exit`, reverse postorder (RLN) instead of postorder (LRN).
* @returns {undefined}
* Nothing.
*
* @overload
* @param {Tree} tree
* Tree to traverse.
* @param {BuildVisitor<Tree>} enter
* Handle each node when entering it.
* @param {boolean | null | undefined} [reverse]
* Walk children from last to first;
* for `enter`, reverse preorder (NRL) instead of preorder (NLR);
* for `exit`, reverse postorder (RLN) instead of postorder (LRN).
* @returns {undefined}
* Nothing.
*
* @overload
* @param {Tree} tree
* Tree to traverse.
* @param {BuildVisitors<Tree>} visitors
* Handle each node when exiting it, and optionally when entering it.
* @param {boolean | null | undefined} [reverse]
* Walk children from last to first;
* for `enter`, reverse preorder (NRL) instead of preorder (NLR);
* for `exit`, reverse postorder (RLN) instead of postorder (LRN).
* @returns {undefined}
* Nothing.
*
* @param {UnistNode} tree
* Tree to traverse.
* @param {Visitor | Visitors | Test} testOrEnterOrVisitors
* `unist-util-is`-compatible test, `enter`, or `visitors`.
* @param {Visitor | Visitors | boolean | null | undefined} [enterOrVisitorsOrReverse]
* `enter`, `visitors`, or `reverse` after a test.
* @param {boolean | null | undefined} [reverse]
* Walk children from last to first;
* for `enter`, reverse preorder (NRL) instead of preorder (NLR);
* for `exit`, reverse postorder (RLN) instead of postorder (LRN).
* @returns {undefined}
* Nothing.
*
* @template {UnistNode} Tree
* Node type.
* @template {Test} Check
* `unist-util-is`-compatible test.
*/
export function visitParents<Tree extends UnistNode, Check extends Test>(tree: Tree, visitors: BuildVisitors<Tree>, reverse?: boolean | null | undefined): undefined;
/**
* Continue traversing as normal.
*/
export const CONTINUE: true;
/**
* Stop traversing immediately.
*/
export const EXIT: false;
/**
* Do not traverse this node’s children.
* Only works when entering a node.
*/
export const SKIP: "skip";
/**
* Test from `unist-util-is`.
*
* Note: we have remove and add `undefined`, because otherwise when generating
* automatic `.d.ts` files, TS tries to flatten paths from a local perspective,
* which doesn’t work when publishing on npm.
*/
export type Test = Exclude<import("unist-util-is").Test, undefined> | undefined;
/**
* Get the value of a type guard `Fn`.
*/
export type Predicate<Fn, Fallback> = (Fn extends (value: any) => value is infer Thing ? Thing : Fallback);
/**
* Check whether a node matches a primitive check in the type system.
*/
export type MatchesOne<Value, Check> = (Check extends null | undefined ? Value : Value extends {
type: Check;
} ? Value : Value extends Check ? Value : Check extends Function ? Predicate<Check, Value> extends Value ? Predicate<Check, Value> : never : never);
/**
* Check whether a node matches a check in the type system.
*/
export type Matches<Value, Check> = (Check extends ReadonlyArray<infer T> ? MatchesOne<Value, T> : Check extends Array<infer T> ? MatchesOne<Value, T> : MatchesOne<Value, Check>);
/**
* Number; capped reasonably.
*/
export type Uint = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10;
/**
* Increment a number in the type system.
*/
export type Increment<I extends Uint = 0> = I extends 0 ? 1 : I extends 1 ? 2 : I extends 2 ? 3 : I extends 3 ? 4 : I extends 4 ? 5 : I extends 5 ? 6 : I extends 6 ? 7 : I extends 7 ? 8 : I extends 8 ? 9 : 10;
/**
* Collect nodes that can be parents of `Child`.
*/
export type InternalParent<Node extends UnistNode, Child extends UnistNode> = (Node extends UnistParent ? Node extends {
children: Array<infer Children>;
} ? Child extends Children ? Node : never : never : never);
/**
* Collect nodes in `Tree` that can be parents of `Child`.
*/
export type Parent<Tree extends UnistNode, Child extends UnistNode> = InternalParent<InclusiveDescendant<Tree>, Child>;
/**
* Collect nodes in `Tree` that can be ancestors of `Child`.
*/
export type InternalAncestor<Node extends UnistNode, Child extends UnistNode, Max extends Uint = 10, Depth extends Uint = 0> = (Depth extends Max ? never : InternalParent<Node, Child> | InternalAncestor<Node, InternalParent<Node, Child>, Max, Increment<Depth>>);
/**
* Collect nodes in `Tree` that can be ancestors of `Child`.
*/
export type Ancestor<Tree extends UnistNode, Child extends UnistNode> = InternalAncestor<InclusiveDescendant<Tree>, Child>;
/**
* Collect all (inclusive) descendants of `Tree`.
*
* > 👉 **Note**: for performance reasons, this seems to be the fastest way to
* > recurse without actually running into an infinite loop, which the
* > previous version did.
* >
* > Practically, a max of `2` is typically enough assuming a `Root` is
* > passed, but it doesn’t improve performance.
* > It gets higher with `List > ListItem > Table > TableRow > TableCell`.
* > Using up to `10` doesn’t hurt or help either.
*/
export type InclusiveDescendant<Tree extends UnistNode, Max extends Uint = 10, Depth extends Uint = 0> = (Tree extends UnistParent ? Depth extends Max ? Tree : Tree | InclusiveDescendant<Tree["children"][number], Max, Increment<Depth>> : Tree);
/**
* Union of the action types.
*/
export type Action = "skip" | boolean;
/**
* Move to the sibling at `index` next (after node itself is completely
* traversed).
*
* Useful if mutating the tree, such as removing the node the visitor is
* currently on, or any of its previous siblings.
* Results less than 0 or greater than or equal to `children.length` stop
* traversing the parent.
*/
export type Index = number;
/**
* List with one or two values, the first an action, the second an index.
*/
export type ActionTuple = [(Action | null | undefined | void)?, (Index | null | undefined)?];
/**
* Any value that can be returned from an enter visitor.
*
* Like `VisitorResultExit`,
* but `SKIP` can also be returned,
* to not walk the children of the node,
* and `ActionTuple` can be used to combine an action with an index.
*/
export type VisitorResult = Action | ActionTuple | Index | null | undefined | void;
/**
* Any value that can be returned from an exit visitor.
*/
export type VisitorResultExit = Index | boolean | null | undefined | void;
/**
* Handle a node (matching `test`, if given) before its children.
*
* Changes inside `node` are walked next.
* Replacing or removing it is easier in `exit`.
* When replacing or removing it here,
* return `SKIP` (as otherwise its old children are walked),
* or `[SKIP, index]` to continue with the node now at `index`.
* Changing next siblings (in walk order) is fine;
* changing previous siblings needs a new `Index`.
* Removing an ancestor or changing its previous siblings is not supported.
*/
export type Visitor<Visited extends UnistNode = UnistNode, VisitedParents extends UnistParent = UnistParent> = (node: Visited, ancestors: Array<VisitedParents>, index: number | undefined) => VisitorResult;
/**
* Handle a node (matching `test`, if given) after its children.
*
* Changes inside `node` are not walked,
* which makes this a good place to change `node` based on its children,
* or to replace or remove it.
* When removing `node` or changing previous siblings (in walk order),
* return a new `Index`.
* Removing an ancestor or changing its previous siblings is not supported.
*/
export type VisitorExit<Visited extends UnistNode = UnistNode, VisitedParents extends UnistParent = UnistParent> = (node: Visited, ancestors: Array<VisitedParents>, index: number | undefined) => VisitorResultExit;
/**
* Handle nodes when entering and exiting them.
* The `enter` visitor is optional while `exit` is required.
*
* Pass an `enter` visitor directly to only handle nodes when entering them.
*
* `enter` is called before children (if any) are walked and `exit` after that.
* `exit` is still called when `enter` returns `SKIP`.
* Both `enter` and `exit` are only called for nodes that match an optional `test`.
*/
export type Visitors<Visited extends UnistNode = UnistNode, VisitedParents extends UnistParent = UnistParent> = {
/**
* Handle a node before its children (optional).
*/
enter?: Visitor<Visited, VisitedParents> | null | undefined;
/**
* Handle a node after its children.
*/
exit: VisitorExit<Visited, VisitedParents>;
};
/**
* Build a typed `Visitor` function from a tree and a test.
*
* It will infer which values are passed as `node` and which as `parents`.
*/
export type BuildVisitor<Tree extends UnistNode = UnistNode, Check extends Test = Test> = Visitor<Matches<InclusiveDescendant<Tree>, Check>, Ancestor<Tree, Matches<InclusiveDescendant<Tree>, Check>>>;
/**
* Build typed `Visitors` from a tree and a test.
*
* It will infer which values are passed as `node` and which as `parents`.
*/
export type BuildVisitors<Tree extends UnistNode = UnistNode, Check extends Test = Test> = Visitors<Matches<InclusiveDescendant<Tree>, Check>, Ancestor<Tree, Matches<InclusiveDescendant<Tree>, Check>>>;
import type { Node as UnistNode } from 'unist';
import type { Parent as UnistParent } from 'unist';
//# sourceMappingURL=index.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.js"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwUG,6BAiEsB,IAAI,SAAhB,SAAW,EAEJ,KAAK,SAAX,IAAK,QAlER,IAAI,SAEJ,KAAK,SAEL,YAAY,CAAC,IAAI,EAAE,KAAK,CAAC,YAEzB,OAAO,GAAG,IAAI,GAAG,SAAS,GAIxB,SAAS,CAGnB;;;;;;;;;;;;;;;;;;;;;;;;;;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;;oBA8B5B,OAAO,SAApB,SAAW,cAEI,cAAc,SAA7B,WAAa,yBAhBf,OAAO,aAEP,KAAK,CAAC,cAAc,CAAC,SAErB,MAAM,GAAG,SAAS,KAGhB,aAAa;;;;;;;;;;;wBAoCA,OAAO,SAApB,SAAW,cAEI,cAAc,SAA7B,WAAa,yBAff,OAAO,aAEP,KAAK,CAAC,cAAc,CAAC,SAErB,MAAM,GAAG,SAAS,KAGhB,iBAAiB;;;;;;;;;;;qBAaJ,OAAO,SAApB,SAAW,cAEI,cAAc,SAA7B,WAAa;;;;YAWZ,OAAO,CAAC,OAAO,EAAE,cAAc,CAAC,GAAG,IAAI,GAAG,SAAS;;;;UAEnD,WAAW,CAAC,OAAO,EAAE,cAAc,CAAC;;;;;;;yBASxB,IAAI,SAAjB,SAAW,cAEH,KAAK,SAAZ,IAAK,WANN,OAAO,CAAC,OAAO,CAAC,mBAAmB,CAAC,IAAI,CAAC,EAAE,KAAK,CAAC,EAAE,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC,mBAAmB,CAAC,IAAI,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC;;;;;;0BAehG,IAAI,SAAjB,SAAW,cAEH,KAAK,SAAZ,IAAK,WANN,QAAQ,CAAC,OAAO,CAAC,mBAAmB,CAAC,IAAI,CAAC,EAAE,KAAK,CAAC,EAAE,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC,mBAAmB,CAAC,IAAI,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC;uCAhRhE,OAAO;2CAAP,OAAO"}
+582
View File
@@ -0,0 +1,582 @@
/**
* @import {Node as UnistNode, Parent as UnistParent} from 'unist'
*/
/**
* @typedef {Exclude<import('unist-util-is').Test, undefined> | undefined} Test
* Test from `unist-util-is`.
*
* Note: we have remove and add `undefined`, because otherwise when generating
* automatic `.d.ts` files, TS tries to flatten paths from a local perspective,
* which doesn’t work when publishing on npm.
*/
/**
* @typedef {(
* Fn extends (value: any) => value is infer Thing
* ? Thing
* : Fallback
* )} Predicate
* Get the value of a type guard `Fn`.
* @template Fn
* Value; typically function that is a type guard (such as `(x): x is Y`).
* @template Fallback
* Value to yield if `Fn` is not a type guard.
*/
/**
* @typedef {(
* Check extends null | undefined // No test.
* ? Value
* : Value extends {type: Check} // String (type) test.
* ? Value
* : Value extends Check // Partial test.
* ? Value
* : Check extends Function // Function test.
* ? Predicate<Check, Value> extends Value
* ? Predicate<Check, Value>
* : never
* : never // Some other test?
* )} MatchesOne
* Check whether a node matches a primitive check in the type system.
* @template Value
* Value; typically unist `Node`.
* @template Check
* Value; typically `unist-util-is`-compatible test, but not arrays.
*/
/**
* @typedef {(
* Check extends ReadonlyArray<infer T>
* ? MatchesOne<Value, T>
* : Check extends Array<infer T>
* ? MatchesOne<Value, T>
* : MatchesOne<Value, Check>
* )} Matches
* Check whether a node matches a check in the type system.
* @template Value
* Value; typically unist `Node`.
* @template Check
* Value; typically `unist-util-is`-compatible test.
*/
/**
* @typedef {0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10} Uint
* Number; capped reasonably.
*/
/**
* @typedef {I extends 0 ? 1 : I extends 1 ? 2 : I extends 2 ? 3 : I extends 3 ? 4 : I extends 4 ? 5 : I extends 5 ? 6 : I extends 6 ? 7 : I extends 7 ? 8 : I extends 8 ? 9 : 10} Increment
* Increment a number in the type system.
* @template {Uint} [I=0]
* Index.
*/
/**
* @typedef {(
* Node extends UnistParent
* ? Node extends {children: Array<infer Children>}
* ? Child extends Children ? Node : never
* : never
* : never
* )} InternalParent
* Collect nodes that can be parents of `Child`.
* @template {UnistNode} Node
* All node types in a tree.
* @template {UnistNode} Child
* Node to search for.
*/
/**
* @typedef {InternalParent<InclusiveDescendant<Tree>, Child>} Parent
* Collect nodes in `Tree` that can be parents of `Child`.
* @template {UnistNode} Tree
* All node types in a tree.
* @template {UnistNode} Child
* Node to search for.
*/
/**
* @typedef {(
* Depth extends Max
* ? never
* :
* | InternalParent<Node, Child>
* | InternalAncestor<Node, InternalParent<Node, Child>, Max, Increment<Depth>>
* )} InternalAncestor
* Collect nodes in `Tree` that can be ancestors of `Child`.
* @template {UnistNode} Node
* All node types in a tree.
* @template {UnistNode} Child
* Node to search for.
* @template {Uint} [Max=10]
* Max; searches up to this depth.
* @template {Uint} [Depth=0]
* Current depth.
*/
/**
* @typedef {InternalAncestor<InclusiveDescendant<Tree>, Child>} Ancestor
* Collect nodes in `Tree` that can be ancestors of `Child`.
* @template {UnistNode} Tree
* All node types in a tree.
* @template {UnistNode} Child
* Node to search for.
*/
/**
* @typedef {(
* Tree extends UnistParent
* ? Depth extends Max
* ? Tree
* : Tree | InclusiveDescendant<Tree['children'][number], Max, Increment<Depth>>
* : Tree
* )} InclusiveDescendant
* Collect all (inclusive) descendants of `Tree`.
*
* > 👉 **Note**: for performance reasons, this seems to be the fastest way to
* > recurse without actually running into an infinite loop, which the
* > previous version did.
* >
* > Practically, a max of `2` is typically enough assuming a `Root` is
* > passed, but it doesn’t improve performance.
* > It gets higher with `List > ListItem > Table > TableRow > TableCell`.
* > Using up to `10` doesn’t hurt or help either.
* @template {UnistNode} Tree
* Tree type.
* @template {Uint} [Max=10]
* Max; searches up to this depth.
* @template {Uint} [Depth=0]
* Current depth.
*/
/**
* @typedef {'skip' | boolean} Action
* Union of the action types.
*
* @typedef {number} Index
* Move to the sibling at `index` next (after node itself is completely
* traversed).
*
* Useful if mutating the tree, such as removing the node the visitor is
* currently on, or any of its previous siblings.
* Results less than 0 or greater than or equal to `children.length` stop
* traversing the parent.
*
* @typedef {[(Action | null | undefined | void)?, (Index | null | undefined)?]} ActionTuple
* List with one or two values, the first an action, the second an index.
*
* @typedef {Action | ActionTuple | Index | null | undefined | void} VisitorResult
* Any value that can be returned from an enter visitor.
*
* Like `VisitorResultExit`,
* but `SKIP` can also be returned,
* to not walk the children of the node,
* and `ActionTuple` can be used to combine an action with an index.
*
* @typedef {Index | boolean | null | undefined | void} VisitorResultExit
* Any value that can be returned from an exit visitor.
*/
/**
* @callback Visitor
* Handle a node (matching `test`, if given) before its children.
*
* Changes inside `node` are walked next.
* Replacing or removing it is easier in `exit`.
* When replacing or removing it here,
* return `SKIP` (as otherwise its old children are walked),
* or `[SKIP, index]` to continue with the node now at `index`.
* Changing next siblings (in walk order) is fine;
* changing previous siblings needs a new `Index`.
* Removing an ancestor or changing its previous siblings is not supported.
* @param {Visited} node
* Found node.
* @param {Array<VisitedParents>} ancestors
* Ancestors of `node`.
* @param {number | undefined} index
* Index of `node` in its parent (the last of `ancestors`),
* or `undefined` for the tree itself.
* @returns {VisitorResult}
* What to do next.
*
* Like `VisitorExit`,
* but `SKIP` can also be returned,
* to not walk the children of `node`.
* Passing a tuple back (`ActionTuple`) only makes sense as `[SKIP, Index]`.
* @template {UnistNode} [Visited=UnistNode]
* Visited node type.
* @template {UnistParent} [VisitedParents=UnistParent]
* Ancestor type.
*/
/**
* @callback VisitorExit
* Handle a node (matching `test`, if given) after its children.
*
* Changes inside `node` are not walked,
* which makes this a good place to change `node` based on its children,
* or to replace or remove it.
* When removing `node` or changing previous siblings (in walk order),
* return a new `Index`.
* Removing an ancestor or changing its previous siblings is not supported.
* @param {Visited} node
* Found node.
* @param {Array<VisitedParents>} ancestors
* Ancestors of `node`.
* @param {number | undefined} index
* Index of `node` in its parent (the last of `ancestors`),
* or `undefined` for the tree itself.
* @returns {VisitorResultExit}
* What to do next.
*
* `CONTINUE` (`true`, nothing) continues as normal,
* `EXIT` (`false`) stops traversing,
* and `Index` continues at that sibling.
* @template {UnistNode} [Visited=UnistNode]
* Visited node type.
* @template {UnistParent} [VisitedParents=UnistParent]
* Ancestor type.
*/
/**
* @template {UnistNode} [Visited=UnistNode]
* Visited node type.
* @template {UnistParent} [VisitedParents=UnistParent]
* Ancestor type.
* @typedef Visitors
* Handle nodes when entering and exiting them.
* The `enter` visitor is optional while `exit` is required.
*
* Pass an `enter` visitor directly to only handle nodes when entering them.
*
* `enter` is called before children (if any) are walked and `exit` after that.
* `exit` is still called when `enter` returns `SKIP`.
* Both `enter` and `exit` are only called for nodes that match an optional `test`.
* @property {Visitor<Visited, VisitedParents> | null | undefined} [enter]
* Handle a node before its children (optional).
* @property {VisitorExit<Visited, VisitedParents>} exit
* Handle a node after its children.
*/
/**
* @typedef {Visitor<Matches<InclusiveDescendant<Tree>, Check>, Ancestor<Tree, Matches<InclusiveDescendant<Tree>, Check>>>} BuildVisitor
* Build a typed `Visitor` function from a tree and a test.
*
* It will infer which values are passed as `node` and which as `parents`.
* @template {UnistNode} [Tree=UnistNode]
* Tree type.
* @template {Test} [Check=Test]
* Test type.
*/
/**
* @typedef {Visitors<Matches<InclusiveDescendant<Tree>, Check>, Ancestor<Tree, Matches<InclusiveDescendant<Tree>, Check>>>} BuildVisitors
* Build typed `Visitors` from a tree and a test.
*
* It will infer which values are passed as `node` and which as `parents`.
* @template {UnistNode} [Tree=UnistNode]
* Tree type.
* @template {Test} [Check=Test]
* Test type.
*/
import {convert} from 'unist-util-is'
import {color} from 'unist-util-visit-parents/do-not-use-color'
/** @type {Readonly<ActionTuple>} */
const empty = []
/**
* Continue traversing as normal.
*/
export const CONTINUE = true
/**
* Stop traversing immediately.
*/
export const EXIT = false
/**
* Do not traverse this node’s children.
* Only works when entering a node.
*/
export const SKIP = 'skip'
/**
* Visit nodes, with ancestral information.
*
* This algorithm performs *depth-first* *tree traversal* in *preorder*
* (**NLR**) or if `reverse` is given,
* in *reverse preorder* (**NRL**).
* An `exit` visitor is called in *postorder* (**LRN**)
* or if `reverse` is given, in *reverse postorder* (**RLN**).
*
* You can choose which nodes are visited by passing a `test`.
* For complex tests, you should test yourself in a visitor, as it will be
* faster and will have improved type information.
*
* Walking the tree is an intensive task.
* Make use of the return values of the visitor when possible.
* Instead of walking a tree multiple times, walk it once, use `unist-util-is`
* to check if a node matches, and then perform different operations.
*
* You can change the tree.
* Changes inside a node made when entering it are walked,
* changes made when exiting it are not.
* See `Visitor` and `VisitorExit` for more info.
*
* @overload
* @param {Tree} tree
* Tree to traverse.
* @param {Check} check
* `unist-util-is`-compatible test.
* @param {BuildVisitor<Tree, Check>} enter
* Handle each node when entering it.
* @param {boolean | null | undefined} [reverse]
* Walk children from last to first;
* for `enter`, reverse preorder (NRL) instead of preorder (NLR);
* for `exit`, reverse postorder (RLN) instead of postorder (LRN).
* @returns {undefined}
* Nothing.
*
* @overload
* @param {Tree} tree
* Tree to traverse.
* @param {Check} check
* `unist-util-is`-compatible test.
* @param {BuildVisitors<Tree, Check>} visitors
* Handle each node when exiting it, and optionally when entering it.
* @param {boolean | null | undefined} [reverse]
* Walk children from last to first;
* for `enter`, reverse preorder (NRL) instead of preorder (NLR);
* for `exit`, reverse postorder (RLN) instead of postorder (LRN).
* @returns {undefined}
* Nothing.
*
* @overload
* @param {Tree} tree
* Tree to traverse.
* @param {BuildVisitor<Tree>} enter
* Handle each node when entering it.
* @param {boolean | null | undefined} [reverse]
* Walk children from last to first;
* for `enter`, reverse preorder (NRL) instead of preorder (NLR);
* for `exit`, reverse postorder (RLN) instead of postorder (LRN).
* @returns {undefined}
* Nothing.
*
* @overload
* @param {Tree} tree
* Tree to traverse.
* @param {BuildVisitors<Tree>} visitors
* Handle each node when exiting it, and optionally when entering it.
* @param {boolean | null | undefined} [reverse]
* Walk children from last to first;
* for `enter`, reverse preorder (NRL) instead of preorder (NLR);
* for `exit`, reverse postorder (RLN) instead of postorder (LRN).
* @returns {undefined}
* Nothing.
*
* @param {UnistNode} tree
* Tree to traverse.
* @param {Visitor | Visitors | Test} testOrEnterOrVisitors
* `unist-util-is`-compatible test, `enter`, or `visitors`.
* @param {Visitor | Visitors | boolean | null | undefined} [enterOrVisitorsOrReverse]
* `enter`, `visitors`, or `reverse` after a test.
* @param {boolean | null | undefined} [reverse]
* Walk children from last to first;
* for `enter`, reverse preorder (NRL) instead of preorder (NLR);
* for `exit`, reverse postorder (RLN) instead of postorder (LRN).
* @returns {undefined}
* Nothing.
*
* @template {UnistNode} Tree
* Node type.
* @template {Test} Check
* `unist-util-is`-compatible test.
*/
export function visitParents(
tree,
testOrEnterOrVisitors,
enterOrVisitorsOrReverse,
reverse
) {
if (!tree || typeof tree !== 'object') {
throw new Error('Unexpected value `' + tree + '` for `tree`, expected node')
}
let preorder = true
/** @type {Test} */
let check
/** @type {Visitors | Visitor} */
let visitors
/** @type {Visitor | null | undefined} */
let enter
/** @type {VisitorExit | null | undefined} */
let exit
// Third parameter is an enter visitor or a visitors object, so expect a `test` too.
if (
typeof enterOrVisitorsOrReverse === 'function' ||
(enterOrVisitorsOrReverse && typeof enterOrVisitorsOrReverse === 'object')
) {
check = /** @type {Test} */ (testOrEnterOrVisitors)
visitors = enterOrVisitorsOrReverse
if (reverse) preorder = false
}
// Assume no test.
else {
visitors = /** @type {Visitors | Visitor} */ (testOrEnterOrVisitors)
if (enterOrVisitorsOrReverse) preorder = false
}
if (typeof visitors === 'function') {
enter = visitors
} else if (visitors && typeof visitors === 'object') {
if (visitors.enter === null || visitors.enter === undefined) {
// Empty.
} else if (typeof visitors.enter === 'function') {
enter = visitors.enter
} else {
throw new Error(
'Unexpected value `' +
visitors.enter +
'` for `visitors.enter`, expected optional visitor'
)
}
if (typeof visitors.exit === 'function') {
exit = visitors.exit
} else {
throw new Error(
'Unexpected value `' +
visitors.exit +
'` for `visitors.exit`, expected visitor (pass a visitor directly if you only want an enter visitor)'
)
}
} else {
throw new Error(
'Unexpected value `' +
visitors +
'` for `enter` or `visitors`, expected visitor or object with visitors'
)
}
const is = convert(check)
const step = preorder ? 1 : -1
factory(tree, undefined, [])()
/**
* Create a function to visit a node.
*
* @param {UnistNode} node
* Node to visit.
* @param {number | undefined} index
* Index of `node` in its parent.
* @param {Array<UnistParent>} parents
* Ancestors of `node`.
* @returns {() => Readonly<ActionTuple>}
* Visit `node`.
*/
function factory(node, index, parents) {
const value = /** @type {Record<string, unknown>} */ (
node && typeof node === 'object' ? node : {}
)
if (typeof value.type === 'string') {
const name =
// `hast`
typeof value.tagName === 'string'
? value.tagName
: // `xast`
typeof value.name === 'string'
? value.name
: undefined
Object.defineProperty(visit, 'name', {
value:
'node (' + color(node.type + (name ? '<' + name + '>' : '')) + ')'
})
}
return visit
function visit() {
const matches =
!check || is(node, index, parents[parents.length - 1] || undefined)
/** @type {Readonly<ActionTuple>} */
let result = empty
if (enter && matches) {
result = toResult(enter(node, parents, index))
if (result[0] === EXIT) {
return result
}
}
if ('children' in node && node.children) {
const nodeAsParent = /** @type {UnistParent} */ (node)
if (nodeAsParent.children && result[0] !== SKIP) {
let offset = (preorder ? -1 : nodeAsParent.children.length) + step
const grandparents = [...parents, nodeAsParent]
while (offset > -1 && offset < nodeAsParent.children.length) {
const child = nodeAsParent.children[offset]
const subresult = factory(child, offset, grandparents)()
if (subresult[0] === EXIT) {
return subresult
}
offset =
typeof subresult[1] === 'number' ? subresult[1] : offset + step
}
}
}
if (exit && matches) {
const exitResult = toResult(exit(node, parents, index))
if (exitResult[0] === SKIP) {
throw new Error(
'Unexpected value `' +
exitResult[0] +
'` from `exit`, expected `CONTINUE`, `EXIT`, index, or nothing'
)
}
// Prefer a result from `exit` over `enter`.
if (exitResult[0] === EXIT || typeof exitResult[1] === 'number') {
return exitResult
}
}
return result
}
}
}
/**
* Turn a return value into a clean result.
*
* @param {VisitorResult} value
* Valid return values from visitors.
* @returns {Readonly<ActionTuple>}
* Clean result.
*/
function toResult(value) {
if (Array.isArray(value)) {
return value
}
if (typeof value === 'number') {
return [CONTINUE, value]
}
return value === null || value === undefined ? empty : [value]
}
+22
View File
@@ -0,0 +1,22 @@
(The MIT License)
Copyright (c) Titus Wormer <tituswormer@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+96
View File
@@ -0,0 +1,96 @@
{
"author": "Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)",
"bugs": "https://github.com/syntax-tree/unist-util-visit-parents/issues",
"contributors": [
"Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)"
],
"dependencies": {
"@types/unist": "^3.0.0",
"unist-util-is": "^6.0.0"
},
"description": "unist utility to recursively walk over nodes, with ancestral information",
"devDependencies": {
"@types/hast": "^3.0.0",
"@types/mdast": "^4.0.0",
"@types/node": "^26.0.0",
"@types/xast": "^2.0.0",
"c8": "^12.0.0",
"mdast-util-from-markdown": "^2.0.0",
"mdast-util-gfm": "^3.0.0",
"micromark-extension-gfm": "^3.0.0",
"prettier": "^3.0.0",
"remark-cli": "^12.0.0",
"remark-preset-wooorm": "^11.0.0",
"strip-ansi": "^7.0.0",
"tsd": "^0.33.0",
"type-coverage": "^2.0.0",
"typescript": "^6.0.0",
"xo": "^5.0.0"
},
"exports": {
".": "./index.js",
"./do-not-use-color": {
"node": "./lib/color.node.js",
"default": "./lib/color.js"
}
},
"files": [
"lib/",
"index.d.ts",
"index.js"
],
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/unified"
},
"keywords": [
"ast",
"check",
"parents",
"parent",
"traverse",
"tree",
"unist-util",
"unist",
"utility",
"util",
"visit",
"walk"
],
"license": "MIT",
"name": "unist-util-visit-parents",
"prettier": {
"bracketSpacing": false,
"semi": false,
"singleQuote": true,
"tabWidth": 2,
"trailingComma": "none",
"useTabs": false
},
"remarkConfig": {
"plugins": [
"remark-preset-wooorm"
]
},
"repository": "syntax-tree/unist-util-visit-parents",
"scripts": {
"build": "tsc --build --clean && tsc --build && tsd && type-coverage",
"format": "remark --frail --output --quiet -- . && prettier --log-level warn --write -- . && xo --fix",
"prepack": "npm run build && npm run format",
"test-api": "node --conditions development test.js",
"test-coverage": "c8 --100 --reporter lcov -- npm run test-api",
"test": "npm run build && npm run format && npm run test-coverage"
},
"sideEffects": false,
"typeCoverage": {
"atLeast": 100,
"#": "needed `any`s",
"ignoreFiles": [
"lib/index.d.ts"
],
"strict": true
},
"types": "./index.d.ts",
"type": "module",
"version": "6.1.0"
}
+499
View File
@@ -0,0 +1,499 @@
# unist-util-visit-parents
[![Build][build-badge]][build]
[![Coverage][coverage-badge]][coverage]
[![Downloads][downloads-badge]][downloads]
[![Size][size-badge]][size]
[![Sponsors][sponsors-badge]][collective]
[![Backers][backers-badge]][collective]
[![Chat][chat-badge]][chat]
[unist][] utility to walk the tree with a stack of parents.
## Contents
* [What is this?](#what-is-this)
* [When should I use this?](#when-should-i-use-this)
* [Install](#install)
* [Use](#use)
* [API](#api)
* [`visitParents(tree[, test], enter|visitors[, reverse])`](#visitparentstree-test-entervisitors-reverse)
* [`CONTINUE`](#continue)
* [`EXIT`](#exit)
* [`SKIP`](#skip)
* [`Action`](#action)
* [`ActionTuple`](#actiontuple)
* [`BuildVisitor`](#buildvisitor)
* [`BuildVisitors`](#buildvisitors)
* [`Index`](#index)
* [`Test`](#test)
* [`Visitor`](#visitor)
* [`VisitorExit`](#visitorexit)
* [`VisitorResult`](#visitorresult)
* [`VisitorResultExit`](#visitorresultexit)
* [`Visitors`](#visitors)
* [Types](#types)
* [Compatibility](#compatibility)
* [Related](#related)
* [Contribute](#contribute)
* [License](#license)
## What is this?
This is a very important utility for working with unist as it lets you walk the
tree.
## When should I use this?
You can use this utility when you want to walk the tree and want to know about
every parent of each node.
You can use [`unist-util-visit`][unist-util-visit] if you don’t care about the
entire stack of parents.
## Install
This package is [ESM only][esm].
In Node.js (version 16+), install with [npm][]:
```sh
npm install unist-util-visit-parents
```
In Deno with [`esm.sh`][esmsh]:
```js
import {visitParents} from 'https://esm.sh/unist-util-visit-parents@6'
```
In browsers with [`esm.sh`][esmsh]:
```html
<script type="module">
import {visitParents} from 'https://esm.sh/unist-util-visit-parents@6?bundle'
</script>
```
## Use
```js
import {visitParents} from 'unist-util-visit-parents'
import {fromMarkdown} from 'mdast-util-from-markdown'
const tree = fromMarkdown('Some *emphasis*, **strong**, and `code`.')
visitParents(tree, 'strong', function (node, ancestors) {
console.log(node.type, ancestors.map(ancestor => ancestor.type))
})
```
Yields:
```js
strong ['root', 'paragraph']
```
## API
This package exports the identifiers [`CONTINUE`][api-continue],
[`EXIT`][api-exit], [`SKIP`][api-skip], and [`visitParents`][api-visitparents].
There is no default export.
### `visitParents(tree[, test], enter|visitors[, reverse])`
Visit nodes, with ancestral information.
This algorithm performs *[depth-first][]* *[tree traversal][tree-traversal]*
in *[preorder][]* (**NLR**) or if `reverse` is given,
in *reverse preorder* (**NRL**).
An [`exit`][api-visitors] visitor is called in *[postorder][]* (**LRN**)
or if `reverse` is given, in *reverse postorder* (**RLN**).
You can choose which nodes are visited by passing a `test`.
For complex tests, you should test yourself in a visitor, as it will be
faster and will have improved type information.
Walking the tree is an intensive task.
Make use of the return values of the visitor when possible.
Instead of walking a tree multiple times, walk it once, use
[`unist-util-is`][unist-util-is] to check if a node matches, and then perform
different operations.
You can change the tree.
Changes inside a node made when entering it are walked,
changes made when exiting it are not.
See [`Visitor`][api-visitor] and [`VisitorExit`][api-visitorexit] for more
info.
###### Signatures
* `visitParents(tree[, test], enter[, reverse])`
* `visitParents(tree[, test], visitors[, reverse])`
###### Parameters
* `tree` ([`Node`][node])
— tree to traverse
* `test` ([`Test`][api-test], optional)
— [`unist-util-is`][unist-util-is]-compatible test
* `enter` ([`Visitor`][api-visitor])
— handle each node when entering it
* `visitors` ([`Visitors`][api-visitors])
— handle each node when exiting it,
and optionally when entering it
* `reverse` (`boolean`, default: `false`)
— walk children from last to first;
for `enter`, reverse preorder (NRL) instead of preorder (NLR);
for `exit`, reverse postorder (RLN) instead of postorder (LRN)
###### Returns
Nothing (`undefined`).
### `CONTINUE`
Continue traversing as normal (`true`).
### `EXIT`
Stop traversing immediately (`false`).
### `SKIP`
Do not traverse this node’s children (`'skip'`).
Only works when entering a node.
### `Action`
Union of the action types (TypeScript type).
###### Type
```ts
type Action = typeof CONTINUE | typeof EXIT | typeof SKIP
```
### `ActionTuple`
List with one or two values, the first an action, the second an index
(TypeScript type).
###### Type
```ts
type ActionTuple = [
(Action | null | undefined | void)?,
(Index | null | undefined)?
]
```
### `BuildVisitor`
Build a typed `Visitor` function from a tree and a test (TypeScript type).
It will infer which values are passed as `node` and which as `parents`.
###### Type parameters
* `Tree` ([`Node`][node], default: `Node`)
— tree type
* `Check` ([`Test`][api-test], default: `Test`)
— test type
###### Returns
[`Visitor`][api-visitor].
### `BuildVisitors`
Build typed [`Visitors`][api-visitors] from a tree and a test (TypeScript
type).
It will infer which values are passed as `node` and which as `parents`.
###### Type parameters
* `Tree` ([`Node`][node], default: `Node`)
— tree type
* `Check` ([`Test`][api-test], default: `Test`)
— test type
###### Returns
[`Visitors`][api-visitors].
### `Index`
Move to the sibling at `index` next (after node itself is completely
traversed) (TypeScript type).
Useful if mutating the tree, such as removing the node the visitor is currently
on, or any of its previous siblings.
Results less than `0` or greater than or equal to `children.length` stop
traversing the parent.
###### Type
```ts
type Index = number
```
### `Test`
[`unist-util-is`][unist-util-is] compatible test (TypeScript type).
### `Visitor`
Handle a node (matching `test`, if given) before its children (TypeScript
type).
Changes inside `node` are walked next.
Replacing or removing it is easier in `exit`.
When replacing or removing it here,
return `SKIP` (as otherwise its old children are walked),
or `[SKIP, index]` to continue with the node now at `index`.
Changing next siblings (in walk order) is fine;
changing previous siblings needs a new `Index`.
Removing an ancestor or changing its previous siblings is not supported.
###### Parameters
* `node` ([`Node`][node])
— found node
* `parents` ([`Array<Node>`][node])
— ancestors of `node`
* `index` (`number` or `undefined`)
— index of `node` in its parent (the last of `parents`),
or `undefined` for the tree itself
###### Returns
What to do next ([`VisitorResult`][api-visitorresult]).
Passing a tuple back ([`ActionTuple`][api-actiontuple]) only makes sense as
`[SKIP, Index]`.
### `VisitorExit`
Handle a node (matching `test`, if given) after its children (TypeScript type).
Changes inside `node` are not walked,
which makes this a good place to change `node` based on its children,
or to replace or remove it.
When removing `node` or changing previous siblings (in walk order),
return a new `Index`.
Removing an ancestor or changing its previous siblings is not supported.
###### Parameters
* `node` ([`Node`][node])
— found node
* `parents` ([`Array<Node>`][node])
— ancestors of `node`
* `index` (`number` or `undefined`)
— index of `node` in its parent (the last of `parents`),
or `undefined` for the tree itself
###### Returns
What to do next ([`VisitorResultExit`][api-visitorresultexit]).
`CONTINUE` (`true`, nothing) continues as normal,
`EXIT` (`false`) stops traversing,
and `Index` continues at that sibling.
### `VisitorResult`
Any value that can be returned from an enter visitor (TypeScript type).
Like [`VisitorResultExit`][api-visitorresultexit] but `SKIP` can be returned to
not walk children of the node,
and [`ActionTuple`][api-actiontuple] can be used to combine an action with an
index.
###### Type
```ts
type VisitorResult =
| Action
| ActionTuple
| Index
| null
| undefined
| void
```
### `VisitorResultExit`
Any value that can be returned from an exit visitor (TypeScript type).
###### Type
```ts
type VisitorResultExit = Index | boolean | null | undefined | void
```
### `Visitors`
Handle nodes when entering and exiting them (TypeScript type).
The `enter` visitor is optional while `exit` is required.
Pass an `enter` visitor directly to only handle nodes when entering them.
`enter` is called before children (if any) are walked and `exit` after that.
`exit` is still called when `enter` returns `SKIP`.
Both `enter` and `exit` are only called for nodes that match an optional `test`.
###### Fields
* `enter` ([`Visitor`][api-visitor], optional)
— handle a node before its children
* `exit` ([`VisitorExit`][api-visitorexit])
— handle a node after its children
## Types
This package is fully typed with [TypeScript][].
It exports the additional types [`Action`][api-action],
[`ActionTuple`][api-actiontuple],
[`BuildVisitor`][api-buildvisitor],
[`BuildVisitors`][api-buildvisitors],
[`Index`][api-index],
[`Test`][api-test],
[`Visitor`][api-visitor],
[`VisitorExit`][api-visitorexit],
[`VisitorResult`][api-visitorresult],
[`VisitorResultExit`][api-visitorresultexit], and
[`Visitors`][api-visitors].
## Compatibility
Projects maintained by the unified collective are compatible with maintained
versions of Node.js.
When we cut a new major release, we drop support for unmaintained versions of
Node.
This means we try to keep the current release line,
`unist-util-visit-parents@^6`, compatible with Node.js 16.
## Related
* [`unist-util-visit`][unist-util-visit]
— walk the tree with one parent
* [`unist-util-filter`](https://github.com/syntax-tree/unist-util-filter)
— create a new tree with all nodes that pass a test
* [`unist-util-map`](https://github.com/syntax-tree/unist-util-map)
— create a new tree with all nodes mapped by a given function
* [`unist-util-flatmap`](https://gitlab.com/staltz/unist-util-flatmap)
— create a new tree by mapping (to an array) with the given function
* [`unist-util-remove`](https://github.com/syntax-tree/unist-util-remove)
— remove nodes from a tree that pass a test
* [`unist-util-select`](https://github.com/syntax-tree/unist-util-select)
— select nodes with CSS-like selectors
## Contribute
See [`contributing.md`][contributing] in [`syntax-tree/.github`][health] for
ways to get started.
See [`support.md`][support] for ways to get help.
This project has a [code of conduct][coc].
By interacting with this repository, organization, or community you agree to
abide by its terms.
## License
[MIT][license] © [Titus Wormer][author]
<!-- Definition -->
[api-action]: #action
[api-actiontuple]: #actiontuple
[api-buildvisitor]: #buildvisitor
[api-buildvisitors]: #buildvisitors
[api-continue]: #continue
[api-exit]: #exit
[api-index]: #index
[api-skip]: #skip
[api-test]: #test
[api-visitor]: #visitor
[api-visitorexit]: #visitorexit
[api-visitorresult]: #visitorresult
[api-visitorresultexit]: #visitorresultexit
[api-visitors]: #visitors
[api-visitparents]: #visitparentstree-test-entervisitors-reverse
[author]: https://wooorm.com
[backers-badge]: https://opencollective.com/unified/backers/badge.svg
[build]: https://github.com/syntax-tree/unist-util-visit-parents/actions
[build-badge]: https://github.com/syntax-tree/unist-util-visit-parents/workflows/main/badge.svg
[chat]: https://github.com/syntax-tree/unist/discussions
[chat-badge]: https://img.shields.io/badge/chat-discussions-success.svg
[coc]: https://github.com/syntax-tree/.github/blob/HEAD/code-of-conduct.md
[collective]: https://opencollective.com/unified
[contributing]: https://github.com/syntax-tree/.github/blob/HEAD/contributing.md
[coverage]: https://codecov.io/github/syntax-tree/unist-util-visit-parents
[coverage-badge]: https://img.shields.io/codecov/c/github/syntax-tree/unist-util-visit-parents.svg
[depth-first]: https://github.com/syntax-tree/unist#depth-first-traversal
[downloads]: https://www.npmjs.com/package/unist-util-visit-parents
[downloads-badge]: https://img.shields.io/npm/dm/unist-util-visit-parents.svg
[esm]: https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c
[esmsh]: https://esm.sh
[health]: https://github.com/syntax-tree/.github
[license]: license
[node]: https://github.com/syntax-tree/unist#node
[npm]: https://docs.npmjs.com/cli/install
[postorder]: https://github.com/syntax-tree/unist#postorder
[preorder]: https://github.com/syntax-tree/unist#preorder
[size]: https://bundlejs.com/?q=unist-util-visit-parents
[size-badge]: https://img.shields.io/badge/dynamic/json?label=minzipped%20size&query=$.size.compressedSize&url=https://deno.bundlejs.com/?q=unist-util-visit-parents
[sponsors-badge]: https://opencollective.com/unified/sponsors/badge.svg
[support]: https://github.com/syntax-tree/.github/blob/HEAD/support.md
[tree-traversal]: https://github.com/syntax-tree/unist#tree-traversal
[typescript]: https://www.typescriptlang.org
[unist]: https://github.com/syntax-tree/unist
[unist-util-is]: https://github.com/syntax-tree/unist-util-is
[unist-util-visit]: https://github.com/syntax-tree/unist-util-visit