svelte-docinfo

static analysis for TypeScript and Svelte 📜

repo 0.18.0 npm

npm i -D svelte-docinfo

introduction #

svelte-docinfo extracts JSON describing the exports of TypeScript and Svelte modules for open-ended use cases like docs, code search, and dev tools. It uses the TypeScript compiler API and svelte2tsx to resolve types, track exports+imports, and extract semantic details.

svelte-docinfo is largely inspired by sveld, but uses the TypeScript compiler API instead of AST-only inspection, and also analyzes TypeScript modules. See the comparison below.

The library is mostly complete for Svelte 5 and used in production websites, but you may find gaps and flaws -- please open issues for bugs, and discussions for everything else!

Dependencies are minimal and the tool's scope is limited to data, not presentation. These docs were made using the data produced by svelte-docinfo, like the architecture and API reference, with fuz_ui components.

AI disclosure: the code and docs beyond the intro were mostly written by Claude Code with uneven human guidance. The first release took 5 months of intermittent work and ~500 manual commits to extract its initial implementation from fuz_ui, which was more limited, lacking the fancy TS compiler usage, and grew slowly over years without AI assistance.

Install
#

npm i -D svelte-docinfo

Peer dependencies: svelte 5+, svelte2tsx, and typescript 5.9+ or 6, plus vite 6+ for the Vite plugin.

Three ways to use it
#

All three run the same analysis and produce the same data, AnalyzeResultJson: {modules, diagnostics}.

Vite plugin
#

For SvelteKit and Vite projects, the Vite plugin analyzes at build time and serves the result as a virtual module that stays current in dev:

// vite.config.ts import {defineConfig} from 'vite'; import {sveltekit} from '@sveltejs/kit/vite'; import svelteDocinfo from 'svelte-docinfo/vite.js'; export default defineConfig({plugins: [sveltekit(), svelteDocinfo()]}); // anywhere in your app import {modules} from 'virtual:svelte-docinfo';

CLI
#

The CLI inspects a project, writes a JSON file, or feeds a shell pipeline:

npx svelte-docinfo --pretty -o library.json

JS API
#

The JS API serves scripts and build tools: analyzeFromFiles finds the files itself, analyze takes contents you already have, and createAnalysisSession re-analyzes incrementally.

import {analyzeFromFiles} from 'svelte-docinfo'; const {modules, diagnostics} = await analyzeFromFiles({projectRoot: process.cwd()});

By default all three document the source files your package.json exports point to, falling back to everything under src/lib; see source files. The output format reference shows the JSON.

What it extracts
#

  • every export of every documented module, with the checker's types (generics, imported and inferred types, no annotations needed), docs, and source lines
  • TSDoc and JSDoc tags, plus @nodocs to leave a declaration out and @mutates for side effects
  • structured types: typeInfo trees beside the flat type strings, recovering alias names TypeScript drops (z.infer, v.InferOutput)
  • Svelte 5 components: props with types, defaults, and bindability, snippet and callback parameters, generics, children, exported snippets, and runes ($state, $derived) in any file
  • component styling: the CSS custom properties a component's styles read, plus those documented with @cssprop
  • JS modules documented like their TS twins, from JSDoc types, @typedefs, @templates, and @overloads
  • re-exports and the import graph between modules
  • diagnostics collected without halting, for doc problems like misplaced tags and stale @params

Limitations
#

  • Svelte 4 named slots, slot props, and events aren't modeled, nor context (setContext); a request would bump context's priority. Legacy export let components document their props.
  • Standalone namespace Foo {} declarations document as a bare variable (export * as ns works), and decorators aren't modeled.
  • CommonJS isn't modeled (see CommonJS).

Compared to sveld
#

sveld is a Svelte component documentation generator that walks the AST and infers types from JSDoc annotations and literal values. svelte-docinfo instead uses the TypeScript compiler API (via svelte2tsx) as its source of truth, so it resolves imported types, generics, and complex inferred types in TypeScript components without @type annotations. It also analyzes TypeScript modules, not just .svelte files, tracks re-exports across modules, computes dependency graphs, and records source locations.

Vite plugin #

The Vite plugin is the recommended path for SvelteKit and Vite projects. It runs analysis at build time and serves the result as 'virtual:svelte-docinfo'. In dev it watches your source files, plus the other files they import like internal/ modules, and reloads the page when an edit changes the result.

The plugin keeps a persistent createAnalysisSession, so dev re-analysis reuses parsed ASTs and svelte2tsx output. To write the data to a file instead, use the CLI.

Setup
#

Requires Vite 6 or later.

  1. Add the plugin to vite.config.ts:

    import {defineConfig} from 'vite'; import {sveltekit} from '@sveltejs/kit/vite'; import svelteDocinfo from 'svelte-docinfo/vite.js'; export default defineConfig({ plugins: [sveltekit(), svelteDocinfo()], });
  2. Add TypeScript support in your app.d.ts:

    /// <reference types="svelte-docinfo/virtual-svelte-docinfo.js" />
  3. Import the virtual module anywhere in your app:

    import {modules, diagnostics} from 'virtual:svelte-docinfo'; // or use the default export: import data from 'virtual:svelte-docinfo'; // data.modules and data.diagnostics are the same as the named exports

    The data is AnalyzeResultJson in its wire form (AnalyzeResultJsonWire). modules and diagnostics are always arrays, but entries in modules omit empty arrays and false flags. Treat absent as empty, or restore the defaults per module with parseModuleJson from svelte-docinfo/types.js, which is light enough for the browser (see compact JSON). See diagnostics for diagnostics.

If TypeScript reports Cannot find module 'virtual:svelte-docinfo', check the /// <reference> line in app.d.ts.

Options
#

All options are optional; the minimal call discovers files from package.json exports, falling back to glob:

svelteDocinfo()

Every option, with its default in the comment above it:

