Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(ingestion): Svelte at the Full tier via a byte-preserving TS projection (#1221)

Raghav Chamadiya7d0f4277edc7
diff --git a/README.md b/README.md
index 3c5730cce..eb19b0c99 100644
--- a/README.md
+++ b/README.md
@@ -107,7 +107,7 @@ queryable from the CLI, the MCP tools, and the local dashboard.
| Layer | What it gives you | Edge |
|---|---|---|
-| **◈ Graph** | Dependency graph across 16 languages · file + symbol nodes · 3-tier call resolution · Leiden communities · PageRank and execution flows · framework-aware route→handler edges | A real graph most tools never build |
+| **◈ Graph** | Dependency graph across 17 languages · file + symbol nodes · 3-tier call resolution · Leiden communities · PageRank and execution flows · framework-aware route→handler edges | A real graph most tools never build |
| **◈ Git** | Hotspots (churn × complexity) · ownership % · co-change pairs (hidden coupling) · bus factor · which files actually get bug-fixed, and how recently | Behavioural signals static analysis cannot see |
| **◈ Docs** | A generated wiki page per module and file · rebuilt incrementally every commit · freshness and confidence scoring · hybrid search (full-text + vector) · selectable style and output language | Stays current instead of rotting |
| **◈ Decisions** | Architectural decisions mined from eight sources, evidence-backed, linked to the graph nodes they govern, connected by supersedes / refines / conflicts_with, tracked for staleness | **★ Captured nowhere else** |
@@ -339,13 +339,14 @@ Set Up This Repository**. Guide: **[docs/agent/VSCODE.md →](docs/agent/VSCODE.
## Supported languages
-**16 languages parsed to AST · 11 at the Full tier · framework-aware across all of them.**
+**17 languages parsed to AST · 12 at the Full tier · framework-aware across all of them.**
<p>
<strong>Full tier &nbsp;</strong>
<img src="https://img.shields.io/badge/Python-3776AB?style=flat-square&logo=python&logoColor=white" alt="Python" />
<img src="https://img.shields.io/badge/TypeScript-3178C6?style=flat-square&logo=typescript&logoColor=white" alt="TypeScript" />
<img src="https://img.shields.io/badge/JavaScript-F7DF1E?style=flat-square&logo=javascript&logoColor=black" alt="JavaScript" />
+ <img src="https://img.shields.io/badge/Svelte-FF3E00?style=flat-square&logo=svelte&logoColor=white" alt="Svelte" />
<img src="https://img.shields.io/badge/Java-ED8B00?style=flat-square&logo=openjdk&logoColor=white" alt="Java" />
<img src="https://img.shields.io/badge/Kotlin-7F52FF?style=flat-square&logo=kotlin&logoColor=white" alt="Kotlin" />
<img src="https://img.shields.io/badge/Go-00ADD8?style=flat-square&logo=go&logoColor=white" alt="Go" />
diff --git a/docs/architecture/language-support.md b/docs/architecture/language-support.md
index 87274a440..fd77b8f99 100644
--- a/docs/architecture/language-support.md
+++ b/docs/architecture/language-support.md
@@ -23,6 +23,8 @@ Extension/filename -> LanguageTag (via LanguageRegistry)
|
+-- Config/data language? -> empty ParsedFile (passthrough)
+-- Special format? -> special_handlers.py (OpenAPI/Dockerfile/Makefile/SQL)
+ +-- Multi-language file? -> svelte_source.py projects it to one
+ | grammar's language at identical offsets
+-- Has grammar? -> tree-sitter AST parsing
|
v
@@ -44,7 +46,9 @@ Extension/filename -> LanguageTag (via LanguageRegistry)
(src/ + monorepo packages/*/src + PEP 420 namespace
packages), __init__.py re-export barrels, stem fallback
TS/JS: relative paths, tsconfig aliases, workspace exports,
- `export ... from` re-export barrels, node_modules
+ `export ... from` re-export barrels, node_modules,
+ package.json "imports" (`#alias/*`) subpath imports
+ Svelte: the TS/JS resolver plus SvelteKit's `$lib` -> src/lib
Go: go.mod module path stripping
Rust: crate::/self::/super::, mod.rs probing
C/C++: compile_commands.json include directories
@@ -112,6 +116,7 @@ ingestion/
registry.py # HintRegistry
django.py pytest_hints.py python_imports.py node.py dotnet.py
spring.py ruby.py php.py scala.py swift.py c.py cpp.py luau.py go.py jvm.py
+ svelte_source.py # Multi-language-file projection (see below)
parser.py # ASTParser (language-agnostic orchestration)
graph.py # GraphBuilder (import/call/heritage resolution)
@@ -168,8 +173,10 @@ SPEC = LanguageSpec(
Then register it in `languages/specs/__init__.py` by importing the module and
slotting it into the `ALL_SPECS` tuple. **Order matters**: `LanguageRegistry`
builds its extension map first-spec-wins, so place more specific languages
-ahead of ones that share an extension (e.g. TypeScript before JavaScript). You
-never edit `registry.py` itself.
+ahead of ones that share an extension (e.g. TypeScript before JavaScript). A
+spec using `shares_grammar_with` must also come *after* the spec it borrows
+from, which is resolved against the registry built so far. You never edit
+`registry.py` itself.
### Step 2: Add the `LanguageTag`
@@ -196,7 +203,10 @@ tree-sitter S-expression syntax. Follow the capture-name conventions:
| `@call.receiver` | Object the call is made on | No |
| `@call.arguments` | Call arguments | No |
-`python.scm` and `typescript.scm` are good starting points.
+`python.scm` and `typescript.scm` are good starting points. A language whose
+syntax *is* another's can skip this step entirely by pointing `scm_file` at the
+existing query file — that field names the query to load, so `svelte` declares
+`scm_file="typescript.scm"` and writes no `.scm` of its own.
### Step 4: Add a `LanguageConfig` entry
@@ -267,6 +277,44 @@ language sets from the registry automatically.
---
+## Multi-language files (the Svelte pattern)
+
+Some file types hold more than one language. A `.svelte` component is TS/JS in
+its `<script>` blocks, Svelte-flavoured HTML in its markup, and CSS in
+`<style>`. `tree-sitter-svelte` parses the markup but returns each `<script>`
+body as one opaque `raw_text` node, so a `.scm` query against it captures no
+symbol, import, or call — a grammar alone cannot support such a language.
+
+`ingestion/svelte_source.py` solves this with a **byte-preserving projection**
+rather than a second coordinate space:
+
+1. the Svelte grammar *locates* the JS-bearing regions — every `<script>` body,
+ every markup `{expression}`, and the `{#if}` / `{@html}` heads;
+2. every byte outside those regions is blanked to a space, with newlines kept;
+3. each kept markup expression is fenced by rewriting its surrounding `{` and
+ `}` to `;`, so `{a}{b}` cannot run together and an unterminated final script
+ statement cannot swallow the following expression via ASI.
+
+The result is valid TypeScript whose every byte offset and line number matches
+the original file. That single property is what makes the rest free: the spec
+declares `shares_grammar_with="typescript"` and `scm_file="typescript.scm"`, the
+`LanguageConfig` is an alias of TypeScript's, and the three health dialect
+registries alias the TS entries. Each consumer that hands raw bytes to a
+tree-sitter `Parser` calls `prepare_source(language, source)` first — the
+ingestion parser plus the complexity, dataflow, and duplication walkers. It is
+a no-op for every other language.
+
+Two things markup carries that the projection cannot express are minted
+separately: the component symbol itself (via
+`extractors/synthetic_symbols/svelte_component.py`, since the filename is the
+only thing that names a component) and `<Foo />` instantiation call edges (via
+`component_call_sites`, the analogue of `tsx.scm`'s JSX captures).
+
+The same three steps would fit Vue SFCs or Astro components; only the
+region-locating grammar changes.
+
+---
+
## Optional language-specific passes
Several pluggable hooks let a language opt into deeper resolution without
diff --git a/docs/business/COMMERCIAL.md b/docs/business/COMMERCIAL.md
index e184dd75b..8417652ef 100644
--- a/docs/business/COMMERCIAL.md
+++ b/docs/business/COMMERCIAL.md
@@ -41,7 +41,7 @@ scale, in a regulated or security-sensitive environment**:
All of the following ship in `pip install repowise` today, free for internal use.
-- **Five intelligence layers** — Graph (tree-sitter AST across 16 languages, two-tier
+- **Five intelligence layers** — Graph (tree-sitter AST across 17 languages, two-tier
dependency graph, call resolution, heritage extraction, Leiden communities,
PageRank / betweenness / SCC), Git (hotspots, ownership, co-change pairs, bus
factor, significant commits, contributor profiles, module health), Documentation
@@ -82,7 +82,7 @@ All of the following ship in `pip install repowise` today, free for internal use
## 3. First-class language coverage
-Repowise treats **11 languages at Full tier** (Python, TypeScript, JavaScript, Java,
+Repowise treats **12 languages at Full tier** (Python, TypeScript, JavaScript, Svelte, Java,
Kotlin, Go, Rust, C++, **C#**, Scala, and Ruby) with AST parsing, import resolution,
named bindings, call resolution, heritage extraction, multi-project workspace
resolvers, framework-aware edges, per-language dynamic-hint extractors, and
diff --git a/docs/layers/INTELLIGENCE_LAYERS.md b/docs/layers/INTELLIGENCE_LAYERS.md
index dca482501..60c0e66a4 100644
--- a/docs/layers/INTELLIGENCE_LAYERS.md
+++ b/docs/layers/INTELLIGENCE_LAYERS.md
@@ -28,7 +28,7 @@ Two cross-cutting capabilities sit on top of the layers:
## Graph Intelligence
-tree-sitter parses every file across 16 languages into a **two-tier dependency
+tree-sitter parses every file across 17 languages into a **two-tier dependency
graph**: file nodes and symbol nodes (functions, classes, methods). A 3-tier
call resolver with confidence scoring handles import aliases, barrel
re-exports, and namespace imports. Heritage extraction covers `extends`,
diff --git a/docs/layers/LANGUAGE_SUPPORT.md b/docs/layers/LANGUAGE_SUPPORT.md
index 4126a45ec..bf2c6f6f3 100644
--- a/docs/layers/LANGUAGE_SUPPORT.md
+++ b/docs/layers/LANGUAGE_SUPPORT.md
@@ -1,7 +1,7 @@
# Language Support
-repowise parses **16 languages to a full AST**, resolves imports and call
-graphs across them, and scores **11 at the Full tier** with code-health markers.
+repowise parses **17 languages to a full AST**, resolves imports and call
+graphs across them, and scores **12 at the Full tier** with code-health markers.
Everything else in your repo is still tracked through git history and appears in
the wiki. This page is the "what works for my language today" reference.
@@ -19,7 +19,7 @@ produce meaningful output.
| Tier | Languages | What works |
|------|-----------|------------|
-| **Full** | Python · TypeScript · JavaScript · Java · Kotlin · Go · Rust · C++ · C# · Scala · Ruby | AST parsing, import resolution, named bindings, call resolution, heritage, docstrings, framework-aware edges, dynamic-hint extractors, and **code-health markers** |
+| **Full** | Python · TypeScript · JavaScript · Svelte · Java · Kotlin · Go · Rust · C++ · C# · Scala · Ruby | AST parsing, import resolution, named bindings, call resolution, heritage, docstrings, framework-aware edges, dynamic-hint extractors, and **code-health markers** |
| **Good** | C · Swift · PHP · Dart | Everything above except code-health markers (C, Swift, PHP; Dart *does* get health markers). Dedicated workspace resolvers and framework edges per language |
| **SQL / dbt** | `.sql` via sqlglot | Tables / views / functions / procedures as symbols with wiki pages; dbt projects get real `ref()` / `source()` lineage |
| **Shell** | `.sh` `.bash` `.zsh` | Function definitions as symbols, `source` / `.` import edges (incl. `$SCRIPT_DIR` / `dirname` / `$BATS_ROOT` idioms), and function-level code-health complexity (CCN, nesting, cognitive). No class metrics, heritage, bindings, or dead-code flagging |
@@ -61,6 +61,7 @@ extractors, and code-health markers.
| **Python** | `.py` `.pyi` | `import x` / `from x import y`; source-root-aware module index (src/, monorepo `packages/*/src`, PEP 420), `__init__.py` re-export barrels |
| **TypeScript** | `.ts` `.tsx` | ESM / `require()` with tsconfig path aliases, npm/yarn/pnpm workspaces, `export * from` barrels, optional `.vue`/`.svelte`/`.astro` probing |
| **JavaScript** | `.js` `.jsx` `.mjs` `.cjs` | `import` / `require()` including CommonJS re-export shapes and member picks |
+| **Svelte** | `.svelte` | Same resolver as TS/JS, plus SvelteKit's `$lib` alias and Node `#`-prefixed subpath imports; `$app/*` / `$env/*` stay external (virtual modules) |
| **Java** | `.java` | `import pkg.Class` / `.*` / `import static` with Maven + Gradle reactor discovery, JPMS recognition, package fan-out |
| **Kotlin** | `.kt` `.kts` | Shares the JVM workspace index with Java (cross-language resolution); `.kt` under `src/main/java` recognised |
| **Go** | `.go` | `import "path"` with multi-module `go.mod` discovery; a package import fans out to every file in the package |
@@ -70,10 +71,33 @@ extractors, and code-health markers.
| **Scala** | `.scala` | `import pkg.Foo`, brace/wildcard/package imports via the shared JVM index (cross-language with Java/Kotlin); SBT / Mill build parsing as fallback (partial import resolution¹) |
| **Ruby** | `.rb` | `require` / `require_relative` with `$LOAD_PATH` probing, Gemfile externals, RSpec mirror edges, Rails / Zeitwerk autoloading |
-All eleven also support three-tier call resolution (same-file, cross-file,
+All twelve also support three-tier call resolution (same-file, cross-file,
global stem match) and docstring extraction (Python, Ruby comments, JSDoc,
GoDoc, Rustdoc, Javadoc, Scaladoc, Doxygen, XML doc).
+**Svelte components** are three languages in one file, so they get a dedicated
+projection rather than a grammar of their own. `tree-sitter-svelte` locates the
+`<script>` blocks and the markup `{expressions}`; everything else (markup,
+`<style>`) is blanked to spaces with newlines preserved, and the result is
+parsed as TypeScript at **byte-identical offsets**. So a component reuses the
+TypeScript queries, config, and all three health dialects verbatim, and every
+line number points at the real `.svelte` file. Three Svelte-specific pieces sit
+on top:
+
+- the **component itself** becomes a class-kind symbol named after the file
+ (`Button.svelte` → `Button`), since nothing in the source names it;
+- **`<Foo />` in markup** mints a call edge on `Foo`, the same way `tsx.scm`
+ treats a JSX element;
+- **markup expressions are kept**, so a handler referenced only from
+ `on:click={inc}` still carries an edge instead of reading as dead code.
+
+Two deliberate ceilings: `{#each x as y}` / `{#await …}` heads are Svelte block
+syntax rather than JS expressions and are skipped, as are object-literal
+attributes (`use:action={{ a, b }}`), which read as a block at statement
+position. And a component's `export let` props are set by the parent as markup
+attributes, never imported by name, so the unused-export pass is suppressed for
+`.svelte` — the alternative would flag every prop in the repo.
+
**Framework-aware edges** connect routes to handlers, DI registrations to
implementations, and ORM entities to relationships:
@@ -85,7 +109,7 @@ implementations, and ORM entities to relationships:
| C# | ASP.NET (attribute + minimal API), EF Core, gRPC-dotnet, host-builder extension methods, CommunityToolkit MVVM |
| Go | net/http, gin, echo, chi, gRPC server registration |
| Rust | Axum, Actix route → handler |
-| JS / TS | Next.js App Router, Hono / Fastify / Koa / Elysia, Remix / SvelteKit / Astro, tRPC, Express / NestJS |
+| JS / TS / Svelte | Next.js App Router, Hono / Fastify / Koa / Elysia, Remix / SvelteKit (`+page.svelte`, `+layout.svelte` and their `.ts` siblings) / Astro, tRPC, Express / NestJS |
| C++ | GoogleTest, Catch2, Boost.Test, doctest, Google Benchmark, libFuzzer |
The dead-code analyzer understands each ecosystem's entry points, generated-file
@@ -184,6 +208,7 @@ is "Full" vs "Good".
|----------|:---:|:---:|:---:|:---:|:---:|
| Python | ✅ | ✅ | ✅ | ✅ | ✅ |
| TypeScript / JavaScript | ✅ | ✅ | ✅ | ✅ | ✅ |
+| Svelte | ✅¹⁰ | ✅ | ✅ | ✅ | ✅ |
| Java | ✅ | ✅ | ✅ | ✅ | ✅ |
| Go | ✅ | n/a¹ | ✅ | ✅ | ✅ |
| Rust | ✅ | ✅ | ✅ | ✅ | ✅² |
@@ -232,6 +257,12 @@ keeps in-memory `Registry.find(name)` lookups silent. Backticks / `system` /
`Open3` are subprocess sinks; `s += "…"` in a loop is flagged while `s << x`
(amortized append) never is.
+¹⁰ Svelte rides the TypeScript dialect on all three health layers, because a
+component reaches them as a TypeScript buffer. Markers therefore cover the
+`<script>` blocks and markup expressions — the parts that *are* JS. Markup
+structure and `<style>` carry no health signal, so a component's markers
+describe its logic, not its template size.
+
⁹ Shell gets function-level complexity only (CCN / nesting / cognitive / NLOC).
`&&` / `||` command lists count toward CCN (`cmd || exit 1` is +1), which is
honest: shell branching is chained command lists. There are no classes,
@@ -250,6 +281,7 @@ where a dialect isn't wired yet. Per-marker mechanics and precision hazards:
| Language | Target tier | Status |
|----------|------------|--------|
+| Svelte | Full | Shipped: TS projection of `<script>` + markup expressions, component symbols, `<Foo />` call edges, `$lib` / `#`-subpath resolution, SvelteKit route edges, all three health dialects. Next: `{#each}` head bindings, object-literal attributes, `.svelte.ts` rune modules |
| Dart | Good | Shipped: AST, health control-flow + class facts, perf dialect, Flutter edges. Next: riverpod/get_it dynamic hints, dataflow dialect |
| Scala | Full (health) | Shipped: complexity/class/assertion markers + perf dialect (JVM lexicon, `.r` recompile, sync-over-Future). Next: dataflow dialect, combinator (`.map`/`.foreach`) loop tracking via the shared `block_loop_body` hook Ruby established |
| Ruby | Full (health) | Shipped: complexity/class/assertion markers + perf dialect with block-iteration loops (`.each`/`.map` blocks) and the stratified ActiveRecord N+1 lexicon. Next: dataflow dialect, LCOM4 via `@ivar` grouping |
diff --git a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
index 339393340..069cf1d80 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
@@ -85,6 +85,11 @@ _LANGUAGE_NON_IMPORTABLE: dict[str, frozenset[str]] = {
# Kinds allowed as top-level imports in TS/JS (top-level `export const` literals/objects)
_TS_JS_IMPORTABLE_KINDS: frozenset[str] = frozenset({"constant", "variable"})
+# Every kind a Svelte component prop can take — see _non_importable_kinds.
+_SVELTE_PROP_KINDS: frozenset[str] = frozenset(
+ {"constant", "variable", "function", "class", "interface", "type_alias"}
+)
+
def _non_importable_kinds(language: str) -> frozenset[str]:
"""Per-language set of symbol kinds excluded from unused-export passes.
@@ -93,6 +98,17 @@ def _non_importable_kinds(language: str) -> frozenset[str]:
additions. Cheap to call — short lookup, no per-call allocation
when the language has no additions.
"""
+ # A .svelte component's top-level exports are its props: ``export let x``
+ # is set by the PARENT as a markup attribute (``<Foo x={1} />``), never by
+ # an ``import { x }``. repowise models component instantiation as a call
+ # edge on the component, not as symbol-level edges on each prop, so every
+ # prop would read as an unused export. Suppressing the whole pass for
+ # svelte is the honest ceiling: it costs the genuinely-dead exports of a
+ # ``<script context="module">`` block, which cannot be told apart from
+ # props without modelling attribute-to-prop binding across files.
+ if language == "svelte":
+ return _UNIVERSAL_NON_IMPORTABLE | _SVELTE_PROP_KINDS
+
extra = _LANGUAGE_NON_IMPORTABLE.get(language)
if extra is None:
if language in ("typescript", "javascript"):
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/languages.py b/packages/core/src/repowise/core/analysis/health/complexity/languages.py
index 0318b81ee..2f29ac504 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/languages.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/languages.py
@@ -698,6 +698,9 @@ LANGUAGE_MAPS: dict[str, LanguageNodeMap] = {
"python": _PY,
"typescript": _TS,
"tsx": _TS,
+ # A .svelte component reaches the walker as a TypeScript buffer (see
+ # ingestion/svelte_source.py), so the TS node map applies verbatim.
+ "svelte": _TS,
"javascript": _JS,
"jsx": _JS,
"go": _GO,
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/walker.py b/packages/core/src/repowise/core/analysis/health/complexity/walker.py
index 7a889d6ab..bae09378f 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/walker.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/walker.py
@@ -115,8 +115,13 @@ def walk_file(
return FileComplexity(functions=[], classes=[], file_nloc=_count_file_nloc(source))
try:
+ from repowise.core.ingestion.svelte_source import prepare_source
+
parser = Parser(grammar)
- tree = parser.parse(source)
+ # Svelte components reach the TS grammar as a markup-blanked buffer at
+ # byte-identical offsets, so every offset below (including the NLOC
+ # slices, which read the ORIGINAL bytes) stays valid. No-op elsewhere.
+ tree = parser.parse(prepare_source(language, source))
except Exception as exc:
log.debug("complexity_walker_parse_failed", path=abs_path, error=str(exc))
return FileComplexity(functions=[], classes=[], file_nloc=_count_file_nloc(source))
diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/__init__.py b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/__init__.py
index d7b8db4ef..4357ff262 100644
--- a/packages/core/src/repowise/core/analysis/health/dataflow/dialects/__init__.py
+++ b/packages/core/src/repowise/core/analysis/health/dataflow/dialects/__init__.py
@@ -35,6 +35,8 @@ _REGISTER: tuple[tuple[str, BaseDefUseDialect], ...] = (
("go", _go.DIALECT),
("typescript", _ts_js.DIALECT),
("tsx", _ts_js.DIALECT),
+ # .svelte <script> blocks are TS/JS and reach the pass as a TS buffer.
+ ("svelte", _ts_js.DIALECT),
("javascript", _ts_js.DIALECT),
("jsx", _ts_js.DIALECT),
("java", _java.DIALECT),
diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/parsing.py b/packages/core/src/repowise/core/analysis/health/dataflow/parsing.py
index 5e18f4460..d1e0799f5 100644
--- a/packages/core/src/repowise/core/analysis/health/dataflow/parsing.py
+++ b/packages/core/src/repowise/core/analysis/health/dataflow/parsing.py
@@ -48,8 +48,11 @@ def parse_source(
return None
try:
+ from repowise.core.ingestion.svelte_source import prepare_source
+
parser = Parser(grammar)
- tree = parser.parse(source)
+ # Markup-blanked TS buffer for .svelte, identical offsets. No-op else.
+ tree = parser.parse(prepare_source(language, source))
except Exception as exc:
log.debug("dataflow_parse_failed", path=abs_path, error=str(exc))
return None
diff --git a/packages/core/src/repowise/core/analysis/health/duplication/tokenizer.py b/packages/core/src/repowise/core/analysis/health/duplication/tokenizer.py
index fb7ba70e5..70b3033c4 100644
--- a/packages/core/src/repowise/core/analysis/health/duplication/tokenizer.py
+++ b/packages/core/src/repowise/core/analysis/health/duplication/tokenizer.py
@@ -157,7 +157,11 @@ def tokenize_file(language: str, source: bytes) -> list[Token]:
if grammar is None:
return []
try:
+ from repowise.core.ingestion.svelte_source import prepare_source
+
parser = Parser(grammar)
+ # Markup-blanked TS buffer for .svelte, identical offsets. No-op else.
+ source = prepare_source(language, source)
tree = parser.parse(source)
except Exception:
return []
diff --git a/packages/core/src/repowise/core/analysis/health/perf/dialects/__init__.py b/packages/core/src/repowise/core/analysis/health/perf/dialects/__init__.py
index 3f585b2de..fb9b9c008 100644
--- a/packages/core/src/repowise/core/analysis/health/perf/dialects/__init__.py
+++ b/packages/core/src/repowise/core/analysis/health/perf/dialects/__init__.py
@@ -32,6 +32,8 @@ _REGISTER: tuple[tuple[str, BasePerfDialect], ...] = (
("python", _python.DIALECT),
("typescript", _ts_js.DIALECT),
("tsx", _ts_js.DIALECT),
+ # .svelte <script> blocks are TS/JS and reach the pass as a TS buffer.
+ ("svelte", _ts_js.DIALECT),
("javascript", _ts_js.DIALECT),
("jsx", _ts_js.DIALECT),
("java", _java.DIALECT),
diff --git a/packages/core/src/repowise/core/ingestion/extractors/bindings/__init__.py b/packages/core/src/repowise/core/ingestion/extractors/bindings/__init__.py
index 4ae8842c5..d63fb2765 100644
--- a/packages/core/src/repowise/core/ingestion/extractors/bindings/__init__.py
+++ b/packages/core/src/repowise/core/ingestion/extractors/bindings/__init__.py
@@ -39,6 +39,8 @@ _DISPATCH: dict[str, Callable[[Node, str], tuple[list[str], list[NamedBinding]]]
"python": extract_python_bindings,
"typescript": extract_ts_js_bindings,
"javascript": extract_ts_js_bindings,
+ # A component's <script> imports are ordinary ESM.
+ "svelte": extract_ts_js_bindings,
"go": extract_go_bindings,
"rust": extract_rust_bindings,
"java": extract_java_bindings,
diff --git a/packages/core/src/repowise/core/ingestion/extractors/docstrings.py b/packages/core/src/repowise/core/ingestion/extractors/docstrings.py
index b5e857bd3..e9d0b16c7 100644
--- a/packages/core/src/repowise/core/ingestion/extractors/docstrings.py
+++ b/packages/core/src/repowise/core/ingestion/extractors/docstrings.py
@@ -57,7 +57,7 @@ def extract_module_docstring(root: Node, src: str, lang: str) -> str | None:
"future_import_statement",
):
break
- elif lang in ("typescript", "javascript"):
+ elif lang in ("typescript", "javascript", "svelte"):
# Look for leading /** ... */ comment
for child in root.children:
if child.type == "comment":
@@ -233,7 +233,7 @@ def extract_symbol_docstring(def_node: Node, src: str, lang: str) -> str | None:
return None
return None
- elif lang in ("typescript", "javascript"):
+ elif lang in ("typescript", "javascript", "svelte"):
return find_preceding_jsdoc(def_node, src)
elif lang == "go":
diff --git a/packages/core/src/repowise/core/ingestion/extractors/heritage/__init__.py b/packages/core/src/repowise/core/ingestion/extractors/heritage/__init__.py
index 5d94a6e26..dd62ab8a5 100644
--- a/packages/core/src/repowise/core/ingestion/extractors/heritage/__init__.py
+++ b/packages/core/src/repowise/core/ingestion/extractors/heritage/__init__.py
@@ -46,6 +46,7 @@ HERITAGE_EXTRACTORS: dict[str, Callable[..., None]] = {
"python": _extract_python_heritage,
"typescript": _extract_ts_js_heritage,
"javascript": _extract_ts_js_heritage,
+ "svelte": _extract_ts_js_heritage,
"java": _extract_java_heritage,
"go": _extract_go_heritage,
"rust": _extract_rust_heritage,
diff --git a/packages/core/src/repowise/core/ingestion/extractors/synthetic_symbols/__init__.py b/packages/core/src/repowise/core/ingestion/extractors/synthetic_symbols/__init__.py
index e765cce3b..eff5b7fdf 100644
--- a/packages/core/src/repowise/core/ingestion/extractors/synthetic_symbols/__init__.py
+++ b/packages/core/src/repowise/core/ingestion/extractors/synthetic_symbols/__init__.py
@@ -31,6 +31,7 @@ from .java_records import java_record_synthetic_symbols
from .jvm_codegen import jvm_codegen_synthetic_symbols
from .kotlin_jvm import kotlin_synthetic_symbols
from .lombok import lombok_synthetic_symbols
+from .svelte_component import svelte_component_symbols
if TYPE_CHECKING:
from tree_sitter import Node
@@ -51,6 +52,7 @@ _SYNTHETIC_PROVIDERS: dict[str, list[_Provider]] = {
"kotlin": [kotlin_synthetic_symbols],
"cpp": [cpp_macro_synthetic_symbols],
"c": [cpp_macro_synthetic_symbols],
+ "svelte": [svelte_component_symbols],
}
diff --git a/packages/core/src/repowise/core/ingestion/extractors/synthetic_symbols/svelte_component.py b/packages/core/src/repowise/core/ingestion/extractors/synthetic_symbols/svelte_component.py
new file mode 100644
index 000000000..88974c0d4
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/extractors/synthetic_symbols/svelte_component.py
@@ -0,0 +1,51 @@
+"""The component a ``.svelte`` file declares.
+
+A Svelte component has no declaration in its own source — the file *is* the
+component, and its name comes from the filename. Nothing in the ``<script>``
+block names it, so the ordinary symbol pass finds nothing to hang the
+component off, and ``<Button />`` in a parent's markup has no symbol to
+resolve to.
+
+This provider mints that symbol: one class-kind ``Symbol`` per component,
+named after the file stem, spanning the file. It is the same shape of
+compile-time-only name the Lombok and Java-record providers synthesise, so the
+graph, dead-code, and wiki passes treat it identically.
+"""
+
+from __future__ import annotations
+
+from pathlib import PurePosixPath
+from typing import TYPE_CHECKING
+
+from ...models import FileInfo, Symbol
+from ._helpers import build_synthetic_symbol
+
+if TYPE_CHECKING:
+ from tree_sitter import Node
+
+
+def svelte_component_symbols(root: Node, src: str, file_info: FileInfo) -> list[Symbol]:
+ """Return the single component symbol for a ``.svelte`` file."""
+ name = PurePosixPath(file_info.path).stem
+ if not name:
+ return []
+
+ # SvelteKit route files are named ``+page`` / ``+layout`` / ``+error``.
+ # Strip the sigil so the symbol reads as a name rather than an operator;
+ # the path already disambiguates which route it belongs to.
+ name = name.lstrip("+")
+ if not name or not (name[0].isalpha() or name[0] == "_"):
+ return []
+
+ end_line = root.end_point[0] + 1
+ return [
+ build_synthetic_symbol(
+ name=name,
+ kind="class",
+ signature=f"<{name} />",
+ start_line=1,
+ end_line=end_line,
+ file_info=file_info,
+ parent_name=None,
+ )
+ ]
diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/remix.py b/packages/core/src/repowise/core/ingestion/framework_edges/remix.py
index c5fab327f..4c0b3592c 100644
--- a/packages/core/src/repowise/core/ingestion/framework_edges/remix.py
+++ b/packages/core/src/repowise/core/ingestion/framework_edges/remix.py
@@ -27,9 +27,13 @@ if TYPE_CHECKING:
_REMIX_ROUTE_RE = re.compile(r"(?:^|/)(?:app/)?routes/")
-_SVELTE_ROUTE_RE = re.compile(r"/\+(?:page|layout|server|error)\.(ts|tsx|js|mjs)$")
+_SVELTE_ROUTE_RE = re.compile(r"/\+(?:page|layout|server|error)[.\w]*\.(ts|tsx|js|mjs|svelte)$")
_ASTRO_PAGE_RE = re.compile(r"(?:^|/)src/pages/")
+# SvelteKit's +page.svelte / +layout.svelte are convention routes in their own
+# right, so components count here alongside their .ts/.js siblings.
+_ROUTE_LANGUAGES = ("typescript", "javascript", "svelte")
+
def _is_convention_route(path: str) -> bool:
if _SVELTE_ROUTE_RE.search(path):
@@ -46,7 +50,7 @@ class _ConventionRouteHandler:
if any(tok in dctx.stack_lower for tok in ("remix", "sveltekit", "astro")):
return True
for path, parsed in dctx.parsed_files.items():
- if parsed.file_info.language not in ("typescript", "javascript"):
+ if parsed.file_info.language not in _ROUTE_LANGUAGES:
continue
if _is_convention_route(path):
return True
@@ -61,7 +65,7 @@ class _ConventionRouteHandler:
) -> int:
count = 0
for path, parsed in parsed_files.items():
- if parsed.file_info.language not in ("typescript", "javascript"):
+ if parsed.file_info.language not in _ROUTE_LANGUAGES:
continue
if not _is_convention_route(path):
continue
diff --git a/packages/core/src/repowise/core/ingestion/language_configs.py b/packages/core/src/repowise/core/ingestion/language_configs.py
index 6b8d8c436..a6005e1d6 100644
--- a/packages/core/src/repowise/core/ingestion/language_configs.py
+++ b/packages/core/src/repowise/core/ingestion/language_configs.py
@@ -368,3 +368,8 @@ LANGUAGE_CONFIGS: dict[str, LanguageConfig] = {
parent_class_types=frozenset(),
),
}
+
+# A .svelte component's <script> block IS TypeScript, and svelte_source hands
+# the parser a TS buffer, so the TypeScript config applies verbatim. Aliasing
+# rather than copying keeps the two from drifting apart.
+LANGUAGE_CONFIGS["svelte"] = LANGUAGE_CONFIGS["typescript"]
diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/__init__.py b/packages/core/src/repowise/core/ingestion/languages/specs/__init__.py
index 6ee8335ff..fe62a9cde 100644
--- a/packages/core/src/repowise/core/ingestion/languages/specs/__init__.py
+++ b/packages/core/src/repowise/core/ingestion/languages/specs/__init__.py
@@ -49,6 +49,7 @@ from .rust import SPEC as _RUST
from .scala import SPEC as _SCALA
from .shell import SPEC as _SHELL
from .sql import SPEC as _SQL
+from .svelte import SPEC as _SVELTE
from .swift import SPEC as _SWIFT
from .terraform import SPEC as _TERRAFORM
from .toml import SPEC as _TOML
@@ -66,6 +67,9 @@ ALL_SPECS: tuple[LanguageSpec, ...] = (
_PYTHON,
_TYPESCRIPT,
_JAVASCRIPT,
+ # Must follow _TYPESCRIPT: shares_grammar_with resolves against the
+ # registry built so far, so typescript's grammar has to be loaded first.
+ _SVELTE,
_GO,
_RUST,
_JAVA,
diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/svelte.py b/packages/core/src/repowise/core/ingestion/languages/specs/svelte.py
new file mode 100644
index 000000000..b30d1b6b7
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/languages/specs/svelte.py
@@ -0,0 +1,73 @@
+"""LanguageSpec for svelte.
+
+A ``.svelte`` component is parsed as TypeScript: ``svelte_source`` blanks the
+markup and ``<style>`` so the ``<script>`` blocks and markup expressions sit at
+byte-identical offsets in a valid TS buffer. Hence ``shares_grammar_with`` and
+``scm_file`` both point at typescript — the Svelte grammar itself is loaded
+separately by ``svelte_source`` and only locates regions, it extracts nothing.
+"""
+
+from ..spec import LanguageSpec
+
+SPEC = LanguageSpec(
+ tag="svelte",
+ display_name="Svelte",
+ import_support="full",
+ test_infixes=(".test.", ".spec."),
+ extensions=frozenset({".svelte"}),
+ shares_grammar_with="typescript",
+ scm_file="typescript.scm",
+ heritage_node_types=frozenset(
+ {"class_declaration", "abstract_class_declaration", "interface_declaration"}
+ ),
+ # SvelteKit's filesystem router: these are loaded by convention, never
+ # imported, so they anchor reachability for everything they pull in.
+ entry_point_patterns=("+page.svelte", "+layout.svelte", "+error.svelte", "App.svelte"),
+ manifest_files=("package.json", "svelte.config.js"),
+ lock_files=("package-lock.json", "yarn.lock", "pnpm-lock.yaml"),
+ blocked_dirs=("node_modules", ".svelte-kit", "dist", "build"),
+ # Svelte 5 runes and the template builtins. These are compiler intrinsics,
+ # not user functions — they must never mint a call edge.
+ builtin_calls=frozenset(
+ {
+ "$state",
+ "$derived",
+ "$effect",
+ "$props",
+ "$bindable",
+ "$inspect",
+ "$host",
+ "onMount",
+ "onDestroy",
+ "beforeUpdate",
+ "afterUpdate",
+ "tick",
+ "setContext",
+ "getContext",
+ "hasContext",
+ "createEventDispatcher",
+ "console",
+ "JSON",
+ "Math",
+ "Object",
+ "Array",
+ "String",
+ "Number",
+ "Boolean",
+ "Date",
+ "Promise",
+ "Set",
+ "Map",
+ "Error",
+ "fetch",
+ "setTimeout",
+ "clearTimeout",
+ "setInterval",
+ "clearInterval",
+ "parseInt",
+ "parseFloat",
+ }
+ ),
+ builtin_parents=frozenset({"Error", "Object"}),
+ color_hex="#FF3E00",
+)
diff --git a/packages/core/src/repowise/core/ingestion/models.py b/packages/core/src/repowise/core/ingestion/models.py
index 3a6b6aa94..b70cb85fb 100644
--- a/packages/core/src/repowise/core/ingestion/models.py
+++ b/packages/core/src/repowise/core/ingestion/models.py
@@ -22,6 +22,8 @@ LanguageTag = Literal[
"python",
"typescript",
"javascript",
+ # Single-file components — parsed as TypeScript via svelte_source.
+ "svelte",
"go",
"rust",
"java",
diff --git a/packages/core/src/repowise/core/ingestion/parser.py b/packages/core/src/repowise/core/ingestion/parser.py
index b13e400cb..9df1b9262 100644
--- a/packages/core/src/repowise/core/ingestion/parser.py
+++ b/packages/core/src/repowise/core/ingestion/parser.py
@@ -75,6 +75,7 @@ from .parser_helpers import (
)
from .python_local_refs import extract_python_local_refs
from .special_handlers import SPECIAL_HANDLER_LANGUAGES, parse_special
+from .svelte_source import component_call_sites, prepare_source
log = structlog.get_logger(__name__)
@@ -110,7 +111,12 @@ def _load_compiled_query(lang: str, grammar_tag: str | None = None) -> object |
if language is None:
return None
- scm_path = QUERIES_DIR / f"{lang}.scm"
+ # The spec names the query file, so a language can reuse another's
+ # queries wholesale (svelte -> typescript.scm). Every other spec declares
+ # ``<tag>.scm``, which is what the default preserves.
+ spec = _LANG_REGISTRY.get(lang)
+ scm_name = (spec.scm_file if spec and spec.scm_file else None) or f"{lang}.scm"
+ scm_path = QUERIES_DIR / scm_name
if not scm_path.exists():
log.debug("No .scm query file found", language=lang, path=str(scm_path))
return None
@@ -273,6 +279,15 @@ class ASTParser:
content_hash=content_hash,
)
+ # Svelte components are three languages in one file. ``prepare_source``
+ # blanks the markup and <style> so what reaches the TypeScript grammar
+ # is valid TS at byte-identical offsets — no offset translation is
+ # needed anywhere downstream. A no-op for every other language.
+ # ``content_hash`` above deliberately hashes the ORIGINAL bytes, so
+ # incremental update still tracks the real file.
+ original_source = source
+ source = prepare_source(lang, source)
+
parser = Parser(language)
tree = parser.parse(source)
src = source.decode("utf-8", errors="replace")
@@ -332,6 +347,12 @@ class ASTParser:
symbols.extend(s for s in synthetic if s.id not in existing_ids)
imports = self._extract_imports(matches, config, file_info, src)
calls = self._extract_calls(matches, config, file_info, src, symbols)
+ # Svelte instantiates a component by writing its tag in the markup
+ # (``<Foo />``), which the blanked TS buffer no longer contains. Mint
+ # those call sites from the Svelte grammar directly — the same way
+ # tsx.scm turns ``<Component />`` into a call for React.
+ if lang == "svelte":
+ calls.extend(component_call_sites(original_source, symbols))
heritage = extract_heritage(matches, config, file_info, src)
exports = self._derive_exports(symbols, config, src)
docstring = extract_module_docstring(root, src, lang)
@@ -397,7 +418,7 @@ class ASTParser:
# Deferred-export names (``export { x }`` / ``export default x``),
# computed once per file for the TS/JS visibility refinement.
ts_deferred_exports: frozenset[str] | None = None
- if file_info.language in ("typescript", "javascript"):
+ if file_info.language in ("typescript", "javascript", "svelte"):
ts_deferred_exports = ts_deferred_export_names(src)
for capture_dict in matches:
@@ -528,7 +549,7 @@ class ASTParser:
visibility, is_exported_symbol = refine_cpp_visibility(def_node, visibility, src)
# TS/JS: a top-level declaration is only public when exported —
# inline, via ``export { x }`` lists, or ``export default x``.
- elif file_info.language in ("typescript", "javascript"):
+ elif file_info.language in ("typescript", "javascript", "svelte"):
visibility = refine_ts_visibility(def_node, visibility, name, ts_deferred_exports)
# Parent class detection
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/__init__.py b/packages/core/src/repowise/core/ingestion/resolvers/__init__.py
index 7b49a774b..a7ea9a709 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/__init__.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/__init__.py
@@ -35,6 +35,9 @@ _RESOLVERS: dict[str, ResolverFn] = {
"python": resolve_python_import,
"typescript": resolve_ts_js_import,
"javascript": resolve_ts_js_import,
+ # A component's imports are ordinary ESM — same resolver, plus the
+ # SvelteKit ``$lib`` alias it now understands for .ts/.js files too.
+ "svelte": resolve_ts_js_import,
"go": resolve_go_import,
"rust": resolve_rust_import,
"cpp": resolve_cpp_import,
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/subpath_imports.py b/packages/core/src/repowise/core/ingestion/resolvers/subpath_imports.py
new file mode 100644
index 000000000..83a6e481b
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/resolvers/subpath_imports.py
@@ -0,0 +1,131 @@
+"""Node.js subpath imports (``package.json`` ``"imports"``, the ``#`` prefix).
+
+Node lets a package declare private aliases for its own internals::
+
+ "imports": { "#lib/*": "./src/lib/*", "#config": "./src/config.ts" }
+
+so ``import x from '#lib/components/Modal.svelte'`` resolves inside the same
+package. This is a plain Node/ESM feature — SvelteKit apps reach for it as the
+alternative to ``$lib``, but so do ordinary TS/JS packages. Without it every
+``#``-prefixed specifier becomes an ``external:`` node, which strands whatever
+it points at: on svelte.dev that alone marked eight live components unreachable.
+
+Only ``"imports"`` (``#`` keys, package-private) lives here. ``"exports"``
+(what a package shows the outside world) is already handled by
+``ts_workspace.resolve_via_workspaces``.
+"""
+
+from __future__ import annotations
+
+import json
+import posixpath
+from typing import TYPE_CHECKING
+
+from .ts_workspace import _get_repo_scan, _probe_path
+
+if TYPE_CHECKING:
+ from .context import ResolverContext
+
+_SUBPATH_PREFIX = "#"
+
+# Beyond the TS/JS extensions _probe_path already tries — a subpath alias
+# routinely points straight at a component.
+_EXTRA_EXTENSIONS = (".svelte", ".vue", ".astro")
+
+
+def _flatten(value: object) -> str | None:
+ """Reduce a conditional target ({"import": ..., "default": ...}) to a path."""
+ if isinstance(value, str):
+ return value
+ if isinstance(value, dict):
+ for key in ("import", "module", "default", "require", "node"):
+ if key in value:
+ flattened = _flatten(value[key])
+ if flattened:
+ return flattened
+ for nested in value.values():
+ flattened = _flatten(nested)
+ if flattened:
+ return flattened
+ if isinstance(value, list):
+ for item in value:
+ flattened = _flatten(item)
+ if flattened:
+ return flattened
+ return None
+
+
+def _build_index(ctx: ResolverContext) -> tuple[tuple[str, dict[str, str]], ...]:
+ """(package_dir, {alias_key: target}) for every package declaring imports.
+
+ Sorted deepest-first so a nested package's aliases win over the root's.
+ """
+ cached = getattr(ctx, "_subpath_imports_index", None)
+ if cached is not None:
+ return cached
+
+ entries: list[tuple[str, dict[str, str]]] = []
+ if ctx.repo_path is not None:
+ for pkg_file in _get_repo_scan(ctx).package_jsons:
+ try:
+ data = json.loads(pkg_file.read_text(encoding="utf-8"))
+ except Exception:
+ continue
+ raw = data.get("imports")
+ if not isinstance(raw, dict):
+ continue
+ aliases: dict[str, str] = {}
+ for key, value in raw.items():
+ if not isinstance(key, str) or not key.startswith(_SUBPATH_PREFIX):
+ continue
+ target = _flatten(value)
+ if target:
+ aliases[key] = target.lstrip("./")
+ if not aliases:
+ continue
+ try:
+ pkg_dir = pkg_file.parent.relative_to(ctx.repo_path).as_posix()
+ except ValueError:
+ continue
+ entries.append(("" if pkg_dir == "." else pkg_dir, aliases))
+
+ entries.sort(key=lambda pair: len(pair[0]), reverse=True)
+ result = tuple(entries)
+ ctx._subpath_imports_index = result # type: ignore[attr-defined]
+ return result
+
+
+def _apply(alias_key: str, target: str, module_path: str) -> str | None:
+ """Expand one alias entry against *module_path*, or None if it misses."""
+ if "*" not in alias_key:
+ return target if module_path == alias_key else None
+ prefix, _, suffix = alias_key.partition("*")
+ if not module_path.startswith(prefix) or not module_path.endswith(suffix):
+ return None
+ star = module_path[len(prefix) : len(module_path) - len(suffix) or None]
+ return target.replace("*", star, 1)
+
+
+def resolve_subpath_import(
+ module_path: str, importer_path: str, ctx: ResolverContext
+) -> str | None:
+ """Resolve a ``#alias`` specifier to a repo-relative file, or None."""
+ if not module_path.startswith(_SUBPATH_PREFIX):
+ return None
+
+ for pkg_dir, aliases in _build_index(ctx):
+ if pkg_dir and not importer_path.startswith(pkg_dir + "/"):
+ continue
+ # Longest key first so "#lib/ui/*" beats "#lib/*".
+ for alias_key in sorted(aliases, key=len, reverse=True):
+ expanded = _apply(alias_key, aliases[alias_key], module_path)
+ if expanded is None:
+ continue
+ base = posixpath.join(pkg_dir, expanded) if pkg_dir else expanded
+ hit = _probe_path(base, ctx.path_set)
+ if hit is not None:
+ return hit
+ for ext in _EXTRA_EXTENSIONS:
+ if base + ext in ctx.path_set:
+ return base + ext
+ return None
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/svelte_kit.py b/packages/core/src/repowise/core/ingestion/resolvers/svelte_kit.py
new file mode 100644
index 000000000..1ac51d20e
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/resolvers/svelte_kit.py
@@ -0,0 +1,93 @@
+"""SvelteKit ``$lib`` alias resolution.
+
+SvelteKit projects import shared code as ``$lib/...``. The alias is not
+declared in a tsconfig a repo checks in — it lives in the generated
+``.svelte-kit/tsconfig.json``, which is a build artifact and is almost always
+gitignored. Without this module every ``$lib`` import in a SvelteKit app
+resolves to an ``external:`` node, so the whole ``src/lib`` tree looks
+unreachable.
+
+The alias is a fixed convention: ``$lib`` -> ``<project>/src/lib``, where
+``<project>`` is the directory holding ``svelte.config.js``. A monorepo can
+hold several SvelteKit apps, so projects are matched longest-prefix-first
+against the importing file.
+
+The other ``$`` specifiers (``$app/*``, ``$env/*``, ``$service-worker``) are
+virtual modules the framework synthesises at build time — they have no file in
+the repo, so they correctly stay external and are not handled here.
+
+Ceiling: ``kit.files.lib`` can relocate the directory in ``svelte.config.js``.
+Reading it back would mean evaluating JS, so the convention default is used.
+A project that moves ``lib`` falls back to ``external:`` exactly as today.
+"""
+
+from __future__ import annotations
+
+import posixpath
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from .context import ResolverContext
+
+_CONFIG_NAMES = ("svelte.config.js", "svelte.config.ts", "svelte.config.mjs")
+
+_LIB_ALIAS = "$lib"
+_DEFAULT_LIB_DIR = "src/lib"
+
+
+def _project_lib_dirs(ctx: ResolverContext) -> tuple[tuple[str, str], ...]:
+ """(project_dir, lib_dir) for every SvelteKit project, longest-first."""
+ cached = getattr(ctx, "_svelte_lib_dirs", None)
+ if cached is not None:
+ return cached
+
+ projects: list[tuple[str, str]] = []
+ for path in ctx.sorted_paths:
+ name = path.rsplit("/", 1)[-1]
+ if name not in _CONFIG_NAMES:
+ continue
+ project_dir = path[: -(len(name) + 1)] if "/" in path else ""
+ lib_dir = posixpath.join(project_dir, _DEFAULT_LIB_DIR) if project_dir else _DEFAULT_LIB_DIR
+ projects.append((project_dir, lib_dir))
+
+ # A repo can ship a SvelteKit app with no svelte.config.js at the root of
+ # a plain ``src/lib`` layout; fall back to the repo root so single-app
+ # checkouts still resolve.
+ if not projects and any(p.startswith(_DEFAULT_LIB_DIR + "/") for p in ctx.path_set):
+ projects.append(("", _DEFAULT_LIB_DIR))
+
+ projects.sort(key=lambda pair: len(pair[0]), reverse=True)
+ result = tuple(projects)
+ ctx._svelte_lib_dirs = result # type: ignore[attr-defined]
+ return result
+
+
+def resolve_lib_alias(module_path: str, importer_path: str, ctx: ResolverContext) -> str | None:
+ """Resolve ``$lib/foo/bar`` to a repo-relative file, or None."""
+ if module_path != _LIB_ALIAS and not module_path.startswith(_LIB_ALIAS + "/"):
+ return None
+
+ subpath = module_path[len(_LIB_ALIAS) :].lstrip("/")
+
+ for project_dir, lib_dir in _project_lib_dirs(ctx):
+ if project_dir and not importer_path.startswith(project_dir + "/"):
+ continue
+ base = posixpath.join(lib_dir, subpath) if subpath else lib_dir
+ if base in ctx.path_set:
+ return base
+ for ext in (
+ ".ts",
+ ".tsx",
+ ".js",
+ ".jsx",
+ ".mts",
+ ".mjs",
+ ".svelte",
+ "/index.ts",
+ "/index.js",
+ "/index.svelte",
+ ):
+ candidate = base + ext
+ if candidate in ctx.path_set:
+ return candidate
+ return None
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/typescript.py b/packages/core/src/repowise/core/ingestion/resolvers/typescript.py
index 8e0d0afde..12c283e09 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/typescript.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/typescript.py
@@ -6,6 +6,8 @@ import posixpath
from pathlib import Path
from .context import ResolverContext
+from .subpath_imports import resolve_subpath_import
+from .svelte_kit import resolve_lib_alias
from .ts_workspace import resolve_via_workspaces
@@ -56,6 +58,18 @@ def resolve_ts_js_import(module_path: str, importer_path: str, ctx: ResolverCont
return candidate
return None
+ # Node.js subpath imports (``#lib/...`` via package.json "imports").
+ subpath_resolved = resolve_subpath_import(module_path, importer_path, ctx)
+ if subpath_resolved is not None:
+ return subpath_resolved
+
+ # SvelteKit's $lib alias. Checked before tsconfig because the tsconfig
+ # that declares it (.svelte-kit/tsconfig.json) is generated and gitignored,
+ # so it is virtually never present in an indexed checkout.
+ lib_resolved = resolve_lib_alias(module_path, importer_path, ctx)
+ if lib_resolved is not None:
+ return lib_resolved
+
# Non-relative: try tsconfig path-alias resolution first.
if ctx.tsconfig_resolver is not None:
importer_abs = str(ctx.repo_path / importer_path) if ctx.repo_path else importer_path
diff --git a/packages/core/src/repowise/core/ingestion/svelte_source.py b/packages/core/src/repowise/core/ingestion/svelte_source.py
new file mode 100644
index 000000000..dfdef158c
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/svelte_source.py
@@ -0,0 +1,244 @@
+"""Svelte single-file-component source preparation.
+
+A ``.svelte`` file is three languages in one file: ``<script>`` blocks hold
+TS/JS, the markup is Svelte-flavoured HTML, and ``<style>`` is CSS.
+``tree-sitter-svelte`` parses the markup but hands each ``<script>`` body back
+as a single opaque ``raw_text`` node — a ``.scm`` query run against the Svelte
+grammar captures no symbol, no import and no call.
+
+So the Svelte grammar is used here only to *locate* the JS-bearing regions:
+
+* every ``<script>`` body,
+* every markup ``{expression}`` (``{label(item)}``, ``on:click={inc}``), plus
+ the ``{#if cond}`` and ``{@html expr}`` heads, which are also plain JS.
+
+:func:`prepare_source` then blanks every byte *outside* those regions to a
+space, preserving newlines. The result is valid TypeScript at **byte-identical
+offsets**, so ``typescript.scm``, the TypeScript ``LanguageConfig`` and every
+code-health walker read correct line numbers straight off the original file
+with no offset bookkeeping and no second coordinate space.
+
+Keeping the markup expressions matters for more than call edges: a handler
+like ``function inc() {}`` that is only ever referenced from ``on:click={inc}``
+would otherwise carry no graph edge at all and read as dead code. Svelte's
+whole idiom is markup-driven usage, so dropping the markup would make the
+dead-code pass wrong on nearly every component.
+
+``{#each items as item, i}`` and ``{#await p then v}`` heads are deliberately
+*not* kept: their bodies are Svelte block syntax, not JS expressions, and
+feeding them to the TypeScript grammar would only mint parse errors.
+"""
+
+from __future__ import annotations
+
+from functools import lru_cache
+from typing import TYPE_CHECKING, NamedTuple
+
+import structlog
+
+if TYPE_CHECKING:
+ from tree_sitter import Language, Node
+
+log = structlog.get_logger(__name__)
+
+# ``svelte_raw_text`` parents whose body is a plain JS expression. ``each_start``
+# and ``await_start`` are excluded — see the module docstring.
+_JS_EXPRESSION_PARENTS = frozenset({"expression", "if_start", "key_start", "html_tag"})
+
+# First characters that mark a raw text as Svelte block syntax rather than a JS
+# expression. The grammar normally routes these to their own node types, but a
+# stray ``{/each}`` in a malformed component falls back to ``expression``.
+_BLOCK_SIGILS = ("/", "#", ":", "@")
+
+# An expression whose body opens with ``{`` is an object literal
+# (``use:action={{ a, b }}``). At statement position the TypeScript grammar
+# reads that as a block, so these are dropped rather than mis-parsed —
+# a deliberate ceiling: object literals in attributes carry identifier reads
+# but essentially never call edges. Lifting it would need a real expression
+# context, i.e. wrapping in parens, which no spare byte is available for.
+_OBJECT_LITERAL_PREFIX = "{"
+
+_TAG_PARENTS = frozenset({"start_tag", "self_closing_tag"})
+
+# Svelte's own namespaced elements (<svelte:component>, <svelte:head>, …) are
+# compiler directives, not user components — they must never mint a call edge.
+_SVELTE_NAMESPACE = "svelte:"
+
+_NEWLINE = 0x0A
+_CARRIAGE_RETURN = 0x0D
+_SPACE = 0x20
+_SEMICOLON = 0x3B
+_OPEN_BRACE = 0x7B
+_CLOSE_BRACE = 0x7D
+
+
+class SvelteScan(NamedTuple):
+ """What the Svelte grammar found in one component file."""
+
+ # (start_byte, end_byte) of each JS-bearing region, in source order.
+ js_spans: tuple[tuple[int, int], ...]
+ # Byte offsets that must become ``;``. Every kept markup expression is
+ # fenced on both sides: the trailing ``;`` stops ``{a}{b}`` running
+ # together, and the leading one stops an unterminated final script
+ # statement from swallowing the expression via ASI — ``const o = { x: 1 }``
+ # followed by ``{() => f()}`` otherwise parses as one call expression.
+ terminators: tuple[int, ...]
+ # (component_name, line) for every capitalized markup tag.
+ component_tags: tuple[tuple[str, int], ...]
+ # True when the Svelte grammar itself could not parse the file cleanly.
+ has_error: bool
+
+
+_EMPTY_SCAN = SvelteScan(js_spans=(), terminators=(), component_tags=(), has_error=False)
+
+
+def _svelte_language() -> Language | None:
+ """Load the tree-sitter Svelte grammar, or None when unavailable."""
+ return _cached_svelte_language()
+
+
+@lru_cache(maxsize=1)
+def _cached_svelte_language() -> Language | None:
+ try:
+ import tree_sitter_svelte
+ from tree_sitter import Language
+
+ return Language(tree_sitter_svelte.language())
+ except Exception as exc: # pragma: no cover - depends on install shape
+ log.debug("tree-sitter grammar unavailable", language="svelte", reason=str(exc))
+ return None
+
+
+def _walk(node: Node, scan_state: dict) -> None:
+ """Collect script bodies, JS expressions and component tags in one pass."""
+ node_type = node.type
+
+ if node_type == "script_element":
+ for child in node.children:
+ if child.type == "raw_text":
+ scan_state["spans"].append((child.start_byte, child.end_byte))
+ elif node_type == "svelte_raw_text":
+ parent = node.parent
+ if parent is not None and parent.type in _JS_EXPRESSION_PARENTS:
+ body = (node.text or b"").decode("utf-8", errors="replace").lstrip()
+ if body and not body.startswith((*_BLOCK_SIGILS, _OBJECT_LITERAL_PREFIX)):
+ scan_state["spans"].append((node.start_byte, node.end_byte))
+ # The enclosing node's first and last bytes are its ``{`` and
+ # ``}``. Rewriting both to ``;`` fences the expression into its
+ # own statement without shifting a single offset.
+ if parent.start_byte < node.start_byte:
+ scan_state["terminators"].append(parent.start_byte)
+ if parent.end_byte - 1 >= node.end_byte:
+ scan_state["terminators"].append(parent.end_byte - 1)
+ elif node_type in _TAG_PARENTS:
+ for child in node.children:
+ if child.type != "tag_name":
+ continue
+ name = child.text.decode("utf-8", errors="replace") if child.text else ""
+ if name[:1].isupper() and not name.startswith(_SVELTE_NAMESPACE):
+ scan_state["tags"].append((name, child.start_point[0] + 1))
+
+ for child in node.children:
+ _walk(child, scan_state)
+
+
+def scan(source: bytes) -> SvelteScan:
+ """Locate the JS regions and component tags of a ``.svelte`` source.
+
+ Returns an empty scan when the Svelte grammar is unavailable, which
+ degrades the file to zero symbols rather than to wrong ones.
+ """
+ return _cached_scan(source)
+
+
+# parse_file asks for the prepared source and the component tags back to back,
+# and the health walkers re-prepare the same bytes. A tiny cache keeps that to
+# one tree-sitter parse per file without holding sources alive across a repo.
+@lru_cache(maxsize=4)
+def _cached_scan(source: bytes) -> SvelteScan:
+ language = _svelte_language()
+ if language is None:
+ return _EMPTY_SCAN
+
+ try:
+ from tree_sitter import Parser
+
+ tree = Parser(language).parse(source)
+ except Exception as exc:
+ log.debug("svelte_scan_failed", error=str(exc))
+ return _EMPTY_SCAN
+
+ scan_state: dict = {"spans": [], "terminators": [], "tags": []}
+ _walk(tree.root_node, scan_state)
+ return SvelteScan(
+ js_spans=tuple(sorted(scan_state["spans"])),
+ terminators=tuple(sorted(scan_state["terminators"])),
+ component_tags=tuple(scan_state["tags"]),
+ has_error=tree.root_node.has_error,
+ )
+
+
+def _blank(source: bytes, scan_result: SvelteScan) -> bytes:
+ """Blank every non-JS byte, preserving newlines and byte offsets."""
+ out = bytearray(len(source))
+ for index, byte in enumerate(source):
+ out[index] = byte if byte in (_NEWLINE, _CARRIAGE_RETURN) else _SPACE
+ for start, end in scan_result.js_spans:
+ out[start:end] = source[start:end]
+ for offset in scan_result.terminators:
+ # Only ever rewrite a brace the scan pointed at — never a byte that
+ # turned out to be part of a kept expression.
+ if source[offset] in (_OPEN_BRACE, _CLOSE_BRACE):
+ out[offset] = _SEMICOLON
+ return bytes(out)
+
+
+def component_call_sites(source: bytes, symbols: list) -> list:
+ """Turn every capitalized markup tag into a call site on that component.
+
+ ``<Foo />`` in the markup is how Svelte instantiates ``Foo`` — the exact
+ analogue of a JSX element, which ``tsx.scm`` already captures as a call.
+ The blanked TypeScript buffer has no markup left, so these are minted here
+ from the Svelte grammar instead.
+ """
+ from .models import CallSite
+ from .parser_helpers import _find_enclosing_symbol
+
+ tags = scan(source).component_tags
+ if not tags:
+ return []
+
+ symbol_ranges = sorted(
+ [(s.start_line, s.end_line, s.id) for s in symbols],
+ key=lambda t: (t[0], -t[1]),
+ )
+
+ calls: list = []
+ seen: set[tuple[int, str]] = set()
+ for name, line in tags:
+ if (line, name) in seen:
+ continue
+ seen.add((line, name))
+ calls.append(
+ CallSite(
+ target_name=name,
+ receiver_name=None,
+ caller_symbol_id=_find_enclosing_symbol(line, symbol_ranges),
+ line=line,
+ argument_count=None,
+ )
+ )
+ return calls
+
+
+def prepare_source(language: str, source: bytes) -> bytes:
+ """Return *source* as the bytes the tree-sitter pipeline should parse.
+
+ A no-op for every language but ``svelte``. Call this at each point that
+ hands raw file bytes to a tree-sitter ``Parser`` — the ingestion parser and
+ the three code-health walkers — so all of them see the same TypeScript
+ projection of a component at the same offsets.
+ """
+ if language != "svelte" or not source:
+ return source
+ return _blank(source, scan(source))
diff --git a/packages/core/src/repowise/core/ingestion/tsconfig_resolver.py b/packages/core/src/repowise/core/ingestion/tsconfig_resolver.py
index 5e0b72039..41b84cf5c 100644
--- a/packages/core/src/repowise/core/ingestion/tsconfig_resolver.py
+++ b/packages/core/src/repowise/core/ingestion/tsconfig_resolver.py
@@ -455,7 +455,9 @@ def wire_tsconfig_resolver(
Needs to be called after add_file() but before build().
"""
- _ts_langs = {"typescript", "javascript"}
+ # Svelte counts: a SvelteKit app's aliases live in its tsconfig, and a
+ # .svelte component's imports go through the same TS/JS resolver.
+ _ts_langs = {"typescript", "javascript", "svelte"}
# We duck-type graph_builder to avoid circular imports. It has ._parsed_files.
parsed_files = graph_builder._parsed_files.values()
diff --git a/packages/core/src/repowise/core/pipeline/phases/ingestion.py b/packages/core/src/repowise/core/pipeline/phases/ingestion.py
index a44cdfb73..b4930be73 100644
--- a/packages/core/src/repowise/core/pipeline/phases/ingestion.py
+++ b/packages/core/src/repowise/core/pipeline/phases/ingestion.py
@@ -406,7 +406,7 @@ async def _run_ingestion(
# Only runs when the repo has TS/JS files. On large TS monorepos the
# resolver indexes hundreds of tsconfig files up-front; without a phase
# label this shows up as a silent gap right after parsing.
- _ts_langs = {"typescript", "javascript"}
+ _ts_langs = {"typescript", "javascript", "svelte"}
if any(pf.file_info.language in _ts_langs for pf in parsed_files):
if progress:
progress.on_phase_start("tsconfig", None)
diff --git a/pyproject.toml b/pyproject.toml
index 3edc7d19b..c141a5be0 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -51,6 +51,9 @@ dependencies = [
"tree-sitter-php>=0.23,<1",
"tree-sitter-luau>=1.2,<2",
"tree-sitter-bash>=0.23,<1",
+ # Svelte: locates <script> blocks and markup expressions only; the JS
+ # inside them is parsed with the TypeScript grammar (see svelte_source.py).
+ "tree-sitter-svelte>=1,<2",
# SQL parsing (multi-dialect, error-tolerant, pure Python)
"sqlglot>=26,<28",
# Dependency graph
diff --git a/tests/unit/ingestion/test_language_capabilities.py b/tests/unit/ingestion/test_language_capabilities.py
index 7e183c4a7..4e5b00de3 100644
--- a/tests/unit/ingestion/test_language_capabilities.py
+++ b/tests/unit/ingestion/test_language_capabilities.py
@@ -143,6 +143,9 @@ _FULL = {
"python",
"ruby",
"rust",
+ # svelte components resolve through the TS/JS resolver plus the
+ # SvelteKit $lib alias.
+ "svelte",
"swift",
"typescript",
}
diff --git a/tests/unit/ingestion/test_svelte_extractors.py b/tests/unit/ingestion/test_svelte_extractors.py
new file mode 100644
index 000000000..e6f9774b7
--- /dev/null
+++ b/tests/unit/ingestion/test_svelte_extractors.py
@@ -0,0 +1,292 @@
+"""Svelte end-to-end extraction: symbols, imports, calls, health, dead code."""
+
+from __future__ import annotations
+
+from datetime import datetime
+
+import pytest
+
+from repowise.core.ingestion.models import FileInfo
+from repowise.core.ingestion.parser import ASTParser
+from repowise.core.ingestion.resolvers import ResolverContext, resolve_import
+
+_COMPONENT = b"""<script lang="ts">
+ import Child from './Child.svelte';
+ import { fmt } from '$lib/fmt';
+
+ export let count: number = 0;
+
+ /** Bump the counter. */
+ export function inc() {
+ if (count > 10) {
+ count = 0;
+ } else {
+ count += 1;
+ }
+ }
+</script>
+
+<button on:click={inc}>{fmt(count)}</button>
+<Child {count} />
+<Child count={0} />
+"""
+
+
+def _file(path: str = "src/lib/Counter.svelte") -> FileInfo:
+ return FileInfo(
+ path=path,
+ abs_path=f"/repo/{path}",
+ language="svelte",
+ size_bytes=len(_COMPONENT),
+ git_hash="",
+ last_modified=datetime.now(),
+ is_test=False,
+ is_config=False,
+ is_api_contract=False,
+ is_entry_point=False,
+ )
+
+
[email protected](scope="module")
+def parser() -> ASTParser:
+ return ASTParser()
+
+
[email protected](scope="module")
+def parsed(parser: ASTParser):
+ return parser.parse_file(_file(), _COMPONENT)
+
+
+class TestSymbols:
+ def test_the_file_itself_becomes_a_component_symbol(self, parsed) -> None:
+ # Nothing in a .svelte source names the component — the filename does.
+ component = [s for s in parsed.symbols if s.name == "Counter"]
+ assert len(component) == 1
+ assert component[0].kind == "class"
+ assert component[0].start_line == 1
+
+ def test_script_functions_are_extracted(self, parsed) -> None:
+ assert "inc" in {s.name for s in parsed.symbols}
+
+ def test_symbol_lines_point_at_the_original_file(self, parsed) -> None:
+ inc = next(s for s in parsed.symbols if s.name == "inc")
+ # `export function inc()` is on line 8 of the component source.
+ assert inc.start_line == 8
+
+ def test_route_sigil_is_stripped_from_the_component_name(self, parser) -> None:
+ result = parser.parse_file(_file("src/routes/+page.svelte"), _COMPONENT)
+ assert "page" in {s.name for s in result.symbols}
+
+ def test_no_parse_errors_on_a_well_formed_component(self, parsed) -> None:
+ assert parsed.parse_errors == []
+
+
+class TestImports:
+ def test_relative_component_import(self, parsed) -> None:
+ child = next(i for i in parsed.imports if i.module_path.endswith("Child.svelte"))
+ assert child.is_relative
+ assert child.imported_names == ["Child"]
+
+ def test_named_bindings_are_extracted(self, parsed) -> None:
+ fmt = next(i for i in parsed.imports if i.module_path == "$lib/fmt")
+ assert fmt.imported_names == ["fmt"]
+ assert [b.local_name for b in fmt.bindings] == ["fmt"]
+
+
+class TestCalls:
+ def test_script_calls_are_extracted(self, parsed) -> None:
+ assert "fmt" in {c.target_name for c in parsed.calls}
+
+ def test_markup_component_tags_become_calls(self, parsed) -> None:
+ # <Child /> is how Svelte instantiates Child — the JSX analogue.
+ child_calls = [c for c in parsed.calls if c.target_name == "Child"]
+ assert len(child_calls) == 2
+ assert {c.line for c in child_calls} == {18, 19}
+
+ def test_calls_are_attributed_to_the_component(self, parsed) -> None:
+ child = next(c for c in parsed.calls if c.target_name == "Child")
+ assert child.caller_symbol_id is not None
+ assert child.caller_symbol_id.endswith("::Counter")
+
+ def test_runes_are_not_call_targets(self, parser) -> None:
+ src = b"<script>\n let n = $state(0);\n let d = $derived(n * 2);\n</script>\n"
+ result = parser.parse_file(_file(), src)
+ targets = {c.target_name for c in result.calls}
+ assert "$state" not in targets
+ assert "$derived" not in targets
+
+
+class TestSvelteKitLibAlias:
+ """$lib is declared only in the generated .svelte-kit tsconfig, which is
+ gitignored — without explicit handling every $lib import goes external."""
+
+ def _ctx(self, paths: set[str]) -> ResolverContext:
+ import networkx as nx
+
+ return ResolverContext(path_set=paths, stem_map={}, graph=nx.DiGraph())
+
+ def test_lib_alias_resolves_to_src_lib(self) -> None:
+ ctx = self._ctx({"svelte.config.js", "src/lib/fmt.ts", "src/routes/+page.svelte"})
+ assert (
+ resolve_import("$lib/fmt", "src/routes/+page.svelte", "svelte", ctx) == "src/lib/fmt.ts"
+ )
+
+ def test_lib_alias_resolves_a_component(self) -> None:
+ ctx = self._ctx({"svelte.config.js", "src/lib/Button.svelte", "src/routes/+page.svelte"})
+ assert (
+ resolve_import("$lib/Button.svelte", "src/routes/+page.svelte", "svelte", ctx)
+ == "src/lib/Button.svelte"
+ )
+
+ def test_lib_alias_resolves_an_index_barrel(self) -> None:
+ ctx = self._ctx({"svelte.config.js", "src/lib/ui/index.ts", "src/routes/+page.svelte"})
+ assert (
+ resolve_import("$lib/ui", "src/routes/+page.svelte", "svelte", ctx)
+ == "src/lib/ui/index.ts"
+ )
+
+ def test_monorepo_picks_the_nearest_project(self) -> None:
+ ctx = self._ctx(
+ {
+ "apps/web/svelte.config.js",
+ "apps/web/src/lib/fmt.ts",
+ "apps/docs/svelte.config.js",
+ "apps/docs/src/lib/fmt.ts",
+ "apps/docs/src/routes/+page.svelte",
+ }
+ )
+ assert (
+ resolve_import("$lib/fmt", "apps/docs/src/routes/+page.svelte", "svelte", ctx)
+ == "apps/docs/src/lib/fmt.ts"
+ )
+
+ def test_app_virtual_modules_stay_external(self) -> None:
+ # $app/* is synthesised by the framework — it has no file in the repo.
+ ctx = self._ctx({"svelte.config.js", "src/routes/+page.svelte"})
+ resolved = resolve_import("$app/navigation", "src/routes/+page.svelte", "svelte", ctx)
+ assert resolved == "external:$app/navigation"
+
+
+class TestNodeSubpathImports:
+ """package.json "imports" (#lib/*) — the other alias style SvelteKit apps
+ use. svelte.dev uses it, and without it eight live components read as
+ unreachable."""
+
+ def _ctx(self, tmp_path, pkg: dict, paths: set[str]):
+ import json
+
+ import networkx as nx
+
+ from repowise.core.ingestion.resolvers import ResolverContext
+
+ (tmp_path / "package.json").write_text(json.dumps(pkg), encoding="utf-8")
+ for rel in paths:
+ target = tmp_path / rel
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_text("", encoding="utf-8")
+ return ResolverContext(
+ path_set=set(paths) | {"package.json"},
+ stem_map={},
+ graph=nx.DiGraph(),
+ repo_path=tmp_path,
+ )
+
+ def test_wildcard_alias_resolves_a_component(self, tmp_path) -> None:
+ ctx = self._ctx(
+ tmp_path,
+ {"imports": {"#lib/*": "./src/lib/*"}},
+ {"src/lib/components/Modal.svelte", "src/routes/Page.svelte"},
+ )
+ assert (
+ resolve_import(
+ "#lib/components/Modal.svelte", "src/routes/Page.svelte", "svelte", ctx
+ )
+ == "src/lib/components/Modal.svelte"
+ )
+
+ def test_wildcard_alias_probes_extensions(self, tmp_path) -> None:
+ ctx = self._ctx(
+ tmp_path,
+ {"imports": {"#lib/*": "./src/lib/*"}},
+ {"src/lib/utils.ts", "src/routes/Page.svelte"},
+ )
+ assert (
+ resolve_import("#lib/utils", "src/routes/Page.svelte", "svelte", ctx)
+ == "src/lib/utils.ts"
+ )
+
+ def test_exact_alias_key(self, tmp_path) -> None:
+ ctx = self._ctx(
+ tmp_path,
+ {"imports": {"#config": "./src/config.ts"}},
+ {"src/config.ts", "src/routes/Page.svelte"},
+ )
+ assert (
+ resolve_import("#config", "src/routes/Page.svelte", "svelte", ctx) == "src/config.ts"
+ )
+
+ def test_conditional_target_is_flattened(self, tmp_path) -> None:
+ ctx = self._ctx(
+ tmp_path,
+ {"imports": {"#lib/*": {"import": "./src/lib/*", "default": "./dist/*"}}},
+ {"src/lib/api.ts", "src/routes/Page.svelte"},
+ )
+ assert (
+ resolve_import("#lib/api", "src/routes/Page.svelte", "svelte", ctx) == "src/lib/api.ts"
+ )
+
+ def test_unmatched_alias_falls_through_to_external(self, tmp_path) -> None:
+ ctx = self._ctx(
+ tmp_path,
+ {"imports": {"#lib/*": "./src/lib/*"}},
+ {"src/routes/Page.svelte"},
+ )
+ assert (
+ resolve_import("#nope/x", "src/routes/Page.svelte", "svelte", ctx)
+ == "external:#nope/x"
+ )
+
+ def test_typescript_gets_the_same_treatment(self, tmp_path) -> None:
+ # The "imports" field is plain Node — not Svelte-specific.
+ ctx = self._ctx(
+ tmp_path,
+ {"imports": {"#lib/*": "./src/lib/*"}},
+ {"src/lib/db.ts", "src/server.ts"},
+ )
+ assert resolve_import("#lib/db", "src/server.ts", "typescript", ctx) == "src/lib/db.ts"
+
+
+class TestCodeHealth:
+ def test_complexity_is_measured_on_the_script_block(self) -> None:
+ from repowise.core.analysis.health.complexity.walker import walk_file
+
+ result = walk_file("/repo/src/lib/Counter.svelte", "svelte", _COMPONENT)
+ inc = next(f for f in result.functions if f.name == "inc")
+ # one if/else branch on top of the base path
+ assert inc.ccn == 2
+ assert inc.start_line == 8
+
+ def test_perf_dialect_is_registered(self) -> None:
+ from repowise.core.analysis.health.perf.dialects import PERF_DIALECTS
+
+ assert "svelte" in PERF_DIALECTS
+
+ def test_dataflow_dialect_is_registered(self) -> None:
+ from repowise.core.analysis.health.dataflow.dialects import DEFUSE_DIALECTS
+
+ assert "svelte" in DEFUSE_DIALECTS
+
+
+class TestDeadCode:
+ def test_component_props_are_never_flagged_as_unused_exports(self) -> None:
+ # `export let count` is set by the parent as a markup attribute, never
+ # imported by name, so flagging it would be a guaranteed false positive.
+ from repowise.core.analysis.dead_code.analyzer import _non_importable_kinds
+
+ skipped = _non_importable_kinds("svelte")
+ assert {"constant", "variable", "function", "class"} <= skipped
+
+ def test_typescript_is_unaffected(self) -> None:
+ from repowise.core.analysis.dead_code.analyzer import _non_importable_kinds
+
+ assert "function" not in _non_importable_kinds("typescript")
diff --git a/tests/unit/ingestion/test_svelte_source.py b/tests/unit/ingestion/test_svelte_source.py
new file mode 100644
index 000000000..b03b19e7a
--- /dev/null
+++ b/tests/unit/ingestion/test_svelte_source.py
@@ -0,0 +1,152 @@
+"""Unit tests for the Svelte single-file-component source projection.
+
+``svelte_source`` is the seam every Svelte capability rests on: it blanks the
+markup and ``<style>`` so the TypeScript grammar sees valid TS at
+byte-identical offsets. The offset invariant is what lets the ingestion parser
+and all three code-health walkers share one projection, so it is pinned here
+directly rather than only through its consumers.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.core.ingestion.svelte_source import prepare_source, scan
+
+_COMPONENT = b"""<script lang="ts">
+ import Child from './Child.svelte';
+ import { fmt } from '$lib/fmt';
+
+ export let count: number = 0;
+
+ function inc() {
+ count += 1;
+ }
+</script>
+
+<button on:click={inc}>{fmt(count)}</button>
+<Child {count} />
+
+<style>
+ button { color: red; }
+</style>
+"""
+
+
+class TestOffsetInvariants:
+ """Byte length and line numbering must survive the projection untouched."""
+
+ def test_length_is_preserved(self) -> None:
+ assert len(prepare_source("svelte", _COMPONENT)) == len(_COMPONENT)
+
+ def test_line_count_is_preserved(self) -> None:
+ prepared = prepare_source("svelte", _COMPONENT)
+ assert prepared.count(b"\n") == _COMPONENT.count(b"\n")
+
+ def test_script_lines_are_byte_identical(self) -> None:
+ prepared = prepare_source("svelte", _COMPONENT).splitlines()
+ original = _COMPONENT.splitlines()
+ # The import / export / function lines live inside <script>.
+ for index in (1, 2, 4, 6):
+ assert prepared[index] == original[index]
+
+ def test_non_ascii_markup_keeps_offsets(self) -> None:
+ src = "<script>let a = 1;</script>\n<p>héllo wörld ✨</p>\n".encode()
+ prepared = prepare_source("svelte", src)
+ assert len(prepared) == len(src)
+ assert prepared.count(b"\n") == src.count(b"\n")
+
+ def test_other_languages_pass_through_unchanged(self) -> None:
+ src = b"const a = 1;\n"
+ assert prepare_source("typescript", src) is src
+ assert prepare_source("python", src) is src
+
+
+class TestBlanking:
+ def test_style_block_is_removed(self) -> None:
+ prepared = prepare_source("svelte", _COMPONENT)
+ assert b"color: red" not in prepared
+
+ def test_markup_tags_are_removed(self) -> None:
+ # The closing </script> is itself markup, so slice by line instead.
+ tail = b"\n".join(prepare_source("svelte", _COMPONENT).splitlines()[10:])
+ assert b"button" not in tail
+ assert b"Child" not in tail
+
+ def test_markup_expressions_are_kept(self) -> None:
+ # Without these, a handler referenced only from the template
+ # (on:click={inc}) would carry no edge and read as dead code.
+ tail = b"\n".join(prepare_source("svelte", _COMPONENT).splitlines()[10:])
+ assert b"inc" in tail
+ assert b"fmt(count)" in tail
+
+
+class TestExpressionFencing:
+ """Kept expressions must not run together into one invalid statement."""
+
+ def test_adjacent_expressions_are_separated(self) -> None:
+ src = b"<script>let a=1,b=2;</script>\n<p>{a}{b}</p>\n"
+ prepared = prepare_source("svelte", src)
+ assert b";a;;b;" in prepared.replace(b" ", b"")
+
+ def test_unterminated_script_statement_does_not_swallow_markup(self) -> None:
+ # `const o = { x: 1 }` with no semicolon followed by `{() => f()}`
+ # parses as one call expression unless the expression is fenced.
+ src = b"<script>const o = { x: 1 }</script>\n<b on:click={() => f()}>x</b>\n"
+ prepared = prepare_source("svelte", src)
+ line = prepared.splitlines()[1]
+ assert line.strip().startswith(b";")
+ assert line.rstrip().endswith(b";")
+
+ def test_each_block_head_is_not_kept(self) -> None:
+ # `item, i (item.id)` is Svelte block syntax, not a JS expression.
+ src = b"<script>let items=[];</script>\n{#each items as item, i (item.id)}<p/>{/each}\n"
+ prepared = prepare_source("svelte", src)
+ assert b"item, i" not in prepared
+
+ def test_if_block_head_is_kept(self) -> None:
+ src = b"<script>let n=0;</script>\n{#if n > 0}<p/>{/if}\n"
+ prepared = prepare_source("svelte", src)
+ assert b"n > 0" in prepared
+
+ def test_object_literal_attribute_is_dropped(self) -> None:
+ # A `{ ... }` body reads as a block at statement position; dropping it
+ # is the documented ceiling.
+ src = b"<script>let p=1;</script>\n<b use:act={{ a: p }}>x</b>\n"
+ prepared = prepare_source("svelte", src)
+ assert b"a: p" not in prepared
+
+
+class TestComponentTags:
+ def test_capitalized_tags_are_component_usages(self) -> None:
+ names = {name for name, _ in scan(_COMPONENT).component_tags}
+ assert names == {"Child"}
+
+ def test_lowercase_html_elements_are_not_components(self) -> None:
+ src = b"<div><span>hi</span></div>\n"
+ assert scan(src).component_tags == ()
+
+ def test_svelte_namespace_directives_are_not_components(self) -> None:
+ # <svelte:window> etc. are compiler directives, not user components.
+ src = b"<svelte:window onkeydown={h} />\n<svelte:head><title>x</title></svelte:head>\n"
+ names = {name for name, _ in scan(src).component_tags}
+ assert names == set()
+
+ def test_tag_line_numbers_point_at_the_original_file(self) -> None:
+ tags = dict(scan(_COMPONENT).component_tags)
+ assert tags["Child"] == 13
+
+
+class TestDegradation:
+ @pytest.mark.parametrize(
+ "src",
+ [
+ b"",
+ b"<p>markup only, no script</p>\n",
+ b"<script>",
+ b"<div><span></div>\n",
+ ],
+ )
+ def test_malformed_or_scriptless_input_never_raises(self, src: bytes) -> None:
+ prepared = prepare_source("svelte", src)
+ assert len(prepared) == len(src)