@ast-grep/wasm

中文文档
0.51.1发布于 2026/11/02MITTypeScriptES Module零依赖近 30 天下载 9224

Search and Rewrite code at large scale using precise AST pattern

原始使用文档
文档目录14 节
  1. Installation
  2. Vite
  3. Usage
  4. Registering Languages
  5. Pattern Matching
  6. Code Rewriting
  7. API Reference
  8. Top-level functions
  9. SgRoot
  10. SgNode
  11. Building from Source
  12. Testing
  13. Rust WASM tests
  14. JavaScript tests

@ast-grep/wasm

WebAssembly build of ast-grep for use in browsers and Node.js.

This package provides the same API as @ast-grep/napi but runs in any JavaScript environment that supports WebAssembly, including browsers, Deno, and edge runtimes.

Installation

yarn add @ast-grep/wasm web-tree-sitter

web-tree-sitter is a required peer dependency.

Vite

When using Vite, you need to make tree-sitter.wasm available in your public directory. You can automate this with a postinstall script in your package.json (see web-tree-sitter setup):

"postinstall": "cp node_modules/web-tree-sitter/tree-sitter.wasm public"

Usage

Unlike @ast-grep/napi, this package has no predefined language support. All languages must be registered at runtime by loading their tree-sitter WASM parser.

import { initializeTreeSitter, registerDynamicLanguage, parse, kind } from '@ast-grep/wasm'

// 1. Initialize the tree-sitter WASM runtime (once)
await initializeTreeSitter()

// 2. Register a language by loading its WASM parser
await registerDynamicLanguage({
  javascript: { libraryPath: '/path/to/tree-sitter-javascript.wasm' },
})

// 3. Parse and search code
const sg = parse('javascript', 'console.log("hello world")')
const node = sg.root().find('console.log($ARG)')
console.log(node.getMatch('ARG').text()) // "hello world"

Registering Languages

registerDynamicLanguage accepts a map of language name to registration config. It can be called multiple times to add or update languages.

await registerDynamicLanguage({
  javascript: { libraryPath: '/path/to/tree-sitter-javascript.wasm' },
  python: {
    libraryPath: '/path/to/tree-sitter-python.wasm',
    expandoChar: 'µ',  // custom expando char for languages where $ is special
  },
})

The expandoChar option sets the character used internally to represent metavariables (defaults to $). Use a different character for languages where $ is a valid identifier character (e.g. PHP, Bash).

Pattern Matching

// By pattern string
sg.root().find('console.log($$$ARGS)')

// By kind number
const k = kind('javascript', 'call_expression')
sg.root().find(k)

// By rule config (same as YAML rules)
sg.root().find({
  rule: { pattern: 'console.log($A)' },
  constraints: { A: { kind: 'string' } },
})

Code Rewriting

const match = sg.root().find('console.log($A)')
const edit = match.replace('console.error($A)')
const newCode = sg.root().commitEdits([edit])

API Reference

Top-level functions

initializeTreeSitter(): Promise<void>

Initializes the tree-sitter WASM runtime. Must be called once before any other function.

registerDynamicLanguage(langs: Record<string, { libraryPath: string, expandoChar?: string }>): Promise<void>

Registers one or more language parsers by loading their WASM binaries. Can be called multiple times; existing languages are updated.

parse(lang: string, src: string): SgRoot

Parses source code and returns an SgRoot instance. Throws if the language has not been registered.

kind(lang: string, kindName: string): number

Returns the numeric kind ID for a named node type in the given language. Useful for matching by node kind.

pattern(lang: string, patternStr: string): object

Compiles a pattern string into a rule config object (equivalent to { rule: { pattern: patternStr } }). Useful for building rule configs programmatically.

dumpPattern(lang: string, patternStr: string, selector?: string, strictness?: string): PatternTree

Dumps the internal structure of a pattern for inspection and debugging. Returns a tree showing how ast-grep parses the pattern, including source positions and node kinds.

  • selector: optional kind name for contextual patterns (e.g. 'field_definition')
  • strictness: one of "cst", "smart" (default), "ast", "relaxed", "signature", "template"

Each PatternTree node has:

  • kind: the tree-sitter node kind string
  • pattern: "metaVar", "terminal", or "internal"
  • isNamed: whether the node is a named node
  • text: source text (for metavar and terminal nodes)
  • children: child PatternTree nodes
  • start, end: { line, column } positions in the pattern source

