api #

static analysis for TypeScript and Svelte

38 modules · 388 declarations

Modules
#

AliasLostDiagnostic
#

diagnostics.ts view source

value + type

An exported type alias loses its name at use sites.

The alias's right-hand side (an indexed access or conditional — z.infer<typeof S>, valibot's InferOutput) resolves to a pre-existing interned type that TypeScript never retroactively stamps an alias symbol on, so unannotated positions document the expansion instead of the name. Fires only where nothing self-heals: a loss the alias registry recovers (typeInfo emits {kind: 'reference', name} at use sites) is suppressed, as are literal-only unions (z.enum outputs) and brand-like intersections (.brand()) — readable degradations with no author-side fix worth demanding. @nodocs on the declaration suppresses. The author-side escape for a flagged alias is a nominal symbol, e.g. interface Foo extends z.infer<typeof S> {} where applicable, whose members are the inferred properties (the interface's computed heritage).

Always warning, query-time category (recomputed each query()).

import {AliasLostDiagnostic} from 'svelte-docinfo/diagnostics.ts';

inheritance

extends: SchemaStrictObjectOutput<typeof AliasLostDiagnosticEntries>

members

kind

: "alias_lost"
#

aliasName

: string
#

Name of the alias whose right-hand side resolves to a nameless type.

file

: string
#

File path relative to project root (no leading slash, no ./ prefix).

Normalized at every public API boundary — session.setFile/setFiles (ingest-time), session.query (query-time, via analyzeCore), and the one-shot wrappers analyze / analyzeFromFiles. Producers inside the pipeline may write absolute or virtual paths (e.g., Foo.svelte.__svelte2tsx__.ts); normalization rewrites them to project-relative form before they reach consumers.

The exception is discovery — discoverSourceFiles / discoverFromExports return their diagnostics unnormalized, since they run before any session exists. Their file is already project-root-relative, but message can embed an absolute path (an fs error names the file it failed on), so a consumer wiring discovery up itself owns the normalizeDiagnosticPaths call — analyzeFromFiles and the Vite plugin both make it before merging.

The absolute form is the one to write. Normalization deliberately leaves an already-relative path alone (relativizing it would resolve against cwd), so a producer writing a ModuleJson.path — relative to sourceRoot, a different base — passes through untouched and publishes the same file under a second name. Absolute is what the pass can actually correct.

message

: string
#

Human-readable description of the issue.

severity

: "error" | "warning"
#

line

?: number
#

Line number (1-based), absent if location unavailable.

column

?: number
#

Column number (1-based), absent if location unavailable.

AliasLostDiagnosticInput
#

diagnostics.ts view source

The input AliasLostDiagnostic parses, with any field it defaults optional.

import type {AliasLostDiagnosticInput} from 'svelte-docinfo/diagnostics.ts';

inheritance

extends: SchemaStrictObjectInput<typeof AliasLostDiagnosticEntries>

members

kind

: "alias_lost"
#

aliasName

: string
#

Name of the alias whose right-hand side resolves to a nameless type.

file

: string
#

File path relative to project root (no leading slash, no ./ prefix).

Normalized at every public API boundary — session.setFile/setFiles (ingest-time), session.query (query-time, via analyzeCore), and the one-shot wrappers analyze / analyzeFromFiles. Producers inside the pipeline may write absolute or virtual paths (e.g., Foo.svelte.__svelte2tsx__.ts); normalization rewrites them to project-relative form before they reach consumers.

The exception is discovery — discoverSourceFiles / discoverFromExports return their diagnostics unnormalized, since they run before any session exists. Their file is already project-root-relative, but message can embed an absolute path (an fs error names the file it failed on), so a consumer wiring discovery up itself owns the normalizeDiagnosticPaths call — analyzeFromFiles and the Vite plugin both make it before merging.

The absolute form is the one to write. Normalization deliberately leaves an already-relative path alone (relativizing it would resolve against cwd), so a producer writing a ModuleJson.path — relative to sourceRoot, a different base — passes through untouched and publishes the same file under a second name. Absolute is what the pass can actually correct.

message

: string
#

Human-readable description of the issue.

severity

: "error" | "warning"
#

line

?: number
#

Line number (1-based), absent if location unavailable.

column

?: number
#

Column number (1-based), absent if location unavailable.

AliasRegistry
#

typescript-extract-type-json.ts view source

Identity-keyed registry of exported alias-lost type aliases, consulted by the tree builder at nameless positions behind written-name recovery. Built per analysis cycle by buildAliasRegistry (typescript-alias-registry.ts); undefined wherever no pre-pass ran (registry recovery disabled, written recovery unaffected).

Registry hits must be linkable: identity-exact matches against aliases the output documents. That's why @nodocs aliases and aliases in gated modules (internal/) never register, and why package aliases never do ("never name what the project didn't declare").

import type {AliasRegistry} from 'svelte-docinfo/typescript-extract-type-json.ts';

members

byType

: Map<Type, AliasRegistryEntry>
#

Checker type identity → the winning alias (compareStrings name-then-module tie-break).

byMemberSet

: Map<string, AliasRegistryEntry>
#

Union member-set key (unionMemberSetKey) → the winning alias, for registered unions only. Consulted at optional-widened positions, where a null-bearing union flattens with the widening undefined into a type object the identity lookup can never match — the registered members survive by identity inside the widened union, so the set matches exactly.

warnedAliasLost

: Set<TypeAliasLike>
#

Alias declarations the alias_lost warning has fired for this cycle. Re-export synthesis re-analyzes canonical declarations (synthesizeCrossFileAlias, within-file renames), so one declaration can reach warnAliasLost from several analyzing sites in a cycle — this set dedupes to one warning per declaration. It rides on the registry because the registry is the one cycle-scoped object every warn site already holds (the warning is gated on a registry being in hand).

AliasRegistryEntry
#

AliasRegistrySource
#

typescript-alias-registry.ts view source

One emitted module offered to the pre-pass: the program's source file (for a Svelte module, the svelte2tsx *virtual* — program.getSourceFile returns undefined for a raw .svelte id, so the caller resolves through virtualPath) and its ModuleJson.path, which becomes AliasRegistryEntry.module and ships verbatim on recovered reference nodes — analyzeCore derives it with the same extractPath call that mints ModuleJson.path, and normalizeModulePathsInTypes deliberately skips the module key, so a caller passing anything else (an absolute path, a virtual-suffixed one) would publish it unrewritten.

import type {AliasRegistrySource} from 'svelte-docinfo/typescript-alias-registry.ts';

members

sourceFile

: SourceFile
#

modulePath

: string
#

AnalysisLanguageService
#

typescript-program.ts view source

Persistent language-service handle that drives a ts.Program incrementally.

Owns the LS, document registry, and a `Map<path, {content, version, scriptKind}>` of "owned" files (real source files + virtuals pushed via setFile). Files not in the owned map are read from disk on demand by the LS host.

Each setFile(path, entry) bumps the version when content or script kind differs from cache, so the next getProgram() reparses only the changed file. Calling getProgram() with no version bumps returns the same ts.Program as the previous call (reference-stable when nothing changed).

import type {AnalysisLanguageService} from 'svelte-docinfo/typescript-program.ts';

members

getProgram

(): Program
#

Get the current ts.Program.

Returns the same reference as the previous call when no setFile / deleteFile invalidated state in between. Returns a fresh ts.Program (sharing parsed ASTs for unchanged files via the document registry) when versions changed.

throws

  • Error - if the underlying LS returned undefined (should not happen in practice — TS only returns undefined during initialization)

getCompilerOptions

(): CompilerOptions
#

The merged compiler options the service was constructed with — parsed tsconfig with the caller's compilerOptions overrides applied per-key.

Cheap accessor over the construction-time loadTsconfig result; prefer it over getProgram().getCompilerOptions() when only the options are needed — getProgram() forces the LS to sync and parse every root file. allowJs is forced on (see withAllowJs), so these are the options the program runs with. Module resolution reads allowJs only for a package's self-name imports through its exports, so a resolver built from the unforced options would resolve the same otherwise; the session's default resolver is built from these, matching the program there too. There, output can differ from the project's own tsc without allowJs: an exports entry listing import/default before types resolves to the JS target.

Treat the returned object as read-only: it is the same reference the LS host serves via getCompilationSettings, so mutating it would desync consumers (e.g., the session's default import resolver) from the checker.

setFile

(path: string, entry: VirtualFileEntry): boolean
#

Set or replace a file's content (real path or virtual path).

  • New file: added to the owned map with version 1.
  • Existing file with identical content and script kind: no-op (version unchanged).
  • Existing file with new content or script kind: version bumped.
returns true when the file was added or its version bumped, false on no-op.

deleteFile

(path: string): boolean
#

Remove a file from the owned set.

returns true when the file was tracked, false when it was unknown.

hasFile

(path: string): boolean
#

Whether the given path is currently tracked.

dispose

(): void
#

Release LS resources.

Calls ts.LanguageService.dispose() and clears the owned map. The service must not be used after disposal.

see also

AnalysisLanguageServiceOptions
#

typescript-program.ts view source

import type {AnalysisLanguageServiceOptions} from 'svelte-docinfo/typescript-program.ts';

inheritance

members

documentRegistry

?: DocumentRegistry
#

Optional document registry for AST sharing across services.

Pass an explicit registry to share parsed source files when running multiple language services (e.g., LSP integration). Defaults to a fresh registry per service when omitted.

AnalysisLog
#

log.ts view source

also exported from index.ts

Minimal logger interface for analysis functions.

Intentionally narrow so that both @fuzdev/fuz_util's Logger class and Vite's built-in logger satisfy it without adapters or casts.

import type {AnalysisLog} from 'svelte-docinfo/log.ts';

members

info

: (msg: string) => void
#

warn

: (msg: string) => void
#

error

: (msg: string) => void
#

examples

// Stderr logger for CLI usage const log: AnalysisLog = { info: (msg) => console.error(msg), warn: (msg) => console.error(`warning: ${msg}`), error: (msg) => console.error(`error: ${msg}`), };

AnalysisProgramOptions
#

typescript-program.ts view source

import type {AnalysisProgramOptions} from 'svelte-docinfo/typescript-program.ts';

inheritance

members

virtualFiles

?: Map<string, VirtualFileEntry>
#

Virtual files to seed the program, keyed by virtual path.

Used to include svelte2tsx transformed outputs alongside real source files, enabling full type resolution for Svelte components via the checker. SvelteVirtualFile satisfies the entry shape structurally, so transform results can be passed as entries directly.

On a LanguageService, virtuals can also be added/replaced/removed after construction via setFile / deleteFile.

AnalysisSession
#

session.ts view source

also exported from index.ts

Persistent analysis handle.

Concurrency: not safe across overlapping calls. Serialize externally (each caller awaits the previous setFile/setFiles before starting the next). The LS underneath is sync, but the resolver phase awaits I/O for async resolvers (Vite/Rollup), so the session does cross await boundaries.

Cache-hit semantics: per-entry, all-or-nothing. The implementation must not split the guarantee across separate caches (e.g. transform-cache hit + lex re-run). The match criterion is mode-discriminated:

  • lex+resolve mode: existing.content === incoming.content AND existing.resolverIdentity === incoming.resolverIdentity.
  • pre-resolved mode: existing.content === incoming.content AND arraysShallowEqual(existing.preResolvedDepsSnapshot, incoming.dependencies).

Mode flips (an entry previously ingested as lex+resolve now arrives with dependencies, or vice versa) always cache-miss.

Deferred resolutions: a cache hit reuses the entry's dependency edges, but an import specifier that resolved to nothing isn't a settled answer — its target may be ingested later, and the file that changes then is the *dep*, not the importer, so the importer would stay a cache hit with a missing edge. A setFiles that adds paths therefore retries the unresolved specifiers of already-owned entries and updates their edges in place, retiring any resolver_failed that has since resolved. This is the one way an entry changes without being re-ingested; it consumes no resolver work for files whose imports all resolved, and none at all for pre-resolved callers, whose edges are theirs to declare.

Promise resolution: setFile / setFiles resolve only after the serial LS push (phase 3) completes for every file in the batch. Awaiting the returned promise is sufficient — no separate flush step.

Owned ⊇ emitted: ingest is additive and ungated — any file can be pushed, and owned entries are served to the checker from memory before the disk fallback, so non-source files (unsaved buffers, virtual-only helpers, configs) can shape type resolution in the modules that import them. query() gates the *module set* through isSource: only owned files under sourceOptions.sourcePaths and not matching exclude emit a ModuleJson, and of those, not a dependency the closure ingested on its own (see contextClosure). The gate emits no diagnostics — query() logs the gated count as info, and list() reports the full owned set for introspection. By default the session completes the owned set itself: contextClosure ingests the in-root non-source dependency closure (e.g. internal/ modules public files import) so those files are version-tracked rather than pinned at their first disk read. Source files the caller didn't supply are ingested the same way, since a Svelte dependency among them reaches the checker only through an ingested virtual.

Input order: query() analyzes the owned set in compareStrings order of file ID, and the language-service host returns owned program roots in that order too, so the same files ingested in any order, in one batch or across many setFile calls, give identical output from a fresh session. Analysis order matters because TypeScript prints a union with no alias origin (z.enum members, literal unions) in type-creation order, which follows the order the checker first visits files; root order matters because it sets the merge order of declare global, module augmentations, and interface merging. Two limits remain, both from type-creation order, for flat strings and for typeInfo unions with no written form (see TypeJson): an edit to an unrelated file can still reorder such a union's members, since it can change which file first creates a member type, and checker work done through getProgram() before the first query() on a fresh program can reorder them in that query's output.

import type {AnalysisSession} from 'svelte-docinfo/session.ts';

members

setFile

(file: SourceFileInfo, opts?: SetFileOptions): Promise<SetFileResult>
#

Ingest one file's content into the session. Idempotent on cache hit.

returns {changed, diagnostics} — changed: false indicates a cache-hit no-op where the cached ingest diagnostics are returned.

setFiles

(files: readonly SourceFileInfo[], opts?: SetFileOptions): Promise<SetFilesResult>
#

Ingest a batch of files. Additive — never removes; use deleteFile for removal. Cache hits are folded into the result with changed: false.

deleteFile

(id: string): Promise<void>
#

Drop a file from the session and evict from the LS.

has

(id: string): boolean
#

Whether the given file ID is currently owned by the session.

list

(): readonly string[]
#

Snapshot of currently-owned file IDs (sort order is insertion order).

Run a two-phase analysis pass against the current owned set, gated by isSource — owned files outside sourcePaths (or matching exclude) provide checker context but emit no module (see "Owned ⊇ emitted" above).

returns analyzed modules and analysis-pass diagnostics. Ingest diagnostics from prior setFile/setFiles calls are NOT included here — concat with those returns for the full picture.

throws

  • Error - if onDuplicates: 'throw' and duplicates exist

allIngestDiagnostics

(): Diagnostic[]
#

Concatenated ingest-time diagnostics across every owned entry — the cumulative view of every setFile/setFiles return, kept current as entries are added/replaced/deleted.

Lets long-lived consumers (Vite plugin, LSP) publish the full ingest picture without tracking per-batch returns themselves. Cheap: walks the owned map.

getProgram

(): Program
#

The LS-backed ts.Program, for incremental consumers doing their own checker work over analyzed declarations (e.g., a docgen provider converting ts.Types into its own structured model).

Freshness caveat: returns whatever the most recent ingest produced — the same reference as the prior call when no file version bumped, else a fresh program reusing unchanged ASTs via the document registry. A retained reference goes stale after any setFile / setFiles / deleteFile; re-call after mutating. Subject to the session's concurrency contract above; invalid after dispose().

Checker work done before query() on a fresh program can reorder origin-less unions in that query's output (see "Input order" above); call query() first.

dispose

(): void
#

Release LS resources and clear the owned set. The session must not be used after disposal.

AnalysisSessionOptions
#

session.ts view source

also exported from index.ts

Options for createAnalysisSession.

documentRegistry flows through to the underlying LanguageService only. tsconfig, compilerOptions, and rootFileNames drive the LS's construction-time loadTsconfig parse — the session's only tsconfig parse. The lazy default ImportResolver reuses the LS's merged options via getCompilerOptions(), so module resolution and the checker see the same merge semantics — user-supplied compilerOptions override parsed tsconfig keys, and only tsconfig: false lifts the config file requirement. The parse is a construction-time snapshot: a tsconfig.json edit mid-session is not picked up — create a new session.

rootFileNames narrows the program to what the session is asked about: a session fed a few files of a large project otherwise pays for every file the tsconfig includes (see RootFileNames for what narrowing can cost).

projectRoot and virtualFiles from the LS options shape are excluded — the session derives projectRoot from sourceOptions and manages svelte2tsx virtuals internally per file.

import type {AnalysisSessionOptions} from 'svelte-docinfo/session.ts';

inheritance

extends: Omit<AnalysisLanguageServiceOptions, "projectRoot" | "virtualFiles">

members

sourceOptions

: ModuleSourceOptions
#

Module source options for path extraction and source filtering.

Must be a fully-constructed ModuleSourceOptions — the session re-runs normalizeSourceOptions (idempotent) but does not apply any defaults. Pass through createSourceOptions(projectRoot, overrides?) to merge with DEFAULT_SOURCE_OPTIONS. (The SourceOptionsOverrides ergonomic shape — exclude-callback form included — exists only on AnalyzeFromFilesOptions.sourceOptions and the Vite plugin, where the defaults merge happens inside createSourceOptions.)

resolveImport

?: ResolveImport
#

Session-default custom import resolver used when no per-call override is supplied — a bare ResolveImportFn or a token-paired ImportResolver (see ResolveImport). A bare function is normalized once at construction, so its synthesized identity is stable for the session's lifetime (cache reuse works). When omitted, the session lazily constructs the TS+tsconfig default on first use.

contextClosure

?: boolean
#

Own the in-root dependency closure the caller didn't supply as context files (default true).

After each ingest batch, the session reads from disk any file the batch's imports resolved to that is under projectRoot, isn't owned yet, has no node_modules/dot-directory segments, and has an analyzer type — transitively, until the closure converges. Context files are owned but never emit modules, and add no dependency edges. For a file that fails isSource (outside sourcePaths or matching exclude — e.g. the src/lib/internal/ convention) what this changes is *freshness*: an owned file's edit version-bumps the LS, whereas a disk-resolved file is read once and pinned for the session's lifetime.

A file that passes isSource is ingested as context too when the caller didn't supply it — a module left out of package exports under exports discovery, or the rest of the project when a caller hands over one component. That one changes output: the checker reads a Svelte file only through its svelte2tsx virtual, so without the ingest every type drawn from an unsupplied component (`ComponentProps<typeof Sibling>) is any`, and the walk passes through unsupplied TS files because a component can sit behind one (a barrel).

Such a file still emits no module. Supplying it through setFile / setFiles later makes it an emitted input, and that call reports it changed; a consumer forwarding an edit to a file it doesn't mean as an input passes context: true to keep it context (see SetFileOptions.context). A context component's <script module> exports and the component itself, when re-exported from an emitted module, document there as they do for a gated internal/ component, and its transform failure surfaces as transform_failed through allIngestDiagnostics(). Watch-style consumers (the Vite plugin) gate their watchers on isSource(file) || session.has(file), so context-file edits trigger re-analysis and public output tracks internal types live.

Context batches always ingest in lex+resolve mode (their edges exist only to walk the closure — context files emit nothing), so a fully pre-resolved consumer whose files import in-root paths it didn't supply constructs the default resolver after all. Context ingest diagnostics surface via allIngestDiagnostics(), not the batch return, and setFiles results stay keyed by the caller's input IDs. Unreadable candidates are skipped silently (the LS disk fallback covers them).

Context files are never evicted: once owned they stay owned (and, under the Vite plugin, watched) for the session's lifetime, even when no importer remains.

A context file created after its importer's last ingest becomes owned on the importer's next change only if its specifier re-resolves — with the default resolver a cached miss sticks until owned-set membership changes (the Vite dev resolver doesn't cache).

Set false only when the caller supplies every file the checker needs (the internal analyze() wrapper does): TS/JS context is covered by the LS disk fallback either way, but a gated .svelte dependency resolves only through the closure's ingest (svelte2tsx runs there — the disk fallback serves raw Svelte the checker can't parse), so analyzeFromFiles() keeps the closure on despite being one-shot.

#

Optional logger for session-level messages.

documentRegistry

?: DocumentRegistry
#

Optional document registry for AST sharing across services.

Pass an explicit registry to share parsed source files when running multiple language services (e.g., LSP integration). Defaults to a fresh registry per service when omitted.

tsconfig

?: string | false = 'tsconfig.json'
#

Path to tsconfig.json, relative to projectRoot; parent directories are searched when it isn't there. Any config file name works, jsconfig.json included.

false analyzes without a config file: no lookup runs, the compiler options are DEFAULT_COMPILER_OPTIONS with compilerOptions merged on top, and there are no config roots. It's an explicit choice, never a fallback — a config that's named or defaulted and can't be found still throws.

compilerOptions

?: CompilerOptions
#

Compiler options merged on top of those parsed from tsconfig.json (per-key override; user-supplied keys win), or on top of DEFAULT_COMPILER_OPTIONS under tsconfig: false. Does not by itself bypass the config file requirement — without tsconfig: false, loadTsconfig still throws when no config file is found.

rootFileNames

?: RootFileNames = the tsconfig's roots
#

The program's root files beyond the analyzed ones, replacing the roots the tsconfig's files/include produce (see RootFileNames).

analyze
#

analyze.ts view source

also exported from index.ts

analyze(options: AnalyzeOptions): Promise<AnalyzeResultJson>

Analyze library source files and extract metadata (one-shot).

Wraps a single-use AnalysisSession. For repeated analyses of the same source set (e.g., a Vite plugin reacting to file edits), use createAnalysisSession directly.

import {analyze} from 'svelte-docinfo/analyze.ts';

returns

analyzed modules (sorted alphabetically) + concatenated ingest + query diagnostics

throws

  • Error - if sourceOptions validation fails or the tsconfig is missing or can't be loaded (see loadTsconfig; tsconfig: false skips it). Also propagates onDuplicates: 'throw' errors.

analyzeComponentCss
#

svelte-css.ts view source

analyzeComponentCss(svelteSource: string): ComponentCss

Read a component's styling API: the custom properties its top-level <style> and its markup's static style text read through an outermost var() with a fallback, or that its style registers with @property, minus the ones it sets itself. The policy is ComponentDeclarationJson.cssCustomProperties's.

One parse with Svelte's parser (modern, loose) over the source with its script content blanked, so script syntax never fails it. A style whose lang or type names another language is blanked too, and reported as css_lang_unsupported. A parse failure reports css_parse_failed, with the parser's position. A source without <style text is parsed only when its non-script text has var(, for its markup's reads; otherwise it reads nothing, with empty reads. Every read, the ones it doesn't list included, lands in reads for documentCssProperties.

import {analyzeComponentCss} from 'svelte-docinfo/svelte-css.ts';

parameters

svelteSource

: string
#

the full Svelte source code

returns

the styling API, plus the problem when the style wasn't read

analyzeCore
#

analyze-core.ts view source

internal

Importable from `svelte-docinfo/analyze-core.js` for tests and power users; not stable API.

analyzeCore(inputs: AnalyzeCoreInputs): AnalyzeResultJson

Run the two-phase analysis loop on pre-prepared inputs. The orchestrator behind session.query, and so behind the one-shot wrappers, which query a single-use session.

Runs the alias-registry pre-pass (buildAliasRegistry) over the emitted set, then phase 1: per-file dispatch (TS / Svelte / CSS / JSON / placeholder for transform-failed Svelte), plus gated Svelte canonicals analyzed as fill context. Phase 2: re-export merge, component-alias fill, sort, duplicate detection, and module-path normalization in printed types (normalizeModulePathsInTypes), then finalizeDiagnostics.

Dependents are read from sourceFile.dependents via extractDependencies; analyzeCore does not compute them. session.query runs computeDependents on the emitted set before invoking this.

import {analyzeCore} from 'svelte-docinfo/analyze-core.ts';

AnalyzeCoreInputs
#

analyze-core.ts view source

Inputs to analyzeCore. The caller (one-shot wrapper or session.query) is responsible for normalizing sourceOptions, obtaining the program, and pre-transforming Svelte files into svelteVirtualFiles.

transformFailedIds carries the IDs of .svelte files whose svelte2tsx transform threw at ingest. The dispatch synthesizes a placeholder ModuleJson (partial: true, empty declarations) for each so consumers see the file's existence in modules even though analysis couldn't run. Identifying these via a sibling Set keeps svelteVirtualFiles a clean "files we can analyze" map; the failure side-channel doesn't pollute it.

import type {AnalyzeCoreInputs} from 'svelte-docinfo/analyze-core.ts';

members

sourceFiles

: readonly SourceFileInfo[]
#

sourceOptions

: ModuleSourceOptions
#

program

: Program
#

svelteVirtualFiles

: ReadonlyMap<string, SvelteVirtualFile>
#

transformFailedIds

?: ReadonlySet<string>
#

Svelte file IDs whose svelte2tsx transform failed at ingest.

contextSvelteFiles

?: readonly SourceFileInfo[]
#

Svelte files that are owned but emit no module — gated ones (the internal/ convention) and source-scope components ingested only as checker context — whose virtuals are in svelteVirtualFiles. Analyzed only when an emitted component alias references them, as canonical-fill context for resolveComponentAliases — their modules never emit and their analysis diagnostics are dropped (partial on the canonical propagates to the filled alias instead).

Resolution requires the component's virtual to exist — via the context closure (analyzeFromFiles included) or by passing the file as analyze() input. Without it a gated component re-export documents as a partial component with nothing filled.

fileExists

?: FileExists
#

Whether a path exists — owned in-memory content or disk. It tells a .svelte file with no svelte2tsx virtual from a mistyped specifier (see SvelteFileStatus). Defaults to the files handed in plus the disk; a session passes its whole owned set, which also holds files that emit nothing and aren't offered as context.

onDuplicates

?: OnDuplicates
#
#

analyzeDeclaration
#

typescript-exports.ts view source

analyzeDeclaration(symbol: Symbol, sourceFile: SourceFile, ctx: ExtractContext, warnMisplacedCssprop?: boolean): DeclarationAnalysis

Analyze a TypeScript symbol and extract rich metadata.

This is a high-level function that combines TSDoc parsing with TypeScript type analysis to produce complete declaration metadata. Suitable for use in documentation generators, IDE integrations, and other tooling.

import {analyzeDeclaration} from 'svelte-docinfo/typescript-exports.ts';

parameters

symbol

: Symbol
#

the TypeScript symbol to analyze

sourceFile

: SourceFile
#

the source file containing the symbol

the extraction pass's context (checker, diagnostics, externality predicate, alias registry)

warnMisplacedCssprop

?: boolean = false
#

whether a @cssprop tag in the declaration's JSDoc warns misplaced_tag (it documents only a component): set by the declaring module's own pass, so an alias re-analyzing the canonical doesn't repeat the warning

returns

complete declaration metadata including docs, types, and parameters, plus nodocs flag

analyzeExports
#

typescript-exports.ts view source

analyzeExports(sourceFile: SourceFile, ctx: ExtractContext, options: ModuleSourceOptions): ModuleExportsAnalysis

Analyze all exports from a TypeScript source file.

Extracts the module-level comment via extractModuleComment (skipped for svelte2tsx virtual files — see the inline note), star exports via extractStarExports, and all exported declarations with complete metadata. Handles re-exports by:

  • Same-name re-exports: tracked in reExports for alsoExportedFrom building
  • Renamed re-exports: included as new declarations with aliasOf metadata
  • Import-then-export (import {foo as bar} from './x'; export {bar}): encoded as its export-from twin, since rename detection steps through import bindings (nextExportHop)
  • Star exports (export * from): tracked in starExports for namespace-level info
  • Direct external re-exports: tracked in externalReExports/externalStarExports (specifier as written; import-then-export and source-chained forms stay silent)

This is a mid-level function (above the individual extract* helpers, below analyze) suitable for building documentation, API explorers, or analysis tools. For standard SvelteKit library layouts, use createSourceOptions(process.cwd()).

import {analyzeExports} from 'svelte-docinfo/typescript-exports.ts';

parameters

sourceFile

: SourceFile
#

the TypeScript source file to analyze

the extraction pass's context (see createExtractContext); its isExternalFile must derive from the same options passed here, since this function derives its path-keyed twin (createIsExternalPath) from options and the two must agree

module source options for path extraction in re-exports

returns

module comment, declarations, re-exports (source + external), and star exports (source + external)

analyzeFromFiles
#

analyze.ts view source

also exported from index.ts

analyzeFromFiles(options: AnalyzeFromFilesOptions): Promise<AnalyzeResultJson>

Analyze a library from files on disk with automatic file discovery.

Recommended high-level API for one-shot use (CLI, build-time generation):

  1. Discovery — discoverSourceFiles (exports-first, glob fallback)
  2. Ingest — push discovered files into a single-use session
  3. Analysis — session.query()
import {analyzeFromFiles} from 'svelte-docinfo/analyze.ts';

returns

analyzed modules + concatenated ingest, discovery, and query diagnostics

throws

  • Error - on invalid or contradictory options, a missing or unloadable tsconfig.json (see loadTsconfig), failed strict 'exports' discovery, or a collision under onDuplicates: 'throw'

AnalyzeFromFilesOptions
#

analyze.ts view source

also exported from index.ts

Options for analyzeFromFiles.

import type {AnalyzeFromFilesOptions} from 'svelte-docinfo/analyze.ts';

members

projectRoot

: string
#

Absolute path to project root directory.

sourceOptions

?: SourceOptionsOverrides
#

Partial overrides for default source options (SvelteKit src/lib layout).

onDuplicates

?: OnDuplicates
#

Opt-in check that declaration names are unique across modules (see OnDuplicates).

#

Optional logger for status and diagnostic messages.

include

?: string[]
#

Glob patterns to include, relative to projectRoot. Collapses discovery: 'auto' to glob (combining with 'exports' throws), and each pattern's static base widens sourceOptions.sourcePaths so the matched files emit modules (see createSourceOptionsWithInclude).

exclude

?: ExcludeOption
#

Glob patterns to exclude — supersedes sourceOptions.exclude whole (no merge; the callback form still receives the built-in defaults). An array replaces the defaults, a callback extends them — see ExcludeOption.

resolveDependencies

?: boolean = `true`
#

Whether to resolve import dependencies (default true).

When false, the session uses a no-op resolver that always returns null, so ModuleJson.dependencies / dependents stay empty. analyzeFromFiles's discovery layer does not pre-populate SourceFileInfo.dependencies, so the session's pre-resolved fast path isn't reachable through this API — to exercise it, drive analyze or createAnalysisSession directly with files whose dependencies field is already filled in by your build tool.

resolveImport

?: ResolveImport
#

Optional custom import resolver — a bare ResolveImportFn or a token-paired ImportResolver (see ResolveImport). One-shot use doesn't benefit from a stable cache identity, so the bare function form is the natural choice here; for long-lived consumers (Vite plugin, LSP) construct an ImportResolver with a stable identity and pass it via createAnalysisSession so cache hits survive across calls.

Cannot be combined with resolveDependencies: false — resolution is then off, so the resolver would never be consulted; passing both throws.

discovery

?: Discovery = 'auto'
#

Discovery strategy for source files.

distDir

?: string = 'dist'
#

Dist directory name for exports-based discovery.

tsconfig

?: string | false = 'tsconfig.json'
#

Path to the tsconfig, relative to the project root, or false to analyze without one (see LoadTsconfigOptions.tsconfig).

compilerOptions

?: CompilerOptions
#

Compiler options merged over the tsconfig's (see LoadTsconfigOptions.compilerOptions).

rootFileNames

?: RootFileNames = the tsconfig's roots
#

Root files for the program in place of the tsconfig's (see RootFileNames).

see also

  • AnalyzeOptions for the build-tool-integration API where you supply sourceFiles and a fully-formed sourceOptions: ModuleSourceOptions directly.

analyzeModule
#

analyze-core.ts view source

internal

Importable from `svelte-docinfo/analyze-core.js` for tests and power users; not stable API.

analyzeModule(sourceFile: SourceFileInfo & { dependents?: readonly string[]; }, program: Program, options: ModuleSourceOptions, diagnostics: Diagnostic[], log?: AnalysisLog, aliasRegistry?: AliasRegistry, isEmittedFile?: IsEmittedFile, fileExists?: FileExists): ModuleJson | undefined

Analyze a single non-Svelte source file and extract module metadata — the per-module dispatcher behind analyzeCore.

Dispatches on file type:

  • TypeScript/JS → analyzeTypescriptModule
  • CSS/JSON → minimal module (no declarations, dependency tracking only)
  • Svelte → module_skipped: requires_program (callers using session API should not reach this path; the session pre-handles Svelte)

Returns undefined when the file is skipped (see findModuleSkip); the diagnostic is added to diagnostics so the caller can keep iterating.

alsoExportedFrom on returned declarations is always empty from this path — cross-module re-export resolution requires all modules (mergeReExports consumes the returned module's reExports in phase 2).

aliasRegistry is optional at this boundary: direct callers assembling modules themselves get written-name recovery only, while analyzeCore passes the registry its pre-pass built (see buildAliasRegistry). isEmittedFile likewise: analyzeCore answers from its emitted set, and a direct caller falls back to isSource (see IsEmittedFile). fileExists too: analyzeCore sees its inputs' in-memory content, and a direct caller falls back to the disk (see SvelteFileStatus).

import {analyzeModule} from 'svelte-docinfo/analyze-core.ts';

AnalyzeOptions
#

analyze.ts view source

also exported from index.ts

Options for analyze.

Requires pre-loaded SourceFileInfo arrays — use analyzeFromFiles for automatic file discovery and loading from disk, or createAnalysisSession for incremental use.

import type {AnalyzeOptions} from 'svelte-docinfo/analyze.ts';

members

sourceFiles

: readonly SourceFileInfo[]
#

Source files to analyze (must have content loaded). Files outside sourceOptions.sourcePaths or matching exclude emit no module — they still feed the checker as in-memory content, so passing extra files (unsaved buffers, virtual-only helpers) shapes type resolution without polluting the output.

sourceOptions

: ModuleSourceOptions
#

Module source options for path extraction and source filtering.

onDuplicates

?: OnDuplicates
#

Opt-in check that declaration names are unique across modules (see OnDuplicates).

#

Optional logger for status and diagnostic messages.

resolveImport

?: ResolveImport
#

Optional custom import resolver for the session default — a bare ResolveImportFn or a token-paired ImportResolver (see ResolveImport). For one-shot analyze() the session is single-use, so a bare function is the natural form; pass an ImportResolver with a stable identity only if you have a reason to control the cache scope.

tsconfig

?: string | false = 'tsconfig.json'
#

Path to the tsconfig, relative to the project root, or false to analyze without one (see LoadTsconfigOptions.tsconfig).

compilerOptions

?: CompilerOptions
#

Compiler options merged over the tsconfig's (see LoadTsconfigOptions.compilerOptions).

rootFileNames

?: RootFileNames = the tsconfig's roots
#

Root files for the program in place of the tsconfig's (see RootFileNames).

AnalyzeResultJson
#

analyze-core.ts view source

value + type

also exported from index.ts

Result of analyze, analyzeFromFiles, and AnalysisSession.query.

Modules sorted alphabetically by path. Diagnostics are query-time (analysis-pass) diagnostics only when produced by session.query; one-shot wrappers concatenate ingest + query diagnostics into this same array.

Schema-validated round-trip

The envelope is a fuz_schema schema (AnalyzeResultJson) — both fields default to [], so JSON.stringify(result, compactReplacer) strips empty arrays on the wire and parseAnalyzeResult(JSON.parse(json)) restores them. Consumers programmatically ingesting analysis JSON should parse through parseAnalyzeResult to get defaults restored; raw-JSON consumers (e.g., jq) treat missing keys as null-equivalent (jq '.diagnostics | length' returns 0 on {}) and don't need the parse step.

Construction sites (one-shot wrappers, session.query) hand back hand-built objects without re-parsing — the inner modules and diagnostics arrays are already schema-validated upstream, and the envelope schema is the type contract, not a validation gate.

See AnalyzeResultJsonWire for the serialized input-side shape published on virtual:svelte-docinfo.

import {AnalyzeResultJson} from 'svelte-docinfo/analyze-core.ts';

inheritance

extends: SchemaStrictObjectOutput<typeof AnalyzeResultJsonEntries>

members

modules

: ModuleJson[]
#

AnalyzeResultJsonInput
#

analyze-core.ts view source

The input AnalyzeResultJson parses, with any field it defaults optional.

import type {AnalyzeResultJsonInput} from 'svelte-docinfo/analyze-core.ts';

inheritance

extends: SchemaStrictObjectInput<typeof AnalyzeResultJsonEntries>

members

modules

?: ModuleJsonInput[]
#

AnalyzeResultJsonWire
#

analyze-core.ts view source

also exported from index.ts

Serialized wire shape of an analysis result, as published by the Vite plugin on virtual:svelte-docinfo — the input-side counterpart to AnalyzeResultJson (the validated output of parseAnalyzeResult).

The two fields are deliberately asymmetric:

  • modules is ModuleJsonInput (the s.InferInput of ModuleJson) because the plugin runs it through compactReplacer, which strips defaulted empty arrays and false booleans. Default-bearing fields therefore arrive undefined.
  • diagnostics is the output Diagnostic — the plugin serializes it without the replacer, and Diagnostic has no defaults to strip, so the array is always present and the shape matches runtime exactly.

Consumers restore defaults with parseAnalyzeResult.

Note this describes the Vite virtual module specifically. The CLI runs the whole envelope through compactReplacer, so its JSON may additionally omit an empty diagnostics array — CLI consumers should parse through parseAnalyzeResult rather than assume this shape.

import type {AnalyzeResultJsonWire} from 'svelte-docinfo/analyze-core.ts';

members

modules

: ModuleJsonInput[]
#

diagnostics

: Diagnostic[]
#

AnalyzerType
#

source.ts view source

also exported from index.ts

type "typescript" | "svelte" | "css" | "json"

Analyzer type for source files.

  • 'typescript' — TypeScript/JS files analyzed via TypeScript compiler API
  • 'svelte' — Svelte components analyzed via svelte2tsx + TypeScript compiler API
  • 'css' — CSS files included as modules with no declarations
  • 'json' — JSON files included as modules with no declarations
import type {AnalyzerType} from 'svelte-docinfo/source.ts';

analyzeSvelteModule
#

svelte.ts view source

analyzeSvelteModule(sourceFile: SourceFileInfo & { dependents?: readonly string[]; }, modulePath: string, checker: TypeChecker, options: ModuleSourceOptions, diagnostics: Diagnostic[], program: Program, virtualFile: SvelteVirtualFile, aliasRegistry?: AliasRegistry, isEmittedFile?: IsEmittedFile, fileExists?: FileExists): ModuleAnalysis | undefined

Analyze a Svelte module using checker-backed analysis.

Requires the svelte2tsx virtual output to be included in the TypeScript program (via createAnalysisProgram({ virtualFiles }), or the language service's setFile in sessions). Provides full type resolution for:

  • Imported prop types (let {x}: ImportedProps = $props())
  • <script module> exports (constants, types, re-exports)
  • Star exports and re-exports from Svelte files

Mirrors the numbered steps in the body:

  1. analyzeExports on the virtual collects <script module> exports, re-exports, and star exports
  2. svelte2tsx internals are filtered (isSvelte2tsxGeneratedExport) and exported snippets reclassified to kind: 'snippet' (isSnippetReturnType); 2b remaps module-level sourceLines to the original .svelte source
  3. the component declaration is synthesized: props via extractPropsViaChecker from the component's PropsAnchor (resolveRunesPropsAnchor for a $props() declaration, else resolveExportLetPropsAnchor for a legacy component's exports), acceptsChildren from a Snippet-typed children prop, template use (__sveltets_2_ensureSnippet) or, failing those, a legacy component's default slot (hasDefaultSlot), the styling API read at transform (SvelteVirtualFile.css), plus generics, doc comment, and source line from the landmarks findComponentNodes locates
  4. the module comment is read from the original source
  5. declarations combine, component first
  6. dependencies are extracted
import {analyzeSvelteModule} from 'svelte-docinfo/svelte.ts';

parameters

sourceFile

: SourceFileInfo & { dependents?: readonly string[]; }
#

the original Svelte source file

modulePath

: string
#

module path relative to source root; feeds ModuleJson.path and the component name, never Diagnostic.file (which is project-root-relative — a different base)

checker

: TypeChecker
#

TypeScript type checker (from the program containing virtual files)

module source options for path extraction

diagnostics

: Diagnostic[]
#

diagnostics collector for non-fatal issues

program

: Program
#

TypeScript program containing the virtual file

virtualFile

: SvelteVirtualFile
#

pre-transformed virtual file data

aliasRegistry

?: AliasRegistry
#

the analyzed set's alias registry (see buildAliasRegistry), or undefined when no pre-pass ran

isEmittedFile

?: IsEmittedFile
#

whether a file emits a module this pass (see IsEmittedFile); defaults to isSource

fileExists

?: FileExists
#

whether a path exists, owned content included (see SvelteFileStatus); defaults to the disk

returns

module analysis with declarations, re-exports, and star exports; undefined if the virtual file is not found in the program

analyzeTypescriptModule
#

typescript-exports.ts view source

analyzeTypescriptModule(sourceFileInfo: SourceFileInfo & { dependents?: readonly string[]; }, tsSourceFile: SourceFile, modulePath: string, ctx: ExtractContext, options: ModuleSourceOptions): ModuleAnalysis

Analyze a TypeScript file and extract module metadata.

The TypeScript arm of analyzeModule: wraps analyzeExports and adds dependency information via extractDependencies. For whole-project analysis use analyze/analyzeFromFiles.

import {analyzeTypescriptModule} from 'svelte-docinfo/typescript-exports.ts';

parameters

sourceFileInfo

: SourceFileInfo & { dependents?: readonly string[]; }
#

the source file info (from file system, build pipeline, or other source)

tsSourceFile

: SourceFile
#

TypeScript source file from the program

modulePath

: string
#

the module path (relative to source root)

the extraction pass's context (see analyzeExports for the construction contract)

module source options for path extraction

returns

module metadata and re-export information

applyHeritageExternalTypes
#

typescript-extract-shared.ts view source

applyHeritageExternalTypes(declaration: DeclarationJsonBuild, heritageTypes: readonly ExpressionWithTypeArguments[], ctx: ExtractContext): void

Set a declaration's externalTypes from its own heritage entries — the interface/class counterpart of filterDocumentedProperties' annotation walk, and the one place the two heritage-bearing extractors express it.

Classes enumerate own members only, and interfaces don't enumerate a named base's (a computed entry's external properties are filtered, by extractComputedHeritageMembers) — what the field records there is the external types the heritage composition reaches whose contributions members therefore never enumerates: `interface Props extends HTMLButtonAttributes` records the bag, directly or through a local base chain, exactly as the same interface annotating $props() records it on the component. Local bases reached and fully enumerated nowhere are the extends field's business, not this one.

Only extends entries are passed by either caller: an interface has no other clause kind, and a class's implements adds no members.

Scoped to the processed declaration's own heritage clauses — the same node extends and members come from — so on a merged interface only the selected block contributes, while a reference to that interface elsewhere descends every block. The three fields stay consistent with each other rather than with the descent.

import {applyHeritageExternalTypes} from 'svelte-docinfo/typescript-extract-shared.ts';

mutates

  • declaration — sets externalTypes when the walk finds any, left absent when not

applyReturnType
#

typescript-extract-shared.ts view source

applyReturnType(target: SignatureReturnTarget, sig: Signature, ctx: ExtractContext): void

Set returnType + returnTypeInfo on a build target from a signature's return type — the one projection of the flat/structured return pair, so the two fields always print from the same ts.Type (returns are never optional, hence the constant false) — and with them the two signature facts neither shows: returnPredicate for a type predicate or assertion, and thisType + thisTypeInfo for a declared this parameter. The written return annotation, when one exists, feeds the tree's name recovery for aliases TypeScript dropped.

import {applyReturnType} from 'svelte-docinfo/typescript-extract-shared.ts';

applyThrowsTypeInfo
#

typescript-extract-shared.ts view source

applyThrowsTypeInfo(declarations: readonly DeclarationJsonBuild[], ctx: ExtractContext): void

Resolve the typeInfo of each braced @throws entry on a declaration, its members, and its props, from the type nodes parseComment kept (throwsTypeNodes). One pass over a module's finished declarations, so no site that applies docs has to thread the checker through.

import {applyThrowsTypeInfo} from 'svelte-docinfo/typescript-extract-shared.ts';

mutates

  • declarations — replaces throws entries that gain a typeInfo

applyToDeclaration
#

tsdoc.ts view source

applyToDeclaration(declaration: DeclarationJsonBuild | MemberJsonBuild, tsdoc: TsdocParsedComment | undefined, isMember?: boolean): void

Apply parsed TSDoc metadata to a declaration.

Consolidates the common pattern of assigning TSDoc fields to declarations, with conditional assignment for array fields (only if non-empty).

import {applyToDeclaration} from 'svelte-docinfo/tsdoc.ts';

parameters

declaration object to update

tsdoc

: TsdocParsedComment | undefined
#

parsed TSDoc comment (if available)

isMember

?: boolean = false
#

whether declaration is a member of a container; function *members* carry defaultValue (the documented behavior when a callback is omitted) while top-level function declarations never do

mutates

  • declaration — adds docComment, deprecatedMessage, internalMessage, examples, seeAlso, throws, since, mutates, defaultValue fields

applyVirtualFiles
#

typescript-program.ts view source

internal

Shared host decoration for `createAnalysisProgram`; exported for test-side hosts — not a stable API.

applyVirtualFiles(host: CompilerHost, virtualFiles: ReadonlyMap<string, VirtualFileEntry>): ReadonlyMap<string, VirtualFileEntry>

Decorate a compiler host so virtualFiles shadow the filesystem — getSourceFile (honoring per-entry scriptKind), fileExists, readFile, and directoryExists.

Entries are copied to minimal {content, scriptKind} records so the host's closures don't retain larger caller objects (a SvelteVirtualFile's source map, say) for the program's lifetime. The copied map is returned so callers layering module resolution on top (.svelte specifier mapping) can key it off the same snapshot instead of re-capturing the caller's map. The entry set is fixed at decoration time — the returned ReadonlyMap and the directory index are built in the same pass, so no host answer can be served from a staler view of the set than another (a LanguageService is the mutable counterpart; see createAnalysisLanguageService).

import {applyVirtualFiles} from 'svelte-docinfo/typescript-program.ts';

returns

the copied entries, keyed by path

mutates

  • host — replaces getSourceFile, fileExists, readFile, and (when the host defines it) directoryExists

baselineExcludesForBase
#

source-config.ts view source

baselineExcludesForBase(base: string): string[]

Anchor the baseline exclusion globs below a discovery base directory.

Anchoring is what preserves the escape hatch at discovery time: the ignores for base .hidden/src are .hidden/src/**\/node_modules/** etc., which don't match the base's own dot segment. '' anchors at the project root. Used as glob ignore by globFiles (per include-pattern base) and discoverFromExports (below the source dir).

import {baselineExcludesForBase} from 'svelte-docinfo/source-config.ts';

blankVerbatimContent
#

svelte-scripts.ts view source

blankVerbatimContent(svelteSource: string, scripts: readonly ScannedScriptTag[], options?: BlankVerbatimContentOptions): string

Copy svelteSource with the content of its script and style tags overwritten by spaces, newlines kept, so every offset and line still means what it meant. Script content needn't be JS that Svelte's parser accepts, and a nested tag's content would be read as template.

A style tag that opens inside a script tag is text in that script, and the search for styles resumes after the script. A leading byte-order mark becomes a space too: Svelte's parse strips one, which would shift every offset it reports.

import {blankVerbatimContent} from 'svelte-docinfo/svelte-scripts.ts';

parameters

svelteSource

: string
#

the full Svelte source code

scripts

: readonly ScannedScriptTag[]
#

the source's scanned script tags (scanScriptTags), nested ones included

which style tags keep their content

returns

the source with the verbatim content blanked, the same length

BlankVerbatimContentOptions
#

svelte-scripts.ts view source

import type {BlankVerbatimContentOptions} from 'svelte-docinfo/svelte-scripts.ts';

members

keepStyle

?: (attributes: Map<string, string | true>) => boolean
#

Whether to keep a style tag's content as written, by its opening-tag attributes. Every style's content is blanked when absent.

buildAliasRegistry
#

typescript-alias-registry.ts view source

buildAliasRegistry(sources: readonly AliasRegistrySource[], checker: TypeChecker): AliasRegistry

Build the alias registry for one analysis cycle.

Registration walks each source's export table and registers an export when it:

  • survives the svelte2tsx filters on virtuals (default and generated $$/__sveltets_ names skipped, and stray HTML-comment typedefs, isStrayComponentTypedef)
  • is declared in the file (star-projected bindings skipped, mirroring analyzeExports's locality rule)
  • resolves — through local export clauses, @nodocs-free ones only — to a type alias (isTypeAliasLike: a TypeAliasDeclaration or a JSDoc @typedef/@callback) in the *same* file (a re-export of another module's alias registers from that module when it's emitted, and never when it's gated — gated aliases have no doc page for a reference to land on; merged value+type symbols select the type-space node via selectDeclarationNode)
  • is non-generic (instantiations are per-argument type objects — the declared type of a generic alias never matches a use site)
  • carries no @nodocs on either declaration of a merged pair
  • is alias-lost (isAliasLostType) and passes the safety gate, or is a brand carrying its generic's alias (isRenamedBrand), which needs no gate

Ambiguity — two aliases over one lost type (type A = z.infer<typeof S> beside type B of the same, z.infer vs z.output, cross-module, type A = B over a lost B) resolves to a global single winner via compareStrings on name then module, so one type documents under one name everywhere (coherent cross-linking, deterministic regardless of iteration order). The member-set side index is derived from the settled winners, so the two indexes can't disagree.

import {buildAliasRegistry} from 'svelte-docinfo/typescript-alias-registry.ts';

parameters

sources

: readonly AliasRegistrySource[]
#

the emitted modules (Svelte modules via their virtuals — see AliasRegistrySource)

checker

: TypeChecker
#

the program's type checker (registry entries are valid exactly as long as this checker's types are)

buildRootFileNames
#

typescript-program.ts view source

internal

Shared by both program paths and the test-side program helpers; not a stable API.

buildRootFileNames(tsconfigRoots: Iterable<string>, extraRoots: readonly string[]): string[]

A program's root list: the Svelte shims for extraRoots (see getSvelteShimRoots), then tsconfigRoots, then extraRoots, deduped by path with first occurrence kept. Dedupe covers an extra root the tsconfig also roots, and a shim the tsconfig (or a caller) roots itself.

Callers own the order of extraRoots; the language-service path passes its owned roots sorted, so the list is a function of the file set.

import {buildRootFileNames} from 'svelte-docinfo/typescript-program.ts';

parameters

tsconfigRoots

: Iterable<string>
#

the tsconfig's root file names

extraRoots

: readonly string[]
#

roots beyond the tsconfig's, virtual files included

returns

a fresh array

byKind
#

ClassDeclarationJson
#

types.ts view source

value + type

also exported from index.ts

A class declaration. Has members, extends, implements.

import {ClassDeclarationJson} from 'svelte-docinfo/types.ts';

inheritance

extends: SchemaStrictObjectOutput<typeof ClassDeclarationJsonEntries>

members

kind

: "class"
#

extends

: string[]
#

Extended base class — 0 or 1 entries (TypeScript allows only one base). An array so every heritage field (extends, implements, externalTypes, InterfaceDeclarationJson.extends) shares one shape; consumers iterate heritage uniformly instead of branching on kind.

Verbatim text of this declaration's own heritage clause (as is implements), so it is spelled as this module wrote it and resolves in its scope — a local rename stays the local name, where externalTypes resolves renames because its walk crosses modules.

see also

  • implements (this variant), InterfaceDeclarationJson.extends for the other verbatim heritage fields, externalTypes (this variant) for the resolved external reach.

extendsInfo

: TypeJson[]
#

Structured form of each extends entry, index-aligned with it: always one node per entry, so the usual absence contract (see TypeJson) is relaxed here and a bare Base is a reference node. It follows the written entry as GenericParamJson.constraintInfo does, and a locally renamed import carries its exported name, where the text beside it keeps the local one; a base that isn't a class or interface by name (extends mixin(B), a const holding a class) is a terminal node over its text.

externalTypes

: string[]
#

External types the extends chain reaches whose contributions members never enumerates — the class counterpart of InterfaceDeclarationJson.externalTypes, descending through local base classes. implements contributes nothing: an implemented interface adds no members, the class declares its own.

Entry normalization (rename resolution, type-parameter substitution, text-dedupe, source order) matches TypeDeclarationJson.externalTypes. A direct external base makes this textually equal to extends; consumers dedupe at render time.

implements

: string[]
#

Implemented interfaces.

implementsInfo

: TypeJson[]
#

Structured form of each implements entry, index-aligned with it, as extendsInfo is.

Class members: methods, properties, constructors, getters/setters — own members only, inherited members excluded whatever their origin. Source order, except accessors (getter/setter pairs merged by name), which follow every other member.

alsoExportedFrom

: string[]
#

Module paths (relative to sourceRoot) that re-export this declaration under the same name. The canonical declaration lives in this module's declarations array; these paths are additional import locations for the same thing.

The same edges appear from the re-exporting side as ModuleJson.reExports — use that when asking "what does this module re-export" instead of inverting these arrays. The two can disagree at the margins: a reExports entry whose canonical declaration is @nodocs (or whose module isn't in the analyzed set) has no back-link here.

Consumer note: To build a complete re-export map, scan two fields:

  1. alsoExportedFrom on each declaration — same-name re-exports
  2. aliasOf on declarations — renamed re-exports (separate declarations)

partial

: boolean
#

Whether extraction failed partway through, leaving some fields missing (e.g., typeSignature, parameters).

examples

: string[]
#

Code examples from @example tags.

seeAlso

: string[]
#

Related items from @see tags, in raw TSDoc format.

throws

: ThrowsJson[]
#

Exceptions from @throws tags. type is the tag's written type, and typeInfo its structured form, present for a braced type (@throws {A<B>}) that isn't the whole story as text (see TypeJson); an unbraced tag's leading word never has one, nor does a tag in a component's HTML @component comment, which is read as text.

name

: string
#

The exported name. Always populated. The default-export slot is named 'default', except a Svelte component, which takes its filename-derived name ('X' for X.svelte) — 'default' is the symbol's actual name in JS (import {default as X} and ns.default both expose it directly), and import X from 'mod' is sugar for import {default as X}. Consumers branch on name === 'default' to render the sugar form when desired.

modifiers

: ("public" | "protected" | "readonly" | "static" | "abstract" | "getter" | "setter")[]
#

TypeScript modifiers like readonly, static, or protected.

genericParams

: GenericParamJson[]
#

Generic type parameters like <T, U>.

aliasOf

?: { module: string; name: string; }
#

For renamed re-exports (export {foo as bar}), points to the original declaration. This declaration's name is the alias; aliasOf.name is the original name.

For renames out of the default slot (export {default as bar} from './x' where ./x is export default ...), aliasOf.name is 'default' — the canonical's actual symbol name. Consumers locate the canonical by (aliasOf.module, aliasOf.name).

Svelte component exception: when the source is a .svelte file (e.g., export {default as Foo} from './X.svelte'), the canonical's name is the component name (derived from the filename), so aliasOf.name is the component name ('X'), NOT 'default'. Consumers that branch on aliasOf.name === 'default' to detect default-rename should additionally check whether aliasOf.module ends with .svelte.

Different from alsoExportedFrom: aliases create new API surface names, while alsoExportedFrom tracks additional import paths for the same name.

A type-only rename of a value (export type {someConst as c} from './x') synthesizes a normal alias — declarations carry no type-only marker.

deprecatedMessage

?: string
#

Deprecation message from @deprecated tag.

since

?: string
#

Version introduced, from @since tag.

internalMessage

?: string
#

Internal-API marker from the @internal tag. Presence means the tag was written; an empty string is a bare tag with no trailing prose.

A marker, not an exclusion: @internal means "not stable public API" (TSDoc semantics) while the declaration, member, or prop stays documented — unlike @nodocs, which removes a declaration from output entirely (and is ignored on props and members).

mutates

?: Record<string, string>
#

Mutation documentation from @mutates tags (non-standard), mapping keys to descriptions.

Keys are intentionally unvalidated — typically a parameter name, but authors may also use compound paths (this.foo, obj.field) or multi-word external state references. Backticks are stripped from keys so `` a `` and a normalize to one key; an empty-string value is a bare tag with no description. The schema accepts any string key so consumers can render whatever the author wrote.

On a component prop it declares the component's mutation contract for the value it's handed: the component writes into the prop's object or array in place (@mutates items - appends the selected entry, @mutates options.cache - fills on first render). Reassigning a prop is not a mutation in this sense (bindable covers it), though a $bindable prop can carry both.

docComment

?: string
#

JSDoc/TSDoc comment.

typeSignature

?: string
#

Full TypeScript type signature.

sourceLine

?: number
#

1-based line in the source file, a positive integer. Synthesized aliases (see aliasOf) carry the local export specifier's line, not the canonical's.

ClassDeclarationJsonInput
#

types.ts view source

The input ClassDeclarationJson parses, with any field it defaults optional.

import type {ClassDeclarationJsonInput} from 'svelte-docinfo/types.ts';

inheritance

extends: SchemaStrictObjectInput<typeof ClassDeclarationJsonEntries>

members

kind

: "class"
#

name

: string
#

The exported name. Always populated. The default-export slot is named 'default', except a Svelte component, which takes its filename-derived name ('X' for X.svelte) — 'default' is the symbol's actual name in JS (import {default as X} and ns.default both expose it directly), and import X from 'mod' is sugar for import {default as X}. Consumers branch on name === 'default' to render the sugar form when desired.

extends

?: string[]
#

Extended base class — 0 or 1 entries (TypeScript allows only one base). An array so every heritage field (extends, implements, externalTypes, InterfaceDeclarationJson.extends) shares one shape; consumers iterate heritage uniformly instead of branching on kind.

Verbatim text of this declaration's own heritage clause (as is implements), so it is spelled as this module wrote it and resolves in its scope — a local rename stays the local name, where externalTypes resolves renames because its walk crosses modules.

see also

  • implements (this variant), InterfaceDeclarationJson.extends for the other verbatim heritage fields, externalTypes (this variant) for the resolved external reach.

extendsInfo

?: TypeJson[]
#

Structured form of each extends entry, index-aligned with it: always one node per entry, so the usual absence contract (see TypeJson) is relaxed here and a bare Base is a reference node. It follows the written entry as GenericParamJson.constraintInfo does, and a locally renamed import carries its exported name, where the text beside it keeps the local one; a base that isn't a class or interface by name (extends mixin(B), a const holding a class) is a terminal node over its text.

externalTypes

?: string[]
#

External types the extends chain reaches whose contributions members never enumerates — the class counterpart of InterfaceDeclarationJson.externalTypes, descending through local base classes. implements contributes nothing: an implemented interface adds no members, the class declares its own.

Entry normalization (rename resolution, type-parameter substitution, text-dedupe, source order) matches TypeDeclarationJson.externalTypes. A direct external base makes this textually equal to extends; consumers dedupe at render time.

implements

?: string[]
#

Implemented interfaces.

implementsInfo

?: TypeJson[]
#

Structured form of each implements entry, index-aligned with it, as extendsInfo is.

Class members: methods, properties, constructors, getters/setters — own members only, inherited members excluded whatever their origin. Source order, except accessors (getter/setter pairs merged by name), which follow every other member.

alsoExportedFrom

?: string[]
#

Module paths (relative to sourceRoot) that re-export this declaration under the same name. The canonical declaration lives in this module's declarations array; these paths are additional import locations for the same thing.

The same edges appear from the re-exporting side as ModuleJson.reExports — use that when asking "what does this module re-export" instead of inverting these arrays. The two can disagree at the margins: a reExports entry whose canonical declaration is @nodocs (or whose module isn't in the analyzed set) has no back-link here.

Consumer note: To build a complete re-export map, scan two fields:

  1. alsoExportedFrom on each declaration — same-name re-exports
  2. aliasOf on declarations — renamed re-exports (separate declarations)

aliasOf

?: { module: string; name: string; }
#

For renamed re-exports (export {foo as bar}), points to the original declaration. This declaration's name is the alias; aliasOf.name is the original name.

For renames out of the default slot (export {default as bar} from './x' where ./x is export default ...), aliasOf.name is 'default' — the canonical's actual symbol name. Consumers locate the canonical by (aliasOf.module, aliasOf.name).

Svelte component exception: when the source is a .svelte file (e.g., export {default as Foo} from './X.svelte'), the canonical's name is the component name (derived from the filename), so aliasOf.name is the component name ('X'), NOT 'default'. Consumers that branch on aliasOf.name === 'default' to detect default-rename should additionally check whether aliasOf.module ends with .svelte.

Different from alsoExportedFrom: aliases create new API surface names, while alsoExportedFrom tracks additional import paths for the same name.

A type-only rename of a value (export type {someConst as c} from './x') synthesizes a normal alias — declarations carry no type-only marker.

partial

?: boolean
#

Whether extraction failed partway through, leaving some fields missing (e.g., typeSignature, parameters).

examples

?: string[]
#

Code examples from @example tags.

deprecatedMessage

?: string
#

Deprecation message from @deprecated tag.

seeAlso

?: string[]
#

Related items from @see tags, in raw TSDoc format.

throws

?: ThrowsJsonInput[]
#

Exceptions from @throws tags. type is the tag's written type, and typeInfo its structured form, present for a braced type (@throws {A<B>}) that isn't the whole story as text (see TypeJson); an unbraced tag's leading word never has one, nor does a tag in a component's HTML @component comment, which is read as text.

since

?: string
#

Version introduced, from @since tag.

internalMessage

?: string
#

Internal-API marker from the @internal tag. Presence means the tag was written; an empty string is a bare tag with no trailing prose.

A marker, not an exclusion: @internal means "not stable public API" (TSDoc semantics) while the declaration, member, or prop stays documented — unlike @nodocs, which removes a declaration from output entirely (and is ignored on props and members).

mutates

?: Record<string, string>
#

Mutation documentation from @mutates tags (non-standard), mapping keys to descriptions.

Keys are intentionally unvalidated — typically a parameter name, but authors may also use compound paths (this.foo, obj.field) or multi-word external state references. Backticks are stripped from keys so `` a `` and a normalize to one key; an empty-string value is a bare tag with no description. The schema accepts any string key so consumers can render whatever the author wrote.

On a component prop it declares the component's mutation contract for the value it's handed: the component writes into the prop's object or array in place (@mutates items - appends the selected entry, @mutates options.cache - fills on first render). Reassigning a prop is not a mutation in this sense (bindable covers it), though a $bindable prop can carry both.

docComment

?: string
#

JSDoc/TSDoc comment.

typeSignature

?: string
#

Full TypeScript type signature.

modifiers

?: ("public" | "protected" | "readonly" | "static" | "abstract" | "getter" | "setter")[]
#

TypeScript modifiers like readonly, static, or protected.

sourceLine

?: number
#

1-based line in the source file, a positive integer. Synthesized aliases (see aliasOf) carry the local export specifier's line, not the canonical's.

genericParams

?: GenericParamJsonInput[]
#

Generic type parameters like <T, U>.

ClassMemberDiagnostic
#

diagnostics.ts view source

value + type

Class member analysis failed.

import {ClassMemberDiagnostic} from 'svelte-docinfo/diagnostics.ts';

inheritance

extends: SchemaStrictObjectOutput<typeof ClassMemberDiagnosticEntries>

members

kind

: "class_member_failed"
#

className

: string
#

Name of the class.

memberName

: string
#

Name of the member that failed.

file

: string
#

File path relative to project root (no leading slash, no ./ prefix).

Normalized at every public API boundary — session.setFile/setFiles (ingest-time), session.query (query-time, via analyzeCore), and the one-shot wrappers analyze / analyzeFromFiles. Producers inside the pipeline may write absolute or virtual paths (e.g., Foo.svelte.__svelte2tsx__.ts); normalization rewrites them to project-relative form before they reach consumers.

The exception is discovery — discoverSourceFiles / discoverFromExports return their diagnostics unnormalized, since they run before any session exists. Their file is already project-root-relative, but message can embed an absolute path (an fs error names the file it failed on), so a consumer wiring discovery up itself owns the normalizeDiagnosticPaths call — analyzeFromFiles and the Vite plugin both make it before merging.

The absolute form is the one to write. Normalization deliberately leaves an already-relative path alone (relativizing it would resolve against cwd), so a producer writing a ModuleJson.path — relative to sourceRoot, a different base — passes through untouched and publishes the same file under a second name. Absolute is what the pass can actually correct.

message

: string
#

Human-readable description of the issue.

severity

: "error" | "warning"
#

line

?: number
#

Line number (1-based), absent if location unavailable.

column

?: number
#

Column number (1-based), absent if location unavailable.

ClassMemberDiagnosticInput
#

diagnostics.ts view source

The input ClassMemberDiagnostic parses, with any field it defaults optional.

import type {ClassMemberDiagnosticInput} from 'svelte-docinfo/diagnostics.ts';

inheritance

extends: SchemaStrictObjectInput<typeof ClassMemberDiagnosticEntries>

members

kind

: "class_member_failed"
#

className

: string
#

Name of the class.

memberName

: string
#

Name of the member that failed.

file

: string
#

File path relative to project root (no leading slash, no ./ prefix).

Normalized at every public API boundary — session.setFile/setFiles (ingest-time), session.query (query-time, via analyzeCore), and the one-shot wrappers analyze / analyzeFromFiles. Producers inside the pipeline may write absolute or virtual paths (e.g., Foo.svelte.__svelte2tsx__.ts); normalization rewrites them to project-relative form before they reach consumers.

The exception is discovery — discoverSourceFiles / discoverFromExports return their diagnostics unnormalized, since they run before any session exists. Their file is already project-root-relative, but message can embed an absolute path (an fs error names the file it failed on), so a consumer wiring discovery up itself owns the normalizeDiagnosticPaths call — analyzeFromFiles and the Vite plugin both make it before merging.

The absolute form is the one to write. Normalization deliberately leaves an already-relative path alone (relativizing it would resolve against cwd), so a producer writing a ModuleJson.path — relative to sourceRoot, a different base — passes through untouched and publishes the same file under a second name. Absolute is what the pass can actually correct.

message

: string
#

Human-readable description of the issue.

severity

: "error" | "warning"
#

line

?: number
#

Line number (1-based), absent if location unavailable.

column

?: number
#

Column number (1-based), absent if location unavailable.

cleanComment
#

tsdoc.ts view source

cleanComment(commentText: string): string | undefined

Clean raw JSDoc comment text by removing comment markers and leading asterisks.

Transforms /** ... *\/ style comments into clean text.

import {cleanComment} from 'svelte-docinfo/tsdoc.ts';

parameters

commentText

: string
#

the raw comment text including /** and *\/ markers

returns

cleaned comment text, or undefined if empty after cleaning

examples

cleanComment('/** Hello world *\/') // => 'Hello world' cleanComment('/**\n * Line 1\n * Line 2\n *\/') // => 'Line 1\nLine 2'

CliOptions
#

cli.ts view source

CLI options parsed from command line arguments.

import type {CliOptions} from 'svelte-docinfo/cli.ts';

members

include

?: string[]
#

File patterns to include (undefined = use exports discovery or defaults).

Relative to the project root; an absolute pattern inside it relativizes, an out-of-root one throws.

exclude

?: string[]
#

File patterns to exclude (undefined = use defaults — test/spec files and internal/ directories).

When provided, fully replaces the defaults (the API's callback form has no CLI equivalent) — see ExcludeOption.

output

?: string
#

Output file path (undefined = stdout).

resolveDependencies

?: boolean
#

Whether to resolve dependencies. Mapped from the --no-resolve-dependencies flag (commander populates true by default; false when the flag is passed). Optional here so external callers can omit it; treated as true when undefined.

discovery

?: Discovery
#

Discovery strategy (undefined = 'auto').

Mapped from --discovery <auto|exports|glob>.

distDir

?: string
#

Dist directory name for exports-based discovery (undefined = 'dist').

sourceDir

?: string[]
#

Source directories, relative to project root or absolute inside it (undefined = ['src/lib']); an out-of-root entry throws.

Repeatable. Drives the implicit include glob in the glob-discovery fallback (via deriveIncludePatterns inside discoverSourceFiles) so custom source directories survive without needing an explicit --include.

sourceRoot

?: string
#

Source root for module path extraction, relative to project root or absolute inside it (undefined = single sourceDir or longest common prefix).

Module paths in output are stripped of <projectRoot>/<sourceRoot>/. Pass . (or "") to keep module paths project-relative — useful when sourceDir entries share no common prefix. The . form is normalized to "" inside normalizeSourceOptions.

onDuplicates

?: OnDuplicates
#

Opt-in check that declaration names are unique across modules (see OnDuplicates). Undefined skips the check.

tsconfig

?: string | false
#

Path to the tsconfig, relative to the project root (undefined = tsconfig.json), or false to analyze without one.

Mapped from --tsconfig <path> and --no-tsconfig.

only

?: string[]
#

Glob patterns to filter the emitted modules array against ModuleJson.path (undefined = emit all analyzed modules).

Repeatable. Output-only filter: full-project analysis still runs so re-exports, dependents, and alsoExportedFrom stay correct against the complete owned set. Diagnostics aren't filtered — they may reference modules dropped from output.

quiet

?: boolean
#

Whether to suppress info messages to stderr. Treated as false when undefined.

pretty

?: boolean
#

Whether to pretty-print JSON output. Treated as false when undefined.

CommonjsUnsupportedDiagnostic
#

diagnostics.ts view source

value + type

A JS module exports through CommonJS (module.exports = …, exports.x = …), which isn't modeled.

The module still emits, with no declarations; line/column point at the first export assignment. Fires only when the checker gives the file no module symbol (no ES syntax under bundler/esnext) and a top-level statement assigns to module.exports or exports. A file with ES syntax is an ES module, its assignments ordinary code; under node16/nodenext or moduleDetection: 'force' the checker binds the CommonJS exports itself, and its named exports (exports.x, module.exports = {a, b}) document, with no warning; a module.exports = of a non-object documents nothing. A script with no exports either way (require calls alone), or one whose own top-level declaration binds exports or module, doesn't fire.

Always warning, query-time category (recomputed each query()).

import {CommonjsUnsupportedDiagnostic} from 'svelte-docinfo/diagnostics.ts';

inheritance

extends: SchemaStrictObjectOutput<typeof CommonjsUnsupportedDiagnosticEntries>

members

kind

: "commonjs_unsupported"
#

file

: string
#

File path relative to project root (no leading slash, no ./ prefix).

Normalized at every public API boundary — session.setFile/setFiles (ingest-time), session.query (query-time, via analyzeCore), and the one-shot wrappers analyze / analyzeFromFiles. Producers inside the pipeline may write absolute or virtual paths (e.g., Foo.svelte.__svelte2tsx__.ts); normalization rewrites them to project-relative form before they reach consumers.

The exception is discovery — discoverSourceFiles / discoverFromExports return their diagnostics unnormalized, since they run before any session exists. Their file is already project-root-relative, but message can embed an absolute path (an fs error names the file it failed on), so a consumer wiring discovery up itself owns the normalizeDiagnosticPaths call — analyzeFromFiles and the Vite plugin both make it before merging.

The absolute form is the one to write. Normalization deliberately leaves an already-relative path alone (relativizing it would resolve against cwd), so a producer writing a ModuleJson.path — relative to sourceRoot, a different base — passes through untouched and publishes the same file under a second name. Absolute is what the pass can actually correct.

message

: string
#

Human-readable description of the issue.

severity

: "error" | "warning"
#

line

?: number
#

Line number (1-based), absent if location unavailable.

column

?: number
#

Column number (1-based), absent if location unavailable.

CommonjsUnsupportedDiagnosticInput
#

diagnostics.ts view source

The input CommonjsUnsupportedDiagnostic parses, with any field it defaults optional.

import type {CommonjsUnsupportedDiagnosticInput} from 'svelte-docinfo/diagnostics.ts';

inheritance

extends: SchemaStrictObjectInput<typeof CommonjsUnsupportedDiagnosticEntries>

members

kind

: "commonjs_unsupported"
#

file

: string
#

File path relative to project root (no leading slash, no ./ prefix).

Normalized at every public API boundary — session.setFile/setFiles (ingest-time), session.query (query-time, via analyzeCore), and the one-shot wrappers analyze / analyzeFromFiles. Producers inside the pipeline may write absolute or virtual paths (e.g., Foo.svelte.__svelte2tsx__.ts); normalization rewrites them to project-relative form before they reach consumers.

The exception is discovery — discoverSourceFiles / discoverFromExports return their diagnostics unnormalized, since they run before any session exists. Their file is already project-root-relative, but message can embed an absolute path (an fs error names the file it failed on), so a consumer wiring discovery up itself owns the normalizeDiagnosticPaths call — analyzeFromFiles and the Vite plugin both make it before merging.

The absolute form is the one to write. Normalization deliberately leaves an already-relative path alone (relativizing it would resolve against cwd), so a producer writing a ModuleJson.path — relative to sourceRoot, a different base — passes through untouched and publishes the same file under a second name. Absolute is what the pass can actually correct.

message

: string
#

Human-readable description of the issue.

severity

: "error" | "warning"
#

line

?: number
#

Line number (1-based), absent if location unavailable.

column

?: number
#

Column number (1-based), absent if location unavailable.

compactReplacer
#

declaration-helpers.ts view source

also exported from index.ts

compactReplacer(key: string, value: unknown): unknown

JSON replacer that strips schema default values for compact serialization.

Strips empty arrays and false booleans — both are schema defaults restored by parseAnalyzeResult / parseModuleJson, so the round-trip is lossless for svelte-docinfo types. Assumes all boolean fields in the schema default to false — a true-defaulted boolean would need its false values preserved, breaking the round-trip.

One keyed exemption: value is never stripped. TypeJson's literal nodes carry data there ({kind: 'literal', value: false} is the literal type false, required by the schema), not a defaulted flag — no other output field is named value, and any future one must not be a false-defaulted boolean.

Root-value caveat: JSON.stringify([], compactReplacer) returns the JS undefined (not the string '[]'), and JSON.stringify(false, compactReplacer) returns the JS undefined too. Object-rooted callers (AnalyzeResultJson envelope, CLI output) don't hit this — empty inner arrays strip and parseAnalyzeResult restores them on the consumer side. Array-rooted callers (Vite plugin, anyone splicing the JSON into a source template) must handle the empty case themselves before calling this; see vite.ts:updateOutputFromQuery for the pattern.

Guard tests in declaration-helpers.test.ts lock this in:

  • every defaulted v.boolean() in types.ts defaults to false — source-regex check that fails on a new v.optional(v.boolean(), true).
  • every schema default is false or a fresh-array factory — walks the schema tree from AnalyzeResultJson, so a default the replacer can't restore (or a shared literal []) fails wherever it's declared.
  • `parse → stringify(compactReplacer) → parse is a faithful round-trip across every variant` — exercises every variant and member through a full round-trip, catching regressions where a false or [] default is removed (or a new field is added that the replacer drops but the schema doesn't restore).
import {compactReplacer} from 'svelte-docinfo/declaration-helpers.ts';

examples

const result = await analyze({sourceFiles, sourceOptions}); const json = JSON.stringify(result, compactReplacer); // on the consumer side, restore the defaults: const restored = parseAnalyzeResult(JSON.parse(json));

compareStrings
#

postprocess.ts view source

compareStrings(a: string, b: string): number

Case-insensitive string comparator for deterministic output ordering.

Case-folded comparison first (so Analyze and analyze sort together instead of all uppercase before all lowercase), then a code-unit tiebreak — so equal-ignoring-case strings still compare unequal and the result is an exact total order. Unlike localeCompare (host-locale/ICU-dependent, so byte-identical input can serialize in different orders on different machines), both passes use Unicode default mappings only and are environment-independent. All output ordering goes through this comparator — never bare localeCompare or default Array.prototype.sort.

import {compareStrings} from 'svelte-docinfo/postprocess.ts';

ComponentCommentMismatchDiagnostic
#

diagnostics.ts view source

value + type

svelte2tsx, and so editor hover, documents a component with a different HTML comment than the analyzer does.

The analyzer reads the first HTML comment with a line starting @component; svelte2tsx takes the last one containing @component anywhere, so a second component comment or a mid-prose mention (a backticked @component in a module comment) takes its slot. line is the comment svelte2tsx picks; reword its @component to agree. Not emitted when in-script JSDoc supplies the component's doc.

import {ComponentCommentMismatchDiagnostic} from 'svelte-docinfo/diagnostics.ts';

inheritance

extends: SchemaStrictObjectOutput<typeof ComponentCommentMismatchDiagnosticEntries>

members

kind

: "component_comment_mismatch"
#

file

: string
#

File path relative to project root (no leading slash, no ./ prefix).

Normalized at every public API boundary — session.setFile/setFiles (ingest-time), session.query (query-time, via analyzeCore), and the one-shot wrappers analyze / analyzeFromFiles. Producers inside the pipeline may write absolute or virtual paths (e.g., Foo.svelte.__svelte2tsx__.ts); normalization rewrites them to project-relative form before they reach consumers.

The exception is discovery — discoverSourceFiles / discoverFromExports return their diagnostics unnormalized, since they run before any session exists. Their file is already project-root-relative, but message can embed an absolute path (an fs error names the file it failed on), so a consumer wiring discovery up itself owns the normalizeDiagnosticPaths call — analyzeFromFiles and the Vite plugin both make it before merging.

The absolute form is the one to write. Normalization deliberately leaves an already-relative path alone (relativizing it would resolve against cwd), so a producer writing a ModuleJson.path — relative to sourceRoot, a different base — passes through untouched and publishes the same file under a second name. Absolute is what the pass can actually correct.

message

: string
#

Human-readable description of the issue.

severity

: "error" | "warning"
#

line

?: number
#

Line number (1-based), absent if location unavailable.

column

?: number
#

Column number (1-based), absent if location unavailable.

ComponentCommentMismatchDiagnosticInput
#

diagnostics.ts view source

The input ComponentCommentMismatchDiagnostic parses, with any field it defaults optional.

import type {ComponentCommentMismatchDiagnosticInput} from 'svelte-docinfo/diagnostics.ts';

inheritance

extends: SchemaStrictObjectInput<typeof ComponentCommentMismatchDiagnosticEntries>

members

kind

: "component_comment_mismatch"
#

file

: string
#

File path relative to project root (no leading slash, no ./ prefix).

Normalized at every public API boundary — session.setFile/setFiles (ingest-time), session.query (query-time, via analyzeCore), and the one-shot wrappers analyze / analyzeFromFiles. Producers inside the pipeline may write absolute or virtual paths (e.g., Foo.svelte.__svelte2tsx__.ts); normalization rewrites them to project-relative form before they reach consumers.

The exception is discovery — discoverSourceFiles / discoverFromExports return their diagnostics unnormalized, since they run before any session exists. Their file is already project-root-relative, but message can embed an absolute path (an fs error names the file it failed on), so a consumer wiring discovery up itself owns the normalizeDiagnosticPaths call — analyzeFromFiles and the Vite plugin both make it before merging.

The absolute form is the one to write. Normalization deliberately leaves an already-relative path alone (relativizing it would resolve against cwd), so a producer writing a ModuleJson.path — relative to sourceRoot, a different base — passes through untouched and publishes the same file under a second name. Absolute is what the pass can actually correct.

message

: string
#

Human-readable description of the issue.

severity

: "error" | "warning"
#

line

?: number
#

Line number (1-based), absent if location unavailable.

column

?: number
#

Column number (1-based), absent if location unavailable.

ComponentCss
#

svelte-css.ts view source

What analyzeComponentCss reads from a component.

import type {ComponentCss} from 'svelte-docinfo/svelte-css.ts';

members

The styling API, in the order of each name's first read.

reads

?: Map<string, ComponentCssRead>
#

Every custom property the component reads through var(), by name: in its <style> at any nesting (var(--a, var(--b)) reads both), and in the static text of its markup's style attributes, style: directives, and child components' style and --a attributes. Names the component sets itself included. undefined when the style wasn't read (problem).

Why the style wasn't read, when it wasn't.

ComponentCssProblem
#

svelte-css.ts view source

type { kind: "css_parse_failed"; message: string; line?: number; column?: number; } | { kind: "css_lang_unsupported"; message: string; lang: string; line: number; column: number; }

Why a component's styling API wasn't read.

import type {ComponentCssProblem} from 'svelte-docinfo/svelte-css.ts';

ComponentCssPropertyJson
#

types.ts view source

value + type

also exported from index.ts

A CSS custom property in a Svelte component's styling API: one a consumer sets on the component (<A --a_color="red" />) or on an ancestor, read by the component's styles.

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

import {ComponentCssPropertyJson} from 'svelte-docinfo/types.ts';

inheritance

extends: SchemaStrictObjectOutput<typeof ComponentCssPropertyJsonEntries>

members

name

: string
#

The custom property's name as written, -- included (--a_color); case-sensitive, as in CSS.

sourceLine

: number
#

1-based line in the original .svelte source of the property's first var() read, or for a documented property the component never reads, of its @cssprop tag.

documented

: boolean
#

Whether a @cssprop tag in the component's doc comment documents the property, as opposed to the fallback-read heuristic (or an @property rule) finding it alone. A consumer can list only the documented entries when a component has any, dropping the global tokens the heuristic also catches.

description

?: string
#

The @cssprop tag's description, raw like docComment. Only on a documented entry.

syntax

?: string
#

The property's value syntax, verbatim, unvalidated: the @cssprop tag's braced syntax (@cssprop {<color>} --a gives <color>), else the syntax descriptor of an @property rule for the name in the component's style, its quotes stripped (syntax: '<color>' gives <color>).

fallback

?: string
#

What the style gives the property when a consumer doesn't set it: the initial-value of an @property rule for the name in the component's style (a registered property is never unset, so its initial value applies whatever a read falls back to), else the fallback of the first var() read with one, the verbatim source text after the comma, trimmed, comments included (var(--a, var(--b, 1px)) gives var(--b, 1px)). Empty for var(--a,), a fallback of nothing. Absent for a documented property no read gives a fallback. Code fact only; the tag's claim is default, and cssprop_default_mismatch warns when the two disagree.

default

?: string
#

The @cssprop tag's bracketed default (@cssprop [--a=1px] gives 1px), verbatim and trimmed. Only on a documented entry. The author's claim beside fallback, the style's fact; a renderer wanting one value takes default ?? fallback.

see also

ComponentCssPropertyJsonInput
#

types.ts view source

The input ComponentCssPropertyJson parses, with any field it defaults optional.

import type {ComponentCssPropertyJsonInput} from 'svelte-docinfo/types.ts';

inheritance

extends: SchemaStrictObjectInput<typeof ComponentCssPropertyJsonEntries>

members

name

: string
#

The custom property's name as written, -- included (--a_color); case-sensitive, as in CSS.

sourceLine

: number
#

1-based line in the original .svelte source of the property's first var() read, or for a documented property the component never reads, of its @cssprop tag.

description

?: string
#

The @cssprop tag's description, raw like docComment. Only on a documented entry.

syntax

?: string
#

The property's value syntax, verbatim, unvalidated: the @cssprop tag's braced syntax (@cssprop {<color>} --a gives <color>), else the syntax descriptor of an @property rule for the name in the component's style, its quotes stripped (syntax: '<color>' gives <color>).

fallback

?: string
#

What the style gives the property when a consumer doesn't set it: the initial-value of an @property rule for the name in the component's style (a registered property is never unset, so its initial value applies whatever a read falls back to), else the fallback of the first var() read with one, the verbatim source text after the comma, trimmed, comments included (var(--a, var(--b, 1px)) gives var(--b, 1px)). Empty for var(--a,), a fallback of nothing. Absent for a documented property no read gives a fallback. Code fact only; the tag's claim is default, and cssprop_default_mismatch warns when the two disagree.

default

?: string
#

The @cssprop tag's bracketed default (@cssprop [--a=1px] gives 1px), verbatim and trimmed. Only on a documented entry. The author's claim beside fallback, the style's fact; a renderer wanting one value takes default ?? fallback.

documented

?: boolean
#

Whether a @cssprop tag in the component's doc comment documents the property, as opposed to the fallback-read heuristic (or an @property rule) finding it alone. A consumer can list only the documented entries when a component has any, dropping the global tokens the heuristic also catches.

ComponentCssRead
#

svelte-css.ts view source

A custom property the component reads somewhere, as documentCssProperties checks a tag.

import type {ComponentCssRead} from 'svelte-docinfo/svelte-css.ts';

members

line

: number
#

1-based line of the first read in the original source, preferring an outermost one.

fallback

: string | undefined
#

The value the property takes when a consumer doesn't set it: an @property rule's initial-value, else the first fallback any read gives, preferring an outermost one's.

syntax

?: string
#

An @property rule's syntax for the name, quotes stripped.

ComponentDeclarationJson
#

types.ts view source

value + type

also exported from index.ts

A Svelte component declaration. Has props, externalTypes, acceptsChildren, cssCustomProperties.

import {ComponentDeclarationJson} from 'svelte-docinfo/types.ts';

inheritance

extends: SchemaStrictObjectOutput<typeof ComponentDeclarationJsonEntries>

members

kind

: "component"
#

externalTypes

: string[]
#

External types whose properties are filtered out of props — the attribute bags a component forwards, such as HTMLButtonAttributes or SvelteHTMLElements['button']. A bag stays listed when some of its properties are documented anyway because the $props() destructuring names them (see props).

Covers every way props compose them: an intersection or union branch, a bare or indexed-access annotation, and interface Props extends Bag (directly or through a local base). Entries carry the written form with the same normalizations as TypeDeclarationJson.externalTypes: import renames at the definition site resolve to the exported name, and a type parameter bound inside the descent substitutes its written argument — interface A<T> extends HTMLAttributes<T> reached via `Props extends A<HTMLDivElement> records HTMLAttributes<HTMLDivElement>`. The component's *own* generics stay in scope and emit as written (HTMLAttributes<T> beside the genericParams documenting T). Each distinct bag appears once, in source order; a local name is used only when it hides a definition the walk cannot traverse (a mapped or conditional type). Names carry no module, so two distinct bags sharing an exported name collapse to one entry.

see also

Svelte component props, in source order.

Properties an external type contributes are left out (externalTypes names their bags), except the ones the $props() destructuring names: type in let {type = 'button', ...rest}: HTMLButtonAttributes = $props() is documented with the external declaration's type and JSDoc. Renamed (class: className) and nested (a: {b}) elements name their prop; the rest element names nothing, and a name the props type has only through an index signature isn't admitted. Admitted props follow the others, in destructuring order, since their declaration position is in a package.

acceptsChildren

: boolean
#

Whether the component accepts children: an explicit or inherited Snippet-typed children prop, implicit template usage, or a default slot (<slot /> or a declared $$Slots) in a legacy component, one svelte2tsx reads as runes-less. A runes component's <slot /> doesn't set it, and neither does a named slot alone.

cssCustomProperties

: ComponentCssPropertyJson[]
#

The component's styling API: the CSS custom properties its styles read with a fallback (var(--a, 1px)), the pattern Svelte's own docs give for a component's styling hooks, or read bare and register with @property, and leave for a consumer to set, plus the ones its doc comment documents with @cssprop. One entry per name: the documented ones first, in tag order, then the rest in the order of each name's first read.

A read counts when it's an outermost var(), not one in another var()'s fallback: var(--a, var(--b)) reads --a, with --b the fallback chain's global token. Reads anywhere in the top-level <style> count, in :global(…) rules, nested rules, @media/@container/@supports blocks, and keyframes alike, and so do reads in the static text of the markup's style attributes and style: directives on elements and style and --a attributes on child components (<Child --a="var(--b, 1px)" /> reads --b). A name drops out when the component sets it itself: a --a: … declaration in its <style>, a style:--a directive, or a --a: in a style attribute on one of its elements. A --a or style attribute on a child component sets nothing, since it styles the child. A name read only without a fallback isn't listed, unless the style registers it with @property --a {…}, whose syntax and initial-value the entry carries (the last rule for a name wins; inherits isn't modeled); a registered name nothing reads isn't listed either: bare reads are mostly global design tokens. A global token read with a fallback is listed too; the author's fix is to drop the fallback or to document the property with @cssprop. There's deliberately no option to filter names at analysis: the output keeps every read, and a consumer that wants less filters it (to documented entries, say). Names are case-sensitive, as in CSS.

@cssprop --a - Description 1 (or @cssproperty) in the component's doc comment, the source that wins docComment (the in-script JSDoc over the HTML @component comment, the losing one's tags ignored), lists --a whatever the heuristic makes of it, documented: true, with the tag's description, syntax, and default. It merges with the read: a bare read, one nested in another's fallback, one the component sets itself, or one in its markup's static style text counts, giving sourceLine and fallback. A name the component never reads stays, at the tag's line, and warns unknown_cssprop; a tag default the style's fallback disagrees with warns cssprop_default_mismatch; a tag that names no property warns malformed_tag, and one repeating a name duplicate_tag, each dropped.

Without tags, empty when the component has no <style> and no markup read, when its style's lang (or type) names a preprocessor language (css_lang_unsupported), or when Svelte's parser rejects the component (css_parse_failed); tagged properties are listed even then.

alsoExportedFrom

: string[]
#

Module paths (relative to sourceRoot) that re-export this declaration under the same name. The canonical declaration lives in this module's declarations array; these paths are additional import locations for the same thing.

The same edges appear from the re-exporting side as ModuleJson.reExports — use that when asking "what does this module re-export" instead of inverting these arrays. The two can disagree at the margins: a reExports entry whose canonical declaration is @nodocs (or whose module isn't in the analyzed set) has no back-link here.

Consumer note: To build a complete re-export map, scan two fields:

  1. alsoExportedFrom on each declaration — same-name re-exports
  2. aliasOf on declarations — renamed re-exports (separate declarations)

partial

: boolean
#

Whether extraction failed partway through, leaving some fields missing (e.g., typeSignature, parameters).

examples

: string[]
#

Code examples from @example tags.

seeAlso

: string[]
#

Related items from @see tags, in raw TSDoc format.

throws

: ThrowsJson[]
#

Exceptions from @throws tags. type is the tag's written type, and typeInfo its structured form, present for a braced type (@throws {A<B>}) that isn't the whole story as text (see TypeJson); an unbraced tag's leading word never has one, nor does a tag in a component's HTML @component comment, which is read as text.

name

: string
#

The exported name. Always populated. The default-export slot is named 'default', except a Svelte component, which takes its filename-derived name ('X' for X.svelte) — 'default' is the symbol's actual name in JS (import {default as X} and ns.default both expose it directly), and import X from 'mod' is sugar for import {default as X}. Consumers branch on name === 'default' to render the sugar form when desired.

modifiers

: ("public" | "protected" | "readonly" | "static" | "abstract" | "getter" | "setter")[]
#

TypeScript modifiers like readonly, static, or protected.

genericParams

: GenericParamJson[]
#

Generic type parameters like <T, U>.

lang

?: "js"
#

Script language. undefined means TypeScript (default), 'js' for JS-only components.

aliasOf

?: { module: string; name: string; }
#

For renamed re-exports (export {foo as bar}), points to the original declaration. This declaration's name is the alias; aliasOf.name is the original name.

For renames out of the default slot (export {default as bar} from './x' where ./x is export default ...), aliasOf.name is 'default' — the canonical's actual symbol name. Consumers locate the canonical by (aliasOf.module, aliasOf.name).

Svelte component exception: when the source is a .svelte file (e.g., export {default as Foo} from './X.svelte'), the canonical's name is the component name (derived from the filename), so aliasOf.name is the component name ('X'), NOT 'default'. Consumers that branch on aliasOf.name === 'default' to detect default-rename should additionally check whether aliasOf.module ends with .svelte.

Different from alsoExportedFrom: aliases create new API surface names, while alsoExportedFrom tracks additional import paths for the same name.

A type-only rename of a value (export type {someConst as c} from './x') synthesizes a normal alias — declarations carry no type-only marker.

deprecatedMessage

?: string
#

Deprecation message from @deprecated tag.

since

?: string
#

Version introduced, from @since tag.

internalMessage

?: string
#

Internal-API marker from the @internal tag. Presence means the tag was written; an empty string is a bare tag with no trailing prose.

A marker, not an exclusion: @internal means "not stable public API" (TSDoc semantics) while the declaration, member, or prop stays documented — unlike @nodocs, which removes a declaration from output entirely (and is ignored on props and members).

mutates

?: Record<string, string>
#

Mutation documentation from @mutates tags (non-standard), mapping keys to descriptions.

Keys are intentionally unvalidated — typically a parameter name, but authors may also use compound paths (this.foo, obj.field) or multi-word external state references. Backticks are stripped from keys so `` a `` and a normalize to one key; an empty-string value is a bare tag with no description. The schema accepts any string key so consumers can render whatever the author wrote.

On a component prop it declares the component's mutation contract for the value it's handed: the component writes into the prop's object or array in place (@mutates items - appends the selected entry, @mutates options.cache - fills on first render). Reassigning a prop is not a mutation in this sense (bindable covers it), though a $bindable prop can carry both.

docComment

?: string
#

JSDoc/TSDoc comment.

typeSignature

?: string
#

Full TypeScript type signature.

sourceLine

?: number
#

1-based line in the source file, a positive integer. Synthesized aliases (see aliasOf) carry the local export specifier's line, not the canonical's.

ComponentDeclarationJsonInput
#

types.ts view source

The input ComponentDeclarationJson parses, with any field it defaults optional.

import type {ComponentDeclarationJsonInput} from 'svelte-docinfo/types.ts';

inheritance

extends: SchemaStrictObjectInput<typeof ComponentDeclarationJsonEntries>

members

kind

: "component"
#

name

: string
#

The exported name. Always populated. The default-export slot is named 'default', except a Svelte component, which takes its filename-derived name ('X' for X.svelte) — 'default' is the symbol's actual name in JS (import {default as X} and ns.default both expose it directly), and import X from 'mod' is sugar for import {default as X}. Consumers branch on name === 'default' to render the sugar form when desired.

externalTypes

?: string[]
#

External types whose properties are filtered out of props — the attribute bags a component forwards, such as HTMLButtonAttributes or SvelteHTMLElements['button']. A bag stays listed when some of its properties are documented anyway because the $props() destructuring names them (see props).

Covers every way props compose them: an intersection or union branch, a bare or indexed-access annotation, and interface Props extends Bag (directly or through a local base). Entries carry the written form with the same normalizations as TypeDeclarationJson.externalTypes: import renames at the definition site resolve to the exported name, and a type parameter bound inside the descent substitutes its written argument — interface A<T> extends HTMLAttributes<T> reached via `Props extends A<HTMLDivElement> records HTMLAttributes<HTMLDivElement>`. The component's *own* generics stay in scope and emit as written (HTMLAttributes<T> beside the genericParams documenting T). Each distinct bag appears once, in source order; a local name is used only when it hides a definition the walk cannot traverse (a mapped or conditional type). Names carry no module, so two distinct bags sharing an exported name collapse to one entry.

see also

Svelte component props, in source order.

Properties an external type contributes are left out (externalTypes names their bags), except the ones the $props() destructuring names: type in let {type = 'button', ...rest}: HTMLButtonAttributes = $props() is documented with the external declaration's type and JSDoc. Renamed (class: className) and nested (a: {b}) elements name their prop; the rest element names nothing, and a name the props type has only through an index signature isn't admitted. Admitted props follow the others, in destructuring order, since their declaration position is in a package.

acceptsChildren

?: boolean
#

Whether the component accepts children: an explicit or inherited Snippet-typed children prop, implicit template usage, or a default slot (<slot /> or a declared $$Slots) in a legacy component, one svelte2tsx reads as runes-less. A runes component's <slot /> doesn't set it, and neither does a named slot alone.

cssCustomProperties

?: ComponentCssPropertyJsonInput[]
#

The component's styling API: the CSS custom properties its styles read with a fallback (var(--a, 1px)), the pattern Svelte's own docs give for a component's styling hooks, or read bare and register with @property, and leave for a consumer to set, plus the ones its doc comment documents with @cssprop. One entry per name: the documented ones first, in tag order, then the rest in the order of each name's first read.

A read counts when it's an outermost var(), not one in another var()'s fallback: var(--a, var(--b)) reads --a, with --b the fallback chain's global token. Reads anywhere in the top-level <style> count, in :global(…) rules, nested rules, @media/@container/@supports blocks, and keyframes alike, and so do reads in the static text of the markup's style attributes and style: directives on elements and style and --a attributes on child components (<Child --a="var(--b, 1px)" /> reads --b). A name drops out when the component sets it itself: a --a: … declaration in its <style>, a style:--a directive, or a --a: in a style attribute on one of its elements. A --a or style attribute on a child component sets nothing, since it styles the child. A name read only without a fallback isn't listed, unless the style registers it with @property --a {…}, whose syntax and initial-value the entry carries (the last rule for a name wins; inherits isn't modeled); a registered name nothing reads isn't listed either: bare reads are mostly global design tokens. A global token read with a fallback is listed too; the author's fix is to drop the fallback or to document the property with @cssprop. There's deliberately no option to filter names at analysis: the output keeps every read, and a consumer that wants less filters it (to documented entries, say). Names are case-sensitive, as in CSS.

@cssprop --a - Description 1 (or @cssproperty) in the component's doc comment, the source that wins docComment (the in-script JSDoc over the HTML @component comment, the losing one's tags ignored), lists --a whatever the heuristic makes of it, documented: true, with the tag's description, syntax, and default. It merges with the read: a bare read, one nested in another's fallback, one the component sets itself, or one in its markup's static style text counts, giving sourceLine and fallback. A name the component never reads stays, at the tag's line, and warns unknown_cssprop; a tag default the style's fallback disagrees with warns cssprop_default_mismatch; a tag that names no property warns malformed_tag, and one repeating a name duplicate_tag, each dropped.

Without tags, empty when the component has no <style> and no markup read, when its style's lang (or type) names a preprocessor language (css_lang_unsupported), or when Svelte's parser rejects the component (css_parse_failed); tagged properties are listed even then.

lang

?: "js"
#

Script language. undefined means TypeScript (default), 'js' for JS-only components.

alsoExportedFrom

?: string[]
#

Module paths (relative to sourceRoot) that re-export this declaration under the same name. The canonical declaration lives in this module's declarations array; these paths are additional import locations for the same thing.

The same edges appear from the re-exporting side as ModuleJson.reExports — use that when asking "what does this module re-export" instead of inverting these arrays. The two can disagree at the margins: a reExports entry whose canonical declaration is @nodocs (or whose module isn't in the analyzed set) has no back-link here.

Consumer note: To build a complete re-export map, scan two fields:

  1. alsoExportedFrom on each declaration — same-name re-exports
  2. aliasOf on declarations — renamed re-exports (separate declarations)

aliasOf

?: { module: string; name: string; }
#

For renamed re-exports (export {foo as bar}), points to the original declaration. This declaration's name is the alias; aliasOf.name is the original name.

For renames out of the default slot (export {default as bar} from './x' where ./x is export default ...), aliasOf.name is 'default' — the canonical's actual symbol name. Consumers locate the canonical by (aliasOf.module, aliasOf.name).

Svelte component exception: when the source is a .svelte file (e.g., export {default as Foo} from './X.svelte'), the canonical's name is the component name (derived from the filename), so aliasOf.name is the component name ('X'), NOT 'default'. Consumers that branch on aliasOf.name === 'default' to detect default-rename should additionally check whether aliasOf.module ends with .svelte.

Different from alsoExportedFrom: aliases create new API surface names, while alsoExportedFrom tracks additional import paths for the same name.

A type-only rename of a value (export type {someConst as c} from './x') synthesizes a normal alias — declarations carry no type-only marker.

partial

?: boolean
#

Whether extraction failed partway through, leaving some fields missing (e.g., typeSignature, parameters).

examples

?: string[]
#

Code examples from @example tags.

deprecatedMessage

?: string
#

Deprecation message from @deprecated tag.

seeAlso

?: string[]
#

Related items from @see tags, in raw TSDoc format.

throws

?: ThrowsJsonInput[]
#

Exceptions from @throws tags. type is the tag's written type, and typeInfo its structured form, present for a braced type (@throws {A<B>}) that isn't the whole story as text (see TypeJson); an unbraced tag's leading word never has one, nor does a tag in a component's HTML @component comment, which is read as text.

since

?: string
#

Version introduced, from @since tag.

internalMessage

?: string
#

Internal-API marker from the @internal tag. Presence means the tag was written; an empty string is a bare tag with no trailing prose.

A marker, not an exclusion: @internal means "not stable public API" (TSDoc semantics) while the declaration, member, or prop stays documented — unlike @nodocs, which removes a declaration from output entirely (and is ignored on props and members).

mutates

?: Record<string, string>
#

Mutation documentation from @mutates tags (non-standard), mapping keys to descriptions.

Keys are intentionally unvalidated — typically a parameter name, but authors may also use compound paths (this.foo, obj.field) or multi-word external state references. Backticks are stripped from keys so `` a `` and a normalize to one key; an empty-string value is a bare tag with no description. The schema accepts any string key so consumers can render whatever the author wrote.

On a component prop it declares the component's mutation contract for the value it's handed: the component writes into the prop's object or array in place (@mutates items - appends the selected entry, @mutates options.cache - fills on first render). Reassigning a prop is not a mutation in this sense (bindable covers it), though a $bindable prop can carry both.

docComment

?: string
#

JSDoc/TSDoc comment.

typeSignature

?: string
#

Full TypeScript type signature.

modifiers

?: ("public" | "protected" | "readonly" | "static" | "abstract" | "getter" | "setter")[]
#

TypeScript modifiers like readonly, static, or protected.

sourceLine

?: number
#

1-based line in the source file, a positive integer. Synthesized aliases (see aliasOf) carry the local export specifier's line, not the canonical's.

genericParams

?: GenericParamJsonInput[]
#

Generic type parameters like <T, U>.

ComponentPropJson
#

types.ts view source

value + type

also exported from index.ts

Component prop information for Svelte components.

Standalone schema (not extending ParameterJson) because component props have different semantics: named attributes with no positional order (<Foo {a} {b} /> = <Foo {b} {a} />), no rest parameters, and support for two-way binding (the $bindable rune, or a legacy export let prop).

import {ComponentPropJson} from 'svelte-docinfo/types.ts';

inheritance

extends: SchemaStrictObjectOutput<typeof ComponentPropJsonEntries>

members

examples

: string[]
#

Code examples from @example tags.

seeAlso

: string[]
#

Related items from @see tags, in raw TSDoc format.

throws

: ThrowsJson[]
#

Exceptions from @throws tags. type is the tag's written type, and typeInfo its structured form, present for a braced type (@throws {A<B>}) that isn't the whole story as text (see TypeJson); an unbraced tag's leading word never has one, nor does a tag in a component's HTML @component comment, which is read as text.

name

: string
#

Prop name as declared in the component's $props() type — the prop's own name, not the local binding a renamed destructuring element introduces.

type

: string
#

Resolved TypeScript type string.

optional

: boolean
#

Whether the prop is optional in the component's props type.

bindable

: boolean
#

Whether the prop supports two-way binding (bind:name): declared with the $bindable() rune, or any prop of a legacy export let component, where every prop can be bound.

deprecatedMessage

?: string
#

Deprecation message from @deprecated tag.

since

?: string
#

Version introduced, from @since tag.

internalMessage

?: string
#

Internal-API marker from the @internal tag. Presence means the tag was written; an empty string is a bare tag with no trailing prose.

A marker, not an exclusion: @internal means "not stable public API" (TSDoc semantics) while the declaration, member, or prop stays documented — unlike @nodocs, which removes a declaration from output entirely (and is ignored on props and members).

mutates

?: Record<string, string>
#

Mutation documentation from @mutates tags (non-standard), mapping keys to descriptions.

Keys are intentionally unvalidated — typically a parameter name, but authors may also use compound paths (this.foo, obj.field) or multi-word external state references. Backticks are stripped from keys so `` a `` and a normalize to one key; an empty-string value is a bare tag with no description. The schema accepts any string key so consumers can render whatever the author wrote.

On a component prop it declares the component's mutation contract for the value it's handed: the component writes into the prop's object or array in place (@mutates items - appends the selected entry, @mutates options.cache - fills on first render). Reassigning a prop is not a mutation in this sense (bindable covers it), though a $bindable prop can carry both.

returnPredicate

?: ReturnPredicateJson
#

The signature's type predicate or assertion, when it declares one; returnType stays the checker's boolean or void.

thisType

?: string
#

The type of a declared this parameter (function f(this: A), or a JS @this {A} tag), which parameters leaves out, since a caller doesn't pass it as an argument.

thisTypeInfo

?: TypeJson
#

Structured thisType; absent when thisType is the whole story (see TypeJson).

typeInfo

?: TypeJson
#

Structured type; absent when type is the whole story (see TypeJson).

description

?: string
#

Description from JSDoc on the prop's type declaration.

defaultValue

?: string
#

The destructuring default's source text, else the @default tag text — verbatim author text either way ("'primary'", () => 10), quotes included, no normalization; consumers render it as highlighted TS.

parameters

?: ParameterJson[]
#

Structured parameters for callable props: a snippet's (Snippet<[text: string]>) or a callback's ((value: string) => void). returnType tells the two apart — a callback has one, a snippet doesn't.

Present when the prop has extractable parameters, absent otherwise. Only populated when there are actual parameters — bare Snippet / Snippet<[]> and a zero-parameter callback do not set this field. Intentionally optional without a default, unlike the other array fields (see the input/output split in the module comment): absence is a meaningful signal, not an empty list.

returnType

?: string
#

A callback prop's return type, and the marker that the prop is one: present exactly when the prop's type has a call signature this project declared (onpick?: (value: string) => void, or a project alias for one). parameters holds that signature's parameters.

The prop's type is read with null and the optional undefined stripped, so (() => void) | null is a callback. A union of several function types is not — typeInfo lists its members instead.

Only project-declared signatures count, as for callable members. A prop typed wholly by a package (MouseEventHandler<HTMLButtonElement>, a Component) carries neither field, since an external callable isn't always a callback. In an intersection of an own signature with an external one (MouseEventHandler<HTMLElement> & (() => void), the shape a redeclared onclick over an attributes bag takes), the own signature is the one described. Of several own signatures, the first.

returnTypeInfo

?: TypeJson
#

Structured return type; absent when returnType is the whole story (see TypeJson).

ComponentPropJsonInput
#

types.ts view source

The input ComponentPropJson parses, with any field it defaults optional.

import type {ComponentPropJsonInput} from 'svelte-docinfo/types.ts';

inheritance

extends: SchemaStrictObjectInput<typeof ComponentPropJsonEntries>

members

name

: string
#

Prop name as declared in the component's $props() type — the prop's own name, not the local binding a renamed destructuring element introduces.

type

: string
#

Resolved TypeScript type string.

examples

?: string[]
#

Code examples from @example tags.

deprecatedMessage

?: string
#

Deprecation message from @deprecated tag.

seeAlso

?: string[]
#

Related items from @see tags, in raw TSDoc format.

throws

?: ThrowsJsonInput[]
#

Exceptions from @throws tags. type is the tag's written type, and typeInfo its structured form, present for a braced type (@throws {A<B>}) that isn't the whole story as text (see TypeJson); an unbraced tag's leading word never has one, nor does a tag in a component's HTML @component comment, which is read as text.

since

?: string
#

Version introduced, from @since tag.

internalMessage

?: string
#

Internal-API marker from the @internal tag. Presence means the tag was written; an empty string is a bare tag with no trailing prose.

A marker, not an exclusion: @internal means "not stable public API" (TSDoc semantics) while the declaration, member, or prop stays documented — unlike @nodocs, which removes a declaration from output entirely (and is ignored on props and members).

mutates

?: Record<string, string>
#

Mutation documentation from @mutates tags (non-standard), mapping keys to descriptions.

Keys are intentionally unvalidated — typically a parameter name, but authors may also use compound paths (this.foo, obj.field) or multi-word external state references. Backticks are stripped from keys so `` a `` and a normalize to one key; an empty-string value is a bare tag with no description. The schema accepts any string key so consumers can render whatever the author wrote.

On a component prop it declares the component's mutation contract for the value it's handed: the component writes into the prop's object or array in place (@mutates items - appends the selected entry, @mutates options.cache - fills on first render). Reassigning a prop is not a mutation in this sense (bindable covers it), though a $bindable prop can carry both.

returnPredicate

?: ReturnPredicateJsonInput
#

The signature's type predicate or assertion, when it declares one; returnType stays the checker's boolean or void.

thisType

?: string
#

The type of a declared this parameter (function f(this: A), or a JS @this {A} tag), which parameters leaves out, since a caller doesn't pass it as an argument.

thisTypeInfo

?: TypeJson
#

Structured thisType; absent when thisType is the whole story (see TypeJson).

typeInfo

?: TypeJson
#

Structured type; absent when type is the whole story (see TypeJson).

optional

?: boolean
#

Whether the prop is optional in the component's props type.

description

?: string
#

Description from JSDoc on the prop's type declaration.

defaultValue

?: string
#

The destructuring default's source text, else the @default tag text — verbatim author text either way ("'primary'", () => 10), quotes included, no normalization; consumers render it as highlighted TS.

bindable

?: boolean
#

Whether the prop supports two-way binding (bind:name): declared with the $bindable() rune, or any prop of a legacy export let component, where every prop can be bound.

parameters

?: ParameterJsonInput[]
#

Structured parameters for callable props: a snippet's (Snippet<[text: string]>) or a callback's ((value: string) => void). returnType tells the two apart — a callback has one, a snippet doesn't.

Present when the prop has extractable parameters, absent otherwise. Only populated when there are actual parameters — bare Snippet / Snippet<[]> and a zero-parameter callback do not set this field. Intentionally optional without a default, unlike the other array fields (see the input/output split in the module comment): absence is a meaningful signal, not an empty list.

returnType

?: string
#

A callback prop's return type, and the marker that the prop is one: present exactly when the prop's type has a call signature this project declared (onpick?: (value: string) => void, or a project alias for one). parameters holds that signature's parameters.

The prop's type is read with null and the optional undefined stripped, so (() => void) | null is a callback. A union of several function types is not — typeInfo lists its members instead.

Only project-declared signatures count, as for callable members. A prop typed wholly by a package (MouseEventHandler<HTMLButtonElement>, a Component) carries neither field, since an external callable isn't always a callback. In an intersection of an own signature with an external one (MouseEventHandler<HTMLElement> & (() => void), the shape a redeclared onclick over an attributes bag takes), the own signature is the one described. Of several own signatures, the first.

returnTypeInfo

?: TypeJson
#

Structured return type; absent when returnType is the whole story (see TypeJson).

computeDependents
#

postprocess.ts view source

computeDependents(files: readonly SourceFileInfo[]): (SourceFileInfo & { dependents?: readonly string[]; })[]

Compute bidirectional dependencies from source files.

If file A has file B in its dependencies, file B gets file A in its dependents. Dependents are derived solely from the forward dependencies edges within files (SourceFileInfo carries no dependents field); edges to files outside the set are ignored.

Returns new SourceFileInfo objects when computed dependents exist or when paths needed posixification; otherwise the original input objects flow through ===-equal (fast path for session callers, who already pass POSIX paths and may have no inferable dependents for a given file).

import {computeDependents} from 'svelte-docinfo/postprocess.ts';

parameters

files

: readonly SourceFileInfo[]
#

source files with optional dependency information

returns

new array with bidirectional dependencies computed

examples

// Input: Calculator.svelte has dependencies: [math.ts] // Output: Calculator.svelte has dependencies: [math.ts] // math.ts has dependents: [Calculator.svelte] const filesWithBidirectional = computeDependents(files);

ConstructorMemberJson
#

types.ts view source

value + type

also exported from index.ts

A constructor member (class constructor, construct signature). Has parameters, overloads — but not returnType/returnDescription (constructors always return their class).

name is narrowed to two literal sentinels: 'constructor' for class constructors and '(construct)' for interface/type-alias construct signatures (which share kind: 'constructor' but originate from getConstructSignatures() on a non-class type — no user-chosen identifier exists). The literal is preserved (rather than omitted) so getDisplayName and consumer renderers reading member.name keep working without a constructor-specific branch.

import {ConstructorMemberJson} from 'svelte-docinfo/types.ts';

inheritance

extends: SchemaStrictObjectOutput<typeof ConstructorMemberJsonEntries>

members

kind

: "constructor"
#

name

: "constructor" | "(construct)"
#

parameters

: ParameterJson[]
#

Function/method/constructor parameters, in signature order.

overloads

: OverloadJson[]
#

Overload signatures (when there are multiple public overloads). Includes all public overloads. The implementation signature is excluded. Empty when there are no overloads (single signature).

partial

: boolean
#

Whether extraction failed partway through, leaving some fields missing (e.g., typeSignature, parameters).

examples

: string[]
#

Code examples from @example tags.

seeAlso

: string[]
#

Related items from @see tags, in raw TSDoc format.

throws

: ThrowsJson[]
#

Exceptions from @throws tags. type is the tag's written type, and typeInfo its structured form, present for a braced type (@throws {A<B>}) that isn't the whole story as text (see TypeJson); an unbraced tag's leading word never has one, nor does a tag in a component's HTML @component comment, which is read as text.

modifiers

: ("public" | "protected" | "readonly" | "static" | "abstract" | "getter" | "setter")[]
#

TypeScript modifiers like readonly, static, or protected.

genericParams

: GenericParamJson[]
#

Generic type parameters like <T, U>.

deprecatedMessage

?: string
#

Deprecation message from @deprecated tag.

since

?: string
#

Version introduced, from @since tag.

internalMessage

?: string
#

Internal-API marker from the @internal tag. Presence means the tag was written; an empty string is a bare tag with no trailing prose.

A marker, not an exclusion: @internal means "not stable public API" (TSDoc semantics) while the declaration, member, or prop stays documented — unlike @nodocs, which removes a declaration from output entirely (and is ignored on props and members).

mutates

?: Record<string, string>
#

Mutation documentation from @mutates tags (non-standard), mapping keys to descriptions.

Keys are intentionally unvalidated — typically a parameter name, but authors may also use compound paths (this.foo, obj.field) or multi-word external state references. Backticks are stripped from keys so `` a `` and a normalize to one key; an empty-string value is a bare tag with no description. The schema accepts any string key so consumers can render whatever the author wrote.

On a component prop it declares the component's mutation contract for the value it's handed: the component writes into the prop's object or array in place (@mutates items - appends the selected entry, @mutates options.cache - fills on first render). Reassigning a prop is not a mutation in this sense (bindable covers it), though a $bindable prop can carry both.

docComment

?: string
#

JSDoc/TSDoc comment.

typeSignature

?: string
#

Full TypeScript type signature.

sourceLine

?: number
#

1-based line in the source file, a positive integer. Synthesized aliases (see aliasOf) carry the local export specifier's line, not the canonical's.

ConstructorMemberJsonInput
#

types.ts view source

The input ConstructorMemberJson parses, with any field it defaults optional.

import type {ConstructorMemberJsonInput} from 'svelte-docinfo/types.ts';

inheritance

extends: SchemaStrictObjectInput<typeof ConstructorMemberJsonEntries>

members

kind

: "constructor"
#

name

: "constructor" | "(construct)"
#

parameters

?: ParameterJsonInput[]
#

Function/method/constructor parameters, in signature order.

overloads

?: OverloadJsonInput[]
#

Overload signatures (when there are multiple public overloads). Includes all public overloads. The implementation signature is excluded. Empty when there are no overloads (single signature).

partial

?: boolean
#

Whether extraction failed partway through, leaving some fields missing (e.g., typeSignature, parameters).

examples

?: string[]
#

Code examples from @example tags.

deprecatedMessage

?: string
#

Deprecation message from @deprecated tag.

seeAlso

?: string[]
#

Related items from @see tags, in raw TSDoc format.

throws

?: ThrowsJsonInput[]
#

Exceptions from @throws tags. type is the tag's written type, and typeInfo its structured form, present for a braced type (@throws {A<B>}) that isn't the whole story as text (see TypeJson); an unbraced tag's leading word never has one, nor does a tag in a component's HTML @component comment, which is read as text.

since

?: string
#

Version introduced, from @since tag.

internalMessage

?: string
#

Internal-API marker from the @internal tag. Presence means the tag was written; an empty string is a bare tag with no trailing prose.

A marker, not an exclusion: @internal means "not stable public API" (TSDoc semantics) while the declaration, member, or prop stays documented — unlike @nodocs, which removes a declaration from output entirely (and is ignored on props and members).

mutates

?: Record<string, string>
#

Mutation documentation from @mutates tags (non-standard), mapping keys to descriptions.

Keys are intentionally unvalidated — typically a parameter name, but authors may also use compound paths (this.foo, obj.field) or multi-word external state references. Backticks are stripped from keys so `` a `` and a normalize to one key; an empty-string value is a bare tag with no description. The schema accepts any string key so consumers can render whatever the author wrote.

On a component prop it declares the component's mutation contract for the value it's handed: the component writes into the prop's object or array in place (@mutates items - appends the selected entry, @mutates options.cache - fills on first render). Reassigning a prop is not a mutation in this sense (bindable covers it), though a $bindable prop can carry both.

docComment

?: string
#

JSDoc/TSDoc comment.

typeSignature

?: string
#

Full TypeScript type signature.

modifiers

?: ("public" | "protected" | "readonly" | "static" | "abstract" | "getter" | "setter")[]
#

TypeScript modifiers like readonly, static, or protected.

sourceLine

?: number
#

1-based line in the source file, a positive integer. Synthesized aliases (see aliasOf) carry the local export specifier's line, not the canonical's.

genericParams

?: GenericParamJsonInput[]
#

Generic type parameters like <T, U>.

ContributedSignatures
#

createAnalysisLanguageService
#

typescript-program.ts view source

createAnalysisLanguageService(options?: AnalysisLanguageServiceOptions, log?: AnalysisLog): AnalysisLanguageService

Create a persistent language service for incremental analysis.

The LS owns parsed source ASTs and checker state across calls. Use the returned handle to push file-content updates (setFile / deleteFile) between analysis passes; subsequent getProgram() calls return either the same ts.Program (no changes since last call) or a fresh one that reuses unchanged files via the document registry.

import {createAnalysisLanguageService} from 'svelte-docinfo/typescript-program.ts';

parameters

configuration options

#

optional logger for info messages

returns

the language service handle

throws

examples

const ls = createAnalysisLanguageService({projectRoot}); ls.setFile('/abs/path/to/foo.ts', {content: 'export const x = 1;'}); const program = ls.getProgram(); // ... use program ... ls.setFile('/abs/path/to/foo.ts', {content: 'export const x = 2;'}); // bumps version const program2 = ls.getProgram(); // fresh program, foo.ts reparsed ls.dispose();

createAnalysisProgram
#

typescript-program.ts view source

createAnalysisProgram(options?: AnalysisProgramOptions, log?: AnalysisLog): Program

Create TypeScript program for one-shot analysis.

Use createAnalysisLanguageService instead when you need to analyze the same source set multiple times — the LS path reuses parsed ASTs and checker state across calls.

import {createAnalysisProgram} from 'svelte-docinfo/typescript-program.ts';

parameters

configuration options for program creation

#

optional logger for info messages

returns

the TypeScript program

throws

examples

const program = createAnalysisProgram({projectRoot: process.cwd()});

createAnalysisSession
#

session.ts view source

also exported from index.ts

createAnalysisSession(options: AnalysisSessionOptions): AnalysisSession

Create a persistent analysis session.

import {createAnalysisSession} from 'svelte-docinfo/session.ts';

examples

Vite plugin integration

const session = createAnalysisSession({sourceOptions, resolveImport, log}); await session.setFiles(initialFiles); const result = session.query(); // on watcher events: await session.setFile({id, content}); await session.deleteFile(removedId); const next = session.query(); // on shutdown: session.dispose();

One-shot via the public wrapper

// Equivalent to `analyze(...)` — the wrapper goes through a session internally // (and opts out of the context closure, since its callers supply the inputs). const session = createAnalysisSession({sourceOptions, contextClosure: false}); try { await session.setFiles(sourceFiles); return session.query(); } finally { session.dispose(); }

createBlockedSpecifierChecker
#

exports.ts view source

createBlockedSpecifierChecker(parsed: ParsedExports): ((specifier: string) => boolean) | null

Build a predicate deciding whether an export specifier is blocked, per Node's resolution semantics: an exact (starless) key wins outright, else the best-matching wildcard key (comparePatternKeys) decides — and when that winner's target is null, the subpath is not exported.

Blocking is only observable when blocked keys exist, so this returns null for the common no-blocked-keys case and callers skip specifier computation entirely.

Exported for consumers reading ParsedExports.blocked directly — this is the one implementation of the interpretation rule.

import {createBlockedSpecifierChecker} from 'svelte-docinfo/exports.ts';

createDefaultResolver
#

dep-resolver.ts view source

createDefaultResolver(compilerOptions: CompilerOptions, projectRoot: string, host?: ModuleResolutionHost): ImportResolver

Create the default ImportResolver (TypeScript + tsconfig).

Uses ts.resolveModuleName against host (default ts.sys) — no ts.Program is built. Identity is a fresh symbol per call, so each session that constructs its own default gets a unique cache scope. Multiple sessions sharing one resolver instance share the cache scope (correct, since resolver state is shared too).

ts.resolveModuleName cannot resolve real .svelte files (no compiler option teaches it the extension), so relative and absolute .svelte specifiers — with or without the extension written — fall back to manual resolution against fromFile through the same host. Non-relative .svelte specifiers (tsconfig paths aliases, package subpaths) stay unresolved; supply a custom resolveImport for those setups.

The resolution cache lives for the resolver's lifetime and caches failed lookups alongside successful ones, so invalidate clears it — the session calls that whenever its owned set's membership changed (see ImportResolver).

import {createDefaultResolver} from 'svelte-docinfo/dep-resolver.ts';

parameters

compilerOptions

: CompilerOptions
#

parsed tsconfig (from loadTsconfig, or the LS handle's getCompilerOptions())

projectRoot

: string
#

absolute project root for the module-resolution cache

host

?: ModuleResolutionHost = ts.sys
#

resolution surface; the session passes an owned-content-aware host so dependency edges see the same world the checker does (in-memory files, including ones in directories that exist nowhere on disk), disk-only callers take the ts.sys default

createExtractContext
#

typescript-extract-shared.ts view source

createExtractContext(program: Program, checker: TypeChecker, options: ModuleSourceOptions, diagnostics: Diagnostic[], aliasRegistry: AliasRegistry | undefined, isEmittedFile?: IsEmittedFile, fileExists?: FileExists): ExtractContext

The module dispatchers' ExtractContext construction — analyzeModule and analyzeSvelteModule are where the program is in hand, and both want the same answers from it. One owner so the derived fields can't drift or be forgotten by a third dispatcher: isExternalFile comes from the very options the pass will be handed (analyzeExports derives its own isExternalPath from that object, and the two axes must agree), and exactOptionalPropertyTypes is read off the *merged* compiler options rather than the raw tsconfig, so a session-level override reaches the strip gate (optionalWidened). svelteFileStatus reads virtuals off the program and existence off fileExists, which defaults to the disk; analyzeCore passes one that also sees owned in-memory content.

Direct callers outside the dispatchers (tests, fixture harnesses, subpath consumers) build the object literal themselves and decide every field explicitly — see mockExtractContext in src/test/test-helpers.ts.

import {createExtractContext} from 'svelte-docinfo/typescript-extract-shared.ts';

parameters

isEmittedFile

?: IsEmittedFile = (file) => isSource(file, options)
#

fileExists

?: FileExists = ts.sys.fileExists
#

createIsExternalFile
#

createIsExternalPath
#

typescript-program.ts view source

createIsExternalPath(options: ModuleSourceOptions): (file: string) => boolean

Path-string counterpart of IsExternalFile, for call sites that hold a file path rather than a ts.SourceFile (re-export classification). Same rule, with declaration-file suffixes standing in for isDeclarationFile.

Deliberately distinct from isSource: isSource answers "does this file emit a module?" while this answers "is this file outside the project?" — an in-root file can fail isSource (the src/lib/internal/ convention, user excludes) while remaining project-local, and conflating the two mis-files project-local re-exports as external-package facts.

import {createIsExternalPath} from 'svelte-docinfo/typescript-program.ts';

createOwnedDirIndex
#

createSourceOptions
#

source-config.ts view source

also exported from index.ts

createSourceOptions(projectRoot: string, overrides?: SourceOptionsOverrides): ModuleSourceOptions

Create complete, normalized, validated source options from project root and optional overrides.

Merges overrides with DEFAULT_SOURCE_OPTIONS, then normalizes via normalizeSourceOptions — so the returned object always has an absolute projectRoot, slash-stripped path entries, and an explicit sourceRoot (auto-derived for multi-path layouts). Throws on validation failure.

import {createSourceOptions} from 'svelte-docinfo/source-config.ts';

parameters

projectRoot

: string
#

path to project root (typically process.cwd()); resolved to absolute

optional overrides for default options

throws

  • Error - if validation fails (empty sourcePaths; a sourcePaths entry, sourceRoot, or absolute exclude glob escaping projectRoot; or sourceRoot not a prefix of all sourcePaths)

examples

// Standard SvelteKit library const options = createSourceOptions(process.cwd());
// Multiple source directories const options = createSourceOptions(process.cwd(), { sourcePaths: ['src/lib', 'src/routes'], sourceRoot: 'src', });
// Extend the default exclusions (callback form — see `ExcludeOption`) const options = createSourceOptions(process.cwd(), { exclude: (defaults) => [...defaults, '**\/*.gen.ts'], });
// Replace the default exclusions wholesale const options = createSourceOptions(process.cwd(), { exclude: ['**\/*.test.ts', '**\/*.internal.ts'], });

createSourceOptionsWithInclude
#

source-config.ts view source

createSourceOptionsWithInclude(projectRoot: string, overrides: SourceOptionsOverrides | undefined, include: readonly string[] | undefined, log?: AnalysisLog): ModuleSourceOptions

Create source options with include-pattern widening applied.

The include-aware form of createSourceOptions, used by the discovery entry points (analyzeFromFiles, the Vite plugin): builds options from overrides, then unions each include pattern's static base into sourcePaths via widenSourcePathsForInclude so include-discovered files pass the query-time source gate. When the set widens, options are rebuilt from the original overrides so sourceRoot derivation and validation (including the projectRoot-escape throw) see the final set — re-normalizing the first result would bake a derived sourceRoot in as if explicit and fail validation against the widened bases. Owning both steps here keeps that original-overrides requirement an implementation detail instead of a caller contract.

Logs when a pattern contributes the '' base: a root-crossing glob ('**\/*.ts') or a literal root file ('vite.config.ts') scopes the whole project root as source — the baseline exclusions (node_modules, dot-directories) shrink that cliff but don't remove it, so the widening leaves a trace instead of happening silently.

import {createSourceOptionsWithInclude} from 'svelte-docinfo/source-config.ts';

parameters

projectRoot

: string
#

path to project root (typically process.cwd()); resolved to absolute

overrides

: SourceOptionsOverrides | undefined
#

optional overrides for default options

include

: readonly string[] | undefined
#

explicit include patterns (absent or empty means plain createSourceOptions); in-root absolute patterns relativize via normalizeIncludePatterns

#

receives the root-scoping info line

throws

  • Error - if validation fails, including a widened base or an absolute include pattern escaping the project root

CssLangUnsupportedDiagnostic
#

diagnostics.ts view source

value + type

A component's <style> names a preprocessor language (lang="scss", type="text/postcss"), which isn't read: its styling API (ComponentDeclarationJson.cssCustomProperties) is left empty. Only lang="css" and type="text/css" read as CSS. line/column point at the style tag.

Always warning, query-time category (reported each query() from the reading cached at transform).

import {CssLangUnsupportedDiagnostic} from 'svelte-docinfo/diagnostics.ts';

inheritance

extends: SchemaStrictObjectOutput<typeof CssLangUnsupportedDiagnosticEntries>

members

kind

: "css_lang_unsupported"
#

lang

: string
#

The style tag's lang (or type) value, as written (scss, text/postcss).

file

: string
#

File path relative to project root (no leading slash, no ./ prefix).

Normalized at every public API boundary — session.setFile/setFiles (ingest-time), session.query (query-time, via analyzeCore), and the one-shot wrappers analyze / analyzeFromFiles. Producers inside the pipeline may write absolute or virtual paths (e.g., Foo.svelte.__svelte2tsx__.ts); normalization rewrites them to project-relative form before they reach consumers.

The exception is discovery — discoverSourceFiles / discoverFromExports return their diagnostics unnormalized, since they run before any session exists. Their file is already project-root-relative, but message can embed an absolute path (an fs error names the file it failed on), so a consumer wiring discovery up itself owns the normalizeDiagnosticPaths call — analyzeFromFiles and the Vite plugin both make it before merging.

The absolute form is the one to write. Normalization deliberately leaves an already-relative path alone (relativizing it would resolve against cwd), so a producer writing a ModuleJson.path — relative to sourceRoot, a different base — passes through untouched and publishes the same file under a second name. Absolute is what the pass can actually correct.

message

: string
#

Human-readable description of the issue.

severity

: "error" | "warning"
#

line

?: number
#

Line number (1-based), absent if location unavailable.

column

?: number
#

Column number (1-based), absent if location unavailable.

CssLangUnsupportedDiagnosticInput
#

diagnostics.ts view source

The input CssLangUnsupportedDiagnostic parses, with any field it defaults optional.

import type {CssLangUnsupportedDiagnosticInput} from 'svelte-docinfo/diagnostics.ts';

inheritance

extends: SchemaStrictObjectInput<typeof CssLangUnsupportedDiagnosticEntries>

members

kind

: "css_lang_unsupported"
#

lang

: string
#

The style tag's lang (or type) value, as written (scss, text/postcss).

file

: string
#

File path relative to project root (no leading slash, no ./ prefix).

Normalized at every public API boundary — session.setFile/setFiles (ingest-time), session.query (query-time, via analyzeCore), and the one-shot wrappers analyze / analyzeFromFiles. Producers inside the pipeline may write absolute or virtual paths (e.g., Foo.svelte.__svelte2tsx__.ts); normalization rewrites them to project-relative form before they reach consumers.

The exception is discovery — discoverSourceFiles / discoverFromExports return their diagnostics unnormalized, since they run before any session exists. Their file is already project-root-relative, but message can embed an absolute path (an fs error names the file it failed on), so a consumer wiring discovery up itself owns the normalizeDiagnosticPaths call — analyzeFromFiles and the Vite plugin both make it before merging.

The absolute form is the one to write. Normalization deliberately leaves an already-relative path alone (relativizing it would resolve against cwd), so a producer writing a ModuleJson.path — relative to sourceRoot, a different base — passes through untouched and publishes the same file under a second name. Absolute is what the pass can actually correct.

message

: string
#

Human-readable description of the issue.

severity

: "error" | "warning"
#

line

?: number
#

Line number (1-based), absent if location unavailable.

column

?: number
#

Column number (1-based), absent if location unavailable.

CssParseFailedDiagnostic
#

diagnostics.ts view source

value + type

Svelte's parser rejected a component that has a <style>, so its styling API (ComponentDeclarationJson.cssCustomProperties) isn't read.

Usually malformed CSS; also any template error under a Svelte that predates loose parsing (5.13). The component still emits, without cssCustomProperties. line/column are the parser's, in the original .svelte source.

Always warning, query-time category (reported each query() from the reading cached at transform).

import {CssParseFailedDiagnostic} from 'svelte-docinfo/diagnostics.ts';

inheritance

extends: SchemaStrictObjectOutput<typeof CssParseFailedDiagnosticEntries>

members

kind

: "css_parse_failed"
#

file

: string
#

File path relative to project root (no leading slash, no ./ prefix).

Normalized at every public API boundary — session.setFile/setFiles (ingest-time), session.query (query-time, via analyzeCore), and the one-shot wrappers analyze / analyzeFromFiles. Producers inside the pipeline may write absolute or virtual paths (e.g., Foo.svelte.__svelte2tsx__.ts); normalization rewrites them to project-relative form before they reach consumers.

The exception is discovery — discoverSourceFiles / discoverFromExports return their diagnostics unnormalized, since they run before any session exists. Their file is already project-root-relative, but message can embed an absolute path (an fs error names the file it failed on), so a consumer wiring discovery up itself owns the normalizeDiagnosticPaths call — analyzeFromFiles and the Vite plugin both make it before merging.

The absolute form is the one to write. Normalization deliberately leaves an already-relative path alone (relativizing it would resolve against cwd), so a producer writing a ModuleJson.path — relative to sourceRoot, a different base — passes through untouched and publishes the same file under a second name. Absolute is what the pass can actually correct.

message

: string
#

Human-readable description of the issue.

severity

: "error" | "warning"
#

line

?: number
#

Line number (1-based), absent if location unavailable.

column

?: number
#

Column number (1-based), absent if location unavailable.

CssParseFailedDiagnosticInput
#

diagnostics.ts view source

The input CssParseFailedDiagnostic parses, with any field it defaults optional.

import type {CssParseFailedDiagnosticInput} from 'svelte-docinfo/diagnostics.ts';

inheritance

extends: SchemaStrictObjectInput<typeof CssParseFailedDiagnosticEntries>

members

kind

: "css_parse_failed"
#

file

: string
#

File path relative to project root (no leading slash, no ./ prefix).

Normalized at every public API boundary — session.setFile/setFiles (ingest-time), session.query (query-time, via analyzeCore), and the one-shot wrappers analyze / analyzeFromFiles. Producers inside the pipeline may write absolute or virtual paths (e.g., Foo.svelte.__svelte2tsx__.ts); normalization rewrites them to project-relative form before they reach consumers.

The exception is discovery — discoverSourceFiles / discoverFromExports return their diagnostics unnormalized, since they run before any session exists. Their file is already project-root-relative, but message can embed an absolute path (an fs error names the file it failed on), so a consumer wiring discovery up itself owns the normalizeDiagnosticPaths call — analyzeFromFiles and the Vite plugin both make it before merging.

The absolute form is the one to write. Normalization deliberately leaves an already-relative path alone (relativizing it would resolve against cwd), so a producer writing a ModuleJson.path — relative to sourceRoot, a different base — passes through untouched and publishes the same file under a second name. Absolute is what the pass can actually correct.

message

: string
#

Human-readable description of the issue.

severity

: "error" | "warning"
#

line

?: number
#

Line number (1-based), absent if location unavailable.

column

?: number
#

Column number (1-based), absent if location unavailable.

CsspropDefaultMismatchDiagnostic
#

diagnostics.ts view source

value + type

A component's @cssprop tag documents a default ([--a=1px]) that differs from the fallback its style gives the property (ComponentCssPropertyJson.fallback: the first var() read's fallback, or an @property rule's initial-value), compared as text with whitespace runs collapsed.

Usually a stale tag after the style changed, or a documented value written in a form the style doesn't use (red against #f00): nothing evaluates CSS, so an equivalent spelling warns too. The entry keeps both, default and fallback, and line is the read's (the entry's sourceLine). Not emitted when the style wasn't read.

Always warning, query-time category.

import {CsspropDefaultMismatchDiagnostic} from 'svelte-docinfo/diagnostics.ts';

inheritance

extends: SchemaStrictObjectOutput<typeof CsspropDefaultMismatchDiagnosticEntries>

members

kind

: "cssprop_default_mismatch"
#

propertyName

: string
#

The custom property the @cssprop tag names, -- included.

componentName

: string
#

Name of the component.

default

: string
#

The tag's bracketed default, verbatim.

fallback

: string
#

The style's fallback for the property, verbatim (ComponentCssPropertyJson.fallback).

file

: string
#

File path relative to project root (no leading slash, no ./ prefix).

Normalized at every public API boundary — session.setFile/setFiles (ingest-time), session.query (query-time, via analyzeCore), and the one-shot wrappers analyze / analyzeFromFiles. Producers inside the pipeline may write absolute or virtual paths (e.g., Foo.svelte.__svelte2tsx__.ts); normalization rewrites them to project-relative form before they reach consumers.

The exception is discovery — discoverSourceFiles / discoverFromExports return their diagnostics unnormalized, since they run before any session exists. Their file is already project-root-relative, but message can embed an absolute path (an fs error names the file it failed on), so a consumer wiring discovery up itself owns the normalizeDiagnosticPaths call — analyzeFromFiles and the Vite plugin both make it before merging.

The absolute form is the one to write. Normalization deliberately leaves an already-relative path alone (relativizing it would resolve against cwd), so a producer writing a ModuleJson.path — relative to sourceRoot, a different base — passes through untouched and publishes the same file under a second name. Absolute is what the pass can actually correct.

message

: string
#

Human-readable description of the issue.

severity

: "error" | "warning"
#

line

?: number
#

Line number (1-based), absent if location unavailable.

column

?: number
#

Column number (1-based), absent if location unavailable.

CsspropDefaultMismatchDiagnosticInput
#

diagnostics.ts view source

The input CsspropDefaultMismatchDiagnostic parses, with any field it defaults optional.

import type {CsspropDefaultMismatchDiagnosticInput} from 'svelte-docinfo/diagnostics.ts';

inheritance

extends: SchemaStrictObjectInput<typeof CsspropDefaultMismatchDiagnosticEntries>

members

kind

: "cssprop_default_mismatch"
#

propertyName

: string
#

The custom property the @cssprop tag names, -- included.

componentName

: string
#

Name of the component.

default

: string
#

The tag's bracketed default, verbatim.

fallback

: string
#

The style's fallback for the property, verbatim (ComponentCssPropertyJson.fallback).

file

: string
#

File path relative to project root (no leading slash, no ./ prefix).

Normalized at every public API boundary — session.setFile/setFiles (ingest-time), session.query (query-time, via analyzeCore), and the one-shot wrappers analyze / analyzeFromFiles. Producers inside the pipeline may write absolute or virtual paths (e.g., Foo.svelte.__svelte2tsx__.ts); normalization rewrites them to project-relative form before they reach consumers.

The exception is discovery — discoverSourceFiles / discoverFromExports return their diagnostics unnormalized, since they run before any session exists. Their file is already project-root-relative, but message can embed an absolute path (an fs error names the file it failed on), so a consumer wiring discovery up itself owns the normalizeDiagnosticPaths call — analyzeFromFiles and the Vite plugin both make it before merging.

The absolute form is the one to write. Normalization deliberately leaves an already-relative path alone (relativizing it would resolve against cwd), so a producer writing a ModuleJson.path — relative to sourceRoot, a different base — passes through untouched and publishes the same file under a second name. Absolute is what the pass can actually correct.

message

: string
#

Human-readable description of the issue.

severity

: "error" | "warning"
#

line

?: number
#

Line number (1-based), absent if location unavailable.

column

?: number
#

Column number (1-based), absent if location unavailable.

CssVarRead
#

svelte-css.ts view source

One var() read in CSS text.

import type {CssVarRead} from 'svelte-docinfo/svelte-css.ts';

members

name

: string
#

The custom property's name as written, -- included.

fallback

: string | undefined
#

The fallback after the comma, trimmed, verbatim (comments included); undefined for a read without one, '' for var(--a,).

offset

: number
#

Offset of the read's var within the scanned text.

fallbackRange

: [start: number, end: number] | undefined
#

Offsets of the fallback's text, after the comma up to the closing ), untrimmed; undefined for a read without one.

DeclarationAnalysis
#

declaration-build.ts view source

Result of analyzing a single declaration.

Produced by analyzeDeclaration (in typescript-exports.ts) and Svelte component analysis. Used by analyzeModule to filter @nodocs declarations before output.

Uses DeclarationJsonBuild (not DeclarationJsonInput) because declarations are constructed incrementally — schema validation happens at the parseModuleJson boundary.

import type {DeclarationAnalysis} from 'svelte-docinfo/declaration-build.ts';

members

#

The analyzed declaration metadata (pre-validation).

nodocs

: boolean
#

Whether the declaration is marked @nodocs (should be excluded from documentation).

declarationFileRoots
#

typescript-program.ts view source

declarationFileRoots(tsconfigRoots: string[]): string[]

A RootFileNames function that keeps the tsconfig's declaration files (.d.ts, .d.mts, .d.cts) and drops its other roots.

Declaration files are where ambient types usually live (app.d.ts, a global.d.ts), so this keeps them resolving while the program stops loading every test, route, and config file the tsconfig includes. It does not cover an ambient declaration written in an ordinary .ts file that nothing imports — a declare global block or a declare module augmentation there is dropped with its file.

import {declarationFileRoots} from 'svelte-docinfo/typescript-program.ts';

DeclarationJson
#

types.ts view source

value + type

also exported from index.ts

type FunctionDeclarationJson | ClassDeclarationJson | InterfaceDeclarationJson | TypeDeclarationJson | VariableDeclarationJson | EnumDeclarationJson | ComponentDeclarationJson | SnippetDeclarationJson | NamespaceDeclarationJson

Metadata for an exported declaration (function, type, class, component, etc.).

Discriminated union on kind — each variant has only the fields relevant to that kind. Use isKind (in declaration-helpers.ts) to narrow, or check declaration.kind directly.

import {DeclarationJson} from 'svelte-docinfo/types.ts';

DeclarationJsonBuild
#

declaration-build.ts view source

Permissive type for constructing declarations incrementally before schema validation.

Used by internal analysis functions (analyzeDeclaration, extractFunctionInfo, etc.) that build declarations by mutating a plain object. The discriminated union schema validates the final shape at the parseModuleJson boundary.

import type {DeclarationJsonBuild} from 'svelte-docinfo/declaration-build.ts';

members

name

?: string
#

docComment

?: string
#

typeSignature

?: string
#

modifiers

?: DeclarationModifier[]
#

sourceLine

?: number
#

parameters

?: ParameterJsonInput[]
#

returnType

?: string
#

returnTypeInfo

?: TypeJson
#

returnPredicate

?: ReturnPredicateJsonInput
#

thisType

?: string
#

thisTypeInfo

?: TypeJson
#

returnDescription

?: string
#

genericParams

?: GenericParamJsonInput[]
#

overloads

?: OverloadJsonInput[]
#

examples

?: string[]
#

deprecatedMessage

?: string
#

internalMessage

?: string
#

seeAlso

?: string[]
#

throws

?: ThrowsJsonInput[]
#

since

?: string
#

mutates

?: Record<string, string>
#

extends

?: string[]
#

extendsInfo

?: TypeJson[]
#

externalTypes

?: string[]
#

implements

?: string[]
#

implementsInfo

?: TypeJson[]
#

members

?: MemberJsonBuild[]
#

acceptsChildren

?: boolean
#

cssCustomProperties

?: ComponentCssPropertyJsonInput[]
#

lang

?: "js"
#

alsoExportedFrom

?: string[]
#

aliasOf

?: { module: string; name: string; }
#

reactivity

?: Reactivity
#

partial

?: boolean
#

module

?: string
#

Source module path for kind: 'namespace' declarations (export * as ns from './x').

defaultValue

?: string
#

Default value documented via @default. Variable declarations only.

mergedValue

?: boolean
#

The exported name also carries a value meaning. Type/interface declarations only.

typeInfo

?: TypeJson
#

Structured type. Variable and type-alias declarations only; see TypeJson.

DeclarationJsonInput
#

DeclarationKind
#

types.ts view source

value + type

also exported from index.ts

"function" | "type" | "variable" | "class" | "interface" | "enum" | "component" | "snippet" | "namespace"

type "function" | "type" | "variable" | "class" | "interface" | "enum" | "component" | "snippet" | "namespace"

The kind of top-level exported declaration.

Does not include 'constructor' — constructors only appear as MemberKind (nested in classes, interfaces, or types with construct signatures), never as top-level module exports.

import {DeclarationKind} from 'svelte-docinfo/types.ts';

DeclarationModifier
#

types.ts view source

value + type

also exported from index.ts

"public" | "protected" | "readonly" | "static" | "abstract" | "getter" | "setter"

type "public" | "protected" | "readonly" | "static" | "abstract" | "getter" | "setter"

TypeScript modifier keywords extracted from declarations.

Only modifiers that appear on public API members are included. Private members (including #field syntax) are filtered out during analysis. Protected members are included as part of the extension API.

import {DeclarationModifier} from 'svelte-docinfo/types.ts';

DEFAULT_COMPILER_OPTIONS
#

typescript-program.ts view source

CompilerOptions

type CompilerOptions

The compiler options used under tsconfig: false, before the caller's compilerOptions are merged on top.

Set explicitly because the compiler's own defaults vary by TypeScript version, and before TypeScript 6 they are non-strict: without strictNullChecks a string | null prop prints as string. allowJs/checkJs type the imports of JS-lang components and .js modules (allowJs is forced on under any options; see withAllowJs).

import {DEFAULT_COMPILER_OPTIONS} from 'svelte-docinfo/typescript-program.ts';

DEFAULT_SOURCE_OPTIONS
#

source-config.ts view source

also exported from index.ts

SourceOptionsDefaults

Default partial options for standard SvelteKit library structure.

Does not include projectRoot — use createSourceOptions to create complete options with your project root.

exclude is the single source of truth for filtering: globs applied at both discovery time (by globFiles/discoverFromExports) and analysis time (by isSource() against project-root-relative paths).

import {DEFAULT_SOURCE_OPTIONS} from 'svelte-docinfo/source-config.ts';

see also

deriveIncludePatterns
#

files.ts view source

also exported from index.ts

deriveIncludePatterns(sourcePaths: readonly string[]): string[]

Build an include pattern array from source paths.

Each path becomes a <path>/**\/*.{ts,mts,tsx,js,mjs,jsx,svelte,css,json} glob. Used by discoverSourceFiles to derive a default include from sourceOptions.sourcePaths when no explicit pattern is supplied — keeps the glob fallback consistent with custom sourcePaths instead of silently defaulting to src/lib.

The '' source path (the whole project root — an explicit '', a normalized '.', or a root-crossing include base) derives a bare **\/*.{...} glob: prefixing it would produce a leading-slash pattern, which tinyglobby treats as absolute from the filesystem root.

import {deriveIncludePatterns} from 'svelte-docinfo/files.ts';

examples

deriveIncludePatterns(['packages/foo', 'packages/bar']) // => [ // 'packages/foo/**\/*.{ts,mts,tsx,js,mjs,jsx,svelte,css,json}', // 'packages/bar/**\/*.{ts,mts,tsx,js,mjs,jsx,svelte,css,json}' // ]

detectReactivity
#

typescript-extract-shared.ts view source

detectReactivity(initializer: Expression | undefined): Reactivity | undefined

Detect a Svelte 5 reactivity rune from a variable or property initializer.

Inspects the AST since runes erase to their inner type after type-checking. Returns undefined for any non-rune expression. See the Reactivity enum in types.ts for the rationale on running this on every file regardless of extension.

import {detectReactivity} from 'svelte-docinfo/typescript-extract-shared.ts';

Diagnostic
#

diagnostics.ts view source

value + type

also exported from index.ts

type TypeExtractionDiagnostic | SignatureAnalysisDiagnostic | ClassMemberDiagnostic | SveltePropDiagnostic | ModuleSkippedDiagnostic | ModuleUnreadableDiagnostic | ImportParseDiagnostic | DuplicateCommentDiagnostic | ComponentCommentMismatchDiagnostic | MisplacedTagDiagnostic | ImplementationDocHiddenDiagnostic | UnknownParamDiagnostic | UnknownCsspropDiagnostic | MalformedTagDiagnostic | DuplicateTagDiagnostic | CsspropDefaultMismatchDiagnostic | SourceMapFailedDiagnostic | DuplicateDeclarationDiagnostic | TransformFailedDiagnostic | ResolverFailedDiagnostic | AliasLostDiagnostic | CommonjsUnsupportedDiagnostic | CssParseFailedDiagnostic | CssLangUnsupportedDiagnostic

Discriminated union of all diagnostic variants. Ingest-time kinds: transform_failed, source_map_failed, import_parse_failed, and resolver_failed; discovery-time: module_unreadable; every other kind is query-time.

import {Diagnostic} from 'svelte-docinfo/diagnostics.ts';

DiagnosticKind
#

diagnostics.ts view source

value + type

also exported from index.ts

"type_extraction_failed" | "signature_analysis_failed" | "class_member_failed" | "svelte_prop_failed" | "module_skipped" | "module_unreadable" | "import_parse_failed" | ... 16 more ... | "css_lang_unsupported"

type "type_extraction_failed" | "signature_analysis_failed" | "class_member_failed" | "svelte_prop_failed" | "module_skipped" | "module_unreadable" | "import_parse_failed" | "duplicate_comment" | "component_comment_mismatch" | "misplaced_tag" | "implementation_doc_hidden" | "unknown_param" | "unknown_cssprop" | "malformed_tag" | "duplicate_tag" | "cssprop_default_mismatch" | "source_map_failed" | "duplicate_declaration" | "transform_failed" | "resolver_failed" | "alias_lost" | "commonjs_unsupported" | "css_parse_failed" | "css_lang_unsupported"

Discriminant for Diagnostic variant types.

Severity is a stable per-kind property: transform_failed and module_unreadable are always error, every other kind always warning.

import {DiagnosticKind} from 'svelte-docinfo/diagnostics.ts';

DiagnosticSeverity
#

diagnostics.ts view source

value + type

also exported from index.ts

"error" | "warning"

type "error" | "warning"

Diagnostic severity levels.

  • 'error' — analysis failed, declaration may be incomplete or missing data
  • 'warning' — partial success, something seems off but analysis continued
import {DiagnosticSeverity} from 'svelte-docinfo/diagnostics.ts';

discoverFromExports
#

exports.ts view source

discoverFromExports(options: ExportsDiscoveryOptions): Promise<ExportsDiscoveryResult>

Discover source files using package.json exports field.

Reads package.json, parses exports, maps dist paths to source paths, expands wildcard patterns, and loads file content.

Returns {files: null} when no package.json or no exports field exists, signaling the caller to fall back to glob discovery. Returns {files: []} when exports exist but resolve no source files (likely misconfigured mapping).

For concrete exports, maps directly to source paths and verifies existence. For wildcard exports, globs the source directory for matching files.

Null-target keys are honored with Node's resolution semantics: a subpath whose most-specific matching key is null is not exported, so its file is not discovered — "./internal/*": null beside the usual "./*.js" wildcards keeps src/lib/internal/ out of discovery exactly as it keeps the subpaths unresolvable for consumers (the src/lib/internal/ convention's exports half).

import {discoverFromExports} from 'svelte-docinfo/exports.ts';

parameters

discovery configuration

returns

ExportsDiscoveryResult with discovered files and any error diagnostics

discoverSourceFiles
#

discovery.ts view source

also exported from index.ts

discoverSourceFiles(options: DiscoverSourceFilesOptions): Promise<DiscoverSourceFilesResult>

Discover source files from a project root.

Used internally by analyzeFromFiles for the discovery step. Standalone consumers can call it directly when they want the discovered file list without running full analysis.

Strategy is selected by discovery (see Discovery). Exclusion globs come from sourceOptions.exclude, also applied at analysis time by isSource(); the always-on baseline (hasBaselineExcludedSegment) applies beneath it at both stages.

import {discoverSourceFiles} from 'svelte-docinfo/discovery.ts';

parameters

discovery configuration

returns

discovered files (content loaded) and any diagnostics from the exports step

throws

  • Error - when include is combined with discovery: 'exports', when an absolute include pattern falls outside projectRoot, or in strict 'exports' mode when exports is missing, resolves to no source files, or can't map a multi-sourcePaths layout with no common prefix

examples

const sourceOptions = createSourceOptions(process.cwd()); const {files, diagnostics} = await discoverSourceFiles({sourceOptions});

DiscoverSourceFilesOptions
#

discovery.ts view source

also exported from index.ts

Options for discoverSourceFiles.

import type {DiscoverSourceFilesOptions} from 'svelte-docinfo/discovery.ts';

members

sourceOptions

: ModuleSourceOptions
#

Source options used to resolve the source directory for exports-based discovery.

sourceOptions.projectRoot is the resolution base for include globs and the sourceOptions.exclude glob patterns. Build via createSourceOptions (which normalizes) or pass a normalized return from normalizeSourceOptions.

sourceOptions.exclude is the single source of truth for exclusion globs — applied at both this discovery stage and analysis time (via isSource()).

include

?: string[]
#

Glob patterns to include (relative to projectRoot; an absolute pattern inside the root relativizes, an out-of-root one throws — see normalizeIncludePatterns).

Filter for glob-based discovery. When discovery is 'auto' (default), providing include collapses the chain to glob immediately. Combining include with discovery: 'exports' throws.

When omitted, the glob fallback derives an include pattern from sourceOptions.sourcePaths via deriveIncludePatterns, so custom sourcePaths (e.g., ['packages/foo']) discover files instead of silently defaulting to src/lib.

Discovery alone doesn't widen the source scope: files outside sourcePaths are dropped at query time unless the options came from createSourceOptionsWithInclude (as analyzeFromFiles and the Vite plugin do).

discovery

?: Discovery = 'auto'
#

Discovery strategy.

see also

distDir

?: string = 'dist'
#

Dist directory name relative to projectRoot, used for exports-based discovery.

Maps dist paths from package.json exports back to source paths.

#

Optional logger for status messages.

DiscoverSourceFilesResult
#

Discovery
#

discovery.ts view source

also exported from index.ts

type "auto" | "exports" | "glob"

Discovery strategy for source files.

  • 'auto' (default) — try package.json exports first, fall back to glob patterns when exports is missing or resolves to nothing
  • 'exports' — package.json exports only, throw if exports is missing or resolves to no source files (strict mode for libraries that should always declare their public surface via exports)
  • 'glob' — skip exports entirely, use glob patterns

Under 'auto', include skips exports and goes straight to glob. Combining 'exports' with include is a configuration error and throws.

import type {Discovery} from 'svelte-docinfo/discovery.ts';

documentCssProperties
#

svelte-css.ts view source

documentCssProperties(css: ComponentCss, tags: readonly TsdocCssProperty[], tagLineOf: (name: string) => number): DocumentedComponentCss

Merge a component's @cssprop tags into its styling API (ComponentDeclarationJson.cssCustomProperties, whose policy this is).

Each tag is an entry, documented: true, in tag order, ahead of the listed undocumented reads, which keep their first-read order. The tag gives description, syntax, and default; the style gives fallback and sourceLine, so the two never overwrite each other. A tagged name the component reads takes the read's line and fallback: the listed entry's when the heuristic found the name, else the first read's anywhere (ComponentCss.reads: a bare read, one nested in another's fallback, one in the markup's static style text, or one of a name the component sets itself). A read name's @property syntax stays when the tag gives none. A tagged name the component never reads is kept at its tag's line and reported in unread; a tag default that disagrees with the fallback, whitespace runs aside, is reported in mismatched. When the style wasn't read (ComponentCss.problem), every tag is kept at its tag's line and nothing is reported.

import {documentCssProperties} from 'svelte-docinfo/svelte-css.ts';

parameters

the component's styling API as analyzeComponentCss read it

tags

: readonly TsdocCssProperty[]
#

the component doc comment's @cssprop tags

tagLineOf

: (name: string) => number
#

the 1-based line of a tag in the original source, by name

DocumentedComponentCss
#

svelte-css.ts view source

What documentCssProperties makes of a component's @cssprop tags.

import type {DocumentedComponentCss} from 'svelte-docinfo/svelte-css.ts';

members

The styling API with the documented properties merged in.

The documented entries the component never reads, at their tags' lines, in tag order.

The documented entries whose tag default disagrees with the style's fallback, in tag order.

DuplicateCommentDiagnostic
#

diagnostics.ts view source

value + type

Duplicate comment sources detected (e.g., both HTML and JSDoc @module, or both HTML @component and JSDoc for component docComment).

import {DuplicateCommentDiagnostic} from 'svelte-docinfo/diagnostics.ts';

inheritance

extends: SchemaStrictObjectOutput<typeof DuplicateCommentDiagnosticEntries>

members

kind

: "duplicate_comment"
#

commentType

: "module_comment" | "doc_comment"
#

Which comment type is duplicated.

file

: string
#

File path relative to project root (no leading slash, no ./ prefix).

Normalized at every public API boundary — session.setFile/setFiles (ingest-time), session.query (query-time, via analyzeCore), and the one-shot wrappers analyze / analyzeFromFiles. Producers inside the pipeline may write absolute or virtual paths (e.g., Foo.svelte.__svelte2tsx__.ts); normalization rewrites them to project-relative form before they reach consumers.

The exception is discovery — discoverSourceFiles / discoverFromExports return their diagnostics unnormalized, since they run before any session exists. Their file is already project-root-relative, but message can embed an absolute path (an fs error names the file it failed on), so a consumer wiring discovery up itself owns the normalizeDiagnosticPaths call — analyzeFromFiles and the Vite plugin both make it before merging.

The absolute form is the one to write. Normalization deliberately leaves an already-relative path alone (relativizing it would resolve against cwd), so a producer writing a ModuleJson.path — relative to sourceRoot, a different base — passes through untouched and publishes the same file under a second name. Absolute is what the pass can actually correct.

message

: string
#

Human-readable description of the issue.

severity

: "error" | "warning"
#

line

?: number
#

Line number (1-based), absent if location unavailable.

column

?: number
#

Column number (1-based), absent if location unavailable.

DuplicateCommentDiagnosticInput
#

diagnostics.ts view source

The input DuplicateCommentDiagnostic parses, with any field it defaults optional.

import type {DuplicateCommentDiagnosticInput} from 'svelte-docinfo/diagnostics.ts';

inheritance

extends: SchemaStrictObjectInput<typeof DuplicateCommentDiagnosticEntries>

members

kind

: "duplicate_comment"
#

commentType

: "module_comment" | "doc_comment"
#

Which comment type is duplicated.

file

: string
#

File path relative to project root (no leading slash, no ./ prefix).

Normalized at every public API boundary — session.setFile/setFiles (ingest-time), session.query (query-time, via analyzeCore), and the one-shot wrappers analyze / analyzeFromFiles. Producers inside the pipeline may write absolute or virtual paths (e.g., Foo.svelte.__svelte2tsx__.ts); normalization rewrites them to project-relative form before they reach consumers.

The exception is discovery — discoverSourceFiles / discoverFromExports return their diagnostics unnormalized, since they run before any session exists. Their file is already project-root-relative, but message can embed an absolute path (an fs error names the file it failed on), so a consumer wiring discovery up itself owns the normalizeDiagnosticPaths call — analyzeFromFiles and the Vite plugin both make it before merging.

The absolute form is the one to write. Normalization deliberately leaves an already-relative path alone (relativizing it would resolve against cwd), so a producer writing a ModuleJson.path — relative to sourceRoot, a different base — passes through untouched and publishes the same file under a second name. Absolute is what the pass can actually correct.

message

: string
#

Human-readable description of the issue.

severity

: "error" | "warning"
#

line

?: number
#

Line number (1-based), absent if location unavailable.

column

?: number
#

Column number (1-based), absent if location unavailable.

DuplicateDeclaration
#

postprocess.ts view source

A duplicate declaration with its full metadata and module path.

import type {DuplicateDeclaration} from 'svelte-docinfo/postprocess.ts';

members

declaration

: DeclarationJson
#

The full declaration metadata.

module

: string
#

Module path where this declaration is defined.

DuplicateDeclarationDiagnostic
#

diagnostics.ts view source

value + type

A declaration name appears in more than one module.

Opt-in: emitted only when onDuplicates is set, for packages that keep a flat export namespace (see OnDuplicates). Emitted at warning severity so the analysis result remains usable; onDuplicates: 'throw' makes it fatal. The default slot (name === 'default') is excluded — every module owns its own.

import {DuplicateDeclarationDiagnostic} from 'svelte-docinfo/diagnostics.ts';

inheritance

extends: SchemaStrictObjectOutput<typeof DuplicateDeclarationDiagnosticEntries>

members

kind

: "duplicate_declaration"
#

declarationName

: string
#

The duplicated declaration name.

modules

: string[]
#

Module paths where the name was defined (>= 2).

ModuleJson.path values — relative to sourceRoot, so a different base than the record's file (project-root-relative, like every diagnostic). The two disagree textually whenever sourceRoot is non-empty; each names what it says it names, a module vs. a file.

file

: string
#

File path relative to project root (no leading slash, no ./ prefix).

Normalized at every public API boundary — session.setFile/setFiles (ingest-time), session.query (query-time, via analyzeCore), and the one-shot wrappers analyze / analyzeFromFiles. Producers inside the pipeline may write absolute or virtual paths (e.g., Foo.svelte.__svelte2tsx__.ts); normalization rewrites them to project-relative form before they reach consumers.

The exception is discovery — discoverSourceFiles / discoverFromExports return their diagnostics unnormalized, since they run before any session exists. Their file is already project-root-relative, but message can embed an absolute path (an fs error names the file it failed on), so a consumer wiring discovery up itself owns the normalizeDiagnosticPaths call — analyzeFromFiles and the Vite plugin both make it before merging.

The absolute form is the one to write. Normalization deliberately leaves an already-relative path alone (relativizing it would resolve against cwd), so a producer writing a ModuleJson.path — relative to sourceRoot, a different base — passes through untouched and publishes the same file under a second name. Absolute is what the pass can actually correct.

message

: string
#

Human-readable description of the issue.

severity

: "error" | "warning"
#

line

?: number
#

Line number (1-based), absent if location unavailable.

column

?: number
#

Column number (1-based), absent if location unavailable.

DuplicateDeclarationDiagnosticInput
#

diagnostics.ts view source

The input DuplicateDeclarationDiagnostic parses, with any field it defaults optional.

import type {DuplicateDeclarationDiagnosticInput} from 'svelte-docinfo/diagnostics.ts';

inheritance

extends: SchemaStrictObjectInput<typeof DuplicateDeclarationDiagnosticEntries>

members

kind

: "duplicate_declaration"
#

declarationName

: string
#

The duplicated declaration name.

modules

: string[]
#

Module paths where the name was defined (>= 2).

ModuleJson.path values — relative to sourceRoot, so a different base than the record's file (project-root-relative, like every diagnostic). The two disagree textually whenever sourceRoot is non-empty; each names what it says it names, a module vs. a file.

file

: string
#

File path relative to project root (no leading slash, no ./ prefix).

Normalized at every public API boundary — session.setFile/setFiles (ingest-time), session.query (query-time, via analyzeCore), and the one-shot wrappers analyze / analyzeFromFiles. Producers inside the pipeline may write absolute or virtual paths (e.g., Foo.svelte.__svelte2tsx__.ts); normalization rewrites them to project-relative form before they reach consumers.

The exception is discovery — discoverSourceFiles / discoverFromExports return their diagnostics unnormalized, since they run before any session exists. Their file is already project-root-relative, but message can embed an absolute path (an fs error names the file it failed on), so a consumer wiring discovery up itself owns the normalizeDiagnosticPaths call — analyzeFromFiles and the Vite plugin both make it before merging.

The absolute form is the one to write. Normalization deliberately leaves an already-relative path alone (relativizing it would resolve against cwd), so a producer writing a ModuleJson.path — relative to sourceRoot, a different base — passes through untouched and publishes the same file under a second name. Absolute is what the pass can actually correct.

message

: string
#

Human-readable description of the issue.

severity

: "error" | "warning"
#

line

?: number
#

Line number (1-based), absent if location unavailable.

column

?: number
#

Column number (1-based), absent if location unavailable.

DuplicateTagDiagnostic
#

diagnostics.ts view source

value + type

A JSDoc tag repeats a key an earlier tag of the same name in the comment already set, so it documents nothing.

Today only @cssprop (@cssproperty): a second tag naming the same custom property. Emitted on a Svelte component's doc comment, at the later tag's line; the first tag wins. On any other declaration the tags warn misplaced_tag instead.

Always warning, query-time category.

import {DuplicateTagDiagnostic} from 'svelte-docinfo/diagnostics.ts';

inheritance

extends: SchemaStrictObjectOutput<typeof DuplicateTagDiagnosticEntries>

members

kind

: "duplicate_tag"
#

tagName

: "cssprop"
#

The tag name without the @ prefix; a synonym reports its canonical name.

declarationName

: string
#

Name of the declaration whose doc comment carries the tags.

key

: string
#

The repeated key: the custom property's name for @cssprop, -- included.

file

: string
#

File path relative to project root (no leading slash, no ./ prefix).

Normalized at every public API boundary — session.setFile/setFiles (ingest-time), session.query (query-time, via analyzeCore), and the one-shot wrappers analyze / analyzeFromFiles. Producers inside the pipeline may write absolute or virtual paths (e.g., Foo.svelte.__svelte2tsx__.ts); normalization rewrites them to project-relative form before they reach consumers.

The exception is discovery — discoverSourceFiles / discoverFromExports return their diagnostics unnormalized, since they run before any session exists. Their file is already project-root-relative, but message can embed an absolute path (an fs error names the file it failed on), so a consumer wiring discovery up itself owns the normalizeDiagnosticPaths call — analyzeFromFiles and the Vite plugin both make it before merging.

The absolute form is the one to write. Normalization deliberately leaves an already-relative path alone (relativizing it would resolve against cwd), so a producer writing a ModuleJson.path — relative to sourceRoot, a different base — passes through untouched and publishes the same file under a second name. Absolute is what the pass can actually correct.

message

: string
#

Human-readable description of the issue.

severity

: "error" | "warning"
#

line

?: number
#

Line number (1-based), absent if location unavailable.

column

?: number
#

Column number (1-based), absent if location unavailable.

DuplicateTagDiagnosticInput
#

diagnostics.ts view source

The input DuplicateTagDiagnostic parses, with any field it defaults optional.

import type {DuplicateTagDiagnosticInput} from 'svelte-docinfo/diagnostics.ts';

inheritance

extends: SchemaStrictObjectInput<typeof DuplicateTagDiagnosticEntries>

members

kind

: "duplicate_tag"
#

tagName

: "cssprop"
#

The tag name without the @ prefix; a synonym reports its canonical name.

declarationName

: string
#

Name of the declaration whose doc comment carries the tags.

key

: string
#

The repeated key: the custom property's name for @cssprop, -- included.

file

: string
#

File path relative to project root (no leading slash, no ./ prefix).

Normalized at every public API boundary — session.setFile/setFiles (ingest-time), session.query (query-time, via analyzeCore), and the one-shot wrappers analyze / analyzeFromFiles. Producers inside the pipeline may write absolute or virtual paths (e.g., Foo.svelte.__svelte2tsx__.ts); normalization rewrites them to project-relative form before they reach consumers.

The exception is discovery — discoverSourceFiles / discoverFromExports return their diagnostics unnormalized, since they run before any session exists. Their file is already project-root-relative, but message can embed an absolute path (an fs error names the file it failed on), so a consumer wiring discovery up itself owns the normalizeDiagnosticPaths call — analyzeFromFiles and the Vite plugin both make it before merging.

The absolute form is the one to write. Normalization deliberately leaves an already-relative path alone (relativizing it would resolve against cwd), so a producer writing a ModuleJson.path — relative to sourceRoot, a different base — passes through untouched and publishes the same file under a second name. Absolute is what the pass can actually correct.

message

: string
#

Human-readable description of the issue.

severity

: "error" | "warning"
#

line

?: number
#

Line number (1-based), absent if location unavailable.

column

?: number
#

Column number (1-based), absent if location unavailable.

emitCallOrConstructSignature
#

typescript-extract-shared.ts view source

emitCallOrConstructSignature(getSignatures: () => readonly Signature[], signatureKind: "call" | "construct", resolveTsdocNode: (sig: Signature) => Node | undefined, paramValidationFallbackNode: Node, declaration: DeclarationJsonBuild, ctx: ExtractContext, errorContext: { node: Node; kindLabel: string; }): void

Append a (call) or (construct) signature member to a declaration.

Captures the extraction logic shared by interface processing (extractTypeInfo) and type-alias property processing (extractTypeAliasProperties): type signature, parameters, generics, overloads, and TSDoc. The TSDoc source node is supplied by the caller — interfaces look it up in node.members (skipping TSDoc when no inline signature is declared, even if one is inherited), type aliases use sig.getDeclaration().

import {emitCallOrConstructSignature} from 'svelte-docinfo/typescript-extract-shared.ts';

parameters

getSignatures

: () => readonly Signature[]
#

thunk to retrieve getCallSignatures() / getConstructSignatures(); called inside the try so checker errors are captured as diagnostics

signatureKind

: "call" | "construct"
#

'call' (member kind: function, includes returnType) or 'construct' (member kind: constructor, no returnType)

resolveTsdocNode

: (sig: Signature) => Node | undefined
#

callback returning the AST node to parse TSDoc from, or undefined to skip TSDoc resolution

paramValidationFallbackNode

: Node
#

location used by validateParamKeys when resolveTsdocNode returns undefined

#

parent declaration (mutated; appended to members)

errorContext

: { node: Node; kindLabel: string; }
#
  • errorContext.node — parent node used to locate diagnostics
  • errorContext.kindLabel — 'interface' or 'type', included in the diagnostic message

mutates

  • declaration — appends a member when signatures are present; sets partial: true on extraction failure
  • ctx.diagnostics — adds signature_analysis_failed on checker error

EnumDeclarationJson
#

types.ts view source

value + type

also exported from index.ts

An enum declaration. Has members for enum values.

import {EnumDeclarationJson} from 'svelte-docinfo/types.ts';

inheritance

extends: SchemaStrictObjectOutput<typeof EnumDeclarationJsonEntries>

members

kind

: "enum"
#

Enum members: name/value pairs with optional JSDoc.

alsoExportedFrom

: string[]
#

Module paths (relative to sourceRoot) that re-export this declaration under the same name. The canonical declaration lives in this module's declarations array; these paths are additional import locations for the same thing.

The same edges appear from the re-exporting side as ModuleJson.reExports — use that when asking "what does this module re-export" instead of inverting these arrays. The two can disagree at the margins: a reExports entry whose canonical declaration is @nodocs (or whose module isn't in the analyzed set) has no back-link here.

Consumer note: To build a complete re-export map, scan two fields:

  1. alsoExportedFrom on each declaration — same-name re-exports
  2. aliasOf on declarations — renamed re-exports (separate declarations)

partial

: boolean
#

Whether extraction failed partway through, leaving some fields missing (e.g., typeSignature, parameters).

examples

: string[]
#

Code examples from @example tags.

seeAlso

: string[]
#

Related items from @see tags, in raw TSDoc format.

throws

: ThrowsJson[]
#

Exceptions from @throws tags. type is the tag's written type, and typeInfo its structured form, present for a braced type (@throws {A<B>}) that isn't the whole story as text (see TypeJson); an unbraced tag's leading word never has one, nor does a tag in a component's HTML @component comment, which is read as text.

name

: string
#

The exported name. Always populated. The default-export slot is named 'default', except a Svelte component, which takes its filename-derived name ('X' for X.svelte) — 'default' is the symbol's actual name in JS (import {default as X} and ns.default both expose it directly), and import X from 'mod' is sugar for import {default as X}. Consumers branch on name === 'default' to render the sugar form when desired.

modifiers

: ("public" | "protected" | "readonly" | "static" | "abstract" | "getter" | "setter")[]
#

TypeScript modifiers like readonly, static, or protected.

genericParams

: GenericParamJson[]
#

Generic type parameters like <T, U>.

aliasOf

?: { module: string; name: string; }
#

For renamed re-exports (export {foo as bar}), points to the original declaration. This declaration's name is the alias; aliasOf.name is the original name.

For renames out of the default slot (export {default as bar} from './x' where ./x is export default ...), aliasOf.name is 'default' — the canonical's actual symbol name. Consumers locate the canonical by (aliasOf.module, aliasOf.name).

Svelte component exception: when the source is a .svelte file (e.g., export {default as Foo} from './X.svelte'), the canonical's name is the component name (derived from the filename), so aliasOf.name is the component name ('X'), NOT 'default'. Consumers that branch on aliasOf.name === 'default' to detect default-rename should additionally check whether aliasOf.module ends with .svelte.

Different from alsoExportedFrom: aliases create new API surface names, while alsoExportedFrom tracks additional import paths for the same name.

A type-only rename of a value (export type {someConst as c} from './x') synthesizes a normal alias — declarations carry no type-only marker.

deprecatedMessage

?: string
#

Deprecation message from @deprecated tag.

since

?: string
#

Version introduced, from @since tag.

internalMessage

?: string
#

Internal-API marker from the @internal tag. Presence means the tag was written; an empty string is a bare tag with no trailing prose.

A marker, not an exclusion: @internal means "not stable public API" (TSDoc semantics) while the declaration, member, or prop stays documented — unlike @nodocs, which removes a declaration from output entirely (and is ignored on props and members).

mutates

?: Record<string, string>
#

Mutation documentation from @mutates tags (non-standard), mapping keys to descriptions.

Keys are intentionally unvalidated — typically a parameter name, but authors may also use compound paths (this.foo, obj.field) or multi-word external state references. Backticks are stripped from keys so `` a `` and a normalize to one key; an empty-string value is a bare tag with no description. The schema accepts any string key so consumers can render whatever the author wrote.

On a component prop it declares the component's mutation contract for the value it's handed: the component writes into the prop's object or array in place (@mutates items - appends the selected entry, @mutates options.cache - fills on first render). Reassigning a prop is not a mutation in this sense (bindable covers it), though a $bindable prop can carry both.

docComment

?: string
#

JSDoc/TSDoc comment.

typeSignature

?: string
#

Full TypeScript type signature.

sourceLine

?: number
#

1-based line in the source file, a positive integer. Synthesized aliases (see aliasOf) carry the local export specifier's line, not the canonical's.

EnumDeclarationJsonInput
#

types.ts view source

The input EnumDeclarationJson parses, with any field it defaults optional.

import type {EnumDeclarationJsonInput} from 'svelte-docinfo/types.ts';

inheritance

extends: SchemaStrictObjectInput<typeof EnumDeclarationJsonEntries>

members

kind

: "enum"
#

name

: string
#

The exported name. Always populated. The default-export slot is named 'default', except a Svelte component, which takes its filename-derived name ('X' for X.svelte) — 'default' is the symbol's actual name in JS (import {default as X} and ns.default both expose it directly), and import X from 'mod' is sugar for import {default as X}. Consumers branch on name === 'default' to render the sugar form when desired.

Enum members: name/value pairs with optional JSDoc.

alsoExportedFrom

?: string[]
#

Module paths (relative to sourceRoot) that re-export this declaration under the same name. The canonical declaration lives in this module's declarations array; these paths are additional import locations for the same thing.

The same edges appear from the re-exporting side as ModuleJson.reExports — use that when asking "what does this module re-export" instead of inverting these arrays. The two can disagree at the margins: a reExports entry whose canonical declaration is @nodocs (or whose module isn't in the analyzed set) has no back-link here.

Consumer note: To build a complete re-export map, scan two fields:

  1. alsoExportedFrom on each declaration — same-name re-exports
  2. aliasOf on declarations — renamed re-exports (separate declarations)

aliasOf

?: { module: string; name: string; }
#

For renamed re-exports (export {foo as bar}), points to the original declaration. This declaration's name is the alias; aliasOf.name is the original name.

For renames out of the default slot (export {default as bar} from './x' where ./x is export default ...), aliasOf.name is 'default' — the canonical's actual symbol name. Consumers locate the canonical by (aliasOf.module, aliasOf.name).

Svelte component exception: when the source is a .svelte file (e.g., export {default as Foo} from './X.svelte'), the canonical's name is the component name (derived from the filename), so aliasOf.name is the component name ('X'), NOT 'default'. Consumers that branch on aliasOf.name === 'default' to detect default-rename should additionally check whether aliasOf.module ends with .svelte.

Different from alsoExportedFrom: aliases create new API surface names, while alsoExportedFrom tracks additional import paths for the same name.

A type-only rename of a value (export type {someConst as c} from './x') synthesizes a normal alias — declarations carry no type-only marker.

partial

?: boolean
#

Whether extraction failed partway through, leaving some fields missing (e.g., typeSignature, parameters).

examples

?: string[]
#

Code examples from @example tags.

deprecatedMessage

?: string
#

Deprecation message from @deprecated tag.

seeAlso

?: string[]
#

Related items from @see tags, in raw TSDoc format.

throws

?: ThrowsJsonInput[]
#

Exceptions from @throws tags. type is the tag's written type, and typeInfo its structured form, present for a braced type (@throws {A<B>}) that isn't the whole story as text (see TypeJson); an unbraced tag's leading word never has one, nor does a tag in a component's HTML @component comment, which is read as text.

since

?: string
#

Version introduced, from @since tag.

internalMessage

?: string
#

Internal-API marker from the @internal tag. Presence means the tag was written; an empty string is a bare tag with no trailing prose.

A marker, not an exclusion: @internal means "not stable public API" (TSDoc semantics) while the declaration, member, or prop stays documented — unlike @nodocs, which removes a declaration from output entirely (and is ignored on props and members).

mutates

?: Record<string, string>
#

Mutation documentation from @mutates tags (non-standard), mapping keys to descriptions.

Keys are intentionally unvalidated — typically a parameter name, but authors may also use compound paths (this.foo, obj.field) or multi-word external state references. Backticks are stripped from keys so `` a `` and a normalize to one key; an empty-string value is a bare tag with no description. The schema accepts any string key so consumers can render whatever the author wrote.

On a component prop it declares the component's mutation contract for the value it's handed: the component writes into the prop's object or array in place (@mutates items - appends the selected entry, @mutates options.cache - fills on first render). Reassigning a prop is not a mutation in this sense (bindable covers it), though a $bindable prop can carry both.

docComment

?: string
#

JSDoc/TSDoc comment.

typeSignature

?: string
#

Full TypeScript type signature.

modifiers

?: ("public" | "protected" | "readonly" | "static" | "abstract" | "getter" | "setter")[]
#

TypeScript modifiers like readonly, static, or protected.

sourceLine

?: number
#

1-based line in the source file, a positive integer. Synthesized aliases (see aliasOf) carry the local export specifier's line, not the canonical's.

genericParams

?: GenericParamJsonInput[]
#

Generic type parameters like <T, U>.

errorsOf
#

ExcludeOption
#

source-config.ts view source

also exported from index.ts

type string[] | ((defaults: string[]) => string[])

Exclude patterns as accepted by the override surfaces (createSourceOptions, analyzeFromFiles, the Vite plugin — not the CLI, whose --exclude is array-only).

An array replaces DEFAULT_SOURCE_OPTIONS.exclude wholesale (the test, spec, and internal/ filters are dropped unless restated); the callback form receives a fresh copy of those defaults and returns the list to use, so extending them doesn't require restating them:

exclude: (defaults) => [...defaults, '**\/*.gen.ts'] // add a pattern exclude: (defaults) => defaults.filter((p) => p !== '**\/internal/**') // drop one

The callback runs at most once per built options object (include-pattern widening rebuilds options from the already-resolved array). Resolved to a plain array before normalization; ModuleSourceOptions.exclude never carries the function form. The always-on baseline (node_modules + dot-directories below a matched source path, hasBaselineExcludedSegment) applies beneath either form and is unaffected by overrides.

import type {ExcludeOption} from 'svelte-docinfo/source-config.ts';

ExportEntry
#

exports.ts view source

A parsed entry from package.json exports field.

import type {ExportEntry} from 'svelte-docinfo/exports.ts';

members

specifier

: string
#

The export specifier (e.g., ".", "./*.js").

isPattern

: boolean
#

Whether the specifier contains a wildcard (*).

conditions

: Record<string, string>
#

Resolved dist paths by condition (e.g., {types: "./dist/index.d.ts", default: "./dist/index.js"}).

ExportsDiscoveryOptions
#

exports.ts view source

Options for discoverFromExports.

import type {ExportsDiscoveryOptions} from 'svelte-docinfo/exports.ts';

members

projectRoot

: string
#

Absolute path to project root.

distDir

?: string
#

Dist directory name relative to projectRoot. Default: 'dist'.

sourceDir

?: string
#

Source directory name relative to projectRoot. Default: 'src/lib'.

exclude

?: string[]
#

Glob patterns to exclude from discovered files.

ExportsDiscoveryResult
#

exports.ts view source

Result of discovering source files from package.json exports.

Self-contained: includes both the discovered files and any error diagnostics (e.g., files that exist but could not be read).

import type {ExportsDiscoveryResult} from 'svelte-docinfo/exports.ts';

members

files

: SourceFileInfo[] | null
#

Discovered source files, or null if no exports field found. Empty array means exports field exists but resolved no source files (likely a misconfigured dist-to-source mapping).

diagnostics

: Diagnostic[]
#

Error diagnostics for files that exist but could not be read.

ExportSurface
#

postprocess.ts view source

also exported from index.ts

A module's resolved export surface — see resolveExportSurface.

import type {ExportSurface} from 'svelte-docinfo/postprocess.ts';

members

#

Surface entries, sorted by name (case-insensitive order, compareStrings).

unresolvedStarExports

: string[]
#

Star targets (own or transitive) whose projected names are unknown, so the surface is incomplete: ones absent from modules (a filtered list, modules assembled by hand — a whole analysis result's starExports only name modules it contains), and partial placeholders, such as a component that failed to transform.

externalStarExports

: string[]
#

External star specifiers reachable from this module (own or transitive) — their projected names are unknowable without analyzing the package.

ExportSurfaceEntry
#

postprocess.ts view source

also exported from index.ts

One name on a module's resolved export surface.

import type {ExportSurfaceEntry} from 'svelte-docinfo/postprocess.ts';

members

name

: string
#

Exported name, in the docinfo model's terms — Svelte components appear under their filename-derived name (the model's convention for default exports of .svelte files), not 'default'.

via

: "declaration" | "reExport" | "external" | "star"
#

How the name reaches this module's surface: an own declaration (including synthesized aliases), a same-name re-export edge, a direct external re-export, or projection through export * from './x'.

module

?: string
#

Canonical module path, when known (undefined for external entries).

declaration

?: DeclarationJson
#

The canonical declaration, when present in the analyzed set.

specifier

?: string
#

Package specifier for external entries (as written in the statement).

originalName

?: string
#

Name inside the external package when renamed.

typeOnly

?: boolean
#

Type-only re-export — the name is erased at runtime.

starFrom

?: string
#

For star-projected entries: the starExports target the name arrived through.

ExternalReExportJson
#

types.ts view source

value + type

also exported from index.ts

A re-export whose immediate target is an external package — export {x} from 'pkg', export {x as y} from 'pkg', or export * as ns from 'pkg'. External is per createIsExternalPath; a project-local target excluded from output (the internal/ convention) is not external, and its re-exports synthesize alias declarations instead.

specifier is the module specifier as written (usually a package name); there is no canonical declaration to resolve, so these entries are flat facts about the statement rather than edges into the module graph.

Only statements that *directly* reference the external specifier are captured. Forms that stay silent: import {x} from 'pkg'; export {x}; (import-then-export), re-export chains that reach a package through another source module (that module owns the entry) or through a project-local gated module, and specifiers the checker can't resolve. Statement-level @nodocs suppresses the entry.

import {ExternalReExportJson} from 'svelte-docinfo/types.ts';

inheritance

extends: SchemaStrictObjectOutput<typeof ExternalReExportJsonEntries>

members

name

: string
#

Public exported name from this module.

specifier

: string
#

Module specifier as written in the statement (e.g. 'pkg').

typeOnly

: boolean
#

Whether the statement or specifier is type-only — see ReExportJson.typeOnly.

originalName

?: string
#

The name inside the external module when renamed (export {x as y} from 'pkg' → 'x'). Omitted for same-name re-exports and namespace form (export * as ns).

sourceLine

?: number
#

1-based line of the export specifier in this module's source, a positive integer.

ExternalReExportJsonInput
#

types.ts view source

The input ExternalReExportJson parses, with any field it defaults optional.

import type {ExternalReExportJsonInput} from 'svelte-docinfo/types.ts';

inheritance

extends: SchemaStrictObjectInput<typeof ExternalReExportJsonEntries>

members

name

: string
#

Public exported name from this module.

specifier

: string
#

Module specifier as written in the statement (e.g. 'pkg').

originalName

?: string
#

The name inside the external module when renamed (export {x as y} from 'pkg' → 'x'). Omitted for same-name re-exports and namespace form (export * as ns).

typeOnly

?: boolean
#

Whether the statement or specifier is type-only — see ReExportJson.typeOnly.

sourceLine

?: number
#

1-based line of the export specifier in this module's source, a positive integer.

extractClassInfo
#

typescript-extract-class.ts view source

internal

Used by `analyzeDeclaration` — not part of the public barrel export.

extractClassInfo(node: Node, declaration: DeclarationJsonBuild, ctx: ExtractContext): void

Extract class information with rich member metadata. Decorators aren't modeled.

A JS class reads as the checker reads it, so it documents like its TypeScript twin: JSDoc modifier tags through extractModifiers and isPrivateMemberDeclaration, @extends/@implements tags as heritage (classExtendsType, classImplementsTypes), and this.x = … assignments as members (collectThisAssignedMembers).

import {extractClassInfo} from 'svelte-docinfo/typescript-extract-class.ts';

parameters

node

: Node
#

the declaration AST node

#

the declaration to populate

the extraction pass's context

mutates

  • declaration — adds extends, implements, genericParams, members

extractComputedHeritageMembers
#

typescript-extract-type-properties.ts view source

extractComputedHeritageMembers(node: InterfaceDeclaration, heritageTypes: readonly ExpressionWithTypeArguments[], declaration: DeclarationJsonBuild, ctx: ExtractContext): ContributedSignatures

Emit the members an interface gets from its computed heritage.

An interface's members are its own, plus what each extends entry that isn't a named interface or class contributes (isNamedHeritageType). A named base has its own declaration, which extends names, so its members stay there. A computed type has none: `interface A extends z.infer<typeof S> {}, the author-side fix for alias_lost`, or interface A extends Omit<Base, 'b'> {}, would otherwise document no member reachable anywhere. Each computed entry contributes what the same type documents as a type alias's members (extractTypeAliasProperties): its properties through the same projection (emitPropertyMembers), filtered by the same external-origin and visibility rules (filterDocumentedProperties; the labels for what that drops come from applyHeritageExternalTypes, which walks the same entries), then its local string and number index signatures. So a computed type over a named interface (Partial<Base>, Pick<Base, 'a'>, Base & {c: C}) lists the base's properties it keeps, as the alias would, and a project type alias in extends, an object type with no declaration of its own, contributes too, even when it is documented itself.

Which entry a name comes from follows TypeScript's inheritance: a name the interface declares wins, then the first heritage entry, named or computed, that has the name. The declared names are read from every merged block (symbol.members), though only node's block is documented (its members by extractTypeInfo, its extends here): a name another block declares drops from the contribution and documents nowhere, which is right where it overrides the heritage's type, and the other block's members going undocumented is a limitation of the one-block reading, not of this rule. A name a named base supplies first stays that base's; one an external bag supplies first is dropped. An index signature likewise comes from the first entry with that key type, unless the interface declares one. Contributed members follow the own ones, entry by entry in heritage order, each type's properties in the checker's order, then their index signatures. They carry no sourceLine, like every member.

Call and construct signatures go by declaration the same way: the first entry whose type has a signature declaration claims it, so one a named base supplies first stays the base's even when a later computed entry reaches it too (extends Base, Base & {…}), and each declaration is contributed once. The caller emits them, since they join the own signatures as overloads of one member (extractTypeInfo).

import {extractComputedHeritageMembers} from 'svelte-docinfo/typescript-extract-type-properties.ts';

parameters

heritageTypes

: readonly ExpressionWithTypeArguments[]
#

the processed declaration's own extends entries

returns

the signature declarations the computed entries contribute, local ones only

mutates

  • declaration — appends the contributed members (and partial: true on extraction failure)
  • ctx.diagnostics — adds type_extraction_failed on checker errors

ExtractContext
#

typescript-extract-shared.ts view source

The pass-scoped, cross-cutting state one extraction run threads through the extractor seams — analyzeDeclaration down to the resolveTypeInfo call sites. Constructed once per module walk (analyzeExports, analyzeSvelteModule) or per direct call (tests, fixture harnesses).

Membership is deliberately tight: only state that is constant for the pass and consumed across extractor boundaries belongs here. Per-declaration inputs (nodes, symbols, parsed TSDoc, written annotations, names) stay positional parameters.

import type {ExtractContext} from 'svelte-docinfo/typescript-extract-shared.ts';

members

checker

: TypeChecker
#

diagnostics

: Diagnostic[]
#

Accumulator for non-fatal issues — mutated via Array.push throughout the pass.

isExternalFile

: IsExternalFile
#

Predicate for external source files (node_modules, out-of-tree declarations).

aliasRegistry

: AliasRegistry | undefined
#

Identity-keyed registry of the analyzed set's exported alias-lost type aliases (buildAliasRegistry in typescript-alias-registry.ts), or undefined when no pre-pass ran — registry recovery is then disabled while written-name recovery keeps working. A required field so every construction site decides explicitly.

exactOptionalPropertyTypes

: boolean
#

The program's exactOptionalPropertyTypes compiler option — read it off program.getCompilerOptions(). Consumed by optionalWidened, which documents the strip-gating policy. A required field so every construction site decides explicitly, like aliasRegistry.

isEmittedFile

: IsEmittedFile
#

Whether a file emits a module this pass (see IsEmittedFile).

svelteFileStatus

: (file: string) => SvelteFileStatus
#

What the pass can see of a .svelte file (see SvelteFileStatus).

extractDependencies
#

source-config.ts view source

extractDependencies(sourceFile: SourceFileInfo & { dependents?: readonly string[]; }, options: ModuleSourceOptions): { dependencies: string[]; dependents: string[]; }

Extract dependencies and dependents for a module from source file info.

Filters to only include source modules (excludes external packages, node_modules, tests). Returns sorted arrays of module paths (relative to sourceRoot) for deterministic output.

Native paths in sourceFile.dependencies/dependents are accepted — isSource and extractPath posixify their inputs, so direct callers with hand-built input need not pre-normalize.

Accepts SourceFileInfo plus an optional dependents field — the public input type carries only dependencies (caller-supplied opt-in), while dependents is computed downstream by computeDependents and flows through as an enriched shape.

import {extractDependencies} from 'svelte-docinfo/source-config.ts';

parameters

sourceFile

: SourceFileInfo & { dependents?: readonly string[]; }
#

the source file info to extract dependencies from

module source options for filtering and path extraction

returns

sorted arrays of module paths (relative to sourceRoot) for dependencies and dependents

extractEnumInfo
#

typescript-extract-type.ts view source

internal

Used by `analyzeDeclaration` — not part of the public barrel export.

extractEnumInfo(node: Node, declaration: DeclarationJsonBuild, ctx: ExtractContext): void

Extract enum member information from an enum declaration.

Iterates node.members to extract each enum member's name, initializer value, type, and JSDoc. Members are represented as MemberJson with kind 'variable'.

A JS @enum {T} const (isJSDocEnumSymbol) arrives as its variable declaration. Its typeSignature is the tag's type, T, the type the name means in an annotation (@param {A} a takes any T), and its members are the value's properties in declaration order, each with its own JSDoc and checker type.

import {extractEnumInfo} from 'svelte-docinfo/typescript-extract-type.ts';

mutates

  • declaration — adds members and typeSignature

extractFunctionInfo
#

typescript-extract-function.ts view source

internal

Used by `analyzeDeclaration` — not part of the public barrel export.

extractFunctionInfo(node: Node, symbol: Symbol, declaration: DeclarationJsonBuild, tsdoc: TsdocParsedComment | undefined, ctx: ExtractContext): void

Extract function/method information including parameters with descriptions and default values.

import {extractFunctionInfo} from 'svelte-docinfo/typescript-extract-function.ts';

parameters

node

: Node
#

the declaration AST node

symbol

: Symbol
#

the TypeScript symbol

#

the declaration to populate

tsdoc

: TsdocParsedComment | undefined
#

parsed TSDoc comment (if available)

the extraction pass's context

mutates

  • declaration — adds typeSignature, returnType, returnDescription, parameters, genericParams, overloads (and partial: true on signature failure)
  • ctx.diagnostics — adds signature_analysis_failed diagnostic on checker error

extractHtmlModuleComment
#

svelte.ts view source

extractHtmlModuleComment(svelteSource: string): TsdocParsedComment | undefined

Extract and parse the @module comment from HTML comments in Svelte source.

Scans all <!-- ... --> comments for one containing @module at the start of a line. This allows @component and @module to coexist as separate HTML comments. Works for template-only components.

The lines' common indentation is stripped (dedentHtmlComment), then the text parses through parseModuleComment, the parser a script's module comment uses, so tags read the same in either form (a *\/ in the HTML text survives intact).

import {extractHtmlModuleComment} from 'svelte-docinfo/svelte.ts';

parameters

svelteSource

: string
#

the full Svelte source code

returns

the parsed module comment, or undefined if no @module HTML comment is found or it holds nothing but @module

extractModifiers
#

typescript-extract-shared.ts view source

extractModifiers(node: Declaration, extraFlags?: ModifierFlags): DeclarationModifier[]

Extract a declaration's modifiers, like ['public', 'static', 'readonly'], in the order TypeScript requires them written, so a JS declaration's tags and keywords order like its TS twin's keywords.

Read through ts.getCombinedModifierFlags, which in JS adds the JSDoc modifier tags the checker reads (@public, @protected, @readonly; @private hides the member, see isPrivateMemberDeclaration) and in a .ts file reads keywords only. The checker reads no @static or @abstract tag, so neither does this; @override it reads, but override isn't a modeled modifier in either language.

import {extractModifiers} from 'svelte-docinfo/typescript-extract-shared.ts';

parameters

extraFlags

?: ModifierFlags = ts.ModifierFlags.None
#

flags the declaration's position implies, like a static this.x = … member's Static

extractModuleComment
#

typescript-exports.ts view source

internal

Used by `analyzeTypescriptModule` and `analyzeSvelteModule`'s script handling. Exposed via the `svelte-docinfo/typescript-exports.js` subpath so the Svelte analyzer can reuse it without circular imports, but **not part of the stable barrel export**. The module comment is the first `/**` comment with a line starting with `@module`; later ones are ignored. It parses through `parseModuleComment`, so its tags read as a declaration's do and `@module` lines (with any `@module custom-name` rename) are dropped. `toModuleDocFields` projects the result onto `ModuleJson`, and `warnModuleCommentTags` reports the tags it drops.

extractModuleComment(sourceFile: SourceFile): TsdocParsedComment | undefined

Extract and parse the module-level comment.

import {extractModuleComment} from 'svelte-docinfo/typescript-exports.ts';

returns

the parsed comment, or undefined if no @module comment is found or it holds nothing but @module

see also

extractModuleScriptContent
#

svelte.ts view source

extractModuleScriptContent(svelteSource: string): string | undefined

Extract the content of the component's module <script> from Svelte source.

Counterpart of extractScriptContent: matches only the module script, under the same top-level rule and at the same per-call cost, so the two partition a source's script tags consistently.

import {extractModuleScriptContent} from 'svelte-docinfo/svelte.ts';

returns

the module script tag content, or undefined if no module script is found

extractPath
#

source-config.ts view source

extractPath(sourceId: string, options: ModuleSourceOptions): string

Extract module path relative to source root from absolute source ID.

Uses proper path semantics: strips projectRoot/sourceRoot/ prefix.

import {extractPath} from 'svelte-docinfo/source-config.ts';

parameters

sourceId

: string
#

absolute path to the source file

module source options for path extraction

examples

const options = createSourceOptions('/home/user/project'); extractPath('/home/user/project/src/lib/foo.ts', options) // => 'foo.ts' extractPath('/home/user/project/src/lib/nested/bar.svelte', options) // => 'nested/bar.svelte'
const options = createSourceOptions('/home/user/project', { sourcePaths: ['src/lib', 'src/routes'], sourceRoot: 'src', }); extractPath('/home/user/project/src/lib/foo.ts', options) // => 'lib/foo.ts' extractPath('/home/user/project/src/routes/page.svelte', options) // => 'routes/page.svelte'

extractScriptContent
#

svelte.ts view source

extractScriptContent(svelteSource: string): string | undefined

Extract the content of the component's instance <script> from Svelte source: the top-level one that isn't a module script (<script module>, <script context="module">). A commented-out script doesn't count, and neither does one nested in the template (<svelte:head>, an element, a block), which is an ordinary element.

Locates the tags itself on every call (findScriptTags), parsing the template when the scan can't prove them top-level.

import {extractScriptContent} from 'svelte-docinfo/svelte.ts';

returns

the script tag content, or undefined if the source has no instance script

extractSignatureParameters
#

typescript-extract-shared.ts view source

extractSignatureParameters(sig: Signature, ctx: ExtractContext, tsdocParams: Record<string, string> | undefined): ParameterJson[]

Extract parameters from a TypeScript signature with TSDoc descriptions and default values.

Shared helper for extracting parameter information from both standalone functions and class methods/constructors.

import {extractSignatureParameters} from 'svelte-docinfo/typescript-extract-shared.ts';

parameters

sig

: Signature
#

the TypeScript signature to extract parameters from

the extraction pass's context (checker + alias registry)

tsdocParams

: Record<string, string> | undefined
#

record of parameter names to TSDoc descriptions (from TsdocParsedComment.params)

returns

array of ParameterJson objects

extractSnippetParameters
#

svelte.ts view source

extractSnippetParameters(snippetType: Type, checker: TypeChecker, aliasRegistry: AliasRegistry | undefined, writtenNode?: TypeNode): ParameterJsonInput[]

Extract structured parameters from a Snippet<[...]> type.

Snippet is an interface, so type arguments are on TypeReference (accessed via checker.getTypeArguments), not on aliasTypeArguments (which is only for type aliases).

Returns full ParameterJson input objects (with optional and rest always set) for runtime consistency with extractSignatureParameters in typescript-extract-shared.ts. Optional tuple elements are widened to include undefined — under exactOptionalPropertyTypes too, unlike properties — so the element type is stripped unconditionally via getTypeSignature and optional: true carries it alone. Rest elements report like rest signature parameters — rest: true with the printed array form (...rest: B[] carries B[]) — and a variadic spread (...T) carries the spread type itself, mirroring the structured typeInfo tuple (buildTuple). Callers pass the bare Snippet<...> TypeReference — a union wrapping it (optional widening, | null) reports no type arguments.

import {extractSnippetParameters} from 'svelte-docinfo/svelte.ts';

parameters

aliasRegistry

: AliasRegistry | undefined
#

the analyzed set's alias registry, or undefined when no pre-pass ran — feeds typeInfo name recovery like the prop-level tree

writtenNode

?: TypeNode
#

the written annotation the snippet type came from, when one exists — feeds typeInfo name recovery, the same node the caller hands the prop-level tree so the two projections can't disagree

returns

array of parameter info for the snippet's tuple type arguments, or [] for bare Snippet / Snippet<[]>

extractSvelteModuleComment
#

svelte.ts view source

extractSvelteModuleComment(scriptContent: string): TsdocParsedComment | undefined

Extract module-level comment from Svelte script content.

Parses the script content as TypeScript and delegates to extractModuleComment for the shared @module tag detection logic. Works on either script's content — instance <script> and <script module> (see extractScriptContent/extractModuleScriptContent).

import {extractSvelteModuleComment} from 'svelte-docinfo/svelte.ts';

parameters

scriptContent

: string
#

the content of a <script> or <script module> tag

returns

the parsed module comment, or undefined if none is found

extractTypeAliasProperties
#

typescript-extract-type-properties.ts view source

extractTypeAliasProperties(node: TypeAliasLike, nodeType: Type, declaration: DeclarationJsonBuild, ctx: ExtractContext): void

Extract properties from a type alias via the TypeScript checker API.

Handles object literals, intersections, mapped types (Partial, Pick, Readonly, etc.), type references, and function types. Extracts:

  • Named properties (with readonly/optional detection, TSDoc from declarations)
  • Index signatures (string/number)
  • Call signatures ((call))
  • Construct signatures ((construct))

A JSDoc typedef reads the same way: a @typedef {object} builds its properties from @property tags (each tag's description is the member's docComment, and a bracketed [x] or {T=} makes it optional), and a @callback is a function type, so it gets a (call) member whose parameters and return carry the callback's @param/@returns text.

import {extractTypeAliasProperties} from 'svelte-docinfo/typescript-extract-type-properties.ts';

mutates

  • declaration — adds members

extractTypeInfo
#

typescript-extract-type.ts view source

internal

Used by `analyzeDeclaration` — not part of the public barrel export.

extractTypeInfo(node: Node, declaration: DeclarationJsonBuild, ctx: ExtractContext): void

Extract type/interface information with rich property metadata.

import {extractTypeInfo} from 'svelte-docinfo/typescript-extract-type.ts';

parameters

node

: Node
#

the declaration AST node

#

the declaration to populate

the extraction pass's context

mutates

  • declaration — adds typeSignature, genericParams, extends, externalTypes, members (and partial: true on extraction failure)
  • ctx.diagnostics — adds type_extraction_failed / signature_analysis_failed diagnostics on checker errors

extractVariableInfo
#

typescript-extract-function.ts view source

internal

Used by `analyzeDeclaration` — not part of the public barrel export.

extractVariableInfo(node: Node, symbol: Symbol, declaration: DeclarationJsonBuild, ctx: ExtractContext): void

Extract variable information.

import {extractVariableInfo} from 'svelte-docinfo/typescript-extract-function.ts';

parameters

node

: Node
#

the declaration AST node

symbol

: Symbol
#

the TypeScript symbol

#

the declaration to populate

the extraction pass's context

mutates

  • declaration — adds typeSignature, reactivity (when initialized with a Svelte rune)

FileExists
#

typescript-extract-shared.ts view source

Whether a path exists for an analysis pass — owned in-memory content or disk.

import type {FileExists} from 'svelte-docinfo/typescript-extract-shared.ts';

members

(file: string): boolean

filterDocumentedProperties
#

typescript-extract-shared.ts view source

filterDocumentedProperties(type: Type, typeNode: Node, checker: TypeChecker, isExternalFile: IsExternalFile, admitNames?: ReadonlySet<string>): { properties: Symbol[]; admitted: Symbol[]; externalTypes: string[]; }

Reduce a type's properties to the ones consumers can see, and collect the external type references that contributed the dropped ones.

Two axes drop a property, both by declaration:

  • Origin (isExternalProperty) — the property comes from node_modules or a declaration file. Structure-agnostic: TypeScript preserves original declaration sources on derived properties, so the test gives the right answer through utility-type wrappers (Partial, Pick, OmitStrict) too. A property with no declarations (synthesized) is treated as local and kept.
  • Visibility (isPrivateProperty) — the property is private or a # field of a class this type projects. Only classes can declare either, so this is a no-op on every other shape; it exists because a class *type* reaches here whenever a structural container names one (`type X = LocalClass, type X = LocalGen<string>`), and what the class's own declaration hides an alias over it must hide too.

Applies to any composition shape — intersection, union, bare reference, indexed-access — not only intersections. The labels naming the dropped external contributors come from an AST walk (collectExternalTypeRefs) — the authoritative source for the &/|/index-access shape inference would otherwise erase — which descends through project-local names so a bag inherited via interface Props extends Bag is labeled like an inline Bag & {…} branch. Private properties are dropped silently: they are the project's own code, with nothing to attribute.

admitNames exempts named properties from the origin axis only: an external-origin property whose name is in the set lands in admitted instead of being dropped. Components pass the names their $props() destructuring binds, since naming a prop there shows the component handles it. Only named properties qualify: a name matching nothing but an index signature (data-${string}) has no property symbol to admit. Admission leaves externalTypes alone: the walk labels contributors by the written type, not by which of their properties survive, so a bag stays listed after some of its properties are admitted. It still contributes the rest, and it is where the admitted ones are declared.

import {filterDocumentedProperties} from 'svelte-docinfo/typescript-extract-shared.ts';

finalizeDiagnostics
#

analyze-core.ts view source

finalizeDiagnostics(diagnostics: Diagnostic[], options: { projectRoot: string; virtualFiles?: Iterable<SvelteVirtualFile> | undefined; }): void

Run the diagnostic boundary passes in their required order: virtual position remap first (remapVirtualDiagnosticPositions), then path normalization (normalizeDiagnosticPaths — it strips the virtual suffix the remap matches file against, so the reverse order silently keeps virtual positions). The one call for callers assembling modules themselves through analyzeModule / analyzeSvelteModule; using it makes the ordering unrepresentable instead of a contract to remember. Omit virtualFiles when no Svelte virtuals are in play.

Last, identical diagnostics collapse to the first: a symbol analyzed more than once (a renamed re-export's alias re-analyzes its canonical, a type alias over a class reads its members) re-reports the same warning at the same position.

import {finalizeDiagnostics} from 'svelte-docinfo/analyze-core.ts';

mutates

  • diagnostics — rewrites positions, file, and message, and removes duplicates

findCsspropTagLine
#

svelte-css.ts view source

findCsspropTagLine(svelteSource: string, start: number, end: number, name: string | undefined, occurrence?: number): number | undefined

The 1-based line, in the original source, of a @cssprop tag in a range of it (the doc comment the tags came from): the occurrenceth tag, from zero, that names name, or with name undefined, that names nothing (a malformed tag).

Tags are matched by text, line-leading only, so a mention later in a line (a // comment citing the tag, or a backticked one in prose) never takes the tag's place, and a tag written mid-line, which TS still reads, isn't found, leaving the caller's fallback line. A line-leading mention ahead of the tag can still take its place. A tag's text runs to the next line-leading tag, as the comment parser reads it (csspropTagText), so a name on the line after the tag and a default spanning lines parse as the tag does (parseCsspropTagText).

import {findCsspropTagLine} from 'svelte-docinfo/svelte-css.ts';

parameters

svelteSource

: string
#

the full Svelte source code

start

: number
#

offset where the comment starts

end

: number
#

offset where the comment ends

name

: string | undefined
#

the documented property's name, or undefined for a malformed tag

occurrence

?: number = 0
#

which matching tag, from zero (the second tag naming name is 1)

returns

the line, or undefined when the range holds no such tag

findDuplicates
#

postprocess.ts view source

findDuplicates(modules: ModuleJson[]): Map<string, DuplicateDeclaration[]>

Find duplicate declaration names across modules.

A duplicate is two *different things* sharing a name in the flat namespace. Occurrences are compared by canonical identity — aliasOf chains are resolved first, so an alias and its canonical (or two aliases of the same canonical) are one thing, not a collision. Documenting a same-name re-export (which synthesizes an alias) or re-exporting a component under its own name (export {default as Foo} from './Foo.svelte') therefore doesn't flag. When a name does flag, all occurrences are reported, aliases included.

The analysis entry points run this only under the opt-in onDuplicates.

import {findDuplicates} from 'svelte-docinfo/postprocess.ts';

returns

Map of declaration names to their DuplicateDeclaration occurrences (only includes duplicates)

examples

const duplicates = findDuplicates(modules); duplicates.get('parse'); // [{declaration, module: 'a.ts'}, {declaration, module: 'b.ts'}]

findHtmlComments
#

svelte-scripts.ts view source

findHtmlComments(svelteSource: string): HtmlComment[]

Collect the HTML comments (<!-- ... -->) in Svelte source, in source order, skipping script and style text, as Svelte's parser and svelte2tsx do: a <!-- in a script's string literal isn't a comment.

import {findHtmlComments} from 'svelte-docinfo/svelte-scripts.ts';

findScriptTags
#

svelte-scripts.ts view source

findScriptTags(svelteSource: string, options?: FindScriptTagsOptions): FoundScriptTags

Find a component's script tags: the <script> tags at the top level of the source, in source order. A <script> nested in an element, a block, or <svelte:head> isn't one, matching Svelte, which reads only a top-level tag as the instance or module script.

scanScriptTags finds the candidates. When it proves every one of them top-level, which covers the usual component with its scripts ahead of the template, that's the answer. Otherwise Svelte's parser decides: the source is parsed with script and style content blanked, and the tags at the offsets of the root's instance and module are kept. svelte2tsx parses the same blanked source, but demotes only the tags the parser reads as nested elements, so a tag spelled inside an expression string or an attribute value is still a script to it and isn't one here.

Limits: a </script> or </style> inside a string or comment ends that tag's blanked content early, and what's left over is parsed as template. And svelte2tsx's own tag matcher is narrower in one spelling: it doesn't take a closing tag with whitespace before the > (</script >), so there its virtual doesn't have the scripts as written while this returns them. A legacy component written that way documents no props, with a svelte_prop_failed warning for each export let; a runes one documents none, with no warning.

import {findScriptTags} from 'svelte-docinfo/svelte-scripts.ts';

parameters

svelteSource

: string
#

the full Svelte source code

returns

the top-level script tags and how they were decided

FindScriptTagsOptions
#

svelte-scripts.ts view source

Options for findScriptTags.

import type {FindScriptTagsOptions} from 'svelte-docinfo/svelte-scripts.ts';

members

scanProof

?: boolean = true
#

Take the scan's proof when it covers every tag, without parsing. false sends every source with a tag to the parser.

parseTemplate

?: ParseSvelteTemplate
#

The parser asked about tags the scan can't prove. Defaults to Svelte's.

firstJSDocOverloadSignature
#

tsdoc.ts view source

firstJSDocOverloadSignature(node: Node): JSDocSignature | undefined

The first of jsdocOverloadSignatures, the declaration's first public signature, or undefined when it has no @overload tags.

import {firstJSDocOverloadSignature} from 'svelte-docinfo/tsdoc.ts';

formatDiagnostic
#

diagnostics.ts view source

also exported from index.ts

formatDiagnostic(diagnostic: Diagnostic): string

Format a diagnostic for display.

Assumes diagnostic.file is project-root-relative (the contract enforced by analyze / analyzeFromFiles). The displayed path is prefixed with ./.

import {formatDiagnostic} from 'svelte-docinfo/diagnostics.ts';

parameters

diagnostic

: Diagnostic
#

the diagnostic to format

returns

formatted string like './file.ts:10:5: error: message'

examples

for (const d of errorsOf(diagnostics)) { console.error(formatDiagnostic(d)); }

FoundScriptTags
#

FunctionDeclarationJson
#

types.ts view source

value + type

also exported from index.ts

A function declaration. Has parameters, returnType, returnDescription, overloads.

import {FunctionDeclarationJson} from 'svelte-docinfo/types.ts';

inheritance

extends: SchemaStrictObjectOutput<typeof FunctionDeclarationJsonEntries>

members

kind

: "function"
#

parameters

: ParameterJson[]
#

Function/method/constructor parameters, in signature order.

overloads

: OverloadJson[]
#

Overload signatures (when there are multiple public overloads). Includes all public overloads. The implementation signature is excluded. Empty when there are no overloads (single signature).

alsoExportedFrom

: string[]
#

Module paths (relative to sourceRoot) that re-export this declaration under the same name. The canonical declaration lives in this module's declarations array; these paths are additional import locations for the same thing.

The same edges appear from the re-exporting side as ModuleJson.reExports — use that when asking "what does this module re-export" instead of inverting these arrays. The two can disagree at the margins: a reExports entry whose canonical declaration is @nodocs (or whose module isn't in the analyzed set) has no back-link here.

Consumer note: To build a complete re-export map, scan two fields:

  1. alsoExportedFrom on each declaration — same-name re-exports
  2. aliasOf on declarations — renamed re-exports (separate declarations)

partial

: boolean
#

Whether extraction failed partway through, leaving some fields missing (e.g., typeSignature, parameters).

examples

: string[]
#

Code examples from @example tags.

seeAlso

: string[]
#

Related items from @see tags, in raw TSDoc format.

throws

: ThrowsJson[]
#

Exceptions from @throws tags. type is the tag's written type, and typeInfo its structured form, present for a braced type (@throws {A<B>}) that isn't the whole story as text (see TypeJson); an unbraced tag's leading word never has one, nor does a tag in a component's HTML @component comment, which is read as text.

name

: string
#

The exported name. Always populated. The default-export slot is named 'default', except a Svelte component, which takes its filename-derived name ('X' for X.svelte) — 'default' is the symbol's actual name in JS (import {default as X} and ns.default both expose it directly), and import X from 'mod' is sugar for import {default as X}. Consumers branch on name === 'default' to render the sugar form when desired.

modifiers

: ("public" | "protected" | "readonly" | "static" | "abstract" | "getter" | "setter")[]
#

TypeScript modifiers like readonly, static, or protected.

genericParams

: GenericParamJson[]
#

Generic type parameters like <T, U>.

returnDescription

?: string
#

Return value description from @returns tag.

returnPredicate

?: ReturnPredicateJson
#

The signature's type predicate or assertion, when it declares one; returnType stays the checker's boolean or void.

thisType

?: string
#

The type of a declared this parameter (function f(this: A), or a JS @this {A} tag), which parameters leaves out, since a caller doesn't pass it as an argument.

thisTypeInfo

?: TypeJson
#

Structured thisType; absent when thisType is the whole story (see TypeJson).

returnType

?: string
#

Function/method return type.

returnTypeInfo

?: TypeJson
#

Structured return type; absent when returnType is the whole story (see TypeJson).

aliasOf

?: { module: string; name: string; }
#

For renamed re-exports (export {foo as bar}), points to the original declaration. This declaration's name is the alias; aliasOf.name is the original name.

For renames out of the default slot (export {default as bar} from './x' where ./x is export default ...), aliasOf.name is 'default' — the canonical's actual symbol name. Consumers locate the canonical by (aliasOf.module, aliasOf.name).

Svelte component exception: when the source is a .svelte file (e.g., export {default as Foo} from './X.svelte'), the canonical's name is the component name (derived from the filename), so aliasOf.name is the component name ('X'), NOT 'default'. Consumers that branch on aliasOf.name === 'default' to detect default-rename should additionally check whether aliasOf.module ends with .svelte.

Different from alsoExportedFrom: aliases create new API surface names, while alsoExportedFrom tracks additional import paths for the same name.

A type-only rename of a value (export type {someConst as c} from './x') synthesizes a normal alias — declarations carry no type-only marker.

deprecatedMessage

?: string
#

Deprecation message from @deprecated tag.

since

?: string
#

Version introduced, from @since tag.

internalMessage

?: string
#

Internal-API marker from the @internal tag. Presence means the tag was written; an empty string is a bare tag with no trailing prose.

A marker, not an exclusion: @internal means "not stable public API" (TSDoc semantics) while the declaration, member, or prop stays documented — unlike @nodocs, which removes a declaration from output entirely (and is ignored on props and members).

mutates

?: Record<string, string>
#

Mutation documentation from @mutates tags (non-standard), mapping keys to descriptions.

Keys are intentionally unvalidated — typically a parameter name, but authors may also use compound paths (this.foo, obj.field) or multi-word external state references. Backticks are stripped from keys so `` a `` and a normalize to one key; an empty-string value is a bare tag with no description. The schema accepts any string key so consumers can render whatever the author wrote.

On a component prop it declares the component's mutation contract for the value it's handed: the component writes into the prop's object or array in place (@mutates items - appends the selected entry, @mutates options.cache - fills on first render). Reassigning a prop is not a mutation in this sense (bindable covers it), though a $bindable prop can carry both.

docComment

?: string
#

JSDoc/TSDoc comment.

typeSignature

?: string
#

Full TypeScript type signature.

sourceLine

?: number
#

1-based line in the source file, a positive integer. Synthesized aliases (see aliasOf) carry the local export specifier's line, not the canonical's.

FunctionDeclarationJsonInput
#

types.ts view source

The input FunctionDeclarationJson parses, with any field it defaults optional.

import type {FunctionDeclarationJsonInput} from 'svelte-docinfo/types.ts';

inheritance

extends: SchemaStrictObjectInput<typeof FunctionDeclarationJsonEntries>

members

kind

: "function"
#

name

: string
#

The exported name. Always populated. The default-export slot is named 'default', except a Svelte component, which takes its filename-derived name ('X' for X.svelte) — 'default' is the symbol's actual name in JS (import {default as X} and ns.default both expose it directly), and import X from 'mod' is sugar for import {default as X}. Consumers branch on name === 'default' to render the sugar form when desired.

returnDescription

?: string
#

Return value description from @returns tag.

returnPredicate

?: ReturnPredicateJsonInput
#

The signature's type predicate or assertion, when it declares one; returnType stays the checker's boolean or void.

thisType

?: string
#

The type of a declared this parameter (function f(this: A), or a JS @this {A} tag), which parameters leaves out, since a caller doesn't pass it as an argument.

thisTypeInfo

?: TypeJson
#

Structured thisType; absent when thisType is the whole story (see TypeJson).

returnType

?: string
#

Function/method return type.

returnTypeInfo

?: TypeJson
#

Structured return type; absent when returnType is the whole story (see TypeJson).

parameters

?: ParameterJsonInput[]
#

Function/method/constructor parameters, in signature order.

overloads

?: OverloadJsonInput[]
#

Overload signatures (when there are multiple public overloads). Includes all public overloads. The implementation signature is excluded. Empty when there are no overloads (single signature).

alsoExportedFrom

?: string[]
#

Module paths (relative to sourceRoot) that re-export this declaration under the same name. The canonical declaration lives in this module's declarations array; these paths are additional import locations for the same thing.

The same edges appear from the re-exporting side as ModuleJson.reExports — use that when asking "what does this module re-export" instead of inverting these arrays. The two can disagree at the margins: a reExports entry whose canonical declaration is @nodocs (or whose module isn't in the analyzed set) has no back-link here.

Consumer note: To build a complete re-export map, scan two fields:

  1. alsoExportedFrom on each declaration — same-name re-exports
  2. aliasOf on declarations — renamed re-exports (separate declarations)

aliasOf

?: { module: string; name: string; }
#

For renamed re-exports (export {foo as bar}), points to the original declaration. This declaration's name is the alias; aliasOf.name is the original name.

For renames out of the default slot (export {default as bar} from './x' where ./x is export default ...), aliasOf.name is 'default' — the canonical's actual symbol name. Consumers locate the canonical by (aliasOf.module, aliasOf.name).

Svelte component exception: when the source is a .svelte file (e.g., export {default as Foo} from './X.svelte'), the canonical's name is the component name (derived from the filename), so aliasOf.name is the component name ('X'), NOT 'default'. Consumers that branch on aliasOf.name === 'default' to detect default-rename should additionally check whether aliasOf.module ends with .svelte.

Different from alsoExportedFrom: aliases create new API surface names, while alsoExportedFrom tracks additional import paths for the same name.

A type-only rename of a value (export type {someConst as c} from './x') synthesizes a normal alias — declarations carry no type-only marker.

partial

?: boolean
#

Whether extraction failed partway through, leaving some fields missing (e.g., typeSignature, parameters).

examples

?: string[]
#

Code examples from @example tags.

deprecatedMessage

?: string
#

Deprecation message from @deprecated tag.

seeAlso

?: string[]
#

Related items from @see tags, in raw TSDoc format.

throws

?: ThrowsJsonInput[]
#

Exceptions from @throws tags. type is the tag's written type, and typeInfo its structured form, present for a braced type (@throws {A<B>}) that isn't the whole story as text (see TypeJson); an unbraced tag's leading word never has one, nor does a tag in a component's HTML @component comment, which is read as text.

since

?: string
#

Version introduced, from @since tag.

internalMessage

?: string
#

Internal-API marker from the @internal tag. Presence means the tag was written; an empty string is a bare tag with no trailing prose.

A marker, not an exclusion: @internal means "not stable public API" (TSDoc semantics) while the declaration, member, or prop stays documented — unlike @nodocs, which removes a declaration from output entirely (and is ignored on props and members).

mutates

?: Record<string, string>
#

Mutation documentation from @mutates tags (non-standard), mapping keys to descriptions.

Keys are intentionally unvalidated — typically a parameter name, but authors may also use compound paths (this.foo, obj.field) or multi-word external state references. Backticks are stripped from keys so `` a `` and a normalize to one key; an empty-string value is a bare tag with no description. The schema accepts any string key so consumers can render whatever the author wrote.

On a component prop it declares the component's mutation contract for the value it's handed: the component writes into the prop's object or array in place (@mutates items - appends the selected entry, @mutates options.cache - fills on first render). Reassigning a prop is not a mutation in this sense (bindable covers it), though a $bindable prop can carry both.

docComment

?: string
#

JSDoc/TSDoc comment.

typeSignature

?: string
#

Full TypeScript type signature.

modifiers

?: ("public" | "protected" | "readonly" | "static" | "abstract" | "getter" | "setter")[]
#

TypeScript modifiers like readonly, static, or protected.

sourceLine

?: number
#

1-based line in the source file, a positive integer. Synthesized aliases (see aliasOf) carry the local export specifier's line, not the canonical's.

genericParams

?: GenericParamJsonInput[]
#

Generic type parameters like <T, U>.

functionInitializer
#

tsdoc.ts view source

functionInitializer(node: Node): ArrowFunction | FunctionExpression | undefined

A variable's arrow-function or function-expression initializer, which carries the variable's function signature (and, in JS, its statement's JSDoc), or undefined for any other node.

import {functionInitializer} from 'svelte-docinfo/tsdoc.ts';

FunctionMemberJson
#

types.ts view source

value + type

also exported from index.ts

A function member (method, call signature, method signature). Has parameters, returnType, returnDescription, overloads.

optional reflects a ? token on the declaration (e.g., foo?(): void on an interface or type literal, or m?(): void {} on a class). Always false for index/call/construct signatures.

name is the user-chosen method/property identifier, except for call signatures on interfaces and type aliases where it is the literal sentinel '(call)'.

import {FunctionMemberJson} from 'svelte-docinfo/types.ts';

inheritance

extends: SchemaStrictObjectOutput<typeof FunctionMemberJsonEntries>

members

kind

: "function"
#

name

: string
#

User-chosen identifier, or the literal '(call)' sentinel for unnamed call signatures.

optional

: boolean
#

Whether the member has a ? token in its declaration.

property

: boolean
#

Whether the member is a function-typed property (now: () => number) and not a method (now(): number), on an interface or a type alias. The two classify alike, as callables, so a renderer reads this to write the property form, the only one that takes readonly or a default. Set unless one of the property's declarations uses method syntax, so a property with no declaration (a mapped type's) is one too. Never set on a class member: a class's methods are methods, and a field holding a function is a variable.

parameters

: ParameterJson[]
#

Function/method/constructor parameters, in signature order.

overloads

: OverloadJson[]
#

Overload signatures (when there are multiple public overloads). Includes all public overloads. The implementation signature is excluded. Empty when there are no overloads (single signature).

partial

: boolean
#

Whether extraction failed partway through, leaving some fields missing (e.g., typeSignature, parameters).

examples

: string[]
#

Code examples from @example tags.

seeAlso

: string[]
#

Related items from @see tags, in raw TSDoc format.

throws

: ThrowsJson[]
#

Exceptions from @throws tags. type is the tag's written type, and typeInfo its structured form, present for a braced type (@throws {A<B>}) that isn't the whole story as text (see TypeJson); an unbraced tag's leading word never has one, nor does a tag in a component's HTML @component comment, which is read as text.

modifiers

: ("public" | "protected" | "readonly" | "static" | "abstract" | "getter" | "setter")[]
#

TypeScript modifiers like readonly, static, or protected.

genericParams

: GenericParamJson[]
#

Generic type parameters like <T, U>.

typeInfo

?: TypeJson
#

The named function type a callable property is written with (handler: Handler reads {kind: 'reference', name: 'Handler'}), whose signature parameters and returnType expand; absent for a method, an inline function type, and any other written type. A renderer can head the member handler: Handler and keep the signature as detail.

defaultValue

?: string
#

Default value documented via @default — for a callable member, typically the behavior used when the callback is omitted. Always tag-authored (structural containers have no initializers), verbatim with no normalization. Members only: top-level function declarations and overloads never carry one.

returnDescription

?: string
#

Return value description from @returns tag.

returnPredicate

?: ReturnPredicateJson
#

The signature's type predicate or assertion, when it declares one; returnType stays the checker's boolean or void.

thisType

?: string
#

The type of a declared this parameter (function f(this: A), or a JS @this {A} tag), which parameters leaves out, since a caller doesn't pass it as an argument.

thisTypeInfo

?: TypeJson
#

Structured thisType; absent when thisType is the whole story (see TypeJson).

returnType

?: string
#

Function/method return type.

returnTypeInfo

?: TypeJson
#

Structured return type; absent when returnType is the whole story (see TypeJson).

deprecatedMessage

?: string
#

Deprecation message from @deprecated tag.

since

?: string
#

Version introduced, from @since tag.

internalMessage

?: string
#

Internal-API marker from the @internal tag. Presence means the tag was written; an empty string is a bare tag with no trailing prose.

A marker, not an exclusion: @internal means "not stable public API" (TSDoc semantics) while the declaration, member, or prop stays documented — unlike @nodocs, which removes a declaration from output entirely (and is ignored on props and members).

mutates

?: Record<string, string>
#

Mutation documentation from @mutates tags (non-standard), mapping keys to descriptions.

Keys are intentionally unvalidated — typically a parameter name, but authors may also use compound paths (this.foo, obj.field) or multi-word external state references. Backticks are stripped from keys so `` a `` and a normalize to one key; an empty-string value is a bare tag with no description. The schema accepts any string key so consumers can render whatever the author wrote.

On a component prop it declares the component's mutation contract for the value it's handed: the component writes into the prop's object or array in place (@mutates items - appends the selected entry, @mutates options.cache - fills on first render). Reassigning a prop is not a mutation in this sense (bindable covers it), though a $bindable prop can carry both.

docComment

?: string
#

JSDoc/TSDoc comment.

typeSignature

?: string
#

Full TypeScript type signature.

sourceLine

?: number
#

1-based line in the source file, a positive integer. Synthesized aliases (see aliasOf) carry the local export specifier's line, not the canonical's.

FunctionMemberJsonInput
#

types.ts view source

The input FunctionMemberJson parses, with any field it defaults optional.

import type {FunctionMemberJsonInput} from 'svelte-docinfo/types.ts';

inheritance

extends: SchemaStrictObjectInput<typeof FunctionMemberJsonEntries>

members

kind

: "function"
#

name

: string
#

User-chosen identifier, or the literal '(call)' sentinel for unnamed call signatures.

optional

?: boolean
#

Whether the member has a ? token in its declaration.

property

?: boolean
#

Whether the member is a function-typed property (now: () => number) and not a method (now(): number), on an interface or a type alias. The two classify alike, as callables, so a renderer reads this to write the property form, the only one that takes readonly or a default. Set unless one of the property's declarations uses method syntax, so a property with no declaration (a mapped type's) is one too. Never set on a class member: a class's methods are methods, and a field holding a function is a variable.

typeInfo

?: TypeJson
#

The named function type a callable property is written with (handler: Handler reads {kind: 'reference', name: 'Handler'}), whose signature parameters and returnType expand; absent for a method, an inline function type, and any other written type. A renderer can head the member handler: Handler and keep the signature as detail.

defaultValue

?: string
#

Default value documented via @default — for a callable member, typically the behavior used when the callback is omitted. Always tag-authored (structural containers have no initializers), verbatim with no normalization. Members only: top-level function declarations and overloads never carry one.

returnDescription

?: string
#

Return value description from @returns tag.

returnPredicate

?: ReturnPredicateJsonInput
#

The signature's type predicate or assertion, when it declares one; returnType stays the checker's boolean or void.

thisType

?: string
#

The type of a declared this parameter (function f(this: A), or a JS @this {A} tag), which parameters leaves out, since a caller doesn't pass it as an argument.

thisTypeInfo

?: TypeJson
#

Structured thisType; absent when thisType is the whole story (see TypeJson).

returnType

?: string
#

Function/method return type.

returnTypeInfo

?: TypeJson
#

Structured return type; absent when returnType is the whole story (see TypeJson).

parameters

?: ParameterJsonInput[]
#

Function/method/constructor parameters, in signature order.

overloads

?: OverloadJsonInput[]
#

Overload signatures (when there are multiple public overloads). Includes all public overloads. The implementation signature is excluded. Empty when there are no overloads (single signature).

partial

?: boolean
#

Whether extraction failed partway through, leaving some fields missing (e.g., typeSignature, parameters).

examples

?: string[]
#

Code examples from @example tags.

deprecatedMessage

?: string
#

Deprecation message from @deprecated tag.

seeAlso

?: string[]
#

Related items from @see tags, in raw TSDoc format.

throws

?: ThrowsJsonInput[]
#

Exceptions from @throws tags. type is the tag's written type, and typeInfo its structured form, present for a braced type (@throws {A<B>}) that isn't the whole story as text (see TypeJson); an unbraced tag's leading word never has one, nor does a tag in a component's HTML @component comment, which is read as text.

since

?: string
#

Version introduced, from @since tag.

internalMessage

?: string
#

Internal-API marker from the @internal tag. Presence means the tag was written; an empty string is a bare tag with no trailing prose.

A marker, not an exclusion: @internal means "not stable public API" (TSDoc semantics) while the declaration, member, or prop stays documented — unlike @nodocs, which removes a declaration from output entirely (and is ignored on props and members).

mutates

?: Record<string, string>
#

Mutation documentation from @mutates tags (non-standard), mapping keys to descriptions.

Keys are intentionally unvalidated — typically a parameter name, but authors may also use compound paths (this.foo, obj.field) or multi-word external state references. Backticks are stripped from keys so `` a `` and a normalize to one key; an empty-string value is a bare tag with no description. The schema accepts any string key so consumers can render whatever the author wrote.

On a component prop it declares the component's mutation contract for the value it's handed: the component writes into the prop's object or array in place (@mutates items - appends the selected entry, @mutates options.cache - fills on first render). Reassigning a prop is not a mutation in this sense (bindable covers it), though a $bindable prop can carry both.

docComment

?: string
#

JSDoc/TSDoc comment.

typeSignature

?: string
#

Full TypeScript type signature.

modifiers

?: ("public" | "protected" | "readonly" | "static" | "abstract" | "getter" | "setter")[]
#

TypeScript modifiers like readonly, static, or protected.

sourceLine

?: number
#

1-based line in the source file, a positive integer. Synthesized aliases (see aliasOf) carry the local export specifier's line, not the canonical's.

genericParams

?: GenericParamJsonInput[]
#

Generic type parameters like <T, U>.

generateImport
#

declaration-helpers.ts view source

also exported from index.ts

generateImport(declaration: DeclarationJson, modulePath: string, libraryName: string, options?: GenerateImportOptions): string

Generate TypeScript import statement for a declaration.

Produces import type for type/interface declarations, import for values — including type/interface declarations marked mergedValue (a merged value+type symbol like a schema/type pair is importable as a runtime value, so a type-only import would break value use).

Default export handling: when declaration.name === 'default', emits import X from '...' with the binding derived by PascalCasing the module path. ('default' is the symbol's actual name in JS — import X from 'mod' is sugar for import {default as X} from 'mod'.)

import {generateImport} from 'svelte-docinfo/declaration-helpers.ts';

parameters

declaration

: DeclarationJson
#

the DeclarationJson to generate an import for

modulePath

: string
#

module path relative to source root (e.g., foo.ts); the specifier names the file it ships as (.ts, .tsx, .jsx → .js, .mts → .mjs)

libraryName

: string
#

package name for the import specifier (e.g., @pkg/lib)

specifier: 'source' names the source file instead (foo.ts), for a package whose exports map its source extensions ("./*.ts"), as packages following the "imports name the real file" convention do

returns

formatted import statement string

examples

generateImport({name: 'Foo', kind: 'type'}, 'foo.ts', '@pkg/lib') // => "import type {Foo} from '@pkg/lib/foo.js';" generateImport({name: 'default', kind: 'function'}, 'foo-bar.ts', '@pkg/lib') // => "import FooBar from '@pkg/lib/foo-bar.js';" generateImport({name: 'Foo', kind: 'type'}, 'foo.ts', '@pkg/lib', {specifier: 'source'}) // => "import type {Foo} from '@pkg/lib/foo.ts';"

see also

  • getDisplayName for the divergent default-slot fallback used as a display label (the literal 'default', since a label has no use for a synthesized JS binding).

GenerateImportOptions
#

declaration-helpers.ts view source

also exported from index.ts

Options for generateImport.

import type {GenerateImportOptions} from 'svelte-docinfo/declaration-helpers.ts';

members

specifier

?: "dist" | "source"
#

Which file the specifier names: 'dist' (the default) the file a module ships as (foo.ts → foo.js), 'source' the module's own path (foo.ts), for a package whose exports map source extensions.

GenericParamJson
#

types.ts view source

value + type

also exported from index.ts

Generic type parameter metadata extracted from declarations like <T extends string = unknown>.

Present on functions, classes, interfaces, type aliases, and Svelte components that declare generic type parameters.

import {GenericParamJson} from 'svelte-docinfo/types.ts';

inheritance

extends: SchemaStrictObjectOutput<typeof GenericParamJsonEntries>

members

name

: string
#

Parameter name like T.

modifiers

: ("const" | "in" | "out")[]
#

Modifier keywords written on the parameter, in the order TypeScript prints them (const, in, out).

constraint

?: string
#

Constraint like string from T extends string, as source text.

constraintInfo

?: TypeJson
#

Structured constraint; absent when constraint is the whole story (see TypeJson). It follows the written type: a reference keeps its written type arguments and alias names, a computed type (keyof A, typeof a, A['b']) is a terminal node over its text (no tree at the root), and the rest is the checker's reading, so it can spell a type differently from the text beside it (Array<A> reads as an array node).

defaultType

?: string
#

Default type like unknown from T = unknown, as source text.

defaultTypeInfo

?: TypeJson
#

Structured default type; absent when defaultType is the whole story (see TypeJson). It follows the written type, like constraintInfo.

GenericParamJsonInput
#

types.ts view source

The input GenericParamJson parses, with any field it defaults optional.

import type {GenericParamJsonInput} from 'svelte-docinfo/types.ts';

inheritance

extends: SchemaStrictObjectInput<typeof GenericParamJsonEntries>

members

name

: string
#

Parameter name like T.

modifiers

?: ("const" | "in" | "out")[]
#

Modifier keywords written on the parameter, in the order TypeScript prints them (const, in, out).

constraint

?: string
#

Constraint like string from T extends string, as source text.

constraintInfo

?: TypeJson
#

Structured constraint; absent when constraint is the whole story (see TypeJson). It follows the written type: a reference keeps its written type arguments and alias names, a computed type (keyof A, typeof a, A['b']) is a terminal node over its text (no tree at the root), and the rest is the checker's reading, so it can spell a type differently from the text beside it (Array<A> reads as an array node).

defaultType

?: string
#

Default type like unknown from T = unknown, as source text.

defaultTypeInfo

?: TypeJson
#

Structured default type; absent when defaultType is the whole story (see TypeJson). It follows the written type, like constraintInfo.

GenericParamModifier
#

types.ts view source

value + type

also exported from index.ts

"const" | "in" | "out"

type "const" | "in" | "out"

A modifier keyword written on a type parameter: const (<const T>), or the variance annotations in and out (interface A<in out T>).

import {GenericParamModifier} from 'svelte-docinfo/types.ts';

getComponentName
#

source.ts view source

getComponentName(modulePath: string): string

Extract component name from a Svelte module path.

import {getComponentName} from 'svelte-docinfo/source.ts';

examples

getComponentName('Alert.svelte') // => 'Alert' getComponentName('components/Button.svelte') // => 'Button'

getDefaultAnalyzer
#

source.ts view source

also exported from index.ts

getDefaultAnalyzer(path: string): AnalyzerType | null

Default analyzer resolver based on file extension.

  • .svelte → 'svelte'
  • .ts, .mts, .tsx (not .d.ts/.d.mts), .js, .mjs, .jsx → 'typescript'
  • .css → 'css'
  • .json → 'json'
  • Other extensions → null (skip)
import {getDefaultAnalyzer} from 'svelte-docinfo/source.ts';

getDisplayName
#

declaration-helpers.ts view source

also exported from index.ts

getDisplayName(declaration: DeclarationJson | MemberJson): string

Format declaration or member name with generic parameters for display.

Default-slot entries return the literal 'default' (the symbol's actual name in JS). Renderers that want a richer label (PascalCased module path, an explicit "default export" header) should branch on name === 'default' themselves before calling this.

import {getDisplayName} from 'svelte-docinfo/declaration-helpers.ts';

parameters

#

the DeclarationJson or MemberJson to format

returns

name with generic parameters appended (e.g., Map<K, V>)

examples

getDisplayName({name: 'Map', kind: 'type', genericParams: [{name: 'K', modifiers: []}, {name: 'V', modifiers: []}]}) // => 'Map<K, V>'

see also

  • generateImport for the divergent default-slot fallback used in import-statement generation (PascalCased module path, since an import needs a JS identifier binding, not a label).

getLocalExportStatement
#

typescript-extract-shared.ts view source

internal

Shared by the export walk (`analyzeExports`) and the alias-registry pre-pass (`buildAliasRegistry`).

getLocalExportStatement(exportSymbol: Symbol, sourceFile: SourceFile): { node: ExportSpecifier | NamespaceExport; statement: ExportDeclaration; } | { node: ExportAssignment; statement: ExportAssignment; } | undefined

The local export statement and binding node for an alias export symbol — {node, statement} where node is the ExportSpecifier (or, for export * as ns, the NamespaceExport) and statement its ExportDeclaration, or both are the ExportAssignment of an export default x.

Returns undefined when the statement isn't in sourceFile: merged symbols can put a foreign declaration first, and parsing JSDoc or positions there would attribute another module's content here.

import {getLocalExportStatement} from 'svelte-docinfo/typescript-extract-shared.ts';

getNodeLocation
#

typescript-extract-shared.ts view source

getNodeLocation(node: Node): { file: string; line: number; column: number; }

Extract line and column from a TypeScript node. Returns 1-based line and column numbers.

import {getNodeLocation} from 'svelte-docinfo/typescript-extract-shared.ts';

getNonOptionalType
#

typescript-extract-shared.ts view source

getNonOptionalType(type: Type, checker: TypeChecker, optional: boolean): Type

The type of an optional declaration with the widening undefined member removed — the counterpart to getTypeSignature's optional strip for structural queries, taking the position's optionality the same way (false is identity).

A union with undefined reports no call signatures of its own, so under strictNullChecks an optional method (fn?(a: string): number) or function-typed property resolves to ((a: string) => number) | undefined and reads as non-callable, silently costing it typeSignature, parameters, and returnType. Analogous to getNonNullableType, but leaves null in place: fn?: (() => void) | null really isn't callable, and reporting it as a function would hide the null.

A null-free union goes through getNonNullableType, which rebuilds the union rather than picking a member — so a union of callables (fn?: (() => void) | (() => number)) keeps its combined call signature. A null-bearing union is returned unchanged: null poisons callability regardless, so there's nothing to recover by stripping undefined from it.

The selection itself is optionalWideningTarget's — the same owner getTypeSignature and the TypeJson builder select through, so the structural queries can't drift from the printed and structured outputs.

Every callability query routes through this with the member's own optionality, in both widening modes — the property site (populatePropertyMember) and the method sites (interface and class) alike. At an optional position an undefined member — widened or written — is the same runtime observation as absence, already carried by optional: true, so under exactOptionalPropertyTypes a written fn?: (() => void) | undefined classifies callable like fn?: () => void (that spelling is often forced there — assigning a possibly-undefined handler to the property requires it). Two cases stay non-callable and land as kind: 'variable' with the union kept: | null (a real value, per the paragraph above) and a *required* property's written undefined (nothing else carries it; false here is identity). The printed and structured outputs still gate their strips on optionalWidened, where a written undefined is content; on method sites the gate is moot, since method syntax can't write | undefined.

import {getNonOptionalType} from 'svelte-docinfo/typescript-extract-shared.ts';

getSourceRoot
#

source-config.ts view source

getSourceRoot(options: ModuleSourceOptions): string

Get the effective sourceRoot from options.

Returns sourceRoot if provided, otherwise:

  • Single sourcePath: returns that path
  • Multiple sourcePaths: derives the longest common directory prefix
import {getSourceRoot} from 'svelte-docinfo/source-config.ts';

returns

the effective source root path

getSvelteShimRoots
#

typescript-program.ts view source

internal

Shared by both program paths and the test-side program helpers; not a stable API.

getSvelteShimRoots(paths: Iterable<string>): readonly string[]

The program roots svelte2tsx's shims add to a program over paths: the shim files when any path is a Svelte virtual, otherwise none, so TS-only programs keep exactly their tsconfig roots and globals.

Callers put these first in the root list, ahead of the tsconfig roots.

  • Resolution — the svelte2tsx main entry, resolved from svelte-docinfo's own location (the lookup svelte.ts's svelte2tsx import makes), whose directory is the package root holding the shims. So the shims always match the copy that generated the virtuals; the helper signatures change in lockstep with the emitted calls. Resolved once and cached, as POSIX paths.
  • A project that also roots the shims (a tsconfig include, or a triple-slash reference) — the same file dedupes by path. A different copy (another installed svelte2tsx) declares the same globals twice, and no single copy wins: a duplicate type alias keeps its first declaration (ours, rooted first), while duplicate functions merge into one overload set whose resolution order doesn't follow root order. The duplicate-identifier errors land in files analysis never reads, but where the two copies disagree a component's type can mix them. svelte2tsx renames a helper (the __sveltets_2_ prefix) when its shape changes incompatibly, which keeps that rare; it's not detected.
  • Shim globals are project-visible — beside the __sveltets_ helpers, the shims declare unprefixed global types (Expand, KeysMatching, SvelteStore, and others). A project global of the same name collides, and the shim's declaration wins, being rooted first, so a .ts module typed through that global documents the shim's meaning.
  • Never documented — the files resolve under node_modules, so they're external (createIsExternalFile), never isSource, and outside the alias registry. As global scripts they never print as typeof import("…"), so normalizeModulePathsInTypes never sees them.
  • Order — a fixed list, so the language service's root-list comparison still reuses the program when nothing changed. Resolving the helpers can move when the checker first creates a type, which reorders an origin-less union printed elsewhere (see "Input order" on AnalysisSession).
import {getSvelteShimRoots} from 'svelte-docinfo/typescript-program.ts';

getTypeSignature
#

typescript-extract-shared.ts view source

getTypeSignature(type: Type, checker: TypeChecker, optional: boolean): string

Type signature of a declaration — for an optional one, with the implicit | undefined widening removed. The single chokepoint pairing optional with the strip, so a call site can't apply one without the other. The target selection itself lives in optionalWideningTarget (in typescript-extract-type-json.ts), shared with the TypeJson builder so the flat string and the tree can't drift.

The checker widens every optional property and parameter to include undefined, which is redundant with optional: true in the output. Removing it with checker.getNonNullableType drops null too, so x?: string | null printed as "string" and x?: null as "never" — both silently wrong. Filtering undefined out of type.types and rejoining the members is no better: it loses the alias name, the printer's member order, and the parens that keep function members legal.

So null-bearing unions are trimmed on the printed union instead, where TypeScript always emits a top-level undefined last — truncated unions ('a' | ... 11 more ... | undefined) included. Every other union keeps taking getNonNullableType, which prints an optional function type without the union parens the trim would leave behind (() => void, not (() => void)).

Applies to the structured fields only. A callable's typeSignature comes from checker.signatureToString, which has no flag to omit the widening, so it renders optional parameters as the checker does — (a?: number | undefined): void. The strip is top-level only, so an optional property nested in a printed object type keeps its widening too (b: {c?: boolean} → "{ c?: boolean | undefined; }").

The result is the checker's canonical rendering, not what an editor shows on hover: the language service prints from the declaration node, so for an alias-lost type Foo = z.infer<typeof S> (any alias over an indexed access or conditional) hover reads Foo while this carries the expanded, possibly truncated, structure.

A non-union optional is printed as written, since there's no widening member to remove: x?: undefined stays "undefined" (stripping would leave never, the same silent-wrong shape as the null cases above), and x?: unknown stays "unknown" (getNonNullableType would answer {}). See optionalWideningTarget for the full case split.

Under exactOptionalPropertyTypes the checker doesn't widen optional properties at all, so property sites gate the strip off via optionalWidened (passing false here) — every undefined there is author-written (x?: T | undefined is a distinct type from x?: T in that mode) and stripping would trim it. Parameter and tuple-element sites pass optional unconditionally: the flag governs properties only, and both keep widening under it.

import {getTypeSignature} from 'svelte-docinfo/typescript-extract-shared.ts';

globFiles
#

files.ts view source

globFiles(options: GlobFilesOptions): Promise<SourceFileInfo[]>

Discover source files via glob patterns.

The always-on baseline exclusions (node_modules + dot-directories, see baselineExcludesForBase) apply as glob ignores anchored below each pattern's static base — so a root-crossing include ('**\/*.ts') can't rake in node_modules, while an include rooted in a dot directory ('.hidden/src/**') still matches, mirroring isSource's matched-sourcePath relativity.

import {globFiles} from 'svelte-docinfo/files.ts';

parameters

glob configuration

returns

array of source files with content loaded

throws

  • Error - if any matched file cannot be read — the pool rejects on the first read failure

examples

const files = await globFiles({ projectRoot: process.cwd(), include: deriveIncludePatterns(['src/lib']), exclude: DEFAULT_SOURCE_OPTIONS.exclude, });

GlobFilesOptions
#

files.ts view source

Options for globFiles.

import type {GlobFilesOptions} from 'svelte-docinfo/files.ts';

members

projectRoot

: string
#

Absolute path to project root.

include

: readonly string[]
#

Glob patterns to include (relative to projectRoot).

exclude

?: string[]
#

Optional glob patterns to exclude.

hasBaselineExcludedSegment
#

source-config.ts view source

hasBaselineExcludedSegment(relPath: string): boolean

Whether a base-relative path contains an always-excluded directory segment.

The always-on baseline: node_modules directories and dot-directories (.svelte-kit, .git, .cache, …) are never source. Matched against the path *relative to the matched source path*, not the project root — so an explicit dot-dir source path (sourcePaths: ['.hidden/src']) still works: the dot segment sits in the base, not the remainder. That relativity is the opt-out; there is no flag. Deliberately only these two families — dist/build/coverage are ordinary names a project can legitimately keep source in, and over-excluding fails silently.

Only directory segments are checked; the final segment (the file itself) is not, so a dotfile like .config.ts inside a source dir passes.

Deliberately NOT part of DEFAULT_SOURCE_OPTIONS.exclude: user exclude replaces the defaults wholesale and would silently strip the baseline. baselineExcludesForBase is the discovery-time glob form; at analysis it applies wherever isSource does.

import {hasBaselineExcludedSegment} from 'svelte-docinfo/source-config.ts';

parameters

relPath

: string
#

POSIX path relative to a matched source path / discovery base

hasDocContent
#

tsdoc.ts view source

hasDocContent({ text, params, ...tags }: TsdocParsedComment): boolean

Whether a parsed comment carries any documentation — description text or an extracted tag.

Type machinery parses to an empty result (@type/@typedef/@template tags populate no fields), so doc-hunting walks (component docComment) use this to keep lower-precedence sources like the HTML @component comment reachable instead of letting an annotation claim the doc slot with empty text. Structural over the parsed result — any field beyond text/params counts when present — so it can't drift from parseComment's extraction or from TsdocParsedComment gaining fields. cssPropertyProblems counts too: a broken @cssprop is still the author's intent, and only a comment that wins the doc slot gets warned about (malformed_tag, duplicate_tag).

import {hasDocContent} from 'svelte-docinfo/tsdoc.ts';

hasErrors
#

hasModuleTag
#

tsdoc.ts view source

hasModuleTag(text: string): boolean

Whether cleaned comment text is a module comment: a line starts with @module. A backticked or mid-prose mention doesn't count.

import {hasModuleTag} from 'svelte-docinfo/tsdoc.ts';

hasWarnings
#

diagnostics.ts view source

also exported from index.ts

hasWarnings(diagnostics: Diagnostic[]): boolean

Check if any warning-severity diagnostics were collected.

import {hasWarnings} from 'svelte-docinfo/diagnostics.ts';

heritageTypeInfo
#

typescript-extract-shared.ts view source

heritageTypeInfo(types: readonly ExpressionWithTypeArguments[], ctx: ExtractContext): TypeJson[]

The structured form of each heritage entry, index-aligned with the text entries, so always one node per entry: an entry the checker can't resolve is a terminal node over its text.

import {heritageTypeInfo} from 'svelte-docinfo/typescript-extract-shared.ts';

HtmlComment
#

svelte-scripts.ts view source

An HTML comment's raw content (between <!-- and -->) and where the comment starts.

import type {HtmlComment} from 'svelte-docinfo/svelte-scripts.ts';

members

content

: string
#

start

: number
#

Offset of the <!-- in the Svelte source.

ImplementationDocHiddenDiagnostic
#

diagnostics.ts view source

value + type

An overloaded function, method, or constructor documents its implementation, whose JSDoc is hidden.

Only overload signatures are public, so TypeScript's hover ignores the implementation's JSDoc, and so does the output: its prose and tags drop, an implementation @nodocs hides nothing, and the symbol's docs come from its first overload. Fires for a TS implementation (the bodied declaration after its overloads) and for a JS implementation's JSDoc blocks that host no @overload tag, when they carry doc content; a block of types alone (@param {string} a) doesn't fire. line/column point at the implementation. Move the docs to the first overload.

Always warning, query-time category (recomputed each query()).

import {ImplementationDocHiddenDiagnostic} from 'svelte-docinfo/diagnostics.ts';

inheritance

extends: SchemaStrictObjectOutput<typeof ImplementationDocHiddenDiagnosticEntries>

members

kind

: "implementation_doc_hidden"
#

functionName

: string
#

Name of the overloaded function, method, or constructor.

file

: string
#

File path relative to project root (no leading slash, no ./ prefix).

Normalized at every public API boundary — session.setFile/setFiles (ingest-time), session.query (query-time, via analyzeCore), and the one-shot wrappers analyze / analyzeFromFiles. Producers inside the pipeline may write absolute or virtual paths (e.g., Foo.svelte.__svelte2tsx__.ts); normalization rewrites them to project-relative form before they reach consumers.

The exception is discovery — discoverSourceFiles / discoverFromExports return their diagnostics unnormalized, since they run before any session exists. Their file is already project-root-relative, but message can embed an absolute path (an fs error names the file it failed on), so a consumer wiring discovery up itself owns the normalizeDiagnosticPaths call — analyzeFromFiles and the Vite plugin both make it before merging.

The absolute form is the one to write. Normalization deliberately leaves an already-relative path alone (relativizing it would resolve against cwd), so a producer writing a ModuleJson.path — relative to sourceRoot, a different base — passes through untouched and publishes the same file under a second name. Absolute is what the pass can actually correct.

message

: string
#

Human-readable description of the issue.

severity

: "error" | "warning"
#

line

?: number
#

Line number (1-based), absent if location unavailable.

column

?: number
#

Column number (1-based), absent if location unavailable.

ImplementationDocHiddenDiagnosticInput
#

diagnostics.ts view source

The input ImplementationDocHiddenDiagnostic parses, with any field it defaults optional.

import type {ImplementationDocHiddenDiagnosticInput} from 'svelte-docinfo/diagnostics.ts';

inheritance

extends: SchemaStrictObjectInput<typeof ImplementationDocHiddenDiagnosticEntries>

members

kind

: "implementation_doc_hidden"
#

functionName

: string
#

Name of the overloaded function, method, or constructor.

file

: string
#

File path relative to project root (no leading slash, no ./ prefix).

Normalized at every public API boundary — session.setFile/setFiles (ingest-time), session.query (query-time, via analyzeCore), and the one-shot wrappers analyze / analyzeFromFiles. Producers inside the pipeline may write absolute or virtual paths (e.g., Foo.svelte.__svelte2tsx__.ts); normalization rewrites them to project-relative form before they reach consumers.

The exception is discovery — discoverSourceFiles / discoverFromExports return their diagnostics unnormalized, since they run before any session exists. Their file is already project-root-relative, but message can embed an absolute path (an fs error names the file it failed on), so a consumer wiring discovery up itself owns the normalizeDiagnosticPaths call — analyzeFromFiles and the Vite plugin both make it before merging.

The absolute form is the one to write. Normalization deliberately leaves an already-relative path alone (relativizing it would resolve against cwd), so a producer writing a ModuleJson.path — relative to sourceRoot, a different base — passes through untouched and publishes the same file under a second name. Absolute is what the pass can actually correct.

message

: string
#

Human-readable description of the issue.

severity

: "error" | "warning"
#

line

?: number
#

Line number (1-based), absent if location unavailable.

column

?: number
#

Column number (1-based), absent if location unavailable.

ImportParseDiagnostic
#

diagnostics.ts view source

value + type

Import scanning threw during dependency resolution.

Not expected in practice: the parse in lexImports tolerates malformed source rather than rejecting it, so this guards an unexpected throw.

import {ImportParseDiagnostic} from 'svelte-docinfo/diagnostics.ts';

inheritance

extends: SchemaStrictObjectOutput<typeof ImportParseDiagnosticEntries>

members

kind

: "import_parse_failed"
#

file

: string
#

File path relative to project root (no leading slash, no ./ prefix).

Normalized at every public API boundary — session.setFile/setFiles (ingest-time), session.query (query-time, via analyzeCore), and the one-shot wrappers analyze / analyzeFromFiles. Producers inside the pipeline may write absolute or virtual paths (e.g., Foo.svelte.__svelte2tsx__.ts); normalization rewrites them to project-relative form before they reach consumers.

The exception is discovery — discoverSourceFiles / discoverFromExports return their diagnostics unnormalized, since they run before any session exists. Their file is already project-root-relative, but message can embed an absolute path (an fs error names the file it failed on), so a consumer wiring discovery up itself owns the normalizeDiagnosticPaths call — analyzeFromFiles and the Vite plugin both make it before merging.

The absolute form is the one to write. Normalization deliberately leaves an already-relative path alone (relativizing it would resolve against cwd), so a producer writing a ModuleJson.path — relative to sourceRoot, a different base — passes through untouched and publishes the same file under a second name. Absolute is what the pass can actually correct.

message

: string
#

Human-readable description of the issue.

severity

: "error" | "warning"
#

line

?: number
#

Line number (1-based), absent if location unavailable.

column

?: number
#

Column number (1-based), absent if location unavailable.

ImportParseDiagnosticInput
#

diagnostics.ts view source

The input ImportParseDiagnostic parses, with any field it defaults optional.

import type {ImportParseDiagnosticInput} from 'svelte-docinfo/diagnostics.ts';

inheritance

extends: SchemaStrictObjectInput<typeof ImportParseDiagnosticEntries>

members

kind

: "import_parse_failed"
#

file

: string
#

File path relative to project root (no leading slash, no ./ prefix).

Normalized at every public API boundary — session.setFile/setFiles (ingest-time), session.query (query-time, via analyzeCore), and the one-shot wrappers analyze / analyzeFromFiles. Producers inside the pipeline may write absolute or virtual paths (e.g., Foo.svelte.__svelte2tsx__.ts); normalization rewrites them to project-relative form before they reach consumers.

The exception is discovery — discoverSourceFiles / discoverFromExports return their diagnostics unnormalized, since they run before any session exists. Their file is already project-root-relative, but message can embed an absolute path (an fs error names the file it failed on), so a consumer wiring discovery up itself owns the normalizeDiagnosticPaths call — analyzeFromFiles and the Vite plugin both make it before merging.

The absolute form is the one to write. Normalization deliberately leaves an already-relative path alone (relativizing it would resolve against cwd), so a producer writing a ModuleJson.path — relative to sourceRoot, a different base — passes through untouched and publishes the same file under a second name. Absolute is what the pass can actually correct.

message

: string
#

Human-readable description of the issue.

severity

: "error" | "warning"
#

line

?: number
#

Line number (1-based), absent if location unavailable.

column

?: number
#

Column number (1-based), absent if location unavailable.

ImportResolver
#

dep-resolver.ts view source

also exported from index.ts

Token-paired import resolver.

identity is a stable opaque token that keys the session's resolve cache alongside content. Cache hits require both (a) byte-for-byte identical source content and (b) identity equality. Naive function-reference keys would silently destroy cache reuse when callers wrap the resolver in fresh closures (a very common pattern in Vite/Rollup plugins) — opaque tokens lift the responsibility to the caller, where it can be done correctly.

import type {ImportResolver} from 'svelte-docinfo/dep-resolver.ts';

members

#

Resolve an import specifier to an absolute file path, or null.

identity

: string | symbol
#

Stable opaque token identifying this resolver's cache scope.

Two ImportResolvers with identity === to each other are treated as cache-equivalent. string for human-readable identities (e.g., 'vite-plugin-container'); symbol for generated sentinels.

invalidate

?: () => void
#

Drop any cached resolution state. Optional — implement it when the resolver caches results across calls, and especially when it caches *failed* lookups, which go stale the moment a previously-missing file appears.

The session calls this at the start of a batch whenever its owned file set gained or lost a path since this resolver last ran, so a dep ingested after an importer already failed to resolve it still produces an edge. Content-only changes never trigger it (they can't change what exists). Files appearing on *disk* without being ingested are invisible to the session — a resolver caching disk misses owns that invalidation itself.

includePatternBase
#

source-config.ts view source

includePatternBase(pattern: string): string | null

Static base directory of a discovery include pattern.

picomatch.scan().base for glob patterns ('src/other/**\/*.ts' → 'src/other'); a literal non-glob pattern names a file, so it contributes its directory ('src/foo.ts' → 'src', a root file → ''); a negated pattern has no base (null). Shared by widenSourcePathsForInclude (scope widening), globFiles (anchoring the baseline exclusions), and createSourceOptionsWithInclude (detecting root-scoping patterns to log).

Patterns are expected projectRoot-relative — the discovery seams (createSourceOptionsWithInclude, discoverSourceFiles) run normalizeIncludePatterns first, which relativizes in-root absolute patterns and throws on out-of-root ones, so no absolute pattern reaches the base scan through the public entry points.

import {includePatternBase} from 'svelte-docinfo/source-config.ts';

inferDeclarationKind
#

typescript-extract-shared.ts view source

inferDeclarationKind(symbol: Symbol, node: Node): DeclarationKind

Infer declaration kind from symbol and node.

Maps TypeScript constructs to DeclarationKind:

  • Classes → 'class'
  • Functions (declarations, expressions, arrows) → 'function'
  • Interfaces → 'interface'
  • Type aliases → 'type', JSDoc @typedef / @callback included
  • Enums (regular and const) → 'enum', and a JS @enum const (@enum {string} on export const A = {a: 'a'}): the checker binds the tag as a type alias over the value's name, but like a TypeScript enum the name is a runtime object of members and a type, so it documents as one
  • Variables → 'variable' (unless function-valued → 'function')

Note: namespace re-exports (export * as ns from './x') have no inline declaration form in TypeScript and are caught upstream in analyzeExports via classifyNamespaceReExport. They never reach this function. A direct call here on a ValueModule symbol would fall through to 'variable' and leak typeof import("/abs/path") into the output — keep the namespace dispatch in analyzeExports.

Standalone namespace Foo {} declarations aren't modeled: they fall through to 'variable' and document as typeof Foo (or any for a type-only namespace) with no members.

import {inferDeclarationKind} from 'svelte-docinfo/typescript-extract-shared.ts';

InterfaceDeclarationJson
#

types.ts view source

value + type

also exported from index.ts

An interface declaration. Has members, extends.

import {InterfaceDeclarationJson} from 'svelte-docinfo/types.ts';

inheritance

extends: SchemaStrictObjectOutput<typeof InterfaceDeclarationJsonEntries>

members

kind

: "interface"
#

extends

: string[]
#

Extended interfaces.

Verbatim text of this declaration's own heritage clause, so entries are spelled as this module wrote them and resolve in its scope — a local rename (import type {Bag as B}) stays B. Unlike externalTypes, whose walk crosses modules and therefore resolves renames back to the exported name, this clause never leaves the declaring file.

see also

extendsInfo

: TypeJson[]
#

Structured form of each extends entry, index-aligned with it: always one node per entry, so the usual absence contract (see TypeJson) is relaxed here and a bare Base is a reference node. It follows the written entry as GenericParamJson.constraintInfo does, and a locally renamed import carries its exported name, where the text beside it keeps the local one; a base that isn't a class or interface by name (extends mixin(B), a const holding a class) is a terminal node over its text.

externalTypes

: string[]
#

External types the heritage composition reaches whose contributions members never enumerates.

A named base's members aren't listed, and a computed heritage entry's external properties are filtered out (see members). This field names the external types behind that absence: `interface Props extends HTMLButtonAttributes records the bag directly, and interface Props extends LocalBase (where LocalBase` reaches a bag) records it transitively — the same answer the component annotated with this interface gets, where extends alone dead-ends at a possibly-unexported local name. Inherited *local* content is the extends field's business: the base is documented at its own declaration.

Entry normalization (rename resolution, type-parameter substitution, text-dedupe, source order) matches TypeDeclarationJson.externalTypes. Direct-heritage cases make this textually equal to extends; consumers dedupe at render time.

Interface members: property signatures, method signatures, index signatures, call/construct signatures — the interface's own, plus what each extends entry that isn't a named interface or class contributes.

A named base (extends Base, extends Base<string>, an alias of either), local or external, keeps its members, call/construct signatures included: extends names it, and it is documented at its own declaration. A computed entry has no declaration of its own — a mapped, conditional, or utility-type instantiation (z.infer<typeof S>, Omit<Base, 'a'>, Partial<Base>), an intersection, an object type behind an alias — so it contributes what the same type documents as a type alias's members, external-origin contributions dropped and labeled in externalTypes. A name the interface declares itself wins; otherwise the first heritage entry with the name supplies it, as in TypeScript's inheritance. A call or construct signature likewise goes to the first entry that reaches it: extends Base, Base & {…} leaves Base's to Base, extends Base & {…}, Base lists them. Own members come in source order, then the contributed properties entry by entry, then their index signatures, with call/construct signatures last (own before contributed, as overloads of one member, each signature once).

A merged interface documents the block selectDeclarationNode picks, the first in declaration order: its members and its extends (own call and construct signatures excepted, which come from every block). Another block's members and heritage document nothing, and a name another block declares still drops from the documented block's heritage contribution, since TypeScript takes it from that block.

mergedValue

: boolean
#

The exported name also carries a value meaning — a merged value+type symbol (const Foo = ... + interface Foo {...}), where the interface wins the declaration slot and the value's own type goes undocumented. Tells consumers the name is importable as a runtime value: `import {Foo}, never import type {Foo} (see generateImport`).

see also

alsoExportedFrom

: string[]
#

Module paths (relative to sourceRoot) that re-export this declaration under the same name. The canonical declaration lives in this module's declarations array; these paths are additional import locations for the same thing.

The same edges appear from the re-exporting side as ModuleJson.reExports — use that when asking "what does this module re-export" instead of inverting these arrays. The two can disagree at the margins: a reExports entry whose canonical declaration is @nodocs (or whose module isn't in the analyzed set) has no back-link here.

Consumer note: To build a complete re-export map, scan two fields:

  1. alsoExportedFrom on each declaration — same-name re-exports
  2. aliasOf on declarations — renamed re-exports (separate declarations)

partial

: boolean
#

Whether extraction failed partway through, leaving some fields missing (e.g., typeSignature, parameters).

examples

: string[]
#

Code examples from @example tags.

seeAlso

: string[]
#

Related items from @see tags, in raw TSDoc format.

throws

: ThrowsJson[]
#

Exceptions from @throws tags. type is the tag's written type, and typeInfo its structured form, present for a braced type (@throws {A<B>}) that isn't the whole story as text (see TypeJson); an unbraced tag's leading word never has one, nor does a tag in a component's HTML @component comment, which is read as text.

name

: string
#

The exported name. Always populated. The default-export slot is named 'default', except a Svelte component, which takes its filename-derived name ('X' for X.svelte) — 'default' is the symbol's actual name in JS (import {default as X} and ns.default both expose it directly), and import X from 'mod' is sugar for import {default as X}. Consumers branch on name === 'default' to render the sugar form when desired.

modifiers

: ("public" | "protected" | "readonly" | "static" | "abstract" | "getter" | "setter")[]
#

TypeScript modifiers like readonly, static, or protected.

genericParams

: GenericParamJson[]
#

Generic type parameters like <T, U>.

aliasOf

?: { module: string; name: string; }
#

For renamed re-exports (export {foo as bar}), points to the original declaration. This declaration's name is the alias; aliasOf.name is the original name.

For renames out of the default slot (export {default as bar} from './x' where ./x is export default ...), aliasOf.name is 'default' — the canonical's actual symbol name. Consumers locate the canonical by (aliasOf.module, aliasOf.name).

Svelte component exception: when the source is a .svelte file (e.g., export {default as Foo} from './X.svelte'), the canonical's name is the component name (derived from the filename), so aliasOf.name is the component name ('X'), NOT 'default'. Consumers that branch on aliasOf.name === 'default' to detect default-rename should additionally check whether aliasOf.module ends with .svelte.

Different from alsoExportedFrom: aliases create new API surface names, while alsoExportedFrom tracks additional import paths for the same name.

A type-only rename of a value (export type {someConst as c} from './x') synthesizes a normal alias — declarations carry no type-only marker.

deprecatedMessage

?: string
#

Deprecation message from @deprecated tag.

since

?: string
#

Version introduced, from @since tag.

internalMessage

?: string
#

Internal-API marker from the @internal tag. Presence means the tag was written; an empty string is a bare tag with no trailing prose.

A marker, not an exclusion: @internal means "not stable public API" (TSDoc semantics) while the declaration, member, or prop stays documented — unlike @nodocs, which removes a declaration from output entirely (and is ignored on props and members).

mutates

?: Record<string, string>
#

Mutation documentation from @mutates tags (non-standard), mapping keys to descriptions.

Keys are intentionally unvalidated — typically a parameter name, but authors may also use compound paths (this.foo, obj.field) or multi-word external state references. Backticks are stripped from keys so `` a `` and a normalize to one key; an empty-string value is a bare tag with no description. The schema accepts any string key so consumers can render whatever the author wrote.

On a component prop it declares the component's mutation contract for the value it's handed: the component writes into the prop's object or array in place (@mutates items - appends the selected entry, @mutates options.cache - fills on first render). Reassigning a prop is not a mutation in this sense (bindable covers it), though a $bindable prop can carry both.

docComment

?: string
#

JSDoc/TSDoc comment.

typeSignature

?: string
#

Full TypeScript type signature.

sourceLine

?: number
#

1-based line in the source file, a positive integer. Synthesized aliases (see aliasOf) carry the local export specifier's line, not the canonical's.

InterfaceDeclarationJsonInput
#

types.ts view source

The input InterfaceDeclarationJson parses, with any field it defaults optional.

import type {InterfaceDeclarationJsonInput} from 'svelte-docinfo/types.ts';

inheritance

extends: SchemaStrictObjectInput<typeof InterfaceDeclarationJsonEntries>

members

kind

: "interface"
#

name

: string
#

The exported name. Always populated. The default-export slot is named 'default', except a Svelte component, which takes its filename-derived name ('X' for X.svelte) — 'default' is the symbol's actual name in JS (import {default as X} and ns.default both expose it directly), and import X from 'mod' is sugar for import {default as X}. Consumers branch on name === 'default' to render the sugar form when desired.

extends

?: string[]
#

Extended interfaces.

Verbatim text of this declaration's own heritage clause, so entries are spelled as this module wrote them and resolve in its scope — a local rename (import type {Bag as B}) stays B. Unlike externalTypes, whose walk crosses modules and therefore resolves renames back to the exported name, this clause never leaves the declaring file.

see also

extendsInfo

?: TypeJson[]
#

Structured form of each extends entry, index-aligned with it: always one node per entry, so the usual absence contract (see TypeJson) is relaxed here and a bare Base is a reference node. It follows the written entry as GenericParamJson.constraintInfo does, and a locally renamed import carries its exported name, where the text beside it keeps the local one; a base that isn't a class or interface by name (extends mixin(B), a const holding a class) is a terminal node over its text.

externalTypes

?: string[]
#

External types the heritage composition reaches whose contributions members never enumerates.

A named base's members aren't listed, and a computed heritage entry's external properties are filtered out (see members). This field names the external types behind that absence: `interface Props extends HTMLButtonAttributes records the bag directly, and interface Props extends LocalBase (where LocalBase` reaches a bag) records it transitively — the same answer the component annotated with this interface gets, where extends alone dead-ends at a possibly-unexported local name. Inherited *local* content is the extends field's business: the base is documented at its own declaration.

Entry normalization (rename resolution, type-parameter substitution, text-dedupe, source order) matches TypeDeclarationJson.externalTypes. Direct-heritage cases make this textually equal to extends; consumers dedupe at render time.

Interface members: property signatures, method signatures, index signatures, call/construct signatures — the interface's own, plus what each extends entry that isn't a named interface or class contributes.

A named base (extends Base, extends Base<string>, an alias of either), local or external, keeps its members, call/construct signatures included: extends names it, and it is documented at its own declaration. A computed entry has no declaration of its own — a mapped, conditional, or utility-type instantiation (z.infer<typeof S>, Omit<Base, 'a'>, Partial<Base>), an intersection, an object type behind an alias — so it contributes what the same type documents as a type alias's members, external-origin contributions dropped and labeled in externalTypes. A name the interface declares itself wins; otherwise the first heritage entry with the name supplies it, as in TypeScript's inheritance. A call or construct signature likewise goes to the first entry that reaches it: extends Base, Base & {…} leaves Base's to Base, extends Base & {…}, Base lists them. Own members come in source order, then the contributed properties entry by entry, then their index signatures, with call/construct signatures last (own before contributed, as overloads of one member, each signature once).

A merged interface documents the block selectDeclarationNode picks, the first in declaration order: its members and its extends (own call and construct signatures excepted, which come from every block). Another block's members and heritage document nothing, and a name another block declares still drops from the documented block's heritage contribution, since TypeScript takes it from that block.

mergedValue

?: boolean
#

The exported name also carries a value meaning — a merged value+type symbol (const Foo = ... + interface Foo {...}), where the interface wins the declaration slot and the value's own type goes undocumented. Tells consumers the name is importable as a runtime value: `import {Foo}, never import type {Foo} (see generateImport`).

see also

alsoExportedFrom

?: string[]
#

Module paths (relative to sourceRoot) that re-export this declaration under the same name. The canonical declaration lives in this module's declarations array; these paths are additional import locations for the same thing.

The same edges appear from the re-exporting side as ModuleJson.reExports — use that when asking "what does this module re-export" instead of inverting these arrays. The two can disagree at the margins: a reExports entry whose canonical declaration is @nodocs (or whose module isn't in the analyzed set) has no back-link here.

Consumer note: To build a complete re-export map, scan two fields:

  1. alsoExportedFrom on each declaration — same-name re-exports
  2. aliasOf on declarations — renamed re-exports (separate declarations)

aliasOf

?: { module: string; name: string; }
#

For renamed re-exports (export {foo as bar}), points to the original declaration. This declaration's name is the alias; aliasOf.name is the original name.

For renames out of the default slot (export {default as bar} from './x' where ./x is export default ...), aliasOf.name is 'default' — the canonical's actual symbol name. Consumers locate the canonical by (aliasOf.module, aliasOf.name).

Svelte component exception: when the source is a .svelte file (e.g., export {default as Foo} from './X.svelte'), the canonical's name is the component name (derived from the filename), so aliasOf.name is the component name ('X'), NOT 'default'. Consumers that branch on aliasOf.name === 'default' to detect default-rename should additionally check whether aliasOf.module ends with .svelte.

Different from alsoExportedFrom: aliases create new API surface names, while alsoExportedFrom tracks additional import paths for the same name.

A type-only rename of a value (export type {someConst as c} from './x') synthesizes a normal alias — declarations carry no type-only marker.

partial

?: boolean
#

Whether extraction failed partway through, leaving some fields missing (e.g., typeSignature, parameters).

examples

?: string[]
#

Code examples from @example tags.

deprecatedMessage

?: string
#

Deprecation message from @deprecated tag.

seeAlso

?: string[]
#

Related items from @see tags, in raw TSDoc format.

throws

?: ThrowsJsonInput[]
#

Exceptions from @throws tags. type is the tag's written type, and typeInfo its structured form, present for a braced type (@throws {A<B>}) that isn't the whole story as text (see TypeJson); an unbraced tag's leading word never has one, nor does a tag in a component's HTML @component comment, which is read as text.

since

?: string
#

Version introduced, from @since tag.

internalMessage

?: string
#

Internal-API marker from the @internal tag. Presence means the tag was written; an empty string is a bare tag with no trailing prose.

A marker, not an exclusion: @internal means "not stable public API" (TSDoc semantics) while the declaration, member, or prop stays documented — unlike @nodocs, which removes a declaration from output entirely (and is ignored on props and members).

mutates

?: Record<string, string>
#

Mutation documentation from @mutates tags (non-standard), mapping keys to descriptions.

Keys are intentionally unvalidated — typically a parameter name, but authors may also use compound paths (this.foo, obj.field) or multi-word external state references. Backticks are stripped from keys so `` a `` and a normalize to one key; an empty-string value is a bare tag with no description. The schema accepts any string key so consumers can render whatever the author wrote.

On a component prop it declares the component's mutation contract for the value it's handed: the component writes into the prop's object or array in place (@mutates items - appends the selected entry, @mutates options.cache - fills on first render). Reassigning a prop is not a mutation in this sense (bindable covers it), though a $bindable prop can carry both.

docComment

?: string
#

JSDoc/TSDoc comment.

typeSignature

?: string
#

Full TypeScript type signature.

modifiers

?: ("public" | "protected" | "readonly" | "static" | "abstract" | "getter" | "setter")[]
#

TypeScript modifiers like readonly, static, or protected.

sourceLine

?: number
#

1-based line in the source file, a positive integer. Synthesized aliases (see aliasOf) carry the local export specifier's line, not the canonical's.

genericParams

?: GenericParamJsonInput[]
#

Generic type parameters like <T, U>.

isAbsolutePosixPath
#

paths.ts view source

isAbsolutePosixPath(p: string): boolean

Whether a POSIX-form path is absolute — rooted (/src/x.ts) or drive-qualified (C:/proj/x.ts).

Not node:path's isAbsolute, which is platform-flavored: on Linux it reads a posixified Windows path like C:/proj/x.ts as relative. Everything here is already in the internal POSIX form by contract, so the check has to cover both shapes regardless of host.

import {isAbsolutePosixPath} from 'svelte-docinfo/paths.ts';

examples

isAbsolutePosixPath('/home/user/proj/foo.ts') // => true isAbsolutePosixPath('C:/proj/foo.ts') // => true isAbsolutePosixPath('src/lib/foo.ts') // => false isAbsolutePosixPath('../sibling/foo.ts') // => false

isAliasLostType
#

typescript-extract-type-json.ts view source

isAliasLostType(type: Type): boolean

Whether the checker kept no name for a type-alias declaration's resolved type: no alias symbol (the checker still prints type A = B as B), no nominal symbol (interfaces/classes/enums print their own name), and not an interned terminal (type A = string and type A = 'x' carry no alias symbol either but print fine). True for the expansion-prone class the alias registry targets and the alias_lost diagnostic reports — indexed-access and conditional right-hand sides (z.infer<typeof S> et al.), whose resolution lands on a pre-existing interned type that TypeScript never retroactively stamps an alias symbol on.

An alias whose only alias symbol is svelte2tsx-generated counts as lost (linkableAliasSymbol): type P = ComponentProps<typeof Button> over inline props prints as $$ComponentProps, a name no consumer can look up.

The exception is a lost alias over an array root: namedSymbolName names it Array, so the predicate is false and it never registers.

import {isAliasLostType} from 'svelte-docinfo/typescript-extract-type-json.ts';

isArrayPatternParamTag
#

tsdoc.ts view source

isArrayPatternParamTag(tag: JSDocPropertyLikeTag, sourceFile?: SourceFile): boolean

Whether a @param tag names an array pattern (@param [a, b] - the pair for a parameter written [a, b]). TypeScript's parser reads the bracket as JSDoc's optional-parameter syntax, so the tag's name is a and its comment starts with the pattern's rest (, b] - the pair). The tag still documents the parameter in its position; its name is no name for it.

import {isArrayPatternParamTag} from 'svelte-docinfo/tsdoc.ts';

parameters

sourceFile

?: SourceFile = tag.getSourceFile()
#

isBrandLikeIntersection
#

typescript-extract-type-json.ts view source

isBrandLikeIntersection(type: Type): boolean

Whether a type is an intersection carrying an intrinsic or literal member — the .brand() shape (string & BRAND<'x'>). Such aliases are lost but unrecoverable, readable, and author-unfixable, so the alias_lost diagnostic excludes them.

import {isBrandLikeIntersection} from 'svelte-docinfo/typescript-extract-type-json.ts';

isCss
#

source.ts view source

isCss(path: string): boolean

Check if a path is a CSS file.

import {isCss} from 'svelte-docinfo/source.ts';

isDeclaredInFile
#

typescript-extract-shared.ts view source

internal

Shared by the export walk (`analyzeExports`) and the alias-registry pre-pass (`buildAliasRegistry`) — both must skip star-projected bindings the same way.

isDeclaredInFile(symbol: Symbol, fileName: string): boolean

Whether any of the symbol's declarations lives in fileName (virtual-suffix-normalized).

Merged symbols (module augmentation, declaration merging) can have declarations in several files — a symbol counts as declared in the file when at least one declaration is, so checking a single declaration node would drop locally-declared exports depending on bind order. Symbols without declarations are treated as declared in the file (permissive).

import {isDeclaredInFile} from 'svelte-docinfo/typescript-extract-shared.ts';

IsEmittedFile
#

typescript-extract-shared.ts view source

Whether the file at an absolute POSIX path emits a module in this analysis pass — the question the re-export encodings turn on: a re-export of an emitted canonical links to it, while one whose canonical emits nothing is documented where it's re-exported.

Not the same as isSource. A file can pass isSource and still emit nothing because it isn't one of the analyzed inputs: under exports discovery, a source file outside package.json exports; in a session, a file ingested only as checker context, or one never handed over at all. Linking a re-export to such a file would point at a module the output doesn't contain and leave the name documented nowhere, so it is documented in the re-exporting module instead, exactly as for a gated internal/ file. analyzeCore answers from the set it was handed; a caller analyzing one module with no set to consult falls back to isSource.

Stars follow the same rule: export * from a file that emits nothing is read as the named re-exports it stands for (collectMaterializedStars in typescript-exports.ts), and only a star over an emitted module is a starExports entry.

import type {IsEmittedFile} from 'svelte-docinfo/typescript-extract-shared.ts';

members

(file: string): boolean

IsExternalFile
#

typescript-program.ts view source

Predicate for determining whether a TypeScript source file is external to the project. Used by external-contribution filtering (filterDocumentedProperties and the index/call-signature origin checks) and externalTypes attribution to separate project-authored contributions from library/framework ones.

Built by createIsExternalFile, which defines externality.

import type {IsExternalFile} from 'svelte-docinfo/typescript-program.ts';

members

(sourceFile: SourceFile): boolean

isExternalIndexInfo
#

typescript-extract-shared.ts view source

isExternalIndexInfo(info: IndexInfo, isExternalFile: IsExternalFile): boolean

Check whether an index signature comes from an external file.

The checker synthesizes index infos for every mapped-type instantiation (Record<string, X>, Partial<Indexed>, hand-written {[K in string]: X}) with no declaration, so those read local under originIsExternal's fail-open, while a bare reference or an inherited info preserves the original index-signature declaration, external file included.

import {isExternalIndexInfo} from 'svelte-docinfo/typescript-extract-shared.ts';

isExternalSignature
#

typescript-extract-shared.ts view source

isExternalSignature(sig: Signature, isExternalFile: IsExternalFile): boolean

Check whether a call/construct signature comes from an external file. In practice a signature always carries its original declaration — through intersections, inheritance, and generic instantiation alike — so the fail-open arm is unreachable for the shapes that occur.

import {isExternalSignature} from 'svelte-docinfo/typescript-extract-shared.ts';

isGenericallyNamedBrand
#

typescript-extract-type-json.ts view source

isGenericallyNamedBrand(type: Type): boolean

Whether a type is a brand the checker names by a generic's instantiation (Branded<string, "Uuid">, Flavored<string, "Id">): a brand-like intersection whose alias takes type arguments. The generic is the schema or brand library's, so the name says nothing of which brand it is; a non-generic alias (type FactHash = string & Brand<'FactHash'>) is the brand's own name, which the checker already prints and recovery never overrides.

import {isGenericallyNamedBrand} from 'svelte-docinfo/typescript-extract-type-json.ts';

isJavaScriptNode
#

typescript-extract-type-json.ts view source

isJavaScriptNode(node: Node): boolean

Whether a node was parsed as JS — a .js file, or a Svelte virtual with ScriptKind.JS. TypeScript reads JSDoc types as annotations only there.

import {isJavaScriptNode} from 'svelte-docinfo/typescript-extract-type-json.ts';

isJSDocEnumSymbol
#

typescript-extract-shared.ts view source

isJSDocEnumSymbol(symbol: Symbol): boolean

Whether a symbol is a JS @enum const: the tag declares a type alias merged with the value (inferDeclarationKind documents it as an enum, from the value declaration).

import {isJSDocEnumSymbol} from 'svelte-docinfo/typescript-extract-shared.ts';

isJson
#

source.ts view source

isJson(path: string): boolean

Check if a path is a JSON file.

import {isJson} from 'svelte-docinfo/source.ts';

isKind
#

declaration-helpers.ts view source

also exported from index.ts

isKind<K extends DeclarationKind | "constructor">(declaration: DeclarationJson | MemberJson, kind: K): declaration is Extract<DeclarationJson | MemberJson, { kind: K; }>

Narrow a declaration by kind for type-safe field access.

Works with both DeclarationJson (top-level) and MemberJson (nested). Accepts DeclarationKind | MemberKind so isKind(member, 'constructor') compiles.

import {isKind} from 'svelte-docinfo/declaration-helpers.ts';

examples

if (isKind(declaration, 'function')) { declaration.parameters; // FunctionDeclarationJson — has parameters declaration.returnType; // has returnType } if (isKind(member, 'constructor')) { member.parameters; // ConstructorMemberJson — has parameters }

isLiteralOnlyUnion
#

typescript-extract-type-json.ts view source

isLiteralOnlyUnion(type: Type): boolean

Whether a type is a union of literals only (z.enum outputs — a lost alias over one degrades mildly and readably, so the alias_lost diagnostic excludes it). Enum-member literals match too.

import {isLiteralOnlyUnion} from 'svelte-docinfo/typescript-extract-type-json.ts';

isModuleScript
#

svelte-scripts.ts view source

isModuleScript(attributes: Map<string, string | true>): boolean

A script tag is a module script when it carries a module attribute (Svelte 5) or context="module" (Svelte 4) — Svelte's read_script test, minus its error paths. module inside an attribute *value* doesn't count.

import {isModuleScript} from 'svelte-docinfo/svelte-scripts.ts';

isNodeBuiltin
#

dep-resolver.ts view source

isNodeBuiltin(specifier: string): boolean

Whether a lexed specifier names a Node builtin (fs, node:fs/promises, …).

Builtins can never be a project source file, so resolving them is pointless — and routing them through a host resolver (Vite/Rollup) makes that host emit "externalized for browser compatibility" warnings for browser-targeted configs. Callers skip resolution for these and treat them as unresolved (null), which the downstream isSource filter would do anyway.

import {isNodeBuiltin} from 'svelte-docinfo/dep-resolver.ts';

isPrivateMemberDeclaration
#

typescript-extract-shared.ts view source

isPrivateMemberDeclaration(decl: Declaration): boolean

Check whether a member declaration is private to the class that declares it — a # private identifier name, or a private modifier on a class element, a parameter property, or a this.x = … assignment. In JS a @private tag is the modifier (ts.getCombinedModifierFlags reads JSDoc modifier tags in JS files only); in a .ts file the tag marks nothing, as for the checker. An object literal's property or method keeps its @private member, since the checker enforces the tag in classes only. Expandos (A.prototype.x = …, A.x = …, o.x = …) declare through the assigned property access, so a @private expando hides nothing, though the checker enforces it on a class's.

The one visibility rule, shared by the two ways a class's members reach output: extractClassInfo walking node.members at the class's own declaration, and filterDocumentedProperties projecting a class *type* at a structural container (type X = LocalClass, type X = LocalGen<string>). Held in one place so an alias over a class hides exactly what the class hides — the two paths disagreeing would leak # fields into members through the alias.

protected is deliberately not private: it is part of the extension API a subclass author documents against. Only classes can declare either form — interfaces and type literals have no private members — so this is a no-op on every other shape.

import {isPrivateMemberDeclaration} from 'svelte-docinfo/typescript-extract-shared.ts';

isRenamedBrand
#

typescript-extract-type-json.ts view source

isRenamedBrand(type: Type, name: string): boolean

Whether a type alias names a brand the checker prints by its generic (isGenericallyNamedBrand): type Uuid = Infer<typeof Uuid> over a schema brand(…) computes to Branded<string, "Uuid">, so Uuid is nowhere in output. Not alias-lost (isAliasLostType), since the type has an alias; the registry takes it anyway. Only the alias whose name is the brand's own (a string-literal type argument equal to it) counts, so an alias of the brand under another name (type MemberId = Infer<typeof MemberId> over meta(Uuid, …), the same type) never claims the brand's uses. An instantiation is one type per argument list, so the identity match claims exactly that brand.

import {isRenamedBrand} from 'svelte-docinfo/typescript-extract-type-json.ts';

parameters

name

: string
#

the alias's exported name

isSnippetReturnType
#

svelte.ts view source

isSnippetReturnType(returnType: string): boolean

Check if a return type string matches svelte2tsx's snippet return type pattern.

svelte2tsx transforms exported snippets into arrow functions with ReturnType<import('svelte').Snippet> as the return type annotation. The resolved return type includes unique symbol (from Svelte's non-exported SnippetReturn unique symbol) intersected with the branded render message. We match on both parts to avoid false positives — the branded message alone could theoretically be crafted by user code, but the unique symbol intersection cannot since SnippetReturn is not exported from svelte.

import {isSnippetReturnType} from 'svelte-docinfo/svelte.ts';

isSnippetType
#

svelte.ts view source

isSnippetType(type: Type, checker: TypeChecker): boolean

Whether a checker type is a Snippet instantiation, structurally: a named generic instantiation (referenceSymbolName) named Snippet that carries a call signature — by construction the same shape the TypeJson builder classifies as a Snippet reference.

Callers pass the bare type — a union wrapping the Snippet reference (optional widening, | null) doesn't match, and neither does an intersection (Snippet<[]> & {...}); strip or walk members first.

import {isSnippetType} from 'svelte-docinfo/svelte.ts';

isSource
#

source-config.ts view source

isSource(path: string, options: ModuleSourceOptions): boolean

Check if a path is an analyzable source file.

Combines all filtering: source directory paths, the always-on baseline (node_modules + dot-directories below the matched source path — see hasBaselineExcludedSegment), exclude globs, and analyzer availability. This is the single check for whether a file should be included in library analysis.

Uses proper path semantics with startsWith matching against projectRoot/sourcePath/. No heuristics needed — nested directories are correctly excluded by the prefix check.

Order is sourceDir-then-exclude: the prefix check guarantees the path lives under projectRoot before relativization, so relative() always produces a clean glob-shaped string for the matcher. Files outside projectRoot (rare; would require monorepo path mapping) short-circuit at the prefix check before reaching the matcher.

import {isSource} from 'svelte-docinfo/source-config.ts';

parameters

path

: string
#

full absolute path to check

module source options for filtering

returns

true if the path is an analyzable source file

examples

const options = createSourceOptions('/home/user/project'); isSource('/home/user/project/src/lib/foo.ts', options) // => true isSource('/home/user/project/src/lib/styles.css', options) // => true isSource('/home/user/project/src/lib/data.json', options) // => true isSource('/home/user/project/src/lib/foo.test.ts', options) // => false (excluded) isSource('/home/user/project/src/fixtures/mini/src/lib/bar.ts', options) // => false (wrong prefix)

isStrayComponentTypedef
#

typescript-extract-shared.ts view source

isStrayComponentTypedef(symbol: Symbol): boolean

Whether a Svelte virtual's export is declared only by stray component-comment typedefs (isStrayComponentTypedefTag). It documents nothing: analyzeSvelteModule drops it with its alias_lost warnings and buildAliasRegistry never registers it. A merged symbol (a <script module> declaration of the same name) isn't stray.

import {isStrayComponentTypedef} from 'svelte-docinfo/typescript-extract-shared.ts';

isSvelte
#

source.ts view source

isSvelte(path: string): boolean

Check if a path is a Svelte component file.

import {isSvelte} from 'svelte-docinfo/source.ts';

isSvelte2tsxGeneratedExport
#

source.ts view source

isSvelte2tsxGeneratedExport(name: string): boolean

Whether an export name from a svelte2tsx virtual is generated machinery rather than an author declaration: the default slot (svelte2tsx's own component export — the component declaration is synthesized separately) plus every isSvelte2tsxInternal shape. The one rule shared by the Svelte export filter (analyzeSvelteModule), the alias-registry pre-pass skip, and warnAliasLost's virtual guard — only meaningful for names read off a virtual's export table (a plain TS module's default export is real).

import {isSvelte2tsxGeneratedExport} from 'svelte-docinfo/source.ts';

isSvelte2tsxInternal
#

source.ts view source

isSvelte2tsxInternal(name: string): boolean

Whether a symbol name is an internal svelte2tsx identifier — a generated name that never documents as a declaration: $$ComponentProps, $$render, __sveltets_Render, and the synthesized component class/type alias <ComponentName>__SvelteComponent_. Building block for isSvelte2tsxGeneratedExport, which adds the default slot.

Beyond export filtering, the TypeJson builder treats an alias with one of these names declared in a Svelte virtual or svelte2tsx's shims as no alias at all (linkableAliasSymbol in typescript-extract-type-json.ts), so $$ComponentProps and __sveltets_2_PropsWithChildren never reach a tree and don't mask a project alias over them. Flat type strings are the checker's rendering and still carry these names (Component<$$ComponentProps, {}, "">, __sveltets_2_IsomorphicComponent<…>), as do terminal text nodes nested in them and the generic-component interface $$IsomorphicComponent.

import {isSvelte2tsxInternal} from 'svelte-docinfo/source.ts';

isSvelteShimPath
#

typescript-program.ts view source

internal

Not a stable API.

isSvelteShimPath(fileName: string): boolean

Whether a file is one of the svelte2tsx shims getSvelteShimRoots roots, compared by the same resolved path rather than by file name. The TypeJson builder reads it to treat a shim-declared svelte2tsx alias as nameless (linkableAliasSymbol in typescript-extract-type-json.ts).

import {isSvelteShimPath} from 'svelte-docinfo/typescript-program.ts';

parameters

fileName

: string
#

a POSIX path, as ts.SourceFile.fileName holds it

isSvelteVirtualPath
#

source.ts view source

isSvelteVirtualPath(path: string): boolean

Whether a path names a svelte2tsx virtual file (carries SVELTE_VIRTUAL_SUFFIX).

import {isSvelteVirtualPath} from 'svelte-docinfo/source.ts';

isTypeAliasLike
#

isTypescript
#

source.ts view source

isTypescript(path: string): boolean

Check if a path is a TypeScript or JS file: .ts, .mts, .tsx, .js, .mjs, or .jsx.

JS files count since JS is valid in TS projects; the analysis program reads them with allowJs forced on (see createAnalysisLanguageService). CommonJS extensions (.cjs, .cts) are left out, since CommonJS exports aren't modeled (commonjs_unsupported). Excludes .d.ts and .d.mts declaration files — use a custom getAnalyzerType to include them.

import {isTypescript} from 'svelte-docinfo/source.ts';

jsdocOverloadSignatures
#

tsdoc.ts view source

jsdocOverloadSignatures(node: Node): JSDocSignature[]

The signatures of a JS function, method, or constructor's @overload tags, in order: its public signatures, which hide the implementation's. A variable declaration reads its function initializer's, whose JSDoc is the statement's. The checker honors @overload only in JS, so a .ts file's tags declare nothing, and never on an accessor, whose tags declare nothing either.

import {jsdocOverloadSignatures} from 'svelte-docinfo/tsdoc.ts';

jsdocParamTagDefault
#

tsdoc.ts view source

jsdocParamTagDefault(tag: JSDocParameterTag, sourceFile?: SourceFile): string | undefined

The default a bracketed @param tag writes (@param {number} [b=0] → 0), verbatim source text with quotes kept, matching an initializer's defaultValue. TypeScript's JSDoc parser reads the = … expression and discards it, so the text is sliced from the source: from the = after the name to the bracket that closes the name, skipping brackets and quoted strings inside the default ([b=[1, 2]], [b='a]']). A multi-line default drops each continuation line's * margin. A regex literal containing ] isn't recognized ([c=/]/] reads as /). Callers use it only for an omittable parameter: a bracket on a non-omittable one (a TS b: number with no ?) is ignored.

import {jsdocParamTagDefault} from 'svelte-docinfo/tsdoc.ts';

parameters

sourceFile

?: SourceFile = tag.getSourceFile()
#

returns

the default's text, or undefined when the tag writes none

LegacyExports
#

svelte-legacy.ts view source

What scanLegacyExports reads from an instance script.

import type {LegacyExports} from 'svelte-docinfo/svelte-legacy.ts';

members

props

: LegacyProp[]
#

Props, in source order of their exports.

accessors

: Set<string>
#

Exported names of accessors: export const, export function, export class, and export clauses over those bindings. svelte2tsx lists them in the props type as optional properties, but they're read from the component instance, never passed in.

LegacyProp
#

svelte-legacy.ts view source

A prop found by scanLegacyExports.

import type {LegacyProp} from 'svelte-docinfo/svelte-legacy.ts';

members

name

: string
#

Exported prop name (the rename in the export {a as b} form).

pos

: number
#

Offset of the export within the script content; the caller owns line mapping.

hasInitializer

: boolean
#

Whether the binding has an initializer, which makes the prop optional.

defaultValue

?: string
#

Verbatim source text of the initializer. Absent without one, and for an explicit undefined, which says the same as no default.

LegacyPropsAnchor
#

svelte-legacy.ts view source

The checker anchor for a legacy component's props, resolved by resolveLegacyPropsAnchor.

import type {LegacyPropsAnchor} from 'svelte-docinfo/svelte-legacy.ts';

members

type

: Type
#

The props type.

node

: Node
#

The node the type was read from, in the component's own virtual: the written type (a TS component) or the props object literal (a JS one, which has no type node).

kind

: "untyped" | "generated" | "authored"
#

Which props value shape node was read from:

  • 'untyped' — a bare object literal (a JS component, and a TS one whose exports are all untyped and uninitialized). Every property reads as required, so optionality comes from the script instead (LegacyProp.hasInitializer). Only the scanned prop names are props.
  • 'generated' — a type svelte2tsx wrote from the exports, whose properties carry their own optionality. It lists every export, accessors and type-only exports included, so only the scanned prop names are props.
  • 'authored' — the author's own $$Props, whose properties carry their own optionality. It can declare props the script never exports, so all of its properties are props except the accessors, which svelte2tsx intersects in beside it.

lexImports
#

dep-resolver.ts view source

lexImports(content: string, path?: string): string[]

Lex import specifiers from prepared content.

Parses with TypeScript (ts.createSourceFile, no binding or checking) rather than lexing as JS, so TypeScript syntax a JS lexer misreads as a regex or comparison (a! / b, Promise<Result<A, B>> => {}) can't derail it, and every ES form is seen, including export * as ns from (which TypeScript's lighter preProcessFile scanner misses).

Collects, in source order: static imports and re-exports (type-only ones included: import type, inline type specifiers, `export type {...} from, export type * from), import x = require()`, module augmentations (declare module '…' in a module), and anywhere in the file, dynamic import() with a string literal and import('…') types. CommonJS require() calls and non-literal import() are omitted.

For .svelte files, pass the svelte2tsx-transformed virtual content, not the raw .svelte source.

import {lexImports} from 'svelte-docinfo/dep-resolver.ts';

parameters

content

: string
#

prepared file content (TS/JS, or svelte2tsx virtual)

path

?: string
#

the file's path, when its extension should pick the parse: .tsx and .jsx content parses as TSX, since the TS parse reads JSX markup as type assertions and can lose the imports inside it; any other path, or none, parses as TS

returns

specifiers in source order

linkableAliasSymbol
#

typescript-extract-type-json.ts view source

linkableAliasSymbol(type: Type): Symbol | undefined

The alias symbol a type may be named by: type.aliasSymbol, except a svelte2tsx-generated one (isSvelte2tsxGeneratedAlias), which counts as no alias at all. Every alias read in the tree builder and in name recovery goes through it, so a generated alias is nameless throughout:

  • it never surfaces as a reference name or a union/intersection alias, since nothing exports it and it would be a dead lookup key
  • it doesn't pre-empt recovery: a project alias over it (type P = ComponentProps<typeof Button>) is alias-lost (isAliasLostType), so it registers, recovers at use sites through either channel, and warns alias_lost when neither can
  • what nothing recovers prints its structure (printType expands the alias), and a root whose flat string is the generated name keeps that structure (resolveTypeInfo)

The flat strings are the checker's rendering and keep the generated name.

import {linkableAliasSymbol} from 'svelte-docinfo/typescript-extract-type-json.ts';

loadFile
#

files.ts view source

loadFile(path: string, projectRoot: string): Promise<SourceFileInfo>

Load a single source file from disk.

Accepts either relative or absolute paths. Relative paths are resolved against projectRoot.

import {loadFile} from 'svelte-docinfo/files.ts';

parameters

path

: string
#

file path (relative to projectRoot or absolute)

projectRoot

: string
#

absolute path to project root

returns

source file info with content loaded

throws

  • Error - if the file cannot be read (e.g., missing or permission denied)

examples

const file = await loadFile('src/lib/math.ts', process.cwd()); // {id: '/abs/path/to/src/lib/math.ts', content: '...'}

loadTsconfig
#

typescript-program.ts view source

loadTsconfig(options?: LoadTsconfigOptions, log?: AnalysisLog): { compilerOptions: CompilerOptions; rootFileNames: string[]; }

Load and parse tsconfig.json into compiler options + initial file list.

Shared by createAnalysisProgram and createAnalysisLanguageService so tsconfig-resolution behavior stays identical across the two paths. Also useful directly when a caller needs only CompilerOptions (e.g., import resolution via ts.resolveModuleName) without the cost of building a full ts.Program.

Each call globs the tsconfig include to build rootFileNames; reuse the result rather than calling per resolve.

The config is located like tsc -p: options.tsconfig relative to projectRoot, walking up through parent directories when it isn't there. Relative paths inside it (extends, include, path-valued options) resolve against the config file's own directory, not projectRoot.

A config that can't be fully loaded throws rather than analyzing with a partial config: TypeScript reports a missing extends target as a diagnostic and carries on without the inherited options (lib, types, paths, rootDirs), so external types would silently degrade to any. SvelteKit's generated config is the common case ($app/tsconfig, or .svelte-kit/tsconfig.json before SvelteKit 3) — it exists only after svelte-kit sync. Option-level diagnostics (an unknown option, a bad value) and an include matching no files don't throw: TypeScript still applies the rest of the config, and the project's own typecheck reports them.

Under tsconfig: false no file is read: the options are DEFAULT_COMPILER_OPTIONS with options.compilerOptions merged on top, and the config contributes no roots. options.rootFileNames then replaces or filters the roots either way (see RootFileNames).

import {loadTsconfig} from 'svelte-docinfo/typescript-program.ts';

throws

  • Error - if tsconfig.json (or the file named by options.tsconfig) is not found or fails to parse, or a config in its extends chain is missing or fails to parse. A missing SvelteKit-generated target adds a hint to run svelte-kit sync.

LoadTsconfigOptions
#

typescript-program.ts view source

Base configuration shared by every entry point in this module.

projectRoot + tsconfig + compilerOptions together drive loadTsconfig, which is also exposed publicly. AnalysisProgramOptions and AnalysisLanguageServiceOptions extend this with their own fields.

import type {LoadTsconfigOptions} from 'svelte-docinfo/typescript-program.ts';

members

projectRoot

?: string = process.cwd()
#

Absolute path to project root directory.

tsconfig

?: string | false = 'tsconfig.json'
#

Path to tsconfig.json, relative to projectRoot; parent directories are searched when it isn't there. Any config file name works, jsconfig.json included.

false analyzes without a config file: no lookup runs, the compiler options are DEFAULT_COMPILER_OPTIONS with compilerOptions merged on top, and there are no config roots. It's an explicit choice, never a fallback — a config that's named or defaulted and can't be found still throws.

compilerOptions

?: CompilerOptions
#

Compiler options merged on top of those parsed from tsconfig.json (per-key override; user-supplied keys win), or on top of DEFAULT_COMPILER_OPTIONS under tsconfig: false. Does not by itself bypass the config file requirement — without tsconfig: false, loadTsconfig still throws when no config file is found.

rootFileNames

?: RootFileNames = the tsconfig's roots
#

The program's root files beyond the analyzed ones, replacing the roots the tsconfig's files/include produce (see RootFileNames).

logo_svelte_docinfo
#

logo.ts view source

{ label: string; fill: string; paths: { d: string; }[]; } import {logo_svelte_docinfo} from 'svelte-docinfo/logo.ts';

MalformedTagDiagnostic
#

diagnostics.ts view source

value + type

A JSDoc tag whose text doesn't parse as the tag's form, so it documents nothing.

Today only @cssprop (@cssproperty): its text names no custom property (@cssprop card_width - …, a name without --; @cssprop --a: …; an unclosed {…} or […]; an empty tag). Emitted on a Svelte component's doc comment, at the tag's line; on any other declaration the tag warns misplaced_tag instead, whether or not it parses. The tag is dropped.

Always warning, query-time category.

import {MalformedTagDiagnostic} from 'svelte-docinfo/diagnostics.ts';

inheritance

extends: SchemaStrictObjectOutput<typeof MalformedTagDiagnosticEntries>

members

kind

: "malformed_tag"
#

tagName

: "cssprop"
#

The tag name without the @ prefix; a synonym reports its canonical name.

declarationName

: string
#

Name of the declaration whose doc comment carries the tag.

file

: string
#

File path relative to project root (no leading slash, no ./ prefix).

Normalized at every public API boundary — session.setFile/setFiles (ingest-time), session.query (query-time, via analyzeCore), and the one-shot wrappers analyze / analyzeFromFiles. Producers inside the pipeline may write absolute or virtual paths (e.g., Foo.svelte.__svelte2tsx__.ts); normalization rewrites them to project-relative form before they reach consumers.

The exception is discovery — discoverSourceFiles / discoverFromExports return their diagnostics unnormalized, since they run before any session exists. Their file is already project-root-relative, but message can embed an absolute path (an fs error names the file it failed on), so a consumer wiring discovery up itself owns the normalizeDiagnosticPaths call — analyzeFromFiles and the Vite plugin both make it before merging.

The absolute form is the one to write. Normalization deliberately leaves an already-relative path alone (relativizing it would resolve against cwd), so a producer writing a ModuleJson.path — relative to sourceRoot, a different base — passes through untouched and publishes the same file under a second name. Absolute is what the pass can actually correct.

message

: string
#

Human-readable description of the issue.

severity

: "error" | "warning"
#

line

?: number
#

Line number (1-based), absent if location unavailable.

column

?: number
#

Column number (1-based), absent if location unavailable.

MalformedTagDiagnosticInput
#

diagnostics.ts view source

The input MalformedTagDiagnostic parses, with any field it defaults optional.

import type {MalformedTagDiagnosticInput} from 'svelte-docinfo/diagnostics.ts';

inheritance

extends: SchemaStrictObjectInput<typeof MalformedTagDiagnosticEntries>

members

kind

: "malformed_tag"
#

tagName

: "cssprop"
#

The tag name without the @ prefix; a synonym reports its canonical name.

declarationName

: string
#

Name of the declaration whose doc comment carries the tag.

file

: string
#

File path relative to project root (no leading slash, no ./ prefix).

Normalized at every public API boundary — session.setFile/setFiles (ingest-time), session.query (query-time, via analyzeCore), and the one-shot wrappers analyze / analyzeFromFiles. Producers inside the pipeline may write absolute or virtual paths (e.g., Foo.svelte.__svelte2tsx__.ts); normalization rewrites them to project-relative form before they reach consumers.

The exception is discovery — discoverSourceFiles / discoverFromExports return their diagnostics unnormalized, since they run before any session exists. Their file is already project-root-relative, but message can embed an absolute path (an fs error names the file it failed on), so a consumer wiring discovery up itself owns the normalizeDiagnosticPaths call — analyzeFromFiles and the Vite plugin both make it before merging.

The absolute form is the one to write. Normalization deliberately leaves an already-relative path alone (relativizing it would resolve against cwd), so a producer writing a ModuleJson.path — relative to sourceRoot, a different base — passes through untouched and publishes the same file under a second name. Absolute is what the pass can actually correct.

message

: string
#

Human-readable description of the issue.

severity

: "error" | "warning"
#

line

?: number
#

Line number (1-based), absent if location unavailable.

column

?: number
#

Column number (1-based), absent if location unavailable.

mapConcurrent
#

concurrency.ts view source

mapConcurrent<T, R>(items: readonly T[], concurrency: number, fn: (item: T, index: number) => Promise<R>): Promise<R[]>

Maps over items with a bounded number of in-flight promises, preserving input order.

Fail-fast: when fn rejects, the outer promise rejects with that error and idle workers stop pulling from the queue (already-in-flight fn calls run to completion — there's no AbortSignal plumbing). Subsequent rejections from in-flight calls are swallowed by Promise.all (only the first wins), so a misbehaving fn can't surface a second error after the function returns.

import {mapConcurrent} from 'svelte-docinfo/concurrency.ts';

parameters

items

: readonly T[]
#

input array

concurrency

: number
#

maximum number of concurrent operations

fn

: (item: T, index: number) => Promise<R>
#

mapping function (receives item and index)

returns

array of results in input order

mapDistToSource
#

exports.ts view source

mapDistToSource(distPath: string, condition: string, options: { distDir: string; sourceDir: string; }): string | null

Map a dist file path to its source file path.

Replaces the dist directory prefix with the source directory and maps file extensions based on the export condition.

import {mapDistToSource} from 'svelte-docinfo/exports.ts';

parameters

distPath

: string
#

the dist path from exports (e.g., "./dist/index.js")

condition

: string
#

the export condition (e.g., "default", "svelte", "types")

options

: { distDir: string; sourceDir: string; }
#

mapping configuration

returns

source path relative to project root, or null if not mappable

MAX_FILE_CONCURRENCY
#

MAX_RESOLVE_CONCURRENCY
#

MemberJson
#

types.ts view source

value + type

also exported from index.ts

type FunctionMemberJson | VariableMemberJson | ConstructorMemberJson

Metadata for a nested declaration within a class, interface, type, or enum.

Discriminated union on kind with 3 variants: FunctionMemberJson, VariableMemberJson, ConstructorMemberJson. Use isKind (in declaration-helpers.ts) to narrow, or check member.kind directly.

Does not include fields that exist on declarations but not on members (extends, externalTypes, implements, props, alsoExportedFrom, aliasOf).

Nesting is exactly one level deep — members never contain their own members.

import {MemberJson} from 'svelte-docinfo/types.ts';

MemberJsonBuild
#

declaration-build.ts view source

Permissive type for constructing members incrementally before schema validation.

Used by internal analysis functions in typescript-extract-*.ts that build members by mutating a plain object. The discriminated union schema (MemberJson) validates the final shape at the parseModuleJson boundary.

Mirrors DeclarationJsonBuild for the same reason: construction sites determine kind at runtime, so TypeScript can't narrow the union during incremental field assignment.

import type {MemberJsonBuild} from 'svelte-docinfo/declaration-build.ts';

members

name

?: string
#
#

docComment

?: string
#

typeSignature

?: string
#

modifiers

?: DeclarationModifier[]
#

sourceLine

?: number
#

genericParams

?: GenericParamJsonInput[]
#

parameters

?: ParameterJsonInput[]
#

returnType

?: string
#

returnTypeInfo

?: TypeJson
#

returnPredicate

?: ReturnPredicateJsonInput
#

thisType

?: string
#

thisTypeInfo

?: TypeJson
#

returnDescription

?: string
#

overloads

?: OverloadJsonInput[]
#

examples

?: string[]
#

deprecatedMessage

?: string
#

internalMessage

?: string
#

seeAlso

?: string[]
#

throws

?: ThrowsJsonInput[]
#

since

?: string
#

mutates

?: Record<string, string>
#

reactivity

?: Reactivity
#

partial

?: boolean
#

optional

?: boolean
#

Whether the member has a ? token in its declaration. Function and variable members only.

property

?: boolean
#

Whether a function member is a function-typed property, not a method.

defaultValue

?: string
#

Default value documented via @default. Variable and function members only.

typeInfo

?: TypeJson
#

Structured type. Variable members only; see TypeJson.

MemberJsonInput
#

MemberKind
#

types.ts view source

value + type

also exported from index.ts

"function" | "variable" | "constructor"

type "function" | "variable" | "constructor"

The subset of declaration kinds that appear as nested members in classes, interfaces, and types.

Class members include constructors ('constructor'), methods ('function'), and properties/accessors ('variable'). Interface/type properties use the same kinds for property signatures, method signatures, index signatures, and call/construct signatures.

Every other DeclarationKind is top-level only; nesting is exactly one level deep.

import {MemberKind} from 'svelte-docinfo/types.ts';

memberNameText
#

typescript-extract-shared.ts view source

memberNameText(name: PropertyName): string | undefined

The output name for a member's property-name node: the unquoted text of an identifier or string/numeric literal (matching the symbol-based paths, where prop.getName() yields data-foo for a written 'data-foo'), or undefined for computed names (runtime-dependent; the symbol paths skip their __@-prefixed forms too).

import {memberNameText} from 'svelte-docinfo/typescript-extract-shared.ts';

mergeReExports
#

postprocess.ts view source

also exported from index.ts

mergeReExports(modules: ModuleJson[]): ModuleJson[]

Build alsoExportedFrom arrays from the modules' forward re-export edges.

Each module carries its same-name re-export edges as ModuleJson.reExports (collected in phase 1); this phase-2 pass inverts them onto the canonical declarations so both directions of the same fact are queryable. Edges whose canonical module or declaration is absent from modules are skipped — the forward entry remains without a back-link (see ReExportJson for the presence caveats).

Component-only fields on renamed component aliases (props, acceptsChildren, etc.) are populated separately by resolveComponentAliases — call it after this function. They split because they touch disjoint fields and have different inputs.

Pure: the input array and its objects are never mutated. Modules and declarations that gain no back-link flow through ===-equal (structural sharing), so a re-run over already-merged output returns the same object references. New re-exporters union with existing alsoExportedFrom entries (deduped + sorted), keeping repeated merges idempotent by content.

import {mergeReExports} from 'svelte-docinfo/postprocess.ts';

parameters

modules

: ModuleJson[]
#

the analyzed modules. Must be parsed ModuleJsons — wire JSON strips empty arrays, so run raw JSON through AnalyzeResultJson.parse first or reExports may be undefined

returns

a new array; declarations with new back-links are copies with alsoExportedFrom unioned, everything else is the input object

examples

// helpers.ts exports: foo, bar // index.ts does: export {foo, bar} from './helpers.js' // (so index.ts's ModuleJson carries reExports: // [{name: 'foo', module: 'helpers.ts'}, {name: 'bar', module: 'helpers.ts'}]) // const merged = mergeReExports(modules); // - helpers.ts foo declaration gets: alsoExportedFrom: ['index.ts'] // - helpers.ts bar declaration gets: alsoExportedFrom: ['index.ts']

MisplacedTagDiagnostic
#

diagnostics.ts view source

value + type

A JSDoc tag found somewhere it has no effect.

Two contexts emit this:

  • Non-primary overload signature — symbol-scope tags (@example, @deprecated, @internal, @since, @see, @throws, @mutates, @default, @nodocs) describe the function as a whole, not individual signatures. The primary signature's JSDoc feeds the parent declaration's symbol-level extraction; tags on non-primary overload signatures are silently dropped from output. This diagnostic surfaces them so authors can move them to the primary signature. @default and @nodocs are included even though overloads never carry a defaultValue or per-overload exclusion: their presence on a non-primary signature is always a misplacement.
  • Module comment — tags that only describe a declaration (@param, @returns, @mutates, @throws, @default, @nodocs, @cssprop) have no module-level meaning, so a @module comment's are dropped, one warning per tag name per comment. @nodocs applies to declarations and export statements; to omit a module from analysis, use exclude patterns instead. @param and @returns occur only here.
  • Non-component declaration — @cssprop (or @cssproperty, reported as 'cssprop') documents a Svelte component's CSS custom properties, so on any other exported declaration (a function, a <script module> export) it's dropped, one warning per declaration. Members, props, and parameters drop it silently.
import {MisplacedTagDiagnostic} from 'svelte-docinfo/diagnostics.ts';

inheritance

extends: SchemaStrictObjectOutput<typeof MisplacedTagDiagnosticEntries>

members

kind

: "misplaced_tag"
#

tagName

: "since" | "throws" | "mutates" | "default" | "example" | "deprecated" | "internal" | "see" | "nodocs" | "param" | "returns" | "cssprop"
#

The tag name without the @ prefix (e.g., 'example', 'deprecated'). A synonym reports its canonical name: @return as 'returns', @defaultValue as 'default'.

file

: string
#

File path relative to project root (no leading slash, no ./ prefix).

Normalized at every public API boundary — session.setFile/setFiles (ingest-time), session.query (query-time, via analyzeCore), and the one-shot wrappers analyze / analyzeFromFiles. Producers inside the pipeline may write absolute or virtual paths (e.g., Foo.svelte.__svelte2tsx__.ts); normalization rewrites them to project-relative form before they reach consumers.

The exception is discovery — discoverSourceFiles / discoverFromExports return their diagnostics unnormalized, since they run before any session exists. Their file is already project-root-relative, but message can embed an absolute path (an fs error names the file it failed on), so a consumer wiring discovery up itself owns the normalizeDiagnosticPaths call — analyzeFromFiles and the Vite plugin both make it before merging.

The absolute form is the one to write. Normalization deliberately leaves an already-relative path alone (relativizing it would resolve against cwd), so a producer writing a ModuleJson.path — relative to sourceRoot, a different base — passes through untouched and publishes the same file under a second name. Absolute is what the pass can actually correct.

message

: string
#

Human-readable description of the issue.

severity

: "error" | "warning"
#

functionName

?: string
#

Name of the enclosing symbol: the function or method whose overload carries the misplaced tag, or the declaration carrying a @cssprop. Absent for module-comment misplacements (no enclosing symbol).

line

?: number
#

Line number (1-based), absent if location unavailable.

column

?: number
#

Column number (1-based), absent if location unavailable.

MisplacedTagDiagnosticInput
#

diagnostics.ts view source

The input MisplacedTagDiagnostic parses, with any field it defaults optional.

import type {MisplacedTagDiagnosticInput} from 'svelte-docinfo/diagnostics.ts';

inheritance

extends: SchemaStrictObjectInput<typeof MisplacedTagDiagnosticEntries>

members

kind

: "misplaced_tag"
#

tagName

: "since" | "throws" | "mutates" | "default" | "example" | "deprecated" | "internal" | "see" | "nodocs" | "param" | "returns" | "cssprop"
#

The tag name without the @ prefix (e.g., 'example', 'deprecated'). A synonym reports its canonical name: @return as 'returns', @defaultValue as 'default'.

file

: string
#

File path relative to project root (no leading slash, no ./ prefix).

Normalized at every public API boundary — session.setFile/setFiles (ingest-time), session.query (query-time, via analyzeCore), and the one-shot wrappers analyze / analyzeFromFiles. Producers inside the pipeline may write absolute or virtual paths (e.g., Foo.svelte.__svelte2tsx__.ts); normalization rewrites them to project-relative form before they reach consumers.

The exception is discovery — discoverSourceFiles / discoverFromExports return their diagnostics unnormalized, since they run before any session exists. Their file is already project-root-relative, but message can embed an absolute path (an fs error names the file it failed on), so a consumer wiring discovery up itself owns the normalizeDiagnosticPaths call — analyzeFromFiles and the Vite plugin both make it before merging.

The absolute form is the one to write. Normalization deliberately leaves an already-relative path alone (relativizing it would resolve against cwd), so a producer writing a ModuleJson.path — relative to sourceRoot, a different base — passes through untouched and publishes the same file under a second name. Absolute is what the pass can actually correct.

message

: string
#

Human-readable description of the issue.

severity

: "error" | "warning"
#

functionName

?: string
#

Name of the enclosing symbol: the function or method whose overload carries the misplaced tag, or the declaration carrying a @cssprop. Absent for module-comment misplacements (no enclosing symbol).

line

?: number
#

Line number (1-based), absent if location unavailable.

column

?: number
#

Column number (1-based), absent if location unavailable.

ModuleAnalysis
#

declaration-build.ts view source

Result of analyzing a module (TypeScript or Svelte).

Produced by analyzeTypescriptModule and analyzeSvelteModule. Both analyzers return this same structure for uniform handling by analyzeModule in analyze-core.ts.

import type {ModuleAnalysis} from 'svelte-docinfo/declaration-build.ts';

inheritance

members

path

: string
#

Module path relative to source root.

dependencies

: string[]
#

Dependencies (other source modules this module imports). Empty if none.

dependents

: string[]
#

Dependents (other source modules that import this module). Empty if none.

ModuleDocFields
#

tsdoc.ts view source

Partial<Pick<ModuleJsonInput, "moduleComment" | "examples" | "deprecatedMessage" | "seeAlso" | "since" | "internalMessage">>

type Partial<Pick<ModuleJsonInput, "moduleComment" | "examples" | "deprecatedMessage" | "seeAlso" | "since" | "internalMessage">>

The ModuleJson fields a module comment populates.

import type {ModuleDocFields} from 'svelte-docinfo/tsdoc.ts';

members

moduleComment

?: string
#

The prose of the file-level comment, the one carrying a @module tag: its main text, with every tag line removed. Absent when the comment has no prose (a tag-only comment, or none at all).

The comment's tags parse as a declaration's do, into the fields below (examples, deprecatedMessage, seeAlso, since, internalMessage). Tags that only describe a declaration (@param, @returns, @mutates, @throws, @default, @nodocs) are dropped with a misplaced_tag warning, and unknown tags drop silently. For a Svelte file it comes from the instance <script>, the <script module>, or an HTML comment with a @module line, the first in that order whose comment populates any of these fields.

examples

?: string[]
#

Code examples from @example tags.

deprecatedMessage

?: string
#

Deprecation message from @deprecated tag.

seeAlso

?: string[]
#

Related items from @see tags, in raw TSDoc format.

since

?: string
#

Version introduced, from @since tag.

internalMessage

?: string
#

Internal-API marker from the @internal tag. Presence means the tag was written; an empty string is a bare tag with no trailing prose.

A marker, not an exclusion: @internal means "not stable public API" (TSDoc semantics) while the declaration, member, or prop stays documented — unlike @nodocs, which removes a declaration from output entirely (and is ignored on props and members).

ModuleExportsAnalysis
#

declaration-build.ts view source

Result of analyzing a module's exports.

Produced by analyzeExports in typescript-exports.ts.

import type {ModuleExportsAnalysis} from 'svelte-docinfo/declaration-build.ts';

members

moduleDoc

?: TsdocParsedComment
#

The parsed module-level comment, projected onto ModuleJson by toModuleDocFields. Always undefined for svelte2tsx virtual files — analyzeSvelteModule extracts Svelte module comments from the original source instead.

declarations

: DeclarationAnalysis[]
#

All exported declarations with @nodocs flags — consumer filters based on policy.

reExports

: ReExportJsonInput[]
#

Same-name re-exports. Published as ModuleJson.reExports and consumed by mergeReExports in phase 2 to build alsoExportedFrom arrays on canonical declarations. Unsorted here and may contain exact duplicates (Svelte default-slot re-keying) — ordering and dedup are applied at publication in analyze-core.ts.

starExports

: string[]
#

Star exports (export * from './module') — module paths that are fully re-exported.

externalReExports

: ExternalReExportJsonInput[]
#

Direct re-exports from external packages. Published as ModuleJson.externalReExports; unsorted here, sorted at publication.

externalStarExports

: string[]
#

External star exports (export * from 'pkg') — specifiers as written.

ModuleJson
#

types.ts view source

value + type

also exported from index.ts

Metadata for a source module — the top-level container in the data model.

analyze, analyzeFromFiles, and AnalysisSession.query return AnalyzeResultJson, whose modules is sorted by path (compareStrings). Each module contains its exported declarations, dependency graph, and optional moduleComment.

import {ModuleJson} from 'svelte-docinfo/types.ts';

inheritance

extends: SchemaStrictObjectOutput<typeof ModuleJsonEntries>

members

dependencies

: string[]
#

Modules this imports (paths relative to sourceRoot).

dependents

: string[]
#

Modules that import this (paths relative to sourceRoot).

starExports

: string[]
#

Modules fully re-exported via export * from './module'. Paths are relative to sourceRoot. Statement-level @nodocs suppresses the entry, like the other re-export encodings. `export type * from` is recorded like a value star — per-statement type-only-ness isn't captured — and each target appears once, however many statements name it.

Only modules that are themselves in the result appear. A star over a project module that emits nothing (gated, or outside the analyzed inputs) has no entry: the bindings it projects are documented in this module as the named re-exports the star stands for — declarations with aliasOf, or reExports entries for bindings whose canonical does emit — following ES star semantics (default doesn't project, a local export shadows, a name two stars disagree on is excluded). A binding such a module re-exports from a package is not recorded anywhere.

A star over a component that failed to transform names its partial placeholder module, whose bindings are unknown (resolveExportSurface reports it unresolved); one that emits nothing (gated, never supplied) is dropped.

reExports

: ReExportJson[]
#

Same-name re-exports in this module's source, sorted by name then module (names can collide — see ReExportJson). The forward view of alsoExportedFrom — see ReExportJson for the full contract (canonical resolution, Svelte default-slot naming, @nodocs suppression, presence caveats).

externalReExports

: ExternalReExportJson[]
#

Re-exports whose immediate target is an external package, sorted by name then specifier. See ExternalReExportJson for which forms are captured.

externalStarExports

: string[]
#

External modules fully re-exported via export * from 'pkg', as written (statement order, each specifier once). The projected names are unknown — the package isn't analyzed. Statement-level @nodocs suppresses the entry; unresolvable specifiers are skipped. A relative .svelte specifier is never an entry, whether or not its component has a virtual (see starExports).

partial

: boolean
#

Whether the module is a placeholder for a file that couldn't be analyzed.

Currently only set for Svelte files where svelte2tsx threw at ingest (the transform_failed diagnostic carries the error). Placeholder modules have declarations: [] and serve as a structural slot so the modules array reflects the full emitted (source-gated) set; consumers render them as "broken" entries.

examples

: string[]
#

Code examples from @example tags.

seeAlso

: string[]
#

Related items from @see tags, in raw TSDoc format.

path

: string
#

Path relative to sourceRoot (e.g., helpers.ts for the default SvelteKit src/lib layout). sourceRoot is configurable via createSourceOptions / the CLI --source-root flag — consumers with a custom layout (e.g., sourcePaths: ['src/lib', 'src/routes'], sourceRoot: 'src') see prefixes like lib/foo.ts here.

Exported declarations from this module.

deprecatedMessage

?: string
#

Deprecation message from @deprecated tag.

since

?: string
#

Version introduced, from @since tag.

internalMessage

?: string
#

Internal-API marker from the @internal tag. Presence means the tag was written; an empty string is a bare tag with no trailing prose.

A marker, not an exclusion: @internal means "not stable public API" (TSDoc semantics) while the declaration, member, or prop stays documented — unlike @nodocs, which removes a declaration from output entirely (and is ignored on props and members).

moduleComment

?: string
#

The prose of the file-level comment, the one carrying a @module tag: its main text, with every tag line removed. Absent when the comment has no prose (a tag-only comment, or none at all).

The comment's tags parse as a declaration's do, into the fields below (examples, deprecatedMessage, seeAlso, since, internalMessage). Tags that only describe a declaration (@param, @returns, @mutates, @throws, @default, @nodocs) are dropped with a misplaced_tag warning, and unknown tags drop silently. For a Svelte file it comes from the instance <script>, the <script module>, or an HTML comment with a @module line, the first in that order whose comment populates any of these fields.

ModuleJsonInput
#

types.ts view source

The input ModuleJson parses, with any field it defaults optional.

import type {ModuleJsonInput} from 'svelte-docinfo/types.ts';

inheritance

extends: SchemaStrictObjectInput<typeof ModuleJsonEntries>

members

path

: string
#

Path relative to sourceRoot (e.g., helpers.ts for the default SvelteKit src/lib layout). sourceRoot is configurable via createSourceOptions / the CLI --source-root flag — consumers with a custom layout (e.g., sourcePaths: ['src/lib', 'src/routes'], sourceRoot: 'src') see prefixes like lib/foo.ts here.

dependencies

?: string[]
#

Modules this imports (paths relative to sourceRoot).

dependents

?: string[]
#

Modules that import this (paths relative to sourceRoot).

starExports

?: string[]
#

Modules fully re-exported via export * from './module'. Paths are relative to sourceRoot. Statement-level @nodocs suppresses the entry, like the other re-export encodings. `export type * from` is recorded like a value star — per-statement type-only-ness isn't captured — and each target appears once, however many statements name it.

Only modules that are themselves in the result appear. A star over a project module that emits nothing (gated, or outside the analyzed inputs) has no entry: the bindings it projects are documented in this module as the named re-exports the star stands for — declarations with aliasOf, or reExports entries for bindings whose canonical does emit — following ES star semantics (default doesn't project, a local export shadows, a name two stars disagree on is excluded). A binding such a module re-exports from a package is not recorded anywhere.

A star over a component that failed to transform names its partial placeholder module, whose bindings are unknown (resolveExportSurface reports it unresolved); one that emits nothing (gated, never supplied) is dropped.

reExports

?: ReExportJsonInput[]
#

Same-name re-exports in this module's source, sorted by name then module (names can collide — see ReExportJson). The forward view of alsoExportedFrom — see ReExportJson for the full contract (canonical resolution, Svelte default-slot naming, @nodocs suppression, presence caveats).

externalReExports

?: ExternalReExportJsonInput[]
#

Re-exports whose immediate target is an external package, sorted by name then specifier. See ExternalReExportJson for which forms are captured.

externalStarExports

?: string[]
#

External modules fully re-exported via export * from 'pkg', as written (statement order, each specifier once). The projected names are unknown — the package isn't analyzed. Statement-level @nodocs suppresses the entry; unresolvable specifiers are skipped. A relative .svelte specifier is never an entry, whether or not its component has a virtual (see starExports).

partial

?: boolean
#

Whether the module is a placeholder for a file that couldn't be analyzed.

Currently only set for Svelte files where svelte2tsx threw at ingest (the transform_failed diagnostic carries the error). Placeholder modules have declarations: [] and serve as a structural slot so the modules array reflects the full emitted (source-gated) set; consumers render them as "broken" entries.

examples

?: string[]
#

Code examples from @example tags.

deprecatedMessage

?: string
#

Deprecation message from @deprecated tag.

seeAlso

?: string[]
#

Related items from @see tags, in raw TSDoc format.

since

?: string
#

Version introduced, from @since tag.

internalMessage

?: string
#

Internal-API marker from the @internal tag. Presence means the tag was written; an empty string is a bare tag with no trailing prose.

A marker, not an exclusion: @internal means "not stable public API" (TSDoc semantics) while the declaration, member, or prop stays documented — unlike @nodocs, which removes a declaration from output entirely (and is ignored on props and members).

Exported declarations from this module.

moduleComment

?: string
#

The prose of the file-level comment, the one carrying a @module tag: its main text, with every tag line removed. Absent when the comment has no prose (a tag-only comment, or none at all).

The comment's tags parse as a declaration's do, into the fields below (examples, deprecatedMessage, seeAlso, since, internalMessage). Tags that only describe a declaration (@param, @returns, @mutates, @throws, @default, @nodocs) are dropped with a misplaced_tag warning, and unknown tags drop silently. For a Svelte file it comes from the instance <script>, the <script module>, or an HTML comment with a @module line, the first in that order whose comment populates any of these fields.

ModuleSkippedDiagnostic
#

diagnostics.ts view source

value + type

Module was skipped during the analysis pass.

Always warning severity — the rest of the analysis still runs and the module's absence in modules reflects the skip. Reasons:

  • not_in_program — the file wasn't in the ts.Program (race between session ingest and query, or virtual file missing for a .svelte)
  • no_analyzer — file extension didn't match any analyzer
  • requires_program — Svelte file reached the non-Svelte dispatcher (caller should use the session API instead of analyzeModule directly)

Discovery-time file-read failures are a separate kind: module_unreadable.

import {ModuleSkippedDiagnostic} from 'svelte-docinfo/diagnostics.ts';

inheritance

extends: SchemaStrictObjectOutput<typeof ModuleSkippedDiagnosticEntries>

members

kind

: "module_skipped"
#

reason

: "not_in_program" | "no_analyzer" | "requires_program"
#

Reason the module was skipped.

file

: string
#

File path relative to project root (no leading slash, no ./ prefix).

Normalized at every public API boundary — session.setFile/setFiles (ingest-time), session.query (query-time, via analyzeCore), and the one-shot wrappers analyze / analyzeFromFiles. Producers inside the pipeline may write absolute or virtual paths (e.g., Foo.svelte.__svelte2tsx__.ts); normalization rewrites them to project-relative form before they reach consumers.

The exception is discovery — discoverSourceFiles / discoverFromExports return their diagnostics unnormalized, since they run before any session exists. Their file is already project-root-relative, but message can embed an absolute path (an fs error names the file it failed on), so a consumer wiring discovery up itself owns the normalizeDiagnosticPaths call — analyzeFromFiles and the Vite plugin both make it before merging.

The absolute form is the one to write. Normalization deliberately leaves an already-relative path alone (relativizing it would resolve against cwd), so a producer writing a ModuleJson.path — relative to sourceRoot, a different base — passes through untouched and publishes the same file under a second name. Absolute is what the pass can actually correct.

message

: string
#

Human-readable description of the issue.

severity

: "error" | "warning"
#

line

?: number
#

Line number (1-based), absent if location unavailable.

column

?: number
#

Column number (1-based), absent if location unavailable.

ModuleSkippedDiagnosticInput
#

diagnostics.ts view source

The input ModuleSkippedDiagnostic parses, with any field it defaults optional.

import type {ModuleSkippedDiagnosticInput} from 'svelte-docinfo/diagnostics.ts';

inheritance

extends: SchemaStrictObjectInput<typeof ModuleSkippedDiagnosticEntries>

members

kind

: "module_skipped"
#

reason

: "not_in_program" | "no_analyzer" | "requires_program"
#

Reason the module was skipped.

file

: string
#

File path relative to project root (no leading slash, no ./ prefix).

Normalized at every public API boundary — session.setFile/setFiles (ingest-time), session.query (query-time, via analyzeCore), and the one-shot wrappers analyze / analyzeFromFiles. Producers inside the pipeline may write absolute or virtual paths (e.g., Foo.svelte.__svelte2tsx__.ts); normalization rewrites them to project-relative form before they reach consumers.

The exception is discovery — discoverSourceFiles / discoverFromExports return their diagnostics unnormalized, since they run before any session exists. Their file is already project-root-relative, but message can embed an absolute path (an fs error names the file it failed on), so a consumer wiring discovery up itself owns the normalizeDiagnosticPaths call — analyzeFromFiles and the Vite plugin both make it before merging.

The absolute form is the one to write. Normalization deliberately leaves an already-relative path alone (relativizing it would resolve against cwd), so a producer writing a ModuleJson.path — relative to sourceRoot, a different base — passes through untouched and publishes the same file under a second name. Absolute is what the pass can actually correct.

message

: string
#

Human-readable description of the issue.

severity

: "error" | "warning"
#

line

?: number
#

Line number (1-based), absent if location unavailable.

column

?: number
#

Column number (1-based), absent if location unavailable.

ModuleSourceOptions
#

source-config.ts view source

also exported from index.ts

Configuration for module source detection and path extraction.

Uses proper path semantics with projectRoot as the base for all path operations. Paths are matched using startsWith rather than substring search, which correctly handles nested directories without special heuristics.

import type {ModuleSourceOptions} from 'svelte-docinfo/source-config.ts';

members

projectRoot

: string
#

Path to the project root directory.

All sourcePaths are relative to this. Typically process.cwd(). Normalized (resolved to absolute, posixified to forward slashes, trailing slash stripped) by normalizeSourceOptions, which returns a new options object. Internal callers (isSource, extractPath) assume this is already POSIX form — construct via createSourceOptions / normalizeSourceOptions rather than building ModuleSourceOptions literals by hand on Windows.

'/home/user/my-project'

sourcePaths

: string[]
#

Source directory paths to include, relative to projectRoot.

Absolute entries are accepted when they resolve inside projectRoot and are stored root-relative; an entry resolving outside it throws (a root-anchored '/src/lib' is taken as filesystem-absolute, not shorthand — the error hints to drop the slash). Normalized (./.. segments collapsed, trailing slashes stripped) by normalizeSourceOptions, which returns a new options object.

['src/lib'] // single source directory
['src/lib', 'src/routes'] // multiple directories

sourceRoot

?: string
#

Source root for extracting relative module paths, relative to projectRoot.

Normalized like sourcePaths entries (absolute-inside-root accepted and stored root-relative, ./.. collapsed — so '.' becomes '', trailing slashes stripped, out-of-root throws) by normalizeSourceOptions, which returns a new options object.

When omitted:

  • Single sourcePath: defaults to that path
  • Multiple sourcePaths: auto-derived as the longest common directory prefix (or '' when paths share no common prefix — produces project-relative module paths)
'src/lib' // module paths like 'foo.ts', 'utils/bar.ts'
'src' // module paths like 'lib/foo.ts', 'routes/page.svelte'
'' // or '.': module paths stay project-relative, e.g. 'src/lib/foo.ts'

exclude

: string[] = `['**\/*.{test,spec}.{ts,mts,tsx,js,mjs,jsx}', '**\/internal/**']`
#

Glob patterns to exclude from analysis, relative to projectRoot; an absolute pattern inside the root relativizes at normalizeSourceOptions, an out-of-root one throws.

Applied at both stages of the pipeline:

  • Discovery time by globFiles/discoverFromExports, preventing matched files from being loaded.
  • Analysis time by isSource() against relative(projectRoot, absolutePath), which gates both the emitted module set (query()) and dependency edges.

Beneath it, the always-on baseline (node_modules + dot-directories below a matched source path — see hasBaselineExcludedSegment) applies independently; overriding exclude can't strip it.

The defaults exclude tests and internal/ directories — the src/lib/internal/ convention: internal modules ship in the package for public modules to import (typically paired with an "./internal/*": null package.json exports entry blocking consumer imports), but aren't part of the documented surface. The override surfaces accept a (defaults) => patterns callback (see ExcludeOption) so extending the defaults doesn't require restating them; this normalized field is always a plain array.

analyzeFromFiles and the Vite plugin accept a top-level exclude that replaces this field (no merge).

Compiled to a matcher once per options object via picomatch and cached by reference; mutating this array post-isSource-call has no effect — pass through normalizeSourceOptions (which returns a fresh object) or otherwise build a new options object to apply changes.

getAnalyzerType

: (path: string) => AnalyzerType | null = `getDefaultAnalyzer` (by file extension)
#

Determine which analyzer to use for a file path.

Called wherever the pipeline classifies a path (ingest, every isSource check, context-closure candidates), so keep it cheap and pure. Return an AnalyzerType (see there for what each analyzes) or null to skip.

Extend the default table by delegating to getDefaultAnalyzer (exported from the main barrel) for everything but the added case — restating the table drifts when it grows.

// Add MDsveX support getAnalyzerType: (path) => (path.endsWith('.svx') ? 'svelte' : getDefaultAnalyzer(path))
// Include .d.ts files (the default excludes them) getAnalyzerType: (path) => (path.endsWith('.d.ts') ? 'typescript' : getDefaultAnalyzer(path))

examples

const options = createSourceOptions(process.cwd(), { sourcePaths: ['src/lib', 'src/routes'], sourceRoot: 'src', });

ModuleUnreadableDiagnostic
#

diagnostics.ts view source

value + type

File discovered via package.json exports exists but couldn't be read.

Always error severity — discovery-time, emitted by discoverFromExports when readFile fails (permission denied, FS error). Distinct from module_skipped so severity is a stable per-kind property and downstream consumers can route discovery failures separately from analysis-pass skips.

import {ModuleUnreadableDiagnostic} from 'svelte-docinfo/diagnostics.ts';

inheritance

extends: SchemaStrictObjectOutput<typeof ModuleUnreadableDiagnosticEntries>

members

kind

: "module_unreadable"
#

file

: string
#

File path relative to project root (no leading slash, no ./ prefix).

Normalized at every public API boundary — session.setFile/setFiles (ingest-time), session.query (query-time, via analyzeCore), and the one-shot wrappers analyze / analyzeFromFiles. Producers inside the pipeline may write absolute or virtual paths (e.g., Foo.svelte.__svelte2tsx__.ts); normalization rewrites them to project-relative form before they reach consumers.

The exception is discovery — discoverSourceFiles / discoverFromExports return their diagnostics unnormalized, since they run before any session exists. Their file is already project-root-relative, but message can embed an absolute path (an fs error names the file it failed on), so a consumer wiring discovery up itself owns the normalizeDiagnosticPaths call — analyzeFromFiles and the Vite plugin both make it before merging.

The absolute form is the one to write. Normalization deliberately leaves an already-relative path alone (relativizing it would resolve against cwd), so a producer writing a ModuleJson.path — relative to sourceRoot, a different base — passes through untouched and publishes the same file under a second name. Absolute is what the pass can actually correct.

message

: string
#

Human-readable description of the issue.

severity

: "error" | "warning"
#

line

?: number
#

Line number (1-based), absent if location unavailable.

column

?: number
#

Column number (1-based), absent if location unavailable.

ModuleUnreadableDiagnosticInput
#

diagnostics.ts view source

The input ModuleUnreadableDiagnostic parses, with any field it defaults optional.

import type {ModuleUnreadableDiagnosticInput} from 'svelte-docinfo/diagnostics.ts';

inheritance

extends: SchemaStrictObjectInput<typeof ModuleUnreadableDiagnosticEntries>

members

kind

: "module_unreadable"
#

file

: string
#

File path relative to project root (no leading slash, no ./ prefix).

Normalized at every public API boundary — session.setFile/setFiles (ingest-time), session.query (query-time, via analyzeCore), and the one-shot wrappers analyze / analyzeFromFiles. Producers inside the pipeline may write absolute or virtual paths (e.g., Foo.svelte.__svelte2tsx__.ts); normalization rewrites them to project-relative form before they reach consumers.

The exception is discovery — discoverSourceFiles / discoverFromExports return their diagnostics unnormalized, since they run before any session exists. Their file is already project-root-relative, but message can embed an absolute path (an fs error names the file it failed on), so a consumer wiring discovery up itself owns the normalizeDiagnosticPaths call — analyzeFromFiles and the Vite plugin both make it before merging.

The absolute form is the one to write. Normalization deliberately leaves an already-relative path alone (relativizing it would resolve against cwd), so a producer writing a ModuleJson.path — relative to sourceRoot, a different base — passes through untouched and publishes the same file under a second name. Absolute is what the pass can actually correct.

message

: string
#

Human-readable description of the issue.

severity

: "error" | "warning"
#

line

?: number
#

Line number (1-based), absent if location unavailable.

column

?: number
#

Column number (1-based), absent if location unavailable.

namedSymbolName
#

typescript-extract-type-json.ts view source

namedSymbolName(type: Type): string | undefined

The type's non-anonymous symbol name (__type/__object/__function mark anonymous shapes). The one anonymity rule shared by the recovery gate here, the alias-lost predicate (isAliasLostType), and the registry's safety-gate walk (typescript-alias-registry.ts) — never ObjectFlags.Anonymous, which real inferred schema outputs (zod's and valibot's are Mapped | Instantiated) don't carry.

import {namedSymbolName} from 'svelte-docinfo/typescript-extract-type-json.ts';

NamespaceDeclarationJson
#

types.ts view source

value + type

also exported from index.ts

A namespace re-export binding: export * as ns from './x'.

Carries no inline members — module points to the source module whose declarations are projected under this name. Consumers that want to render ns.a can deref by reading the source module's declarations array.

Over a .svelte file with no svelte2tsx virtual (its transform failed, or it was never supplied) the binding is partial: its members are unknown, and module names the component's partial placeholder, or a module the result lacks when the component emits nothing.

import {NamespaceDeclarationJson} from 'svelte-docinfo/types.ts';

inheritance

extends: SchemaStrictObjectOutput<typeof NamespaceDeclarationJsonEntries>

members

kind

: "namespace"
#

module

: string
#

Source module path (relative to sourceRoot) projected under this binding.

alsoExportedFrom

: string[]
#

Module paths (relative to sourceRoot) that re-export this declaration under the same name. The canonical declaration lives in this module's declarations array; these paths are additional import locations for the same thing.

The same edges appear from the re-exporting side as ModuleJson.reExports — use that when asking "what does this module re-export" instead of inverting these arrays. The two can disagree at the margins: a reExports entry whose canonical declaration is @nodocs (or whose module isn't in the analyzed set) has no back-link here.

Consumer note: To build a complete re-export map, scan two fields:

  1. alsoExportedFrom on each declaration — same-name re-exports
  2. aliasOf on declarations — renamed re-exports (separate declarations)

partial

: boolean
#

Whether extraction failed partway through, leaving some fields missing (e.g., typeSignature, parameters).

examples

: string[]
#

Code examples from @example tags.

seeAlso

: string[]
#

Related items from @see tags, in raw TSDoc format.

throws

: ThrowsJson[]
#

Exceptions from @throws tags. type is the tag's written type, and typeInfo its structured form, present for a braced type (@throws {A<B>}) that isn't the whole story as text (see TypeJson); an unbraced tag's leading word never has one, nor does a tag in a component's HTML @component comment, which is read as text.

name

: string
#

The exported name. Always populated. The default-export slot is named 'default', except a Svelte component, which takes its filename-derived name ('X' for X.svelte) — 'default' is the symbol's actual name in JS (import {default as X} and ns.default both expose it directly), and import X from 'mod' is sugar for import {default as X}. Consumers branch on name === 'default' to render the sugar form when desired.

modifiers

: ("public" | "protected" | "readonly" | "static" | "abstract" | "getter" | "setter")[]
#

TypeScript modifiers like readonly, static, or protected.

genericParams

: GenericParamJson[]
#

Generic type parameters like <T, U>.

aliasOf

?: { module: string; name: string; }
#

For renamed re-exports (export {foo as bar}), points to the original declaration. This declaration's name is the alias; aliasOf.name is the original name.

For renames out of the default slot (export {default as bar} from './x' where ./x is export default ...), aliasOf.name is 'default' — the canonical's actual symbol name. Consumers locate the canonical by (aliasOf.module, aliasOf.name).

Svelte component exception: when the source is a .svelte file (e.g., export {default as Foo} from './X.svelte'), the canonical's name is the component name (derived from the filename), so aliasOf.name is the component name ('X'), NOT 'default'. Consumers that branch on aliasOf.name === 'default' to detect default-rename should additionally check whether aliasOf.module ends with .svelte.

Different from alsoExportedFrom: aliases create new API surface names, while alsoExportedFrom tracks additional import paths for the same name.

A type-only rename of a value (export type {someConst as c} from './x') synthesizes a normal alias — declarations carry no type-only marker.

deprecatedMessage

?: string
#

Deprecation message from @deprecated tag.

since

?: string
#

Version introduced, from @since tag.

internalMessage

?: string
#

Internal-API marker from the @internal tag. Presence means the tag was written; an empty string is a bare tag with no trailing prose.

A marker, not an exclusion: @internal means "not stable public API" (TSDoc semantics) while the declaration, member, or prop stays documented — unlike @nodocs, which removes a declaration from output entirely (and is ignored on props and members).

mutates

?: Record<string, string>
#

Mutation documentation from @mutates tags (non-standard), mapping keys to descriptions.

Keys are intentionally unvalidated — typically a parameter name, but authors may also use compound paths (this.foo, obj.field) or multi-word external state references. Backticks are stripped from keys so `` a `` and a normalize to one key; an empty-string value is a bare tag with no description. The schema accepts any string key so consumers can render whatever the author wrote.

On a component prop it declares the component's mutation contract for the value it's handed: the component writes into the prop's object or array in place (@mutates items - appends the selected entry, @mutates options.cache - fills on first render). Reassigning a prop is not a mutation in this sense (bindable covers it), though a $bindable prop can carry both.

docComment

?: string
#

JSDoc/TSDoc comment.

typeSignature

?: string
#

Full TypeScript type signature.

sourceLine

?: number
#

1-based line in the source file, a positive integer. Synthesized aliases (see aliasOf) carry the local export specifier's line, not the canonical's.

NamespaceDeclarationJsonInput
#

types.ts view source

The input NamespaceDeclarationJson parses, with any field it defaults optional.

import type {NamespaceDeclarationJsonInput} from 'svelte-docinfo/types.ts';

inheritance

extends: SchemaStrictObjectInput<typeof NamespaceDeclarationJsonEntries>

members

kind

: "namespace"
#

module

: string
#

Source module path (relative to sourceRoot) projected under this binding.

name

: string
#

The exported name. Always populated. The default-export slot is named 'default', except a Svelte component, which takes its filename-derived name ('X' for X.svelte) — 'default' is the symbol's actual name in JS (import {default as X} and ns.default both expose it directly), and import X from 'mod' is sugar for import {default as X}. Consumers branch on name === 'default' to render the sugar form when desired.

alsoExportedFrom

?: string[]
#

Module paths (relative to sourceRoot) that re-export this declaration under the same name. The canonical declaration lives in this module's declarations array; these paths are additional import locations for the same thing.

The same edges appear from the re-exporting side as ModuleJson.reExports — use that when asking "what does this module re-export" instead of inverting these arrays. The two can disagree at the margins: a reExports entry whose canonical declaration is @nodocs (or whose module isn't in the analyzed set) has no back-link here.

Consumer note: To build a complete re-export map, scan two fields:

  1. alsoExportedFrom on each declaration — same-name re-exports
  2. aliasOf on declarations — renamed re-exports (separate declarations)

aliasOf

?: { module: string; name: string; }
#

For renamed re-exports (export {foo as bar}), points to the original declaration. This declaration's name is the alias; aliasOf.name is the original name.

For renames out of the default slot (export {default as bar} from './x' where ./x is export default ...), aliasOf.name is 'default' — the canonical's actual symbol name. Consumers locate the canonical by (aliasOf.module, aliasOf.name).

Svelte component exception: when the source is a .svelte file (e.g., export {default as Foo} from './X.svelte'), the canonical's name is the component name (derived from the filename), so aliasOf.name is the component name ('X'), NOT 'default'. Consumers that branch on aliasOf.name === 'default' to detect default-rename should additionally check whether aliasOf.module ends with .svelte.

Different from alsoExportedFrom: aliases create new API surface names, while alsoExportedFrom tracks additional import paths for the same name.

A type-only rename of a value (export type {someConst as c} from './x') synthesizes a normal alias — declarations carry no type-only marker.

partial

?: boolean
#

Whether extraction failed partway through, leaving some fields missing (e.g., typeSignature, parameters).

examples

?: string[]
#

Code examples from @example tags.

deprecatedMessage

?: string
#

Deprecation message from @deprecated tag.

seeAlso

?: string[]
#

Related items from @see tags, in raw TSDoc format.

throws

?: ThrowsJsonInput[]
#

Exceptions from @throws tags. type is the tag's written type, and typeInfo its structured form, present for a braced type (@throws {A<B>}) that isn't the whole story as text (see TypeJson); an unbraced tag's leading word never has one, nor does a tag in a component's HTML @component comment, which is read as text.

since

?: string
#

Version introduced, from @since tag.

internalMessage

?: string
#

Internal-API marker from the @internal tag. Presence means the tag was written; an empty string is a bare tag with no trailing prose.

A marker, not an exclusion: @internal means "not stable public API" (TSDoc semantics) while the declaration, member, or prop stays documented — unlike @nodocs, which removes a declaration from output entirely (and is ignored on props and members).

mutates

?: Record<string, string>
#

Mutation documentation from @mutates tags (non-standard), mapping keys to descriptions.

Keys are intentionally unvalidated — typically a parameter name, but authors may also use compound paths (this.foo, obj.field) or multi-word external state references. Backticks are stripped from keys so `` a `` and a normalize to one key; an empty-string value is a bare tag with no description. The schema accepts any string key so consumers can render whatever the author wrote.

On a component prop it declares the component's mutation contract for the value it's handed: the component writes into the prop's object or array in place (@mutates items - appends the selected entry, @mutates options.cache - fills on first render). Reassigning a prop is not a mutation in this sense (bindable covers it), though a $bindable prop can carry both.

docComment

?: string
#

JSDoc/TSDoc comment.

typeSignature

?: string
#

Full TypeScript type signature.

modifiers

?: ("public" | "protected" | "readonly" | "static" | "abstract" | "getter" | "setter")[]
#

TypeScript modifiers like readonly, static, or protected.

sourceLine

?: number
#

1-based line in the source file, a positive integer. Synthesized aliases (see aliasOf) carry the local export specifier's line, not the canonical's.

genericParams

?: GenericParamJsonInput[]
#

Generic type parameters like <T, U>.

noDepsResolver
#

dep-resolver.ts view source

ImportResolver

Shared no-op ImportResolver for the "dependency resolution disabled" case.

Stable string identity ('no-deps') instead of a per-call symbol so that repeated ingests within a long-lived session cache-hit on identity. Each session still owns its own cache (entries live on the per-session owned map; sessions don't share state), but within one session every reference to noDepsResolver is === to every other — so a Vite re-save of byte-identical content with resolveDependencies: false exercises the cache-hit branch. The resolver always returns null, so any two calls with identical content under this identity produce identical resolution results — string identity correctly captures that. Used by both the one-shot analyzeFromFiles path and the long-lived Vite plugin (resolveDependencies: false).

import {noDepsResolver} from 'svelte-docinfo/dep-resolver.ts';

normalizeDiagnosticPaths
#

analyze-core.ts view source

normalizeDiagnosticPaths(diagnostics: Diagnostic[], projectRoot: string): void

Normalize the paths a Diagnostic carries to project-root-relative form, in place.

Producers inside the analysis pipeline can write absolute paths or virtual paths (svelte2tsx output like Foo.svelte.__svelte2tsx__.ts). This pass collapses both to the public contract: a path relative to projectRoot with no leading slash and no ./ prefix. A file outside the root gets the ../ form, matching module paths in printed type text — so the documented "rejoin with projectRoot to get an absolute path" holds for it too.

message gets the same treatment as file, by textual substitution. A message is free-form, and not every path in one comes from a field this pass can see — a wrapped error message can embed the file name itself. Scrubbing here means the contract holds for the whole record rather than one field, so a producer can't reintroduce an absolute path through prose.

Exposed for build-tool integrations that bypass the session and collect their own discovery/dep diagnostics — they need the same normalization to match the public contract. Hand it absolute paths. An already-relative file is left alone (relativizing it would resolve against cwd), so this pass can only correct the absolute form — a relative path on a base other than the project root passes through and ships as-is.

import {normalizeDiagnosticPaths} from 'svelte-docinfo/analyze-core.ts';

mutates

  • diagnostics — rewrites each diagnostic's file and message

see also

  • finalizeDiagnostics — when Svelte virtuals are in play, the position remap must run before this pass (it strips the suffix the remap matches on)

normalizeIncludePatterns
#

source-config.ts view source

normalizeIncludePatterns(include: readonly string[], projectRoot: string): readonly string[]

Normalize discovery include patterns to projectRoot-relative form.

The include-pattern counterpart of normalizeSourceOptions' absolute-entry handling: in-root absolute patterns relativize, out-of-root ones throw, relative ones pass through (see normalizeGlobPattern; exclude gets the same treatment inside normalizeSourceOptions). Applied by the discovery seams (createSourceOptionsWithInclude, discoverSourceFiles) so widening, the anchored baseline ignores, and the glob itself all see canonical relative patterns; projectRoot must be normalized (absolute POSIX, no trailing slash) — pass ModuleSourceOptions.projectRoot.

import {normalizeIncludePatterns} from 'svelte-docinfo/source-config.ts';

normalizeModulePathsInTypes
#

analyze-core.ts view source

normalizeModulePathsInTypes(modules: ModuleJson[], options: ModuleSourceOptions, program: Program): void

Normalize the absolute module paths TypeScript embeds in printed type text, in place, dropping the resolution-mode import attribute the checker adds beside them (RESOLUTION_MODE_ATTRIBUTE_RE).

The checker prints a module object as typeof import("<absolute path>"), which reaches output through every checker-printed field — typeSignature on declarations and members, returnType, and the text of a TypeJson node (a module object is a terminal other node, never a reference). Left alone it makes output machine-dependent (two checkouts of the same source produce different bytes), publishes local filesystem paths on any site that renders typeSignature, and exposes the svelte2tsx virtual suffix that stripVirtualSuffix exists to hide. A written import('./x').T annotation resolves to the type's own name and never carries a path.

A path that resolves to a module in this output is rewritten to that module's ModuleJson.path, so the string doubles as a lookup key: a consumer linkifies with modules.find((m) => m.path === s) and reads a miss as "not a module here." See createModulePathNormalizer for the remaining tiers. The string's shape doesn't distinguish them (sub/nested.ts and pkg/index.d.ts look alike) — the lookup does, which keeps sourceRoot out of the output envelope.

Runs as a whole-output pass rather than at the ~20 typeToString / signatureToString call sites, so a new printing site can't miss it.

import {normalizeModulePathsInTypes} from 'svelte-docinfo/analyze-core.ts';

mutates

  • modules — rewrites printed type text on declarations and members

normalizeResolveImport
#

dep-resolver.ts view source

also exported from index.ts

normalizeResolveImport(value: ResolveImport | undefined): ImportResolver | undefined

Normalize the public ResolveImport union to an ImportResolver.

Wraps a bare function via wrapResolveImport (fresh synthesized identity); passes a token-paired resolver through unchanged. undefined in, undefined out — callers fall back to the session default. Call once per logical resolver scope: at session construction for the default, per call for an override.

import {normalizeResolveImport} from 'svelte-docinfo/dep-resolver.ts';

normalizeSourceOptions
#

source-config.ts view source

normalizeSourceOptions(options: ModuleSourceOptions): ModuleSourceOptions

Normalize and validate ModuleSourceOptions, returning a new options object.

Normalization:

  • projectRoot resolved to absolute via path.resolve (relative paths resolve against cwd)
  • Trailing slash stripped from projectRoot
  • sourcePaths entries and sourceRoot resolved against projectRoot and stored root-relative: ./.. segments collapse (src/../lib → lib, . → ''), trailing slashes drop, and absolute entries inside the root relativize (matching loadFile's treatment of path inputs)
  • exclude globs relativized when absolute inside the root (textual prefix strip, since glob metacharacters aren't path segments), so discovery's glob ignore and analysis-time isSource see the same relative pattern

Validation (after normalization):

  1. No sourcePaths entry, sourceRoot, or absolute exclude glob resolves outside projectRoot (out-of-root modules are unrepresentable — module paths and diagnostics are project-root-relative; widened include bases funnel through here too; absolute out-of-root entries get a drop-the-leading-slash hint)
  2. sourcePaths has at least one entry
  3. sourceRoot (if provided and non-empty) is a prefix of all sourcePaths

When sourceRoot is omitted and multiple sourcePaths are provided, sourceRoot is auto-derived as their longest common path prefix. If the paths share no common prefix, the derived root is '' and extractPath produces project-relative module paths.

Returns a fresh object — the input is not mutated. Re-normalization produces a fresh identity, which naturally invalidates the excludeMatcherCache (keyed by options-object identity) without a separate "rebuild a fresh object" rule.

import {normalizeSourceOptions} from 'svelte-docinfo/source-config.ts';

returns

a new ModuleSourceOptions with normalized fields

throws

  • Error - if validation fails

examples

// Normalization: trailing slash and dot segments collapse, relative projectRoot resolves const normalized = normalizeSourceOptions({projectRoot: '.', sourcePaths: ['src/../src/lib/'], ...}); // normalized.projectRoot is now absolute, normalized.sourcePaths is ['src/lib']

OnDuplicates
#

analyze-core.ts view source

also exported from index.ts

type "diagnostic" | "warn" | "throw"

Opt-in check that declaration names are unique across modules.

For packages that keep a flat export namespace, where every exported name is unique across the whole package. Most packages don't, and two modules exporting the same name is ordinary, so the check is off by default: omitted, duplicate detection doesn't run and nothing is reported.

Every mode emits a duplicate_declaration diagnostic per colliding name:

  • 'diagnostic' — the diagnostics only
  • 'warn' — also log the collisions to log.warn and continue
  • 'throw' — also throw an Error listing every duplicate

The throw fires before the result is returned, so 'throw' callers never reach the diagnostics array. For custom handling, use 'diagnostic' and read the records with byKind(diagnostics, 'duplicate_declaration').

import type {OnDuplicates} from 'svelte-docinfo/analyze-core.ts';

optionalWidened
#

typescript-extract-shared.ts view source

optionalWidened(ctx: ExtractContext, optional: boolean): boolean

Whether the checker widened this optional *property* position with undefined — i.e. whether the optional-widening strip applies. Under exactOptionalPropertyTypes the checker doesn't widen optional properties at all, so every undefined in the type is author-written and stripping would corrupt it: x?: T | undefined trimmed to T, `x?: T | null | undefined to T | null`, and a null-free multi-member union rebuilt through getNonNullableType (x?: E | F printed as NonNullable<E> | NonNullable<F>).

Property sites only — component props, type-alias and interface properties, class properties. Optional *parameters* and optional *tuple elements* widen under both modes (probed on TS 5.9), so their call sites pass optional unconditionally and never route through this gate. populatePropertyMember's callability query also bypasses it — an optional callable strips in both modes (see getNonOptionalType).

import {optionalWidened} from 'svelte-docinfo/typescript-extract-shared.ts';

optionalWideningTarget
#

typescript-extract-type-json.ts view source

optionalWideningTarget(type: Type, checker: TypeChecker, optional: boolean): { target: Type; dropUndefined: boolean; }

The single owner of the optional-widening strip, shared with getTypeSignature and getNonOptionalType (in typescript-extract-shared.ts) so the flat string, the tree, and the structural queries can't drift. Owns the optional gate too — a non-optional position passes through, so call sites hand over the flag rather than branching around the call. For a type at an optional-flagged position (a ?-marked or otherwise omittable declaration, or a tuple element):

  • a non-union carries no separate widening member to strip, so it passes through. Three shapes land here: x?: undefined (the written type and the widening coincide), and x?: unknown / x?: any (both absorb undefined). getNonNullableType must not run on any of them — it answers {} for unknown, which would report x?: unknown as "{}"
  • a null-bearing union keeps its shape and reports dropUndefined — the walk drops only the widening member (so the alias survives) and the printer trims the printed suffix
  • a union left with exactly one member after dropping undefined takes that member directly — it *is* the annotated type. Matters for a bare unconstrained type parameter (c?: E), where getNonNullableType can only answer NonNullable<E>
  • every other union takes getNonNullableType, which rebuilds the union rather than picking a member (so a union of callables keeps its combined call signature) and preserves the alias symbol

Under exactOptionalPropertyTypes the checker widens optional *properties* not at all, so property sites gate optional off via optionalWidened (in typescript-extract-shared.ts) and never reach the strip; optional parameters and tuple elements widen under both modes and keep passing optional unconditionally.

import {optionalWideningTarget} from 'svelte-docinfo/typescript-extract-type-json.ts';

OverloadJson
#

types.ts view source

value + type

also exported from index.ts

A single function overload signature.

When a function has multiple overload signatures, each public overload is captured here. The implementation signature is excluded.

import {OverloadJson} from 'svelte-docinfo/types.ts';

inheritance

extends: SchemaStrictObjectOutput<typeof OverloadJsonEntries>

members

genericParams

: GenericParamJson[]
#

Generic type parameters for this overload.

typeSignature

: string
#

Full TypeScript type signature for this overload.

parameters

: ParameterJson[]
#

Parameters for this overload.

docComment

?: string
#

JSDoc/TSDoc comment specific to this overload.

returnDescription

?: string
#

Return value description from @returns tag on this overload.

returnPredicate

?: ReturnPredicateJson
#

The signature's type predicate or assertion, when it declares one; returnType stays the checker's boolean or void.

thisType

?: string
#

The type of a declared this parameter (function f(this: A), or a JS @this {A} tag), which parameters leaves out, since a caller doesn't pass it as an argument.

thisTypeInfo

?: TypeJson
#

Structured thisType; absent when thisType is the whole story (see TypeJson).

returnType

?: string
#

Return type for this overload.

returnTypeInfo

?: TypeJson
#

Structured return type; absent when returnType is the whole story (see TypeJson).

OverloadJsonInput
#

types.ts view source

The input OverloadJson parses, with any field it defaults optional.

import type {OverloadJsonInput} from 'svelte-docinfo/types.ts';

inheritance

extends: SchemaStrictObjectInput<typeof OverloadJsonEntries>

members

typeSignature

: string
#

Full TypeScript type signature for this overload.

genericParams

?: GenericParamJsonInput[]
#

Generic type parameters for this overload.

docComment

?: string
#

JSDoc/TSDoc comment specific to this overload.

returnDescription

?: string
#

Return value description from @returns tag on this overload.

returnPredicate

?: ReturnPredicateJsonInput
#

The signature's type predicate or assertion, when it declares one; returnType stays the checker's boolean or void.

thisType

?: string
#

The type of a declared this parameter (function f(this: A), or a JS @this {A} tag), which parameters leaves out, since a caller doesn't pass it as an argument.

thisTypeInfo

?: TypeJson
#

Structured thisType; absent when thisType is the whole story (see TypeJson).

parameters

?: ParameterJsonInput[]
#

Parameters for this overload.

returnType

?: string
#

Return type for this overload.

returnTypeInfo

?: TypeJson
#

Structured return type; absent when returnType is the whole story (see TypeJson).

OwnedDirIndex
#

typescript-program.ts view source

internal

Shared by the one-shot host, the LS host, and the session's dependency-resolution host; not a stable API.

Ancestor-directory index over a path set, maintained as the set mutates.

Module resolution probes directoryExists before trying file candidates inside it (directoryProbablyExists): a directory reported absent has every candidate recorded as a failed lookup with fileExists never consulted, so a directory that exists only as the prefix of served in-memory paths must report present. Refcounted per ancestor so removal is exact — O(path depth) per mutation, O(1) per query; a per-probe scan of the path set would multiply into resolution's hot path (bare-specifier resolution walks many nonexistent ancestor node_modules directories per import).

The index owns its path set, so add/remove are idempotent and a caller can't skew the refcounts by double-adding or by removing something it never added (which would drop an ancestor still holding live paths). Membership bookkeeping therefore stays here rather than in each caller's guard.

import type {OwnedDirIndex} from 'svelte-docinfo/typescript-program.ts';

members

add

(path: string): void
#

Count path's ancestor directories into the index. Idempotent.

remove

(path: string): void
#

Reverse of add; a path that isn't indexed is a no-op.

has

(dir: string): boolean
#

Whether dir is an ancestor of any indexed path (trailing slash tolerated).

clear

(): void
#

ParameterJson
#

types.ts view source

value + type

also exported from index.ts

Parameter information for functions and methods.

Kept distinct from ComponentPropJson despite structural similarity. Function parameters form a tuple with positional semantics: calling order matters (fn(a, b) vs fn(b, a)), may include rest parameters and destructuring patterns.

Carries no doc fields beyond description, unlike ComponentPropJson: a parameter's docs come from one @param line, while a prop has a JSDoc block of its own.

import {ParameterJson} from 'svelte-docinfo/types.ts';

inheritance

extends: SchemaStrictObjectOutput<typeof ParameterJsonEntries>

members

name

: string
#

Parameter name (e.g., options, args); rest-ness is carried by rest, never the name.

type

: string
#

Resolved TypeScript type string (e.g., string, Record<string, unknown>).

optional

: boolean
#

Whether a caller may omit the argument, by the checker's isOptionalParameter: a ? token, an initializer with no required parameter after it (b = 0), and in JS a bracketed @param {T} [b] or @param {T=} b. When set, type and typeInfo drop a top-level undefined (the optional widening, or one an initialized parameter's type already holds), so optional carries it alone. A rest parameter is never optional.

rest

: boolean
#

Whether the parameter uses rest syntax (...args).

pattern

?: string
#

A destructured parameter's binding pattern ({ a, b = 1 }, [a, b]), printed on one line with its defaults kept and comments dropped (a string default that spans lines keeps its line breaks). Such a parameter has no name of its own, so name is the one TypeScript gives it by position (__0 for the first parameter, __1 for the second, a this parameter counted); a renderer shows the pattern in its place. Absent on an identifier-named parameter.

docName

?: string
#

The name a destructured parameter's @param tag gives it (options for fn({a, b}: T) under @param options), the tag TypeScript matches by position; on a callable property's function type (m: ({a}: O) => void), the property's tag in that position. A renderer can anchor or link the parameter by it where name is only the positional __0. Absent on an identifier-named parameter, with no such tag, and for an array pattern's tag (@param [a, b]), whose name is no name.

typeInfo

?: TypeJson
#

Structured type; absent when type is the whole story (see TypeJson).

description

?: string
#

Description from @param tag.

defaultValue

?: string
#

The initializer's source text, verbatim (e.g., "'hello'", 42, () => 10) — quotes included, no normalization; consumers render it as highlighted TS. Without an initializer, the default a bracketed @param {T} [b=0] writes, verbatim the same way.

propertyDescriptions

?: Record<string, string>
#

Descriptions for properties of a named object parameter, from dotted @param tags (@param obj.prop - ...), the ones TypeScript nests under a braced @param {object} obj included.

Keyed by the sub-path relative to this parameter — @param obj.prop becomes {prop: '...'}, @param obj.a.b becomes {'a.b': '...'}, and an array element's @param arr[].prop becomes {'[].prop': '...'}. Keys are unvalidated against the parameter's actual type (matching the @mutates philosophy); absent when no dotted @param tags reference this parameter. Only populated for function/method/constructor signature parameters.

Matching is by the parameter's name. A destructured parameter (fn({a, b}: T)), which TypeScript names __0, takes the @param tag in its position as TypeScript does (@param options then @param options.a), where that tag isn't itself dotted; its description comes from the same tag.

ParameterJsonInput
#

types.ts view source

The input ParameterJson parses, with any field it defaults optional.

import type {ParameterJsonInput} from 'svelte-docinfo/types.ts';

inheritance

extends: SchemaStrictObjectInput<typeof ParameterJsonEntries>

members

name

: string
#

Parameter name (e.g., options, args); rest-ness is carried by rest, never the name.

type

: string
#

Resolved TypeScript type string (e.g., string, Record<string, unknown>).

pattern

?: string
#

A destructured parameter's binding pattern ({ a, b = 1 }, [a, b]), printed on one line with its defaults kept and comments dropped (a string default that spans lines keeps its line breaks). Such a parameter has no name of its own, so name is the one TypeScript gives it by position (__0 for the first parameter, __1 for the second, a this parameter counted); a renderer shows the pattern in its place. Absent on an identifier-named parameter.

docName

?: string
#

The name a destructured parameter's @param tag gives it (options for fn({a, b}: T) under @param options), the tag TypeScript matches by position; on a callable property's function type (m: ({a}: O) => void), the property's tag in that position. A renderer can anchor or link the parameter by it where name is only the positional __0. Absent on an identifier-named parameter, with no such tag, and for an array pattern's tag (@param [a, b]), whose name is no name.

typeInfo

?: TypeJson
#

Structured type; absent when type is the whole story (see TypeJson).

optional

?: boolean
#

Whether a caller may omit the argument, by the checker's isOptionalParameter: a ? token, an initializer with no required parameter after it (b = 0), and in JS a bracketed @param {T} [b] or @param {T=} b. When set, type and typeInfo drop a top-level undefined (the optional widening, or one an initialized parameter's type already holds), so optional carries it alone. A rest parameter is never optional.

rest

?: boolean
#

Whether the parameter uses rest syntax (...args).

description

?: string
#

Description from @param tag.

defaultValue

?: string
#

The initializer's source text, verbatim (e.g., "'hello'", 42, () => 10) — quotes included, no normalization; consumers render it as highlighted TS. Without an initializer, the default a bracketed @param {T} [b=0] writes, verbatim the same way.

propertyDescriptions

?: Record<string, string>
#

Descriptions for properties of a named object parameter, from dotted @param tags (@param obj.prop - ...), the ones TypeScript nests under a braced @param {object} obj included.

Keyed by the sub-path relative to this parameter — @param obj.prop becomes {prop: '...'}, @param obj.a.b becomes {'a.b': '...'}, and an array element's @param arr[].prop becomes {'[].prop': '...'}. Keys are unvalidated against the parameter's actual type (matching the @mutates philosophy); absent when no dotted @param tags reference this parameter. Only populated for function/method/constructor signature parameters.

Matching is by the parameter's name. A destructured parameter (fn({a, b}: T)), which TypeScript names __0, takes the @param tag in its position as TypeScript does (@param options then @param options.a), where that tag isn't itself dotted; its description comes from the same tag.

parseAnalyzeResult
#

analyze-core.ts view source

also exported from index.ts

parseAnalyzeResult(value: unknown): AnalyzeResultJson

Validate an analysis result, restoring the defaults the wire form omits.

The stable way to consume serialized output (the CLI's JSON, a file written with compactReplacer, virtual:svelte-docinfo's data), independent of the schema library behind AnalyzeResultJson: empty arrays and false booleans that compactReplacer stripped come back, and anything that doesn't match the schema throws.

The result is not a fresh copy: an object that needed no default is the one in value, so the result can be value itself or share objects with it, and mutating one then mutates the other.

import {parseAnalyzeResult} from 'svelte-docinfo/analyze-core.ts';

parameters

value

: unknown
#

an analysis result, typically from JSON.parse

returns

the validated result with every default present

throws

  • Error - when value doesn't match the schema; the message lists the reported issues, one per line, as path: message (modules.0.declarations.1.kind: expected …, received "funtion"), the value that failed in place of its type when it's a string, number, or boolean (an unknown key's never), the dot path omitted for an issue at the root, and ends with a line saying there may be more when it holds a hundred. The class is the schema library's (fuz_schema's SchemaError, the structured list on issues), so catch it as a plain Error unless you depend on fuz_schema
  • RangeError - when value nests deeper than the call stack allows, as a TypeJson tree thousands of levels deep does

examples

const result = parseAnalyzeResult(JSON.parse(await readFile('docinfo.json', 'utf8')));

parseComment
#

tsdoc.ts view source

parseComment(node: Node, sourceFile?: SourceFile, skipTypedefBlocks?: boolean): TsdocParsedComment | undefined

Parse JSDoc comment from a TypeScript node.

Extracts and parses all JSDoc tags including:

  • @param - parameter descriptions
  • @returns - return value description (@return accepted as a synonym)
  • @throws - error documentation
  • @example - code examples
  • @deprecated - deprecation warnings
  • @internal - internal-API marker (trailing prose kept)
  • @see - related references
  • @since - version information
  • @default - default value (@defaultValue/@defaultvalue accepted as synonyms)
  • @mutates - mutation documentation (non-standard)
  • @nodocs - exclusion flag (non-standard)
  • @cssprop - a component's CSS custom property (@cssproperty accepted as a synonym); a tag that documents nothing lands in cssPropertyProblems

A JSDoc @typedef or @callback tag parses to the typedef's docs (parseTypedefComment), and a @callback's signature to its parameter and return descriptions (parseCallbackSignatureComment).

A JS function, method, or constructor with @overload tags is documented by its overloads, as the checker types it: an @overload's signature parses to its block's docs plus its own @param and @returns tags (parseOverloadSignatureComment), and the declaration to its first overload's (firstJSDocOverloadSignature). The implementation's own block is hidden, prose and tags alike, as a TypeScript implementation signature's JSDoc is.

JSDoc blocks tagged @module are excluded entirely (text and tags): a module comment attaches to the file's first statement in the AST, and without the filter it would read as that statement's own docs. Module comments parse through parseModuleComment, which parses the comment's text the same way. Typedef blocks (isTypedefBlock: a @typedef/@callback without a @param or @returns) are excluded the same way, as TypeScript's hover skips them: they document their typedefs, not the declaration below. skipTypedefBlocks: false keeps them, for a block that stands for a module or component comment, which a @typedef line doesn't make a typedef's: there the tag drops as an unknown one, and the prose stays.

import {parseComment} from 'svelte-docinfo/tsdoc.ts';

parameters

node

: Node
#

the TypeScript node to extract JSDoc from

sourceFile

?: SourceFile = node.getSourceFile()
#

source file for full-text tag reads (@see); defaults to the node's own

skipTypedefBlocks

?: boolean = true
#

whether typedef blocks are excluded

returns

parsed comment with structured metadata, or undefined if no JSDoc found (or only @module and typedef blocks)

examples

const tsdoc = parseComment(declarationNode, sourceFile); if (tsdoc) { console.log(tsdoc.text); // main comment text console.log(tsdoc.params); // {paramName: 'description'} }

parseCommentText
#

tsdoc.ts view source

parseCommentText(text: string): TsdocParsedComment | undefined

Parse comment text that has no node of its own with parseComment, so it reads every tag exactly as a declaration's JSDoc does.

The text is rewrapped as a JSDoc block on a throwaway statement and parsed there. A *\/ in it (an HTML comment can hold one) is escaped for the parse with a placeholder the text doesn't hold, and restored in the result, and so is an @ in the middle of a line: only a line-leading @ starts a tag here, where a declaration's JSDoc, read by TypeScript in place, starts one at any @ after whitespace. A @module line makes the block a module block, which parseComment skips, so parseModuleComment strips it first.

import {parseCommentText} from 'svelte-docinfo/tsdoc.ts';

parameters

text

: string
#

comment text without comment markers, as cleanComment returns it

returns

the parsed comment; its text is empty when the comment holds only tags

parseCsspropTagText
#

tsdoc.ts view source

parseCsspropTagText(text: string): TsdocCssProperty | undefined

Parse a @cssprop tag's text (after the tag name), the Custom Elements Manifest form: an optional braced syntax ({<color>}), the name, bare (--a) or bracketed with an optional default ([--a=red]), then the description, its leading - separator dropped. The default runs to the bracket that closes the name, skipping nested brackets and quoted strings ([--a=var(--b, 1px)]). An empty syntax or default is absent.

import {parseCsspropTagText} from 'svelte-docinfo/tsdoc.ts';

parameters

text

: string
#

the tag's comment text

returns

the property, or undefined when the text names no custom property (a name without --, an unclosed brace or bracket)

ParsedExports
#

exports.ts view source

Result of reading and parsing package.json exports.

import type {ParsedExports} from 'svelte-docinfo/exports.ts';

members

entries

: ExportEntry[]
#

All parsed export entries.

blocked

: string[]
#

Specifiers (exact or wildcard patterns) whose export target resolves nothing — a literal null, a conditions object with no usable target (all-null or empty), or a fallback array with no usable element. Node's explicit-exclusion form: "./internal/*": null blocks the subpaths a broader wildcard would otherwise expose. Discovery honors these with Node's best-match semantics: a subpath whose most-specific matching key is blocked is not exported, so its source file is not discovered.

Interpret via createBlockedSpecifierChecker — a naive membership check (blocked.includes(specifier)) is wrong for wildcard keys and ignores the positive keys that can out-match a blocked one.

hasExports

: boolean
#

Whether the package.json had an exports field.

parseDiagnostics
#

diagnostics.ts view source

also exported from index.ts

parseDiagnostics(value: unknown): Diagnostic[]

Validate an array of diagnostics.

The stable way to validate diagnostics stored or sent on their own, independent of the schema library behind Diagnostic. For a whole analysis result use parseAnalyzeResult.

The result is value itself when it matches: no diagnostic has a default to fill in, so nothing is copied.

import {parseDiagnostics} from 'svelte-docinfo/diagnostics.ts';

parameters

value

: unknown
#

an array of diagnostics, typically from JSON.parse

returns

the validated diagnostics

throws

  • Error - when value doesn't match the schema; the message lists the reported issues, one per line, as path: message (0.severity: expected …, received "warn"), the value that failed in place of its type when it's a string, number, or boolean (an unknown key's never), the dot path omitted for an issue at the root, and ends with a line saying there may be more when it holds a hundred. The class is the schema library's (fuz_schema's SchemaError, the structured list on issues), so catch it as a plain Error unless you depend on fuz_schema

parseGenericParam
#

typescript-extract-shared.ts view source

parseGenericParam(param: TypeParameterDeclaration, ctx: ExtractContext): GenericParamJsonInput

Parse a TypeScript generic type parameter declaration into structured info.

A JSDoc @template {C} T writes its constraint on the tag rather than the parameter, for the tag's first parameter only, which ts.getEffectiveConstraintOfTypeParameter reads; the braces are dropped, so constraint is C as in <T extends C>. A bracketed default (@template [T=D]) is on the parameter like TypeScript's.

import {parseGenericParam} from 'svelte-docinfo/typescript-extract-shared.ts';

parameters

param

: TypeParameterDeclaration
#

the TypeScript type parameter declaration node

returns

structured GenericParamJson with name, constraint, and default type

parseHiddenJSDocImplementationComment
#

tsdoc.ts view source

parseHiddenJSDocImplementationComment(node: Node, sourceFile?: SourceFile): TsdocParsedComment | undefined

The docs parseComment hides on a JS function, method, or constructor with @overload tags: the prose and tags of its JSDoc blocks that host no @overload (module and typedef blocks aside), the implementation's, as a TypeScript implementation signature's JSDoc is hidden. Undefined without @overload tags, or when those blocks carry no doc content (hasDocContent), so a types-only implementation block (@param {T} a) counts as none.

import {parseHiddenJSDocImplementationComment} from 'svelte-docinfo/tsdoc.ts';

parameters

sourceFile

?: SourceFile = node.getSourceFile()
#

parseModuleComment
#

tsdoc.ts view source

parseModuleComment(text: string): TsdocParsedComment | undefined

Parse a module comment's cleaned text with parseCommentText, after dropping each @module line (an optional @module name rename is ignored).

Shared by every module-comment source — a TS module comment, a Svelte script's, and a Svelte HTML comment with a @module line — so they parse their tags as one. Prose after the @module line stays prose; prose after any other tag belongs to that tag, as in a declaration's JSDoc.

import {parseModuleComment} from 'svelte-docinfo/tsdoc.ts';

parameters

text

: string
#

the comment's text without comment markers

returns

the parsed comment, or undefined when it holds neither prose nor a parsed tag (a bare @module)

parseModuleJson
#

types.ts view source

also exported from index.ts

parseModuleJson(value: unknown): ModuleJson

Validate a ModuleJson, restoring the defaults the wire form omits.

The stable way to validate a module or restore what compactReplacer stripped (empty arrays, false booleans), independent of the schema library behind ModuleJson.

The result is not a fresh copy: an object that needed no default is the one in value, so the result can be value itself or share objects with it, and mutating one then mutates the other.

import {parseModuleJson} from 'svelte-docinfo/types.ts';

parameters

value

: unknown
#

a module, typically from JSON.parse of compact output

returns

the validated module with every default present

throws

  • Error - when value doesn't match the schema; the message lists the reported issues, one per line, as path: message (declarations.1.kind: expected …, received "funtion"), the value that failed in place of its type when it's a string, number, or boolean (an unknown key's never), the dot path omitted for an issue at the root, and ends with a line saying there may be more when it holds a hundred. The class is the schema library's (fuz_schema's SchemaError, the structured list on issues), so catch it as a plain Error unless you depend on fuz_schema
  • RangeError - when value nests deeper than the call stack allows, as a TypeJson tree thousands of levels deep does

parsePackageExports
#

exports.ts view source

parsePackageExports(projectRoot: string): Promise<ParsedExports>

Read and parse the exports field from package.json.

Handles all Node.js export formats: strings, objects with conditions, nested conditions, fallback arrays (first usable element), null exclusions (surfaced on blocked for best-match blocking during discovery), and wildcard patterns.

import {parsePackageExports} from 'svelte-docinfo/exports.ts';

parameters

projectRoot

: string
#

absolute path to project root

returns

parsed ParsedExports, or {entries: [], blocked: [], hasExports: false} if no exports field

ParseSvelteTemplate
#

svelte-scripts.ts view source

Parses a Svelte source whose script and style content is blanked, and says where its top-level scripts are. Throws when the source doesn't parse.

import type {ParseSvelteTemplate} from 'svelte-docinfo/svelte-scripts.ts';

members

(blankedSource: string): SvelteTemplateScripts

parseWithSummary
#

schema.ts view source

internal

parseWithSummary<TSchema extends s.Schema>(schema: TSchema, value: unknown): Infer<TSchema>

Validate value against schema, throwing an error that lists every issue the parse reports.

s.parse_or_throw's message stops at ten issues; this one lists every issue the parse builds, one per line, as s.format_issue_with_value writes it: path: expected X, received Y, or the bare text for an issue at the root, where Y is the value that failed when it's a string, number, or boolean (a string quoted as JSON and cut at 32 code units, so received "funtion"), and its type otherwise (received undefined, received object). An unknown key reads its value's type, never the value. So the message carries short pieces of value's values, which issues never does. Unknown keys of a strict object are each reported. fuz_schema builds at most a hundred issues for a parse, so a message of a hundred ends with a line saying there may be more.

import {parseWithSummary} from 'svelte-docinfo/schema.ts';

parameters

schema

: TSchema
#

the schema to validate against

value

: unknown
#

the value to validate

returns

the parsed output, defaults applied

throws

  • SchemaError - when value doesn't match; message lists the issues in the format above and issues holds them structured

populateCallableMember
#

typescript-extract-shared.ts view source

populateCallableMember(target: DeclarationJsonBuild | MemberJsonBuild, signatures: readonly Signature[], ctx: ExtractContext, tsdoc: TsdocParsedComment | undefined, paramValidationNode: Node, name: string, includeReturn?: boolean): void

Populate the callable fields of a declaration or member from its call/construct signatures: typeSignature, parameters, overloads, and (unless includeReturn is false) returnType / returnTypeInfo / returnDescription.

The shared core of every named-callable extractor — standalone functions, interface methods, class methods/constructors, and type-alias function properties. Callers differ in how they obtain signatures (symbol type, constructor declarations, property call signatures) and in their own try/catch + diagnostic kind, so those stay at the callsite; this captures only the identical projection from a resolved signature list onto the build target. No-op when signatures is empty.

import {populateCallableMember} from 'svelte-docinfo/typescript-extract-shared.ts';

parameters

declaration or member build object (mutated)

signatures

: readonly Signature[]
#

public call/construct signatures (signatures[0] supplies typeSignature, parameters, and the return type)

the extraction pass's context

tsdoc

: TsdocParsedComment | undefined
#

parsed TSDoc for the target (supplies @param/@returns)

paramValidationNode

: Node
#

node validateParamKeys reports unknown_param against

name

: string
#

target name, for diagnostic messages

includeReturn

?: boolean = true
#

set false for constructors (no return type/description)

mutates

  • target — sets typeSignature, parameters, overloads, returnType, returnTypeInfo, returnDescription
  • ctx.diagnostics — via validateParamKeys / extractOverloads

populatePropertyMember
#

typescript-extract-shared.ts view source

populatePropertyMember(member: MemberJsonBuild, propType: Type, ctx: ExtractContext, optional: boolean, tsdoc: TsdocParsedComment | undefined, paramValidationNode: Node, name: string, annotation: TypeNode | undefined, isMethod?: boolean): void

Populate a property-shaped member from its checker type: a callable property becomes kind: 'function' with the full signature field set (generic signatures carry genericParams like method signatures do), everything else gets the flat/structured pair (typeSignature + typeInfo) with the optional-widening strip paired to optional like every checker-backed site. Callability counts local call signatures only (isExternalSignature) — a property typed by an external function documents as the flat type text rather than enumerating the external package's overloads and docs. TSDoc applies here after the projection; members carry @default → defaultValue whatever kind the classification settles on (for a callable member it documents the behavior used when the callback is omitted).

The one projection shared by the structural property sites — type-alias properties and interface property signatures — so the same written shape can't extract differently across the two container kinds. Class fields deliberately don't route here: a field holding a function is still a field (kind: 'variable'), while on the structural containers callability is the member's classification.

import {populatePropertyMember} from 'svelte-docinfo/typescript-extract-shared.ts';

parameters

annotation

: TypeNode | undefined
#

the written type annotation, when one exists (feeds typeInfo name recovery)

isMethod

?: boolean = false
#

whether the property is declared with method syntax, which leaves a callable member's property unset

mutates

  • member — sets kind, doc fields, and either the callable field set or typeSignature/typeInfo
  • ctx.diagnostics — via populateCallableMember

QueryOptions
#

session.ts view source

also exported from index.ts

Per-call input to query.

import type {QueryOptions} from 'svelte-docinfo/session.ts';

members

onDuplicates

?: OnDuplicates
#

Opt-in check that declaration names are unique across modules (see OnDuplicates).

#

Per-call logger override (defaults to the session-level logger).

Reactivity
#

types.ts view source

value + type

also exported from index.ts

"$state" | "$state.raw" | "$derived" | "$derived.by"

type "$state" | "$state.raw" | "$derived" | "$derived.by"

Reactivity flavor for a variable declaration or class field, captured from the rune call at the initializer (e.g., let count = $state(0)).

Only the value-producing reactivity runes are represented here — $props and $bindable are modeled separately as ComponentPropJson.bindable (and prop-presence on the props array), which a legacy export let prop sets too. A renderer wanting "all rune annotations across declarations and props" needs to read both this field and ComponentPropJson.bindable.

  • $state — deeply reactive proxy
  • $state.raw — reference-only reactive (no proxy)
  • $derived — recomputed from dependencies (re-assignable)
  • $derived.by — same as $derived, with a function argument

Detection is syntactic (AST-based) and runs on every analyzed file regardless of extension. Most reactive declarations live in .svelte, .svelte.ts, or .svelte.js, but the field will also surface on any .ts/.js file that uses the same rune call patterns — by design, so documentation pipelines can capture any rune-shaped declaration their conventions choose to expose.

import {Reactivity} from 'svelte-docinfo/types.ts';

reclassifySnippetDeclaration
#

svelte.ts view source

reclassifySnippetDeclaration(declaration: DeclarationJsonBuild): void

Turn the function declaration svelte2tsx makes of an exported snippet back into a kind: 'snippet', in place; any other declaration is left alone.

svelte2tsx transforms {#snippet} + export into an arrow function whose return type is ReturnType<import('svelte').Snippet> (isSnippetReturnType), so the checker-backed extraction sees a function with svelte2tsx's types. Runs wherever such a declaration can surface: a component's own module exports, and an alias another module synthesizes when it re-exports the snippet from a component that emits no module of its own.

import {reclassifySnippetDeclaration} from 'svelte-docinfo/svelte.ts';

mutates

  • declaration — sets kind and typeSignature, drops the return and overload fields

ReExportJson
#

types.ts view source

value + type

also exported from index.ts

A same-name re-export edge, from the re-exporting module's side.

Each entry on ModuleJson.reExports records that the module's source contains export {name} from ..., or the import-then-export form it stands for (import {name} from ...; export {name}, export default X over a default import), where the canonical declaration lives in module. This is the forward view of the same fact that alsoExportedFrom records on the canonical declaration — consumers resolve the canonical by (module, name), the same lookup contract as aliasOf.

Same-name re-exports of analyzed source only. Renamed re-exports appear as declarations with aliasOf in the re-exporting module; star exports live in ModuleJson.starExports; external re-exports in ModuleJson.externalReExports / externalStarExports. Use resolveExportSurface (in postprocess.ts) to combine all of these into a module's full export surface — it handles the name dedup (a documented same-name re-export appears both here and as a synthesized alias declaration) and the ES star semantics (explicit exports shadow star-projected ones, names ambiguous between stars are excluded, default doesn't project).

module points at the *canonical* module (multi-hop chains are resolved), not the immediate specifier in the export statement. For Svelte default-slot re-exports (export {default} from './X.svelte', or `import X from './X.svelte'; export default X), name` is the component name derived from the filename ('X'), matching the canonical declaration's name — the same exception documented on aliasOf. Because of that re-keying, two entries in one module can share a name (a re-keyed component colliding with a same-name re-export from another module); (module, name) pairs remain unique (exact duplicates are deduped at construction).

@nodocs on the export statement suppresses the entry (and the alsoExportedFrom back-link). When the canonical declaration itself is @nodocs, the entry still exists but has no matching back-link. module is always a module in the same result: a re-export whose canonical module emits nothing (gated, or outside the analyzed inputs) is a declaration with aliasOf in the re-exporting module instead, and aliasOf.module is the one field that can name a module the result doesn't contain.

A star over a module that emits nothing produces entries here too, one per projected binding whose canonical does emit, with the star statement's line and type-only-ness (see ModuleJson.starExports).

import {ReExportJson} from 'svelte-docinfo/types.ts';

inheritance

extends: SchemaStrictObjectOutput<typeof ReExportJsonEntries>

members

name

: string
#

Exported name — the canonical declaration's name in module.

module

: string
#

Module path (relative to sourceRoot) where the canonical declaration lives.

typeOnly

: boolean
#

Whether the statement (export type {A} from ...) or specifier (export {type A} from ...) is type-only — the name is erased at runtime and importable only via import type. A type-only *rename* carries no such marker (see aliasOf).

sourceLine

?: number
#

1-based line of the export specifier in this module's source, a positive integer. When identical (name, module) edges are deduped (Svelte default-slot re-keying), the smallest line is kept.

ReExportJsonInput
#

types.ts view source

The input ReExportJson parses, with any field it defaults optional.

import type {ReExportJsonInput} from 'svelte-docinfo/types.ts';

inheritance

extends: SchemaStrictObjectInput<typeof ReExportJsonEntries>

members

name

: string
#

Exported name — the canonical declaration's name in module.

module

: string
#

Module path (relative to sourceRoot) where the canonical declaration lives.

typeOnly

?: boolean
#

Whether the statement (export type {A} from ...) or specifier (export {type A} from ...) is type-only — the name is erased at runtime and importable only via import type. A type-only *rename* carries no such marker (see aliasOf).

sourceLine

?: number
#

1-based line of the export specifier in this module's source, a positive integer. When identical (name, module) edges are deduped (Svelte default-slot re-keying), the smallest line is kept.

referenceSymbolName
#

typescript-extract-type-json.ts view source

referenceSymbolName(type: Type, checker: TypeChecker): string | undefined

The symbol name of a named generic instantiation (Snippet<[a: string]>, Map<string, B>) — checker Reference-flagged, non-anonymous symbol, carrying type arguments — or undefined for everything else. One predicate for the two decisions that must agree: the callable-classification exception (such a type is a reference node even when it has call signatures) and the object branch's reference emission. Tuples never match (their references carry no symbol); bare and aliased signatures are Anonymous-flagged; non-generic callable interfaces either aren't Reference-flagged (thisless) or carry no type arguments (the declared type of a this-referencing interface or a class is its own Reference with an empty argument list) — all of these stay function nodes.

import {referenceSymbolName} from 'svelte-docinfo/typescript-extract-type-json.ts';

registerExactOptionalChecker
#

typescript-extract-type-json.ts view source

registerExactOptionalChecker(checker: TypeChecker): void

Record that a checker's program sets exactOptionalPropertyTypes (see exactOptionalCheckers).

import {registerExactOptionalChecker} from 'svelte-docinfo/typescript-extract-type-json.ts';

remapVirtualDiagnosticPositions
#

svelte.ts view source

internal

Half of an ordered pair — `finalizeDiagnostics` (in `analyze-core.ts`) owns the order and is the entry point for callers assembling modules themselves through `analyzeModule` / `analyzeSvelteModule`.

remapVirtualDiagnosticPositions(diagnostics: Diagnostic[], virtualFiles: Iterable<SvelteVirtualFile>): void

Remap diagnostic positions emitted against svelte2tsx virtuals back to original .svelte positions, in place.

Extractors locate diagnostics via getNodeLocation, which reads whatever source file the node lives in — for a <script module> declaration that's the virtual. normalizeDiagnosticPaths later rewrites file to the .svelte path but has no position input, so without this pass the published combination is the original file with the virtual's line — actively misleading. Runs over the whole batch keyed by file, so a diagnostic emitted against *another* component's virtual (a rename re-export re-analyzes its canonical in the canonical's own source file) remaps through that virtual's map.

Must run before normalizeDiagnosticPaths, which strips the virtual suffix this pass matches on. An unmappable position (no source map, or a node svelte2tsx synthesized) drops line/column — absence over a virtual line.

import {remapVirtualDiagnosticPositions} from 'svelte-docinfo/svelte.ts';

mutates

  • diagnostics — rewrites line/column on virtual-file entries

resolveComponentAliases
#

postprocess.ts view source

also exported from index.ts

resolveComponentAliases(modules: ModuleJson[], contextModules?: readonly ModuleJson[]): ModuleJson[]

Copy props/acceptsChildren/lang/etc. from canonical component declarations onto synthesized component-aliased declarations.

Renamed Svelte component re-exports (export {default as Foo} from './X.svelte') are emitted as kind: 'component' placeholders by analyzeExports, with aliasOf pointing at the canonical. The canonical's component-specific fields are only available after analyzeSvelteModule synthesizes the canonical declaration, so the copy happens here in phase 2 once all modules are analyzed.

Call this *after* mergeReExports — both walk the same modules array but read/write disjoint fields, so order between them only matters for clarity.

Pure: the input array and its objects are never mutated. Aliases with a resolvable canonical are replaced by filled copies (canonical field values are shared by reference, not cloned); everything else flows through ===-equal.

Doc-comment fields fill gaps only: local doc fields applied to the alias before phase 2 (from JSDoc on the re-export statement) stick.

import {resolveComponentAliases} from 'svelte-docinfo/postprocess.ts';

parameters

modules

: ModuleJson[]
#

the analyzed modules (parsed ModuleJsons)

contextModules

?: readonly ModuleJson[] = []
#

canonical-lookup-only modules that never appear in output — gated component canonicals (the internal/ convention) analyzed as fill context by analyzeCore. An alias whose aliasOf.module is gated fills from here; an emitted module with the same path (impossible by construction) would win the lookup

returns

a new array with component-only fields filled on aliased component declarations

resolveExportSurface
#

postprocess.ts view source

also exported from index.ts

resolveExportSurface(modules: ModuleJson[], path: string): ExportSurface | null

Resolve a module's full export surface from the analyzed model, applying ES module semantics to star exports.

Combines the module's own declarations (including synthesized aliases), reExports edges, externalReExports, and transitively-resolved starExports into one deduped, name-sorted list. The ES rules applied to star projection:

  • explicit exports (declarations, edges, externals) shadow star-projected names
  • a name projected by two stars that resolve to *different* canonicals is ambiguous and excluded (same canonical through a diamond is included once)
  • default is never star-projected — including canonical Svelte component declarations, which represent their file's default export. (Caveat: a star-projected re-export edge whose canonical is a component is treated as a default-slot re-export and skipped; a <script module> const sharing the component's exact name would be skipped with it.)

A Position-3 alias and its reExports edge are the same fact — the declaration entry wins, inheriting the edge's typeOnly.

Cyclic star graphs terminate by contributing nothing along the back-edge (an approximation of ES fixpoint resolution — fine in practice). Surfaces resolved inside a cycle are path-relative and not memoized, so sibling star paths resolve independently rather than inheriting them. Star targets missing from modules or partial (a placeholder whose bindings are unknown) are reported in unresolvedStarExports rather than guessed at; externalStarExports aggregates external star specifiers reachable from the module, whose names are unknowable.

import {resolveExportSurface} from 'svelte-docinfo/postprocess.ts';

parameters

modules

: ModuleJson[]
#

the analyzed modules (parsed ModuleJsons — run wire JSON through AnalyzeResultJson.parse first)

path

: string
#

the module to resolve, as a ModuleJson.path value

returns

the resolved surface, or null when path isn't in modules

ResolveImport
#

dep-resolver.ts view source

also exported from index.ts

type (ResolveImportFn) | ImportResolver

Public resolver shape accepted across the API — a bare ResolveImportFn or the token-paired ImportResolver.

Every entry point that accepts resolveImport (analyze, analyzeFromFiles, createAnalysisSession, and the session's setFile/setFiles per-call override) takes this union, so the same value copy-pastes between them. Pass:

  • a bare function for the common case — a fresh cache identity is synthesized at the boundary. Correct for one-shot use (analyze, analyzeFromFiles) and for a session default (wrapped once at construction, so identity is stable for the session's lifetime).
  • an ImportResolver with a stable identity when you need the session to reuse its resolve cache across calls where the same logical resolver is rebuilt as a fresh closure (Vite/Rollup plugins). A bare function handed to a *per-call* setFile/setFiles override is treated as a distinct resolver each call (fresh identity → touched files re-resolve), which is the expected behavior for a deliberate one-off override.
import type {ResolveImport} from 'svelte-docinfo/dep-resolver.ts';

ResolveImportFn
#

dep-resolver.ts view source

also exported from index.ts

Bare import-resolver function — the convenience form.

Resolve an import specifier to an absolute file path, or null if the specifier is unresolvable (external package, missing file, etc.). May return synchronously or asynchronously; sync returns are awaited harmlessly in the session's parallel resolve phase.

import type {ResolveImportFn} from 'svelte-docinfo/dep-resolver.ts';

members

(specifier: string, fromFile: string): string | Promise<string | null> | null

resolveLegacyPropsAnchor
#

svelte-legacy.ts view source

resolveLegacyPropsAnchor(propsValue: Expression | undefined, checker: TypeChecker): LegacyPropsAnchor | undefined

Resolve the props anchor of a legacy component from its svelte2tsx virtual.

svelte2tsx ends $$render with return {props: …, slots: …, …}, and the props value is the anchor. The shapes recognized:

  • Typed — <object> as <Type>. The type is a literal svelte2tsx writes from the exports, carrying each prop's JSDoc and optionality ({a?: typeof a, b: number}: 'generated'), or the author's reserved $$Props, bare or intersected with a literal of the accessors ('authored').
  • Untyped — a bare object literal ({a: a, b: b}: 'untyped'), what a JS component gets, and a TS one whose exports are all untyped and uninitialized, with each binding's JSDoc copied onto its property, so a @type there types the prop.

Anything else is undefined: an unknown virtual yields no props rather than guessed ones, and the caller reports it.

A props value svelte2tsx built from no exports is unrecognized here too: an empty object under a cast ({} as Record<string, never>, or in JS a JSDoc cast on ({})). The caller asks only when the scan found exports, so an empty value means svelte2tsx didn't read the script the scan read, and the exports are reported, not dropped in silence.

Whether the component is legacy at all isn't decided here. The caller asks only for a component svelte2tsx read as legacy (classifyRenderMode in svelte.ts); one it read as runes has an empty props type that would be unrecognized here, and its exported bindings are instance exports.

The props are what the type declares, so an export let name an authored $$Props leaves out is no prop: a typed consumer can't pass it.

Where svelte2tsx's props value departs from Svelte, the output follows it:

  • A binding exported both directly and through a renaming clause (export let a; export {a as b}) keeps only the renamed prop, without the binding's JSDoc. In TS it reads as optional.
  • An export clause written above its binding loses the binding's JSDoc too, and in TS reads as optional.
import {resolveLegacyPropsAnchor} from 'svelte-docinfo/svelte-legacy.ts';

parameters

propsValue

: Expression | undefined
#

the props value of the object $$render returns, when the virtual has one

returns

the anchor, or undefined when the value's shape isn't recognized or the checker throws

ResolverFailedDiagnostic
#

diagnostics.ts view source

value + type

Import resolver threw while resolving a specifier.

Distinguishes a buggy resolver from a legitimately unresolvable specifier: resolvers that return null for unknown specifiers stay silent (the normal "external package" case); resolvers that *throw* surface here so consumers can fix the resolver. Recoverable — the session treats the throw as null and continues, so analysis still runs but with a missing dependency edge. Durable on the entry until a later setFiles that adds paths resolves the specifier, which retires the diagnostic and adds the edge.

Emitted at ingest time by the session's resolve phase.

import {ResolverFailedDiagnostic} from 'svelte-docinfo/diagnostics.ts';

inheritance

extends: SchemaStrictObjectOutput<typeof ResolverFailedDiagnosticEntries>

members

kind

: "resolver_failed"
#

specifier

: string
#

The import specifier the resolver failed on.

file

: string
#

File path relative to project root (no leading slash, no ./ prefix).

Normalized at every public API boundary — session.setFile/setFiles (ingest-time), session.query (query-time, via analyzeCore), and the one-shot wrappers analyze / analyzeFromFiles. Producers inside the pipeline may write absolute or virtual paths (e.g., Foo.svelte.__svelte2tsx__.ts); normalization rewrites them to project-relative form before they reach consumers.

The exception is discovery — discoverSourceFiles / discoverFromExports return their diagnostics unnormalized, since they run before any session exists. Their file is already project-root-relative, but message can embed an absolute path (an fs error names the file it failed on), so a consumer wiring discovery up itself owns the normalizeDiagnosticPaths call — analyzeFromFiles and the Vite plugin both make it before merging.

The absolute form is the one to write. Normalization deliberately leaves an already-relative path alone (relativizing it would resolve against cwd), so a producer writing a ModuleJson.path — relative to sourceRoot, a different base — passes through untouched and publishes the same file under a second name. Absolute is what the pass can actually correct.

message

: string
#

Human-readable description of the issue.

severity

: "error" | "warning"
#

line

?: number
#

Line number (1-based), absent if location unavailable.

column

?: number
#

Column number (1-based), absent if location unavailable.

ResolverFailedDiagnosticInput
#

diagnostics.ts view source

The input ResolverFailedDiagnostic parses, with any field it defaults optional.

import type {ResolverFailedDiagnosticInput} from 'svelte-docinfo/diagnostics.ts';

inheritance

extends: SchemaStrictObjectInput<typeof ResolverFailedDiagnosticEntries>

members

kind

: "resolver_failed"
#

specifier

: string
#

The import specifier the resolver failed on.

file

: string
#

File path relative to project root (no leading slash, no ./ prefix).

Normalized at every public API boundary — session.setFile/setFiles (ingest-time), session.query (query-time, via analyzeCore), and the one-shot wrappers analyze / analyzeFromFiles. Producers inside the pipeline may write absolute or virtual paths (e.g., Foo.svelte.__svelte2tsx__.ts); normalization rewrites them to project-relative form before they reach consumers.

The exception is discovery — discoverSourceFiles / discoverFromExports return their diagnostics unnormalized, since they run before any session exists. Their file is already project-root-relative, but message can embed an absolute path (an fs error names the file it failed on), so a consumer wiring discovery up itself owns the normalizeDiagnosticPaths call — analyzeFromFiles and the Vite plugin both make it before merging.

The absolute form is the one to write. Normalization deliberately leaves an already-relative path alone (relativizing it would resolve against cwd), so a producer writing a ModuleJson.path — relative to sourceRoot, a different base — passes through untouched and publishes the same file under a second name. Absolute is what the pass can actually correct.

message

: string
#

Human-readable description of the issue.

severity

: "error" | "warning"
#

line

?: number
#

Line number (1-based), absent if location unavailable.

column

?: number
#

Column number (1-based), absent if location unavailable.

resolveTypeInfo
#

typescript-extract-type-json.ts view source

resolveTypeInfo(type: Type, checker: TypeChecker, aliasRegistry: AliasRegistry | undefined, optional: boolean, options?: ResolveTypeInfoOptions): TypeJson | undefined

The structured type for an output field, or undefined when the flat string is the whole story (the TypeJson absence contract).

Matches getTypeSignature's optional handling by construction — both select through optionalWideningTarget (see there for the case split); x?: undefined stays terminal. What's specific to the tree: union members walk the union's origin (see unionMemberTypes), so a null-bearing optional alias survives: dropping the widening from the origin list leaves the alias-carrying union as the sole member, which the 1-member collapse promotes to the root (a?: A where A is nullable yields the A union, matching the flat string's printed-string surgery). When no usable origin exists both degrade together, bounded: alias lost. Members then take the written order where a written union node is recoverable (writtenUnionMemberTypes), so they can list in a different order from the flat string, which always prints in the checker's.

Self-named alias roots relax the contract. checker.typeToString prints a type carrying an alias symbol as that alias's bare name, so a type alias's own typeSignature reads "StrArr", not "string[]" — there is no descriptive flat sibling for the tree to defer to, and the usual gate would leave type StrArr = string[] and type Pair = [string, number] with no type information at all. When the type reports ownAliasName as its alias the node is emitted regardless, except for the kinds members already covers (REDUNDANT_WITH_MEMBERS). Interned types (intrinsics, literals) never carry the alias symbol, so type Str = string still prints structurally and stays absent.

Recovered roots relax it too. When writtenNode or aliasRegistry names a nameless type, the tree emits {kind: 'reference', name} (see buildWrittenNameMap / recoveredReference) — and at the root that node is emitted even though a bare reference normally stays absent: a checker-named bare reference defers to a flat sibling printing the same name, while a recovered one stands against a flat sibling printing the anonymous expansion, so the name exists only in the tree.

Generated-alias roots relax it too. A type whose alias is svelte2tsx-generated (linkableAliasSymbol) prints as that name in the flat string ($$ComponentProps), which nothing exports, so the node is emitted with the structure expanded — and so is an array or tuple over one ($$ComponentProps[]), whose expanded object element wouldn't otherwise qualify (printsGeneratedAlias). At a type-alias declaration the REDUNDANT_WITH_MEMBERS kinds still stay absent, since members carries them.

import {resolveTypeInfo} from 'svelte-docinfo/typescript-extract-type-json.ts';

parameters

type

: Type
#

the checker type the flat string was printed from

checker

: TypeChecker
#

TypeScript type checker

aliasRegistry

: AliasRegistry | undefined
#

the analyzed set's alias registry, or undefined when no pre-pass ran; required so a call site can't silently opt out of registry recovery

optional

: boolean
#

whether the declaration site carries a ? token (pairs the widening strip, like getTypeSignature)

the declaration-site context: ownAliasName at a type-alias declaration (see BuildTypeJsonOptions.skipAliasName; also suppresses registry hits at the root — the self-skip), writtenNode wherever a written annotation exists (the name-recovery source for aliases TypeScript dropped, and the written order for union members)

ResolveTypeInfoOptions
#

typescript-extract-type-json.ts view source

Declaration-site context for resolveTypeInfo — see its param doc.

import type {ResolveTypeInfoOptions} from 'svelte-docinfo/typescript-extract-type-json.ts';

members

ownAliasName

?: string
#

At a type-alias declaration site, the alias's own name.

writtenNode

?: TypeNode
#

The declaration's written type annotation, when one exists.

always

?: boolean
#

Emit the node whatever its shape, for a position that has to carry one: a heritage entry, whose trees align by index with the text entries.

followWritten

?: boolean
#

Whether the tree follows writtenNode where the checker's reading would say something other than what was written (followWrittenAnnotation). Defaults to true; resolveWrittenTypeInfo turns it off for its own reading of the node, and a type-alias declaration root (ownAliasName) never follows, so the alias documents its definition.

resolveWrittenTypeInfo
#

typescript-extract-type-json.ts view source

resolveWrittenTypeInfo(node: TypeNode, ctx: WrittenTypeContext, always?: boolean): TypeJson | undefined

The structured type of a written type node whose flat sibling is its source text: a generic's constraint or default, a heritage entry, a braced @throws type. The tree follows what was written, so it says no more than the text beside it:

  • A reference keeps the written type arguments, each read the same way, never the checker's defaulted or expanded ones (Base stays bare, not Base<unknown>), and the name written, as exported (an import rename reads as the name its module exports). Where the checker already names the written entity, its node stays (a recovered alias with its module, an alias over a union written without arguments, with its members, since a union node can't carry them); where it looked through or lost a type alias, interface, or class (L<B> read as Base<B, B>, a generic lost alias like SchemaKeys<T>, a callable alias or interface read as function), the node is a reference to the name written. A reference through an import type (import('./a.ts').A<B>) reads the same way.
  • Array syntax and Array<A>/ReadonlyArray<A> are array nodes over the written element type.
  • A type operator, query, or computed type (keyof A, typeof a, typeof import('./a.ts'), A['b'], a conditional, mapped, or template literal type) is opaque: the checker would print what it computes to (keyof A as the union of keys, typeof a as the value's whole type). At the root it has no tree, so a renderer links the flat text; nested, or with always, it is {kind: 'other', text} over its verbatim source text, local names included.
  • Nested or with always, an object or function type literal losing a written name in the checker's printing is writtenLiteralNode's text.
  • Anything else (a union, intersection, tuple, or literal) is the checker's reading of the node, name recovery included, so a reference inside one reads as everywhere else in typeInfo, and a union's members and a tuple's elements follow their written nodes (followWrittenMember).

Each written type argument starts a fresh tree, so the depth cap applies per argument and a written chain is bounded by its source text instead.

import {resolveWrittenTypeInfo} from 'svelte-docinfo/typescript-extract-type-json.ts';

parameters

always

?: boolean = false
#

emit a node whatever its shape (ResolveTypeInfoOptions.always)

returns

undefined under the absence contract, and when the checker can't resolve the node at all (an unknown name, or a throw)

restElementForms
#

typescript-extract-type-json.ts view source

restElementForms(elementType: Type, checker: TypeChecker, aliasRegistry: AliasRegistry | undefined, writtenNode?: TypeNode): { type: string; typeInfo: TypeJson | undefined; }

Both output forms of a rest tuple element, which present it as the array it collects (...rest: B[] carries "B[]" and an array node) — the flat/structured counterpart of buildTuple's array rewrap, for extractSnippetParameters. Paired in one function so the two can't be half applied: a printed array beside a non-array tree would describe two different types.

The string prints through the checker's internal createArrayType so parenthesization is the printer's own — hand rules get the edges wrong (a readonly B[] element *must* parenthesize or readonly B[][] denotes a different type, a bare union needs parens, a unique symbol prints as a typeof query). If the internal factory disappears, the fallback parenthesizes everything but bare identifier paths — sometimes over-parenthesized, never a different type. The tree is presence-gated like any array node (present when the element is a reference or carries structure). writtenNode and aliasRegistry feed name recovery (and writtenNode union member order) like resolveTypeInfo's — the caller passes the same annotation and registry it hands the sibling tree, so the two projections of one element can't disagree on a recovered name.

import {restElementForms} from 'svelte-docinfo/typescript-extract-type-json.ts';

ReturnPredicateJson
#

types.ts view source

value + type

also exported from index.ts

A signature's type predicate (x is A) or assertion (asserts x is A, asserts x), which the return type beside it can't show: returnType is the checker's type for the return value, boolean or void. A renderer writes the return clause from this instead: asserts when asserts, then parameterName, then is and type when there is one.

import {ReturnPredicateJson} from 'svelte-docinfo/types.ts';

inheritance

extends: SchemaStrictObjectOutput<typeof ReturnPredicateJsonEntries>

members

parameterName

: string
#

The parameter the predicate narrows, or this for a this is A predicate.

asserts

: boolean
#

Whether it is an assertion (asserts x is A, asserts x), which returns void.

type

?: string
#

The type narrowed to; absent for a bare asserts x.

typeInfo

?: TypeJson
#

Structured type; absent when type is the whole story (see TypeJson).

ReturnPredicateJsonInput
#

types.ts view source

The input ReturnPredicateJson parses, with any field it defaults optional.

import type {ReturnPredicateJsonInput} from 'svelte-docinfo/types.ts';

inheritance

extends: SchemaStrictObjectInput<typeof ReturnPredicateJsonEntries>

members

parameterName

: string
#

The parameter the predicate narrows, or this for a this is A predicate.

asserts

?: boolean
#

Whether it is an assertion (asserts x is A, asserts x), which returns void.

type

?: string
#

The type narrowed to; absent for a bare asserts x.

typeInfo

?: TypeJson
#

Structured type; absent when type is the whole story (see TypeJson).

RootFileNames
#

typescript-program.ts view source

type string[] | ((tsconfigRoots: string[]) => string[])

Root files for the analysis program: a list, or a function from the tsconfig's roots to the ones to keep (it receives [] under tsconfig: false). Paths are absolute or relative to projectRoot.

By default every file the tsconfig includes is a root, so the cold cost of a program scales with the project — tests, routes, and config files are parsed and bound, along with the packages only they import — however few files are analyzed. The files a session or a one-shot entry analyzes, and their imports, are always in the program (they're roots of their own), so narrowing the roots changes output only where a type reaches a file through no import: an ambient declaration (declare global, a declare module augmentation, a script-style .d.ts) in a file nothing imports. Drop such a root and the types it declares resolve to any, with no diagnostic.

declarationFileRoots keeps the declaration files, the usual home of ambient types, and is the narrowing to reach for first:

rootFileNames: declarationFileRoots

[] roots nothing but the analyzed files — the fastest program, for projects known to declare no ambient types.

import type {RootFileNames} from 'svelte-docinfo/typescript-program.ts';

runCli
#

cli.ts view source

runCli(argv?: string[]): Promise<number>

Run the CLI with the given arguments.

import {runCli} from 'svelte-docinfo/cli.ts';

parameters

argv

?: string[] = process.argv
#

command line arguments (defaults to process.argv)

returns

exit code: 0 for success (including --help and --version), 1 if errors in diagnostics, 2 for CLI errors (an unknown flag, a missing or invalid option value) or any thrown analysis error (including an --on-duplicates throw collision)

scanCssVarReads
#

svelte-css.ts view source

scanCssVarReads(text: string, start?: number, end?: number): CssVarRead[]

Scan CSS text for its outermost var() reads, in source order.

A read nested in another one's fallback isn't returned (var(--a, var(--b)) reads --a, with var(--b) its fallback), and neither is anything in a string, a comment, or an unquoted url(). The function name matches case-insensitively, as CSS does; a var( with no -- name or no closing ) reads nothing.

import {scanCssVarReads} from 'svelte-docinfo/svelte-css.ts';

parameters

text

: string
#

CSS text, typically a declaration's value

start

?: number = 0
#

offset to start scanning at

end

?: number = text.length
#

offset to stop scanning at

returns

the reads, with offsets into text

scanLegacyExports
#

svelte-legacy.ts view source

scanLegacyExports(scriptSource: SourceFile): LegacyExports

Scan an instance script for legacy props and accessors.

Runes-less components declare props by exporting mutable bindings — export let a / export var a directly, or let a; export {a as b} for renames (the reserved-word workaround). export const / export function / export class are accessors, not props, and type-only exports aren't runtime bindings.

The scan says what the script exports, not what mode the component is in: a runes component can export a mutable binding too, as an instance export. The caller scans only a component svelte2tsx didn't read as runes (classifyRenderMode in svelte.ts).

The scan reads the *original* instance script because svelte2tsx rewrites the export modifier away inside $$render; a purely syntactic walk over top-level statements is all it needs. It's also where defaults come from: defaultValue is the initializer's source text as the author wrote it.

import {scanLegacyExports} from 'svelte-docinfo/svelte-legacy.ts';

parameters

scriptSource

: SourceFile
#

parsed instance <script> content from the original source

returns

props in source order (empty when the script exports no mutable binding) and accessor names

ScannedScriptTag
#

svelte-scripts.ts view source

A script tag the scan matched, before anything has decided whether it's top-level.

import type {ScannedScriptTag} from 'svelte-docinfo/svelte-scripts.ts';

inheritance

members

open

: number
#

Offset of the tag's opening <, which is where Svelte's parser places the script.

end

: number
#

Offset just past the tag's closing >.

provenTopLevel

: boolean
#

Whether the scan alone proves the tag top-level, with no parser: see scanScriptTags for the proof and its conditions.

scanScriptTags
#

svelte-scripts.ts view source

scanScriptTags(svelteSource: string): ScannedScriptTag[]

Scan Svelte source for script tags with content, in source order, and mark the ones the scan itself proves top-level.

The scan is syntactic and knows nothing about nesting, so it returns nested tags too; findScriptTags is the function that answers which are the component's. Limits: whitespace around an attribute = makes a tag unmatchable (Svelte rejects one of those spellings, and svelte2tsx matches neither), and </script> in a string literal ends the content early.

provenTopLevel holds for a tag when everything from the start of the file to it is whitespace, complete HTML comments, and earlier script tags that are themselves proven. Svelte's parser reads each of those at the root and comes back to the root: whitespace is text, a comment runs to the first -->, and a top-level script runs from its opening tag to the first </script>, the same extents the regex matched. So it meets this tag at the root, where a <script> is the instance or module script.

Anything that would need more than that argument leaves the tag unproven, along with every tag after it:

  • any other text or markup before the tag: a <style>, <svelte:options>, an unterminated comment, what's left over when a </script> in a string ended an earlier match early, and tags the regex doesn't match (<SCRIPT>, a spelling with whitespace around =)
  • a self-closing <script />, which Svelte's parser rejects at the top level
  • attributes outside UNAMBIGUOUS_ATTRIBUTES_MATCHER
import {scanScriptTags} from 'svelte-docinfo/svelte-scripts.ts';

ScriptTagsDecision
#

svelte-scripts.ts view source

type "scan" | "parser" | "unparsed"

How findScriptTags decided which tags are top-level:

  • 'scan' — the scan proved every tag top-level (provenTopLevel), so nothing was parsed
  • 'parser' — Svelte's parser said which tags are the instance and module scripts
  • 'unparsed' — the parser threw, and every matched tag is returned
import type {ScriptTagsDecision} from 'svelte-docinfo/svelte-scripts.ts';

scrubVirtualSuffixes
#

source.ts view source

scrubVirtualSuffixes(text: string): string

Remove every occurrence of the virtual suffix from free-form text.

The text twin of stripVirtualSuffix: that one strips a path's trailing suffix, this one scrubs a prose string (a diagnostic message) that may embed virtual paths anywhere. Both readings of the suffix live here so a suffix change has one home.

import {scrubVirtualSuffixes} from 'svelte-docinfo/source.ts';

selectDeclarationNode
#

typescript-extract-shared.ts view source

selectDeclarationNode(symbol: Symbol): Declaration | undefined

Select the declaration node that carries a symbol's documented meaning.

Mirrors inferDeclarationKind's flag priority. A symbol can merge value and type meanings — const Foo = ... + type Foo = ... (the schema/type pattern) or const Foo + interface Foo share one symbol with combined flags — and there valueDeclaration points at the value while the flags resolve a type-space kind, so value-first selection would document the value's type under the type's kind. When the flags resolve type-space (interface, type, enum), the first matching type-space declaration is selected instead; value-space kinds (and unmerged symbols) keep the valueDeclaration-first selection. The merged value meaning goes undocumented under the one-declaration-per-export-name model — the type is what consumers look up. A class+interface merge resolves value-space (class), so it documents the class with no doc fallback and no mergedValue marker — a class already implies value+type.

JS merges the same way: const Foo = … beside @typedef {…} Foo selects the typedef tag, as type Foo would be. A JS @enum const selects its value declaration, which holds the members (isJSDocEnumSymbol).

import {selectDeclarationNode} from 'svelte-docinfo/typescript-extract-shared.ts';

SetFileOptions
#

session.ts view source

also exported from index.ts

Options for a per-file or per-batch resolver override.

import type {SetFileOptions} from 'svelte-docinfo/session.ts';

members

resolveImport

?: ResolveImport
#

Per-call override of the session-default resolver — a bare ResolveImportFn or a token-paired ImportResolver (see ResolveImport).

A bare function is normalized with a fresh identity on each call, so the files touched by this call re-resolve rather than cache-hitting — the expected behavior for a deliberate one-off override. To reuse the resolve cache across calls, pass an ImportResolver with a stable identity.

context

?: boolean = false
#

The role the call's files take: false (the default) makes them *inputs*, which emit a module when they pass isSource; true makes them *context*, which feed the checker and never emit.

The role is set by every call, not only the first, so a consumer forwarding edits has to say which it means. Passing a file the context closure ingested (see AnalysisSessionOptions.contextClosure) without this makes it an input, and its module appears in the next query(); a watcher refreshing such a file passes true to leave it context. Passing true for a file that is an input removes its module. Either change of role is reported as changed, content edit or not.

SetFileResult
#

session.ts view source

also exported from index.ts

Result of setFile (single-file ingest).

changed is true when content or the mode-specific cache key (resolver identity for lex+resolve; dependency snapshot for pre-resolved) differed from the cached entry — the owned entry was rewritten. An LS push accompanies the entry write only when the file is TS/JS or has a successful Svelte virtual; CSS/JSON and transform-failed Svelte rewrite the entry without touching the LS. false indicates a cache-hit no-op: the cached ingestDiagnostics are returned but no work ran.

import type {SetFileResult} from 'svelte-docinfo/session.ts';

members

changed

: boolean
#

Whether content or the mode-specific cache key differed from the cached entry.

diagnostics

: Diagnostic[]
#

Ingest-time diagnostics for this file (durable on the entry).

SetFilesResult
#

session.ts view source

also exported from index.ts

Result of setFiles (batch ingest).

Carries both aggregate views (changedIds, pre-flattened diagnostics) and a structured perFile map. HMR-style consumers want changedIds.size > 0 as the hot check; LSP-style consumers want per-file diagnostic association via perFile. Both are populated in the same single-pass walk over the batch — no extra cost.

import type {SetFilesResult} from 'svelte-docinfo/session.ts';

members

changedIds

: ReadonlySet<string>
#

IDs whose content or mode-specific cache key differed from the cached entry — the subset of input file IDs that actually triggered work. Empty when every file was a cache-hit no-op.

diagnostics

: Diagnostic[]
#

Pre-flattened union of every file's ingestDiagnostics. Consumers can group by Diagnostic.file for per-file publish — already project-root-relative, normalized at rest before the entry was stored.

The array is fresh but its elements are the *stored* diagnostic objects, so mutating one (re-running normalizeDiagnosticPaths against a different root, say) corrupts the session's own state. Copy before mutating.

perFile

: ReadonlyMap<string, SetFileResult>
#

Per-file SetFileResult keyed by input file ID. Use this when the grouping Diagnostic.file would do isn't enough — e.g., LSP wanting to publish empty-diagnostic-list updates for files that ingested cleanly.

SignatureAnalysisDiagnostic
#

diagnostics.ts view source

value + type

Function/method signature analysis failed.

import {SignatureAnalysisDiagnostic} from 'svelte-docinfo/diagnostics.ts';

inheritance

extends: SchemaStrictObjectOutput<typeof SignatureAnalysisDiagnosticEntries>

members

kind

: "signature_analysis_failed"
#

functionName

: string
#

Name of the function or method.

file

: string
#

File path relative to project root (no leading slash, no ./ prefix).

Normalized at every public API boundary — session.setFile/setFiles (ingest-time), session.query (query-time, via analyzeCore), and the one-shot wrappers analyze / analyzeFromFiles. Producers inside the pipeline may write absolute or virtual paths (e.g., Foo.svelte.__svelte2tsx__.ts); normalization rewrites them to project-relative form before they reach consumers.

The exception is discovery — discoverSourceFiles / discoverFromExports return their diagnostics unnormalized, since they run before any session exists. Their file is already project-root-relative, but message can embed an absolute path (an fs error names the file it failed on), so a consumer wiring discovery up itself owns the normalizeDiagnosticPaths call — analyzeFromFiles and the Vite plugin both make it before merging.

The absolute form is the one to write. Normalization deliberately leaves an already-relative path alone (relativizing it would resolve against cwd), so a producer writing a ModuleJson.path — relative to sourceRoot, a different base — passes through untouched and publishes the same file under a second name. Absolute is what the pass can actually correct.

message

: string
#

Human-readable description of the issue.

severity

: "error" | "warning"
#

line

?: number
#

Line number (1-based), absent if location unavailable.

column

?: number
#

Column number (1-based), absent if location unavailable.

SignatureAnalysisDiagnosticInput
#

diagnostics.ts view source

The input SignatureAnalysisDiagnostic parses, with any field it defaults optional.

import type {SignatureAnalysisDiagnosticInput} from 'svelte-docinfo/diagnostics.ts';

inheritance

extends: SchemaStrictObjectInput<typeof SignatureAnalysisDiagnosticEntries>

members

kind

: "signature_analysis_failed"
#

functionName

: string
#

Name of the function or method.

file

: string
#

File path relative to project root (no leading slash, no ./ prefix).

Normalized at every public API boundary — session.setFile/setFiles (ingest-time), session.query (query-time, via analyzeCore), and the one-shot wrappers analyze / analyzeFromFiles. Producers inside the pipeline may write absolute or virtual paths (e.g., Foo.svelte.__svelte2tsx__.ts); normalization rewrites them to project-relative form before they reach consumers.

The exception is discovery — discoverSourceFiles / discoverFromExports return their diagnostics unnormalized, since they run before any session exists. Their file is already project-root-relative, but message can embed an absolute path (an fs error names the file it failed on), so a consumer wiring discovery up itself owns the normalizeDiagnosticPaths call — analyzeFromFiles and the Vite plugin both make it before merging.

The absolute form is the one to write. Normalization deliberately leaves an already-relative path alone (relativizing it would resolve against cwd), so a producer writing a ModuleJson.path — relative to sourceRoot, a different base — passes through untouched and publishes the same file under a second name. Absolute is what the pass can actually correct.

message

: string
#

Human-readable description of the issue.

severity

: "error" | "warning"
#

line

?: number
#

Line number (1-based), absent if location unavailable.

column

?: number
#

Column number (1-based), absent if location unavailable.

SignatureReturnTarget
#

signatureTypeParameters
#

typescript-extract-shared.ts view source

signatureTypeParameters(decl: Node | undefined): readonly TypeParameterDeclaration[] | undefined

A signature declaration's own type parameters, the checker's reading (ts.getEffectiveTypeParameterDeclarations), so a JS function or method's @template tags count like <T>, and an @overload's are its block's @template tags (a block of several overloads gives each of them its templates, as the checker does; one inside the overload's signature, after its @overload and before its last @param/@returns, is a parse error the checker drops; one at the block's end is accepted). An implementation with @overload tags (firstJSDocOverloadSignature) reads its first overload's, as a TypeScript function's generics are its first overload's; its own @template tags are hidden with it. None for a @callback's signature: its templates document on the alias (typeAliasTypeParameters), as a generic type A<T> = (x: T) => T keeps T off its (call) member.

import {signatureTypeParameters} from 'svelte-docinfo/typescript-extract-shared.ts';

SnippetDeclarationJson
#

types.ts view source

value + type

also exported from index.ts

A Svelte snippet declaration exported from <script module>. Has parameters.

import {SnippetDeclarationJson} from 'svelte-docinfo/types.ts';

inheritance

extends: SchemaStrictObjectOutput<typeof SnippetDeclarationJsonEntries>

members

kind

: "snippet"
#

parameters

: ParameterJson[]
#

Snippet parameters.

alsoExportedFrom

: string[]
#

Module paths (relative to sourceRoot) that re-export this declaration under the same name. The canonical declaration lives in this module's declarations array; these paths are additional import locations for the same thing.

The same edges appear from the re-exporting side as ModuleJson.reExports — use that when asking "what does this module re-export" instead of inverting these arrays. The two can disagree at the margins: a reExports entry whose canonical declaration is @nodocs (or whose module isn't in the analyzed set) has no back-link here.

Consumer note: To build a complete re-export map, scan two fields:

  1. alsoExportedFrom on each declaration — same-name re-exports
  2. aliasOf on declarations — renamed re-exports (separate declarations)

partial

: boolean
#

Whether extraction failed partway through, leaving some fields missing (e.g., typeSignature, parameters).

examples

: string[]
#

Code examples from @example tags.

seeAlso

: string[]
#

Related items from @see tags, in raw TSDoc format.

throws

: ThrowsJson[]
#

Exceptions from @throws tags. type is the tag's written type, and typeInfo its structured form, present for a braced type (@throws {A<B>}) that isn't the whole story as text (see TypeJson); an unbraced tag's leading word never has one, nor does a tag in a component's HTML @component comment, which is read as text.

name

: string
#

The exported name. Always populated. The default-export slot is named 'default', except a Svelte component, which takes its filename-derived name ('X' for X.svelte) — 'default' is the symbol's actual name in JS (import {default as X} and ns.default both expose it directly), and import X from 'mod' is sugar for import {default as X}. Consumers branch on name === 'default' to render the sugar form when desired.

modifiers

: ("public" | "protected" | "readonly" | "static" | "abstract" | "getter" | "setter")[]
#

TypeScript modifiers like readonly, static, or protected.

genericParams

: GenericParamJson[]
#

Generic type parameters like <T, U>.

aliasOf

?: { module: string; name: string; }
#

For renamed re-exports (export {foo as bar}), points to the original declaration. This declaration's name is the alias; aliasOf.name is the original name.

For renames out of the default slot (export {default as bar} from './x' where ./x is export default ...), aliasOf.name is 'default' — the canonical's actual symbol name. Consumers locate the canonical by (aliasOf.module, aliasOf.name).

Svelte component exception: when the source is a .svelte file (e.g., export {default as Foo} from './X.svelte'), the canonical's name is the component name (derived from the filename), so aliasOf.name is the component name ('X'), NOT 'default'. Consumers that branch on aliasOf.name === 'default' to detect default-rename should additionally check whether aliasOf.module ends with .svelte.

Different from alsoExportedFrom: aliases create new API surface names, while alsoExportedFrom tracks additional import paths for the same name.

A type-only rename of a value (export type {someConst as c} from './x') synthesizes a normal alias — declarations carry no type-only marker.

deprecatedMessage

?: string
#

Deprecation message from @deprecated tag.

since

?: string
#

Version introduced, from @since tag.

internalMessage

?: string
#

Internal-API marker from the @internal tag. Presence means the tag was written; an empty string is a bare tag with no trailing prose.

A marker, not an exclusion: @internal means "not stable public API" (TSDoc semantics) while the declaration, member, or prop stays documented — unlike @nodocs, which removes a declaration from output entirely (and is ignored on props and members).

mutates

?: Record<string, string>
#

Mutation documentation from @mutates tags (non-standard), mapping keys to descriptions.

Keys are intentionally unvalidated — typically a parameter name, but authors may also use compound paths (this.foo, obj.field) or multi-word external state references. Backticks are stripped from keys so `` a `` and a normalize to one key; an empty-string value is a bare tag with no description. The schema accepts any string key so consumers can render whatever the author wrote.

On a component prop it declares the component's mutation contract for the value it's handed: the component writes into the prop's object or array in place (@mutates items - appends the selected entry, @mutates options.cache - fills on first render). Reassigning a prop is not a mutation in this sense (bindable covers it), though a $bindable prop can carry both.

docComment

?: string
#

JSDoc/TSDoc comment.

typeSignature

?: string
#

Full TypeScript type signature.

sourceLine

?: number
#

1-based line in the source file, a positive integer. Synthesized aliases (see aliasOf) carry the local export specifier's line, not the canonical's.

SnippetDeclarationJsonInput
#

types.ts view source

The input SnippetDeclarationJson parses, with any field it defaults optional.

import type {SnippetDeclarationJsonInput} from 'svelte-docinfo/types.ts';

inheritance

extends: SchemaStrictObjectInput<typeof SnippetDeclarationJsonEntries>

members

kind

: "snippet"
#

name

: string
#

The exported name. Always populated. The default-export slot is named 'default', except a Svelte component, which takes its filename-derived name ('X' for X.svelte) — 'default' is the symbol's actual name in JS (import {default as X} and ns.default both expose it directly), and import X from 'mod' is sugar for import {default as X}. Consumers branch on name === 'default' to render the sugar form when desired.

parameters

?: ParameterJsonInput[]
#

Snippet parameters.

alsoExportedFrom

?: string[]
#

Module paths (relative to sourceRoot) that re-export this declaration under the same name. The canonical declaration lives in this module's declarations array; these paths are additional import locations for the same thing.

The same edges appear from the re-exporting side as ModuleJson.reExports — use that when asking "what does this module re-export" instead of inverting these arrays. The two can disagree at the margins: a reExports entry whose canonical declaration is @nodocs (or whose module isn't in the analyzed set) has no back-link here.

Consumer note: To build a complete re-export map, scan two fields:

  1. alsoExportedFrom on each declaration — same-name re-exports
  2. aliasOf on declarations — renamed re-exports (separate declarations)

aliasOf

?: { module: string; name: string; }
#

For renamed re-exports (export {foo as bar}), points to the original declaration. This declaration's name is the alias; aliasOf.name is the original name.

For renames out of the default slot (export {default as bar} from './x' where ./x is export default ...), aliasOf.name is 'default' — the canonical's actual symbol name. Consumers locate the canonical by (aliasOf.module, aliasOf.name).

Svelte component exception: when the source is a .svelte file (e.g., export {default as Foo} from './X.svelte'), the canonical's name is the component name (derived from the filename), so aliasOf.name is the component name ('X'), NOT 'default'. Consumers that branch on aliasOf.name === 'default' to detect default-rename should additionally check whether aliasOf.module ends with .svelte.

Different from alsoExportedFrom: aliases create new API surface names, while alsoExportedFrom tracks additional import paths for the same name.

A type-only rename of a value (export type {someConst as c} from './x') synthesizes a normal alias — declarations carry no type-only marker.

partial

?: boolean
#

Whether extraction failed partway through, leaving some fields missing (e.g., typeSignature, parameters).

examples

?: string[]
#

Code examples from @example tags.

deprecatedMessage

?: string
#

Deprecation message from @deprecated tag.

seeAlso

?: string[]
#

Related items from @see tags, in raw TSDoc format.

throws

?: ThrowsJsonInput[]
#

Exceptions from @throws tags. type is the tag's written type, and typeInfo its structured form, present for a braced type (@throws {A<B>}) that isn't the whole story as text (see TypeJson); an unbraced tag's leading word never has one, nor does a tag in a component's HTML @component comment, which is read as text.

since

?: string
#

Version introduced, from @since tag.

internalMessage

?: string
#

Internal-API marker from the @internal tag. Presence means the tag was written; an empty string is a bare tag with no trailing prose.

A marker, not an exclusion: @internal means "not stable public API" (TSDoc semantics) while the declaration, member, or prop stays documented — unlike @nodocs, which removes a declaration from output entirely (and is ignored on props and members).

mutates

?: Record<string, string>
#

Mutation documentation from @mutates tags (non-standard), mapping keys to descriptions.

Keys are intentionally unvalidated — typically a parameter name, but authors may also use compound paths (this.foo, obj.field) or multi-word external state references. Backticks are stripped from keys so `` a `` and a normalize to one key; an empty-string value is a bare tag with no description. The schema accepts any string key so consumers can render whatever the author wrote.

On a component prop it declares the component's mutation contract for the value it's handed: the component writes into the prop's object or array in place (@mutates items - appends the selected entry, @mutates options.cache - fills on first render). Reassigning a prop is not a mutation in this sense (bindable covers it), though a $bindable prop can carry both.

docComment

?: string
#

JSDoc/TSDoc comment.

typeSignature

?: string
#

Full TypeScript type signature.

modifiers

?: ("public" | "protected" | "readonly" | "static" | "abstract" | "getter" | "setter")[]
#

TypeScript modifiers like readonly, static, or protected.

sourceLine

?: number
#

1-based line in the source file, a positive integer. Synthesized aliases (see aliasOf) carry the local export specifier's line, not the canonical's.

genericParams

?: GenericParamJsonInput[]
#

Generic type parameters like <T, U>.

sortModules
#

postprocess.ts view source

sortModules(modules: ModuleJson[]): ModuleJson[]

Sort modules alphabetically by path for deterministic output and cleaner diffs.

Case-insensitive order (compareStrings) so the output is environment-independent.

import {sortModules} from 'svelte-docinfo/postprocess.ts';

parameters

modules

: ModuleJson[]
#

the modules to sort

returns

a new sorted array (does not mutate input)

SourceFileInfo
#

source.ts view source

also exported from index.ts

File information for source analysis.

Provides file content to analysis functions from any source: file system, build pipeline, or in-memory.

Note: content is required so callers control what the checker sees for the files they supply. Files they don't (context-closure files, node_modules, other unowned imports) are read from disk.

import type {SourceFileInfo} from 'svelte-docinfo/source.ts';

members

id

: string
#

Absolute path to the file. Native paths are fine at the boundary — ids are posixified at ingest (see paths.ts).

content

: string
#

File content (required — the checker sees this, not the disk, for ingested files).

dependencies

?: readonly string[]
#

Pre-resolved absolute file paths of modules this file imports.

Opt-in optimization — when supplied, the session treats this as the authoritative dependency set for the file and skips its own lex+resolve pass for this entry. Build-tool integrations that already maintain a dependency graph can hand it over directly instead of paying the lex+resolve cost twice.

Omit (undefined) → default behavior — the session lexes import specifiers from content and resolves them via its ImportResolver. This is the right choice when the caller doesn't already have a graph.

Only include resolved local imports — node_modules paths are filtered out at storage time by the configured isSource predicate either way.

Trust contract — the session treats this array as authoritative and does not cross-check against the file's content. Edges declared here are accepted as-is, even if the source code doesn't actually import them; edges that *are* in content but missing from this array are silently omitted. The lex+resolve fallback path has no such hole — its edges are always grounded in syntactic imports. Build-tool integrations that supply this field own the correctness of the graph they hand over.

Type-only imports (import type {...}) are the most common asymmetry versus the lex+resolve path: the default lex (lexImports) keeps type-only imports and re-exports; pre-resolved callers backed by a build tool's import graph often drop them. Both are intentional within their respective contracts.

Cache semantics: the session compares this array element-wise (shallow equality) against the snapshot stored from the prior call — a fresh array with identical contents cache-hits, while any length, element, or order difference invalidates. Callers that produce fresh arrays per call (e.g., [...dependencies.keys()] from a graph's Map) reuse the cache cleanly across persistent-session calls.

Order is significant. Reordering without a content change is treated as a real change — sort upstream if you want order-insensitive caching. Map-iteration-order callers (e.g., a module graph emitting [...dependencies.keys()]) are naturally stable across calls for the same content, so no defensive sort is needed there.

SourceMapFailedDiagnostic
#

diagnostics.ts view source

value + type

Source map parsing failed for a Svelte virtual file.

Analysis continues without position mapping: query-time diagnostics drop line/column rather than point into svelte2tsx-generated TS — those emitted against the virtual via remapVirtualDiagnosticPositions, svelte_prop_failed at its own emission site — while declaration sourceLines fall back to virtual positions. Rare; usually signals a malformed or incompatible svelte2tsx output.

Emitted at ingest time by transformSvelteSource (in svelte.ts); flows through setFile/setFiles ingest diagnostics rather than the analysis pass.

import {SourceMapFailedDiagnostic} from 'svelte-docinfo/diagnostics.ts';

inheritance

extends: SchemaStrictObjectOutput<typeof SourceMapFailedDiagnosticEntries>

members

kind

: "source_map_failed"
#

file

: string
#

File path relative to project root (no leading slash, no ./ prefix).

Normalized at every public API boundary — session.setFile/setFiles (ingest-time), session.query (query-time, via analyzeCore), and the one-shot wrappers analyze / analyzeFromFiles. Producers inside the pipeline may write absolute or virtual paths (e.g., Foo.svelte.__svelte2tsx__.ts); normalization rewrites them to project-relative form before they reach consumers.

The exception is discovery — discoverSourceFiles / discoverFromExports return their diagnostics unnormalized, since they run before any session exists. Their file is already project-root-relative, but message can embed an absolute path (an fs error names the file it failed on), so a consumer wiring discovery up itself owns the normalizeDiagnosticPaths call — analyzeFromFiles and the Vite plugin both make it before merging.

The absolute form is the one to write. Normalization deliberately leaves an already-relative path alone (relativizing it would resolve against cwd), so a producer writing a ModuleJson.path — relative to sourceRoot, a different base — passes through untouched and publishes the same file under a second name. Absolute is what the pass can actually correct.

message

: string
#

Human-readable description of the issue.

severity

: "error" | "warning"
#

line

?: number
#

Line number (1-based), absent if location unavailable.

column

?: number
#

Column number (1-based), absent if location unavailable.

SourceMapFailedDiagnosticInput
#

diagnostics.ts view source

The input SourceMapFailedDiagnostic parses, with any field it defaults optional.

import type {SourceMapFailedDiagnosticInput} from 'svelte-docinfo/diagnostics.ts';

inheritance

extends: SchemaStrictObjectInput<typeof SourceMapFailedDiagnosticEntries>

members

kind

: "source_map_failed"
#

file

: string
#

File path relative to project root (no leading slash, no ./ prefix).

Normalized at every public API boundary — session.setFile/setFiles (ingest-time), session.query (query-time, via analyzeCore), and the one-shot wrappers analyze / analyzeFromFiles. Producers inside the pipeline may write absolute or virtual paths (e.g., Foo.svelte.__svelte2tsx__.ts); normalization rewrites them to project-relative form before they reach consumers.

The exception is discovery — discoverSourceFiles / discoverFromExports return their diagnostics unnormalized, since they run before any session exists. Their file is already project-root-relative, but message can embed an absolute path (an fs error names the file it failed on), so a consumer wiring discovery up itself owns the normalizeDiagnosticPaths call — analyzeFromFiles and the Vite plugin both make it before merging.

The absolute form is the one to write. Normalization deliberately leaves an already-relative path alone (relativizing it would resolve against cwd), so a producer writing a ModuleJson.path — relative to sourceRoot, a different base — passes through untouched and publishes the same file under a second name. Absolute is what the pass can actually correct.

message

: string
#

Human-readable description of the issue.

severity

: "error" | "warning"
#

line

?: number
#

Line number (1-based), absent if location unavailable.

column

?: number
#

Column number (1-based), absent if location unavailable.

SourceOptionsDefaults
#

source-config.ts view source

also exported from index.ts

Default source options preset (without projectRoot).

Use with createSourceOptions to build complete options. Contains all ModuleSourceOptions fields except projectRoot, which is provided separately as the first argument to createSourceOptions.

import type {SourceOptionsDefaults} from 'svelte-docinfo/source-config.ts';

members

sourcePaths

: string[]
#

Source directory paths to include, relative to projectRoot.

Absolute entries are accepted when they resolve inside projectRoot and are stored root-relative; an entry resolving outside it throws (a root-anchored '/src/lib' is taken as filesystem-absolute, not shorthand — the error hints to drop the slash). Normalized (./.. segments collapsed, trailing slashes stripped) by normalizeSourceOptions, which returns a new options object.

['src/lib'] // single source directory
['src/lib', 'src/routes'] // multiple directories

sourceRoot

?: string
#

Source root for extracting relative module paths, relative to projectRoot.

Normalized like sourcePaths entries (absolute-inside-root accepted and stored root-relative, ./.. collapsed — so '.' becomes '', trailing slashes stripped, out-of-root throws) by normalizeSourceOptions, which returns a new options object.

When omitted:

  • Single sourcePath: defaults to that path
  • Multiple sourcePaths: auto-derived as the longest common directory prefix (or '' when paths share no common prefix — produces project-relative module paths)
'src/lib' // module paths like 'foo.ts', 'utils/bar.ts'
'src' // module paths like 'lib/foo.ts', 'routes/page.svelte'
'' // or '.': module paths stay project-relative, e.g. 'src/lib/foo.ts'

exclude

: string[] = `['**\/*.{test,spec}.{ts,mts,tsx,js,mjs,jsx}', '**\/internal/**']`
#

Glob patterns to exclude from analysis, relative to projectRoot; an absolute pattern inside the root relativizes at normalizeSourceOptions, an out-of-root one throws.

Applied at both stages of the pipeline:

  • Discovery time by globFiles/discoverFromExports, preventing matched files from being loaded.
  • Analysis time by isSource() against relative(projectRoot, absolutePath), which gates both the emitted module set (query()) and dependency edges.

Beneath it, the always-on baseline (node_modules + dot-directories below a matched source path — see hasBaselineExcludedSegment) applies independently; overriding exclude can't strip it.

The defaults exclude tests and internal/ directories — the src/lib/internal/ convention: internal modules ship in the package for public modules to import (typically paired with an "./internal/*": null package.json exports entry blocking consumer imports), but aren't part of the documented surface. The override surfaces accept a (defaults) => patterns callback (see ExcludeOption) so extending the defaults doesn't require restating them; this normalized field is always a plain array.

analyzeFromFiles and the Vite plugin accept a top-level exclude that replaces this field (no merge).

Compiled to a matcher once per options object via picomatch and cached by reference; mutating this array post-isSource-call has no effect — pass through normalizeSourceOptions (which returns a fresh object) or otherwise build a new options object to apply changes.

getAnalyzerType

: (path: string) => AnalyzerType | null = `getDefaultAnalyzer` (by file extension)
#

Determine which analyzer to use for a file path.

Called wherever the pipeline classifies a path (ingest, every isSource check, context-closure candidates), so keep it cheap and pure. Return an AnalyzerType (see there for what each analyzes) or null to skip.

Extend the default table by delegating to getDefaultAnalyzer (exported from the main barrel) for everything but the added case — restating the table drifts when it grows.

// Add MDsveX support getAnalyzerType: (path) => (path.endsWith('.svx') ? 'svelte' : getDefaultAnalyzer(path))
// Include .d.ts files (the default excludes them) getAnalyzerType: (path) => (path.endsWith('.d.ts') ? 'typescript' : getDefaultAnalyzer(path))

SourceOptionsOverrides
#

source-config.ts view source

also exported from index.ts

type Omit<Partial<SourceOptionsDefaults>, "exclude"> & { exclude?: ExcludeOption; }

Override surface for building ModuleSourceOptions: all fields optional, with exclude widened to ExcludeOption so callers can extend the default patterns instead of replacing them. Accepted by createSourceOptions / createSourceOptionsWithInclude and the option types layered on them (AnalyzeFromFilesOptions.sourceOptions, the Vite plugin's sourceOptions).

import type {SourceOptionsOverrides} from 'svelte-docinfo/source-config.ts';

members

sourcePaths

?: string[]
#

Source directory paths to include, relative to projectRoot.

Absolute entries are accepted when they resolve inside projectRoot and are stored root-relative; an entry resolving outside it throws (a root-anchored '/src/lib' is taken as filesystem-absolute, not shorthand — the error hints to drop the slash). Normalized (./.. segments collapsed, trailing slashes stripped) by normalizeSourceOptions, which returns a new options object.

['src/lib'] // single source directory
['src/lib', 'src/routes'] // multiple directories

sourceRoot

?: string
#

Source root for extracting relative module paths, relative to projectRoot.

Normalized like sourcePaths entries (absolute-inside-root accepted and stored root-relative, ./.. collapsed — so '.' becomes '', trailing slashes stripped, out-of-root throws) by normalizeSourceOptions, which returns a new options object.

When omitted:

  • Single sourcePath: defaults to that path
  • Multiple sourcePaths: auto-derived as the longest common directory prefix (or '' when paths share no common prefix — produces project-relative module paths)
'src/lib' // module paths like 'foo.ts', 'utils/bar.ts'
'src' // module paths like 'lib/foo.ts', 'routes/page.svelte'
'' // or '.': module paths stay project-relative, e.g. 'src/lib/foo.ts'

getAnalyzerType

?: (path: string) => AnalyzerType | null = `getDefaultAnalyzer` (by file extension)
#

Determine which analyzer to use for a file path.

Called wherever the pipeline classifies a path (ingest, every isSource check, context-closure candidates), so keep it cheap and pure. Return an AnalyzerType (see there for what each analyzes) or null to skip.

Extend the default table by delegating to getDefaultAnalyzer (exported from the main barrel) for everything but the added case — restating the table drifts when it grows.

// Add MDsveX support getAnalyzerType: (path) => (path.endsWith('.svx') ? 'svelte' : getDefaultAnalyzer(path))
// Include .d.ts files (the default excludes them) getAnalyzerType: (path) => (path.endsWith('.d.ts') ? 'typescript' : getDefaultAnalyzer(path))

exclude

?: ExcludeOption
#

specifierExportedName
#

typescript-extract-type-json.ts view source

specifierExportedName(symbol: Symbol): string | undefined

The name a module exports an aliased symbol under, or undefined when the alias names no export (a default or namespace import, a star re-export).

The one rule shared by both name-recovery channels — this file's written-name lookup and externalTypeRefText's textual substitution (typescript-extract-shared.ts). Both specifier kinds carry the name, on opposite sides of their own as: an ImportSpecifier takes the module's side, its propertyName (import type {Bag as B} → Bag, B being this file's private spelling), while an ExportSpecifier *is* the module's side, so its name is what it publishes (export {Internal as Public} → Public, Internal being the other module's). Unrenamed, both collapse to the one name written.

Stopping at a specifier rather than resolving the whole alias chain is what makes the result importable: the chain ends at the *declaration's* name, which a module renaming on the way out never exports — recovering Internal there names something no consumer of that module can reach.

import {specifierExportedName} from 'svelte-docinfo/typescript-extract-type-json.ts';

stripVirtualSuffix
#

source.ts view source

stripVirtualSuffix(path: string): string

Strip the svelte2tsx virtual file suffix from a path, if present.

Maps Component.svelte.__svelte2tsx__.ts back to Component.svelte. Returns the path unchanged if the suffix is not present.

import {stripVirtualSuffix} from 'svelte-docinfo/source.ts';

SVELTE_COMPONENT_ALIAS_SUFFIX
#

source.ts view source

"__SvelteComponent_"

Suffix svelte2tsx appends to the synthesized component const/type alias (<Name>__SvelteComponent_). One of the generated-identifier shapes isSvelte2tsxInternal filters.

import {SVELTE_COMPONENT_ALIAS_SUFFIX} from 'svelte-docinfo/source.ts';

SVELTE_VIRTUAL_SUFFIX
#

source.ts view source

".__svelte2tsx__.ts"

Suffix appended to .svelte file paths to create virtual TypeScript file paths.

Used by svelte2tsx integration: Component.svelte → Component.svelte.__svelte2tsx__.ts.

import {SVELTE_VIRTUAL_SUFFIX} from 'svelte-docinfo/source.ts';

SvelteFileStatus
#

typescript-extract-shared.ts view source

type "virtual" | "virtualless" | "missing"

What an extraction pass can see of a .svelte file at an absolute POSIX path, which decides how a relative .svelte re-export reads:

  • 'virtual' — the program has its svelte2tsx virtual, so ordinary resolution applies
  • 'virtualless' — the file exists (owned content or disk) but the program has no virtual for it: its transform failed, or it was never supplied
  • 'missing' — no virtual and no file, as for a mistyped specifier

Without a virtual, a .svelte specifier would otherwise resolve to nothing, or to the svelte package's ambient declare module '*.svelte' once some file in the program imports svelte — so the reading would turn on unrelated files. The re-export arms ask this by path instead.

import type {SvelteFileStatus} from 'svelte-docinfo/typescript-extract-shared.ts';

SveltePropDiagnostic
#

diagnostics.ts view source

value + type

Svelte prop type resolution failed.

Also emitted once per export let prop of a legacy component whose svelte2tsx output has no recognized props type: those props aren't extracted, and each failure carries its export's line.

file is the original .svelte path, so line/column are present only when the prop's declaration lives in the component's own virtual *and* maps back to the original source — an imported props type or a node svelte2tsx synthesized leaves the position absent rather than publishing a virtual line, the rule remapVirtualDiagnosticPositions applies to extractor diagnostics.

import {SveltePropDiagnostic} from 'svelte-docinfo/diagnostics.ts';

inheritance

extends: SchemaStrictObjectOutput<typeof SveltePropDiagnosticEntries>

members

kind

: "svelte_prop_failed"
#

componentName

: string
#

Name of the component.

propName

: string
#

Name of the prop.

file

: string
#

File path relative to project root (no leading slash, no ./ prefix).

Normalized at every public API boundary — session.setFile/setFiles (ingest-time), session.query (query-time, via analyzeCore), and the one-shot wrappers analyze / analyzeFromFiles. Producers inside the pipeline may write absolute or virtual paths (e.g., Foo.svelte.__svelte2tsx__.ts); normalization rewrites them to project-relative form before they reach consumers.

The exception is discovery — discoverSourceFiles / discoverFromExports return their diagnostics unnormalized, since they run before any session exists. Their file is already project-root-relative, but message can embed an absolute path (an fs error names the file it failed on), so a consumer wiring discovery up itself owns the normalizeDiagnosticPaths call — analyzeFromFiles and the Vite plugin both make it before merging.

The absolute form is the one to write. Normalization deliberately leaves an already-relative path alone (relativizing it would resolve against cwd), so a producer writing a ModuleJson.path — relative to sourceRoot, a different base — passes through untouched and publishes the same file under a second name. Absolute is what the pass can actually correct.

message

: string
#

Human-readable description of the issue.

severity

: "error" | "warning"
#

line

?: number
#

Line number (1-based), absent if location unavailable.

column

?: number
#

Column number (1-based), absent if location unavailable.

SveltePropDiagnosticInput
#

diagnostics.ts view source

The input SveltePropDiagnostic parses, with any field it defaults optional.

import type {SveltePropDiagnosticInput} from 'svelte-docinfo/diagnostics.ts';

inheritance

extends: SchemaStrictObjectInput<typeof SveltePropDiagnosticEntries>

members

kind

: "svelte_prop_failed"
#

componentName

: string
#

Name of the component.

propName

: string
#

Name of the prop.

file

: string
#

File path relative to project root (no leading slash, no ./ prefix).

Normalized at every public API boundary — session.setFile/setFiles (ingest-time), session.query (query-time, via analyzeCore), and the one-shot wrappers analyze / analyzeFromFiles. Producers inside the pipeline may write absolute or virtual paths (e.g., Foo.svelte.__svelte2tsx__.ts); normalization rewrites them to project-relative form before they reach consumers.

The exception is discovery — discoverSourceFiles / discoverFromExports return their diagnostics unnormalized, since they run before any session exists. Their file is already project-root-relative, but message can embed an absolute path (an fs error names the file it failed on), so a consumer wiring discovery up itself owns the normalizeDiagnosticPaths call — analyzeFromFiles and the Vite plugin both make it before merging.

The absolute form is the one to write. Normalization deliberately leaves an already-relative path alone (relativizing it would resolve against cwd), so a producer writing a ModuleJson.path — relative to sourceRoot, a different base — passes through untouched and publishes the same file under a second name. Absolute is what the pass can actually correct.

message

: string
#

Human-readable description of the issue.

severity

: "error" | "warning"
#

line

?: number
#

Line number (1-based), absent if location unavailable.

column

?: number
#

Column number (1-based), absent if location unavailable.

SvelteScriptTag
#

svelte-scripts.ts view source

A located script tag: parsed attributes, content, and where the content starts in the source.

import type {SvelteScriptTag} from 'svelte-docinfo/svelte-scripts.ts';

members

attributes

: Map<string, string | true>
#

Opening-tag attributes; bare attributes (module) map to true.

content

: string
#

start

: number
#

Offset of content within the source, for mapping script positions to original lines.

SvelteTemplateScripts
#

svelte-scripts.ts view source

The part of Svelte's parsed root that findScriptTags reads.

import type {SvelteTemplateScripts} from 'svelte-docinfo/svelte-scripts.ts';

members

instance

?: { start: number; } | null
#

The instance script, at the offset of its opening <.

module

?: { start: number; } | null
#

The module script, at the offset of its opening <.

SvelteVirtualFile
#

svelte.ts view source

Pre-transformed Svelte virtual file data.

Produced by transformSvelteSource and consumed by analyzeSvelteModule to provide checker-backed analysis of Svelte components.

import type {SvelteVirtualFile} from 'svelte-docinfo/svelte.ts';

members

virtualPath

: string
#

Path used for the virtual file in the TypeScript program.

content

: string
#

svelte2tsx transformed TypeScript content.

sourceMap

: TraceMap | null
#

Source map for position mapping back to the original .svelte file.

scriptKind

: ScriptKind
#

Parser treatment for the virtual: ts.ScriptKind.JS for JS-only components (no lang="ts"), so the checker reads their JSDoc types — the parse tolerates the TS-only statements svelte2tsx emits (a grammar diagnostic, never surfaced) — else ts.ScriptKind.TS. The single encoding of the script language: ComponentDeclarationJson.lang is derived from it at output.

scriptTags

?: readonly SvelteScriptTag[]
#

The component's script tags as located in the original source: the top-level <script> tags, in source order (findScriptTags). transformSvelteSource locates them once, and analyzeSvelteModule reads the instance and module scripts from here on every analysis.

Optional so a virtual built by hand needs none: analyzeSvelteModule then locates them in the source it's given.

The component's styling API as analyzeComponentCss reads it from the original source, read once at transform like scriptTags, plus the problem analyzeSvelteModule reports when the style wasn't read.

Optional so a virtual built by hand needs none: analyzeSvelteModule then reads it from the source it's given.

synthesizeSnippetTypeSignature
#

svelte.ts view source

synthesizeSnippetTypeSignature(parameters: ParameterJsonInput[]): string

Synthesize a Snippet<[...]> type string from structured parameters.

Used for kind: 'snippet' declarations where the raw svelte2tsx type is implementation noise. Renders the normalized form — an optional parameter as b?: number, matching the structured parameter fields rather than the checker's widened b?: number | undefined, and a rest parameter with its ... marker (Svelte compile-errors rest parameters in {#snippet}, but analysis never runs that check — svelte2tsx passes them through, so the invalid-but-parseable case renders faithfully rather than dropping the marker).

import {synthesizeSnippetTypeSignature} from 'svelte-docinfo/svelte.ts';

ThrowsJson
#

types.ts view source

value + type

also exported from index.ts

One @throws tag: the thrown type, when the tag names one, and its description.

import {ThrowsJson} from 'svelte-docinfo/types.ts';

inheritance

extends: SchemaStrictObjectOutput<typeof ThrowsJsonEntries>

members

description

: string
#

The tag's description; empty for a bare @throws {A}.

type

?: string
#

The thrown type as written: a braced type's text, or an unbraced tag's leading word.

typeInfo

?: TypeJson
#

Structured type; absent when type is the whole story (see TypeJson).

ThrowsJsonInput
#

types.ts view source

The input ThrowsJson parses, with any field it defaults optional.

import type {ThrowsJsonInput} from 'svelte-docinfo/types.ts';

inheritance

extends: SchemaStrictObjectInput<typeof ThrowsJsonEntries>

members

description

: string
#

The tag's description; empty for a bare @throws {A}.

type

?: string
#

The thrown type as written: a braced type's text, or an unbraced tag's leading word.

typeInfo

?: TypeJson
#

Structured type; absent when type is the whole story (see TypeJson).

throwsTypeNodes
#

tsdoc.ts view source

WeakMap<ThrowsJsonInput, TypeNode>

type WeakMap<ThrowsJsonInput, TypeNode>

The type node of each braced @throws {A} entry parseComment produced, keyed by the entry object. Parsing has no checker, so the extractors read the node back to resolve the entry's typeInfo (applyThrowsTypeInfo), and a parsed comment stays plain data.

import {throwsTypeNodes} from 'svelte-docinfo/tsdoc.ts';

toErrorMessage
#

error.ts view source

toErrorMessage(value: unknown, fallback?: string): string

Extract a human-readable message from an unknown thrown value.

import {toErrorMessage} from 'svelte-docinfo/error.ts';

toModuleDocFields
#

tsdoc.ts view source

toModuleDocFields(tsdoc: TsdocParsedComment | undefined): ModuleDocFields

Project a parsed module comment onto its ModuleJson fields: the prose as moduleComment (absent when empty) plus the tags a module can carry. Tags that only describe a declaration (@param, @returns, @throws, @mutates, @default, @nodocs, @cssprop) are dropped; the analyzers warn misplaced_tag for each.

import {toModuleDocFields} from 'svelte-docinfo/tsdoc.ts';

parameters

tsdoc

: TsdocParsedComment | undefined
#

the module comment as parseModuleComment returns it

toPosixPath
#

paths.ts view source

toPosixPath(p: string): string

Normalize a path to POSIX form (forward slashes).

Replaces every backslash with a forward slash. Idempotent: forward-slash input returns unchanged. Empty string returns empty string.

import {toPosixPath} from 'svelte-docinfo/paths.ts';

examples

toPosixPath('C:\\proj\\src\\lib\\foo.ts') // => 'C:/proj/src/lib/foo.ts' toPosixPath('/home/user/proj/foo.ts') // => '/home/user/proj/foo.ts' (unchanged) toPosixPath('') // => ''

TransformFailedDiagnostic
#

diagnostics.ts view source

value + type

svelte2tsx transform threw for a .svelte file.

Unrecoverable at ingest — the file's owned-entry stays in the session (virtual: undefined, unfilteredDeps: [], transformFailed: true) so query() can synthesize a placeholder ModuleJson (partial: true, empty declarations). The originating error message lives in message; this diagnostic is the authoritative cause-of-failure signal.

import {TransformFailedDiagnostic} from 'svelte-docinfo/diagnostics.ts';

inheritance

extends: SchemaStrictObjectOutput<typeof TransformFailedDiagnosticEntries>

members

kind

: "transform_failed"
#

file

: string
#

File path relative to project root (no leading slash, no ./ prefix).

Normalized at every public API boundary — session.setFile/setFiles (ingest-time), session.query (query-time, via analyzeCore), and the one-shot wrappers analyze / analyzeFromFiles. Producers inside the pipeline may write absolute or virtual paths (e.g., Foo.svelte.__svelte2tsx__.ts); normalization rewrites them to project-relative form before they reach consumers.

The exception is discovery — discoverSourceFiles / discoverFromExports return their diagnostics unnormalized, since they run before any session exists. Their file is already project-root-relative, but message can embed an absolute path (an fs error names the file it failed on), so a consumer wiring discovery up itself owns the normalizeDiagnosticPaths call — analyzeFromFiles and the Vite plugin both make it before merging.

The absolute form is the one to write. Normalization deliberately leaves an already-relative path alone (relativizing it would resolve against cwd), so a producer writing a ModuleJson.path — relative to sourceRoot, a different base — passes through untouched and publishes the same file under a second name. Absolute is what the pass can actually correct.

message

: string
#

Human-readable description of the issue.

severity

: "error" | "warning"
#

line

?: number
#

Line number (1-based), absent if location unavailable.

column

?: number
#

Column number (1-based), absent if location unavailable.

TransformFailedDiagnosticInput
#

diagnostics.ts view source

The input TransformFailedDiagnostic parses, with any field it defaults optional.

import type {TransformFailedDiagnosticInput} from 'svelte-docinfo/diagnostics.ts';

inheritance

extends: SchemaStrictObjectInput<typeof TransformFailedDiagnosticEntries>

members

kind

: "transform_failed"
#

file

: string
#

File path relative to project root (no leading slash, no ./ prefix).

Normalized at every public API boundary — session.setFile/setFiles (ingest-time), session.query (query-time, via analyzeCore), and the one-shot wrappers analyze / analyzeFromFiles. Producers inside the pipeline may write absolute or virtual paths (e.g., Foo.svelte.__svelte2tsx__.ts); normalization rewrites them to project-relative form before they reach consumers.

The exception is discovery — discoverSourceFiles / discoverFromExports return their diagnostics unnormalized, since they run before any session exists. Their file is already project-root-relative, but message can embed an absolute path (an fs error names the file it failed on), so a consumer wiring discovery up itself owns the normalizeDiagnosticPaths call — analyzeFromFiles and the Vite plugin both make it before merging.

The absolute form is the one to write. Normalization deliberately leaves an already-relative path alone (relativizing it would resolve against cwd), so a producer writing a ModuleJson.path — relative to sourceRoot, a different base — passes through untouched and publishes the same file under a second name. Absolute is what the pass can actually correct.

message

: string
#

Human-readable description of the issue.

severity

: "error" | "warning"
#

line

?: number
#

Line number (1-based), absent if location unavailable.

column

?: number
#

Column number (1-based), absent if location unavailable.

TransformResult
#

svelte.ts view source

Result of transformSvelteSource — a virtual file (when transform succeeded) plus any ingest-time diagnostics produced during the transform.

virtual is undefined when svelte2tsx threw; in that case diagnostics contains a transform_failed entry. When the transform succeeded but source map construction failed, virtual is populated and diagnostics contains a source_map_failed entry. The session's owned-entry stores both — the virtual (or transformFailed: true flag) and the ingest diagnostics.

import type {TransformResult} from 'svelte-docinfo/svelte.ts';

members

virtual

: SvelteVirtualFile | undefined
#

diagnostics

: Diagnostic[]
#

transformSvelteSource
#

svelte.ts view source

transformSvelteSource(sourceFile: SourceFileInfo): TransformResult

Pre-transform a Svelte source file via svelte2tsx.

Produces a SvelteVirtualFile containing the transformed TypeScript content and source map. The virtual file can be included in a TypeScript program (via createAnalysisProgram({ virtualFiles }), or the language service's setFile in sessions) so that the checker can resolve imported types, <script module> exports, and re-exports.

Errors at ingest are returned via diagnostics rather than thrown:

  • svelte2tsx throws → transform_failed, virtual: undefined
  • source map construction fails → source_map_failed, virtual populated

Diagnostic file paths are the original .svelte source ID; downstream normalization rewrites them to project-root-relative form.

import {transformSvelteSource} from 'svelte-docinfo/svelte.ts';

parameters

sourceFile

: SourceFileInfo
#

the Svelte source file with content loaded

returns

virtual file data (or undefined on transform failure) plus ingest diagnostics

throws

  • Error - if Svelte version is below 5 (checked once on first call)

TsdocCssProperty
#

tsdoc.ts view source

A CSS custom property documented by a @cssprop tag (@cssprop {<color>} [--a=red] - Description 1).

import type {TsdocCssProperty} from 'svelte-docinfo/tsdoc.ts';

members

name

: string
#

The property's name as written, -- included.

description

?: string
#

The tag's description, without its leading - separator.

syntax

?: string
#

The braced syntax before the name (<color>), verbatim without the braces.

default

?: string
#

The bracketed default after the name ([--a=red] → red), verbatim and trimmed.

TsdocCssPropertyProblem
#

tsdoc.ts view source

A @cssprop tag that documents nothing, for the analyzers to warn about.

import type {TsdocCssPropertyProblem} from 'svelte-docinfo/tsdoc.ts';

members

kind

: "malformed" | "duplicate"
#

malformed when the text names no custom property, duplicate when it repeats a name.

text

: string
#

The tag's text after the tag name, trimmed.

name

?: string
#

The repeated name, on a duplicate.

TsdocParsedComment
#

tsdoc.ts view source

Parsed JSDoc/TSDoc comment with structured metadata.

Returned by parseComment — consumers typically pass this to applyToDeclaration to populate DeclarationJsonBuild fields.

import type {TsdocParsedComment} from 'svelte-docinfo/tsdoc.ts';

members

text

: string
#

Comment text (excluding comment markers).

params

: Record<string, string>
#

Parameter descriptions mapped by parameter name.

returns

?: string
#

Return value description from @returns (or its JSDoc @return synonym).

throws

?: ThrowsJsonInput[]
#

Thrown errors from @throws. A braced tag's type node is kept beside its entry in throwsTypeNodes, for the checker to read.

examples

?: string[]
#

Code examples from @example.

deprecatedMessage

?: string
#

Deprecation message from @deprecated.

internalMessage

?: string
#

Internal-API marker from @internal. Presence means the tag was written; an empty string is a bare tag with no trailing prose. Means "not stable public API" — the declaration is still documented (use @nodocs to exclude from output).

seeAlso

?: string[]
#

Related references from @see.

since

?: string
#

Version information from @since.

defaultValue

?: string
#

Default value from @default (or its @defaultValue/@defaultvalue spellings).

mutates

?: Record<string, string>
#

Mutation documentation from @mutates (non-standard), mapped by target — typically a parameter name, possibly a compound path (this.foo) or a multi-word external reference. Empty string for a bare tag with no description.

nodocs

?: boolean
#

Whether to exclude from documentation. From @nodocs tag.

cssProperties

?: TsdocCssProperty[]
#

CSS custom properties from @cssprop (or its @cssproperty synonym), in tag order, one per name: a later tag naming the same property is ignored (cssPropertyProblems records it).

cssPropertyProblems

?: TsdocCssPropertyProblem[]
#

The @cssprop tags that document nothing, in tag order: one whose text names no custom property (malformed), and one naming a property an earlier tag already documents (duplicate). They count as doc content (hasDocContent), so a comment of broken tags alone still reaches the analyzer that warns about them.

TupleElementJson
#

types.ts view source

value + type

also exported from index.ts

One element of a {kind: 'tuple'} node.

optional and rest are emitted only when true, matching the tree's meaningful-absence optionality (unlike ParameterJson's defaulted booleans, so the recursive schema keeps input = output).

import {TupleElementJson} from 'svelte-docinfo/types.ts';

members

name

?: string
#

The written label of a named tuple member ([a: string]).

type

: TypeJson
#

The element's type. An optional element's type has the widening undefined stripped so optional carries it alone (the enclosing flat string keeps it — see the normalization policy); a rest element's is the array it collects (...rest: boolean[] carries an array node over boolean, matching the written form), while a variadic spread of an unresolved type (...T) carries the spread type itself.

optional

?: boolean
#

The element's ? marker; emitted only when true.

rest

?: boolean
#

The element's ... marker; emitted only when true.

tupleElementName
#

typescript-extract-type-json.ts view source

tupleElementName(el: TupleTypeElement): string | undefined

The written element label as an output name: a NamedTupleMember's identifier, or a parameter-derived label's (Parameters<F> tuples) — the identifier guard is defensive, since binding-pattern parameters produce no label declaration at all. The one naming rule for both tupleElements consumers, so parameters and the typeInfo tree can't disagree on names.

import {tupleElementName} from 'svelte-docinfo/typescript-extract-type-json.ts';

tupleElements
#

TupleTypeElement
#

typescript-extract-type-json.ts view source

Per-element checker metadata from tupleElements — one walk, projected per consumer.

import type {TupleTypeElement} from 'svelte-docinfo/typescript-extract-type-json.ts';

members

type

: Type
#

The element's type argument; widened with undefined when optional.

label

: NamedTupleMember | ParameterDeclaration | undefined
#

The written label declaration, when the tuple has one for this slot.

optional

: boolean
#

Whether the element carries a ? marker.

rest

: boolean
#

Whether the element is a rest element (...boolean[]; type is the array *element* type).

variadic

: boolean
#

Whether the element is an unresolved variadic spread (...T; type is the spread type).

TypeAliasLike
#

typescript-extract-type-json.ts view source

type TypeAliasDeclaration | JSDocTypedefTag | JSDocCallbackTag

A type-alias declaration in either language: TypeScript's type A = …, or a JSDoc @typedef / @callback tag, which declares the same alias symbol (ts.SymbolFlags.TypeAlias) in a JS file. Every alias path tests isTypeAliasLike and reads the parts through typeAliasTypeNode and typeAliasTypeParameters, so a typedef documents like its TypeScript twin. A JSDoc @enum tag declares an alias too, but documents as kind: 'enum' over its value, so it isn't alias-like here. TypeScript binds these tags in JS files only: a @typedef in a .ts file declares nothing, so it never reaches an alias path.

import type {TypeAliasLike} from 'svelte-docinfo/typescript-extract-type-json.ts';

typeAliasTypeNode
#

typescript-extract-type-json.ts view source

typeAliasTypeNode(node: TypeAliasLike): TypeNode | undefined

The written right-hand side of a type alias: type A = <this>, a typedef's braced type (@typedef {<this>} A), the JSDocTypeLiteral a @typedef {object} A (or an untyped @typedef A) builds from its @property tags, or a @callback's JSDocSignature. undefined for a bare @typedef A that writes neither a type nor properties.

import {typeAliasTypeNode} from 'svelte-docinfo/typescript-extract-type-json.ts';

typeAliasTypeParameters
#

typescript-extract-type-json.ts view source

typeAliasTypeParameters(node: TypeAliasLike): readonly TypeParameterDeclaration[]

A type alias's type parameters: a TypeScript alias's own, or the @template tags in a typedef's JSDoc block (@template T beside @typedef {{a: T}} A), the checker's reading (ts.getEffectiveTypeParameterDeclarations).

import {typeAliasTypeParameters} from 'svelte-docinfo/typescript-extract-type-json.ts';

TypeDeclarationJson
#

types.ts view source

value + type

also exported from index.ts

A type alias declaration. Has members, externalTypes.

import {TypeDeclarationJson} from 'svelte-docinfo/types.ts';

inheritance

extends: SchemaStrictObjectOutput<typeof TypeDeclarationJsonEntries>

members

kind

: "type"
#

externalTypes

: string[]
#

External types whose contributions are filtered out of members.

Filtering is by declaration origin at every granularity — named properties, index signatures, call/construct signatures — so a purely structural external branch (an index-signature-only or callable-only interface) is recorded here exactly like a named-property bag. A declaration-less contribution (the index signature the checker synthesizes for a mapped-type instantiation like Record<string, X> or Partial<Indexed>) is kept in members and records nothing here.

Covers every composition the written type reaches: an intersection or union branch, a bare or indexed-access reference, and a type composed behind a project-local name (type Base = Bag & {…}, a local interface's extends, a local container's accessed property LocalMap['a']). Entries carry the written form with two normalizations: an identifier bound by an import rename at the definition site (import type {Bag as B}) resolves back to the name its module exports, and a type parameter bound inside the descent substitutes its written argument (interface A<T> extends ExtG<T> reached via extends A<string> records ExtG<string>). Each distinct contributor appears once, in source order; a generic reference keeps its arguments. A local name is used only when it hides a definition the walk cannot traverse — a mapped or conditional type.

Names carry no module, so the dedupe is by name alone: two *distinct* external types sharing an exported name (one from each of two packages) collapse to a single entry.

see also

Type members: properties (property and method signatures) first, then index signatures (string, number), then call and construct signatures.

mergedValue

: boolean
#

The exported name also carries a value meaning — a merged value+type symbol (const Foo = z.strictObject({...}) + `type Foo = z.infer<typeof Foo>`, the schema/type pattern), where the type alias wins the declaration slot and the value's own type goes undocumented. Tells consumers the name is importable as a runtime value: import {Foo}, never import type {Foo} (see generateImport).

see also

alsoExportedFrom

: string[]
#

Module paths (relative to sourceRoot) that re-export this declaration under the same name. The canonical declaration lives in this module's declarations array; these paths are additional import locations for the same thing.

The same edges appear from the re-exporting side as ModuleJson.reExports — use that when asking "what does this module re-export" instead of inverting these arrays. The two can disagree at the margins: a reExports entry whose canonical declaration is @nodocs (or whose module isn't in the analyzed set) has no back-link here.

Consumer note: To build a complete re-export map, scan two fields:

  1. alsoExportedFrom on each declaration — same-name re-exports
  2. aliasOf on declarations — renamed re-exports (separate declarations)

partial

: boolean
#

Whether extraction failed partway through, leaving some fields missing (e.g., typeSignature, parameters).

examples

: string[]
#

Code examples from @example tags.

seeAlso

: string[]
#

Related items from @see tags, in raw TSDoc format.

throws

: ThrowsJson[]
#

Exceptions from @throws tags. type is the tag's written type, and typeInfo its structured form, present for a braced type (@throws {A<B>}) that isn't the whole story as text (see TypeJson); an unbraced tag's leading word never has one, nor does a tag in a component's HTML @component comment, which is read as text.

name

: string
#

The exported name. Always populated. The default-export slot is named 'default', except a Svelte component, which takes its filename-derived name ('X' for X.svelte) — 'default' is the symbol's actual name in JS (import {default as X} and ns.default both expose it directly), and import X from 'mod' is sugar for import {default as X}. Consumers branch on name === 'default' to render the sugar form when desired.

modifiers

: ("public" | "protected" | "readonly" | "static" | "abstract" | "getter" | "setter")[]
#

TypeScript modifiers like readonly, static, or protected.

genericParams

: GenericParamJson[]
#

Generic type parameters like <T, U>.

typeInfo

?: TypeJson
#

Structured type; absent when typeSignature is the whole story (see TypeJson). The headline case: a union alias's typeSignature prints as its own name (ColorScheme), and this field carries the enumerable members. Type aliases print as their own name for every non-interned type, so the tree is emitted there whatever its shape — the exception is object and function roots, whose content members already carries.

aliasOf

?: { module: string; name: string; }
#

For renamed re-exports (export {foo as bar}), points to the original declaration. This declaration's name is the alias; aliasOf.name is the original name.

For renames out of the default slot (export {default as bar} from './x' where ./x is export default ...), aliasOf.name is 'default' — the canonical's actual symbol name. Consumers locate the canonical by (aliasOf.module, aliasOf.name).

Svelte component exception: when the source is a .svelte file (e.g., export {default as Foo} from './X.svelte'), the canonical's name is the component name (derived from the filename), so aliasOf.name is the component name ('X'), NOT 'default'. Consumers that branch on aliasOf.name === 'default' to detect default-rename should additionally check whether aliasOf.module ends with .svelte.

Different from alsoExportedFrom: aliases create new API surface names, while alsoExportedFrom tracks additional import paths for the same name.

A type-only rename of a value (export type {someConst as c} from './x') synthesizes a normal alias — declarations carry no type-only marker.

deprecatedMessage

?: string
#

Deprecation message from @deprecated tag.

since

?: string
#

Version introduced, from @since tag.

internalMessage

?: string
#

Internal-API marker from the @internal tag. Presence means the tag was written; an empty string is a bare tag with no trailing prose.

A marker, not an exclusion: @internal means "not stable public API" (TSDoc semantics) while the declaration, member, or prop stays documented — unlike @nodocs, which removes a declaration from output entirely (and is ignored on props and members).

mutates

?: Record<string, string>
#

Mutation documentation from @mutates tags (non-standard), mapping keys to descriptions.

Keys are intentionally unvalidated — typically a parameter name, but authors may also use compound paths (this.foo, obj.field) or multi-word external state references. Backticks are stripped from keys so `` a `` and a normalize to one key; an empty-string value is a bare tag with no description. The schema accepts any string key so consumers can render whatever the author wrote.

On a component prop it declares the component's mutation contract for the value it's handed: the component writes into the prop's object or array in place (@mutates items - appends the selected entry, @mutates options.cache - fills on first render). Reassigning a prop is not a mutation in this sense (bindable covers it), though a $bindable prop can carry both.

docComment

?: string
#

JSDoc/TSDoc comment.

typeSignature

?: string
#

Full TypeScript type signature.

sourceLine

?: number
#

1-based line in the source file, a positive integer. Synthesized aliases (see aliasOf) carry the local export specifier's line, not the canonical's.

TypeDeclarationJsonInput
#

types.ts view source

The input TypeDeclarationJson parses, with any field it defaults optional.

import type {TypeDeclarationJsonInput} from 'svelte-docinfo/types.ts';

inheritance

extends: SchemaStrictObjectInput<typeof TypeDeclarationJsonEntries>

members

kind

: "type"
#

name

: string
#

The exported name. Always populated. The default-export slot is named 'default', except a Svelte component, which takes its filename-derived name ('X' for X.svelte) — 'default' is the symbol's actual name in JS (import {default as X} and ns.default both expose it directly), and import X from 'mod' is sugar for import {default as X}. Consumers branch on name === 'default' to render the sugar form when desired.

externalTypes

?: string[]
#

External types whose contributions are filtered out of members.

Filtering is by declaration origin at every granularity — named properties, index signatures, call/construct signatures — so a purely structural external branch (an index-signature-only or callable-only interface) is recorded here exactly like a named-property bag. A declaration-less contribution (the index signature the checker synthesizes for a mapped-type instantiation like Record<string, X> or Partial<Indexed>) is kept in members and records nothing here.

Covers every composition the written type reaches: an intersection or union branch, a bare or indexed-access reference, and a type composed behind a project-local name (type Base = Bag & {…}, a local interface's extends, a local container's accessed property LocalMap['a']). Entries carry the written form with two normalizations: an identifier bound by an import rename at the definition site (import type {Bag as B}) resolves back to the name its module exports, and a type parameter bound inside the descent substitutes its written argument (interface A<T> extends ExtG<T> reached via extends A<string> records ExtG<string>). Each distinct contributor appears once, in source order; a generic reference keeps its arguments. A local name is used only when it hides a definition the walk cannot traverse — a mapped or conditional type.

Names carry no module, so the dedupe is by name alone: two *distinct* external types sharing an exported name (one from each of two packages) collapse to a single entry.

see also

typeInfo

?: TypeJson
#

Structured type; absent when typeSignature is the whole story (see TypeJson). The headline case: a union alias's typeSignature prints as its own name (ColorScheme), and this field carries the enumerable members. Type aliases print as their own name for every non-interned type, so the tree is emitted there whatever its shape — the exception is object and function roots, whose content members already carries.

Type members: properties (property and method signatures) first, then index signatures (string, number), then call and construct signatures.

mergedValue

?: boolean
#

The exported name also carries a value meaning — a merged value+type symbol (const Foo = z.strictObject({...}) + `type Foo = z.infer<typeof Foo>`, the schema/type pattern), where the type alias wins the declaration slot and the value's own type goes undocumented. Tells consumers the name is importable as a runtime value: import {Foo}, never import type {Foo} (see generateImport).

see also

alsoExportedFrom

?: string[]
#

Module paths (relative to sourceRoot) that re-export this declaration under the same name. The canonical declaration lives in this module's declarations array; these paths are additional import locations for the same thing.

The same edges appear from the re-exporting side as ModuleJson.reExports — use that when asking "what does this module re-export" instead of inverting these arrays. The two can disagree at the margins: a reExports entry whose canonical declaration is @nodocs (or whose module isn't in the analyzed set) has no back-link here.

Consumer note: To build a complete re-export map, scan two fields:

  1. alsoExportedFrom on each declaration — same-name re-exports
  2. aliasOf on declarations — renamed re-exports (separate declarations)

aliasOf

?: { module: string; name: string; }
#

For renamed re-exports (export {foo as bar}), points to the original declaration. This declaration's name is the alias; aliasOf.name is the original name.

For renames out of the default slot (export {default as bar} from './x' where ./x is export default ...), aliasOf.name is 'default' — the canonical's actual symbol name. Consumers locate the canonical by (aliasOf.module, aliasOf.name).

Svelte component exception: when the source is a .svelte file (e.g., export {default as Foo} from './X.svelte'), the canonical's name is the component name (derived from the filename), so aliasOf.name is the component name ('X'), NOT 'default'. Consumers that branch on aliasOf.name === 'default' to detect default-rename should additionally check whether aliasOf.module ends with .svelte.

Different from alsoExportedFrom: aliases create new API surface names, while alsoExportedFrom tracks additional import paths for the same name.

A type-only rename of a value (export type {someConst as c} from './x') synthesizes a normal alias — declarations carry no type-only marker.

partial

?: boolean
#

Whether extraction failed partway through, leaving some fields missing (e.g., typeSignature, parameters).

examples

?: string[]
#

Code examples from @example tags.

deprecatedMessage

?: string
#

Deprecation message from @deprecated tag.

seeAlso

?: string[]
#

Related items from @see tags, in raw TSDoc format.

throws

?: ThrowsJsonInput[]
#

Exceptions from @throws tags. type is the tag's written type, and typeInfo its structured form, present for a braced type (@throws {A<B>}) that isn't the whole story as text (see TypeJson); an unbraced tag's leading word never has one, nor does a tag in a component's HTML @component comment, which is read as text.

since

?: string
#

Version introduced, from @since tag.

internalMessage

?: string
#

Internal-API marker from the @internal tag. Presence means the tag was written; an empty string is a bare tag with no trailing prose.

A marker, not an exclusion: @internal means "not stable public API" (TSDoc semantics) while the declaration, member, or prop stays documented — unlike @nodocs, which removes a declaration from output entirely (and is ignored on props and members).

mutates

?: Record<string, string>
#

Mutation documentation from @mutates tags (non-standard), mapping keys to descriptions.

Keys are intentionally unvalidated — typically a parameter name, but authors may also use compound paths (this.foo, obj.field) or multi-word external state references. Backticks are stripped from keys so `` a `` and a normalize to one key; an empty-string value is a bare tag with no description. The schema accepts any string key so consumers can render whatever the author wrote.

On a component prop it declares the component's mutation contract for the value it's handed: the component writes into the prop's object or array in place (@mutates items - appends the selected entry, @mutates options.cache - fills on first render). Reassigning a prop is not a mutation in this sense (bindable covers it), though a $bindable prop can carry both.

docComment

?: string
#

JSDoc/TSDoc comment.

typeSignature

?: string
#

Full TypeScript type signature.

modifiers

?: ("public" | "protected" | "readonly" | "static" | "abstract" | "getter" | "setter")[]
#

TypeScript modifiers like readonly, static, or protected.

sourceLine

?: number
#

1-based line in the source file, a positive integer. Synthesized aliases (see aliasOf) carry the local export specifier's line, not the canonical's.

genericParams

?: GenericParamJsonInput[]
#

Generic type parameters like <T, U>.

TypeExtractionDiagnostic
#

diagnostics.ts view source

value + type

Type extraction failed (e.g., complex or recursive types).

import {TypeExtractionDiagnostic} from 'svelte-docinfo/diagnostics.ts';

inheritance

extends: SchemaStrictObjectOutput<typeof TypeExtractionDiagnosticEntries>

members

kind

: "type_extraction_failed"
#

symbolName

: string
#

Name of the symbol whose type couldn't be extracted.

file

: string
#

File path relative to project root (no leading slash, no ./ prefix).

Normalized at every public API boundary — session.setFile/setFiles (ingest-time), session.query (query-time, via analyzeCore), and the one-shot wrappers analyze / analyzeFromFiles. Producers inside the pipeline may write absolute or virtual paths (e.g., Foo.svelte.__svelte2tsx__.ts); normalization rewrites them to project-relative form before they reach consumers.

The exception is discovery — discoverSourceFiles / discoverFromExports return their diagnostics unnormalized, since they run before any session exists. Their file is already project-root-relative, but message can embed an absolute path (an fs error names the file it failed on), so a consumer wiring discovery up itself owns the normalizeDiagnosticPaths call — analyzeFromFiles and the Vite plugin both make it before merging.

The absolute form is the one to write. Normalization deliberately leaves an already-relative path alone (relativizing it would resolve against cwd), so a producer writing a ModuleJson.path — relative to sourceRoot, a different base — passes through untouched and publishes the same file under a second name. Absolute is what the pass can actually correct.

message

: string
#

Human-readable description of the issue.

severity

: "error" | "warning"
#

line

?: number
#

Line number (1-based), absent if location unavailable.

column

?: number
#

Column number (1-based), absent if location unavailable.

TypeExtractionDiagnosticInput
#

diagnostics.ts view source

The input TypeExtractionDiagnostic parses, with any field it defaults optional.

import type {TypeExtractionDiagnosticInput} from 'svelte-docinfo/diagnostics.ts';

inheritance

extends: SchemaStrictObjectInput<typeof TypeExtractionDiagnosticEntries>

members

kind

: "type_extraction_failed"
#

symbolName

: string
#

Name of the symbol whose type couldn't be extracted.

file

: string
#

File path relative to project root (no leading slash, no ./ prefix).

Normalized at every public API boundary — session.setFile/setFiles (ingest-time), session.query (query-time, via analyzeCore), and the one-shot wrappers analyze / analyzeFromFiles. Producers inside the pipeline may write absolute or virtual paths (e.g., Foo.svelte.__svelte2tsx__.ts); normalization rewrites them to project-relative form before they reach consumers.

The exception is discovery — discoverSourceFiles / discoverFromExports return their diagnostics unnormalized, since they run before any session exists. Their file is already project-root-relative, but message can embed an absolute path (an fs error names the file it failed on), so a consumer wiring discovery up itself owns the normalizeDiagnosticPaths call — analyzeFromFiles and the Vite plugin both make it before merging.

The absolute form is the one to write. Normalization deliberately leaves an already-relative path alone (relativizing it would resolve against cwd), so a producer writing a ModuleJson.path — relative to sourceRoot, a different base — passes through untouched and publishes the same file under a second name. Absolute is what the pass can actually correct.

message

: string
#

Human-readable description of the issue.

severity

: "error" | "warning"
#

line

?: number
#

Line number (1-based), absent if location unavailable.

column

?: number
#

Column number (1-based), absent if location unavailable.

TypeJson
#

types.ts view source

value + type

also exported from index.ts

type { kind: "intrinsic"; text: string; } | { kind: "literal"; value: string | number | boolean; text: string; } | { kind: "reference"; name: string; module?: string; typeArgs?: TypeJson[]; } | { kind: "array"; element: TypeJson; readonly?: boolean; } | { kind: "tuple"; elements?: TupleElementJson[]; readonly?: boolean; } | { kind: "union"; alias?: string; members: TypeJson[]; } | { kind: "intersection"; alias?: string; members: TypeJson[]; } | { kind: "function"; text: string; } | { kind: "object"; text: string; } | { kind: "other"; text: string; }

Structured type information — the machine-readable counterpart to the flat type strings (ParameterJson.type, ComponentPropJson.type, the typeSignature fields that carry a typeInfo sibling, and returnType beside returnTypeInfo).

Absence contract: the field holding a TypeJson is absent when the flat string is the whole story — the type is terminal at the root (an intrinsic, a plain object literal, a function type, a bare named reference). Present only when the node carries structure the string can't: union/intersection members, reference type arguments, enumerable literals; an array or tuple qualifies when an element does (readonly alone doesn't — the flat string carries it, except at alias roots where the relaxation emits the tree regardless). A reference over the *empty* tuple is the one instantiation that doesn't qualify: Snippet<[]> prints itself in full, so the tree would wrap nothing (Snippet<[a: string]> still qualifies — its tuple has elements). Nested nodes inside a present tree are always populated (they have no flat-string sibling).

One exception, on TypeDeclarationJson for type aliases: the checker prints an aliased type as its bare alias name, so type StrArr = string[] has typeSignature: "StrArr" — no flat sibling to defer to. There the tree is emitted whatever its shape, except for object and function roots, whose content the declaration's own members already carries. Interned types (intrinsics, literals) don't carry an alias symbol and print structurally, so type Str = string is still absent.

Expansion policy: unions and intersections recurse into members; named references keep name plus recursive typeArgs; arrays carry their element; tuples carry elements (label, ?/... markers, recursive type); both mark readonly when written so (readonly Tome[], ReadonlyArray<Tome>, readonly [a, b]). Everything else is terminal: object literals, function types, and unclassified types (type parameters, conditional types, module objects) carry only text. Object property maps are deliberately not expanded. Recursion is depth-capped; nodes past the cap degrade to {kind: 'other', text}.

Written annotations: where a site has a written annotation the tree follows what was written, not what the checker computes it to. A reference keeps its written name and type arguments (x: Uuid is {kind: 'reference', name: 'Uuid'} though the flat string prints its branded expansion), a computed type (keyof A, typeof a, A['b'], a conditional, mapped, or template literal type) is {kind: 'other', text} over its source text, root included, unless the flat string already prints it so, and a written intersection the checker distributed over a union is an intersection of the written members. A written union's members and a written tuple's elements follow their own written nodes the same way (keyof A | null keeps keyof A). An object or function type literal whose checker printing loses a name the source wrote (a lost alias expanded) is terminal text printed from the written literal, root included ({ theme: Theme; }), one line with comments dropped. Type-alias declaration roots, annotations over another type than the site's, typeof over a value from a package, and module-private alias names keep the checker's reading. Any reference drops trailing type arguments identical to their parameter's default (x: A is never A<Default>), and a bare one whose flat string prints them keeps its node.

Alias policy: alias is emitted whenever the checker reports an alias symbol, root or nested — for a root node it may duplicate the flat string (type: "ColorScheme" beside alias: "ColorScheme"), which is accepted for uniformity: nested nodes have no flat sibling, and consumers get one lookup key (alias on composites, name on references) at any depth. This covers the composite kinds only. An aliased object type becomes a reference under its alias name.

svelte2tsx-generated aliases don't count. A component whose props have no name of their own (an inline $props() annotation, a JS component's JSDoc) types them through svelte2tsx's $$ComponentProps, which nothing exports; a legacy component with slots, through the shims' __sveltets_2_PropsWithChildren. The tree treats those aliases as absent: they're never a name or alias, a project alias over one (type P = ComponentProps<typeof Button>) recovers like any alias-lost type (below), and where nothing recovers the structure is expanded. A root whose flat string is the generated name, bare or as an array or tuple element ($$ComponentProps[]), keeps its tree, except object and function roots of a type alias, whose members carry them. The flat strings still print $$ComponentProps. Generated names inside a terminal node's text ({ a: $$ComponentProps; }, or an other node past the depth cap) are printed as the checker prints them.

Callable classification: callability is the load-bearing renderer signal, so anything with a call signature is a function node — with one narrow exception: a *named generic instantiation* (checker Reference-flagged, symbol-named, carrying type arguments) classifies as a reference even when callable, so Snippet<[a: string]> is a reference whose tuple typeArg carries real elements, and an alias over one, nested, references by the alias name (type MySnippet = Snippet<[string]> in a union is {kind: 'reference', name: 'MySnippet'}; at its own declaration root the self-alias skip applies and the Snippet reference shows through). Bare signatures (() => void), aliased function types, and anonymous or hybrid callables — non-generic callable interfaces included — stay function, so their name survives only inside text (type Handler = (e: Event) => void nested in a union is {kind: 'function', text: 'Handler'}, which a whole-string type-link lookup still resolves, but a structural walk can't distinguish from a printed signature). The trees beside source-text types (constraintInfo, extendsInfo, …) follow the written name instead: there a written callable alias or interface is a reference.

Normalization: the optional-widening undefined member is dropped from a root union like the flat string drops it (optional: true carries it) — but the flat string strips at the top level only, while the tree strips at every optional-flagged position it expands, so Snippet<[a: string, b?: number]> prints b?: number | undefined while the tuple element reports number with optional: true. Treat typeSignature as the checker's canonical rendering and the structured fields as normalized. At property sites the strip applies only when the checker widened: under exactOptionalPropertyTypes an author-written undefined on an optional property is kept (parameters and tuple elements always strip). Separately, a true | false literal pair collapses to the boolean intrinsic (the checker expands boolean inside unions). A union reduced to one member by either rule becomes that member directly, never a 1-member union.

Terminal text fields are printed with NoTruncation up to a 1000-char budget, past which the checker's own elided rendering is used — so text is always a well-formed type string, and one node can't grow without bound the way the depth cap prevents for the tree. The flat strings keep the checker's default ~160-char truncation throughout (they are the checker's canonical rendering; see getTypeSignature). The budget bites only on types whose alias TypeScript dropped — an alias over an indexed access or conditional (z.infer<typeof S>, valibot's InferOutput) carries no alias symbol, so the checker expands its whole structure at every use. Terminal text is the checker's otherwise, with the optional widening stripped inside it as the tree strips it (an optional property's, parameter's, or tuple element's | undefined; properties not under exactOptionalPropertyTypes), so { a?: string; } where the flat string prints { a?: string | undefined; }.

Written-name recovery: at each annotated position, each bare type reference is resolved by checker type identity, and a type the checker has no name for — the alias-dropped shapes above — emits {kind: 'reference', name} instead of expanding, alias-lost unions and intersections included. The annotated positions: return types (per overload too), parameters, variables, type-alias declarations, properties of type aliases, interfaces, and classes, index signatures, accessors (the getter's return, else a setter-only accessor's parameter), component props, and snippet parameters. The name resolves through import aliases to the importable one (import {Original as Renamed} recovers Original); a name the checker has is never overridden; typeof queries, import types, inline type literals, and argument-carrying references (z.infer<typeof S> itself, Extract<D, {kind: K}> — whose bare symbol name would misrepresent the instantiation) never recover. A recovered bare reference is emitted even at the root, relaxing the absence contract the way alias roots do: a checker-named bare reference defers to a flat sibling printing the same name, while a recovered one stands against the anonymous expansion, so the name exists only in the tree. Both recovery channels still fire at the depth cap, so a capped alias-lost type emits its reference instead of elided text. A lost union written as one member of a larger union (LostUnion | null, 'z' | LostUnion) recovers as one reference member at its written position, though the checker flattens its members into the outer union: the written reference is the only trace left, so this needs a written union (at the site, or an alias right-hand side like type Opt = LostUnion | null, which then recovers at every use). It falls back to the expanded members when they don't all survive as distinct members — string absorbing a literal member (LostUnion | string), or a member written earlier overlapping one ('a' | LostUnion) — and for a lost union that includes undefined at an optional position, whose undefined the widening strip removed, since the member-set match can't tell that strip from a type operator removing undefined (Exclude<LostUnion, undefined>).

Registry recovery: behind the written channel, unannotated positions recover through the analyzed set's alias registry — any exported, non-@nodocs, non-generic lost alias of an emitted module, matched by checker type identity. A brand whose type the checker names by a generic's instantiation (Branded<string, "Uuid"> for `type Uuid = Infer<typeof Uuid>`) recovers the same way, and through the written channel too, though the type has an alias; the registry takes only the alias named by the brand's own literal (Uuid), never another alias of the same type. A registry-recovered reference additionally carries module, the declaring module's ModuleJson.path — provenance for collision-exact linking, and always an emitted module (gated modules never register), so a consumer lookup by (module, name) can't dangle. module appears only on registry-recovered references: written-channel recoveries name whatever the author wrote (which may not be the registry's winner), and checker-named references and alias-carrying union/intersection nodes carry no provenance. Consumers must handle absence.

Member order and nested aliases: union members follow the written order wherever a written union node is recoverable: the alias declaration's right-hand side for a non-generic aliased union (covering every use, inferred ones included), else the annotation at the site. null/undefined still sink last, and a member written as a named sub-union survives as its own alias-carrying union node (ColorScheme stays nested, not flattened literals) when the checker kept it grouped, and a written lost union as its recovered reference (see written-name recovery). Elsewhere — inferred unions, keyof, mapped and conditional results, generic alias instantiations — members follow the checker's internal order, which depends on type-creation history and can shift with unrelated edits. Flat strings always print in the checker's order, so tree and flat string can list the same members in different orders (written ColorScheme | number prints number | ColorScheme); the tree is the one to read for author intent, such as control options. One edge: the site lookup matches by member set, so a union takes the order (and lost-union grouping) of the first union written over the same members anywhere in that annotation — two written unions in different orders (['a' | 'b', 'b' | 'a']) both read "a" | "b", and an unwritten one there (Exclude<…>) borrows a written one's order.

import {TypeJson} from 'svelte-docinfo/types.ts';

TypeJsonToken
#

declaration-helpers.ts view source

also exported from index.ts

type { kind: "text"; text: string; } | { kind: "name"; name: string; module?: string; } | { kind: "code"; text: string; }

One rendered piece of a TypeJson tree, produced by typeJsonToTokens: name tokens are candidate references for a renderer to link (or print plainly) — reference names, alias names of alias-carrying unions/intersections — code tokens are terminal type text (intrinsics, literals, anonymous objects/functions, depth-capped nodes) for a renderer to syntax-highlight, and text tokens are structural punctuation (<, | , [], tuple labels). A name token carries module when its reference node does (registry-recovered references — the declaring ModuleJson.path), so a renderer can scope the link; alias-name tokens never carry it.

import type {TypeJsonToken} from 'svelte-docinfo/declaration-helpers.ts';

typeJsonToText
#

declaration-helpers.ts view source

also exported from index.ts

typeJsonToText(node: TypeJson): string

The plain-text printed form of a TypeJson tree — typeJsonToTokens concatenated. For consumers with no linkification or highlighting surface (CLI output, markdown code spans, log lines) and for test assertions. Not a reprint of the flat string: union members keep the tree's order (see typeJsonToTokens).

import {typeJsonToText} from 'svelte-docinfo/declaration-helpers.ts';

examples

typeJsonToText({kind: 'union', members: [ {kind: 'reference', name: 'Tome'}, {kind: 'intrinsic', text: 'null'} ]}) // => 'Tome | null'

typeJsonToTokens
#

declaration-helpers.ts view source

also exported from index.ts

typeJsonToTokens(node: TypeJson): TypeJsonToken[]

Flatten a TypeJson tree into a render-ready token list.

The semantic linearization for renderers: spacing, separators, parenthesization (((x) => void) | null, (A | B)[]), and tuple labels ([a: string, b?: number, ...rest: boolean[]]) are decided here — in lockstep with the TypeJson schema's projection rules — so a renderer maps tokens to output without re-deriving type syntax. What a token *looks like* stays the consumer's decision: fuz_ui links name tokens to API docs and syntax-highlights code tokens; a CLI might print them all plainly. Adjacent punctuation merges into single text tokens.

Union members render in the tree's order — written order where the tree recovered it (see TypeJson) — so the result can list them in a different order from the flat string beside the tree, which prints in the checker's.

import {typeJsonToTokens} from 'svelte-docinfo/declaration-helpers.ts';

parameters

node

: TypeJson
#

the TypeJson tree to flatten (a typeInfo/returnTypeInfo field)

returns

tokens in source order; concatenating their text yields the printed type

examples

typeJsonToTokens({kind: 'reference', name: 'Map', typeArgs: [ {kind: 'intrinsic', text: 'string'}, {kind: 'reference', name: 'Tome'} ]}) // => [{kind: 'name', name: 'Map'}, {kind: 'text', text: '<'}, // {kind: 'code', text: 'string'}, {kind: 'text', text: ', '}, // {kind: 'name', name: 'Tome'}, {kind: 'text', text: '>'}]

unionMemberSetKey
#

typescript-extract-type-json.ts view source

unionMemberSetKey(type: UnionType): string | undefined

The member-set key of a union — sorted internal type ids, undefined filtered — or undefined when unusable (an internal-API id missing, or fewer than two non-undefined members, a set no widened-union lookup can produce). One function for both sides so registration and lookup can't drift. Identity safety carries over from the ids: two unions share a key only when they share their non-undefined members by object identity.

import {unionMemberSetKey} from 'svelte-docinfo/typescript-extract-type-json.ts';

UnknownCsspropDiagnostic
#

diagnostics.ts view source

value + type

A component's @cssprop tag names a custom property the component never reads through var(): not in its <style> (nested fallbacks included), nor in the static text of its markup's style attributes, style: directives, or child components' style and --a attributes.

Usually a typo or a stale tag; it may also be a property the component leaves for its children to read. The entry stays in ComponentDeclarationJson.cssCustomProperties, documented: true, at the tag's line, which line also points at. Not emitted when the style wasn't read (css_parse_failed, css_lang_unsupported).

Always warning, query-time category.

import {UnknownCsspropDiagnostic} from 'svelte-docinfo/diagnostics.ts';

inheritance

extends: SchemaStrictObjectOutput<typeof UnknownCsspropDiagnosticEntries>

members

kind

: "unknown_cssprop"
#

propertyName

: string
#

The custom property the @cssprop tag names, -- included.

componentName

: string
#

Name of the component.

file

: string
#

File path relative to project root (no leading slash, no ./ prefix).

Normalized at every public API boundary — session.setFile/setFiles (ingest-time), session.query (query-time, via analyzeCore), and the one-shot wrappers analyze / analyzeFromFiles. Producers inside the pipeline may write absolute or virtual paths (e.g., Foo.svelte.__svelte2tsx__.ts); normalization rewrites them to project-relative form before they reach consumers.

The exception is discovery — discoverSourceFiles / discoverFromExports return their diagnostics unnormalized, since they run before any session exists. Their file is already project-root-relative, but message can embed an absolute path (an fs error names the file it failed on), so a consumer wiring discovery up itself owns the normalizeDiagnosticPaths call — analyzeFromFiles and the Vite plugin both make it before merging.

The absolute form is the one to write. Normalization deliberately leaves an already-relative path alone (relativizing it would resolve against cwd), so a producer writing a ModuleJson.path — relative to sourceRoot, a different base — passes through untouched and publishes the same file under a second name. Absolute is what the pass can actually correct.

message

: string
#

Human-readable description of the issue.

severity

: "error" | "warning"
#

line

?: number
#

Line number (1-based), absent if location unavailable.

column

?: number
#

Column number (1-based), absent if location unavailable.

UnknownCsspropDiagnosticInput
#

diagnostics.ts view source

The input UnknownCsspropDiagnostic parses, with any field it defaults optional.

import type {UnknownCsspropDiagnosticInput} from 'svelte-docinfo/diagnostics.ts';

inheritance

extends: SchemaStrictObjectInput<typeof UnknownCsspropDiagnosticEntries>

members

kind

: "unknown_cssprop"
#

propertyName

: string
#

The custom property the @cssprop tag names, -- included.

componentName

: string
#

Name of the component.

file

: string
#

File path relative to project root (no leading slash, no ./ prefix).

Normalized at every public API boundary — session.setFile/setFiles (ingest-time), session.query (query-time, via analyzeCore), and the one-shot wrappers analyze / analyzeFromFiles. Producers inside the pipeline may write absolute or virtual paths (e.g., Foo.svelte.__svelte2tsx__.ts); normalization rewrites them to project-relative form before they reach consumers.

The exception is discovery — discoverSourceFiles / discoverFromExports return their diagnostics unnormalized, since they run before any session exists. Their file is already project-root-relative, but message can embed an absolute path (an fs error names the file it failed on), so a consumer wiring discovery up itself owns the normalizeDiagnosticPaths call — analyzeFromFiles and the Vite plugin both make it before merging.

The absolute form is the one to write. Normalization deliberately leaves an already-relative path alone (relativizing it would resolve against cwd), so a producer writing a ModuleJson.path — relative to sourceRoot, a different base — passes through untouched and publishes the same file under a second name. Absolute is what the pass can actually correct.

message

: string
#

Human-readable description of the issue.

severity

: "error" | "warning"
#

line

?: number
#

Line number (1-based), absent if location unavailable.

column

?: number
#

Column number (1-based), absent if location unavailable.

UnknownParamDiagnostic
#

diagnostics.ts view source

value + type

@param tag references a name that doesn't match any actual parameter.

Usually a typo (@param argz for parameter args) or stale doc after a rename. The description is dropped; analysis continues.

import {UnknownParamDiagnostic} from 'svelte-docinfo/diagnostics.ts';

inheritance

extends: SchemaStrictObjectOutput<typeof UnknownParamDiagnosticEntries>

members

kind

: "unknown_param"
#

paramName

: string
#

The @param key that didn't match a real parameter.

functionName

: string
#

Name of the function or method.

file

: string
#

File path relative to project root (no leading slash, no ./ prefix).

Normalized at every public API boundary — session.setFile/setFiles (ingest-time), session.query (query-time, via analyzeCore), and the one-shot wrappers analyze / analyzeFromFiles. Producers inside the pipeline may write absolute or virtual paths (e.g., Foo.svelte.__svelte2tsx__.ts); normalization rewrites them to project-relative form before they reach consumers.

The exception is discovery — discoverSourceFiles / discoverFromExports return their diagnostics unnormalized, since they run before any session exists. Their file is already project-root-relative, but message can embed an absolute path (an fs error names the file it failed on), so a consumer wiring discovery up itself owns the normalizeDiagnosticPaths call — analyzeFromFiles and the Vite plugin both make it before merging.

The absolute form is the one to write. Normalization deliberately leaves an already-relative path alone (relativizing it would resolve against cwd), so a producer writing a ModuleJson.path — relative to sourceRoot, a different base — passes through untouched and publishes the same file under a second name. Absolute is what the pass can actually correct.

message

: string
#

Human-readable description of the issue.

severity

: "error" | "warning"
#

line

?: number
#

Line number (1-based), absent if location unavailable.

column

?: number
#

Column number (1-based), absent if location unavailable.

UnknownParamDiagnosticInput
#

diagnostics.ts view source

The input UnknownParamDiagnostic parses, with any field it defaults optional.

import type {UnknownParamDiagnosticInput} from 'svelte-docinfo/diagnostics.ts';

inheritance

extends: SchemaStrictObjectInput<typeof UnknownParamDiagnosticEntries>

members

kind

: "unknown_param"
#

paramName

: string
#

The @param key that didn't match a real parameter.

functionName

: string
#

Name of the function or method.

file

: string
#

File path relative to project root (no leading slash, no ./ prefix).

Normalized at every public API boundary — session.setFile/setFiles (ingest-time), session.query (query-time, via analyzeCore), and the one-shot wrappers analyze / analyzeFromFiles. Producers inside the pipeline may write absolute or virtual paths (e.g., Foo.svelte.__svelte2tsx__.ts); normalization rewrites them to project-relative form before they reach consumers.

The exception is discovery — discoverSourceFiles / discoverFromExports return their diagnostics unnormalized, since they run before any session exists. Their file is already project-root-relative, but message can embed an absolute path (an fs error names the file it failed on), so a consumer wiring discovery up itself owns the normalizeDiagnosticPaths call — analyzeFromFiles and the Vite plugin both make it before merging.

The absolute form is the one to write. Normalization deliberately leaves an already-relative path alone (relativizing it would resolve against cwd), so a producer writing a ModuleJson.path — relative to sourceRoot, a different base — passes through untouched and publishes the same file under a second name. Absolute is what the pass can actually correct.

message

: string
#

Human-readable description of the issue.

severity

: "error" | "warning"
#

line

?: number
#

Line number (1-based), absent if location unavailable.

column

?: number
#

Column number (1-based), absent if location unavailable.

VariableDeclarationJson
#

types.ts view source

value + type

also exported from index.ts

A variable declaration. Has optional reactivity for top-level rune-module exports (e.g., export let count = $state(0) in .svelte.ts or <script module>).

import {VariableDeclarationJson} from 'svelte-docinfo/types.ts';

inheritance

extends: SchemaStrictObjectOutput<typeof VariableDeclarationJsonEntries>

members

kind

: "variable"
#

alsoExportedFrom

: string[]
#

Module paths (relative to sourceRoot) that re-export this declaration under the same name. The canonical declaration lives in this module's declarations array; these paths are additional import locations for the same thing.

The same edges appear from the re-exporting side as ModuleJson.reExports — use that when asking "what does this module re-export" instead of inverting these arrays. The two can disagree at the margins: a reExports entry whose canonical declaration is @nodocs (or whose module isn't in the analyzed set) has no back-link here.

Consumer note: To build a complete re-export map, scan two fields:

  1. alsoExportedFrom on each declaration — same-name re-exports
  2. aliasOf on declarations — renamed re-exports (separate declarations)

partial

: boolean
#

Whether extraction failed partway through, leaving some fields missing (e.g., typeSignature, parameters).

examples

: string[]
#

Code examples from @example tags.

seeAlso

: string[]
#

Related items from @see tags, in raw TSDoc format.

throws

: ThrowsJson[]
#

Exceptions from @throws tags. type is the tag's written type, and typeInfo its structured form, present for a braced type (@throws {A<B>}) that isn't the whole story as text (see TypeJson); an unbraced tag's leading word never has one, nor does a tag in a component's HTML @component comment, which is read as text.

name

: string
#

The exported name. Always populated. The default-export slot is named 'default', except a Svelte component, which takes its filename-derived name ('X' for X.svelte) — 'default' is the symbol's actual name in JS (import {default as X} and ns.default both expose it directly), and import X from 'mod' is sugar for import {default as X}. Consumers branch on name === 'default' to render the sugar form when desired.

modifiers

: ("public" | "protected" | "readonly" | "static" | "abstract" | "getter" | "setter")[]
#

TypeScript modifiers like readonly, static, or protected.

genericParams

: GenericParamJson[]
#

Generic type parameters like <T, U>.

reactivity

?: "$state" | "$state.raw" | "$derived" | "$derived.by"
#

Rune flavor when this variable is initialized with a value-producing reactivity rune.

defaultValue

?: string
#

Default value documented via @default, verbatim tag text with no normalization. Useful when the AST initializer is opaque (a call expression, computed value) and the author wants to document the conceptual default.

typeInfo

?: TypeJson
#

Structured type; absent when typeSignature is the whole story (see TypeJson).

aliasOf

?: { module: string; name: string; }
#

For renamed re-exports (export {foo as bar}), points to the original declaration. This declaration's name is the alias; aliasOf.name is the original name.

For renames out of the default slot (export {default as bar} from './x' where ./x is export default ...), aliasOf.name is 'default' — the canonical's actual symbol name. Consumers locate the canonical by (aliasOf.module, aliasOf.name).

Svelte component exception: when the source is a .svelte file (e.g., export {default as Foo} from './X.svelte'), the canonical's name is the component name (derived from the filename), so aliasOf.name is the component name ('X'), NOT 'default'. Consumers that branch on aliasOf.name === 'default' to detect default-rename should additionally check whether aliasOf.module ends with .svelte.

Different from alsoExportedFrom: aliases create new API surface names, while alsoExportedFrom tracks additional import paths for the same name.

A type-only rename of a value (export type {someConst as c} from './x') synthesizes a normal alias — declarations carry no type-only marker.

deprecatedMessage

?: string
#

Deprecation message from @deprecated tag.

since

?: string
#

Version introduced, from @since tag.

internalMessage

?: string
#

Internal-API marker from the @internal tag. Presence means the tag was written; an empty string is a bare tag with no trailing prose.

A marker, not an exclusion: @internal means "not stable public API" (TSDoc semantics) while the declaration, member, or prop stays documented — unlike @nodocs, which removes a declaration from output entirely (and is ignored on props and members).

mutates

?: Record<string, string>
#

Mutation documentation from @mutates tags (non-standard), mapping keys to descriptions.

Keys are intentionally unvalidated — typically a parameter name, but authors may also use compound paths (this.foo, obj.field) or multi-word external state references. Backticks are stripped from keys so `` a `` and a normalize to one key; an empty-string value is a bare tag with no description. The schema accepts any string key so consumers can render whatever the author wrote.

On a component prop it declares the component's mutation contract for the value it's handed: the component writes into the prop's object or array in place (@mutates items - appends the selected entry, @mutates options.cache - fills on first render). Reassigning a prop is not a mutation in this sense (bindable covers it), though a $bindable prop can carry both.

docComment

?: string
#

JSDoc/TSDoc comment.

typeSignature

?: string
#

Full TypeScript type signature.

sourceLine

?: number
#

1-based line in the source file, a positive integer. Synthesized aliases (see aliasOf) carry the local export specifier's line, not the canonical's.

VariableDeclarationJsonInput
#

types.ts view source

The input VariableDeclarationJson parses, with any field it defaults optional.

import type {VariableDeclarationJsonInput} from 'svelte-docinfo/types.ts';

inheritance

extends: SchemaStrictObjectInput<typeof VariableDeclarationJsonEntries>

members

kind

: "variable"
#

name

: string
#

The exported name. Always populated. The default-export slot is named 'default', except a Svelte component, which takes its filename-derived name ('X' for X.svelte) — 'default' is the symbol's actual name in JS (import {default as X} and ns.default both expose it directly), and import X from 'mod' is sugar for import {default as X}. Consumers branch on name === 'default' to render the sugar form when desired.

reactivity

?: "$state" | "$state.raw" | "$derived" | "$derived.by"
#

Rune flavor when this variable is initialized with a value-producing reactivity rune.

defaultValue

?: string
#

Default value documented via @default, verbatim tag text with no normalization. Useful when the AST initializer is opaque (a call expression, computed value) and the author wants to document the conceptual default.

typeInfo

?: TypeJson
#

Structured type; absent when typeSignature is the whole story (see TypeJson).

alsoExportedFrom

?: string[]
#

Module paths (relative to sourceRoot) that re-export this declaration under the same name. The canonical declaration lives in this module's declarations array; these paths are additional import locations for the same thing.

The same edges appear from the re-exporting side as ModuleJson.reExports — use that when asking "what does this module re-export" instead of inverting these arrays. The two can disagree at the margins: a reExports entry whose canonical declaration is @nodocs (or whose module isn't in the analyzed set) has no back-link here.

Consumer note: To build a complete re-export map, scan two fields:

  1. alsoExportedFrom on each declaration — same-name re-exports
  2. aliasOf on declarations — renamed re-exports (separate declarations)

aliasOf

?: { module: string; name: string; }
#

For renamed re-exports (export {foo as bar}), points to the original declaration. This declaration's name is the alias; aliasOf.name is the original name.

For renames out of the default slot (export {default as bar} from './x' where ./x is export default ...), aliasOf.name is 'default' — the canonical's actual symbol name. Consumers locate the canonical by (aliasOf.module, aliasOf.name).

Svelte component exception: when the source is a .svelte file (e.g., export {default as Foo} from './X.svelte'), the canonical's name is the component name (derived from the filename), so aliasOf.name is the component name ('X'), NOT 'default'. Consumers that branch on aliasOf.name === 'default' to detect default-rename should additionally check whether aliasOf.module ends with .svelte.

Different from alsoExportedFrom: aliases create new API surface names, while alsoExportedFrom tracks additional import paths for the same name.

A type-only rename of a value (export type {someConst as c} from './x') synthesizes a normal alias — declarations carry no type-only marker.

partial

?: boolean
#

Whether extraction failed partway through, leaving some fields missing (e.g., typeSignature, parameters).

examples

?: string[]
#

Code examples from @example tags.

deprecatedMessage

?: string
#

Deprecation message from @deprecated tag.

seeAlso

?: string[]
#

Related items from @see tags, in raw TSDoc format.

throws

?: ThrowsJsonInput[]
#

Exceptions from @throws tags. type is the tag's written type, and typeInfo its structured form, present for a braced type (@throws {A<B>}) that isn't the whole story as text (see TypeJson); an unbraced tag's leading word never has one, nor does a tag in a component's HTML @component comment, which is read as text.

since

?: string
#

Version introduced, from @since tag.

internalMessage

?: string
#

Internal-API marker from the @internal tag. Presence means the tag was written; an empty string is a bare tag with no trailing prose.

A marker, not an exclusion: @internal means "not stable public API" (TSDoc semantics) while the declaration, member, or prop stays documented — unlike @nodocs, which removes a declaration from output entirely (and is ignored on props and members).

mutates

?: Record<string, string>
#

Mutation documentation from @mutates tags (non-standard), mapping keys to descriptions.

Keys are intentionally unvalidated — typically a parameter name, but authors may also use compound paths (this.foo, obj.field) or multi-word external state references. Backticks are stripped from keys so `` a `` and a normalize to one key; an empty-string value is a bare tag with no description. The schema accepts any string key so consumers can render whatever the author wrote.

On a component prop it declares the component's mutation contract for the value it's handed: the component writes into the prop's object or array in place (@mutates items - appends the selected entry, @mutates options.cache - fills on first render). Reassigning a prop is not a mutation in this sense (bindable covers it), though a $bindable prop can carry both.

docComment

?: string
#

JSDoc/TSDoc comment.

typeSignature

?: string
#

Full TypeScript type signature.

modifiers

?: ("public" | "protected" | "readonly" | "static" | "abstract" | "getter" | "setter")[]
#

TypeScript modifiers like readonly, static, or protected.

sourceLine

?: number
#

1-based line in the source file, a positive integer. Synthesized aliases (see aliasOf) carry the local export specifier's line, not the canonical's.

genericParams

?: GenericParamJsonInput[]
#

Generic type parameters like <T, U>.

VariableMemberJson
#

types.ts view source

value + type

also exported from index.ts

A variable member (property, accessor, index signature, enum value). Shared fields plus optional reactivity for class fields initialized with a Svelte rune ($state, $state.raw, $derived, $derived.by).

optional reflects a ? token on the declaration (e.g., x?: string). Always false for index signatures and enum values.

import {VariableMemberJson} from 'svelte-docinfo/types.ts';

inheritance

extends: SchemaStrictObjectOutput<typeof VariableMemberJsonEntries>

members

kind

: "variable"
#

optional

: boolean
#

Whether the member has a ? token in its declaration.

partial

: boolean
#

Whether extraction failed partway through, leaving some fields missing (e.g., typeSignature, parameters).

examples

: string[]
#

Code examples from @example tags.

seeAlso

: string[]
#

Related items from @see tags, in raw TSDoc format.

throws

: ThrowsJson[]
#

Exceptions from @throws tags. type is the tag's written type, and typeInfo its structured form, present for a braced type (@throws {A<B>}) that isn't the whole story as text (see TypeJson); an unbraced tag's leading word never has one, nor does a tag in a component's HTML @component comment, which is read as text.

name

: string
#

The exported name. Always populated. The default-export slot is named 'default', except a Svelte component, which takes its filename-derived name ('X' for X.svelte) — 'default' is the symbol's actual name in JS (import {default as X} and ns.default both expose it directly), and import X from 'mod' is sugar for import {default as X}. Consumers branch on name === 'default' to render the sugar form when desired.

modifiers

: ("public" | "protected" | "readonly" | "static" | "abstract" | "getter" | "setter")[]
#

TypeScript modifiers like readonly, static, or protected.

genericParams

: GenericParamJson[]
#

Generic type parameters like <T, U>.

reactivity

?: "$state" | "$state.raw" | "$derived" | "$derived.by"
#

Rune flavor when this field is initialized with a value-producing reactivity rune.

defaultValue

?: string
#

Default value documented via @default, verbatim tag text with no normalization. Initializers aren't captured — a class field's typeSignature is its checker type, not its initializer.

typeInfo

?: TypeJson
#

Structured type; absent when typeSignature is the whole story (see TypeJson). Member types are checker-backed everywhere — type-alias and interface properties and index signatures, class properties (annotated or inferred), and accessors (getter-backed or setter-only) all resolve through the checker, with written annotations feeding name recovery.

deprecatedMessage

?: string
#

Deprecation message from @deprecated tag.

since

?: string
#

Version introduced, from @since tag.

internalMessage

?: string
#

Internal-API marker from the @internal tag. Presence means the tag was written; an empty string is a bare tag with no trailing prose.

A marker, not an exclusion: @internal means "not stable public API" (TSDoc semantics) while the declaration, member, or prop stays documented — unlike @nodocs, which removes a declaration from output entirely (and is ignored on props and members).

mutates

?: Record<string, string>
#

Mutation documentation from @mutates tags (non-standard), mapping keys to descriptions.

Keys are intentionally unvalidated — typically a parameter name, but authors may also use compound paths (this.foo, obj.field) or multi-word external state references. Backticks are stripped from keys so `` a `` and a normalize to one key; an empty-string value is a bare tag with no description. The schema accepts any string key so consumers can render whatever the author wrote.

On a component prop it declares the component's mutation contract for the value it's handed: the component writes into the prop's object or array in place (@mutates items - appends the selected entry, @mutates options.cache - fills on first render). Reassigning a prop is not a mutation in this sense (bindable covers it), though a $bindable prop can carry both.

docComment

?: string
#

JSDoc/TSDoc comment.

typeSignature

?: string
#

Full TypeScript type signature.

sourceLine

?: number
#

1-based line in the source file, a positive integer. Synthesized aliases (see aliasOf) carry the local export specifier's line, not the canonical's.

VariableMemberJsonInput
#

types.ts view source

The input VariableMemberJson parses, with any field it defaults optional.

import type {VariableMemberJsonInput} from 'svelte-docinfo/types.ts';

inheritance

extends: SchemaStrictObjectInput<typeof VariableMemberJsonEntries>

members

kind

: "variable"
#

name

: string
#

The exported name. Always populated. The default-export slot is named 'default', except a Svelte component, which takes its filename-derived name ('X' for X.svelte) — 'default' is the symbol's actual name in JS (import {default as X} and ns.default both expose it directly), and import X from 'mod' is sugar for import {default as X}. Consumers branch on name === 'default' to render the sugar form when desired.

optional

?: boolean
#

Whether the member has a ? token in its declaration.

reactivity

?: "$state" | "$state.raw" | "$derived" | "$derived.by"
#

Rune flavor when this field is initialized with a value-producing reactivity rune.

defaultValue

?: string
#

Default value documented via @default, verbatim tag text with no normalization. Initializers aren't captured — a class field's typeSignature is its checker type, not its initializer.

typeInfo

?: TypeJson
#

Structured type; absent when typeSignature is the whole story (see TypeJson). Member types are checker-backed everywhere — type-alias and interface properties and index signatures, class properties (annotated or inferred), and accessors (getter-backed or setter-only) all resolve through the checker, with written annotations feeding name recovery.

partial

?: boolean
#

Whether extraction failed partway through, leaving some fields missing (e.g., typeSignature, parameters).

examples

?: string[]
#

Code examples from @example tags.

deprecatedMessage

?: string
#

Deprecation message from @deprecated tag.

seeAlso

?: string[]
#

Related items from @see tags, in raw TSDoc format.

throws

?: ThrowsJsonInput[]
#

Exceptions from @throws tags. type is the tag's written type, and typeInfo its structured form, present for a braced type (@throws {A<B>}) that isn't the whole story as text (see TypeJson); an unbraced tag's leading word never has one, nor does a tag in a component's HTML @component comment, which is read as text.

since

?: string
#

Version introduced, from @since tag.

internalMessage

?: string
#

Internal-API marker from the @internal tag. Presence means the tag was written; an empty string is a bare tag with no trailing prose.

A marker, not an exclusion: @internal means "not stable public API" (TSDoc semantics) while the declaration, member, or prop stays documented — unlike @nodocs, which removes a declaration from output entirely (and is ignored on props and members).

mutates

?: Record<string, string>
#

Mutation documentation from @mutates tags (non-standard), mapping keys to descriptions.

Keys are intentionally unvalidated — typically a parameter name, but authors may also use compound paths (this.foo, obj.field) or multi-word external state references. Backticks are stripped from keys so `` a `` and a normalize to one key; an empty-string value is a bare tag with no description. The schema accepts any string key so consumers can render whatever the author wrote.

On a component prop it declares the component's mutation contract for the value it's handed: the component writes into the prop's object or array in place (@mutates items - appends the selected entry, @mutates options.cache - fills on first render). Reassigning a prop is not a mutation in this sense (bindable covers it), though a $bindable prop can carry both.

docComment

?: string
#

JSDoc/TSDoc comment.

typeSignature

?: string
#

Full TypeScript type signature.

modifiers

?: ("public" | "protected" | "readonly" | "static" | "abstract" | "getter" | "setter")[]
#

TypeScript modifiers like readonly, static, or protected.

sourceLine

?: number
#

1-based line in the source file, a positive integer. Synthesized aliases (see aliasOf) carry the local export specifier's line, not the canonical's.

genericParams

?: GenericParamJsonInput[]
#

Generic type parameters like <T, U>.

VirtualFileEntry
#

typescript-program.ts view source

A host-served file entry: content plus optional parser treatment.

import type {VirtualFileEntry} from 'svelte-docinfo/typescript-program.ts';

members

content

: string
#

scriptKind

?: ScriptKind
#

Overrides script-kind inference from the path's extension; undefined defers to the extension. JS-lang Svelte virtuals set this to parse as JS despite their .ts suffix; no allowJs needed, since virtuals are host-served.

VitePluginSvelteDocinfoOptions
#

vite.ts view source

Options for the svelteDocinfo Vite plugin.

import type {VitePluginSvelteDocinfoOptions} from 'svelte-docinfo/vite.ts';

members

projectRoot

?: string
#

Absolute path to project root directory. Defaults to Vite's resolved config.root.

include

?: string[]
#

Glob patterns to include, relative to projectRoot. Collapses discovery: 'auto' to glob (combining with 'exports' throws at config-resolve time), and each pattern's static base widens sourceOptions.sourcePaths so the matched files emit modules and the watcher tracks them (see createSourceOptionsWithInclude).

exclude

?: ExcludeOption
#

Glob patterns to exclude, applied at both discovery and analysis time — supersedes sourceOptions.exclude whole (no merge; the callback form still receives the built-in defaults). An array replaces the defaults, a callback extends them — see ExcludeOption.

resolveDependencies

?: boolean = true
#

Whether to resolve import dependencies.

When false, the session's resolver returns null for every specifier, so module dependencies/dependents stay empty.

discovery

?: Discovery = 'auto'
#

Discovery strategy for source files.

see also

distDir

?: string = 'dist'
#

Dist directory name relative to project root, used for exports-based discovery.

sourceOptions

?: SourceOptionsOverrides
#

Partial overrides for default source options (SvelteKit src/lib layout).

onDuplicates

?: OnDuplicates
#

Opt-in check that declaration names are unique across modules (see OnDuplicates).

tsconfig

?: string | false = 'tsconfig.json'
#

Path to the tsconfig, relative to the project root, or false to analyze without one (see LoadTsconfigOptions.tsconfig).

compilerOptions

?: CompilerOptions
#

Compiler options merged over the tsconfig's (see LoadTsconfigOptions.compilerOptions).

rootFileNames

?: RootFileNames = the tsconfig's roots
#

Root files for the program in place of the tsconfig's (see RootFileNames).

hmrDebounceMs

?: number = 100
#

Dev re-analysis debounce delay in milliseconds. Coalesces rapid file changes.

warningsOf
#

warnModuleCommentTags
#

typescript-exports.ts view source

internal

Split by source, not by file type: `analyzeExports` covers TS files only — it skips a svelte2tsx virtual, where hoisted instance-script comments would read as module comments — so `analyzeSvelteModule` owns all three Svelte sources (instance script, `<script module>`, HTML comment), reading each from the original file.

warnModuleCommentTags(moduleDoc: TsdocParsedComment | undefined, diagnosticFile: string, diagnostics: Diagnostic[]): void

Warn misplaced_tag for each tag a module comment carries that only describes a declaration: @param, @returns, @mutates, @throws, @default, @nodocs, and @cssprop (a component's). toModuleDocFields drops them, so in a module comment they do nothing. @nodocs applies to declarations and export statements; to omit a module, use exclude patterns.

Reads the parsed comment, so a tag counts when parseComment extracted it: a bare @returns or @throws with no text is dropped without a warning, as on an overload. Unknown tags drop silently, as on declarations.

import {warnModuleCommentTags} from 'svelte-docinfo/typescript-exports.ts';

parameters

moduleDoc

: TsdocParsedComment | undefined
#

the module comment as extractModuleComment (or a Svelte extractor) returns it

diagnosticFile

: string
#

absolute source id, the form normalizeDiagnosticPaths rewrites to the project-root-relative Diagnostic.file contract. Not a module path — those are relative to sourceRoot, and normalization passes an already-relative path through untouched, so a module path here ships as a second base for the same file.

mutates

  • diagnostics — appends one misplaced_tag per misplaced tag name

widenSourcePathsForInclude
#

source-config.ts view source

widenSourcePathsForInclude(sourcePaths: readonly string[], include: readonly string[]): readonly string[]

Union sourcePaths with the static base directories of explicit include patterns, so include-discovered files count as source at analysis time.

Discovery include globs can reach outside sourcePaths (`--include 'src/other/' under the default ['src/lib']`); without widening, the query-time source gate would drop those modules, and extractPath would have no root to relativize their paths against (its fallback is the absolute path). Each pattern contributes its static base (see includePatternBase). A root-crossing pattern (`'\/*.ts'`) contributes '', which scopes the whole project root as source.

Pure path-set logic — callers re-run createSourceOptions on the widened list so sourceRoot derivation and validation see the final set (an *explicit* sourceRoot that doesn't prefix a widened path fails that validation loudly rather than emitting absolute module paths; an out-of-root base hits the projectRoot-escape throw). Returns the input array identity when nothing widens. createSourceOptionsWithInclude wraps both steps for the common call shape.

import {widenSourcePathsForInclude} from 'svelte-docinfo/source-config.ts';

wrapResolveImport
#

dep-resolver.ts view source

wrapResolveImport(resolveImport: ResolveImportFn, identity?: string | symbol): ImportResolver

Wrap a bare resolveImport function into an ImportResolver token.

identity is optional; when omitted, a fresh Symbol('wrapped') is synthesized per call. The synthesized default suits single-use scopes — normalizeResolveImport relies on it to wrap a bare function for a one-shot analyze call or for a session default (wrapped once at construction, so the identity stays stable for the session's lifetime).

For a long-lived session that re-wraps the *same* logical resolver across calls (Vite plugin, LSP), a throwaway identity cache-misses every time — the fresh Symbol('wrapped') never compares equal. Pass a stable identity here, or — simpler — construct an ImportResolver ({resolve, identity}) directly and pass it through the ResolveImport union.

import {wrapResolveImport} from 'svelte-docinfo/dep-resolver.ts';

parameters

identity

?: string | symbol = Symbol('wrapped')
#

writtenGetterTypeNode
#

typescript-extract-type-json.ts view source

writtenGetterTypeNode(getter: GetAccessorDeclaration): TypeNode | undefined

The written type of a getter, the checker's reading: in JS a @type {A} tag on the getter wins, typing the accessor A, then the written return type (writtenReturnTypeNode).

import {writtenGetterTypeNode} from 'svelte-docinfo/typescript-extract-type-json.ts';

writtenReturnTypeNode
#

typescript-extract-type-json.ts view source

writtenReturnTypeNode(decl: SignatureDeclaration): TypeNode | undefined

The written return type of a signature declaration, the checker's reading (TypeScript's internal getEffectiveReturnTypeNode) outside JSDoc signatures, which applyReturnType reads itself: its own type, or in JS the @returns tag's type, else the return type of a function type its @type tag writes (ts.getJSDocReturnType).

import {writtenReturnTypeNode} from 'svelte-docinfo/typescript-extract-type-json.ts';

writtenTypeAnnotation
#

typescript-extract-type-json.ts view source

writtenTypeAnnotation(node: ParameterDeclaration | VariableDeclaration | PropertyDeclaration | PropertySignature | JSDocPropertyLikeTag): TypeNode | undefined

The written type annotation of a declaration, the checker's reading (TypeScript's internal getEffectiveTypeAnnotationNode): its own type, or in JS its JSDoc type — a @param/@property tag's braced type, or the @type tag's (ts.getJSDocType). In a .ts file JSDoc types annotate nothing, so they're never read. Every variable, parameter, property, and property-tag site reads its writtenNode through it, so a JSDoc-annotated JS site gets written-name recovery and written union order like its TypeScript twin.

import {writtenTypeAnnotation} from 'svelte-docinfo/typescript-extract-type-json.ts';

WrittenTypeContext
#