Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(ingestion): Vue support via a shared single-file-component projection (#1232)
Raghav Chamadiyaeaa165c770d8
diff --git a/README.md b/README.mdindex eb19b0c99..ddedf3dbe 100644--- a/README.md+++ b/README.md@@ -339,7 +339,7 @@ Set Up This Repository**. Guide: **[docs/agent/VSCODE.md →](docs/agent/VSCODE.## Supported languages-**17 languages parsed to AST · 12 at the Full tier · framework-aware across all of them.**+**18 languages parsed to AST · 13 at the Full tier · framework-aware across all of them.**<p><strong>Full tier </strong>@@ -347,6 +347,7 @@ Set Up This Repository**. Guide: **[docs/agent/VSCODE.md →](docs/agent/VSCODE.<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/Vue-42B883?style=flat-square&logo=vuedotjs&logoColor=white" alt="Vue" /><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.mdindex fbb7aed94..4271160cb 100644--- a/docs/architecture/language-support.md+++ b/docs/architecture/language-support.md@@ -23,7 +23,7 @@ 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+ +-- Multi-language file? -> sfc_source.py projects it to one| grammar's language at identical offsets+-- Has grammar? -> tree-sitter AST parsing|@@ -116,7 +116,7 @@ ingestion/registry.py # HintRegistrydjango.py pytest_hints.py python_imports.py node.py dotnet.pyspring.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)+ sfc_source.py # Multi-language-file (SFC) projection (see below)parser.py # ASTParser (language-agnostic orchestration)graph.py # GraphBuilder (import/call/heritage resolution)@@ -277,23 +277,24 @@ language sets from the registry automatically.----## Multi-language files (the Svelte pattern)+## Multi-language files (the SFC 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+Some file types hold more than one language. A `.svelte` or `.vue` component is+TS/JS in its `<script>` blocks, framework-flavoured HTML in its markup, and CSS+in `<style>`. The markup grammars parse the file but return each `<script>`+body as one opaque `raw_text` node, so a `.scm` query against them captures nosymbol, import, or call — a grammar alone cannot support such a language.-`ingestion/svelte_source.py` solves this with a **byte-preserving projection**+`ingestion/sfc_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;+1. a markup grammar *locates* the JS-bearing regions — every `<script>` body+ and every markup expression;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.+3. each kept markup expression is fenced by rewriting its two surrounding+ delimiter bytes to `;`, so adjacent expressions 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 matchesthe original file. That single property is what makes the rest free: the spec@@ -302,16 +303,42 @@ declares `shares_grammar_with="typescript"` and `scm_file="typescript.scm"`, theregistries alias the TS entries. Each consumer that hands raw bytes to atree-sitter `Parser` calls `prepare_source(language, source)` first — theingestion parser plus the complexity, dataflow, and duplication walkers. It is-a no-op for every other language.+a no-op for every language without a registered locator.++### The locator registry++Only step 1 differs per language, so it lives behind `_LOCATORS`, a dict of+`Locator(grammar_module, visit, component_name)`. The blanking, fencing,+caching and offset invariants are shared; adding a markup language means adding+a `Locator`, not a second copy of the walker.++| | Svelte | Vue |+|---|---|---|+| Grammar | `tree-sitter-svelte` | `tree-sitter-html` |+| Expression nodes | `svelte_raw_text` under `expression` / `if_start` / `key_start` / `html_tag` | `attribute_value` inside `quoted_attribute_value`; `{{ … }}` scanned inside `text` |+| Fence bytes | the surrounding `{` `}` | the surrounding `"` or `'` |+| Skipped binding forms | `{#each}`, `{#await}` heads | `v-for`, `v-slot` / `#default` |+| Non-component tags | the `svelte:*` namespace | `<KeepAlive>`, `<Transition>`, `<RouterView>`, … in either spelling |++There is no `tree-sitter-vue` on PyPI. The HTML grammar parses a Vue SFC+cleanly anyway, because `<template>`, `<script>` and `<style>` are ordinary+elements to it — so one dependency covers Vue and, later, plain HTML.++Vue's expressions live in attribute *values*, which is why the fence bytes are+quotes rather than braces, and why only directive attributes (`:`, `@`, `v-`)+are projected: `class="btn primary"` is a literal string, and projecting it+would put two juxtaposed identifiers at statement position.Two things markup carries that the projection cannot express are mintedseparately: 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.+`extractors/synthetic_symbols/sfc_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). For Vue both+run the filename and the tag through the *same* normaliser, so+`back-to-top.vue` and `<back-to-top />` cannot disagree about the name+`BackToTop`.++The same steps would fit Astro components; only the locator changes.---diff --git a/docs/business/COMMERCIAL.md b/docs/business/COMMERCIAL.mdindex 8417652ef..4b53cba72 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 17 languages, two-tier+- **Five intelligence layers** — Graph (tree-sitter AST across 18 languages, two-tierdependency graph, call resolution, heritage extraction, Leiden communities,PageRank / betweenness / SCC), Git (hotspots, ownership, co-change pairs, busfactor, significant commits, contributor profiles, module health), Documentationdiff --git a/docs/layers/INTELLIGENCE_LAYERS.md b/docs/layers/INTELLIGENCE_LAYERS.mdindex 60c0e66a4..2d226afe4 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 17 languages into a **two-tier dependency+tree-sitter parses every file across 18 languages into a **two-tier dependencygraph**: file nodes and symbol nodes (functions, classes, methods). A 3-tiercall resolver with confidence scoring handles import aliases, barrelre-exports, and namespace imports. Heritage extraction covers `extends`,diff --git a/docs/layers/LANGUAGE_SUPPORT.md b/docs/layers/LANGUAGE_SUPPORT.mdindex f455d37b8..253f9da3b 100644--- a/docs/layers/LANGUAGE_SUPPORT.md+++ b/docs/layers/LANGUAGE_SUPPORT.md@@ -1,7 +1,7 @@# Language Support-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.+repowise parses **18 languages to a full AST**, resolves imports and call+graphs across them, and scores **13 at the Full tier** with code-health markers.Everything else in your repo is still tracked through git history and appears inthe 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 · 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** |+| **Full** | Python · TypeScript · JavaScript · Svelte · Vue · 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 |@@ -62,6 +62,7 @@ extractors, and code-health markers.| **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) |+| **Vue** | `.vue` | Same resolver as TS/JS, including `jsconfig`/`tsconfig` path aliases (`@/* → src/*`), directory-index components (`./Foo` → `Foo/index.vue`), and router `import()` specifiers || **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 |@@ -75,28 +76,56 @@ 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:+**Single-file components** (`.svelte`, `.vue`) are three languages in one file,+so they get a shared projection rather than a grammar of their own. A markup+grammar 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 source file. Only the region-location+step differs per language, behind a small locator registry in `sfc_source.py`.++Vue has no grammar on PyPI, but `tree-sitter-html` parses an SFC cleanly —+`<template>`, `<script>` and `<style>` are just elements to it — so one+dependency covers both Vue and plain HTML.++| | Svelte | Vue |+|---|---|---|+| Script blocks | `<script>`, `<script context="module">` | `<script>`, `<script setup>` |+| Markup expressions | `{expr}`, `on:click={inc}`, `{#if}` heads | `:class="c"`, `@click="inc"`, `v-if="ok"`, `{{ interp }}` |+| Expression fence | the surrounding `{` `}` | the surrounding attribute quotes |+| Skipped binding forms | `{#each x as y}`, `{#await}` | `v-for="x in xs"`, `v-slot` / `#default` |++Three pieces sit on top for both:- the **component itself** becomes a class-kind symbol named after the file- (`Button.svelte` → `Button`), since nothing in the source names it;+ (`Button.svelte` → `Button`), since nothing in the source names it. Vue+ normalises the stem the same way it normalises a tag, so `warningBar.vue`,+ `back-to-top.vue` and `Logo/index.vue` declare `WarningBar`, `BackToTop` and+ `Logo` — which is what a parent actually imports and writes;- **`<Foo />` in markup** mints a call edge on `Foo`, the same way `tsx.scm`- treats a JSX element;+ treats a JSX element. Framework intrinsics never do: Svelte's `svelte:*`+ namespace, and Vue's `<KeepAlive>` / `<Transition>` / `<RouterView>` in+ either the PascalCase or kebab spelling;- **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.+ `on:click={inc}` or `@click="inc"` still carries an edge instead of reading+ as dead code.++Deliberate ceilings. Binding forms (the table above) *parse* as JS but mean+something else, so they are skipped — a parse that succeeds with the wrong+meaning is worse than a skip. Object-literal attributes (`use:action={{ a, b }}`,+`#default="{ row }"`) read as a block at statement position and are dropped. A+component's props are set by the parent as markup attributes and never imported+by name, so the unused-export pass is suppressed for both languages — the+alternative flags every prop, and every component, in the repo.++One ceiling is Vue-specific: an Options-API member spelled+`foo: function () {}` or `foo: () => {}` is not captured, because+`typescript.scm` has no pattern for a `pair` with a function value. The+shorthand `foo() {}` spelling **is** captured, which covers 1,588 of 1,592+member functions (99.7%) across the 275 Options-API files in the validation+corpus. The remaining 0.3% is a general TS/JS object-literal gap, not a Vue+one, so lifting it belongs in `typescript.scm`.**Framework-aware edges** connect routes to handlers, DI registrations toimplementations, and ORM entities to relationships:@@ -209,6 +238,7 @@ is "Full" vs "Good".| Python | ✅ | ✅ | ✅ | ✅ | ✅ || TypeScript / JavaScript | ✅ | ✅ | ✅ | ✅ | ✅ || Svelte | ✅¹⁰ | ✅ | ✅ | ✅ | ✅ |+| Vue | ✅¹⁰ | ✅ | ✅ | ✅ | ✅ || Java | ✅ | ✅ | ✅ | ✅ | ✅ || Go | ✅ | n/a¹ | ✅ | ✅ | ✅ || Rust | ✅ | ✅ | ✅ | ✅ | ✅² |@@ -257,7 +287,7 @@ 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+¹⁰ Svelte and Vue ride the TypeScript dialect on all three health layers, because acomponent reaches them as a TypeScript buffer. Markers therefore cover the`<script>` blocks and markup expressions — the parts that *are* JS. Markupstructure and `<style>` carry no health signal, so a component's markers@@ -332,6 +362,7 @@ where a dialect isn't wired yet. Per-marker mechanics and precision hazards:| Language | Target tier | Status ||----------|------------|--------|+| Vue | Full | Shipped: TS projection of `<script>` / `<script setup>` + template expressions, component symbols with tag-consistent naming, `<Foo />` call edges, alias + directory-index + dynamic-`import()` resolution, all three health dialects. Next: Options-API `pair`-function members, `v-for` head bindings || 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 |diff --git a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py b/packages/core/src/repowise/core/analysis/dead_code/analyzer.pyindex a7128fc4d..7f70b6f29 100644--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py@@ -89,8 +89,13 @@ _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(+# Single-file-component languages: the whole file is one component, so their+# exports behave unlike an ordinary module's — see _non_importable_kinds.+_SFC_LANGUAGES: frozenset[str] = frozenset({"svelte", "vue"})++# Every kind an SFC component prop can take, plus "class" for the synthetic+# component symbol itself — see _non_importable_kinds.+_SFC_NON_IMPORTABLE_KINDS: frozenset[str] = frozenset({"constant", "variable", "function", "class", "interface", "type_alias"})@@ -102,16 +107,25 @@ def _non_importable_kinds(language: str) -> frozenset[str]:additions. Cheap to call — short lookup, no per-call allocationwhen 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+ # An SFC's top-level exports are its props: Svelte's ``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.+ #+ # The component symbol itself needs the same treatment, which is why+ # "class" is in the set. A component is reached as a whole module — by a+ # markup tag, or by a router's ``import('@/views/profile')``, which binds+ # no name at all — so it never carries the symbol-level inbound edge the+ # unused-export pass looks for. On vue-element-admin that alone accounted+ # for 45 of 53 findings, every one of them a false positive.+ #+ # Suppressing the whole pass is the honest ceiling: it costs the+ # genuinely-dead named exports of a Svelte ``<script context="module">``+ # or a Vue non-setup ``<script>``, which cannot be told apart from props+ # without modelling attribute-to-prop binding across files.+ if language in _SFC_LANGUAGES:+ return _UNIVERSAL_NON_IMPORTABLE | _SFC_NON_IMPORTABLE_KINDSextra = _LANGUAGE_NON_IMPORTABLE.get(language)if extra is None:diff --git a/packages/core/src/repowise/core/analysis/health/complexity/languages.py b/packages/core/src/repowise/core/analysis/health/complexity/languages.pyindex 372a1829f..deefc1c0c 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/languages.py+++ b/packages/core/src/repowise/core/analysis/health/complexity/languages.py@@ -723,9 +723,10 @@ 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.+ # An SFC reaches the walker as a TypeScript buffer (see+ # ingestion/sfc_source.py), so the TS node map applies verbatim."svelte": _TS,+ "vue": _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.pyindex bae09378f..d3a97f132 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/walker.py+++ b/packages/core/src/repowise/core/analysis/health/complexity/walker.py@@ -115,10 +115,10 @@ def walk_file(return FileComplexity(functions=[], classes=[], file_nloc=_count_file_nloc(source))try:- from repowise.core.ingestion.svelte_source import prepare_source+ from repowise.core.ingestion.sfc_source import prepare_sourceparser = Parser(grammar)- # Svelte components reach the TS grammar as a markup-blanked buffer at+ # SFCs 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))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__.pyindex 19bff70d0..fa0754467 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@@ -36,8 +36,9 @@ _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.+ # SFC <script> blocks are TS/JS and reach the pass as a TS buffer.("svelte", _ts_js.DIALECT),+ ("vue", _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.pyindex d1e0799f5..ce9afe0fb 100644--- a/packages/core/src/repowise/core/analysis/health/dataflow/parsing.py+++ b/packages/core/src/repowise/core/analysis/health/dataflow/parsing.py@@ -48,10 +48,10 @@ def parse_source(return Nonetry:- from repowise.core.ingestion.svelte_source import prepare_source+ from repowise.core.ingestion.sfc_source import prepare_sourceparser = Parser(grammar)- # Markup-blanked TS buffer for .svelte, identical offsets. No-op else.+ # Markup-blanked TS buffer for SFCs, 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))diff --git a/packages/core/src/repowise/core/analysis/health/duplication/tokenizer.py b/packages/core/src/repowise/core/analysis/health/duplication/tokenizer.pyindex 70b3033c4..c855b8b8b 100644--- a/packages/core/src/repowise/core/analysis/health/duplication/tokenizer.py+++ b/packages/core/src/repowise/core/analysis/health/duplication/tokenizer.py@@ -157,10 +157,10 @@ def tokenize_file(language: str, source: bytes) -> list[Token]:if grammar is None:return []try:- from repowise.core.ingestion.svelte_source import prepare_source+ from repowise.core.ingestion.sfc_source import prepare_sourceparser = Parser(grammar)- # Markup-blanked TS buffer for .svelte, identical offsets. No-op else.+ # Markup-blanked TS buffer for SFCs, identical offsets. No-op else.source = prepare_source(language, source)tree = parser.parse(source)except Exception: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__.pyindex f7af63f95..1a77f6428 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@@ -34,8 +34,9 @@ _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.+ # SFC <script> blocks are TS/JS and reach the pass as a TS buffer.("svelte", _ts_js.DIALECT),+ ("vue", _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__.pyindex d63fb2765..0c6b74120 100644--- a/packages/core/src/repowise/core/ingestion/extractors/bindings/__init__.py+++ b/packages/core/src/repowise/core/ingestion/extractors/bindings/__init__.py@@ -41,6 +41,7 @@ _DISPATCH: dict[str, Callable[[Node, str], tuple[list[str], list[NamedBinding]]]"javascript": extract_ts_js_bindings,# A component's <script> imports are ordinary ESM."svelte": extract_ts_js_bindings,+ "vue": 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.pyindex e9d0b16c7..9200fc649 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", "svelte"):+ elif lang in ("typescript", "javascript", "svelte", "vue"):# Look for leading /** ... */ commentfor 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 Nonereturn None- elif lang in ("typescript", "javascript", "svelte"):+ elif lang in ("typescript", "javascript", "svelte", "vue"):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__.pyindex dd62ab8a5..d5ef913c8 100644--- a/packages/core/src/repowise/core/ingestion/extractors/heritage/__init__.py+++ b/packages/core/src/repowise/core/ingestion/extractors/heritage/__init__.py@@ -47,6 +47,7 @@ HERITAGE_EXTRACTORS: dict[str, Callable[..., None]] = {"typescript": _extract_ts_js_heritage,"javascript": _extract_ts_js_heritage,"svelte": _extract_ts_js_heritage,+ "vue": _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__.pyindex eff5b7fdf..b89f9284f 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,7 +31,7 @@ from .java_records import java_record_synthetic_symbolsfrom .jvm_codegen import jvm_codegen_synthetic_symbolsfrom .kotlin_jvm import kotlin_synthetic_symbolsfrom .lombok import lombok_synthetic_symbols-from .svelte_component import svelte_component_symbols+from .sfc_component import sfc_component_symbolsif TYPE_CHECKING:from tree_sitter import Node@@ -52,13 +52,12 @@ _SYNTHETIC_PROVIDERS: dict[str, list[_Provider]] = {"kotlin": [kotlin_synthetic_symbols],"cpp": [cpp_macro_synthetic_symbols],"c": [cpp_macro_synthetic_symbols],- "svelte": [svelte_component_symbols],+ "svelte": [sfc_component_symbols],+ "vue": [sfc_component_symbols],}-def extract_synthetic_symbols(- root: Node, src: str, file_info: FileInfo-) -> list[Symbol]:+def extract_synthetic_symbols(root: Node, src: str, file_info: FileInfo) -> list[Symbol]:"""Dispatch to the language-appropriate synthetic-symbol providers.Returns an empty list for languages with no registered provider.diff --git a/packages/core/src/repowise/core/ingestion/extractors/synthetic_symbols/sfc_component.py b/packages/core/src/repowise/core/ingestion/extractors/synthetic_symbols/sfc_component.pynew file mode 100644index 000000000..0a6ff2f9e--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/extractors/synthetic_symbols/sfc_component.py@@ -0,0 +1,73 @@+"""The component a single-file component declares.++An SFC 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, 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.++Svelte and Vue derive the name differently. Svelte components are PascalCase by+convention and SvelteKit's routes carry a ``+`` sigil, so the stem is used+as-is. Vue tolerates ``warningBar.vue`` and ``back-to-top.vue`` while parents+still write ``<WarningBar />``, so the Vue stem is normalised through the same+rule the markup tags go through — see+:func:`~repowise.core.ingestion.sfc_source.vue_component_name_from_stem`.+"""++from __future__ import annotations++from pathlib import PurePosixPath+from typing import TYPE_CHECKING++from ...models import FileInfo, Symbol+from ...sfc_source import vue_component_name_from_stem+from ._helpers import build_synthetic_symbol++if TYPE_CHECKING:+ from tree_sitter import Node+++def _svelte_name(path: PurePosixPath) -> str:+ # 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.+ return path.stem.lstrip("+")+++def _vue_name(path: PurePosixPath) -> str:+ return vue_component_name_from_stem(path.stem, path.parent.name)+++_NAMERS = {"svelte": _svelte_name, "vue": _vue_name}+++def sfc_component_symbols(root: Node, src: str, file_info: FileInfo) -> list[Symbol]:+ """Return the single component symbol for a ``.svelte`` / ``.vue`` file."""+ path = PurePosixPath(file_info.path)+ if not path.stem:+ return []++ namer = _NAMERS.get(file_info.language)+ if namer is None:+ return []++ name = namer(path)+ 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/extractors/synthetic_symbols/svelte_component.py b/packages/core/src/repowise/core/ingestion/extractors/synthetic_symbols/svelte_component.pydeleted file mode 100644index 88974c0d4..000000000--- a/packages/core/src/repowise/core/ingestion/extractors/synthetic_symbols/svelte_component.py+++ /dev/null@@ -1,51 +0,0 @@-"""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/language_configs.py b/packages/core/src/repowise/core/ingestion/language_configs.pyindex a6005e1d6..0d95b4bb6 100644--- a/packages/core/src/repowise/core/ingestion/language_configs.py+++ b/packages/core/src/repowise/core/ingestion/language_configs.py@@ -369,7 +369,8 @@ LANGUAGE_CONFIGS: dict[str, LanguageConfig] = {),}-# 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.+# An SFC's <script> block IS TypeScript, and sfc_source hands the parser a TS+# buffer, so the TypeScript config applies verbatim. Aliasing rather than+# copying keeps them from drifting apart.LANGUAGE_CONFIGS["svelte"] = LANGUAGE_CONFIGS["typescript"]+LANGUAGE_CONFIGS["vue"] = 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__.pyindex fe62a9cde..76bf55203 100644--- a/packages/core/src/repowise/core/ingestion/languages/specs/__init__.py+++ b/packages/core/src/repowise/core/ingestion/languages/specs/__init__.py@@ -55,6 +55,7 @@ from .terraform import SPEC as _TERRAFORMfrom .toml import SPEC as _TOMLfrom .typescript import SPEC as _TYPESCRIPTfrom .unknown import SPEC as _UNKNOWN+from .vue import SPEC as _VUEfrom .xaml import SPEC as _XAMLfrom .yaml import SPEC as _YAMLfrom .zig import SPEC as _ZIG@@ -70,6 +71,7 @@ ALL_SPECS: tuple[LanguageSpec, ...] = (# Must follow _TYPESCRIPT: shares_grammar_with resolves against the# registry built so far, so typescript's grammar has to be loaded first._SVELTE,+ _VUE,_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.pyindex b30d1b6b7..aa4f01575 100644--- a/packages/core/src/repowise/core/ingestion/languages/specs/svelte.py+++ b/packages/core/src/repowise/core/ingestion/languages/specs/svelte.py@@ -1,10 +1,10 @@"""LanguageSpec for svelte.-A ``.svelte`` component is parsed as TypeScript: ``svelte_source`` blanks the+A ``.svelte`` component is parsed as TypeScript: ``sfc_source`` blanks themarkup and ``<style>`` so the ``<script>`` blocks and markup expressions sit atbyte-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.+separately by ``sfc_source`` and only locates regions, it extracts nothing."""from ..spec import LanguageSpecdiff --git a/packages/core/src/repowise/core/ingestion/languages/specs/vue.py b/packages/core/src/repowise/core/ingestion/languages/specs/vue.pynew file mode 100644index 000000000..5e7c34995--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/languages/specs/vue.py@@ -0,0 +1,95 @@+"""LanguageSpec for vue.++A ``.vue`` component is parsed as TypeScript: ``sfc_source`` blanks the+``<template>`` markup and ``<style>`` so the ``<script>`` blocks and the markup+expressions sit at byte-identical offsets in a valid TS buffer. Hence+``shares_grammar_with`` and ``scm_file`` both point at typescript — the markup+grammar (tree-sitter-html, which parses an SFC cleanly) is loaded separately by+``sfc_source`` and only locates regions, it extracts nothing.++Ceiling: an Options-API member spelled ``foo: function () {}`` or+``foo: () => {}`` inside ``methods``/``computed``/``watch`` is not captured,+because ``typescript.scm`` has no pattern for a ``pair`` with a function value.+The shorthand ``foo() {}`` spelling *is* captured — it parses as a+``method_definition`` — which covers 1588 of 1592 member functions (99.7%)+across the 275 Options-API files in the validation corpus. Lifting the+remaining 0.3% belongs in ``typescript.scm``, not here: the gap is a general+TS/JS one that affects every object literal in every ``.ts``/``.js`` file.+"""++from ..spec import LanguageSpec++SPEC = LanguageSpec(+ tag="vue",+ display_name="Vue",+ import_support="full",+ test_infixes=(".test.", ".spec."),+ extensions=frozenset({".vue"}),+ shares_grammar_with="typescript",+ scm_file="typescript.scm",+ heritage_node_types=frozenset(+ {"class_declaration", "abstract_class_declaration", "interface_declaration"}+ ),+ # Nuxt's filesystem router and the conventional SPA root: loaded by+ # convention, never imported, so they anchor reachability for everything+ # they pull in.+ entry_point_patterns=("App.vue", "app.vue", "error.vue", "default.vue"),+ manifest_files=("package.json", "vite.config.js", "nuxt.config.ts"),+ lock_files=("package-lock.json", "yarn.lock", "pnpm-lock.yaml"),+ blocked_dirs=("node_modules", ".nuxt", ".output", "dist", "build"),+ # Vue's compiler macros and template intrinsics. These are compiler+ # intrinsics, not user functions — they must never mint a call edge.+ builtin_calls=frozenset(+ {+ "defineProps",+ "defineEmits",+ "defineExpose",+ "defineOptions",+ "defineSlots",+ "defineModel",+ "withDefaults",+ "ref",+ "reactive",+ "computed",+ "watch",+ "watchEffect",+ "onMounted",+ "onUnmounted",+ "onBeforeMount",+ "onBeforeUnmount",+ "onUpdated",+ "nextTick",+ "provide",+ "inject",+ "toRef",+ "toRefs",+ "unref",+ "shallowRef",+ "markRaw",+ "useSlots",+ "useAttrs",+ "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="#42B883",+)diff --git a/packages/core/src/repowise/core/ingestion/models.py b/packages/core/src/repowise/core/ingestion/models.pyindex b70cb85fb..591bcf5d8 100644--- a/packages/core/src/repowise/core/ingestion/models.py+++ b/packages/core/src/repowise/core/ingestion/models.py@@ -22,8 +22,9 @@ LanguageTag = Literal["python","typescript","javascript",- # Single-file components — parsed as TypeScript via svelte_source.+ # Single-file components — parsed as TypeScript via sfc_source."svelte",+ "vue","go","rust","java",@@ -283,10 +284,17 @@ class TypeReference:type_name: str # head identifier (e.g. "IBasketService" from "IBasketService<T>")line: int # 1-indexed source lineorigin: Literal[- "ctor_param", "method_param", "delegate_param", # C#- "param_type", "field_type", "composite_literal", # Go- "return_type", "type_alias", "generic_constraint", # TS/JS- "extends", "implements", # TS heritage clauses (file-level type_use)+ "ctor_param",+ "method_param",+ "delegate_param", # C#+ "param_type",+ "field_type",+ "composite_literal", # Go+ "return_type",+ "type_alias",+ "generic_constraint", # TS/JS+ "extends",+ "implements", # TS heritage clauses (file-level type_use)] = "ctor_param"diff --git a/packages/core/src/repowise/core/ingestion/parser.py b/packages/core/src/repowise/core/ingestion/parser.pyindex 77058744f..1bd50a203 100644--- a/packages/core/src/repowise/core/ingestion/parser.py+++ b/packages/core/src/repowise/core/ingestion/parser.py@@ -74,8 +74,8 @@ from .parser_helpers import (_run_query,)from .python_local_refs import extract_python_local_refs+from .sfc_source import component_call_sites, prepare_sourcefrom .special_handlers import SPECIAL_HANDLER_LANGUAGES, parse_special-from .svelte_source import component_call_sites, prepare_sourcelog = structlog.get_logger(__name__)@@ -94,6 +94,11 @@ QUERIES_DIR = Path(__file__).parent / "queries"# it would misfire on the parent lexical_declaration kind mapping._MODULE_ANCHORED_NODE_TYPES = frozenset({"assignment", "variable_declarator"})+# Languages whose source reaches the parser as TypeScript/JavaScript. The two+# SFC tags are here because ``sfc_source`` projects their <script> blocks into+# a TS buffer at identical offsets, so every TS/JS code path applies verbatim.+_TS_JS_LANGUAGES = ("typescript", "javascript", "svelte", "vue")+@cachedef _load_compiled_query(lang: str, grammar_tag: str | None = None) -> object | None:@@ -273,10 +278,11 @@ 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.+ # An SFC (.svelte, .vue) is 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@@ -293,11 +299,18 @@ class ASTParser:# tree-sitter-typescript produces ERROR nodes. Re-parse using the TSX# grammar ONLY IF:# 1. Initial parse yielded error nodes (parse_errors is non-empty)- # 2. The file is TypeScript (lang == "typescript" and grammar_tag != "tsx")+ # 2. The file projects to TypeScript and is not already on tsx# 3. Source contains JSX-specific closing tokens (b"/>" or b"</")+ # A .vue render function may be written in JSX+ # (``vnodes.push(<i class={c} />)``), which is the single TS parse+ # failure across a 1,593-file .vue corpus. ``source`` here is the+ # markup-blanked projection, so the template's own ``</`` and ``/>``+ # are already spaces — the token test still keys on real JSX only.+ # The swap is strictly safe: it only takes effect when TSX yields+ # FEWER errors than the first parse.if (parse_errors- and lang == "typescript"+ and lang in ("typescript", "vue")and grammar_tag != "tsx"and (b"/>" in source or b"</" in source)):@@ -341,12 +354,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+ # An SFC 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))+ # those call sites from the markup grammar directly — the same way+ # tsx.scm turns ``<Component />`` into a call for React. Returns [] for+ # every non-SFC language.+ calls.extend(component_call_sites(lang, 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)@@ -412,7 +425,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", "svelte"):+ if file_info.language in _TS_JS_LANGUAGES:ts_deferred_exports = ts_deferred_export_names(src)for capture_dict in matches:@@ -543,7 +556,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", "svelte"):+ elif file_info.language in _TS_JS_LANGUAGES:visibility = refine_ts_visibility(def_node, visibility, name, ts_deferred_exports)# Parent class detection@@ -738,6 +751,32 @@ class ASTParser:)continue+ # Dynamic ESM import: ``import('./mod')``. The query captures the+ # call_expression, which would otherwise fall into the CommonJS+ # branch below and be dropped on the floor — a dynamic import+ # holds no ``require()`` for ``collect_cjs_requires`` to find.+ # ``imported_names`` is empty because the construct binds a module+ # namespace at runtime, not a static name; the file-to-file edge is+ # what reachability needs.+ if (+ file_info.language in _TS_JS_LANGUAGES+ and stmt_node.type == "call_expression"+ and (_fn := stmt_node.child_by_field_name("function")) is not None+ and _fn.type == "import"+ ):+ imports.append(+ Import(+ raw_statement=raw,+ module_path=module_text,+ imported_names=[],+ is_relative=module_text.startswith("."),+ resolved_file=None,+ bindings=[],+ is_reexport=False,+ )+ )+ continue+# CommonJS assignment / Object.assign shapes: the query captures# the outer statement once; walk it for every require() it# contains (a hub like Object.assign(module.exports,diff --git a/packages/core/src/repowise/core/ingestion/queries/javascript.scm b/packages/core/src/repowise/core/ingestion/queries/javascript.scmindex a531b0a1d..0cf503e9c 100644--- a/packages/core/src/repowise/core/ingestion/queries/javascript.scm+++ b/packages/core/src/repowise/core/ingestion/queries/javascript.scm@@ -88,6 +88,30 @@source: (string) @import.module) @import.statement+; Re-export (barrel) statements — only those with a `source` are imports of+; another module's symbols. Captured as @import.statement so the existing+; import pipeline resolves the edge and carries the re-exported names:+; export { A, B } from "./module"+; export { default as AppMain } from "./AppMain"+; export * from "./module"+; Kept in step with typescript.scm, which has carried this pattern all along.+; Without it a .js barrel yielded no edge whatsoever, so every component it+; re-exported read as unreachable — 6 of the 8 residual dead-code findings on+; vue-element-admin traced back to exactly this.+(export_statement+ source: (string) @import.module+) @import.statement++; Dynamic import: import("./module") — the ESM code-splitting form, and how a+; router lazy-loads a route component:+; component: () => import('@/views/user/profile')+; The specifier is a real module edge, so without this the target carries no+; inbound import and reads as unreachable. Kept in step with typescript.scm.+(call_expression+ function: (import)+ arguments: (arguments (string) @import.module)+) @import.statement+; CommonJS: const svc = require('./svc') / const { a, b } = require('./svc'); Tag the individual declarator so multi-declarator statements aren't deduped.(variable_declaratordiff --git a/packages/core/src/repowise/core/ingestion/queries/typescript.scm b/packages/core/src/repowise/core/ingestion/queries/typescript.scmindex 95948aa9f..f917f7efa 100644--- a/packages/core/src/repowise/core/ingestion/queries/typescript.scm+++ b/packages/core/src/repowise/core/ingestion/queries/typescript.scm@@ -132,6 +132,20 @@source: (string) @import.module) @import.statement+; Dynamic import: import("./module") — the ESM code-splitting form, and how+; a router lazy-loads a route component:+; component: () => import('@/views/user/profile')+; The specifier is a real module edge, so without this the target carries no+; inbound import and reads as unreachable. That is the dominant dead-code+; false positive on any app with a lazy route table (Vue Router, React.lazy,+; Angular loadChildren) — it flagged 94 of 131 components on vue-element-admin.+; Named as @import.statement on the call so multiple lazy imports in one route+; table are not deduped into a single edge.+(call_expression+ function: (import)+ arguments: (arguments (string) @import.module)+) @import.statement+; CommonJS: const svc = require('./svc') / const { a, b } = require('./svc'); Tag the individual declarator so multi-declarator statements aren't deduped.(variable_declaratordiff --git a/packages/core/src/repowise/core/ingestion/resolvers/__init__.py b/packages/core/src/repowise/core/ingestion/resolvers/__init__.pyindex a7ea9a709..0046fa015 100644--- a/packages/core/src/repowise/core/ingestion/resolvers/__init__.py+++ b/packages/core/src/repowise/core/ingestion/resolvers/__init__.py@@ -38,6 +38,7 @@ _RESOLVERS: dict[str, ResolverFn] = {# 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,+ "vue": 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/typescript.py b/packages/core/src/repowise/core/ingestion/resolvers/typescript.pyindex 12c283e09..9f88bbb51 100644--- a/packages/core/src/repowise/core/ingestion/resolvers/typescript.py+++ b/packages/core/src/repowise/core/ingestion/resolvers/typescript.py@@ -39,7 +39,21 @@ def resolve_ts_js_import(module_path: str, importer_path: str, ctx: ResolverCont"/index.js",)if ctx.has_sfc_files:- exts = (*exts, ".vue", ".svelte", ".astro")+ # Both the bare file (``./Foo`` -> ``Foo.vue``) and the directory+ # index (``./components/TodoList`` -> ``.../TodoList/index.vue``).+ # The index forms were missing here while ``/index.ts`` and+ # ``/index.js`` were present, so a directory-index component+ # resolved to nothing and read as unreachable — the same gap+ # ``subpath_imports`` already handles via ``/index.svelte``.+ exts = (+ *exts,+ ".vue",+ ".svelte",+ ".astro",+ "/index.vue",+ "/index.svelte",+ "/index.astro",+ )for ext in exts:candidate = base_posix + extif candidate in ctx.path_set:diff --git a/packages/core/src/repowise/core/ingestion/sfc_source.py b/packages/core/src/repowise/core/ingestion/sfc_source.pynew file mode 100644index 000000000..392213bad--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/sfc_source.py@@ -0,0 +1,499 @@+"""Single-file-component source preparation.++A ``.svelte`` or ``.vue`` file is three languages in one file: ``<script>``+blocks hold TS/JS, the markup is a framework-flavoured HTML, and ``<style>`` is+CSS. The markup grammars parse the file but hand each ``<script>`` body back as+one opaque ``raw_text`` node — a ``.scm`` query run against them captures no+symbol, no import and no call.++So a markup grammar is used here only to *locate* the JS-bearing regions:++* every ``<script>`` body,+* every markup expression — Svelte's ``{expr}`` and ``on:click={inc}``, Vue's+ ``@click="inc"`` / ``:class="cls"`` / ``{{ interpolation }}``.++: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}`` or+``@click="inc"`` would otherwise carry no graph edge at all and read as dead+code. Markup-driven usage is the whole idiom of both frameworks, so dropping+the markup would make the dead-code pass wrong on nearly every component.++Only the *region-location* step differs per language, so it lives behind+:data:`_LOCATORS`; the blanking, fencing, caching and offset invariants are+shared. Adding a markup language means adding a :class:`Locator`, not a second+copy of the walker.++Binding forms are deliberately skipped rather than kept: Svelte's+``{#each items as item}`` and ``{#await}`` heads, and Vue's ``v-for="item in+items"`` and ``v-slot``/``#default``. They *parse* as JS — ``item in items`` is+the ``in`` operator — but mean something else, and a parse that succeeds with+the wrong meaning is worse than a skip. The names they bind are declarations,+not reads, so keeping them would mint phantom identifier references.+"""++from __future__ import annotations++from collections.abc import Callable+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 = (b"/", b"#", b":", b"@")++# An expression whose body opens with ``{`` is an object literal+# (``use:action={{ a, b }}``, Vue's ``#default="{ row }"``). 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 = b"{"++# Both markup grammars nest ``tag_name`` under these.+_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:"++# Vue's built-in components, in the PascalCase spelling every kebab tag is+# normalised to below. Compiler/runtime intrinsics and vue-router's globally+# registered pair — none of them resolve to a component in the repo.+_VUE_BUILTIN_TAGS = frozenset(+ {+ "Component",+ "Transition",+ "TransitionGroup",+ "KeepAlive",+ "Teleport",+ "Suspense",+ "Slot",+ "Template",+ "RouterView",+ "RouterLink",+ }+)++# Vue attributes whose value is a *binding* form, not an expression to read.+_VUE_BINDING_ATTR_PREFIXES = ("v-slot", "#")++_NEWLINE = 0x0A+_CARRIAGE_RETURN = 0x0D+_SPACE = 0x20+_SEMICOLON = 0x3B+_OPEN_BRACE = 0x7B+_CLOSE_BRACE = 0x7D+_DOUBLE_QUOTE = 0x22+_SINGLE_QUOTE = 0x27++# Only a byte the scan pointed at *and* that is a real delimiter is ever+# rewritten to ``;`` — never a byte that turned out to be part of a kept+# expression. Svelte fences with braces, Vue with attribute quotes.+_FENCE_BYTES = frozenset({_OPEN_BRACE, _CLOSE_BRACE, _DOUBLE_QUOTE, _SINGLE_QUOTE})+++class SfcScan(NamedTuple):+ """What a markup 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 markup tag naming a component.+ component_tags: tuple[tuple[str, int], ...]+ # True when the markup grammar itself could not parse the file cleanly.+ has_error: bool+++_EMPTY_SCAN = SfcScan(js_spans=(), terminators=(), component_tags=(), has_error=False)+++class Locator(NamedTuple):+ """How one markup language exposes its JS regions and component tags."""++ # Importable module exposing a ``language()`` capsule.+ grammar_module: str+ # Called for every node; appends to ``state`` (spans/terminators/tags).+ visit: Callable[[Node, dict], None]+ # Maps a raw markup tag name to the component name it instantiates, or+ # None when the tag is not a user component.+ component_name: Callable[[str], str | None]+++# ---------------------------------------------------------------------------+# Shared helpers+# ---------------------------------------------------------------------------+++def _should_keep(body: bytes) -> bool:+ """True when a located markup expression is safe to project as JS."""+ stripped = body.lstrip()+ return bool(stripped) and not stripped.startswith((*_BLOCK_SIGILS, _OBJECT_LITERAL_PREFIX))+++def _keep(state: dict, start: int, end: int, open_fence: int, close_fence: int) -> None:+ """Record a kept span plus the two delimiter bytes that fence it."""+ state["spans"].append((start, end))+ if open_fence < start:+ state["terminators"].append(open_fence)+ if close_fence >= end:+ state["terminators"].append(close_fence)+++def _decode(node: Node | None) -> str:+ if node is None or node.text is None:+ return ""+ return node.text.decode("utf-8", errors="replace")+++def _record_script_bodies(node: Node, state: dict) -> None:+ """``<script>`` bodies reach both grammars as a single ``raw_text`` child."""+ for child in node.children:+ if child.type == "raw_text":+ state["spans"].append((child.start_byte, child.end_byte))+++# ---------------------------------------------------------------------------+# Svelte+# ---------------------------------------------------------------------------+++def _svelte_visit(node: Node, state: dict) -> None:+ node_type = node.type++ if node_type == "script_element":+ _record_script_bodies(node, state)+ elif node_type == "svelte_raw_text":+ parent = node.parent+ if (+ parent is not None+ and parent.type in _JS_EXPRESSION_PARENTS+ and _should_keep(node.text or b"")+ ):+ # 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.+ _keep(+ state,+ node.start_byte,+ node.end_byte,+ parent.start_byte,+ parent.end_byte - 1,+ )+ elif node_type in _TAG_PARENTS:+ _record_tags(node, state, _svelte_component_name)+++def _svelte_component_name(name: str) -> str | None:+ if not name[:1].isupper() or name.startswith(_SVELTE_NAMESPACE):+ return None+ return name+++# ---------------------------------------------------------------------------+# Vue+# ---------------------------------------------------------------------------+++def _vue_visit(node: Node, state: dict) -> None:+ node_type = node.type++ if node_type == "script_element":+ _record_script_bodies(node, state)+ elif node_type == "attribute":+ _vue_attribute(node, state)+ elif node_type == "text":+ _vue_interpolations(node, state)+ elif node_type in _TAG_PARENTS:+ _record_tags(node, state, _vue_component_name)+++def _is_vue_expression_attr(name: str) -> bool:+ """True for directive attributes whose value is a JS expression.++ Plain HTML attributes are excluded: ``class="btn primary"`` is a literal+ string, and projecting it would produce two juxtaposed identifiers — a+ guaranteed parse error on nearly every element in the corpus.+ """+ if name.startswith(_VUE_BINDING_ATTR_PREFIXES) or name == "v-for":+ return False+ return name.startswith((":", "@", "v-"))+++def _vue_attribute(node: Node, state: dict) -> None:+ """``@click="inc(1)"`` — the span sits inside ``quoted_attribute_value``.++ The surrounding quote bytes are the two fence bytes, exactly as Svelte uses+ its surrounding braces.+ """+ name_node = None+ quoted = None+ for child in node.children:+ if child.type == "attribute_name":+ name_node = child+ elif child.type == "quoted_attribute_value":+ quoted = child++ if name_node is None or quoted is None:+ return+ if not _is_vue_expression_attr(_decode(name_node)):+ return++ inner = next((c for c in quoted.children if c.type == "attribute_value"), None)+ if inner is None or not _should_keep(inner.text or b""):+ return++ _keep(state, inner.start_byte, inner.end_byte, quoted.start_byte, quoted.end_byte - 1)+++def _vue_interpolations(node: Node, state: dict) -> None:+ """``{{ expr }}`` sits inside a ``text`` node, not its own grammar node.++ tree-sitter-html has no interpolation rule, so the ``{{``/``}}`` pair is+ found by scanning within an already-located node. The scan works in bytes+ so the offsets stay byte-exact for non-ASCII markup.+ """+ raw = node.text or b""+ base = node.start_byte+ pos = 0+ while True:+ open_at = raw.find(b"{{", pos)+ if open_at < 0:+ return+ close_at = raw.find(b"}}", open_at + 2)+ if close_at < 0:+ return+ inner_start, inner_end = open_at + 2, close_at+ if _should_keep(raw[inner_start:inner_end]):+ # Fence with the inner brace of each pair: the second ``{`` and the+ # first ``}``. The outer two blank to spaces like any other markup.+ _keep(+ state,+ base + inner_start,+ base + inner_end,+ base + open_at + 1,+ base + close_at,+ )+ pos = close_at + 2+++def _de_kebab(name: str) -> str:+ if "-" not in name:+ return name+ return "".join(part[:1].upper() + part[1:] for part in name.split("-") if part)+++def _vue_component_name(name: str) -> str | None:+ """``<my-widget />`` and ``<MyWidget />`` name the same component.++ Vue resolves a kebab-case tag to its PascalCase component, so the tag is+ normalised before the built-in filter runs — that way ``<keep-alive>`` and+ ``<KeepAlive>`` are both recognised as intrinsics. A tag containing ``-``+ is always a custom element; no native HTML element has one. A bare+ lowercase tag (``<div>``) is a native element and is deliberately *not*+ capitalised into existence here.+ """+ name = _de_kebab(name)+ if not name[:1].isupper() or name in _VUE_BUILTIN_TAGS:+ return None+ return name+++def vue_component_name_from_stem(stem: str, parent_dir: str = "") -> str:+ """The component name a ``.vue`` filename declares.++ Unlike a markup tag, a filename is *always* a component, so this+ capitalises unconditionally: ``warningBar.vue`` declares ``WarningBar``,+ which is what a parent writes both in its import and in its markup.++ ``components/Logo/index.vue`` is the ``Logo`` component — the directory+ index convention — so a bare ``index`` stem defers to its directory.++ Sharing this with :func:`_vue_component_name` is the point: a tag and the+ file it resolves to are normalised by the same rule, so they cannot+ disagree. Measured on the validation corpus, this lifts filename/import+ agreement from 58.4% to 82.9% of ``.vue`` default imports; the remainder+ are genuine renames that no naming rule can recover.+ """+ if stem.lower() == "index" and parent_dir:+ stem = parent_dir+ stem = _de_kebab(stem)+ return stem[:1].upper() + stem[1:]+++# ---------------------------------------------------------------------------+# Registry+# ---------------------------------------------------------------------------+++def _record_tags(node: Node, state: dict, name_of: Callable[[str], str | None]) -> None:+ for child in node.children:+ if child.type != "tag_name":+ continue+ component = name_of(_decode(child))+ if component:+ state["tags"].append((component, child.start_point[0] + 1))+++_LOCATORS: dict[str, Locator] = {+ "svelte": Locator(+ grammar_module="tree_sitter_svelte",+ visit=_svelte_visit,+ component_name=_svelte_component_name,+ ),+ # tree-sitter-html parses a Vue SFC cleanly: <template>, <script> and+ # <style> are just elements to it. There is no tree-sitter-vue on PyPI, and+ # this grammar covers plain HTML too.+ "vue": Locator(+ grammar_module="tree_sitter_html",+ visit=_vue_visit,+ component_name=_vue_component_name,+ ),+}+++@lru_cache(maxsize=len(_LOCATORS))+def _grammar(module_name: str) -> Language | None:+ """Load a tree-sitter markup grammar, or None when unavailable."""+ try:+ import importlib++ from tree_sitter import Language++ return Language(importlib.import_module(module_name).language())+ except Exception as exc: # pragma: no cover - depends on install shape+ log.debug("tree-sitter grammar unavailable", module=module_name, reason=str(exc))+ return None+++def _walk(node: Node, visit: Callable[[Node, dict], None], state: dict) -> None:+ visit(node, state)+ for child in node.children:+ _walk(child, visit, state)+++def scan(language: str, source: bytes) -> SfcScan:+ """Locate the JS regions and component tags of one SFC source.++ Returns an empty scan for a non-SFC language or when the markup grammar is+ unavailable, which degrades the file to zero symbols rather than to wrong+ ones.+ """+ if language not in _LOCATORS:+ return _EMPTY_SCAN+ return _cached_scan(language, 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(language: str, source: bytes) -> SfcScan:+ locator = _LOCATORS[language]+ grammar = _grammar(locator.grammar_module)+ if grammar is None:+ return _EMPTY_SCAN++ try:+ from tree_sitter import Parser++ tree = Parser(grammar).parse(source)+ except Exception as exc:+ log.debug("sfc_scan_failed", language=language, error=str(exc))+ return _EMPTY_SCAN++ state: dict = {"spans": [], "terminators": [], "tags": []}+ _walk(tree.root_node, locator.visit, state)+ return SfcScan(+ js_spans=tuple(sorted(state["spans"])),+ terminators=tuple(sorted(state["terminators"])),+ component_tags=tuple(state["tags"]),+ has_error=tree.root_node.has_error,+ )+++def _blank(source: bytes, scan_result: SfcScan) -> 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:+ if source[offset] in _FENCE_BYTES:+ out[offset] = _SEMICOLON+ return bytes(out)+++def component_call_sites(language: str, source: bytes, symbols: list) -> list:+ """Turn every component tag in the markup into a call site.++ ``<Foo />`` is how both frameworks instantiate ``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+ markup grammar instead. Returns ``[]`` for every non-SFC language.+ """+ from .models import CallSite+ from .parser_helpers import _find_enclosing_symbol++ tags = scan(language, 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 without a registered locator. 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 not in _LOCATORS or not source:+ return source+ return _blank(source, scan(language, source))diff --git a/packages/core/src/repowise/core/ingestion/svelte_source.py b/packages/core/src/repowise/core/ingestion/svelte_source.pydeleted file mode 100644index dfdef158c..000000000--- a/packages/core/src/repowise/core/ingestion/svelte_source.py+++ /dev/null@@ -1,244 +0,0 @@-"""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.pyindex 41b84cf5c..02338400c 100644--- a/packages/core/src/repowise/core/ingestion/tsconfig_resolver.py+++ b/packages/core/src/repowise/core/ingestion/tsconfig_resolver.py@@ -30,8 +30,23 @@ import structloglog = structlog.get_logger(__name__)-# Extensions probed in TypeScript module resolution order.-_TS_EXTENSIONS = (".ts", ".tsx", ".mts", ".cts", ".js", ".jsx")+# Extensions probed in TypeScript module resolution order. The SFC extensions+# trail the real TS/JS ones so a genuine ``.ts`` always wins, but they must be+# present: a Vue/Nuxt app aliases ``@/* -> src/*`` in jsconfig.json and then+# lazy-loads every route as ``import('@/views/user/profile')`` with no+# extension. Without ``.vue`` here that specifier resolved to nothing, the+# component carried no inbound edge, and the whole route table read as dead.+_TS_EXTENSIONS = (+ ".ts",+ ".tsx",+ ".mts",+ ".cts",+ ".js",+ ".jsx",+ ".vue",+ ".svelte",+ ".astro",+)_INDEX_FILES = ("index.ts","index.tsx",@@ -39,6 +54,9 @@ _INDEX_FILES = ("index.cts","index.js","index.jsx",+ "index.vue",+ "index.svelte",+ "index.astro",)@@ -457,7 +475,7 @@ def wire_tsconfig_resolver("""# 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"}+ _ts_langs = {"typescript", "javascript", "svelte", "vue"}# 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.pyindex 3570e9788..673ab0f5f 100644--- a/packages/core/src/repowise/core/pipeline/phases/ingestion.py+++ b/packages/core/src/repowise/core/pipeline/phases/ingestion.py@@ -409,7 +409,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", "svelte"}+ _ts_langs = {"typescript", "javascript", "svelte", "vue"}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.tomlindex c141a5be0..92a6541b0 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -51,9 +51,13 @@ 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).+ # Markup grammars for single-file components: these locate <script> blocks+ # and markup expressions only; the JS inside them is parsed with the+ # TypeScript grammar (see sfc_source.py). There is no tree-sitter-vue on+ # PyPI — the HTML grammar parses a .vue SFC cleanly, since <template>,+ # <script> and <style> are just elements to it."tree-sitter-svelte>=1,<2",+ "tree-sitter-html>=0.23,<1",# SQL parsing (multi-dialect, error-tolerant, pure Python)"sqlglot>=26,<28",# Dependency graphdiff --git a/tests/unit/ingestion/test_language_capabilities.py b/tests/unit/ingestion/test_language_capabilities.pyindex 4e5b00de3..44aed6767 100644--- a/tests/unit/ingestion/test_language_capabilities.py+++ b/tests/unit/ingestion/test_language_capabilities.py@@ -148,6 +148,9 @@ _FULL = {"svelte","swift","typescript",+ # vue components project to TypeScript through the same SFC pass as+ # svelte, so their <script> imports are ordinary ESM.+ "vue",}_PARTIAL = {"luau",diff --git a/tests/unit/ingestion/test_sfc_source.py b/tests/unit/ingestion/test_sfc_source.pynew file mode 100644index 000000000..9de901320--- /dev/null+++ b/tests/unit/ingestion/test_sfc_source.py@@ -0,0 +1,334 @@+"""Unit tests for the single-file-component source projection.++``sfc_source`` is the seam every Svelte and Vue 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.sfc_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("svelte", _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("svelte", 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("svelte", src).component_tags}+ assert names == set()++ def test_tag_line_numbers_point_at_the_original_file(self) -> None:+ tags = dict(scan("svelte", _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)+++# ---------------------------------------------------------------------------+# Vue+# ---------------------------------------------------------------------------++_VUE_COMPONENT = b"""<template>+ <div :class="cls" @click="inc(1)" v-if="ready">+ {{ label(item) }} and {{ other }}+ </div>+ <WarningBar :msg="msg" />+ <back-to-top />+ <li v-for="row in rows" :key="row.id">{{ row.n }}</li>+ <KeepAlive><slot /></KeepAlive>+ <component :is="which" />+</template>++<script setup lang="ts">+import WarningBar from '@/components/warningBar.vue';++const cls = 'a';++function inc(n: number) {+ return n + 1;+}+</script>++<style scoped>+ .a { color: red; }+</style>+"""+++class TestVueOffsetInvariants:+ """The projection is byte-for-byte positional, exactly as for Svelte."""++ def test_length_is_preserved(self) -> None:+ assert len(prepare_source("vue", _VUE_COMPONENT)) == len(_VUE_COMPONENT)++ def test_newline_count_is_preserved(self) -> None:+ prepared = prepare_source("vue", _VUE_COMPONENT)+ assert prepared.count(b"\n") == _VUE_COMPONENT.count(b"\n")++ def test_non_ascii_markup_keeps_offsets(self) -> None:+ # A multi-byte character in the markup must not shift the script that+ # follows it — the blanking works in bytes, not code points.+ src = "<template><p>日本語のテキスト</p></template>\n<script>const a = 1;</script>\n".encode()+ prepared = prepare_source("vue", src)+ assert len(prepared) == len(src)+ assert prepared.index(b"const a = 1;") == src.index(b"const a = 1;")+++class TestVueScriptAndMarkupProjection:+ def test_script_body_survives_verbatim(self) -> None:+ prepared = prepare_source("vue", _VUE_COMPONENT)+ assert b"import WarningBar from '@/components/warningBar.vue';" in prepared+ assert b"function inc(n: number) {" in prepared++ def test_style_and_plain_markup_are_blanked(self) -> None:+ prepared = prepare_source("vue", _VUE_COMPONENT)+ assert b"color: red" not in prepared+ assert b"<template>" not in prepared++ def test_directive_expressions_are_kept_and_fenced(self) -> None:+ # The two quote bytes around each value become ``;`` so neighbouring+ # attributes cannot run together into one statement.+ prepared = prepare_source("vue", _VUE_COMPONENT)+ assert b";cls;" in prepared+ assert b";inc(1);" in prepared+ assert b";ready;" in prepared++ def test_interpolations_are_kept_and_fenced(self) -> None:+ prepared = prepare_source("vue", _VUE_COMPONENT)+ assert b"; label(item) ;" in prepared+ assert b"; other ;" in prepared++ def test_plain_html_attributes_are_not_projected(self) -> None:+ # class="btn primary" is a literal string; projecting it would put two+ # juxtaposed identifiers at statement position and fail to parse.+ src = b'<template><div class="btn primary" id="x">hi</div></template>\n'+ prepared = prepare_source("vue", src)+ assert b"btn primary" not in prepared++ def test_v_for_binding_is_skipped(self) -> None:+ # ``row in rows`` parses as the ``in`` operator but is a binding form.+ prepared = prepare_source("vue", _VUE_COMPONENT)+ assert b"row in rows" not in prepared+ # ...while :key on the same element is still kept.+ assert b";row.id;" in prepared++ def test_slot_props_object_literal_is_skipped(self) -> None:+ src = b'<template><Table #default="{ row }" /></template>\n'+ prepared = prepare_source("vue", src)+ assert b"row" not in prepared++ def test_projection_parses_as_typescript(self) -> None:+ ts = pytest.importorskip("tree_sitter_typescript")+ from tree_sitter import Language, Parser++ prepared = prepare_source("vue", _VUE_COMPONENT)+ tree = Parser(Language(ts.language_typescript())).parse(prepared)+ assert not tree.root_node.has_error+++class TestVueComponentTags:+ def test_pascal_case_tag_is_a_component(self) -> None:+ names = {name for name, _ in scan("vue", _VUE_COMPONENT).component_tags}+ assert "WarningBar" in names++ def test_kebab_case_tag_normalises_to_pascal_case(self) -> None:+ # Vue resolves <back-to-top> to the BackToTop component, and the+ # synthetic file symbol is named by the same rule, so they agree.+ names = {name for name, _ in scan("vue", _VUE_COMPONENT).component_tags}+ assert "BackToTop" in names++ def test_native_elements_are_not_components(self) -> None:+ names = {name for name, _ in scan("vue", _VUE_COMPONENT).component_tags}+ assert names.isdisjoint({"div", "li", "Div", "Li", "template", "Template"})++ def test_vue_builtins_never_mint_a_call_edge(self) -> None:+ names = {name for name, _ in scan("vue", _VUE_COMPONENT).component_tags}+ assert names.isdisjoint({"KeepAlive", "Slot", "Component"})++ def test_builtin_filter_applies_to_the_kebab_spelling_too(self) -> None:+ src = b"<template><keep-alive><router-view /></keep-alive></template>\n"+ assert scan("vue", src).component_tags == ()++ def test_tag_line_numbers_point_at_the_original_file(self) -> None:+ tags = dict(scan("vue", _VUE_COMPONENT).component_tags)+ assert tags["WarningBar"] == 5+++class TestVueComponentNameFromStem:+ """Filenames and markup tags must normalise through one shared rule."""++ @pytest.mark.parametrize(+ ("stem", "parent", "expected"),+ [+ ("WarningBar", "components", "WarningBar"),+ ("warningBar", "components", "WarningBar"),+ ("back-to-top", "views", "BackToTop"),+ ("index", "Logo", "Logo"),+ ("index", "warning-bar", "WarningBar"),+ ("index", "", "Index"),+ ],+ )+ def test_stem_normalisation(self, stem: str, parent: str, expected: str) -> None:+ from repowise.core.ingestion.sfc_source import vue_component_name_from_stem++ assert vue_component_name_from_stem(stem, parent) == expected+++class TestNonSfcLanguagesAreUntouched:+ @pytest.mark.parametrize("language", ["typescript", "javascript", "python", "go"])+ def test_prepare_source_is_identity(self, language: str) -> None:+ src = b"const a = 1;\n"+ assert prepare_source(language, src) is src++ @pytest.mark.parametrize("language", ["typescript", "python"])+ def test_scan_is_empty(self, language: str) -> None:+ result = scan(language, _VUE_COMPONENT)+ assert result.js_spans == ()+ assert result.component_tags == ()+++class TestVueDegradation:+ @pytest.mark.parametrize(+ "src",+ [+ b"",+ b"<template><p>markup only</p></template>\n",+ b"<script>",+ b"<template><div><span></div></template>\n",+ b'<template><div :class=""></div></template>\n',+ b"<template>{{ }}</template>\n",+ b"<template>{{ unclosed </template>\n",+ ],+ )+ def test_malformed_or_scriptless_input_never_raises(self, src: bytes) -> None:+ prepared = prepare_source("vue", src)+ assert len(prepared) == len(src)+ assert prepared.count(b"\n") == src.count(b"\n")diff --git a/tests/unit/ingestion/test_svelte_source.py b/tests/unit/ingestion/test_svelte_source.pydeleted file mode 100644index b03b19e7a..000000000--- a/tests/unit/ingestion/test_svelte_source.py+++ /dev/null@@ -1,152 +0,0 @@-"""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)