SgRoot

Represents the parsed tree of code.

root(): SgNode

Returns the root SgNode.

filename(): string

Returns "anonymous" when the instance is created via parse.

getInnerTree(): Tree

Returns the underlying web-tree-sitter Tree object. Useful for low-level inspection or debugging.

SgNode

Represents a single AST node.

Position and info

MethodDescription
range()Returns { start, end } where each is { line, column, index }
isLeaf()True if the node has no children
isNamed()True if the node is a named (non-anonymous) node
isNamedLeaf()True if the node is a named node with no named children
kind()Returns the node kind string
is(kind: string)True if the node kind equals kind
text()Returns the source text of the node
id()Returns the unique node ID

Searching

MethodDescription
find(matcher)Returns the first descendant matching the matcher, or undefined
findAll(matcher)Returns all descendants matching the matcher

Matchers can be a pattern string, a kind number (from kind()), or a rule config object.

Relational matchers

MethodDescription
matches(matcher)True if the node itself matches
inside(matcher)True if the node is inside an ancestor matching the matcher
has(matcher)True if the node has a descendant matching the matcher
precedes(matcher)True if the node comes before a sibling matching the matcher
follows(matcher)True if the node comes after a sibling matching the matcher

Match environment

MethodDescription
getMatch(name: string)Returns the node bound to a metavariable (e.g. $VAR)
getMultipleMatches(name: string)Returns nodes bound to a multi-metavariable (e.g. $$$ARGS)
getTransformed(name: string)Returns the string value of a transformed variable

Tree traversal

MethodDescription
children_nodes()Returns all child nodes
parent_node()Returns the parent node, or undefined
child(nth: number)Returns the nth child, or undefined
ancestors()Returns all ancestors from parent to root
next_node()Returns the next sibling, or undefined
nextAll()Returns all following siblings
prev()Returns the previous sibling, or undefined
prevAll()Returns all preceding siblings
field(name: string)Returns the child node for a named field, or undefined
fieldChildren(name: string)Returns all child nodes for a named field

Editing

MethodDescription
replace(text: string)Creates a WasmEdit replacing this node's range with text
commitEdits(edits: WasmEdit[])Applies edits to the node's text and returns the new source string

WasmEdit has start_pos, end_pos (character offsets), and inserted_text. These fields can be modified before calling commitEdits.

Building from Source

Requires wasm-pack.

# For browser (ES module)
yarn build

# For Node.js (CommonJS)
yarn build:nodejs

# For bundlers
yarn build:bundler

Testing

yarn install

Rust WASM tests

yarn test

Note: wasm-pack test --node runs the test harness from a temporary directory. The test script sets NODE_PATH=$PWD/node_modules so that web-tree-sitter and parser WASM files can be resolved. If you run wasm-pack test --node directly, set NODE_PATH yourself:

NODE_PATH=$PWD/node_modules wasm-pack test --node

JavaScript tests

yarn test:js

This builds the WASM package for Node.js and runs AVA tests against it.

版本与发布记录

@ast-grep/wasm 共发布 18 个版本,首次发布于 2026/02/22;过去 12 个月发布了 18 个版本。

版本发布日期距今
0.51.1latest2026/11/025 天前
0.51.02026/10/1523 天前
0.50.02026/10/0929 天前
0.45.32026/08/312 个月前
0.45.22026/08/242 个月前
0.45.12026/08/073 个月前

关于 @ast-grep/wasm 的常见问题

@ast-grep/wasm 是什么?

Search and Rewrite code at large scale using precise AST pattern

如何安装 @ast-grep/wasm?

在项目目录运行 npm install @ast-grep/wasm,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:web-tree-sitter(^0.26.0 || ^0.27.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@ast-grep/wasm 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@ast-grep/wasm 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@ast-grep/wasm 可以商用吗?

@ast-grep/wasm 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@ast-grep/wasm 的下载量有多少?

根据 npm 官方下载统计,@ast-grep/wasm 在 2026/10/07 – 2026/11/05 这 30 天内被下载 9,224 次,日均约 307 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@ast-grep/wasm 还在维护吗?

最新版本 0.51.1 发布于 2026/11/02(5 天前);至今共发布 18 个版本,其中过去 12 个月发布了 18 个;首次发布于 2026/02/22。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。