npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

svelte-ast

v0.17.0

Published

svelte/compiler's AST, 2.4× faster, with zero dependencies.

Readme

svelte-ast

svelte/compiler's AST, 2.4× faster, with zero dependencies.

| | svelte-ast | svelte/compiler | |:---|:---|:---| | Parse 400 components, 1.5 MB | 64.7 ms | 155 ms | | Import in a fresh process | 5.3 ms | 44.7 ms | | parse for the browser, gzipped | 58.5 kB | 126.7 kB | | Memory retained by ten parses kept alive | 147 MB | 294 MB |

Apple M2; see Parity and performance for how they're measured.

bun i svelte-ast
import { parse } from "svelte-ast";

const ast = parse(`<script>let name = "world";</script>\n<h1>Hello {name}!</h1>`);

ast.instance?.content.body; // [VariableDeclaration]
ast.fragment.nodes; // [Text, RegularElement]

Parse .svelte components, including <script lang="ts">, into the same AST, and the same errors, as svelte/compiler's parse(source, { modern: true }). svelte-ast has no dependencies and uses no Node APIs, so it runs in the browser as well as in Node, Bun and Deno.

It's for tools that analyze components statically, such as documentation and type generators that read a component's props, events and slots. They need only the AST, but parse every component in a library, often on every change. sveld, which generates TypeScript definitions and documentation for Svelte components, uses it.

| Function | For | Import from | |:---|:---|:---| | parse | A component's AST, the same as svelte's | svelte-ast | | parseSections | A component's AST without the markup: its <script>s, <style> and <svelte:options> | svelte-ast | | parseModule | A .js or .ts module's AST, the same as a component's <script> | svelte-ast | | parseImportsExports | A module's import and export statements, without parsing the rest | svelte-ast | | parseExports | A module's exports, each a value or only a type, as TypeScript's checker lists them, without reading other files | svelte-ast | | followExports | A module's full export table, its re-exports followed across files with your read and resolve | svelte-ast | | lexImportsExports | Their offsets, sources and names, without loading a parser | svelte-ast/lexer | | lexDynamicImports | A module's import(…), require(…) and import.meta.glob(…), with their offsets and sources, without loading a parser | svelte-ast/lexer | | lexComponent | A component's <script>s, <style> and <svelte:options>, with their attributes and offsets, without loading a parser | svelte-ast/lexer | | lexStrings | A module's string and template literals, with their offsets and values, without loading a parser | svelte-ast/lexer | | createParser, createSectionsParser, createModuleParser | The parsers without TypeScript, named HTML entities or the template parser, for a smaller bundle | svelte-ast/core, svelte-ast/module | | isValidType | Whether a JSDoc type is safe to copy into a .d.ts | svelte-ast | | isRunesMode | Whether svelte compiles a component in runes mode, mostly without parsing it | svelte-ast | | walk, visitorKeys, markupVisitorKeys, valueVisitorKeys, skipTypeWrappers | Visit, skip, stop at or replace nodes, in the whole AST, only the markup, or everything but TypeScript's types | svelte-ast, svelte-ast/walk | | children, forEachChild | A node's children, cached or without allocating | svelte-ast, svelte-ast/walk | | isReference, extractIdentifiers | Which identifiers are references, and which ones a pattern declares | svelte-ast, svelte-ast/walk | | analyzeScopes | Which declaration each name refers to, and every read and write of it | svelte-ast, svelte-ast/scope | | a11yWarnings | svelte's accessibility warnings, without compiling | svelte-ast/a11y | | compilerWarnings | svelte's other warnings, without compiling: unused CSS selectors, empty blocks, attribute and naming mistakes, bidirectional text, nested classes, state read outside a closure, unused props, and runes-mode deprecations | svelte-ast/warnings | | createLocator, locate | Lines and columns for the nodes you report, without parsing with loc | svelte-ast, svelte-ast/walk |

Migrating from svelte/compiler

svelte-ast is a drop-in for parse in most tools: change the import, and pass loc: true if you read line and column numbers.

- import { type AST, parse } from "svelte/compiler";
+ import { type AST, parse } from "svelte-ast";

- const ast = parse(source, { modern: true });
+ const ast = parse(source, { loc: true });