import svelteDocinfo from 'svelte-docinfo/vite.js'; svelteDocinfo({ // Project root directory. Default: Vite's resolved config.root. projectRoot: process.cwd(), // Glob patterns for file discovery. Forces glob mode under discovery: 'auto'. // Default: undefined (use exports discovery). // Each pattern's static base joins sourceOptions.sourcePaths; a pattern // with no base makes the whole project root source and logs an info line. include: ['src/**/*.ts', 'src/**/*.svelte'], // Exclude globs. An array replaces the default // ['**/*.{test,spec}.{ts,mts,tsx,js,mjs,jsx}', '**/internal/**']; a callback extends // it. Replaces sourceOptions.exclude when both are set. node_modules and // dot-directories below a source path are never source. exclude: (defaults) => [...defaults, '**/*.gen.ts'], // Discovery strategy: 'auto' | 'exports' | 'glob'. Default: 'auto'. // 'auto' → exports first, glob fallback // 'exports' → strict; throws if package.json exports is missing or resolves to no files // 'glob' → skip exports, use glob patterns discovery: 'auto', // Dist directory for exports discovery. Default: 'dist'. distDir: 'dist', // Resolve module dependency graph. Default: true. resolveDependencies: true, // Partial overrides for default source options (SvelteKit src/lib layout). // Merged into createSourceOptions(projectRoot, sourceOptions). sourceOptions: {sourcePaths: ['src/lib']}, // dev re-analysis debounce in ms. Default: 100. hmrDebounceMs: 100, // Opt-in check that names are unique across modules, for packages with a // flat export namespace. Default: undefined (off). // 'diagnostic' → emit duplicate_declaration diagnostics // 'warn' → also log them // 'throw' → also fail the build onDuplicates: undefined, // tsconfig path relative to projectRoot (searched upward from it), or false // to analyze without one. Default: 'tsconfig.json'. tsconfig: 'tsconfig.json', // Compiler options merged over the tsconfig's. Default: none. compilerOptions: undefined, // The program's root files, in place of the tsconfig's: a list, or a // function over the tsconfig's roots. Default: the tsconfig's roots. // See the source files guide for the declarationFileRoots preset and its tradeoff. rootFileNames: undefined, })

The plugin runs the same pipeline as analyzeFromFiles: discover, resolve dependencies, analyze. In dev, imports resolve through Vite's resolveId, so Vite aliases apply; in builds, the TypeScript default resolver is used (it honors tsconfig paths). hmrDebounceMs only affects the dev watcher.

source files covers how discovery, include, exclude, sourceOptions, and the tsconfig options decide what's documented.

Dev behavior
#

Options are validated when Vite resolves its config, so a bad one (like discovery: 'exports' with include, or a path outside the project root) fails at startup.

In dev the plugin watches the source files and the files they import, debounces re-analysis by hmrDebounceMs, and re-parses only what changed. Only the files discovery selects emit modules, as in a build: an edit elsewhere refreshes the analysis without adding a module, and a newly created file is checked against discovery again.

Any change to the output reloads the page, even one that only shifts a declaration's source line, instead of letting Svelte HMR update components in place. Importers build state from the data (like a layout building a library from modules), so re-running the module alone would leave them stale.

CLI #

Run in a project with TypeScript or Svelte source and a tsconfig.json at or above its root (or pass --no-tsconfig). The CLI runs analyzeFromFiles once and prints the JSON to stdout.

Basic usage
#

npx svelte-docinfo # analyze the current directory npx svelte-docinfo ./packages/my-lib # analyze a specific directory npx svelte-docinfo -o output.json # write to a file instead npx svelte-docinfo --pretty # pretty-print the JSON output

It documents the files package.json exports point to, falling back to everything under src/lib; source files covers the flags that change that.

Output is compact: empty arrays and false flags are omitted, so treat absent as empty, or parse with parseAnalyzeResult. It pairs well with jq:

npx svelte-docinfo | jq '.modules | length' # count modules npx svelte-docinfo | jq -r '.modules[].declarations[].name' # list all exported names

JSON goes to stdout and messages go to stderr, so > and | capture clean JSON. -q silences info messages; warnings and errors still print.

Options
#

FlagDescription
[project-root]project root directory (default: cwd)
-i, --include <pattern>include pattern (repeatable). Replaces exports discovery and widens the source scope (see below); incompatible with --discovery exports
-e, --exclude <pattern>exclude glob, applied at discovery and analysis (repeatable). Replaces the defaults **/*.{test,spec}.{ts,mts,tsx,js,mjs,jsx}, **/internal/** entirely
-o, --output <file>output file (default: stdout; - also means stdout, so -o "$OUT" works when $OUT=-)
--discovery <mode>auto | exports | glob (default: auto: exports first, glob fallback). exports fails when package.json exports is missing or resolves to no files
--dist-dir <dir>dist directory for exports discovery (default: dist)
--source-dir <dir>source directory, relative to the project root or absolute inside it (default: src/lib). Repeatable; also sets the default include glob
--source-root <dir>base of output module paths (default: single source dir or longest common prefix; . for project-relative)
--only <pattern>glob filter on output module paths (repeatable). The full project is still analyzed, so re-exports and dependents stay correct; diagnostics aren't filtered
--no-resolve-dependenciesdisable dependency resolution (dependencies/dependents stay empty)
--tsconfig <path>path to the tsconfig, relative to the project root and searched upward from it (default: tsconfig.json)
--no-tsconfiganalyze without a tsconfig, using built-in strict compiler options
--prettypretty-print JSON output (default: compact)
-q, --quietsuppress info messages on stderr (warnings and errors still print)
--on-duplicates <mode>opt-in check that names are unique across modules, for packages with a flat export namespace: diagnostic | warn | throw (default: off)
-V, --versionshow version number
-h, --helpshow help

--include, --exclude, --source-dir, and the discovery and tsconfig flags work as source files describes. --exclude always replaces the defaults; there's no form that extends them.

Exit codes: 0 success, 1 analysis errors, 2 CLI errors (an unknown flag, a missing or invalid option value) or a thrown analysis error (a missing or unloadable tsconfig.json, strict exports discovery failing).

To use the data in a SvelteKit or Vite app, see the Vite plugin; from code, the JS API.

JS API #

Three functions run the analysis, each returning the same AnalyzeResultJson. Pick by what your code already has:

FunctionUse when
analyzeFromFilesyou have a project on disk: it finds, reads, and analyzes the files in one call
analyzeyou already hold the file contents, like a bundler plugin
createAnalysisSessionyou re-analyze the same files as they change, like a watcher or editor tool

The Vite plugin runs a session and the CLI runs analyzeFromFiles, so their options map onto these.

analyzeFromFiles
#

import {analyzeFromFiles} from 'svelte-docinfo'; const {modules, diagnostics} = await analyzeFromFiles({ projectRoot: process.cwd(), // the rest are optional: // discovery: 'auto' | 'exports' | 'glob', // include: ['src/**/*.ts'], // exclude: (defaults) => [...defaults, '**/*.gen.ts'], // sourceOptions: {sourcePaths: ['src/lib']}, // tsconfig: 'tsconfig.json', // or false // onDuplicates: 'diagnostic' | 'warn' | 'throw', });

It discovers the files to document from package.json exports, falling back to globs under src/lib, as source files explains along with the options that change it. AnalyzeFromFilesOptions lists every option.

analyze
#

import {analyze, createSourceOptions} from 'svelte-docinfo'; const {modules, diagnostics} = await analyze({ sourceFiles: [{id: '/project/src/lib/a.ts', content: '...'}], sourceOptions: createSourceOptions('/project'), });

Each SourceFileInfo is an absolute id and its content. Files outside the source paths (default src/lib) inform types but emit no module. TS files you leave out are read from disk for their types, but a component you leave out types as any, so pass every component the analyzed code imports. build tools covers pre-resolved dependencies and custom import resolution.

createAnalysisSession
#

import {createAnalysisSession, createSourceOptions} from 'svelte-docinfo'; const session = createAnalysisSession({sourceOptions: createSourceOptions(process.cwd())}); await session.setFiles(files); // again on every change; unchanged files are cache hits const {modules, diagnostics} = session.query(); // ingest diagnostics (like transform_failed) aren't in query(): see allIngestDiagnostics() session.dispose();

A session keeps parsed files and svelte2tsx output between queries. See the session guide.

Results
#

The functions return the result with every default filled in. Serialize it compactly with compactReplacer, as the CLI and Vite plugin do, and read compact JSON back with parseAnalyzeResult, which restores the defaults and validates the shape (see compact JSON):

import {compactReplacer, parseAnalyzeResult} from 'svelte-docinfo'; const json = JSON.stringify(result, compactReplacer); const {modules, diagnostics} = parseAnalyzeResult(JSON.parse(json));

Problems in the analyzed code land in diagnostics; bad setup, like a missing tsconfig or invalid options, throws. See diagnostics.

Imports
#

The svelte-docinfo entry exports the common API and loads the TypeScript compiler. Every module is also importable on its own as svelte-docinfo/<module>.js, and a few are light enough for a browser bundle, for rendering data the analysis produced:

The API examples show more patterns, and the API reference lists everything.

source files #

Every analyzed file informs types, but only source files are documented, each as one ModuleJson: the files discovery finds that sit under the source paths (default src/lib) and match no exclude pattern. This page covers how files are found and scoped; the options are the same across the Vite plugin, the CLI (as flags), and the JS API.

Discovery
#

The discovery option picks how files are found:

  • 'auto' (default): from package.json exports, falling back to globs when there are none
  • 'exports': from exports only, throwing when they're missing or name no source files
  • 'glob': every module file under the source paths

Exports discovery maps each dist entry back to its source: a .js to the .ts, .tsx, .js, or .jsx beside it, in that order, and an .mjs to an .mts or .mjs. Wildcard entries ("./*.js") expand, and null entries ("./internal/*": null) block subpaths with Node's matching rules.

Modules are .svelte, .ts, .mts, .tsx, .js, .mjs, and .jsx files. Discovery also finds .css and .json files, which document as modules with no declarations. .cjs, .cts, and declaration files aren't analyzed.

include globs replace discovery (they collapse 'auto' to glob, and combining them with 'exports' throws). Each pattern's static base joins the source paths, so the files it finds are documented; a pattern with no base (**/*.ts) makes the whole project source.

Excluding files
#

exclude applies at discovery and analysis alike, so an excluded file is never documented however it was found. The default is ['**/*.{test,spec}.{ts,mts,tsx,js,mjs,jsx}', '**/internal/**']. An array replaces it, and a callback extends it:

exclude: (defaults) => [...defaults, '**/*.gen.ts']

The CLI's --exclude always replaces the defaults. Beneath any exclude, node_modules and dot-directories below a source path are never source; dist and build are ordinary names.

src/lib/internal/ holds modules that ship for public modules to import but aren't documented, usually paired with an "./internal/*": null exports entry. They still inform types, and in dev an edit to one re-analyzes the modules that use it. A public re-export of an internal symbol documents in full at the re-export. To document them anyway, drop the pattern: exclude: (defaults) => defaults.filter((p) => p !== '**/internal/**').

Source paths
#

sourceOptions.sourcePaths (CLI: --source-dir, repeatable) lists the source directories, and sourceRoot (--source-root) is the base of ModuleJson.path, by default the single source path or the common prefix of several. Pass '.' for project-relative paths.

import {createSourceOptions} from 'svelte-docinfo'; const sourceOptions = createSourceOptions(process.cwd(), { sourcePaths: ['packages/a/src', 'packages/b/src'], });

Paths and patterns are relative to the project root. Absolute ones inside it are accepted, and anything outside it throws when the options are created. '/src/lib' is a filesystem path, not shorthand for 'src/lib'.

tsconfig
#

Analysis runs with your project's compiler options, from tsconfig.json found at or above the project root (the tsconfig option, or --tsconfig, names another). The file and its whole extends chain must load, so a SvelteKit project needs svelte-kit sync first. tsconfig: false (--no-tsconfig) analyzes without one, under strict built-in options (DEFAULT_COMPILER_OPTIONS), and compilerOptions merge over either, key by key.

allowJs is always on, so JS modules document under any tsconfig (see JS and JSDoc).

Every file the tsconfig includes loads, which makes a cold start scale with the project. rootFileNames narrows that to the analyzed files and what they import; an ambient type declared in a file nothing imports then resolves to any, unless you keep the declaration files with the declarationFileRoots preset (see RootFileNames).

JS and JSDoc #

JS modules (.js, .mjs, .jsx), JS components, and JS <script module> blocks document like their TS twins: svelte-docinfo reads their JSDoc the way TypeScript's checker does, so /** @param {string} a */ types a parameter as a: string would. allowJs is always on for the analysis, so no tsconfig change is needed, and checkJs isn't required.

TypeScript reads none of this in .ts files: there, JSDoc types and the tags below annotate nothing, as in your editor.

Types and parameters
#

A @type, @param, @returns, or @property type is the written annotation at its site, so it recovers alias names and keeps union order as written, like a TS annotation (see structured types).

/** * @param {string} a - a required parameter * @param {number} [b] - optional, as is `{number=}` * @param {number} [c=0] - optional, with defaultValue "0" * @param {object} [d] - an options object * @param {boolean} [d.e] - documents d's property e */ export function fn(a, b, c = 0, d) {}

@typedef and @callback
#

A @typedef or @callback documents as a type alias, like type A = …: @property tags become members with their descriptions, a callback gets a (call) member, and @template tags its generics. A const A with a same-named @typedef A documents as one declaration with mergedValue: true.

As in your editor's hover, a JSDoc block that declares a typedef and has no @param or @returns documents the typedef, not the declaration below it. Give the declaration its own block:

/** * A point. * @typedef {object} Point * @property {number} x - the horizontal position * @property {number} y - the vertical position */ /** The origin. */ export const ORIGIN = {x: 0, y: 0};

A @module block keeps its prose for the module, and a component's JSDoc above $props() for the component. A @typedef in a component's HTML @component comment documents nothing. Declare a component's props typedef in a block of its own, since svelte2tsx copies the block above $props() into its generated code, where svelte-check reports a typedef as a duplicate.

An @enum const documents as kind: 'enum', one member per property.

@template
#

@template tags are genericParams on functions, classes, and methods, with constraints (@template {string} K) and defaults (@template [K='k']), as <K extends string = 'k'> writes them.

@overload
#

Each @overload tag declares a signature, documented by the block it sits in and the @param and @returns tags after it. The first overload documents the function, and the implementation's own block is hidden, as in a TS overload set, so put the prose and tags like @example on the first overload; a documented implementation warns implementation_doc_hidden. Write @template before @overload, since TypeScript rejects one between @overload and its @params.

/** * Doubles a number or a bigint. * @overload * @param {number} n - the number to double * @returns {number} * @example double(2) // 4 */ /** * @overload * @param {bigint} n - the bigint to double * @returns {bigint} */ /** @param {number | bigint} n */ export function double(n) { return /** @type {any} */ (n) * 2; }

Classes
#

  • @private hides a member, and @protected, @public, and @readonly add modifiers, like the TS keywords.
  • @implements {A} fills implements, and @extends {Base<T>} beside extends Base gives the type arguments.
  • this.x = … in the constructor, a method, or an accessor declares a member (static in a static method or block), typed by its first @type and documented by its first documented assignment, preferring the constructor's. These members list just before the constructor, where a TS class declares its fields.
  • A name the base class declares stays the base's (this.name = … in an Error subclass lists nothing). To document it on the subclass, write a field.

Components
#

A JS component's props come from the JSDoc @type on $props(), often a typedef, else from the destructuring. A legacy component's export let props read their @type and initializer.

<script> /** * @typedef {object} Props * @property {string} a - documents prop a */ /** * The component's docs. * @type {Props} */ const {a} = $props(); </script>

CommonJS
#

CommonJS isn't modeled. A JS file with no import or export that exports through module.exports or exports.x documents nothing and warns commonjs_unsupported. Under node16/nodenext or moduleDetection: 'force', TypeScript reads CommonJS exports itself, so named ones (exports.x, module.exports = {a, b}) document. Exports defined through Object.defineProperty or a UMD wrapper document nothing, with no warning.

Limits
#

  • Assignments outside a class (A.prototype.x = …, A.x = …) don't add class members.
  • An @overload's rest parameter ({...T}) is rest, but types as T | undefined, as TypeScript reads it.
  • A @property after a non-@property tag leaves the typedef's property list, as TypeScript reads it, and is dropped.

component styling #

A component's styling hooks are the CSS custom properties a consumer can set to style it. Each component lists them in cssCustomProperties, as ComponentCssPropertyJson entries. Two kinds are found in its styles automatically: a var() read with a fallback, and a property registered with an @property rule. You can also document any property with a @cssprop tag in the doc comment.

Example
#

<!-- @component A card. @cssprop {<length>} [--card_width=20rem] - the card's width @cssprop --card_padding - the inner padding --> <div class="card"></div> <style> @property --card_padding { syntax: '<length>'; inherits: true; initial-value: 1rem; } .card { width: var(--card_width, 20rem); padding: var(--card_padding); background: var(--card_bg, white); border-radius: var(--border_radius, 4px); color: var(--text_color); } </style>

The component's cssCustomProperties:

[ { "name": "--card_width", "description": "the card's width", "syntax": "<length>", "fallback": "20rem", "default": "20rem", "sourceLine": 17, "documented": true }, { "name": "--card_padding", "description": "the inner padding", "syntax": "<length>", "fallback": "1rem", "sourceLine": 18, "documented": true }, {"name": "--card_bg", "fallback": "white", "sourceLine": 19}, {"name": "--border_radius", "fallback": "4px", "sourceLine": 20} ]
  • --card_width is read with a fallback and tagged: the tag gives description, syntax, and default; the read gives fallback and sourceLine.
  • --card_padding is read bare, which alone wouldn't list it, but its @property rule registers it: the rule supplies syntax, and its initial-value becomes fallback.
  • --card_bg is a plain fallback read, listed without a tag.
  • --border_radius is a global design token, but it's read with a fallback, so it's listed too; see choosing what to show.
  • --text_color is read bare and registered nowhere, so it isn't listed: bare reads are mostly global tokens the component consumes, not hooks it offers.

Documented entries come first, in tag order, then the rest in the order of each name's first read. The output format describes each field.

Fallback reads
#

Svelte's docs use var(--track-color, #aaa) to expose a styling hook, so any var() with a fallback counts as one. Reads are found in:

  • the component's top-level <style>, at any depth: nested rules, @media/@container/@supports blocks, keyframes, :global
  • the static text of the markup's style attributes and style: directives on elements
  • the static text of a child component's style and --a attributes (<Child --a="var(--b, 1px)" /> reads --b)

Only the outermost var() counts: var(--a, var(--b)) lists --a, with --b part of its fallback. A name the component sets itself isn't listed, since its own value shadows a consumer's: a --a: … declaration in its style, a style:--a directive, or --a: in an element's style attribute. A --a or style attribute on a child component styles the child, not this one. Names are case-sensitive, as in CSS.

fallback is the verbatim source text after the comma, trimmed, comments and line breaks included; it's empty for var(--a,). When a name is read several times, sourceLine comes from the first read and fallback from the first read that has one, so a bare read before a fallback read doesn't keep the name off the list.

@property
#

An @property rule in the component's style registers a custom property with the browser, so the property is listed even when every read is bare. The rule's syntax descriptor becomes syntax, quotes stripped, and its initial-value becomes fallback: a registered property is never unset, so the initial value wins over any var() fallback. When several rules name one property, the last wins, as in CSS. A registered name nothing reads isn't listed.

inherits isn't modeled. With inherits: false, a consumer's value never reaches the component's elements, so the property isn't a hook at all; register hooks with inherits: true. Svelte doesn't scope @property rules, so a registration applies to the whole page.

@cssprop
#

@cssprop in the component's doc comment documents a property, in the Custom Elements Manifest form (@cssproperty is a synonym):

@cssprop {<syntax>} [--name=default] - description
PartField
{<syntax>}syntax, verbatim and unvalidated (<color>, <length> | auto). Optional; without it, an @property rule's syntax fills in.
--namename, -- included. The brackets are optional without a default.
=defaultdefault, verbatim and trimmed; nested brackets and quoted strings are fine ([--a=var(--b, 1px)]). Optional.
- descriptiondescription, raw like docComment, continuation lines included. The dash is optional. Inline {@link} is kept for the renderer.

A tagged property is always listed, with documented: true. Use a tag to describe a hook, or to list one the fallback rule misses, like a bare read (width: var(--card_width)). A tagged name the component reads anywhere (bare, nested in another fallback, in the markup's static style text, even one it sets itself) merges with the read, taking its sourceLine and fallback. A tagged name it never reads takes the tag's line and warns unknown_cssprop.

default is the author's claim and fallback the style's fact, kept side by side so neither hides the other; a renderer wanting one value takes default ?? fallback. When both exist and differ (compared as text, whitespace runs collapsed), cssprop_default_mismatch warns; usually the style changed and the tag didn't. Nothing evaluates CSS, so red against #f00 warns too: write the default as the style does, or omit it and let fallback speak.

Tags come from the one comment that documents the component: the JSDoc above $props() when it has prose or a tag (a bare @type doesn't count), else the HTML @component comment. When both have content, even a JSDoc of tags alone, duplicate_comment warns and the HTML comment is ignored, prose and tags alike, so keep the tags beside the component's prose. Legacy export let components read only the HTML comment. A tag on a prop, a member, or anything but a component documents no property (see tags).

Warnings
#

Each warning carries the component's name and a line. None removes a listed property; only a malformed or repeated tag is itself dropped. The full list is in diagnostics.

kindWhen
unknown_csspropa tag names a property the component never reads: a typo, a stale tag, or one it leaves to a child (reads aren't resolved across components)
cssprop_default_mismatcha tag's default differs from the style's fallback
malformed_taga tag names no -- property (@cssprop card_width, an unclosed brace or bracket, an empty tag); it's dropped
duplicate_taga tag repeats a name an earlier tag documents; the first wins
css_lang_unsupported, css_parse_failedthe style wasn't read (below); the tags are listed unchecked, with no fallback

Choosing what to show
#

A global design token read with a fallback, like var(--border_radius, 4px) in the example, lists as a hook too, because the analyzer can't tell a token from a hook. In your own components, drop the fallback when the token always exists, or tag the real hooks so consumers can show only those.

There's deliberately no option to filter during analysis: the output keeps every read, and a consumer that wants fewer filters them. A common rule: show the documented entries when a component has any, else all of them:

const documented = declaration.cssCustomProperties.filter((p) => p.documented); const shown = documented.length > 0 ? documented : declaration.cssCustomProperties;

An entry maps onto a Custom Elements Manifest cssProperties entry field for field (name, description, syntax, default); fallback, sourceLine, and documented have no manifest counterpart.

What isn't read
#

  • a <style lang="scss">, or any language but CSS (warns css_lang_unsupported)
  • a component Svelte's parser rejects: malformed CSS, or markup its loose parsing can't absorb (warns css_parse_failed)
  • reads inside a dynamic style expression (style="color: {c}"), or in a <svelte:head> style
  • properties set from script (style.setProperty) or in a dynamic style expression: they count as unset, so their fallback reads stay listed
  • reads in another component: a wrapper documenting a property its child reads through inheritance warns unknown_cssprop

session #

createAnalysisSession returns a persistent analysis handle backed by a TypeScript LanguageService, for re-analyzing the same files as they change (the Vite plugin, watchers, editor tools). It reuses parsed ASTs, svelte2tsx output, and the dependency graph across queries. To analyze once, use the one-shot analyze or analyzeFromFiles (see JS API), which wrap single-use sessions. The full types are in session.ts.

Construction
#

import {createAnalysisSession, createSourceOptions} from 'svelte-docinfo'; const session = createAnalysisSession({ sourceOptions: createSourceOptions(process.cwd()), // Optional: session-default ImportResolver (or a bare resolve function). // Defaults to TypeScript module resolution with your tsconfig. // resolveImport: myResolver, // Optional (default true): also ingest the in-project files your inputs // import that you didn't supply, as non-emitting context. // contextClosure: true, // Optional: a tsconfig path relative to the project root, or false to // analyze without one. Default: 'tsconfig.json'. // tsconfig: 'tsconfig.lib.json', // Optional: the program's root files, in place of the tsconfig's. // rootFileNames: declarationFileRoots, // from 'svelte-docinfo/typescript-program.js' // Optional: logger for session-level messages. // log: console, });

AnalysisSessionOptions requires complete ModuleSourceOptions; build them with createSourceOptions, which merges your overrides with DEFAULT_SOURCE_OPTIONS. The session applies no further defaults.

The tsconfig is parsed once, at construction, so a later edit to it needs a new session. The tsconfig, compilerOptions, and rootFileNames options work as source files describes.

Lifecycle
#

The session owns a source set that you add to, update, and remove from:

MethodPurpose
setFile(file, opts?)Ingest one file's content; a no-op on cache hit. Returns SetFileResult
setFiles(files, opts?)Ingest a batch. Additive; never removes. Returns SetFilesResult with aggregate and per-file views
deleteFile(id)Remove a file from the session
has(id)Whether the given absolute path is currently owned
list()Snapshot of owned file IDs (insertion order), context files included
query(opts?)Analyze the owned set. Files outside sourcePaths, matching exclude, or held as context inform type resolution but emit no module. Returns AnalyzeResultJson
allIngestDiagnostics()Cumulative ingest-time diagnostics across every owned entry
getProgram()The underlying ts.Program, for your own checker work. It goes stale after any setFile, setFiles, or deleteFile that changes the session, so call it again afterward
dispose()Release resources and clear the owned set. Don't use the session afterward

Concurrency. The session isn't safe for overlapping calls, so serialize them. setFile, setFiles, and deleteFile are async (resolvers may await I/O); query is sync and reads the current owned set, so await pending ingests first.

Cache-hit semantics
#

Re-ingesting a file either reuses everything cached for it or recomputes everything. What counts as a hit depends on the mode:

  • lex+resolve (default): identical content and the same ImportResolver identity.
  • pre-resolved (caller supplies SourceFileInfo.dependencies): identical content and an element-wise equal array. A fresh array with the same elements hits, so [...filer.deps.keys()] per call works; any length, element, or order difference misses. The dependencies are trusted unchecked; see trust contract.

Switching a file between modes always misses.

Unresolved imports are the exception: a file's edges can change without re-ingesting it. When a setFile / setFiles call adds files, the session retries specifiers that previously resolved to null in lex+resolve files (with the same resolver), updates their edges, and clears stale resolver_failed diagnostics. It also calls the resolver's optional invalidate() before the next batch whenever files were added or removed since it last ran, so cached failed lookups don't stick. Pre-resolved files are untouched.

On a hit, SetFileResult.changed is false and the cached ingest diagnostics are returned without doing any work, unless the call changes the file's role (context), which reports changed: true since the emitted set moves.

ImportResolver and identity
#

ImportResolver is {resolve, identity, invalidate?}. identity is a stable opaque token (string or symbol) that keys the cache alongside content; invalidate() clears any cached failed lookups when files are added or removed.

import type {ImportResolver} from 'svelte-docinfo'; const myResolver: ImportResolver = { identity: 'vite-plugin-container', resolve: (specifier, fromFile) => { // return absolute path, or null for externals return null; }, };

identity is required because function references make poor cache keys: callers often wrap a resolver in a fresh closure per call (a common Vite/Rollup pattern), which would defeat caching. Reuse the same token as long as resolution behaves the same, and change it when it doesn't.

resolveImport also accepts a bare resolve function. The session-level one is wrapped once at construction, so its identity is stable; a bare function passed per call gets a fresh identity every call, and so never cache-hits.

When neither AnalysisSessionOptions.resolveImport nor a per-call SetFileOptions.resolveImport is supplied, the session builds a default from TypeScript module resolution and the merged compiler options on first use. It sees files that exist only in the session, even in directories absent from disk; a custom resolver must handle in-memory files itself to get dependency edges for them.

Context files
#

By default a session also ingests the in-project files its sources import that you didn't supply (transitively, skipping node_modules and dot-directories), so edits to them, like internal/ modules, stay live instead of being read from disk once. These context files emit no modules and add no edges. Their imports always go through lex+resolve, so when the closure finds files, even a fully pre-resolved session builds the default resolver (unless you supply resolveImport). analyze() turns the closure off; analyzeFromFiles keeps it on.

That includes source files, such as a component left out of package.json exports, or the rest of the project when you hand over one component. The type checker can only read a component through its transformed form, so without the ingest every type drawn from that component would be any. Such a file still emits no module until you supply it yourself. Each setFile/setFiles call sets the role of its files: they're inputs by default, so to forward an edit to a context file without turning it into a module, pass {context: true}. With the closure off, as in analyze(), pass every component the checker needs.

Diagnostics: ingest-time vs query-time
#

Diagnostic kinds have two lifecycles:

  • Ingest-time (transform_failed, source_map_failed, import_parse_failed, resolver_failed): returned from setFile / setFiles and kept with the file until it is re-ingested or deleted. A resolver_failed also clears once a later batch resolves its specifier.
  • Query-time (the rest): recomputed and returned by every query call.

query() does not include ingest diagnostics, and setFile / setFiles return only those for the files you passed (not context-closure files). allIngestDiagnostics() returns the complete set for every owned file:

const queryResult = session.query(); const fullDiagnostics = [ ...session.allIngestDiagnostics(), ...queryResult.diagnostics, ];

It's cheap, so long-lived consumers can republish the full picture every cycle without tracking per-batch returns. The Vite plugin does this on every dev re-analysis.

Discovery-time diagnostics (module_unreadable) are a third category. Sessions don't run discovery, so if you do, keep those diagnostics yourself and merge them into what you publish (see discoverSourceFiles).

Worked example: incremental loop
#

An LSP-style edit/query loop. Each setFile updates one file; query reanalyzes, reusing parsed ASTs and svelte2tsx output for unchanged files.

import {createAnalysisSession, createSourceOptions, hasErrors} from 'svelte-docinfo'; const session = createAnalysisSession({ sourceOptions: createSourceOptions(process.cwd()), }); // Initial population. await session.setFiles([ {id: '/abs/src/lib/a.ts', content: '...'}, {id: '/abs/src/lib/b.ts', content: '...'}, ]); // Edit: one file changed. const {changed} = await session.setFile({ id: '/abs/src/lib/a.ts', content: '... new content ...', }); if (changed) { const {modules, diagnostics: pass} = session.query(); const all = [...session.allIngestDiagnostics(), ...pass]; if (hasErrors(all)) { // surface to the editor } } // Tear down. session.dispose();

For HMR and file watchers, pass all changed files to one setFiles call rather than looping setFile: a batch resolves imports in parallel.

build tools #

svelte-docinfo is build-tool agnostic: you hand it files as SourceFileInfo objects, from disk, a build pipeline, or editor buffers. This page covers embedding analysis in a bundler, watcher, or editor tool, beyond the JS API basics.

Apart from discovery in analyzeFromFiles, the analyzer reads the disk only for the tsconfig, for type-checker context you don't supply, and, except in analyze(), for the in-project files your inputs import that you didn't supply (context files).

SourceFileInfo
#

analyze and the session's setFile / setFiles take SourceFileInfo, and discoverSourceFiles returns it:

interface SourceFileInfo { id: string; // absolute path (native ok at boundary) content: string; // file contents dependencies?: ReadonlyArray<string>; // optional: pre-resolved deps }
  • id: absolute path. Native Windows paths are accepted (see Paths).
  • content: required; inputs are never read from disk.
  • dependencies: optional absolute paths. When supplied, the session skips its own import parsing for this file (see Pre-resolved dependencies).

Reverse edges (dependents) are always computed by the analyzer.

discoverSourceFiles (standalone)
#

discoverSourceFiles runs file discovery without analysis, for tools that need the source set up front (watcher registration, counts, pre-flight checks) and analyze separately.

import {discoverSourceFiles, createSourceOptions} from 'svelte-docinfo'; const {files, diagnostics} = await discoverSourceFiles({ sourceOptions: createSourceOptions(process.cwd()), // discovery: 'auto' | 'exports' | 'glob' (default 'auto') // include: ['src/**/*.ts'] (forces glob under 'auto') // distDir: 'dist' (for exports discovery) }); // files: Array<SourceFileInfo> — content already loaded from disk // diagnostics: module_unreadable for any file the exports map names // but readFile failed on (permission denied, FS error)

The strategies are the ones discovery describes.

Unlike analyzeFromFiles and the Vite plugin, standalone discovery doesn't widen sourcePaths to cover include, so files outside src/lib would be dropped at analysis. To keep them, build the options with createSourceOptionsWithInclude (from svelte-docinfo/source-config.js), passing the same include.

Session consumers own the discovery-time module_unreadable diagnostics, since sessions don't run discovery (analyzeFromFiles merges them for you). Their message embeds the filesystem error's absolute path, so pass them through normalizeDiagnosticPaths (from svelte-docinfo/analyze-core.js) before publishing.

Pre-resolved dependencies (fast path)
#

Build tools with their own dependency graph (Gro's filer, Rollup's bundle graph, webpack's module graph) can hand it over in SourceFileInfo.dependencies as absolute paths. The session then skips import parsing and resolution for that file.

import type {SourceFileInfo} from 'svelte-docinfo'; // inside your build-tool integration const files: Array<SourceFileInfo> = [...filer.modules].map(([id, mod]) => ({ id, content: mod.content, dependencies: [...mod.dependencies.keys()], // absolute paths })); await session.setFiles(files);

A file re-ingested with the same content and an element-wise equal dependencies array is a cache hit, so building a fresh array per call is fine. See Cache-hit semantics.

Trust contract
#

Pre-resolved dependencies are trusted: the session doesn't check them against content. A buggy upstream resolver goes unnoticed:

  • Edges in dependencies but absent from content are accepted.
  • Imports in content but missing from dependencies are omitted.

Neither case emits a diagnostic, because legitimate sequences across batches (declaring a dependency on a file that is set later, or later deleted) would be flagged too. The default lex+resolve path always follows the actual imports, so use it if you don't fully trust your dependency source.

Type-only edges
#

With pre-resolved dependencies, you decide whether import type {X} from './x' counts as a dependency. Two common stances:

  • Keep type-only edges: what the default lex+resolve path does, for import type, inline type specifiers, and type-only re-exports like export type {X} from.
  • Drop type-only edges: what Gro's filer does, so the output reflects the runtime graph only.

Switching from lex+resolve to Gro's graph therefore removes type-only edges from ModuleJson.dependencies and dependents.

Custom import resolution
#

Without pre-resolved dependencies, the session parses import specifiers from content and resolves them with TypeScript module resolution and your tsconfig. To match the rest of your build instead, pass an ImportResolver as resolveImport; see the session guide.

Paths
#

Native paths are accepted at the API boundary, so Windows callers can pass C:\repo\src\lib\foo.ts. Every path in the output, and the session's list(), is POSIX form (forward slashes). Drive-letter case and \\?\ prefixes aren't normalized.

architecture #

svelte-docinfo analyzes its own source and draws the result below. Each node is one module under src/lib/ (the index.ts barrel left out); each arrow is an internal import. Click a module to open its API page.

How to read it
#

  • Arrows point from importer to imported: X depends on Y. Reads with gravity, so dependencies fall downward toward the foundation.
  • Layers are assigned by longest-path-from-sink. A module's layer is one plus the deepest layer it transitively depends on. Sinks (no internal imports) land at the bottom.
  • Hover a module to isolate its immediate neighbors. Edges split by direction: what the module depends on and what depends on it.

What the layers say
#

The bottom row is the modules that import nothing else in the library: path and error helpers, concurrency caps, logging, the schema helpers, and the Svelte script scanners. The middle rows are the per-kind TypeScript extractors and the file-system helpers. The top rows are the orchestrators: the persistent session on top of core analysis, then the one-shot wrappers and the Vite plugin (both built directly on the session), then the CLI and its main.ts entry.

Across 37 modules and 166 internal imports, the graph is naturally acyclic, so no back-edges had to be reversed to lay it out.

How this was drawn
#

The layout is precomputed at build time by dependency_graph.gen.json.ts, which calls analyzeFromFiles on this project and runs a Sugiyama-style layered layout: longest-path-from-sink for layer assignment, dummy nodes on long edges, median-heuristic crossing reduction. The result is a small JSON sibling the Svelte component renders to SVG. No layout libraries, just a few hundred lines of layout code.

output format #

svelte-docinfo outputs JSON describing your project's exported API. Modules contain declarations, and some declarations contain members or props. To see it in practice, jump to the examples.

Top-level structure
#

Every surface returns the same envelope, AnalyzeResultJson: the JS API (analyze, analyzeFromFiles, a session's query()), the CLI's JSON, and the Vite plugin's virtual module.

{ modules: ModuleJson[], diagnostics: Diagnostic[] }

diagnostics is covered in diagnostics. The CLI emits compact JSON, so an empty project prints {}; parse it with parseAnalyzeResult to restore the defaults.

ModuleJson
#

A ModuleJson describes a single source file and its exports:

  • path: file path relative to the source root (e.g., "math.ts")
  • declarations: exported items from this module
  • moduleComment: the prose of the file-level @module comment, if it has any
  • examples, deprecatedMessage, seeAlso, since, internalMessage: that comment's tags, as on a declaration (see @module)
  • dependencies: paths of modules this file imports
  • dependents: paths of modules that import this file
  • starExports: export * from './module' targets
  • reExports: same-name re-export edges ({name, module, typeOnly, sourceLine}), the forward view of alsoExportedFrom (see re-exports)
  • externalReExports: direct re-exports from packages ({name, specifier, originalName?, typeOnly, sourceLine})
  • externalStarExports: export * from 'pkg' specifiers as written
  • partial: true when the module is a placeholder for a .svelte file that svelte2tsx failed to transform (see transform_failed)

Array fields are omitted from JSON when empty and default to [] after parsing.

DeclarationJson
#

Each declaration is a DeclarationJson, a discriminated union on kind with nine variants:

  • "function": adds parameters, returnType, returnTypeInfo, returnDescription, overloads
  • "variable": adds typeInfo, optional defaultValue (from @default), and reactivity (see Reactivity)
  • "class": adds members, extends, implements, externalTypes
  • "interface": adds members, extends, externalTypes, mergedValue
  • "type": adds typeInfo, members, externalTypes, mergedValue
  • "enum": adds members (enum values)
  • "component": adds props, externalTypes, acceptsChildren, cssCustomProperties, lang (Svelte components). acceptsChildren is set by a Snippet-typed children prop, template use of children, or a legacy component's default <slot />
  • "snippet": adds parameters (exported Svelte template snippets)
  • "namespace": adds module, the path of the module projected by export * as ns from './x'

A name declared as both a value and a type, like the schema pattern export const Foo = z.strictObject({...}) + export type Foo = z.infer<typeof Foo>, produces one declaration. The type meaning documents like its un-merged equivalent (structure, members, typeInfo), and mergedValue: true marks that the name is also a runtime value, so generateImport emits import instead of import type. JSDoc falls back to the value declaration's comment when the type has none, and @nodocs on either declaration excludes the pair. In JS, a const Foo with a same-named @typedef merges the same way.

Shared fields on all variants:

  • name, kind: identity. Default exports carry name === "default", except Svelte components, which take their filename-derived name (see re-exports)
  • docComment: JSDoc comment text
  • typeSignature: the full type as a string, rendered by the TypeScript checker (see module paths)
  • sourceLine: 1-based line number in the source file
  • modifiers: e.g., "readonly", "static", "getter"
  • genericParams: type parameters with constraints and defaults
  • examples, deprecatedMessage, seeAlso, throws, since: from standard JSDoc tags
  • internalMessage: from @internal, a marker rather than an exclusion (empty string for a bare tag)
  • mutates: from @mutates, a Record<string, string> of target to description (empty for a target with no description). See tags
  • alsoExportedFrom: modules that re-export this declaration
  • aliasOf: the canonical {module, name} of a renamed re-export
  • partial: true when extraction failed partway, so the data is incomplete

Declarations tagged @nodocs are excluded from the output and from the opt-in duplicate-name check.

Props and members a package contributes (like HTMLButtonAttributes extended by a component's props) are left out, and the package type is named in externalTypes, unless the $props() destructuring names them.

typeInfo, a structured TypeJson tree beside the flat type string, appears on variables, type aliases, variable members, component props, parameters, and tuple elements; functions, function members, overloads, and callback props carry returnTypeInfo. See structured types.

MemberJson
#

Classes, interfaces, types, and enums list MemberJson entries in members, a discriminated union on kind with three variants:

  • "function": methods and call signatures. Adds parameters, returnType, returnTypeInfo, returnDescription, overloads, and optional defaultValue (from @default, documenting the behavior when a callable option is omitted). A property typed by an external function (run?: typeof spawn) is a "variable" with the flat type text rather than the package's overloads and docs; a mixed callable keeps its local signatures
  • "constructor": class constructors and construct signatures. Adds parameters, overloads
  • "variable": properties, accessors, index signatures, and enum values. Adds optional defaultValue (from @default), typeInfo, and reactivity for class fields initialized with a Svelte rune

Function and variable members also carry optional when the property or method is optional (?, or a mapped modifier such as Partial).

An interface lists its own members, then what each computed extends entry contributes, as the same type would list them as a type alias's members: interface Foo extends Omit<Base, 'a'> {} lists Base's other properties, and interface Foo extends z.infer<typeof S> {} the schema's. Members inherited from a named interface or class stay with that base, which extends names.

Nesting is exactly one level deep: members never contain members.

Member name is the source identifier, or a synthesized name where none exists: "constructor" (class constructor), "(construct)" and "(call)" (construct and call signatures on an interface or type alias), and index-signature names like "[key: string]" (the parameter name as written for an interface's own; a synthesized key for type aliases and for what an interface's computed heritage contributes).

ComponentPropJson
#

Component declarations have a props array of ComponentPropJson entries, in source order, followed by any props an external type declares that the $props() destructuring names, in destructuring order (a legacy export let component orders by its exports). Each entry has:

  • name, type: prop name and TypeScript type
  • typeInfo: structured TypeJson tree, when it adds structure
  • optional: whether the prop is optional
  • description: from JSDoc on the prop
  • defaultValue: the default's source text, else the @default tag text
  • bindable: set when the prop is declared with $bindable(), so <Foo bind:value /> works. Every prop of a legacy export let component is bindable
  • parameters: structured parameters for snippet-typed props (e.g., Snippet<[text: string]>) and callback props; absent when there are none
  • returnType and returnTypeInfo: a callback prop's return type (onpick?: (value: string) => void, or a project alias for one). Its presence is what marks a prop as a callback, including one with no parameters; snippets never carry it. Only call signatures your project declares count, so a prop typed wholly by a package (MouseEventHandler<HTMLButtonElement>, a Component) has neither field
  • examples, deprecatedMessage, seeAlso, throws, since, internalMessage, mutates: from the prop's own doc comment. On a prop, mutates declares what the component writes into the object or array it's handed

ComponentCssPropertyJson
#

A component's cssCustomProperties lists its styling API as ComponentCssPropertyJson entries, documented ones first (see component styling):

  • name: the property as written, -- included
  • description: from a @cssprop tag
  • syntax: a tag's braced syntax, else an @property rule's syntax descriptor
  • fallback: what the style gives the property when unset, as source text: an @property rule's initial-value, else the first read's fallback (var(--a, var(--b)) gives var(--b))
  • default: a @cssprop tag's bracketed default, the author's claim beside fallback; a renderer wanting one value takes default ?? fallback
  • sourceLine: the first read's line, or the tag's for a property never read
  • documented: whether a @cssprop tag documents it

ParameterJson
#

Functions, methods, constructors, overloads, snippets, and snippet or callback props list ParameterJson entries in parameters:

  • name: parameter name (e.g., "options"; a rest parameter's dots live in rest, not the name)
  • type: resolved TypeScript type as a string
  • typeInfo: structured TypeJson tree, when it adds structure
  • optional: whether a caller may omit the argument (a ?, a default, or in JS a bracketed @param {T} [b])
  • rest: whether the parameter uses rest syntax (...args)
  • description: from @param
  • defaultValue: default value expression from the source, if present, else from a bracketed @param {T} [b=0]
  • propertyDescriptions: sub-path to description, from dotted @param obj.prop tags on a named object parameter (destructured parameters aren't covered)

ParameterJson deliberately lacks the tag fields ComponentPropJson has: a prop is a named slot with its own documentation, while a parameter's @example, @deprecated, and similar tags belong on the enclosing function per the TSDoc spec. Parameters get their docs from @param only.

OverloadJson
#

Functions and constructors with multiple signatures list OverloadJson entries in overloads. Each carries only the fields that vary per signature:

  • typeSignature: the full overload signature as a string
  • parameters: this overload's parameters, with its own @param descriptions
  • returnType: return type for this overload (functions only)
  • returnTypeInfo: structured TypeJson tree for the return type, when it adds structure
  • genericParams: type parameters for this overload
  • docComment: per-overload JSDoc text, if present
  • returnDescription: from @returns on this overload

Symbol-scope tags (@example, @deprecated, and the rest) live on the parent declaration only, read from the primary overload. On a non-primary overload they emit misplaced_tag and are dropped. See Symbol-scope vs signature-scope.

Reactivity
#

reactivity appears on VariableDeclarationJson and VariableMemberJson when the initializer is a value-producing Svelte rune call: $state, $state.raw, $derived, or $derived.by. Detection is syntactic and runs on every file, so a plain .ts file is treated the same as .svelte.ts or a component script.

Only variables and class fields are annotated, not parameters or destructured bindings. $props and $bindable surface on ComponentPropJson instead.

GenericParamJson
#

Declarations and members with type parameters list GenericParamJson entries in genericParams:

  • name: type parameter name (e.g., "T")
  • constraint: extends constraint, if present
  • defaultType: default type, if present

Compact JSON
#

Output uses compact JSON via compactReplacer: empty arrays, false booleans, and undefined fields are stripped, so optional, acceptsChildren, partial, rest, bindable, and similar fields vanish at their default. The value key is exempt, so a {kind: "literal", value: false} type node survives. Parsing with parseAnalyzeResult (or parseModuleJson for one module) restores every default and validates the shape, so the round-trip is lossless. The helpers are the stable entry point; the fuz_schema schemas behind them are exported too.

Raw-JSON consumers (jq, pipelines that skip parsing) must treat absent as false: decl.optional === false fails because the key is gone. Parse first, or use truthiness checks like if (decl.optional).

Examples
#

These show the compact wire form, so empty and default fields are stripped.

A TypeScript function in math.ts:

/** Clamp a number to a range. */ export function clamp(value: number, min: number, max: number): number { return Math.min(Math.max(value, min), max); } { "modules": [ { "path": "math.ts", "declarations": [ { "name": "clamp", "kind": "function", "docComment": "Clamp a number to a range.", "typeSignature": "(value: number, min: number, max: number): number", "sourceLine": 2, "parameters": [ {"name": "value", "type": "number"}, {"name": "min", "type": "number"}, {"name": "max", "type": "number"} ], "returnType": "number" } ] } ] }

A Svelte component Card.svelte with a snippet prop, children, an exported snippet, and a styling hook:

<!-- @component A card with a customizable header. --> <script lang="ts" module> /** Default footer snippet. */ export {card_footer}; </script> <script lang="ts"> import type {Snippet} from 'svelte'; const { title, header, children, }: { title: string; /** Custom header rendering. */ header?: Snippet<[title: string]>; children?: Snippet; } = $props(); </script> <div class="card"> {#if header}{@render header(title)}{:else}<h2>{title}</h2>{/if} {@render children?.()} </div> {#snippet card_footer(text: string)} <small>{text}</small> {/snippet} <style> .card { background: var(--card_bg, white); } </style> { "modules": [ { "path": "Card.svelte", "declarations": [ { "name": "Card", "kind": "component", "docComment": "A card with a customizable header.", "sourceLine": 7, "props": [ {"name": "title", "type": "string"}, { "name": "header", "type": "Snippet<[title: string]>", "typeInfo": { "kind": "reference", "name": "Snippet", "typeArgs": [ { "kind": "tuple", "elements": [ {"name": "title", "type": {"kind": "intrinsic", "text": "string"}} ] } ] }, "optional": true, "description": "Custom header rendering.", "parameters": [ {"name": "title", "type": "string"} ] }, {"name": "children", "type": "Snippet<[]>", "optional": true} ], "acceptsChildren": true, "cssCustomProperties": [ {"name": "--card_bg", "fallback": "white", "sourceLine": 33} ] }, { "name": "card_footer", "kind": "snippet", "docComment": "Default footer snippet.", "typeSignature": "Snippet<[text: string]>", "sourceLine": 27, "parameters": [ {"name": "text", "type": "string"} ] } ] } ] }

A rune module counter.svelte.ts exporting reactive state:

export let count = $state(0); export const doubled = $derived(count * 2); { "modules": [ { "path": "counter.svelte.ts", "declarations": [ { "name": "count", "kind": "variable", "typeSignature": "number", "sourceLine": 1, "reactivity": "$state" }, { "name": "doubled", "kind": "variable", "typeSignature": "number", "sourceLine": 2, "reactivity": "$derived" } ] } ] }

A barrel index.ts that re-exports clamp from math.ts under a new name and star-exports other.ts. The rename synthesizes a declaration with aliasOf that inherits the canonical's signature and docs, the star export lands on starExports, and the dependency fields connect the modules. A same-name re-export would instead add the barrel to the canonical's alsoExportedFrom.

// index.ts export {clamp as clampNumber} from './math.js'; export * from './other.js'; // other.ts export const TAU = Math.PI * 2; { "modules": [ { "path": "index.ts", "declarations": [ { "name": "clampNumber", "kind": "function", "docComment": "Clamp a number to a range.", "typeSignature": "(value: number, min: number, max: number): number", "sourceLine": 1, "aliasOf": {"module": "math.ts", "name": "clamp"}, "parameters": [ {"name": "value", "type": "number"}, {"name": "min", "type": "number"}, {"name": "max", "type": "number"} ], "returnType": "number" } ], "dependencies": ["math.ts", "other.ts"], "starExports": ["other.ts"] }, { "path": "math.ts", "declarations": [ { "name": "clamp", "kind": "function", "docComment": "Clamp a number to a range.", "typeSignature": "(value: number, min: number, max: number): number", "sourceLine": 2, "parameters": [ {"name": "value", "type": "number"}, {"name": "min", "type": "number"}, {"name": "max", "type": "number"} ], "returnType": "number" } ], "dependents": ["index.ts"] }, { "path": "other.ts", "declarations": [ {"name": "TAU", "kind": "variable", "typeSignature": "number", "sourceLine": 1} ], "dependents": ["index.ts"] } ] }

See the types module for the full schemas, and the API reference for all exported types.

structured types #

Types come two ways. The flat strings (typeSignature, type, returnType) are the TypeScript checker's own rendering. Beside them, a TypeJson tree in typeInfo (returnTypeInfo for return types) gives the structure, for rendering types with links and highlighting.

typeInfo appears on variables, type aliases, variable members, component props, parameters, and tuple elements; returnTypeInfo on functions, function members, overloads, and callback props.

When it's present
#

A tree is absent when the flat string says everything: intrinsics, bare references, and object and function types. It's present when it adds structure: union and intersection members, a reference's type arguments, array elements, and tuple elements with their labels and ?/... markers.

A type alias's typeSignature prints only its name, so an alias carries its tree whatever the shape, except object and function types, which its members cover. Intrinsic and literal aliases (type A = string) print structurally and get no tree.

Nodes
#

The node kinds are intrinsic, literal, reference, array, tuple, union, intersection, function, object, and other.

  • Union and intersection members keep alias names. Union members follow the order the author wrote them, with null and undefined last, while the flat strings use TypeScript's internal order, so read the tree for author intent. A union with no written form (inferred, keyof, mapped) keeps TypeScript's order in both.
  • A literal's value is its runtime value, except that a bigint is its text ("1n") and a non-finite number a string ("Infinity").
  • A named generic instantiation is a reference with typeArgs (Snippet<[a: string]>), and other callables are function nodes. Object literal and function types are object and function nodes carrying the checker's text.
  • Arrays and tuples carry readonly, and the optional-property undefined is dropped, since optional: true says it.

Lost alias names
#

TypeScript drops the name of an alias over an indexed access or conditional type, like type Foo = z.infer<typeof S> or valibot's InferOutput, and prints its expanded structure wherever it's used. The tree recovers the name as {kind: "reference", name: "Foo"}, from the annotation written at that position or by matching the project's exported aliases. A name recovered by matching also carries module, the ModuleJson.path declaring it.

An exported alias neither way recovers warns alias_lost (see diagnostics). Declaring it as an interface keeps its name: interface Foo extends z.infer<typeof S> {}, which documents the inferred properties as its members.

Rendering
#

typeJsonToTokens flattens a tree into tokens, deciding spacing, separators, and parentheses, so a renderer only decides what each token looks like: link name tokens, highlight code tokens, and print text as-is. typeJsonToText joins them into a plain string.

import {typeJsonToTokens} from 'svelte-docinfo/declaration-helpers.js'; if (declaration.typeInfo) typeJsonToTokens(declaration.typeInfo); // [{kind: 'name', name: 'Map'}, {kind: 'text', text: '<'}, // {kind: 'code', text: 'string'}, {kind: 'text', text: ', '}, // {kind: 'name', name: 'Tome'}, {kind: 'text', text: '>'}]

Module paths
#

TypeScript prints a module object as typeof import("…") with an absolute path. svelte-docinfo rewrites the path in every type text, flat and structured: a module in the output becomes its ModuleJson.path, usable as a lookup key, a package its path below node_modules/, and any other file a path relative to the project root. In a tree, a module object is an other node.

re-exports #

A declaration is documented once, in the module that declares it, and re-exports point to it. An imported binding exported again (import {a} from './x'; export {a}, or export default of an import) counts as the export … from it stands for.

Encodings
#

  • Same name (export {a} from './x'): the declaration's alsoExportedFrom lists the re-exporting modules, and each of those lists the edge in ModuleJson.reExports ({name, module, typeOnly, sourceLine}), with module naming the declaring module through any chain.
  • Renamed (export {a as b} from './x'): a full declaration b in the re-exporting module, with aliasOf: {module, name: "a"} and the local specifier's sourceLine.
  • Star (export * from './x'): x's path in starExports, with no per-name entries. If x isn't documented itself, its names document in the re-exporting module instead.
  • Namespace (export * as ns from './x'): a kind: 'namespace' declaration whose module names x; read its members from that module.
  • Packages (export {a} from 'pkg', export * from 'pkg'): externalReExports and externalStarExports, with the specifier as written.

A re-export of a symbol from a module that isn't documented (like an internal/ one) is a full declaration with aliasOf, even under the same name, since there's no declaration to link to; its aliasOf.module names a module the output lacks. A re-export statement with its own JSDoc also gets a declaration of its own, its docs over the original's, and @nodocs on one drops it entirely.

A Svelte component svelte2tsx failed to transform re-exports as a partial component.

Default exports
#

export default and export {a as default} carry name: "default", except Svelte components, which take their filename's name. A rename out of the default slot (export {default as A} from './x') carries name: "A" and aliasOf: {module, name: "default"}, or the component's name for a Svelte component.

A module's full export surface
#

resolveExportSurface combines a module's declarations, re-exports, and stars with ES semantics: explicit exports shadow star names, names ambiguous between stars drop, and default never projects. It reports stars it can't see into rather than guessing.

import {resolveExportSurface} from 'svelte-docinfo/postprocess.js'; const surface = resolveExportSurface(modules, 'index.ts');

The output format examples include a barrel with a rename and a star.

tags #

svelte-docinfo extracts TSDoc/JSDoc tags from source comments into structured fields on the output. This page lists every parsed tag, where its value lands, and which symbol receives it. JSDoc's type tags (@type, @typedef, @template, @overload) are covered in JS and JSDoc.

The set is the common tags of JSDoc and the TSDoc spec, plus the custom @nodocs and @mutates, and the Custom Elements Manifest's @cssprop for a component's CSS custom properties. Where the standards spell a tag differently, both spellings work (@default / @defaultValue, @return / @returns, @cssprop / @cssproperty).

Inline tags like {@link} are kept in the extracted text for the consumer to render. TypeScript reprints {@link A|b} as {@link A |b}; @see keeps its source text exactly. Please open an issue if a tag you need is missing or off-spec.

Supported tags
#

TagWhere it lands
@paramParameterJson.description on the matching parameter. Dotted keys (obj.prop) land in propertyDescriptions. Keys matching no parameter emit unknown_param
@returnsreturnDescription on functions, function members, and per-overload OverloadJson. @return (JSDoc synonym) parses identically
@throwsthrows array on the parent declaration. A braced type (@throws {TypeError} - description, unions included) lands in type; the description may be empty or multiline. Without braces the first word is the type (@throws TypeError if …), so @throws if … records if as the type. A lone unbraced word is the description
@exampleexamples array on the parent declaration
@deprecateddeprecatedMessage on the parent declaration. An empty body still marks the symbol deprecated
@internalinternalMessage on the parent declaration, member, or component prop. A marker, not an exclusion (see @internal)
@seeseeAlso array, each entry in its source form (URLs, {@link}, module names)
@sincesince string on the parent declaration
@defaultdefaultValue on variable declarations and on variable and function members (for a function member, the behavior when the callback is omitted). Also fills ComponentPropJson.defaultValue when the prop has no destructuring default. Never on top-level functions, overloads, or constructors. @defaultValue and @defaultvalue parse identically
@mutatesmutates record of target to description (see @mutates)
@nodocsExcludes the declaration from output and from the opt-in duplicate-name check (see @nodocs). Applies to declarations and export statements only: in a @module comment it warns misplaced_tag and is dropped, and on a member or component prop it silently does nothing
@csspropA Svelte component's CSS custom property, in ComponentDeclarationJson.cssCustomProperties (see component styling). Read from the component's doc comment only; on any other declaration or in a @module comment it warns misplaced_tag and is dropped. @cssproperty parses identically
@moduleMakes the comment document the file: its prose becomes ModuleJson.moduleComment and its tags the module's own fields, instead of a declaration's doc (see @module)

Symbol-scope vs signature-scope
#

Two tags vary per overload signature; the rest describe the symbol as a whole.

  • Signature-scope: @param and @returns. These flow to the matching overload's parameters[i].description / returnDescription. Each overload can carry its own.
  • Symbol-scope: @example, @deprecated, @internal, @since, @see, @throws, @mutates, @default, @nodocs. These describe the symbol as a whole and live on the parent declaration only.

Put symbol-scope tags on the first overload: its JSDoc documents the symbol, while JSDoc on a later overload documents only that overload, and a symbol-scope tag there warns misplaced_tag. JSDoc on the implementation is hidden and warns implementation_doc_hidden. For JS @overload tags, see JS and JSDoc.

/** * @example double(2) // 4 * @deprecated use `scale` instead */ export function double(n: number): number; export function double(n: bigint): bigint; export function double(n: number | bigint): number | bigint { return (n as any) * 2; }

@param matching and unknown_param
#

@param keys are matched against parameter names, and the leading - separator is stripped from the description. A dotted key (obj.prop) documents a property of a named object parameter.

Dotted keys land in ParameterJson's propertyDescriptions, keyed by sub-path (obj.prop → prop, obj.a.b → a.b). The property path isn't checked against the parameter's type. Destructured parameters (fn({a, b}: T), which TypeScript names __0) can't be matched by name, so they aren't covered.

A key whose name (or dotted root) matches no parameter drops its description and emits unknown_param with the key, usually a typo or a stale doc after a rename.

@mutates
#

A non-standard tag for documenting mutations to parameters or external state: @mutates target - description. The target is everything before the first - (space-hyphen-space), so unlike @param it can be a hyphenated name or a phrase. Targets are not validated against the parameters, and backticks are stripped, so `options` and options are the same key:

  • a parameter name: @mutates options - sets defaults in place
  • a compound path: @mutates this.cache - inserts the result
  • a multi-word external reference: @mutates `app_settings` row - bumps the revision
  • a bare target with no description: @mutates `this`

The output is a Record<string, string> of target to description, empty for the bare form. Without a separator, the first line is the target and any following lines are the description.

On a component prop, @mutates declares that the component writes into the object or array it's handed, the same contract a function declares for a parameter: @mutates items - appends the selected entry. Reassigning a prop isn't a mutation in this sense; bindable covers that. The two combine: Svelte warns when a component mutates state the parent didn't bind, so an in-place write into a parent's $state usually sits on a $bindable prop.

@internal
#

@internal marks a symbol as not stable public API, per TSDoc. It lands as internalMessage on declarations and members of every kind, and on component props: an empty string for a bare tag, or the trailing prose (@internal used during development), kept separate from docComment.

It's a marker, not an exclusion: the declaration stays fully documented, so consumers can badge or filter it. To remove a declaration from output, use @nodocs; to omit whole modules, use exclude patterns.

@nodocs
#

@nodocs on a declaration removes it from the output entirely. It doesn't apply to members or component props, which stay in the output with no warning. It also affects:

  • Duplicate checking (opt-in, via onDuplicates): a hidden helper named parse can coexist with a public parse in another module without duplicate_declaration.
  • Re-exports: on a re-export statement, it drops the alsoExportedFrom link, any synthesized alias, and the module's reExports, starExports, or externalReExports / externalStarExports entry. The canonical declaration is unaffected. In JS, a @nodocs in a @typedef block above the statement hides the typedef instead, and the re-export stays.
  • Merged value+type pairs: a const Foo + type Foo pair is one symbol, so the tag on either excludes it.

@cssprop
#

@cssprop {<syntax>} [--name=default] - description documents a CSS custom property in a Svelte component's doc comment, in the Custom Elements Manifest form; the syntax and brackets are optional. A tag naming no -- property warns malformed_tag and is dropped; a second tag for the same name warns duplicate_tag and the first wins. The bracketed default lands in default, beside the fallback the style gives; when the two disagree, cssprop_default_mismatch warns. See component styling.

@module
#

A comment tagged @module documents the file, not the next declaration. Its prose lands on ModuleJson.moduleComment and never in a declaration's docComment. Its tags parse as a declaration's do, into the module's fields of the same names: examples, deprecatedMessage, seeAlso, since, and internalMessage. Tags that only describe a declaration (@param, @returns, @mutates, @throws, @default, @nodocs, @cssprop) warn misplaced_tag and are dropped, and unknown tags drop silently. A comment of tags alone has no moduleComment. In a module comment only an @ that starts a line starts a tag, so a mid-line @ stays in the text. The comment counts as a module comment only when a line starts with @module (a one-line /** @module */ counts); in /** Text @module */ the text documents the next declaration instead.

/** * Date math utilities. * * @see https://tc39.es/proposal-temporal/ * @since 0.2.0 * @module */ export function add_days(d: Date, n: number): Date { /* ... */ }

A Svelte file's module comment comes from the first of: a JSDoc @module in the instance <script>, one in <script module>, and an HTML comment with @module at a line start. More than one warns duplicate_comment.

A component's doc comment is its JSDoc above $props(), else its HTML @component comment, the first with @component at a line start. A JSDoc with prose beside an HTML comment warns duplicate_comment. Editor hover takes the last comment containing @component anywhere, so component_comment_mismatch warns when the two picks differ.

Tag-related diagnostics
#

Tag problems surface as warnings: misplaced_tag, implementation_doc_hidden, unknown_param, unknown_cssprop, and duplicate_comment, described in the sections above and in diagnostics. The parser is tsdoc.ts.

diagnostics #

Analysis accumulates errors and warnings without halting, as an array of Diagnostic entries alongside modules in the result. Identical diagnostics are reported once.

Two-tier error model
#

Accumulated (non-fatal): appended to the diagnostics array while analysis continues. Covers type resolution failures, member or prop extraction failures, and JSDoc tag misuse. The result is still valid (see partial).

Thrown (fatal): setup-level problems throw from the public entry points:

  • a missing or unloadable tsconfig.json: one that fails to parse, or an extends target that doesn't exist, like SvelteKit's generated tsconfig before svelte-kit sync has run
  • Svelte older than 5
  • invalid source options: empty sourcePaths, a path or absolute pattern outside projectRoot, or sourcePaths not under sourceRoot
  • conflicting options: discovery: 'exports' with include, or resolveImport with resolveDependencies: false
  • discovery: 'exports' when exports is missing or resolves to no files, or when the source paths share no common prefix
  • a name collision under onDuplicates: 'throw'

Wrap analyze / analyzeFromFiles, or createAnalysisSession and query, to handle these. svelte2tsx failures don't throw; they surface as transform_failed.

Shape
#

diagnostics is a plain Array<Diagnostic> beside modules in AnalyzeResultJson. It round-trips through JSON.stringify and parseDiagnostics. Each entry carries:

  • kind: discriminant, one per failure mode (see table below)
  • severity: "error" or "warning"
  • file: POSIX-form and relative to the project root, with no leading ./; a file outside the project takes the ../ form. Join with projectRoot to get the absolute path. It names a file, not a module: ModuleJson.path is relative to sourceRoot, so don't look modules up by file.
  • line, column: 1-based, optional. Absent when there's no precise position (e.g., a module-level skip). Positions in Svelte files point at the original .svelte source; one that can't be mapped is omitted
  • message: human-readable description, with project-root paths made relative like file
  • fields specific to the kind: symbolName, className, tagName, etc.

Diagnostic kinds
#

Severity is fixed per kind: every kind is a warning except transform_failed and module_unreadable, which are always error.

The table below marks each kind's lifecycle. Ingest-time kinds surface when files are ingested and persist with the file until it is re-ingested or deleted, discovery-time comes from file discovery, and unmarked kinds are recomputed on every analysis pass. See the session guide for how they combine.

kindWhen it fires
type_extraction_failedTrigger: type resolution threw on a declaration or member. Consequence: it's included with partial: true; typeSignature and typeInfo may be absent.
signature_analysis_failedTrigger: function or method signature analysis threw. Consequence: declaration included with partial: true; parameters and overloads may be empty.
class_member_failedTrigger: one member of a class couldn't be analyzed. Consequence: member included with partial: true; siblings still extract normally.
svelte_prop_failedTrigger: a Svelte component prop type couldn't be resolved. Consequence: that prop's type falls back to "any"; if the whole props type on $props() is unresolvable, props is empty. When the check for a children snippet fails, only template use of children can set acceptsChildren. A legacy export let component whose svelte2tsx output has no recognized props type reports each exported prop, at its export's line, and has empty props.
module_skippedTrigger: a whole module was skipped during analysis. reason is "not_in_program" (the file wasn't in the TypeScript program), "no_analyzer" (unsupported extension), or "requires_program" (a Svelte file passed to analyzeModule directly). Consequence: module absent from modules[].
module_unreadableTrigger: a file named by package.json exports couldn't be read (permission denied, FS error). Consequence: the file is dropped from the discovered set. Discovery-time.
import_parse_failedTrigger: import scanning threw during dependency resolution (not expected: the parse tolerates malformed source). Consequence: the module's dependency edges are dropped; the module still analyzes. Ingest-time.
duplicate_commentTrigger: two sources supplied a comment for the same target: an HTML @component comment plus script JSDoc, either with prose or a tag (commentType: "doc_comment"), or several @module sources in a Svelte file ("module_comment"). Consequence: the higher-priority source wins whole: script JSDoc for doc comments, its prose and tags replacing the HTML comment's even when the JSDoc holds tags alone; instance <script>, then <script module>, then HTML for module comments, skipping one that holds only dropped tags.
component_comment_mismatchTrigger: svelte2tsx, and so editor hover, would document a component with a different HTML comment than the analyzer: it takes the last comment containing @component anywhere, the analyzer the first with @component at a line start. A second component comment or a passing mention (a backticked @component in a module comment) causes it. Consequence: the analyzer's pick documents the component, and line points at svelte2tsx's; reword that comment's @component so the two agree.
misplaced_tagTrigger: a symbol-scope tag (@example, @deprecated, @internal, @since, @see, @throws, @mutates, @default, @nodocs) on a non-primary overload signature, or a tag that only describes a declaration (@param, @returns, @mutates, @throws, @default, @nodocs, @cssprop) in a @module comment (then functionName is absent), or a @cssprop on an exported declaration other than a component (functionName names it). Consequence: the tag is dropped. On an overload, move it to the primary signature; a @cssprop belongs in the component's doc comment. To omit a module, use exclude patterns rather than @nodocs. Overloads a member borrows through its type (m: typeof fn) never warn; the lending function's own analysis checks its tags.
implementation_doc_hiddenTrigger: an overloaded function, method, or constructor documents its implementation: a TS implementation's JSDoc, or in JS a block with no @overload tag beside the ones that have one, carrying prose or doc tags (a block of types alone doesn't fire). Consequence: the implementation's docs are hidden, as TypeScript's hover hides them, and an implementation @nodocs hides nothing. Move the docs to the first overload. functionName names the function.
unknown_paramTrigger: a @param key matches no parameter (a typo, or a stale doc after a rename). Consequence: the description is dropped.
unknown_csspropTrigger: a component's @cssprop names a property (propertyName) the component never reads through var(), in its <style> or its markup's static style text: a typo, a stale tag, or a property it leaves for its children (reads aren't resolved across components). line is the tag's. Not emitted when the style isn't read (css_parse_failed, css_lang_unsupported). Consequence: none; the entry stays in cssCustomProperties, documented: true.
cssprop_default_mismatchTrigger: a component's @cssprop documents a default ([--a=1px], carried in default) that differs from the fallback its style gives the property (fallback: the first var() read's, or an @property rule's initial-value), compared as text with whitespace runs collapsed, so an equivalent spelling (red against #f00) warns too. line is the read's. Not emitted when the style isn't read. Consequence: none; the entry keeps both values.
malformed_tagTrigger: a @cssprop (tagName) in a component's doc comment whose text names no -- property: a name without the dashes, an unclosed {…} or […], an empty tag. line is the tag's. On any other declaration the tag warns misplaced_tag instead. Consequence: the tag is dropped.
duplicate_tagTrigger: a @cssprop (tagName) in a component's doc comment repeats a property (key) an earlier tag names. line is the later tag's. Consequence: the first tag wins; this one is dropped.
alias_lostTrigger: TypeScript dropped the name of an exported type alias (aliasName) whose right-hand side is an indexed access or conditional, like z.infer<typeof S> or valibot's v.InferOutput<typeof S>, and svelte-docinfo can't recover it. Literal-only unions (z.enum, v.picklist) and brand intersections don't warn, since they read fine expanded, and neither do @nodocs aliases. Consequence: unannotated positions document the alias's structure instead of its name. Where applicable, a nominal symbol (interface Foo extends z.infer<typeof S> {}) restores it, and documents the inferred properties as its members.
commonjs_unsupportedTrigger: a JS module that TypeScript doesn't bind as a module (no import/export under bundler/esnext) exports through CommonJS (module.exports = …, exports.x = …), which isn't modeled. Under node16/nodenext or moduleDetection: 'force' the checker binds CommonJS exports itself, and its named exports (exports.x, module.exports = {a, b}) document without this warning; a module.exports = of a function or literal documents nothing. Consequence: the module is in modules[] with no declarations; its module comment still reads. Converting it to ES exports documents it.
css_parse_failedTrigger: Svelte's parser rejects a component that has a <style>, or a var() in its markup: malformed CSS, two top-level styles, or markup its loose parsing can't absorb (any template error under a Svelte before 5.13). Consequence: the component emits without cssCustomProperties beyond its @cssprop tags; line/column are the parser's.
css_lang_unsupportedTrigger: a component's <style> names a preprocessor language (lang="scss", lang="postcss", type="text/less"), carried in lang. Consequence: the style isn't read, so the component emits without cssCustomProperties beyond its @cssprop tags.
duplicate_declarationTrigger: a declaration name appears in more than one module, and the opt-in onDuplicates check is on (for packages with a flat export namespace). declarationName and modules name the conflict; modules holds ModuleJson.path values, unlike file. Consequence: none beyond the diagnostic, unless onDuplicates is 'warn' (logs) or 'throw'.
transform_failedTrigger: svelte2tsx threw on a .svelte file. Consequence: the file's ModuleJson is a placeholder (partial: true, empty declarations). Its default and namespace re-exports document as partial components or namespaces (a <script module> name stays a bare variable), and a star over it is one resolveExportSurface reports unresolved. Ingest-time.
source_map_failedTrigger: the source map svelte2tsx produced for a .svelte file couldn't be parsed. Consequence: analysis continues without position mapping: other diagnostics for the file omit line/column, and declaration sourceLines point into the generated TypeScript. Ingest-time.
resolver_failedTrigger: the import resolver threw on specifier (as opposed to returning null for an external). Consequence: the dependency edge is deferred and retried when a later setFile / setFiles adds files or the importer changes; the diagnostic clears once it resolves. Ingest-time.

Use byKind to narrow to one variant with typed fields:

import {byKind} from 'svelte-docinfo'; for (const d of byKind(diagnostics, 'misplaced_tag')) { // d.tagName, d.functionName, d.file, d.line are typed console.warn(`${d.functionName}: move @${d.tagName} to the primary overload`); }

severity vs partial
#

severity says how loud to be about a problem. partial: true says a declaration or member has incomplete data, from type_extraction_failed, signature_analysis_failed, or class_member_failed, and a ModuleJson is partial when it's a transform_failed placeholder. svelte_prop_failed sets no flag; the prop's type falls back to any. Check partial directly instead of matching diagnostics by file and line.

Helpers
#

Read helpers for the diagnostics array:

See diagnostics.ts for the schemas and helpers.

Consuming diagnostics
#

The CLI includes diagnostics in its JSON output, omitted when empty (parseAnalyzeResult restores []). Progress messages go to stderr; structured diagnostics appear only in the JSON:

npx svelte-docinfo | jq '.diagnostics | group_by(.kind) | map({kind: .[0].kind, count: length})'

Programmatically:

import {analyzeFromFiles, errorsOf, formatDiagnostic, byKind} from 'svelte-docinfo'; const {modules, diagnostics} = await analyzeFromFiles({projectRoot: process.cwd()}); // File paths in diagnostics are already project-relative. for (const d of errorsOf(diagnostics)) { console.error(formatDiagnostic(d)); } // Specific check: any @param typos? const stale = byKind(diagnostics, 'unknown_param'); if (stale.length) { console.warn(`${stale.length} stale @param tag(s); fix or remove`); }

The Vite plugin's virtual module exports diagnostics too, so an app can render doc warnings without re-running analysis:

import {modules, diagnostics} from 'virtual:svelte-docinfo'; // the diagnostics subpath keeps the TypeScript compiler out of the client bundle import {hasErrors} from 'svelte-docinfo/diagnostics.js'; if (hasErrors(diagnostics)) { // surface in the UI or fail the build }

api #

Browse the full api docs.