analyze-core.ts

Pure two-phase analysis orchestrator.

Separate from analyze.ts so session.ts (which needs the orchestrator) and analyze.ts (which needs the session) both import downward into this module without a cycle.

Public surface:

The barrel-surfaced schemas and types are stable API. Everything else is subpath-only; analyzeCore and analyzeModule are @internal.

view source

Declarations
#

11 declarations

analyzeCore
#

analyze-core.ts view source

internal

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

(inputs: AnalyzeCoreInputs): AnalyzeResultJson import {analyzeCore} from 'svelte-docinfo/analyze-core.js';

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.

inputs

returns

AnalyzeResultJson

AnalyzeCoreInputs
#

analyze-core.ts view source

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

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.

sourceFiles

type readonly SourceFileInfo[]

sourceOptions

type ModuleSourceOptions

program

type Program

svelteVirtualFiles

type ReadonlyMap<string, SvelteVirtualFile>

transformFailedIds?

Svelte file IDs whose svelte2tsx transform failed at ingest.

type ReadonlySet<string>

contextSvelteFiles?

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.

type readonly SourceFileInfo[]

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.

type (file: string): boolean

file

type string
returns boolean

onDuplicates?

type OnDuplicates

log?

type AnalysisLog

analyzeModule
#

analyze-core.ts view source

internal

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

(sourceFile: SourceFileInfo & { dependents?: readonly string[] | undefined; }, program: Program, options: ModuleSourceOptions, diagnostics: Diagnostic[], log?: AnalysisLog | undefined, aliasRegistry?: AliasRegistry | undefined, isEmittedFile?: IsEmittedFile | undefined, fileExists?: FileExists | undefined): ModuleJson | undefined import {analyzeModule} from 'svelte-docinfo/analyze-core.js';

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).

sourceFile

type SourceFileInfo & { dependents?: readonly string[] | undefined; }

program

type Program

options

diagnostics

type Diagnostic[]

log?

optional

aliasRegistry?

optional

isEmittedFile?

optional

fileExists?

optional

returns

ModuleJson | undefined

AnalyzeResultJson
#

analyze-core.ts view source

value + type

also exported from index.ts

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

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.

inheritance

extends: s.SchemaStrictObjectOutput< typeof AnalyzeResultJsonEntries >

modules

type ModuleJson[]

diagnostics

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)[]

AnalyzeResultJsonInput
#

analyze-core.ts view source

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

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

inheritance

extends: s.SchemaStrictObjectInput< typeof AnalyzeResultJsonEntries >

modules?

type ModuleJsonInput[]

diagnostics?

type (TypeExtractionDiagnosticInput | SignatureAnalysisDiagnosticInput | ClassMemberDiagnosticInput | SveltePropDiagnosticInput | ModuleSkippedDiagnosticInput | ModuleUnreadableDiagnosticInput | ImportParseDiagnosticInput | DuplicateCommentDiagnosticInput | ComponentCommentMismatchDiagnosticInput | MisplacedTagDiagnosticInput | ImplementationDocHiddenDiagnosticInput | UnknownParamDiagnosticInput | UnknownCsspropDiagnosticInput | MalformedTagDiagnosticInput | DuplicateTagDiagnosticInput | CsspropDefaultMismatchDiagnosticInput | SourceMapFailedDiagnosticInput | DuplicateDeclarationDiagnosticInput | TransformFailedDiagnosticInput | ResolverFailedDiagnosticInput | AliasLostDiagnosticInput | CommonjsUnsupportedDiagnosticInput | CssParseFailedDiagnosticInput | CssLangUnsupportedDiagnosticInput)[]

AnalyzeResultJsonWire
#

analyze-core.ts view source

also exported from index.ts

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

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.

modules

type ModuleJsonInput[]

diagnostics

type Diagnostic[]

finalizeDiagnostics
#

analyze-core.ts view source

(diagnostics: Diagnostic[], options: { projectRoot: string; virtualFiles?: Iterable<SvelteVirtualFile> | undefined; }): void import {finalizeDiagnostics} from 'svelte-docinfo/analyze-core.js';

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.

diagnostics

type Diagnostic[]

options

type { projectRoot: string; virtualFiles?: Iterable<SvelteVirtualFile> | undefined; }

returns

void

mutates

  • diagnostics — rewrites positions, `file`, and `message`, and removes duplicates

normalizeDiagnosticPaths
#

analyze-core.ts view source

(diagnostics: Diagnostic[], projectRoot: string): void import {normalizeDiagnosticPaths} from 'svelte-docinfo/analyze-core.js';

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.

diagnostics

type Diagnostic[]

projectRoot

type string

returns

void

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)

normalizeModulePathsInTypes
#

analyze-core.ts view source

(modules: ModuleJson[], options: ModuleSourceOptions, program: Program): void import {normalizeModulePathsInTypes} from 'svelte-docinfo/analyze-core.js';

Normalize the absolute module paths TypeScript embeds in printed type text, in place.

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.

modules

type ModuleJson[]

options

program

type Program

returns

void

mutates

  • modules — rewrites printed type text on declarations and members

OnDuplicates
#

analyze-core.ts view source

also exported from index.ts

OnDuplicates

type "diagnostic" | "warn" | "throw"

import type {OnDuplicates} from 'svelte-docinfo/analyze-core.js';

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').

parseAnalyzeResult
#

analyze-core.ts view source

also exported from index.ts

(value: unknown): AnalyzeResultJson import {parseAnalyzeResult} from 'svelte-docinfo/analyze-core.js';

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.

value

an analysis result, typically from JSON.parse

type unknown

returns

AnalyzeResultJson

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')));

Depends on
#

Imported by
#