| | svelte/compiler | svelte-ast | |:---|:---|:---| | loc, name_loc | Always | With loc: true; otherwise only start/end offsets, for a faster parse and a smaller AST | | Errors | CompileError | ParseError: same code, message, position, start, end and frame; no filename; reason, the message without its link | | AST formats | Modern, legacy (modern: false), error-tolerant (loose) | Modern | | Non-ASCII identifiers | Its own Unicode 17 tables | The JavaScript engine's Unicode data, which is smaller to ship: the same in Node 24 and Bun; an engine on another Unicode version differs on the letters added in between | | TypeScript-only errors | Reported, e.g. modifier order or initializers in ambient contexts | Not reported: code that only TypeScript's own checks reject still parses | | Invalid regular expressions | Reported as js_parse_error, e.g. /a/gg or /(/ | Not reported: the literal parses, which keeps acorn's regular expression validator out of the bundle |

Examples

List the components a file renders, e.g. to build a dependency graph:

import { parse, walk } from "svelte-ast";

function componentsUsed(source: string): string[] {
  const names = new Set<string>();
  walk(parse(source, { css: false }).fragment, {
    enter(node) {
      if (node.type === "Component") names.add(node.name);
    },
  });
  return [...names]; // ["Button", "Modal.Root"]
}

Report syntax errors, e.g. in a pre-commit check, with svelte's own messages:

import { ParseError, parse } from "svelte-ast";

try {
  parse(source, { css: false });
} catch (error) {
  if (!(error instanceof ParseError)) throw error;
  console.error(`${file}:${error.start?.line}:${error.start?.column} ${error.code}\n${error.frame}`);
}

examples/ has runnable versions of these and more, each a CLI you can point at your own components: a module graph, unused imports and variables, unused CSS classes, runes-or-legacy detection, $props() and their defaults, .d.ts props from JSDoc, and styles without parsing them.

Parity and performance

  • svelte/compiler parity. Tested on over 12,000 components: carbon-components-svelte, svelte's own test suite, bits-ui, shadcn-svelte, skeleton, flowbite-svelte, svelte.dev, immich, SvelteKit, melt-ui, layerchart and paneforge. Every one either parses to svelte's AST, loc included, or throws svelte's error with the same code, message, position and frame. A differential fuzzer compares the two parsers on mutated components.
  • TypeScript. <script lang="ts"> and .ts modules parse to svelte's AST, key order and loc included, on 6,604 real-world modules and on all but 2 of the 9,586 TypeScript conformance tests svelte parses.

Apple M2, medians of warm calls. The corpus is tests/corpus: all of carbon-components-svelte plus svelte's and sveld's test inputs.

| Input | svelte-ast | svelte-ast, loc: true | svelte/compiler | |:---|:---|:---|:---| | Corpus, 400 components, 1.5 MB | 64.7 ms | 84.0 ms | 155 ms (2.4×) | | Carbon's 5 largest components, 318 kB | 13.8 ms | | 31.3 ms (2.3×) | | lang="ts" components, 22 files | 0.79 ms | | 2.40 ms (3.0×) |

| parse alone, minified for the browser | Gzipped | |:---|:---| | svelte/compiler | 126.7 kB | | svelte-ast | 58.5 kB | | svelte-ast/core's createParser(), without TypeScript and named HTML entities | 41.0 kB |

In a fresh process, importing the parser takes 5.3 ms with svelte-ast and 44.7 ms with svelte/compiler, and a first parse of the whole corpus takes 65 ms against 161 ms. Keeping ten parses of the corpus alive retains 147 MB with svelte-ast, 260 MB with loc: true, and 294 MB with svelte/compiler.

API

parse(source, options?) => AST.Root

| Option | Default | Description | |:---|:---|:---| | loc | false | Add loc (line and column) to script and expression nodes, and name_loc to elements, attributes and directives, as svelte does. They cost time and memory, and most tools only need start/end. | | css | true | Parse <style> into rules and selectors. With false, css keeps its start, end and content, but children and comments are empty and CSS syntax errors aren't reported. It also keeps <style lang="scss"> from failing to parse as CSS. | | script | true | Parse each <script>. With false, instance and module keep their attributes, start and end, and content is a Program with an empty body; their comments aren't collected and their syntax errors aren't reported. Expressions in the markup are still parsed. For a pass that only reads the markup; 3.4× faster on the benchmark corpus. | | comments | true | Collect JavaScript comments, in scripts, expressions and tags. With false, comments is empty and no node has leadingComments or trailingComments, including the HTML comment before a <script> that svelte copies into its content.leadingComments. HTML and CSS comments are kept. 3 to 6% faster, and 8% less memory. |

With loc: true, the result equals svelte's. With the defaults, it's svelte's without loc and name_loc.

A syntax error throws a ParseError with svelte's code (e.g. "block_unclosed"), message, position ([start, end] offsets), start/end ({ line, column, character }) and frame (the source around the error). message is always the reason, a line break, then the link to the error's docs, https://svelte.dev/e/${code}; reason is the reason on its own, e.g. "Unexpected token".

parseSections(source, options?) => AST.Root

parse for a pass that only reads a component's scripts, such as its props or its module script's exports: the top-level <script>s, <style> and <svelte:options> are parsed as parse parses them, and the markup between them is skipped as lexComponent skips it. fragment.nodes is empty, comments has only the scripts' comments, and the markup's syntax errors aren't reported; the rest is parse's, offsets and the HTML comment before a <script> included. It takes parse's options, and on the benchmark corpus it's 1.5× faster, where most of what's left is the scripts. It's a function of its own so that a bundle with only parse doesn't carry the lexer; createParser doesn't return it, and createSectionsParser does, without the parts you leave out.

import { parseSections } from "svelte-ast";

const { instance, module } = parseSections(source, { css: false });
module?.content.body; // the module script's statements, with parse's offsets

parseModule(source, options?) => Program

Parses a JavaScript or TypeScript module, such as a .ts file a component imports, into the same AST a component's <script> gets, with comments attached as leadingComments/trailingComments. The Program's comments is always an array, empty with comments: false. It lists every comment once, in source order, with the shape a component's root.comments has: { type: "Line" | "Block", value, start, end }, and loc with loc: true.

| Option | Default | Description | |:---|:---|:---| | typescript | false | Parse TypeScript. | | dts | false | Parse a declaration file, a .d.ts: the top level is ambient, as inside declare module "a" { … }, so export const a: number; needs no initializer and a function or method no body. Offsets are into the source as given. Implies typescript. | | loc | false | Add loc (line and column) to every node and comment. | | comments | true | Collect and attach comments. With false, comments is empty and no node has leadingComments or trailingComments. |

import { parseModule } from "svelte-ast";

const program = parseModule("/** The size. */\nexport const size: number;\n", { dts: true });
program.body[0]; // ExportNamedDeclaration, start 17, end 43
program.comments; // [{ type: "Block", value: "* The size. ", start: 0, end: 16 }]

parseImportsExports(source, options?) => ModuleDeclaration[]

A module's top-level import and export statements, without parsing the rest, e.g. to rewrite a component's imports or follow a module graph. Each node is the one parseModule(source, { comments: false }) has for that statement: ImportDeclaration, ExportNamedDeclaration, ExportDefaultDeclaration and ExportAllDeclaration, and, in TypeScript, TSImportEqualsDeclaration, TSExportAssignment and TSNamespaceExportDeclaration. import(...) and import.meta are expressions, so they aren't returned; lexDynamicImports finds them. Unlike a regex, it never matches an import in a comment, a string, a template or a nested block such as declare module "a" { ... }.

It stops after the last import or export that could start a statement, so the code after a component's imports is never read: on Carbon's component scripts, it takes a third of parseModule's time, and about a seventh with localExports: false. A syntax error in a statement it returns throws a ParseError, including a name exported twice; errors elsewhere aren't reported.

| Option | Default | Description | |:---|:---|:---| | typescript | false | Parse TypeScript: import type, export type, import a = require("a"). | | localExports | true | Return the exports of the module's own bindings, such as export let a, export function b() {}, export { c } and export default d, parsed in full. With false, only imports and the exports that have a from (export * from "e", export { f } from "f", export import) are returned. |

import { parseImportsExports } from "svelte-ast";

function dependencies(source: string, typescript = false): string[] {
  return parseImportsExports(source, { typescript, localExports: false }).flatMap(
    (node) => ("source" in node && node.source ? [node.source.value] : []),
  );
}

parseExports(source, options?) => ModuleExports

A module's export table, read from its source alone: the names its own declarations export, each a value or only a type, the names it exports from other modules, and its export * sources, for a check that a hand-written .d.ts declares what the .js beside it exports. It doesn't resolve a specifier or read that module; followExports does, with your own read and resolve. A syntax error throws a ParseError.

| Option | Default | Description | |:---|:---|:---| | typescript | false | Parse TypeScript. | | dts | false | Read a .d.ts, parsed as parseModule's dts parses it, with TypeScript's rules for what it exports. Implies typescript. |

import { parseExports } from "svelte-ast";

const { locals } = parseExports(
  'import type { Size } from "./size";\n' +
    "interface Props { size: Size }\n" +
    "export const button: (props: Props) => void;\n",
  { dts: true },
);
locals; // [{ name: "Props", kind: "type" }, { name: "button", kind: "value" }]

const { reExports, stars } = parseExports(
  'export { type Theme, themes } from "./theme.js";\nexport * from "./tokens.js";\n',
  { typescript: true },
);
reExports;
// [{ name: "Theme", source: "./theme.js", imported: "Theme", typeOnly: true },
//  { name: "themes", source: "./theme.js", imported: "themes", typeOnly: false }]
stars; // [{ source: "./tokens.js", typeOnly: false }]

locals and reExports are in source order, and a name is in only one of them, once. A re-export is export { a } from "b", export * as a from "b", or an imported binding exported again, as in import { a } from "b"; export { a }; imported is "default" for a default import and "*" for a namespace. Its kind is the one source gives it, unless typeOnly. export * is in stars, as { source, typeOnly }.

It follows TypeScript's checker: on carbon-components-svelte's 233 .d.ts files and the .js beside each, the two agree on all 1,830 names and their kinds.

  • Values are variables, functions, classes and enums, declare and const enum included, and a namespace that holds anything but interfaces, type aliases, imports, and namespaces and export { … } lists of those.
  • Types are interfaces, type aliases, the namespaces that hold only those, and anything exported with export type, import type, or type before its name. Merged declarations are one name, a value if any of them is.
  • In a .d.ts, every top-level declaration is exported, with or without export, unless the file has an export { … }, an export *, an export =, or an export default of an expression. Imports aren't exported, and neither are declare module "a" and declare global.
  • A file without an import or an export is a script, and exports nothing, as with TypeScript's default moduleDetection.
  • In JavaScript, a @typedef or @callback in a /** … */ comment before a top-level statement, or at the end of the file, is a type. A comment on the line where the statement before it ends belongs to that statement, and one inside a statement declares nothing.
  • export default is the name "default", and export = a is "export=", TypeScript's name for it: a local declaration's kind, a re-export if a is imported, and a value for any other expression. TypeScript lists the members of a as the module's exports instead; parseExports doesn't read them.

CommonJS's module.exports isn't read.

followExports(file, options) => FollowExportsResult

A module's full export table, its re-exports followed across files: parseExports on each module it reaches, read and resolved with the functions you pass, so a tool keeps its own lookup, such as a .d.ts in place of the .js beside it, or a package's exports map.

| Option | Default | Description | |:---|:---|:---| | read | required | (file) => string \| undefined: a file's source, or undefined when it can't be read. | | resolve | required | (specifier, fromFile) => string \| undefined: the file a specifier names, or undefined for one not to follow. | | typescript | by extension | Parse every file as TypeScript, or none. By default, .ts, .tsx, .mts and .cts files are TypeScript. | | dts | by extension | Read every file as a declaration file, or none. By default, .d.ts, .d.mts and .d.cts files are. | | cache | a new Map | Each file's parseExports result, filled as files are read. Pass one Map to calls with the same read, typescript and dts to parse each file once. |

import { existsSync, readFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { followExports } from "svelte-ast";

// src/index.js:  export * from "./button.js"; export * as icons from "icons";
// src/button.js: export const Button = {}; export default Button;
const { exports, missing } = followExports("src/index.js", {
  read: (file) => (existsSync(file) ? readFileSync(file, "utf8") : undefined),
  resolve: (specifier, fromFile) =>
    specifier.startsWith(".") ? join(dirname(fromFile), specifier) : undefined,
});
exports;
// [{ name: "icons", kind: "value", file: undefined },
//  { name: "Button", kind: "value", file: "src/button.js" }]
missing; // [{ file: "src/index.js", source: "icons" }]

The result has exports, ambiguous and missing. Each entry in exports has its name, its kind, and the file that declares it. The module's own names come first, in parseExports' order, then those from each export *, in the order of the statements. It follows how JavaScript links modules, and TypeScript's checker:

  • A module's own names win over the same name from its export *.
  • export * never re-exports default, or export =.
  • A name two export * give from different declarations is ambiguous: it's left out of exports, since JavaScript leaves it out of the module's namespace and an import of it fails to link. It's in ambiguous instead, as { name, files }, with the files that declare it in the order met, so you can report what TypeScript reports as error 2308; TypeScript keeps the first. One declaration reached twice isn't ambiguous, and a module's own name settles it.
  • export * as ns from "a" is one value, ns, and its file is the one "a" resolves to, which isn't read.
  • A type-only re-export or export type * on the way to a name makes it a type; a name also reached without one is a value.
  • A source resolve or read can't give is in missing, as { file, source }. A name re-exported from it is a value with file: undefined, as TypeScript's checker gives it, and an export * from it adds nothing. A name re-exported from a module that doesn't export it, or from a cycle of re-exports, is a value with file: undefined too.
  • A cycle ends: a module met again in its own walk adds nothing.

On carbon-components-svelte's 233 .d.ts files and the .js beside each, with each .d.ts resolved in place of its .js, it lists the same 1,830 names and kinds as TypeScript's checker. A syntax error throws an Error that names the file, with the ParseError as its cause; so does a file that read can't read, without one.

lexImportsExports(source, options?) => LexedStatement[]

From svelte-ast/lexer, and also svelte-ast. A module's top-level import statements and export … from re-exports, read by hand instead of parsed, for a tool on a hot or eagerly loaded path, such as a preprocessor that rewrites a component's imports, that needs each statement's offsets, source and names, but not the AST. svelte-ast/lexer loads no parser, so a fresh process imports it in 1.4 ms, and on Carbon's component scripts it takes 40% of the time parseImportsExports takes with localExports: false.

It finds the statements parseImportsExports returns with localExports: false, with the same offsets, sources and names. It doesn't check syntax and never throws: a statement it can't read, such as import { a from "a" or import a = require("a"), has source: null and no specifiers, and ends where it stopped reading. import type and type before a name are always read.

With exportLists: true, it also returns each top-level export { a, b as c } without from, e.g. to follow a binding through an index.js that imports it and exports it again: source is null, and each specifier has kind local, with local the binding in this module. Those are the ExportNamedDeclarations without a declaration that parseImportsExports returns with localExports: true; export const a, export function b and export default still aren't returned. A module that ends with an export list is read to its end.

import { lexImportsExports } from "svelte-ast/lexer";

for (const statement of lexImportsExports(source)) {
  statement.kind; // "import" | "export"
  statement.start; // offset of `import` or `export`
  statement.end; // after the `;`, or the last token without one
  statement.source; // { value: "carbon-components-svelte", start, end } (quotes included), or null
  statement.typeOnly; // `import type …` or `export type …`
  statement.specifiers;
  // import: { kind: "default" | "namespace" | "named", imported, local, typeOnly, start, end }
  // export: { kind: "all" | "namespace" | "named" | "local", local, exported, typeOnly, start, end }
}

| Specifier | import | export … from | |:---|:---|:---| | a in import a | default, imported: "default", local: "a" | | | * as a | namespace, imported: "*", local: "a" | namespace, local: "*", exported: "a" | | * | | all, local: "*", exported: null | | b as c, "b-c" as d | named, imported: "b", local: "c" | named, local: "b", exported: "c" | | b as c in export { … }, with exportLists | | local, local: "b", exported: "c" |

Names are as the module sees them: escapes decoded, and a string name without its quotes. A specifier's typeOnly is also true in an import type or export type. Its start is that of type before the name, if any, and end is after the last name; for export *, after the *.

lexDynamicImports(source) => LexedDynamicImport[]

From svelte-ast/lexer, and also svelte-ast. A module's import(…) and require(…) calls and Vite's import.meta.glob(…), at any depth, in source order, read without parsing, e.g. to follow the lazily loaded part of a module graph. Unlike a regular expression, it never matches in a comment, a string, a template or a regular expression, and it tells a literal argument from a computed one. lexImportsExports finds the static imports; together they're a module's dependencies.

import { lexDynamicImports } from "svelte-ast/lexer";

for (const call of lexDynamicImports(source)) {
  call.kind; // "import" | "require" | "glob"
  call.start; // offset of `import` or `require`
  call.end; // after the `)`
  call.source; // { value: "./Chart.svelte", start, end } (quotes or backticks included), or null
}

source is the first argument if it's a string or a template without ${…} and it's followed by ) or ,, as in import("a", { with: { type: "json" } }); it's null for a computed argument such as import(`./${name}.js`) or import.meta.glob(["a", "b"]), and for a call without arguments. Type arguments are skipped, as in import.meta.glob<Module>("./*.ts").

Where parseModule accepts the module, the calls are its ImportExpressions, its calls of an identifier require, new require(…) included, and of import.meta.glob, and in TypeScript also its import("a") types, as in typeof import("a"), and the require("a") of import a = require("a"). A method named import or require, such as { import() {} }, isn't a call, and neither are a.require(…), require?.(…) or (require)(…). It doesn't check syntax and never throws. It matched parseModule on all 33,001 modules and component scripts it accepts from the projects under Parity and performance, svelte's tests and TypeScript's conformance tests.

lexComponent(source) => LexedComponent

From svelte-ast/lexer, and also svelte-ast. A component's top-level <script>, <script module>, <style> and <svelte:options>, with their attributes and the offsets of their tags and content, found without parsing: e.g. to read a component's scripts and their imports, its language or its options, or to rewrite a script, on a path that can't afford a parser. On the benchmark corpus it's about 50× faster than parse.

It skips the markup by tracking only tags, attribute values, blocks, and the brackets, strings, comments and templates of each {…} expression, so a <script> in <svelte:head>, a block, an attribute, an expression or an HTML comment isn't one, and it stops after the last <script, <style or <svelte:options. Where parse accepts the component, the sections are its instance, module, css and options, with the same offsets, into the source without a leading byte order mark. It doesn't check syntax and never throws.

import { lexComponent } from "svelte-ast/lexer";

const { typescript, instance, module, css, options } = lexComponent(source);
typescript; // whether `parse` reads it as TypeScript, decided by the first <script> with a lang
instance?.content; // { start, end }: source.slice(start, end) is the script
instance?.attributes; // [{ name: "lang", value: "ts", start, end }]
module?.context; // "module"
options?.attributes; // [{ name: "runes", value: "{true}", start, end }]

An attribute's value is as written, without its quotes: character references aren't decoded, an expression keeps its braces, and an attribute without a value has true.

typescript is what createParser needs to know to load the TypeScript parser only for the components that use it:

import { createParser } from "svelte-ast/core";
import { lexComponent } from "svelte-ast/lexer";

let parser = createParser();
let loaded = false;

async function parseComponent(source: string) {
  if (!loaded && lexComponent(source).typescript) {
    const { typescript } = await import("svelte-ast/typescript");
    parser = createParser({ typescript });
    loaded = true;
  }
  return parser.parse(source);
}

lexStrings(source) => LexedString[]

From svelte-ast/lexer, and also svelte-ast. A module's string literals and the text of its template literals, in source order, read without parsing, for a tool that only needs a script's strings, such as one that collects the class names a component's script can produce. With parse(source, { script: false }) for the markup, it reads a component's scripts in a fraction of the time: on Carbon's 258 components, parse with comments: false takes 19.5 ms, and script: false plus lexStrings on each script 9.6 ms, of which lexStrings is 1.55 ms, 15% of what parseModule takes on the same scripts.

Where parseModule accepts the module, the strings are its Literals with a string value and its TemplateElements, types, imports and directives included, with the same offsets and values. Comments and regular expressions are skipped, and it never throws. It tells a regular expression from a division by the token before it, as acorn's tokenizer does, but acorn's parser can overrule that guess and lexStrings can't: a statement that starts with a regular expression after a line break without a ;, following let a, an import, a type alias ending in }, or a block after case …: or a label, reads as a division, as does / after a variable named of, and a quote in that regular expression starts a string. It matched parseModule on all 21,443 modules and component scripts it accepts from the projects under Parity and performance, and on all 9,647 of TypeScript's conformance tests that parseModule accepts.

import { lexStrings } from "svelte-ast/lexer";

for (const string of lexStrings(source)) {
  string.kind; // "string", a Literal: start and end include the quotes
  // "template", a TemplateElement: the text between the backtick, `${` or `}` around it
  string.value; // escapes decoded, as Literal's value or TemplateElement's value.cooked
}

value is null for an escape acorn rejects in a module, such as "\1", or one that leaves a tagged template's cooked null. A template's line breaks read as \n in value; its raw text is source.slice(start, end), with \r\n and \r as \n.

Smaller bundles: svelte-ast/core and svelte-ast/module

createParser(support?) from svelte-ast/core returns parse, parseModule and parseImportsExports without the TypeScript parser and the table of HTML's named character references, which most tools can do without. createSectionsParser(support?), from the same entry, returns parseSections the same way; it's separate so that a bundle with only createParser doesn't carry the lexer. createModuleParser(support?) from svelte-ast/module returns parseModule and parseImportsExports without the template parser either, for tools that read .js and .ts files but never components, such as a bundler plugin following a module graph. Pass back the parts you need; with them, the parsers are the same as svelte-ast's.

import { createParser, createSectionsParser } from "svelte-ast/core";
import { typescript } from "svelte-ast/typescript";

const { parse, parseModule, parseImportsExports } = createParser({ typescript });
const { parseSections } = createSectionsParser({ typescript });

| Support | Without it | |:---|:---| | typescript from svelte-ast/typescript | A component with <script lang="ts">, or typescript: true, throws an Error, not a ParseError: a missing import, not a syntax error, and never a JavaScript AST of TypeScript | | entities from svelte-ast/entities (createParser and createSectionsParser only) | Numeric references, such as &#169;, and &amp;, &apos;, &gt;, &lt; and &quot; are decoded, but other names, such as &copy;, are left as written, so Text.data differs from svelte's where the source uses them |

Both also export ParseError, the same class as svelte-ast's, and the node types.

isValidType(text, options?) => boolean

Whether text is exactly one TypeScript type, such as a JSDoc {"sm" | "lg"} a tool is about to copy into a .d.ts. The text is parsed as a type on its own, not wrapped in a statement, so a ;, a line break or a } in it can't end the type and smuggle in a statement: string; let x = 1 and { a: string } } are false. Whitespace and comments around the type are allowed. Results aren't cached.

A // comment runs to the end of the line, so string // the size is a valid type but breaks CustomEvent<${text}>. Pass inline: true when the text goes before more code on the same line: it's then also false unless every // comment in it ends with a line break.

isRunesMode(source) => boolean

Whether svelte compiles the component in runes mode, as compile(source).metadata.runes says: by <svelte:options runes> if it has one, otherwise by whether it uses a rune, such as $state or $props, or await outside a function in its instance script or markup. A $state that subscribes to a store named state, or that a function declares, isn't a rune, as in svelte. E.g. to track a migration to Svelte 5, or to pick the rules a linter applies.

Most components are decided without parsing: <svelte:options> is read with lexComponent, a component without a rune's name or await isn't in runes mode, and one whose scripts call a rune in a way that can't be a declaration, a method, a type or a store is. The rest is parsed, without the markup unless a rune's name or await is in it, and a syntax error there throws a ParseError. On 12,808 components from other Svelte projects, it takes a twelfth of the time parsing them does.

walk(node, visitor, keys?) => void

Visits node and every node under it, depth-first and in source order, calling visitor.enter(node, parent, key, index) before a node's children and visitor.leave(node, parent, key, index) after them. parent[key] is the node, or parent[key][index] when the field is an array; all three are null for the node you pass. Checking node.type narrows node.

What enter and leave return controls the walk:

  • SKIP from enter skips the node's children. leave is still called, so a stack you push in enter and pop in leave stays balanced.
  • STOP from enter or leave ends the walk there, without leave on the node's ancestors, e.g. to find the first use of a rune.
  • A node from enter replaces this one: walk writes it to parent[key] (or parent[key][index]), then enters it and visits its children instead, and leave gets the replacement. return node.expression on each TSAsExpression strips a as B as C down to a. The node you pass to walk can't be replaced.
  • Anything else, false included, is ignored, so enter: (node) => node.type === "Component" && names.add(node.name) still visits every node.

It works on any node the parsers return: a Root, a Fragment, an expression, a Program, a <style>'s rules. It never descends into loc, comments or strings, and throws on a node type it doesn't know. A component's sections are visited in scope order, module, instance, fragment, then css, and a template literal's quasis before its expressions. <svelte:options>'s attributes aren't visited; read them from ast.options?.attributes. In import { a } and export { a }, one Identifier is both names, so it's visited twice.

visitorKeys is the table walk reads: the fields of each node type that hold child nodes, in source order, e.g. visitorKeys.IfBlock is ["test", "consequent", "alternate"]. Pass another table as keys to visit other fields; a node whose type it has no entry for throws. markupVisitorKeys visits only the markup: Root's fragment, elements' attributes and fragments, attribute values and blocks' fragments, but no script, style or expression. For a query about the markup, such as the components a file renders or the classes it uses, it's 4.8× faster on the benchmark corpus than walking everything:

import { markupVisitorKeys, walk } from "svelte-ast";

walk(
  ast,
  {
    enter(node) {
      if (node.type === "Component") names.add(node.name);
    },
  },
  markupVisitorKeys,
);

valueVisitorKeys leaves out TypeScript's types: no type annotation, type parameter or type argument, no implements, and no type in as or satisfies. It reaches every value and binding, so an Identifier it reaches is never a type's name, and a tool that rewrites values can't fold size in type S = typeof size or let a: typeof size. It still enters a declaration that holds only types, such as type, interface or an index signature, but not its children, and of declare function f(): void it visits only the name. The TypeScript nodes whose children it visits hold values: as, satisfies, <T>a, a! and a<T> their expression, an enum its members, a namespace its body, import a = b and export = their value, and a parameter property its parameter. Walking with it takes about as long as walking everything.

skipTypeWrappers(node) gives the value inside those wrappers: a for a as T, a satisfies T, <T>a, a!, a<T> and any nesting of them, and node itself for anything else, for code that reads values, such as an evaluator deciding whether size as Size is a constant.

svelte-ast/walk exports walk, SKIP, STOP, visitorKeys, markupVisitorKeys, valueVisitorKeys, skipTypeWrappers, children, forEachChild, isReference, extractIdentifiers, createLocator, locate and the types without loading a parser, for code that walks ASTs from elsewhere, such as a cache.

children() and forEachChild()

The child nodes walk would visit next, in source order, for a traversal of your own, such as one that evaluates expressions and decides per node what to visit. forEachChild(node, (child, key, index) => ...) calls back with each child, the field that holds it, and its index when the field is an array, and allocates nothing. children(node) returns an array that it makes on the first call for each node and returns again after, so a tool that walks the same tree many times lists each node's children once. ASTs don't change after parse, so the cache stays right unless you change one, for instance by replacing a node with walk; don't change the array. Both take keys as walk does and throw on a node type it has no entry for.

import { forEachChild, valueVisitorKeys } from "svelte-ast/walk";

function visit(node) {
  if (node.type === "ConditionalExpression") return evaluateBranches(node);
  forEachChild(node, visit, valueVisitorKeys);
}

isReference(node, parent) => boolean

Whether node is an Identifier that names a variable, function, class, import or other binding, where it's declared or where it's used, given the parent walk passes. It's the check svelte's analyzer makes, from is-reference: false for a property or method name (b in a.b, { b: a } and class { b() {} }, unless computed), the renamed side of an import or export (b in import { b as a } and export { a as b }), and labels. Unlike is-reference, it's also false for import.meta and new.target, an import attribute's key, and b in export * as b from.

In TypeScript, a name in a type isn't a reference (B in let a: B, interface and type alias names), but a value is: the expression of as, satisfies, <T>a, a!, a<T> and export =, an enum's name and member initializers, a parameter property (a in constructor(private a)), and both sides of import a = b. Names of namespaces and of functions without a body (overloads, declare function) aren't references.

import { isReference, parseModule, walk } from "svelte-ast";

const used = new Set<string>();
walk(parseModule("const a = b.c({ d: e });"), {
  enter(node, parent) {
    if (node.type === "Identifier" && isReference(node, parent)) used.add(node.name);
  },
});
used; // Set { "a", "b", "e" }

extractIdentifiers(pattern) => Identifier[]

The Identifier nodes a pattern binds, in source order, as svelte's extract_identifiers returns them: a, c, d, e and f in let { a, b: [c, ...d], e = 1, ...f } = x. Property keys, defaults and type annotations aren't included, and a member expression binds nothing, so [a.b, c] = x yields only c. It takes any binding or assignment target: a declarator's id, a function's params, including a parameter property, a catch clause's param, an each block's context, a snippet's parameters, or an assignment's left, where a!, a as T, a satisfies T and <T>a yield a.

import { extractIdentifiers, parseModule } from "svelte-ast";

const [declaration] = parseModule("let { a, b: [c] } = x;").body;
if (declaration.type === "VariableDeclaration") {
  declaration.declarations.flatMap((d) => extractIdentifiers(d.id)).map((node) => node.name); // ["a", "c"]
}

analyzeScopes(ast, options?) => Scopes

Finds the scopes of a component, its scripts and markup together, or of a module: which declaration each name refers to, and where each binding is read, written or subscribed to. It resolves names as svelte's analyzer does, which tests/scope.test.ts checks on the corpus: on 12,548 components from the corpus, svelte's tests and the Svelte projects listed under parity, they agree on all 208,797 names they both resolve, but for a class expression's name inside its body, a snippet's own name and a var declared twice, where svelte-ast follows JavaScript.

import { parse } from "svelte-ast";
import { analyzeScopes } from "svelte-ast/scope";

const ast = parse(`<script>
  let { size = "md" } = $props();
  function label(size) { return size; }
</script>
<Tooltip let:direction={actual}>{actual} {size}</Tooltip>`);
const scopes = analyzeScopes(ast);

const size = scopes.instance.get("size");
size?.prop; // "size"
size?.rune; // "$props"
size?.initial; // the Literal "md"
size?.references.length; // 1: the parameter in `label` is another binding
size?.references.some((reference) => reference.writes || reference.mutates); // false

It returns:

  • module and instance, the scopes of <script module> and <script> (one scope, for a module). A Scope has the node that makes it, its parent, its declarations by name, and get(name), the binding a name refers to there, or null for a global. With types: true, its types holds its type, interface and type parameter bindings, and getType(name) is the binding a name refers to in a type.
  • scopeOf(node), the scope a node is in; null in a type, the <style> or another AST. The first call walks the AST again to record every node's scope, so a tool that only resolves names doesn't keep a map of every node.
  • bindingOf(identifier), the binding an Identifier declares or refers to; null for a global, a property key or a name in a type.
  • referenceOf(identifier), the Reference an Identifier is, to tell a read from a write or a store subscription; null for one that declares a binding or isn't a reference.
  • declaredIn(node), the bindings of the scope a node makes: a function's parameters (its body's declarations are its body's), a block's or an each block's declarations, a snippet's parameters, or an element's let: names.

A Binding has its name, its kind, the Identifier that declares it as node (null for an each block's index and for let:x without a value), the declaration that holds it, its scope and its references. initial is what it starts as, as svelte's analyzer has it: an initializer, or for a prop destructured from $props(), its default without $bindable. rune is the rune its initializer calls, such as "$state", "$derived" or "$props", unless a binding or a store shadows it, and prop the name a parent passes a prop as: "class" for klass in let { class: klass } = $props() or export { klass as class }, "size" for export let size.

A Reference has its Identifier as node, its parent, its scope and its binding, and says whether it reads the value (all but a plain ='s target), writes it (=, +=, ++, bind:, for (a of b)), or mutates it (a in a.b = c and bind:value={a.b}), and whether it's a store subscription. Names the markup holds as strings, such as Foo in <Foo.Bar>, a in use:a, transition:a and animate:a, and color in style:color, get a new Identifier with the name's start and end.

The markup's scopes are svelte's:

  • {#each items as item, i (key)} declares item and i for the key and the body, but not for {:else}.
  • A snippet's name is declared where the snippet is, and its parameters inside it. A top-level snippet is in the markup's scope, so a <script> that uses one refers to a global, as in svelte's analyzer.
  • {@const} declares a name for its whole block or element, {:then value} and {:catch error} for their branch.
  • let: declares a name for the element's attributes and children, or for a component's default slot; children with a slot attribute get their own scope. let:a={b} declares b, let:a declares a.
  • $count, without a declaration of $count, is a subscription to count, unless it's a rune: $state refers to a store state only if state isn't itself made by a rune.
  • $: a = b declares a if nothing else does, and writes it: the assignment is one of its references.

Names in TypeScript's types aren't references, and type and interface declare nothing; it skips them with valueVisitorKeys. Enums, enum members and namespaces are declared. It doesn't change the AST, and takes less than half as long as parsing it.

| Option | Default | Description | |:---|:---|:---| | types | false | Resolve the names in types too, for a tool that asks which declarations some code uses, such as one that copies a statement with the imports it needs. |

With types: true, type and interface declare bindings of those kinds, and a type parameter or infer U one of kind "type-param", in a scope's types, apart from its values, so type A and const A are two bindings. A name in a type is a Reference with type: true that neither reads, writes nor mutates: A in let a: A, a in typeof a, I in implements I and extends I, N in N.T, and the local name in export type { A }. A name in a type refers to a type, an import, a class or an enum; typeof a to a value; N in N.T to a namespace, an enum or an import, so import type { A } and import { type A } get the references. Property and method names in type literals and interfaces aren't references, but for a computed key's value. Type parameters are in scope for their function, class, method, type alias, interface or function type, infer U for its conditional type's true branch, and the parameters of a function type or signature are bindings of kind "param", for typeof x and x is T. <script generics="...">'s names aren't declared. The value references are those it finds without types.

const ast = parse(`<script lang="ts">
  import type { DataTableHeader } from "carbon-components-svelte";
  let headers: DataTableHeader[] = [];
</script>`);
const { instance } = analyzeScopes(ast, { types: true });
instance.get("DataTableHeader")?.references[0]?.type; // true

a11yWarnings(ast, options?) => A11yWarning[]

From svelte-ast/a11y. The a11y_… warnings svelte's compiler gives for a component, with the same code, message and offsets, and without the ones a <!-- svelte-ignore --> comment before an element, or one of its ancestors, silences. For a linter that already has the AST: on Carbon's 2,202 components it takes 60 ms, against 735 ms for compile(source, { generate: false }). It loads neither acorn nor the parser.

| Option | Default | Description | |:---|:---|:---| | runes | false | Whether the component compiles in runes mode, as isRunesMode says. In runes mode, svelte-ignore takes only svelte 5's codes, separated by commas; in legacy mode, svelte 4's a11y-… codes too, as svelte does. |

import { isRunesMode, parse } from "svelte-ast";
import { a11yWarnings } from "svelte-ast/a11y";

for (const warning of a11yWarnings(parse(source), { runes: isRunesMode(source) })) {
  warning.code; // "a11y_missing_attribute"
  warning.message; // "`<img>` element should have an alt attribute\nhttps://svelte.dev/e/a11y_missing_attribute"
  warning.start; // offsets of the element or attribute
}

The ARIA tables come from svelte's, which read aria-query and axobject-query, generated into the package, so it has no dependencies. On svelte's tests, carbon-components-svelte, bits-ui, shadcn-svelte, skeleton, flowbite-svelte, svelte.dev, immich and SvelteKit, it gives the warnings compile gives for all 13,276 components both accept, 899 warnings, and for 13,163 with their svelte-ignore comments and common a11y attributes removed, 2,185 warnings.

compilerWarnings(ast, options) => CompilerWarning[]

From svelte-ast/warnings. The warnings svelte's compiler gives for a component besides the a11y_… ones, with the same code, message and offsets, and without the ones a svelte-ignore comment silences. It loads neither acorn nor the parser. It gives:

| Code | When | | --- | --- | | css_unused_selector | A selector in the <style> matches no element in the markup | | block_empty | A block's branch holds only whitespace, such as {#if a} {/if} | | element_invalid_self_closing_tag | An HTML element that isn't void is written <div/> | | component_name_lowercase | A lowercase element's name is an imported value, such as <foo /> after import foo from "./Foo.svelte" | | attribute_global_event_reference | onclick={onclick} or {onclick} on an element, where nothing in scope is named onclick | | attribute_avoid_is, attribute_invalid_property_name, attribute_illegal_colon | The is attribute, React's className and htmlFor, and a colon in an attribute name that isn't xmlns: or xlink: | | bind_invalid_each_rest | bind: to a name from the rest of an {#each} pattern, such as ...rest | | attribute_quoted | In runes mode, prop="{value}" on a component or custom element | | event_directive_deprecated, slot_element_deprecated, svelte_component_deprecated, svelte_self_deprecated | In runes mode, on:, <slot>, <svelte:component> and <svelte:self> | | node_invalid_placement_ssr | An element the browser would move out of its parent, such as a <div> in a <p>, with a block between them. Without the block, svelte fails the build | | element_implicitly_closed | A tag closes an open element, such as the second <li> in <li>a<li>b | | svelte_element_invalid_this | <svelte:element this="div">, with a string for this | | script_unknown_attribute | A <script> attribute other than context, generics, lang and module | | script_context_deprecated | In runes mode, <script context="module"> | | options_deprecated_accessors, options_deprecated_immutable | In runes mode, accessors and immutable in <svelte:options> | | options_missing_custom_element | customElement in <svelte:options> without the customElement option | | bidirectional_control_characters | A string, template or text holds a character that changes the direction of the text, such as U+202E | | perf_avoid_inline_class, perf_avoid_nested_class | new class {} outside the module script's top level, and a class declared in a function, a $: statement or the markup | | legacy_code, unknown_code | In runes mode, a svelte-ignore comment names a svelte 4 code, such as a11y-autofocus, or a code svelte doesn't have | | state_referenced_locally | In runes mode, a script reads a $state, $derived or $props binding in the function that declares it, so it gets only the first value. $state warns only if it's reassigned or holds a value svelte doesn't proxy, such as a number | | non_reactive_update | In runes mode, the markup reads a script's binding outside a function, and something reassigns it, but no rune declares it. bind:this counts only inside a block | | store_rune_conflict | $state(...) or another rune's call where a local state makes it a store subscription | | custom_element_props_identifier | In runes mode, a custom element without customElement.props takes let props = $props() or ...rest | | export_let_unused | In legacy mode, nothing reads an export let | | reactive_declaration_invalid_placement | In legacy mode, a $: statement outside the instance script's top level | | reactive_declaration_module_script_dependency | In legacy mode, a $: statement reads a module script's binding that something reassigns | | legacy_component_creation | new App({ target }), where App is the default import of a .svelte file |

Its options:

  • source (required): the source passed to parse. svelte reads it to tell <div/> from <div></div>, which the AST doesn't.
  • filename: svelte's filename option. svelte_self_deprecated names the self-import after it, or Self without one.
  • customElement: svelte's customElement option. <svelte:options customElement> counts without it, except for options_missing_custom_element. A custom element gets no slot_element_deprecated.
  • runes: as for a11yWarnings.
import { isRunesMode, parse } from "svelte-ast";
import { compilerWarnings } from "svelte-ast/warnings";

const ast = parse(source);
for (const warning of compilerWarnings(ast, { source, filename, runes: isRunesMode(source) })) {
  warning.code; // "css_unused_selector"
  warning.message; // 'Unused CSS selector ".a"\nhttps://svelte.dev/e/css_unused_selector'
  warning.start; // offsets of the selector
}

svelte gives some warnings as it parses: element_implicitly_closed and svelte_element_invalid_this. parse records them with the AST it returns, so pass that AST: a copy, or an AST from svelte's parse, gets neither. svelte gives these and the script_…, options_… and store_rune_conflict warnings outside its walk of the markup, so a svelte-ignore comment silences none of them. For non_reactive_update and export_let_unused, only a comment before the declaration counts.

svelte checks every string for bidirectional_control_characters with one regular expression with the g flag. After a match, its next check starts part way into the next string, so svelte can miss one, and the miss carries over to the next component it compiles. svelte-ast follows this within a component, but starts each component afresh, as svelte does for the first one it compiles. svelte throws on an unknown_code or legacy_code in a comment before a <script>; svelte-ast gives no warning for it.

It's a port of svelte 5's analysis, so it gives what svelte 5 gives. It builds scopes only for a component that needs them, and shares them between checks: a check of the scripts' syntax and the markup's text first rules out most components. On the 8,834 components of the projects below that have the AST, it takes 193 ms, against 60 ms without the scope warnings. compile(source, { generate: false }) takes 2,693 ms on the 8,735 of them it accepts. For all the warnings, on the same projects, svelte's tests and the corpus, it gives the warnings compile gives for all 13,097 components both accept, 1,344 warnings. For the warnings besides css_unused_selector, on the same projects, svelte's tests, carbon-components-svelte and the corpus, it gives the warnings compile gives for all 15,090 components both accept with their svelte-ignore comments removed, 602 warnings, and for all 12,119 that compile with <svelte:options runes> added, 1,295 warnings. On svelte's tests, carbon-components-svelte, bits-ui, shadcn-svelte, skeleton, flowbite-svelte, svelte.dev, immich, SvelteKit, melt-ui, layerchart and paneforge, it gives the warnings compile gives for all 14,208 components both accept, 1,516 warnings with the static class and id attributes removed from the markup. A differential fuzzer (scripts/fuzz-css.ts) found no difference on 166,000 more components.

createLocator(source) => (offset) => Position

A function from an offset to its { line, column }, line from 1 and column from 0, as loc: true gives them: for a tool that parses without loc, which is faster, and needs lines only for what it reports. Lines are found on the first call, and each lookup starts its search at the line found last, so lookups in source order are fastest. Lines end at \n, as in the markup's loc and ParseError; acorn's loc in scripts and modules also ends them at a lone \r, U+2028 and U+2029. parse drops a leading byte order mark, so pass the source without one.

import { createLocator, parse, walk } from "svelte-ast";

const locate = createLocator(source);
walk(parse(source), {
  enter(node) {
    if (node.type === "Component") console.log(node.name, locate(node.start).line);
  },
});

locate(source, offset) gives the same { line, column } without keeping a locator: it keeps the lines of the last 64 sources it was called with, so a tool that reports nodes from many files, in any order, looks lines up once per file rather than scanning each from the start.

import { locate } from "svelte-ast";

`${file}:${locate(source, node.start).line}`;

Types

AST is svelte's AST namespace (AST.Root, AST.RegularElement, AST.CSS.Rule, ...), corrected to match what the parser returns: name_loc and a comment's loc are optional, Root.instance/module are absent rather than null when there's no such <script>, Root.js is declared, and every directive has modifiers. Each function's options and results are exported too, e.g. ParseOptions and LexedStatement.

The script's node types are exported as well (Program, Node, Statement, Expression, Identifier, ...), so you don't need a separate types package. They include start/end on every node, and the TypeScript nodes (TSInterfaceDeclaration, TSTypeAnnotation, ...; TSNode is their union) and fields (typeAnnotation, typeParameters, returnType, importKind, ...). The TypeScript nodes are in the Statement, Declaration and Expression unions, so checking node.type narrows to them. Where the grammar only allows a string, such as an import's source, the type is StringLiteral, a Literal whose value is a string.