JavaScript plugin API
Ta treść nie jest jeszcze dostępna w Twoim języku.
JavaScript plugins are JavaScript or TypeScript modules that export lint rules. This page covers the API that Biome provides to them: rules, queries, diagnostics and fixes, and helpers to navigate the syntax tree. To write your first JavaScript plugin, see Create a JavaScript plugin.
Supported languages
Section titled “Supported languages”JavaScript plugins support JavaScript, TypeScript, and their variants, such as JSX. To lint other languages, use a GritQL plugin.
defineRule
Section titled “defineRule”Type: (rule: { query: Query, run: (node, ctx) => void }) => Rule
Defines a lint rule from a query, which selects the nodes the rule inspects, and a run function, which Biome calls for each node that matches the query. For a grit query, it can also be called with a token.
Export the returned rule with export const. The name of the export is the name of the rule, which you also use to silence the rule with a suppression comment:
import { ast, defineRule } from "@biomejs/runtime/plugin";
export const noDebugger = defineRule({ query: ast("JS_DEBUGGER_STATEMENT"), run(node) { // Inspect the node and report diagnostics. },});Query APIs
Section titled “Query APIs”You use query to tell the plugin which nodes to inspect. You can select nodes by their syntax kind with ast, or select them by matching a GritQL pattern with grit.
Find node names
Section titled “Find node names”To find the syntax kind of a node, use the command biome inspect file or the playground. Each node has a name assigned by the Biome grammar, usually in all caps. For example, the name associated with the debugger statement is JS_DEBUGGER_STATEMENT, so you can import its interface called JsDebuggerStatement and use the kind field:
import { defineRule, ast, JsDebuggerStatement } from "@biomejs/runtime/plugin"
export const noAssign = defineRule({ query: ast(JsDebuggerStatement.kind),})ast query
Section titled “ast query”Type: string | ...string, and an optional { semantic?: boolean } options object
Selects nodes by one or more syntax kinds. Pass { semantic: true } as the last argument to make the semantic model of the current file available via ctx.model.
import { defineRule, ast, registerDiagnostic } from "@biomejs/runtime/plugin"
export const noAssign = defineRule({ query: ast("JS_CALL_EXPRESSION", "JS_DEBUGGER"), run(node, ctx) { registerDiagnostic(node, "error", "Can't assign anything.") }})import { defineRule, ast, registerDiagnostic } from "@biomejs/runtime/plugin"
export const noAssign = defineRule({ query: ast("JS_CALL_EXPRESSION", "JS_DEBUGGER", { semantic: true }), run(node, ctx) { const model = ctx.model; registerDiagnostic(node, "error", "Can't assign anything.") }})grit query
Section titled “grit query”Type: string, and an optional { semantic?: boolean } options object
Selects the nodes and tokens that a GritQL pattern matches, instead of selecting them by syntax kind. This is useful when matching a snippet requires inspecting the shape of several AST nodes, which would otherwise take several checks in run.
import { defineRule, grit, registerDiagnostic } from "@biomejs/runtime/plugin"
export const noConsole = defineRule({ query: grit("`console.log($args)`"), run(node) { registerDiagnostic(node, "error", "Unexpected console.log.") }})The pattern is executed against the analyzed file, and run is called once for each match. When a pattern matches a sequence of nodes, such as several sibling statements, run is called for each node in the sequence. The sequence must match exactly, so `foo(); bar()` does not match a list that also contains baz();:
export const noFooThenBar = defineRule({ query: grit("`foo(); bar()`"), run(node) { registerDiagnostic(node, "error", "Don't call foo() immediately before bar().") }})A grit query cannot contain a rewrite (=>), because the query only selects nodes and does not edit the source. Report violations from run instead. The plugin fails to load if the pattern is invalid or contains a rewrite. The pattern must target JavaScript; patterns that declare another target language are not supported.
By default, run does not receive the semantic model. If your rule needs to inspect bindings or scopes, pass { semantic: true } as the second argument to make ctx.model available, like an ast query:
export const noConsole = defineRule({ query: grit("`console.log($args)`", { semantic: true }), run(node, { model }) { // Inspect the bindings of the logged arguments if needed. }})Run APIs
Section titled “Run APIs”The run function receives two arguments, called node and ctx on this page:
node: the node that matched the query.ctx: aRuleContextwith information about the file being linted.
ctx.filePath
Section titled “ctx.filePath”Type: string
The absolute path of the file being linted.
ctx.sourceType
Section titled “ctx.sourceType”Type: JsFileSource
Information about how the file was parsed, such as whether it is JavaScript or TypeScript, whether it is a module or a script, and whether the code is embedded in another file, such as an Astro, Vue, or Svelte component.
ctx.model
Section titled “ctx.model”Type: SemanticModel
Bindings and references in the original analyzed source. Only available when the query passes { semantic: true }.
SemanticModel.binding
Section titled “SemanticModel.binding”Type: (reference: AnyJsIdentifierReference) => Binding | undefined
Resolves an identifier use to the binding it refers to, respecting shadowing. Returns undefined for configured globals and unresolved references.
SemanticModel.asBinding
Section titled “SemanticModel.asBinding”Type: (node: AnyJsIdentifierBinding) => Binding | undefined
Looks up the binding introduced by a declaration’s identifier node. Returns undefined when the model does not track that declaration.
SemanticModel.allBindings
Section titled “SemanticModel.allBindings”Type: () => readonly Binding[]
Returns all tracked bindings in the source, including nested scopes. Declarations with the same name can introduce separate bindings.
SemanticModel.allExportedBindings
Section titled “SemanticModel.allExportedBindings”Type: () => readonly Binding[]
Returns the bindings marked as exported by the model, with each binding appearing once even if it has multiple export sites. Order is unspecified. Re-exports that introduce no local binding are not included.
SemanticModel.hasExports
Section titled “SemanticModel.hasExports”Type: () => boolean
Returns whether the model tracks at least one exported binding. This is not a check for export syntax: an empty export, a re-export without a local binding, or an exported literal can leave this value false.
SemanticModel.scopes
Section titled “SemanticModel.scopes”Type: () => readonly Scope[]
Returns all scopes in this source, including the global scope and nested scopes.
SemanticModel.globalScope
Section titled “SemanticModel.globalScope”Type: () => Scope
Returns the outermost scope of this source, including for an empty file. This scope has no parent. It is unrelated to the global references returned by allGlobalReferences().
SemanticModel.scope
Section titled “SemanticModel.scope”Type: (node: AnyJsAstNode) => Scope | undefined
Returns the most specific scope containing the node’s trimmed source range. Returns undefined for an empty node. Use globalScope() to obtain a scope for an empty file.
SemanticModel.scopeHoistedTo
Section titled “SemanticModel.scopeHoistedTo”Type: (node: AnyJsAstNode) => Scope | undefined
Returns the scope a declaration’s identifier was hoisted to, if the model records one. This can differ from the scope containing its source text.
SemanticModel.allGlobalReferences
Section titled “SemanticModel.allGlobalReferences”Type: () => readonly GlobalReference[]
Returns references resolved to globals configured in the supplied model. Locally shadowed names resolve to local bindings instead.
SemanticModel.allUnresolvedReferences
Section titled “SemanticModel.allUnresolvedReferences”Type: () => readonly UnresolvedReference[]
Returns references that resolve to neither a local binding nor a global configured in the supplied model.
SemanticModel.isGlobalReference
Section titled “SemanticModel.isGlobalReference”Type: (reference: AnyJsIdentifierReference) => boolean
Returns whether an identifier use resolves to a configured global. Returns false for local bindings and unresolved references.
SemanticModel.isUnresolvedReference
Section titled “SemanticModel.isUnresolvedReference”Type: (reference: AnyJsIdentifierReference) => boolean
Returns whether an identifier use has no local binding or configured global. A reference to a declaration later in the source can still resolve.
SemanticModel.isImported
Section titled “SemanticModel.isImported”Type: (node: AnyJsIdentifierBinding | AnyJsIdentifierReference) => boolean
Returns whether a declaration is imported, or a reference resolves to an imported declaration. Returns false when a reference has no local binding.
SemanticModel.isExported
Section titled “SemanticModel.isExported”Type: (node: AnyJsIdentifierBinding | AnyJsIdentifierReference) => boolean
Returns whether a declaration is exported, or a reference resolves to an exported declaration. Returns false when a reference has no local binding.
Binding.syntax
Section titled “Binding.syntax”Type: () => AnyJsIdentifierBinding
Returns the identifier node introducing this binding, rather than the enclosing declaration statement. The node can be used in diagnostics and fixes.
Binding.declarationKind
Section titled “Binding.declarationKind”Type: () => "class" | "enum" | "function" | "generic" | "hoistedValue" | "import" | "importType" | "interface" | "module" | "namespace" | "type" | "unknown" | "using" | "value"
Returns the model’s declaration classification, such as "function", "importType", or "hoistedValue". This describes how the binding was declared, rather than the syntax kind of its identifier node.
Binding.exports
Section titled “Binding.exports”Type: () => readonly (AnyJsIdentifierBinding | AnyJsIdentifierReference)[]
Returns the identifier nodes at this binding’s tracked export sites. A directly exported declaration yields its identifier binding; an export specifier yields the local identifier reference, not its exported alias. Returns an empty array for a binding with no tracked export sites.
Binding.exportRanges
Section titled “Binding.exportRanges”Type: () => readonly { readonly start: number; readonly end: number }[]
Returns the model’s source ranges for this binding’s export sites. Offsets count UTF-8 bytes, with an inclusive start and exclusive end; they are not JavaScript string indices. Returns an empty array when no export sites are tracked.
Binding.scope
Section titled “Binding.scope”Type: () => Scope
Returns the scope containing the declaration’s identifier in the source. For hoisted declarations, use ctx.model.scopeHoistedTo(binding.syntax()) to inspect the destination scope instead.
Binding.allReferences
Section titled “Binding.allReferences”Type: () => readonly Reference[]
Returns all references that resolve to this binding, including reads and writes. References to a different binding with the same name are excluded.
Binding.allReads
Section titled “Binding.allReads”Type: () => readonly Reference[]
Returns references classified as reads by the semantic model.
Binding.allWrites
Section titled “Binding.allWrites”Type: () => readonly Reference[]
Returns references classified as writes by the semantic model.
Binding.isImported
Section titled “Binding.isImported”Type: () => boolean
Returns whether this binding was declared by an import.
Binding.isExported
Section titled “Binding.isExported”Type: () => boolean
Returns whether this binding is exported from the source.
Reference.syntax
Section titled “Reference.syntax”Type: () => AnyJsIdentifierReference
Returns the identifier node at the reference site. The node can be used in diagnostics and fixes.
Reference.binding
Section titled “Reference.binding”Type: () => Binding | undefined
Returns the binding this reference resolves to.
Reference.scope
Section titled “Reference.scope”Type: () => Scope
Returns the scope containing this identifier use, which can differ from the scope containing its declaration.
Reference.isRead
Section titled “Reference.isRead”Type: () => boolean
Returns whether the model classifies this reference as a read.
Reference.isWrite
Section titled “Reference.isWrite”Type: () => boolean
Returns whether the model classifies this reference as a write.
Scope.syntax
Section titled “Scope.syntax”Type: () => AnyJsAstNode
Returns the syntax node associated with this scope, such as a module, function, or block. The node can be used in diagnostics and fixes.
Scope.isGlobalScope
Section titled “Scope.isGlobalScope”Type: () => boolean
Returns whether this is the source’s outermost scope.
Scope.parent
Section titled “Scope.parent”Type: () => Scope | undefined
Returns the immediately enclosing scope, or undefined for the global scope.
Scope.children
Section titled “Scope.children”Type: () => readonly Scope[]
Returns this scope’s immediate child scopes, without their descendants.
Scope.ancestors
Section titled “Scope.ancestors”Type: () => readonly Scope[]
Returns this scope followed by its enclosing scopes, ending with the global scope.
Scope.bindings
Section titled “Scope.bindings”Type: () => readonly Binding[]
Returns bindings declared in or hoisted to this scope. Bindings belonging to parent or child scopes are excluded.
Scope.getBinding
Section titled “Scope.getBinding”Type: (name: string) => Binding | undefined
Looks up a binding in this scope only; parent scopes are not searched. Returns undefined when the name is absent. Unicode escapes are decoded. When a TypeScript name has both type and value bindings, the value binding is preferred, falling back to the type binding if no value exists.
GlobalReference.syntax
Section titled “GlobalReference.syntax”Type: () => AnyJsIdentifierReference
Returns the identifier node that uses the configured global.
GlobalReference.isRead
Section titled “GlobalReference.isRead”Type: () => boolean
Returns whether the model classifies this global reference as a read.
GlobalReference.isWrite
Section titled “GlobalReference.isWrite”Type: () => boolean
Returns whether the model classifies this global reference as a write.
UnresolvedReference.syntax
Section titled “UnresolvedReference.syntax”Type: () => AnyJsIdentifierReference
Returns the identifier node whose name could not be resolved.
Diagnostics and fixes
Section titled “Diagnostics and fixes”registerDiagnostic
Section titled “registerDiagnostic”Type: (element: JsAstNode | JsAstToken | TriviaPiece, severity: Severity, message: string, fix?: CodeFix) => void
Reports a diagnostic. Biome highlights element and shows message with the given severity: "hint", "information", "warning", "error", or "fatal". Nodes and tokens are highlighted without their leading and trailing trivia. To suggest a change, pass a CodeFix as fix.
registerDiagnostic(declaration, "warning", "Use let or const instead of var.");It throws a TypeError if element is a token or a trivia piece that is not part of the analyzed source, such as a token created with factory.token. See also Report diagnostics on tokens and trivia.
CodeFix
Section titled “CodeFix”Type: { mutation: JsMutation, message: string, kind: "safe" | "unsafe" }
A suggested edit attached to a diagnostic:
mutation: the mutation that holds the edits.message: a message that describes the edit.kind:"safe"or"unsafe". Biome applies safe fixes with--write, and unsafe fixes only with--write --unsafe.
createMutation
Section titled “createMutation”Type: (node: AnyJsAstNode) => JsMutation
Creates a mutation that collects the edits of one code fix, for the source that node comes from. Adding edits does not change the source or the nodes you already have. To apply the edits as a fix, pass the mutation to registerDiagnostic as part of a CodeFix.
const mutation = createMutation(statement);mutation.removeNode(statement);Keep the following in mind when you build a fix:
- You are responsible for making sure that the resulting code is valid. For example, removing an argument does not automatically remove its comma.
- Replacements keep the leading and trailing comments and whitespace of the original node or token. Removals delete them along with the node or token.
- Edits to the same node, or to a node and its children, can overwrite each other. Combine these changes into a single replacement for a predictable result.
- Finish adding edits before you register the fix. Once registered, a mutation cannot be changed or attached to another diagnostic.
- You can keep nodes, tokens, and unfinished mutations between
run()calls, but report a fix only for the source the mutation was created from.
JsMutation.replaceNode
Section titled “JsMutation.replaceNode”Type: (previous: AnyJsAstNode, next: AnyJsAstNode) => void
Replaces a node, keeping its leading and trailing comments and whitespace. The replacement can be an existing node or a node created by a field-update method, such as withValueToken().
JsMutation.replaceToken
Section titled “JsMutation.replaceToken”Type: (previous: JsAstToken, next: JsAstToken) => void
Replaces a token, keeping its leading and trailing comments and whitespace. Pass token objects, such as the ones returned by node.token(field), not the strings returned by token fields.
JsMutation.replaceElement
Section titled “JsMutation.replaceElement”Type: (previous: JsAstElement, next: JsAstElement) => void
Replaces a node with a node, or a token with a token, keeping the original’s leading and trailing comments and whitespace. It is useful with the elements returned by childrenWithTokens().
JsMutation.removeNode
Section titled “JsMutation.removeNode”Type: (node: AnyJsAstNode) => void
Removes a node and its leading and trailing comments and whitespace. Adjacent commas and other separators are not removed.
JsMutation.removeToken
Section titled “JsMutation.removeToken”Type: (token: JsAstToken) => void
Removes a token and its leading and trailing comments and whitespace. Use node.token(field) to get the token object rather than its text.
JsMutation.removeElement
Section titled “JsMutation.removeElement”Type: (element: JsAstElement) => void
Removes a node or a token and its leading and trailing comments and whitespace. It is useful with the elements returned by childrenWithTokens().
factory.token
Section titled “factory.token”Type: (kind: JsTokenKind, text?: string) => JsAstToken
Creates a token to use as a replacement in a code fix. Keywords and punctuation have a fixed spelling, so you can leave out text. For identifiers and literals, pass the text, including the quotes of a string literal. Biome uses the text as written, without adding spaces or comments.
const keyword = factory.token("LET_KW");const name = factory.token("IDENT", "newName");const message = factory.token("JS_STRING_LITERAL", '"hello"');Kind sets
Section titled “Kind sets”Kind sets check whether a node or token has one of several kinds. Comparing kind strings, as in the following check, costs one string comparison per kind:
if (node.kind === "JS_CALL_EXPRESSION" || node.kind === "JS_NEW_EXPRESSION") { ... }A kind set checks for any number of kinds in constant time. Build each set once at module scope, then reuse it in every run() call:
import { ast, defineRule, nodeKinds, registerDiagnostic, tokenKinds } from "@biomejs/runtime/plugin"
const CALLS = nodeKinds("JS_CALL_EXPRESSION", "JS_NEW_EXPRESSION");const LOOSE_EQUALITY = tokenKinds("EQ2", "NEQ");
export const kindSets = defineRule({ query: ast("JS_EXPRESSION_STATEMENT"), run(statement, ctx) { const expression = statement.expression; if (!expression) return; if (CALLS.has(expression)) { registerDiagnostic(expression, "information", `${expression.kind} is in CALLS.`) } for (const element of expression.childrenWithTokens()) { if (LOOSE_EQUALITY.has(element)) { registerDiagnostic(expression, "warning", `${element.text} is in LOOSE_EQUALITY.`) } } }})nodeKinds
Section titled “nodeKinds”Type: <K extends keyof JsNodeByKind>(...kinds: K[]) => NodeKindSet<K>
Creates a set of node kinds. It accepts the same names as ast, such as "JS_CALL_EXPRESSION". Pass each kind as a separate argument, not as an array. nodeKinds() with no arguments returns an empty set, which matches nothing.
It throws a TypeError for an unknown name or a token kind. For a token kind, the message names the function to use instead:
nodeKinds() received the token kind "IDENT", but it only accepts node kinds. Create a set of token kinds with tokenKinds("IDENT") instead.tokenKinds
Section titled “tokenKinds”Type: <K extends JsAstToken["kind"]>(...kinds: K[]) => TokenKindSet<K>
Creates a set of token kinds. It accepts any name that token.kind can return, such as "IDENT" or "LET_KW". This includes "EOF", "ERROR_TOKEN", and trivia kinds such as "WHITESPACE" and "COMMENT".
Like nodeKinds, it throws a TypeError if a name is unknown or is a node kind.
NodeKindSet.has
Section titled “NodeKindSet.has”Type: (element: JsAstElement | undefined) => boolean
Returns whether element is a node whose kind is in the set. It returns false for tokens and for undefined, so you can pass optional fields and the results of childrenWithTokens() directly.
It throws a TypeError for anything that is not a node, a token, or undefined. That includes kind strings and null, so CALLS.has("JS_CALL_EXPRESSION") throws.
In TypeScript, a true result narrows element to the node types in the set. After CALLS.has(element), element is a JsCallExpression | JsNewExpression.
TokenKindSet.has
Section titled “TokenKindSet.has”Type: (element: JsAstElement | undefined) => boolean
Returns whether element is a token whose kind is in the set. It returns false for nodes and for undefined, and throws a TypeError for anything else.
In TypeScript, a true result narrows element to a token with one of the set’s kinds. After LOOSE_EQUALITY.has(element), element.kind is "EQ2" | "NEQ".
NodeKindSet.union
Section titled “NodeKindSet.union”Type: (other: NodeKindSet) => NodeKindSet
Returns a new set with the kinds of both sets. Neither set changes, so you can share a base set and extend it in several places:
import { nodeKinds } from "@biomejs/runtime/plugin"
const CALLS = nodeKinds("JS_CALL_EXPRESSION", "JS_NEW_EXPRESSION");const CALLS_AND_IMPORTS = CALLS.union(nodeKinds("JS_IMPORT_CALL_EXPRESSION"));other must be a set returned by nodeKinds(). Passing a token kind set throws a TypeError that says so:
set.union() received a token kind set, but this is a node kind set. Pass a set returned by nodeKinds() instead.It also throws for a kind name, an array, or anything else that is not a node kind set, and when you pass zero or more than one argument. To add a single kind, wrap it in a set first, as in CALLS.union(nodeKinds("JS_IMPORT_CALL_EXPRESSION")).
In TypeScript, the result’s type has the kinds of both sets, so has() on it narrows to any of them. After CALLS_AND_IMPORTS.has(element), element is a JsCallExpression | JsNewExpression | JsImportCallExpression.
TokenKindSet.union
Section titled “TokenKindSet.union”Type: (other: TokenKindSet) => TokenKindSet
Returns a new set with the kinds of both sets. Neither set changes.
import { tokenKinds } from "@biomejs/runtime/plugin"
const EQUALITY = tokenKinds("EQ2", "EQ3", "NEQ", "NEQ2");const COMPARISON = EQUALITY.union(tokenKinds("L_ANGLE", "R_ANGLE", "LTEQ", "GTEQ"));other must be a set returned by tokenKinds(). Like NodeKindSet.union, it throws a TypeError for a node kind set, a kind name, an array, or the wrong number of arguments.
NodeKindSet and TokenKindSet types
Section titled “NodeKindSet and TokenKindSet types”The two set types are separate. You cannot pass a node kind set where a token kind set is expected, or the other way around. That includes union: TypeScript rejects CALLS.union(LOOSE_EQUALITY), and it throws at runtime.
Each set’s type records exactly the kinds it was built with. nodeKinds("JS_CALL_EXPRESSION", "JS_NEW_EXPRESSION") has the type NodeKindSet<"JS_CALL_EXPRESSION" | "JS_NEW_EXPRESSION">, and you cannot assign it to a NodeKindSet with any other kinds, whether fewer, more, or a plain NodeKindSet. A helper that accepts any set must be generic over its kinds:
import type { AnyJsAstNode, JsNodeByKind, NodeKindSet } from "@biomejs/runtime/plugin"
function countMembers<K extends keyof JsNodeByKind>( set: NodeKindSet<K>, nodes: readonly AnyJsAstNode[],): number { return nodes.filter((node) => set.has(node)).length;}For token kind sets, use K extends JsAstToken["kind"] and TokenKindSet<K>.
Traversal APIs
Section titled “Traversal APIs”node.descendants() and node.walk() find nodes of the kinds in a node kind set anywhere inside a node. The search runs inside Biome, which creates JavaScript objects and calls your code only for matching nodes. This is much faster than walking the tree with children(), which turns every node into a JavaScript object.
For example, this recursive walk collects every call in a file:
import { ast, defineRule, registerDiagnostic } from "@biomejs/runtime/plugin"
function findCalls(node, calls) { for (const child of node.children()) { if (child.kind === "JS_CALL_EXPRESSION") { calls.push(child); } findCalls(child, calls); } return calls;}
export const calls = defineRule({ query: ast("JS_MODULE"), run(root) { for (const call of findCalls(root, [])) { registerDiagnostic(call, "information", "Found a call.") } }})With descendants(), the helper goes away:
import { ast, defineRule, nodeKinds, registerDiagnostic } from "@biomejs/runtime/plugin"
const CALLS = nodeKinds("JS_CALL_EXPRESSION");
export const calls = defineRule({ query: ast("JS_MODULE"), run(root) { for (const call of root.descendants(CALLS)) { registerDiagnostic(call, "information", "Found a call.") } }})Neither method includes or visits the node you call it on, even when its kind is in the set. There is no variant for tokens.
node.descendants
Section titled “node.descendants”Type: <K extends keyof JsNodeByKind>(kinds: NodeKindSet<K>) => readonly JsNodeByKind[K][]
Returns a new array with the nodes inside node whose kind is in kinds, in source order. Each call creates new node objects, so calling it twice returns different objects for the same nodes.
kinds must be a set returned by nodeKinds(). A kind string, an array, or a set from tokenKinds() throws a TypeError:
The kinds argument to node.descendants() is not a node kind set. Create one with nodeKinds(), such as nodeKinds("JS_CALL_EXPRESSION"), and pass it instead of a kind string or array.In TypeScript, the result has the node types in the set. root.descendants(nodeKinds("JS_CALL_EXPRESSION", "JS_NEW_EXPRESSION")) returns a readonly (JsCallExpression | JsNewExpression)[].
node.walk
Section titled “node.walk”Type: <K extends keyof JsNodeByKind>(kinds: NodeKindSet<K>, enter: (node: JsNodeByKind[K]) => unknown, exit?: (node: JsNodeByKind[K]) => void) => void
Visits the nodes inside node whose kind is in kinds, in source order. Biome calls enter(match) before it visits the nodes inside a match, and exit(match) after them. exit receives the same object that enter received, and you can omit it.
Use walk() instead of descendants() when you need to know how matches nest, for example to keep a stack of the enclosing functions or JSX elements. This rule reports each call along with the function it is in:
import { ast, defineRule, nodeKinds, registerDiagnostic } from "@biomejs/runtime/plugin"
const FUNCTIONS_AND_CALLS = nodeKinds("JS_FUNCTION_DECLARATION", "JS_FUNCTION_EXPRESSION", "JS_ARROW_FUNCTION_EXPRESSION", "JS_CALL_EXPRESSION");
export const enclosingFunctions = defineRule({ query: ast("JS_MODULE"), run(root) { const functions = []; root.walk( FUNCTIONS_AND_CALLS, (node) => { if (node.kind === "JS_CALL_EXPRESSION") { const enclosing = functions.at(-1) ?? "the module"; registerDiagnostic(node, "information", `${node.callee.text}() is called in ${enclosing}.`) } else if (node.id?.text === "skipped") { return false; } else { functions.push(node.id?.text ?? "an anonymous function"); } }, (node) => { if (node.kind !== "JS_CALL_EXPRESSION") { functions.pop(); } }, ); }})If enter returns exactly false, Biome skips the nodes inside that match and does not call exit for it. In the example above, calls inside a function named skipped are not reported. Any other return value, including undefined, null, and 0, continues the walk.
If enter or exit throws, the walk stops and the exception propagates to your code.
kinds follows the same rules as in descendants(). walk() also throws a TypeError if enter is not a function, or if exit is given and is not a function.
In TypeScript, enter and exit receive the node types in the set.
Trivia APIs
Section titled “Trivia APIs”Comments, whitespace, and line breaks are called trivia: text that does not affect how a program runs. In Biome, trivia is attached to individual tokens:
- A token’s leading trivia is everything between the previous token’s trailing trivia and the token.
- A token’s trailing trivia is everything after the token, up to but not including the next line break. Line breaks inside a block comment do not count, so a block comment that starts on the token’s line is trailing trivia even if it spans several lines.
This means a comment on its own line is leading trivia of the token that follows it, and a comment at the end of a line is trailing trivia of the token before it:
// Adds two numbers.export function add(a, b) { return a + b; // fast path}Here, // Adds two numbers. is leading trivia of the export keyword, and // fast path is trailing trivia of the ; after a + b.
token.text never includes trivia. node.text leaves out the trivia before the node’s first token and after its last token, but keeps the trivia between its tokens. To read the trivia around a node or a token, call leadingTrivia() or trailingTrivia(). To read only the comments around a token, call leadingComments() or trailingComments().
This rule reports every export statement that is not preceded by a JSDoc comment:
import { ast, defineRule, registerDiagnostic } from "@biomejs/runtime/plugin"
export const requireJsdoc = defineRule({ query: ast("JS_EXPORT"), run(node) { const exportToken = node.token("exportToken"); const hasJsdoc = exportToken .leadingComments() .some((comment) => comment.text.startsWith("/**")); if (!hasJsdoc) { registerDiagnostic(exportToken, "warning", "Document this export with a JSDoc comment.") } }})Each call returns a new array, and each piece is a new object, so calling a method twice returns different objects for the same trivia.
node.leadingTrivia
Section titled “node.leadingTrivia”Type: () => readonly TriviaPiece[]
Returns a new array with the leading trivia of the first token of node, in source order. A node without tokens, such as an empty list, returns an empty array.
node.trailingTrivia
Section titled “node.trailingTrivia”Type: () => readonly TriviaPiece[]
Returns a new array with the trailing trivia of the last token of node, in source order. A node without tokens returns an empty array.
token.leadingTrivia
Section titled “token.leadingTrivia”Type: () => readonly TriviaPiece[]
Returns a new array with the trivia before token, in source order. Use it on tokens returned by node.token(field) or node.childrenWithTokens(). Tokens created with factory.token() have no trivia.
token.trailingTrivia
Section titled “token.trailingTrivia”Type: () => readonly TriviaPiece[]
Returns a new array with the trivia after token, up to but not including the next line break outside a comment, in source order.
token.leadingComments
Section titled “token.leadingComments”Type: () => readonly TriviaPiece[]
Returns a new array with the comments in the leading trivia of token, in source order. It returns the same pieces as leadingTrivia(), without the whitespace and line breaks. Tokens created with factory.token() return an empty array.
This rule reports TODO comments right before the var, let, or const keyword of a variable statement:
import { ast, defineRule, registerDiagnostic } from "@biomejs/runtime/plugin"
export const noTodo = defineRule({ query: ast("JS_VARIABLE_STATEMENT"), run(statement) { const keyword = statement.declaration.token("kindToken"); for (const comment of keyword.leadingComments()) { if (comment.text.includes("TODO")) { registerDiagnostic(comment, "warning", "Resolve this TODO.") } } }})On this input, the rule reports only // TODO: rename:
function f() { // TODO: rename const x = 1; // TODO: not leading}The second comment is trailing trivia of the ;, so it is not in the leading comments of const.
Nodes do not have leadingComments() or trailingComments(). To find the comments before or after a node, call them on one of its tokens, such as one returned by node.token(field).
token.trailingComments
Section titled “token.trailingComments”Type: () => readonly TriviaPiece[]
Returns a new array with the comments in the trailing trivia of token, in source order. Tokens created with factory.token() return an empty array.
TriviaPiece
Section titled “TriviaPiece”A piece of trivia has three read-only properties and one method:
kind: aTriviaKind, which is one of"newline","whitespace","singleLineComment", or"multiLineComment".text: the source text of the piece. Comments include their delimiters, such as//.token: theJsAstTokenwhose leading or trailing trivia contains the piece.isComment(): returnstrueifkindis"singleLineComment"or"multiLineComment", andfalseotherwise. In TypeScript, it narrowskindto those two kinds.
Comments are classified by whether they contain a line break, not by their syntax. A // comment and a block comment that fits on one line are both "singleLineComment", and only a block comment that spans several lines is a "multiLineComment".
In files with syntax errors, the text that the parser skipped is not included in the trivia.
Report diagnostics on tokens and trivia
Section titled “Report diagnostics on tokens and trivia”registerDiagnostic also accepts a token or a trivia piece in place of a node. Biome then highlights only that token or piece, instead of the whole node. This rule highlights TODO comments after the semicolon of a variable statement, instead of the whole statement:
import { ast, defineRule, registerDiagnostic } from "@biomejs/runtime/plugin"
export const noTrailingTodo = defineRule({ query: ast("JS_VARIABLE_STATEMENT"), run(statement) { const semicolon = statement.token("semicolonToken"); for (const comment of semicolon?.trailingComments() ?? []) { if (comment.text.includes("TODO")) { registerDiagnostic(comment, "warning", "Resolve this TODO.") } } }})The token or piece must come from the file being analyzed. Passing a token created with factory.token(), or a token or piece read from a node returned by a withX() method, throws a TypeError.
© 2023-present Biome developers and contributors.