99 * @typedef {import('mdast').PhrasingContent } PhrasingContent
1010 * @typedef {import('mdast').Text } Text
1111 * @typedef {Content|Root } Node
12- * @typedef {Extract<Node, import('mdast').Parent> } Parent
12+ * @typedef {Exclude< Extract<Node, import('mdast').Parent>, Root > } Parent
1313 *
1414 * @typedef {import('unist-util-visit-parents').Test } Test
1515 * @typedef {import('unist-util-visit-parents').VisitorResult } VisitorResult
1616 *
1717 * @typedef RegExpMatchObject
1818 * @property {number } index
1919 * @property {string } input
20+ * @property {[Root, ...Array<Parent>, Text] } stack
2021 *
2122 * @typedef {string|RegExp } Find
2223 * @typedef {string|ReplaceFunction } Replace
@@ -119,16 +120,18 @@ export const findAndReplace =
119120 }
120121
121122 if ( grandparent ) {
122- return handler ( node , grandparent )
123+ // @ts -expect-error: stack is fine.
124+ return handler ( node , parents )
123125 }
124126 }
125127
126128 /**
127129 * @param {Text } node
128- * @param {Parent } parent
130+ * @param {[Root, ...Array< Parent>] } parents
129131 * @returns {VisitorResult }
130132 */
131- function handler ( node , parent ) {
133+ function handler ( node , parents ) {
134+ const parent = parents [ parents . length - 1 ]
132135 const find = pairs [ pairIndex ] [ 0 ]
133136 const replace = pairs [ pairIndex ] [ 1 ]
134137 let start = 0
@@ -145,10 +148,13 @@ export const findAndReplace =
145148
146149 while ( match ) {
147150 position = match . index
148- let value = replace ( ...match , {
151+ /** @type {RegExpMatchObject } */
152+ const matchObject = {
149153 index : match . index ,
150- input : match . input
151- } )
154+ input : match . input ,
155+ stack : [ ...parents , node ]
156+ }
157+ let value = replace ( ...match , matchObject )
152158
153159 if ( typeof value === 'string' ) {
154160 value = value . length > 0 ? { type : 'text' , value} : undefined
0 commit comments