Skip to content

Commit

Permalink
fix: bug where matches inside other matches don't get replaced
Browse files Browse the repository at this point in the history
  • Loading branch information
jedwards1211 committed Mar 14, 2024
1 parent 0ee5b0d commit a8ff9de
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 5 deletions.
13 changes: 8 additions & 5 deletions src/Astx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -602,7 +602,10 @@ export default class Astx extends ExtendableProxy implements Iterable<Astx> {
const { parsePatternToNodes } = backend
try {
if (typeof arg0 === 'function') {
for (const astx of this) {
// Always replace in reverse so that if there are matches inside of
// matches, the inner matches get replaced first (since they come
// later in the code)
for (const astx of [...this].reverse()) {
const replacement = arg0(astx, parsePatternToNodes)
replace(
astx.match,
Expand All @@ -614,12 +617,12 @@ export default class Astx extends ExtendableProxy implements Iterable<Astx> {
}
} else if (typeof arg0 === 'string') {
const replacement = parsePatternToNodes(arg0)
for (const match of this._matches) {
replace(match, replacement, this.context)
for (let i = this._matches.length - 1; i >= 0; i--) {
replace(this._matches[i], replacement, this.context)
}
} else if (isNode(arg0) || isNodeArray(arg0)) {
for (const match of this._matches) {
replace(match, arg0, this.context)
for (let i = this._matches.length - 1; i >= 0; i--) {
replace(this._matches[i], arg0, this.context)
}
} else {
const finalPaths = parsePatternToNodes(arg0, ...quasis)
Expand Down
21 changes: 21 additions & 0 deletions test/astx/bugs_nesting.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { TransformOptions } from '../../src'
import { astxTestcase } from '../astxTestcase'
import dedent from 'dedent-js'

astxTestcase({
file: __filename,
input: dedent`
const validator = t.ref(() => t.object({
a: t.ref(() => Foo)
}))
`,
parsers: ['babel', 'babel/tsx'],
astx: ({ astx }: TransformOptions): void => {
astx.find`t.ref(() => $x)`().replace`z.lazy(() => $x)`()
},
expected: dedent`
const validator = z.lazy(() => t.object({
a: z.lazy(() => Foo)
}));
`,
})

0 comments on commit a8ff9de

Please sign in to comment.