ai(instructions)

Replaces code found with ast-grep pattern using instructions provided to LLM.

ai(instructions) requires --OPENAI_API_KEY=somekey to be passed to workflow.

Parameters

instructions
string | readonly string[]
required

Instructions to LLM in natural language with before and after examples.

map(callback)

Works similar to array.map - maps found code with astGrep.

Parameters

callback
CallbackFunction
required
import type { SgNode } from '@ast-grep/napi'

interface CallbackFunctionHelpers {
  getNode: () => SgNode,
  getMatch: (m: string) => SgNode | null,
  getMultipleMatches: (m: string) => SgNode[],
}

type CallbackFunction =
  (helpers: ReplacementFunctionHelpers) =>
  Promise<string | undefined> | string | undefined

It will be called for every found node. It can return anything. You can use file context inside for example.

Helper functions:

replace(replacement)

Replaces code found with astGrep. Receives context with every found node.

Parameters

replacement
string | ReplacementFunction
required
import type { SgNode } from '@ast-grep/napi'

interface ReplacementFunctionHelpers {
  getNode: () => SgNode,
  getMatch: (m: string) => SgNode | null,
  getMultipleMatches: (m: string) => SgNode[],
}

type ReplacementFunction =
  (helpers: ReplacementFunctionHelpers) =>
  Promise<string | undefined> | string | undefined

If string is provided, it will be used as a replacement for every found node. If function is provided, it will be called for every found node. It should return a string which will be used as a replacement.

Replacement string can contain matches from search pattern which would be inserted in place. For example, if search pattern is console.log($$$A) and replacement is console.error($$$A), then console.log('debugging flow') will be replaced with console.error('debugging flow').

If callback is provided, first argument of callback has few helper functions:

  • getNode() - returns current found node
  • getMatch(m: string) - return single match
  • getMultipleMatches(m: string) - return multiple matches You can iterate over matches and return new string.