Skip to main content

fallow_types/
extract.rs

1//! Module extraction types.
2
3use std::path::PathBuf;
4use std::sync::Arc;
5
6use oxc_span::Span;
7
8use crate::discover::FileId;
9use crate::suppress::{Suppression, UnknownSuppressionKind};
10
11/// Extracted module information from a single file.
12///
13/// The `Arc<[T]>` fields are immutable after extraction and are shared by
14/// refcount with the resolver's per-file output, so the resolve/graph path
15/// does not deep-copy per-file extraction payloads.
16#[derive(Debug, Clone)]
17pub struct ModuleInfo {
18    /// Unique identifier for this file.
19    pub file_id: FileId,
20    /// All export declarations in this module.
21    pub exports: Arc<[ExportInfo]>,
22    /// All import declarations in this module.
23    pub imports: Vec<ImportInfo>,
24    /// All re-export declarations (e.g., `export { foo } from './bar'`).
25    pub re_exports: Vec<ReExportInfo>,
26    /// All dynamic `import()` calls with string literal sources.
27    pub dynamic_imports: Vec<DynamicImportInfo>,
28    /// Dynamic import patterns.
29    pub dynamic_import_patterns: Vec<DynamicImportPattern>,
30    /// All `require()` calls.
31    pub require_calls: Vec<RequireCallInfo>,
32    /// Package names statically referenced through package path resolution.
33    pub package_path_references: Box<[String]>,
34    /// Static member access expressions (e.g., `Status.Active`).
35    pub member_accesses: Arc<[MemberAccess]>,
36    /// Typed semantic facts produced by extraction for cross-layer analysis.
37    ///
38    /// This carries facts that were previously encoded as synthetic
39    /// `member_accesses` strings. Extraction and analysis now use typed facts.
40    pub semantic_facts: Arc<[SemanticFact]>,
41    /// Identifiers used in whole-object access patterns.
42    pub whole_object_uses: Arc<[String]>,
43    /// Whether this module uses CommonJS exports.
44    pub has_cjs_exports: bool,
45    /// Whether this module declares an Angular component `templateUrl`.
46    pub has_angular_component_template_url: bool,
47    /// xxh3 hash of the file content for incremental caching.
48    pub content_hash: u64,
49    /// Inline suppression directives parsed from comments.
50    pub suppressions: Vec<Suppression>,
51    /// Suppression tokens that did not parse to any known `IssueKind`.
52    /// Surfaced as `StaleSuppression` findings via `find_stale` so users see
53    /// typos or obsolete kind names instead of having the entire marker
54    /// silently discarded. See issue #449.
55    pub unknown_suppression_kinds: Vec<UnknownSuppressionKind>,
56    /// Local names of import bindings that are never referenced in this file.
57    /// Populated via `oxc_semantic` scope analysis. Used at graph-build time
58    /// to skip adding references for imports whose binding is never read,
59    /// improving unused-export detection precision.
60    pub unused_import_bindings: Vec<String>,
61    /// Local import bindings that are referenced from TypeScript type positions.
62    /// Used to distinguish value-namespace and type-namespace references when a
63    /// module exports both `const X` and `type X`.
64    pub type_referenced_import_bindings: Vec<String>,
65    /// Local import bindings referenced from runtime/value positions.
66    pub value_referenced_import_bindings: Vec<String>,
67    /// Pre-computed byte offsets where each line starts.
68    pub line_offsets: Vec<u32>,
69    /// Per-function complexity metrics.
70    pub complexity: Vec<FunctionComplexity>,
71    /// Feature flag use sites.
72    pub flag_uses: Vec<FlagUse>,
73    /// Heritage metadata for exported classes that declare `implements`.
74    pub class_heritage: Vec<ClassHeritageInfo>,
75    /// Exported free-function factories that provably return one class instance
76    /// (`export function useApi() { return new RESTApi() }`). Origin-module proof
77    /// that an exported function returns a class instance, so a cross-module
78    /// `const x = useApi(); x.member` consumer can credit the returned class.
79    /// See issue #1441 (Part A).
80    pub exported_factory_returns: Arc<[FactoryReturnExport]>,
81    /// Exported factories that return an OBJECT LITERAL whose property values are
82    /// class instances (`export function createUi() { return { orders: factory.ordersPage } }`).
83    /// Each entry maps a dotted property path (`orders`, `invoke.dashboard`) to the
84    /// returned class's local name within the factory module, so a cross-module
85    /// `const ui = createUi(); ui.orders.member` consumer can credit the class. Names
86    /// are local to this module; resolution is deferred to analyze time. See issue #1858.
87    pub exported_factory_return_object_shapes: Arc<[FactoryReturnObjectShapeExport]>,
88    /// Named-type property types declared by this module's top-level interfaces
89    /// and type-literal aliases (`interface Opts { c: OptDep }`). Names are
90    /// local to this module; resolution is deferred to analyze time. Consumed
91    /// by the `unused-class-member` typed-property-hop join and the Playwright
92    /// fixture-type resolution. See issue #1785.
93    pub type_member_types: Arc<[TypeMemberTypeEntry]>,
94    /// Angular `InjectionToken<Interface>` declarations, as
95    /// `(token_export_name, interface_name)` pairs. Recorded only for
96    /// `new InjectionToken<I>(...)` initializers whose `InjectionToken` is
97    /// imported from `@angular/core`. The analyze layer follows the token's
98    /// interface type argument to the classes that `implement` it so a template
99    /// member call through `inject(TOKEN)` credits the concrete implementation.
100    /// See issue #920 (follow-up to #911 / #913).
101    pub injection_tokens: Vec<(String, String)>,
102    /// Local type-capable declarations.
103    pub local_type_declarations: Vec<LocalTypeDeclaration>,
104    /// Type references in exported public signatures.
105    pub public_signature_type_references: Vec<PublicSignatureTypeReference>,
106    /// Aliases of namespace imports re-exported through an object literal.
107    pub namespace_object_aliases: Vec<NamespaceObjectAlias>,
108    /// Deduped Iconify collection prefixes found in static icon props.
109    pub iconify_prefixes: Vec<String>,
110    /// Deduped Nuxt UI `i-<collection>-<icon>` icon class suffixes found in
111    /// static script-side icon properties.
112    pub iconify_icon_names: Vec<String>,
113    /// Bare identifiers that may be resolved by framework auto-imports.
114    pub auto_import_candidates: Vec<String>,
115    /// File-level string directives in source order (e.g. `"use client"`,
116    /// `"use server"`, `"use strict"`). Captured from `Program::directives`.
117    /// Consumed by the security `client-server-leak` detector to identify
118    /// React Server Component client boundaries.
119    pub directives: Vec<String>,
120    /// Byte-offset starts of dynamic `import()` expressions wrapped in
121    /// `next/dynamic(() => import('./X'), { ssr: false })`. The ssr:false option
122    /// is Next.js's sanctioned way to pull a client-only module, so a server-only
123    /// module reached ONLY through such an import is NOT a client-server leak. The
124    /// security `client-server-leak` BFS resolves each dynamic import to a graph
125    /// edge; these span starts let the BFS exclude exactly those edges (matched
126    /// against the edge's `import_span`). Empty for files with no ssr:false
127    /// dynamic import. Captured only by JS/TS extraction.
128    pub client_only_dynamic_import_spans: Vec<u32>,
129    /// Captured security sink sites (category-blind). Consumed by the
130    /// catalogue-driven `tainted_sink` detector. Captured only by JS/TS
131    /// extraction; empty for CSS/MDX/etc. See `security_matchers.toml`.
132    pub security_sinks: Vec<SinkSite>,
133    /// Count of sink-shaped nodes whose callee could not be flattened to a
134    /// static path (dynamic dispatch, computed members, aliased bindings).
135    /// Surfaced in-band so an empty catalogue result with a non-zero count is
136    /// not a clean bill.
137    pub security_sinks_skipped: u32,
138    /// Compact span-level diagnostics for skipped security sink callees. Kept
139    /// next to `security_sinks_skipped` so warm-cache and cold-cache security
140    /// output can explain where the blind spots are concentrated without source
141    /// snippets.
142    pub security_unresolved_callee_sites: Vec<SkippedSecurityCalleeSite>,
143    /// Local bindings whose initializer (or destructured object) is a flattened
144    /// member-access path. Used by the security `tainted_sink` detector to
145    /// back-trace a sink argument to a known untrusted source: the analyze layer
146    /// matches each binding's `source_path` against the data-driven source
147    /// catalogue (`security_matchers.toml` `[[source]]` rows) and treats the
148    /// matching `local` names as source-tainted. Intra-module and name-based
149    /// (no scope analysis); a conservative association, never a taint proof.
150    pub tainted_bindings: Vec<TaintedBinding>,
151    /// Sink arguments that were recognized as sanitizer calls at extraction
152    /// time. Used for direct sink calls such as
153    /// `el.innerHTML = DOMPurify.sanitize(input)`.
154    pub sanitized_sink_args: Vec<SanitizedSinkArg>,
155    /// Known defensive control call sites found in this module. Consumed only by
156    /// the `fallow security --surface` agent JSON path.
157    pub security_control_sites: Vec<SecurityControlSite>,
158    /// Statically flattenable callee paths invoked in this module, deduped per
159    /// unique path (first occurrence wins). Consumed by the
160    /// `boundaries.calls.forbidden` detector. Captured unconditionally because
161    /// extraction is config-blind; the per-module cost is bounded by the
162    /// unique-callee count.
163    pub callee_uses: Vec<CalleeUse>,
164    /// `"use client"` / `"use server"` directive strings written as expression
165    /// statements in `program.body` (misplaced, NOT in the leading
166    /// prologue), so the RSC bundler silently ignores them. One entry per
167    /// occurrence. Consumed by the `misplaced-directive` detector. Captured
168    /// only by JS/TS extraction.
169    pub misplaced_directives: Vec<MisplacedDirectiveSite>,
170    /// Export LOCAL NAMES of exported functions / const-arrows whose body has an
171    /// inline `"use server"` directive (`export async function f() { "use server"
172    /// }`), captured in a NON-`"use server"` file. Consumed by the
173    /// `unused-server-action` detector to reclassify an unused inline Server
174    /// Action export out of `unused-export`. Captured only by JS/TS extraction.
175    pub inline_server_action_exports: Vec<String>,
176    /// Vue `provide`/`inject` and Svelte `setContext`/`getContext` call sites
177    /// keyed by an identifier symbol. Consumed by the `unprovided-inject`
178    /// detector to find an inject/getContext whose key is provided nowhere
179    /// project-wide. Only identifier-keyed sites are recorded (string-literal
180    /// and computed keys abstain). Captured by JS/TS and SFC extraction.
181    pub di_key_sites: Vec<DiKeySite>,
182    /// `true` when this module contains a `provide(...)` / `*.provide(...)` /
183    /// `setContext(...)` call whose key argument is NOT a plain identifier
184    /// (spread, computed, member, loop variable). Such a call can provide an
185    /// unknowable key, so the `unprovided-inject` detector abstains on ALL
186    /// inject findings project-wide when any reachable module sets this flag.
187    /// Mirrors the spread-return whole-object abstain used for Pinia stores.
188    pub has_dynamic_provide: bool,
189    /// Local names of import bindings that ARE referenced somewhere in this file
190    /// (script value/type position OR template/markup). The complement of
191    /// `unused_import_bindings` among `imports`. Derived by
192    /// `prepare_analysis_facts` while both source vectors are still present, so
193    /// it remains readable after the owned release path clears them. It is never
194    /// cached and is recomputed on every cache load. Consumed by the
195    /// `unrendered-component` detector to credit a
196    /// Vue/Svelte SFC that some file actually imports-and-uses, distinguishing it
197    /// from a component reachable only through a barrel re-export.
198    pub referenced_import_bindings: Vec<String>,
199    /// Vue `<script setup>` `defineProps` and Svelte 5 `$props()` declared
200    /// props. Consumed by the `unused-component-prop` detector to flag a prop
201    /// referenced nowhere in its own SFC. Each entry carries `used_in_script` /
202    /// `used_in_template`.
203    pub component_props: Vec<ComponentProp>,
204    /// `true` when the template spreads the whole props/attrs object
205    /// (`v-bind="$attrs"` / `v-bind="$props"` / `v-bind="props"`) or the props
206    /// return is destructured with a rest element. Either form can consume a prop
207    /// indirectly, so the detector abstains on the whole file.
208    pub has_props_attrs_fallthrough: bool,
209    /// `true` when the SFC calls `defineExpose(...)`. A prop may be re-exposed,
210    /// so the detector conservatively abstains on the whole file.
211    pub has_define_expose: bool,
212    /// `true` when the SFC calls `defineModel(...)`. Two-way model props are out
213    /// of scope for v1, so the detector abstains on the whole file.
214    pub has_define_model: bool,
215    /// `true` when props were declared through an unharvestable shape, such as a
216    /// Vue type-reference argument or an opaque Svelte `$props()` destructure.
217    /// The detector abstains on the whole file so a prop is never falsely
218    /// flagged.
219    pub has_unharvestable_props: bool,
220    /// Vue `<script setup>` `defineEmits` declared events. Consumed by the
221    /// `unused-component-emit` detector to flag an event emitted nowhere in its
222    /// own SFC. Each entry carries `used`.
223    pub component_emits: Vec<ComponentEmit>,
224    /// Angular component/directive inputs declared via `@Input()` decorators or
225    /// signal `input()` / `input.required()` / `model()` initializers. Consumed
226    /// by the `unused-component-input` detector to flag an input read nowhere in
227    /// its own component. Empty for every non-Angular class.
228    pub angular_inputs: Vec<AngularInputMember>,
229    /// Angular component/directive outputs declared via `@Output()` decorators or
230    /// signal `output()` / `outputFromObservable()` initializers. Consumed by the
231    /// `unused-component-output` detector to flag an output emitted nowhere in its
232    /// own component. A `model()` is recorded as an input only (see
233    /// `AngularOutputMember`). Empty for every non-Angular class.
234    pub angular_outputs: Vec<AngularOutputMember>,
235    /// Angular `@Component` declarations with their `selector` value(s), harvested
236    /// from `@Component({ selector: '...' })` decorators. Consumed by the Angular
237    /// arm of the `unrendered-component` detector. Empty for every non-Angular
238    /// class and for `@Directive`. See `AngularComponentSelector`.
239    pub angular_component_selectors: Vec<AngularComponentSelector>,
240    /// Lit / web-component custom elements REGISTERED in this file via
241    /// `@customElement('x-foo')` or `customElements.define('x-foo', C)`. Consumed
242    /// by the Lit arm of the `unrendered-component` detector, which flags a
243    /// registered element whose tag is rendered in NO `html` template
244    /// project-wide. Empty for non-Lit / non-web-component files. See
245    /// `RegisteredCustomElement`.
246    pub registered_custom_elements: Vec<RegisteredCustomElement>,
247    /// Custom-element tag names USED (rendered) in this file's `html` tagged
248    /// templates, e.g. `` html`<x-foo></x-foo>` `` -> `x-foo`. Only hyphenated
249    /// (custom-element) tags are recorded; native HTML tags are excluded by the
250    /// hyphen requirement. The detector unions these project-wide into the
251    /// rendered-tag set. Empty for files with no `html` templates.
252    pub used_custom_element_tags: Vec<String>,
253    /// Custom element selector tag names referenced in this file's Angular
254    /// templates (inline `@Component({ template })` and the linked external
255    /// `templateUrl` `.html` module), e.g. `<app-foo>` -> `app-foo`. Native HTML
256    /// tag names are excluded at harvest. The detector unions these project-wide
257    /// into the used-selector set. Empty for non-Angular files.
258    pub angular_used_selectors: Vec<String>,
259    /// Angular component class names referenced as a route entry or bootstrap
260    /// target: a route `component: Foo` / `loadComponent: () => import().then(m =>
261    /// m.Foo)` value, a `bootstrapApplication(Foo)` argument, or a
262    /// `bootstrap: [Foo]` NgModule entry. These are render-equivalent entry points
263    /// (Angular instantiates them without a template `<tag>`), so the Angular
264    /// `unrendered-component` detector abstains on a component whose class name is
265    /// in the project-wide union. A plain `declarations: [...]` / `imports: [...]`
266    /// registration is intentionally NOT harvested here (that is the dead case the
267    /// rule catches). Empty for non-Angular files.
268    pub angular_entry_component_refs: Vec<String>,
269    /// `true` when this file dynamically renders an Angular component fallow
270    /// cannot attribute to a literal class reference: a
271    /// `ViewContainerRef.createComponent(...)` / `*.createComponent(<ident>)`
272    /// call, or an `*ngComponentOutlet` template binding. The Angular
273    /// `unrendered-component` detector abstains project-wide when ANY reachable
274    /// module sets this (mirroring `unprovided-inject`'s `has_dynamic_provide`),
275    /// since a component could be rendered by a non-literal class reference.
276    pub has_dynamic_component_render: bool,
277    /// `true` when `defineEmits` was called with an unharvestable argument (a
278    /// type-reference type argument such as `defineEmits<MyEmits>()`, a
279    /// non-literal runtime form, or an unbound `defineEmits([...])`). The
280    /// detector abstains on the whole file so an emit is never falsely flagged.
281    pub has_unharvestable_emits: bool,
282    /// `true` when an `emit(<nonLiteral>)` call was seen (the emitted event name
283    /// cannot be known statically). The detector abstains on the whole file.
284    pub has_dynamic_emit: bool,
285    /// `true` when the `defineEmits` return binding was used as a WHOLE value
286    /// (passed to a function, returned, or spread), which can emit any event
287    /// opaquely. The detector abstains on the whole file.
288    pub has_emit_whole_object_use: bool,
289    /// SvelteKit `load()` return-object keys harvested from a
290    /// `+page.{ts,server.ts,js,server.js}` file's terminal return literal.
291    /// Consumed by the `unused-load-data-key` detector. Empty for every file
292    /// that is not a page-load producer (gated by basename at harvest time).
293    pub load_return_keys: Vec<LoadReturnKey>,
294    /// `true` when this file's `load()` body could not be harvested safely (a
295    /// spread return, a non-object/non-literal return, more than one top-level
296    /// `return`, a computed key, or a wrapped/re-exported `load`). The detector
297    /// abstains on the whole file so a key is never falsely flagged.
298    pub has_unharvestable_load: bool,
299    /// `true` when this file passes the whole `data` object opaquely (script
300    /// `const X = data`, `fn(data)` / `fn(...data)`, or template `data={data}` /
301    /// `{...data}` in a route component), so a child can read arbitrary keys the
302    /// detector cannot see. Name-gated on the `data` binding. Read ONLY by the
303    /// `unused-load-data-key` detector, so capturing it for all files is
304    /// byte-identity-safe. See FP-1 in the plan.
305    pub has_load_data_whole_use: bool,
306    /// `true` when this file uses the whole `page.data` / `$page.data` store
307    /// object opaquely (e.g. `Object.values(page.data)`, `{...$page.data}`), so a
308    /// reflective read could consume any route's key. Drives the
309    /// `unused-load-data-key` detector's project-wide abstain. Derived by
310    /// `prepare_analysis_facts` from `whole_object_uses` before the owned release
311    /// path clears that vector. It is never cached and is recomputed each run from
312    /// the cached `whole_object_uses`. Reassignment forms
313    /// (`const all = $page.data`) are not whole-object-tracked and stay out of
314    /// scope, matching the syntactic analyzer's conservative posture.
315    pub has_page_data_store_whole_use: bool,
316    /// `true` when a React Router or Remix route consumes the whole
317    /// `useLoaderData()` result opaquely. Derived by `prepare_analysis_facts`
318    /// from the synthetic route-loader marker before the owned release path
319    /// clears `whole_object_uses`. It is recomputed from cached extraction data.
320    pub has_route_loader_data_whole_use: bool,
321    /// React/JSX component definitions: functions/arrows whose body returns JSX.
322    /// Captured only for `.jsx`/`.tsx` files when a React/Preact dependency is
323    /// plausible. Consumed by the React `unused-component-prop` arm and the
324    /// complexity-fold phase. Empty for non-React files.
325    pub component_functions: Vec<ComponentFunction>,
326    /// React component props (reuses the shared `ComponentProp` struct). For
327    /// React, `used_in_template` is always false and `used_in_script` means
328    /// used-in-body. Empty for non-React files.
329    pub react_props: Vec<ComponentProp>,
330    /// React hook call sites (`useState` / `useEffect` / `useMemo` /
331    /// `useCallback` / custom `use*`). Drives hook-density complexity context.
332    /// Empty for non-React files.
333    pub hook_uses: Vec<HookUse>,
334    /// React render edges: one component rendering another. Captured with the
335    /// child's written name; child-to-`FileId` resolution is deferred to graph
336    /// build. Empty for non-React files.
337    pub render_edges: Vec<RenderEdge>,
338    /// Svelte custom events dispatched via `dispatch('<name>')` where `dispatch`
339    /// is the binding from `const dispatch = createEventDispatcher()`. Consumed
340    /// by the `unused-svelte-event` detector to flag an event dispatched here but
341    /// listened to nowhere project-wide. Each entry carries the literal event
342    /// name and its span. Empty for every non-Svelte file.
343    pub svelte_dispatched_events: Vec<DispatchedEvent>,
344    /// Svelte custom-event listener names harvested from template `on:<name>`
345    /// bindings on COMPONENT tags (PascalCase tag names). Lowercase DOM-element
346    /// `on:click` is a DOM event, not a custom event, and is excluded. Unioned
347    /// project-wide by the `unused-svelte-event` detector to build the liberal
348    /// "listened" set. Empty for every non-Svelte file.
349    pub svelte_listened_events: Vec<String>,
350    /// `true` when a `dispatch(<nonLiteral>)` call was seen (the dispatched event
351    /// name cannot be known statically), or the `dispatch` binding was used as a
352    /// whole value (passed / returned). The `unused-svelte-event` detector
353    /// abstains on the whole component so an event is never falsely flagged.
354    pub has_dynamic_dispatch: bool,
355}
356
357impl ModuleInfo {
358    /// A fully-zeroed `ModuleInfo` for the given file.
359    ///
360    /// Fixture builders and non-JS extraction paths start from this and set
361    /// only the fields they care about via struct-update syntax:
362    /// `ModuleInfo { exports: vec![..], ..ModuleInfo::empty(file_id) }`.
363    #[must_use]
364    pub fn empty(file_id: FileId) -> Self {
365        Self {
366            file_id,
367            exports: Arc::default(),
368            imports: Vec::new(),
369            re_exports: Vec::new(),
370            dynamic_imports: Vec::new(),
371            dynamic_import_patterns: Vec::new(),
372            require_calls: Vec::new(),
373            package_path_references: Box::default(),
374            member_accesses: Arc::default(),
375            semantic_facts: Arc::default(),
376            whole_object_uses: Arc::default(),
377            has_cjs_exports: false,
378            has_angular_component_template_url: false,
379            content_hash: 0,
380            suppressions: Vec::new(),
381            unknown_suppression_kinds: Vec::new(),
382            unused_import_bindings: Vec::new(),
383            type_referenced_import_bindings: Vec::new(),
384            value_referenced_import_bindings: Vec::new(),
385            line_offsets: Vec::new(),
386            complexity: Vec::new(),
387            flag_uses: Vec::new(),
388            class_heritage: Vec::new(),
389            exported_factory_returns: Arc::default(),
390            exported_factory_return_object_shapes: Arc::default(),
391            type_member_types: Arc::default(),
392            injection_tokens: Vec::new(),
393            local_type_declarations: Vec::new(),
394            public_signature_type_references: Vec::new(),
395            namespace_object_aliases: Vec::new(),
396            iconify_prefixes: Vec::new(),
397            iconify_icon_names: Vec::new(),
398            auto_import_candidates: Vec::new(),
399            directives: Vec::new(),
400            client_only_dynamic_import_spans: Vec::new(),
401            security_sinks: Vec::new(),
402            security_sinks_skipped: 0,
403            security_unresolved_callee_sites: Vec::new(),
404            tainted_bindings: Vec::new(),
405            sanitized_sink_args: Vec::new(),
406            security_control_sites: Vec::new(),
407            callee_uses: Vec::new(),
408            misplaced_directives: Vec::new(),
409            inline_server_action_exports: Vec::new(),
410            di_key_sites: Vec::new(),
411            has_dynamic_provide: false,
412            referenced_import_bindings: Vec::new(),
413            component_props: Vec::new(),
414            has_props_attrs_fallthrough: false,
415            has_define_expose: false,
416            has_define_model: false,
417            has_unharvestable_props: false,
418            component_emits: Vec::new(),
419            angular_inputs: Vec::new(),
420            angular_outputs: Vec::new(),
421            has_unharvestable_emits: false,
422            has_dynamic_emit: false,
423            has_emit_whole_object_use: false,
424            load_return_keys: Vec::new(),
425            has_unharvestable_load: false,
426            has_load_data_whole_use: false,
427            has_page_data_store_whole_use: false,
428            has_route_loader_data_whole_use: false,
429            component_functions: Vec::new(),
430            react_props: Vec::new(),
431            hook_uses: Vec::new(),
432            render_edges: Vec::new(),
433            svelte_dispatched_events: Vec::new(),
434            svelte_listened_events: Vec::new(),
435            angular_component_selectors: Vec::new(),
436            registered_custom_elements: Vec::new(),
437            used_custom_element_tags: Vec::new(),
438            angular_used_selectors: Vec::new(),
439            angular_entry_component_refs: Vec::new(),
440            has_dynamic_component_render: false,
441            has_dynamic_dispatch: false,
442        }
443    }
444
445    /// Derive compact detector facts from resolution payload before sharing.
446    ///
447    /// Shared analysis sessions keep the source payload for later graph runs,
448    /// but detectors still require the same derived facts that the owned
449    /// release path computes before clearing that payload.
450    #[doc(hidden)]
451    pub fn prepare_analysis_facts(&mut self) {
452        // The analyze-layer `unrendered-component` detector needs the compact
453        // complement of imports and unused bindings after resolution.
454        self.referenced_import_bindings = self
455            .imports
456            .iter()
457            .map(|import| import.local_name.clone())
458            .filter(|name| !name.is_empty() && !self.unused_import_bindings.contains(name))
459            .collect();
460        self.referenced_import_bindings.sort_unstable();
461        self.referenced_import_bindings.dedup();
462
463        // The `unused-load-data-key` detector needs the project-wide signal
464        // after `whole_object_uses` is released from owned artifacts.
465        self.has_page_data_store_whole_use = self
466            .whole_object_uses
467            .iter()
468            .any(|name| name == "page.data" || name == "$page.data");
469        self.has_route_loader_data_whole_use = self
470            .whole_object_uses
471            .iter()
472            .any(|name| name == "$fallow.routeLoaderData");
473    }
474
475    /// Release extraction payload that resolution has already copied into the graph.
476    ///
477    /// This keeps fields needed by analysis, health, security, LSP, coverage,
478    /// and hash drift checks, while dropping vectors that otherwise duplicate
479    /// data owned by `ResolvedModule` or already credited into the module graph.
480    pub fn release_resolution_payload(&mut self) {
481        self.prepare_analysis_facts();
482        Self::release_vec(&mut self.dynamic_imports);
483        Self::release_vec(&mut self.require_calls);
484        Self::release_boxed_slice(&mut self.package_path_references);
485        Self::release_arc_slice(&mut self.whole_object_uses);
486        Self::release_vec(&mut self.unused_import_bindings);
487        Self::release_vec(&mut self.type_referenced_import_bindings);
488        Self::release_vec(&mut self.value_referenced_import_bindings);
489        Self::release_vec(&mut self.namespace_object_aliases);
490        Self::release_vec(&mut self.auto_import_candidates);
491    }
492
493    fn release_vec<T>(values: &mut Vec<T>) {
494        *values = Vec::new();
495    }
496
497    fn release_boxed_slice<T>(values: &mut Box<[T]>) {
498        *values = Box::default();
499    }
500
501    /// Drop this module's refcount; the allocation itself is freed only once
502    /// the sharing `ResolvedModule` releases its clone too.
503    fn release_arc_slice<T>(values: &mut Arc<[T]>) {
504        *values = Arc::default();
505    }
506}
507
508/// Defensive control family detected on a source to sink path.
509#[derive(
510    Debug,
511    Clone,
512    Copy,
513    PartialEq,
514    Eq,
515    PartialOrd,
516    Ord,
517    serde::Serialize,
518    serde::Deserialize,
519    bitcode::Encode,
520    bitcode::Decode,
521)]
522#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
523#[serde(rename_all = "kebab-case")]
524pub enum SecurityControlKind {
525    /// Sanitization or escaping before a sink.
526    Sanitization,
527    /// Input validation or schema parsing.
528    Validation,
529    /// Authentication check or middleware.
530    Authentication,
531    /// Authorization or permission check.
532    Authorization,
533}
534
535/// A known defensive control call site.
536#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, bitcode::Encode, bitcode::Decode)]
537pub struct SecurityControlSite {
538    /// Control family.
539    pub kind: SecurityControlKind,
540    /// Flattened callee path or a stable synthetic name for guard-derived
541    /// controls.
542    pub callee_path: String,
543    /// Byte offset of the control span start.
544    pub span_start: u32,
545    /// Byte offset of the control span end.
546    pub span_end: u32,
547}
548
549/// Sanitizer output domain. Kept intentionally narrow so a sanitizer for one
550/// domain cannot suppress a different sink family.
551#[derive(
552    Debug,
553    Clone,
554    Copy,
555    PartialEq,
556    Eq,
557    PartialOrd,
558    Ord,
559    serde::Serialize,
560    serde::Deserialize,
561    bitcode::Encode,
562    bitcode::Decode,
563)]
564pub enum SanitizerScope {
565    /// HTML markup sanitized by DOMPurify-compatible APIs.
566    Html,
567    /// URL or redirect target checked against a literal-backed allowlist.
568    Url,
569    /// Path value checked against a high-confidence containment guard.
570    Path,
571    /// SQL identifier quoted with a helper that doubles embedded identifier quotes.
572    SqlIdentifier,
573}
574
575/// A captured sink argument that is itself a recognized sanitizer call.
576#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, bitcode::Encode, bitcode::Decode)]
577pub struct SanitizedSinkArg {
578    /// Byte offset of the owning sink span start.
579    pub span_start: u32,
580    /// The positional argument index on the owning sink.
581    pub arg_index: u32,
582    /// The sanitizer output domain for this argument.
583    pub scope: SanitizerScope,
584}
585
586/// A local binding tied to the flattened member-access path it was initialized
587/// from. The analyze layer matches `source_path` against the data-driven source
588/// catalogue; when it matches, `local` is treated as carrying untrusted input.
589///
590/// Captured for two shapes: a direct assignment (`const id = req.query.id` ->
591/// `{ local: "id", source_path: "req.query" }`, the literal-key tail dropped so
592/// the path matches a catalogue prefix) and an object destructure
593/// (`const { id } = req.query` -> `{ local: "id", source_path: "req.query" }`).
594#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, bitcode::Encode, bitcode::Decode)]
595pub struct TaintedBinding {
596    /// The local binding name introduced by the declarator.
597    pub local: String,
598    /// The flattened object member-access path the binding was sourced from.
599    pub source_path: String,
600    /// Byte offset of the source read (the member-access expression the binding
601    /// was sourced from), so the analyze layer can anchor a taint trace's source
602    /// node at the real read line instead of the module import line. Stored as a
603    /// `u32` (not `Span`) to stay bitcode-encodable for the cache. `0` when no
604    /// concrete read expression is available (synthetic framework-param /
605    /// helper-return bindings), in which case the analyze layer falls back to the
606    /// sink site rather than claiming a spurious line.
607    pub source_span_start: u32,
608}
609
610/// Why a sink-shaped callee could not be flattened into a static catalogue
611/// path.
612#[derive(
613    Debug,
614    Clone,
615    Copy,
616    PartialEq,
617    Eq,
618    PartialOrd,
619    Ord,
620    serde::Serialize,
621    serde::Deserialize,
622    bitcode::Encode,
623    bitcode::Decode,
624)]
625#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
626#[serde(rename_all = "kebab-case")]
627pub enum SkippedSecurityCalleeReason {
628    /// A computed member access such as `client[method](input)`.
629    ComputedMember,
630    /// A dynamic non-member callee such as `(factory())(input)`.
631    DynamicDispatch,
632    /// An assignment target whose object could not be flattened.
633    UnsupportedAssignmentObject,
634}
635
636/// Syntactic expression shape for a skipped security callee.
637#[derive(
638    Debug,
639    Clone,
640    Copy,
641    PartialEq,
642    Eq,
643    PartialOrd,
644    Ord,
645    serde::Serialize,
646    serde::Deserialize,
647    bitcode::Encode,
648    bitcode::Decode,
649)]
650#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
651#[serde(rename_all = "kebab-case")]
652pub enum SkippedSecurityCalleeExpressionKind {
653    /// `obj.prop(...)`.
654    StaticMemberExpression,
655    /// `obj[prop](...)`.
656    ComputedMemberExpression,
657    /// A bare identifier or private identifier callee.
658    Identifier,
659    /// Any other call-like expression that cannot be represented compactly.
660    Other,
661}
662
663/// Span-only diagnostic for a skipped security callee inside one module.
664#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, bitcode::Encode, bitcode::Decode)]
665pub struct SkippedSecurityCalleeSite {
666    /// Why the callee was skipped.
667    pub reason: SkippedSecurityCalleeReason,
668    /// Compact expression shape of the skipped callee.
669    pub expression_kind: SkippedSecurityCalleeExpressionKind,
670    /// Start byte offset of the skipped callee expression.
671    pub span_start: u32,
672    /// End byte offset of the skipped callee expression.
673    pub span_end: u32,
674}
675
676/// The syntactic shape of a captured security sink site. Category-blind: the
677/// extractor records the shape and the dotted/bare callee path; the analyze
678/// layer matches it against the data-driven catalogue. See
679/// `crates/security/data/security_matchers.toml`.
680#[derive(
681    Debug,
682    Clone,
683    Copy,
684    PartialEq,
685    Eq,
686    serde::Serialize,
687    serde::Deserialize,
688    bitcode::Encode,
689    bitcode::Decode,
690)]
691pub enum SinkShape {
692    /// A call to a bare identifier (e.g. `eval(x)`).
693    Call,
694    /// A call to a dotted member path (e.g. `child_process.exec(x)`).
695    MemberCall,
696    /// An assignment to a member target (e.g. `el.innerHTML = x`).
697    MemberAssign,
698    /// A tagged template expression (e.g. ``sql`...${x}...` ``).
699    TaggedTemplate,
700    /// A JSX attribute value (e.g. `dangerouslySetInnerHTML={x}`).
701    JsxAttr,
702    /// A constructor call (e.g. `new Function("return x")`).
703    NewExpression,
704    /// A static string literal assigned to a secret-shaped identifier or known
705    /// provider credential prefix.
706    SecretLiteral,
707}
708
709/// The shape of the argument captured at a sink site. Category-blind like
710/// [`SinkShape`], but finer-grained: it lets the catalogue matcher require or
711/// exclude specific argument shapes. The discriminator is what distinguishes an
712/// unsafe SQL string concatenation or template-into-`.execute()` from a
713/// safely-parameterized `` sql`${x}` `` tagged template, an object-literal
714/// `.execute({ sql, args })` argument, or a literal-aware sink argument.
715#[derive(
716    Debug,
717    Clone,
718    Copy,
719    PartialEq,
720    Eq,
721    serde::Serialize,
722    serde::Deserialize,
723    bitcode::Encode,
724    bitcode::Decode,
725)]
726pub enum SinkArgKind {
727    /// A template literal with at least one `${...}` substitution (e.g.
728    /// `` `SELECT ${x}` ``). On a `tagged-template` shape this is the tag's
729    /// quasi; on a `call`/`member-call` shape it is the positional argument.
730    TemplateWithSubst,
731    /// A binary `+` string concatenation (e.g. `"SELECT " + x`).
732    Concat,
733    /// An object literal (e.g. `.execute({ sql, args })`, the parameterized form).
734    Object,
735    /// A call expression argument (e.g. `query(buildSql())`).
736    Call,
737    /// A literal argument admitted by a literal-aware security matcher.
738    Literal,
739    /// A zero-argument sink captured because the callee itself is the signal.
740    NoArg,
741    /// Any other non-literal expression (bare identifier, member access, etc.).
742    Other,
743}
744
745/// Static URL construction shape captured for URL-shaped security sinks.
746#[derive(
747    Debug,
748    Clone,
749    Copy,
750    PartialEq,
751    Eq,
752    serde::Serialize,
753    serde::Deserialize,
754    bitcode::Encode,
755    bitcode::Decode,
756)]
757#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
758#[serde(rename_all = "kebab-case")]
759pub enum SecurityUrlShape {
760    /// The sink target has a fixed origin, scheme, or relative root while only
761    /// path or query components are dynamic.
762    FixedOriginDynamicPath,
763    /// The sink target's scheme or origin is dynamic or opaque.
764    DynamicOrigin,
765}
766
767/// Literal values attached to literal-aware security sink captures.
768#[derive(
769    Debug,
770    Clone,
771    PartialEq,
772    Eq,
773    serde::Serialize,
774    serde::Deserialize,
775    bitcode::Encode,
776    bitcode::Decode,
777)]
778pub enum SinkLiteralValue {
779    /// A string literal value.
780    String(String),
781    /// An integer numeric literal value.
782    Integer(i64),
783    /// A boolean literal value.
784    Boolean(bool),
785    /// A null literal value.
786    Null,
787}
788
789/// Static object-literal property metadata attached to a captured sink
790/// argument. Nested object paths are flattened with dot-separated keys.
791#[derive(
792    Debug,
793    Clone,
794    PartialEq,
795    Eq,
796    serde::Serialize,
797    serde::Deserialize,
798    bitcode::Encode,
799    bitcode::Decode,
800)]
801pub struct SinkObjectProperty {
802    /// Static property name. Nested object properties use dot-separated paths.
803    pub key: String,
804    /// Literal property value when statically knowable.
805    pub value: SinkLiteralValue,
806}
807
808/// A captured sink site. The visitor records every existing non-literal call /
809/// member-assign / member-call / tagged-template / jsx-attr sink site, and a
810/// small allowlist of literal-aware sites where the literal value is the signal.
811/// It knows nothing about CWE categories.
812#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, bitcode::Encode, bitcode::Decode)]
813pub struct SinkSite {
814    /// The syntactic shape of the sink site.
815    pub sink_shape: SinkShape,
816    /// The flattened dotted/bare callee or member path.
817    pub callee_path: String,
818    /// The positional argument index. For zero-argument captures this is 0.
819    pub arg_index: u32,
820    /// Whether the relevant argument is non-literal. Existing non-literal
821    /// catalogue rows require this to remain true.
822    pub arg_is_non_literal: bool,
823    /// The finer-grained shape of the captured argument. Lets the catalogue
824    /// require unsafe shapes (concat / template-with-substitution / literal /
825    /// no-arg) and exclude safe ones (object literal, the parameterized form).
826    /// See [`SinkArgKind`].
827    pub arg_kind: SinkArgKind,
828    /// Literal argument value for literal-aware rows.
829    pub arg_literal: Option<SinkLiteralValue>,
830    /// Risky regex fragment for structural ReDoS candidates.
831    pub regex_pattern: Option<String>,
832    /// Static object-literal properties for option-object rows.
833    pub object_properties: Vec<SinkObjectProperty>,
834    /// Static top-level object-literal keys, including keys whose values are not
835    /// literal. Used by missing-option rows that only need key presence.
836    pub object_property_keys: Vec<String>,
837    /// Whether [`object_property_keys`](Self::object_property_keys) is complete.
838    /// False for non-object arguments and object literals with spread or
839    /// non-static keys, where a missing-key claim would be speculative.
840    pub object_property_keys_complete: bool,
841    /// Identifier names referenced anywhere inside the captured non-literal sink
842    /// argument, or contextual names for zero-argument captures such as a
843    /// token-like `Math.random()` assignment target. Deduped in source order.
844    /// Used by the analyze layer to back-trace the sink argument to a known
845    /// untrusted source or to apply narrow context gates. Intra-module,
846    /// name-based, conservative; it is never a taint proof.
847    pub arg_idents: Vec<String>,
848    /// Flattened static member paths referenced inside the captured non-literal
849    /// sink argument. Includes both the full path and source-object path for
850    /// leaf reads (`process.env.SECRET` records `process.env.SECRET` and
851    /// `process.env`) so direct source expressions can be matched without an
852    /// intermediate local binding.
853    pub arg_source_paths: Vec<String>,
854    /// Byte offset of the sink span start. Stored as `u32` (not `Span`) so the
855    /// struct is bitcode-encodable and can be persisted directly in the cache.
856    pub span_start: u32,
857    /// Byte offset of the sink span end.
858    pub span_end: u32,
859    /// The arg-0 URL string literal of a network-shaped call (`fetch`, `axios.*`,
860    /// `got`, ...), captured so the `secret-to-network` category (#890) can carry
861    /// a destination-host signal on its candidate: `Some(literal)` when the
862    /// destination is a static string literal (almost always intended auth, e.g.
863    /// the credential's own provider), `None` when it is dynamic (the suspicious
864    /// case). `None` for non-call sinks and calls with no arg 0.
865    pub url_arg_literal: Option<String>,
866    /// URL construction shape for URL-like sink arguments when the extractor can
867    /// classify it syntactically. `None` for non-URL sinks and URL expressions
868    /// whose shape is not visible at the sink.
869    pub url_shape: Option<SecurityUrlShape>,
870}
871
872impl SinkSite {
873    /// Reconstruct the source span from the stored byte offsets.
874    #[must_use]
875    pub fn span(&self) -> Span {
876        Span::new(self.span_start, self.span_end)
877    }
878}
879
880/// Env var-name prefixes that frameworks inline into the client bundle by
881/// convention. A read of one of these is normal and safe, so it does NOT count
882/// as a secret source (issue #890). Shared by the extract layer (so public env
883/// vars never become source signals) and the bespoke `client-server-leak` rule.
884pub const PUBLIC_ENV_PREFIXES: &[&str] = &[
885    "NEXT_PUBLIC_",
886    "VITE_",
887    "NUXT_PUBLIC_",
888    "REACT_APP_",
889    "PUBLIC_",
890    "GATSBY_",
891    "EXPO_PUBLIC_",
892    "STORYBOOK_",
893];
894
895/// Exact env var names that are public by convention (no prefix).
896pub const PUBLIC_ENV_EXACT: &[&str] = &["NODE_ENV"];
897
898/// Env var-name tokens that usually describe public build or deployment
899/// metadata rather than secrets. Secret-shaped names win over these tokens.
900pub const PUBLIC_ENV_METADATA_TOKENS: &[&str] =
901    &["BRANCH", "ENVIRONMENT", "MODE", "REF", "SHA", "TAG"];
902
903/// Env var-name tokens that should keep a variable source-backed even when the
904/// name also contains public metadata tokens such as `REF` or `SHA`.
905pub const SECRET_ENV_TOKENS: &[&str] = &[
906    "AUTH",
907    "CREDENTIAL",
908    "CREDENTIALS",
909    "KEY",
910    "PASS",
911    "PASSWORD",
912    "PRIVATE",
913    "SECRET",
914    "TOKEN",
915];
916
917fn env_name_has_token(name: &str, tokens: &[&str]) -> bool {
918    name.split(|ch: char| !ch.is_ascii_alphanumeric())
919        .filter(|part| !part.is_empty())
920        .any(|part| tokens.contains(&part))
921}
922
923/// Whether an env var name is public-by-convention (build-inlined into the
924/// client bundle), and therefore not a secret.
925#[must_use]
926pub fn is_public_env_var(name: &str) -> bool {
927    if PUBLIC_ENV_EXACT.contains(&name) || PUBLIC_ENV_PREFIXES.iter().any(|p| name.starts_with(p)) {
928        return true;
929    }
930    env_name_has_token(name, PUBLIC_ENV_METADATA_TOKENS)
931        && !env_name_has_token(name, SECRET_ENV_TOKENS)
932}
933
934/// Whether a flattened member path is a PUBLIC env-secret read
935/// (`process.env.NEXT_PUBLIC_X`, `import.meta.env.VITE_Y`), which must not be
936/// recorded as a secret source. Non-env paths (`req.query.id`) are never public.
937#[must_use]
938pub fn is_public_env_path(path: &str) -> bool {
939    for object in ["process.env.", "import.meta.env."] {
940        if let Some(var) = path.strip_prefix(object) {
941            return is_public_env_var(var);
942        }
943    }
944    false
945}
946
947/// One alias entry tying an exported object's dotted property path to a namespace import.
948#[derive(Debug, Clone)]
949pub struct NamespaceObjectAlias {
950    /// Canonical export name.
951    pub via_export_name: String,
952    /// Dotted suffix of the property path relative to the export.
953    pub suffix: String,
954    /// Local name of the namespace import.
955    pub namespace_local: String,
956}
957
958/// Compute a table of line-start byte offsets from source text.
959#[must_use]
960#[expect(
961    clippy::cast_possible_truncation,
962    reason = "source files are practically < 4GB"
963)]
964pub fn compute_line_offsets(source: &str) -> Vec<u32> {
965    let mut offsets = vec![0u32];
966    for (i, byte) in source.bytes().enumerate() {
967        if byte == b'\n' {
968            debug_assert!(
969                u32::try_from(i + 1).is_ok(),
970                "source file exceeds u32::MAX bytes: line offsets would overflow"
971            );
972            offsets.push((i + 1) as u32);
973        }
974    }
975    offsets
976}
977
978/// Convert a byte offset to a 1-based line number and 0-based byte column.
979#[must_use]
980#[expect(
981    clippy::cast_possible_truncation,
982    reason = "line count is bounded by source size"
983)]
984pub fn byte_offset_to_line_col(line_offsets: &[u32], byte_offset: u32) -> (u32, u32) {
985    let line_idx = match line_offsets.binary_search(&byte_offset) {
986        Ok(idx) => idx,
987        Err(idx) => idx.saturating_sub(1),
988    };
989    let line = line_idx as u32 + 1;
990    let col = byte_offset - line_offsets[line_idx];
991    (line, col)
992}
993
994/// True when `name` identifies a synthetic template-family complexity unit:
995/// the per-file `<template>` unit every framework template scanner emits, or a
996/// Svelte `<snippet:NAME>` unit. These units are exercised only through their
997/// component, carry no directly measurable test coverage, and are therefore
998/// excluded from the CRAP dimension. The `<component>` rollup is NOT part of
999/// this family: it is an aggregate over class + template findings, not an
1000/// extracted unit.
1001#[must_use]
1002pub fn is_synthetic_template_unit(name: &str) -> bool {
1003    name == "<template>" || name.starts_with("<snippet:")
1004}
1005
1006/// Complexity metrics for a single function/method/arrow.
1007#[derive(Debug, Clone, serde::Serialize, bitcode::Encode, bitcode::Decode)]
1008pub struct FunctionComplexity {
1009    /// Function name (or `"<anonymous>"` for unnamed functions/arrows).
1010    pub name: String,
1011    /// 1-based line number where the function starts.
1012    pub line: u32,
1013    /// 0-based byte column where the function starts.
1014    pub col: u32,
1015    /// `McCabe` cyclomatic complexity (1 + decision points).
1016    pub cyclomatic: u16,
1017    /// `SonarSource` cognitive complexity (structural + nesting penalty).
1018    pub cognitive: u16,
1019    /// Number of lines in the function body.
1020    pub line_count: u32,
1021    /// Number of parameters (excluding TypeScript's `this` parameter).
1022    pub param_count: u8,
1023    /// Number of React hook calls (`useState` / `useEffect` / `useMemo` /
1024    /// `useCallback` / custom `use*`) made directly in this function's body.
1025    /// Non-zero only for React components/hooks; descriptive context surfaced in
1026    /// the hotspot drill-down, never a tunable threshold (anti-numerology).
1027    pub react_hook_count: u16,
1028    /// Maximum JSX element nesting depth reached in this function's body (the
1029    /// deepest chain of element-inside-element). `0` when the function renders
1030    /// no JSX. Descriptive context surfaced in the hotspot drill-down, never a
1031    /// tunable threshold (anti-numerology).
1032    pub react_jsx_max_depth: u16,
1033    /// Number of props destructured from this component's first parameter (the
1034    /// `{ a, b, c }` props object). `0` for non-component functions and for
1035    /// components taking a bare `props` identifier (not statically countable).
1036    /// Descriptive context surfaced in the hotspot drill-down, never a tunable
1037    /// threshold (anti-numerology).
1038    pub react_prop_count: u16,
1039    /// Content digest of the function's full-span source slice.
1040    pub source_hash: Option<String>,
1041    /// Per-decision-point breakdown explaining WHICH constructs drove the
1042    /// cyclomatic and cognitive scores. One entry per increment event (an `if`
1043    /// emits one cyclomatic and one cognitive entry at the same line, because
1044    /// the two metrics accrue at different granularities). Always computed and
1045    /// cached; surfaced in JSON only behind `health --complexity-breakdown`.
1046    pub contributions: Vec<ComplexityContribution>,
1047}
1048
1049/// Structural CSS metrics for a single style rule, computed from the parsed CSS
1050/// syntax tree. A rule is recorded only when it crosses a structural floor (an
1051/// id selector, a complex selector, a `!important` declaration, or deep
1052/// nesting), so the vector stays bounded on normal stylesheets.
1053///
1054/// Not persisted in the extraction cache: `fallow health` computes these
1055/// on demand from the CSS source, so there is no `bitcode` derive.
1056#[derive(Debug, Clone, serde::Serialize)]
1057#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1058pub struct CssRuleMetric {
1059    /// 1-based line of the rule's first selector.
1060    pub line: u32,
1061    /// 1-based column of the rule's first selector.
1062    pub col: u32,
1063    /// Specificity component `a` (id selectors), max across the rule's selectors.
1064    pub specificity_a: u16,
1065    /// Specificity component `b` (class / attribute / pseudo-class selectors).
1066    pub specificity_b: u16,
1067    /// Specificity component `c` (type / pseudo-element selectors).
1068    pub specificity_c: u16,
1069    /// Largest selector component count across the rule's selector list.
1070    pub complexity: u16,
1071    /// Declaration count in the rule (normal plus `!important`).
1072    pub declaration_count: u16,
1073    /// `!important` declaration count in the rule.
1074    pub important_count: u16,
1075    /// Style-rule nesting depth (0 = top level).
1076    pub nesting_depth: u8,
1077}
1078
1079/// A style rule's declaration-block fingerprint and location, for cross-file
1080/// duplicate-block detection. Only rules with a meaningful number of
1081/// declarations are recorded (small blocks repeat legitimately). Internal
1082/// staging only: this is consumed in-process by the health layer to build the
1083/// grouped `duplicate_declaration_blocks` output and is never serialized.
1084#[derive(Debug, Clone)]
1085pub struct CssDeclarationBlock {
1086    /// xxh3 fingerprint over the rule's normalized (sorted, `!important`-tagged)
1087    /// declaration set.
1088    pub fingerprint: u64,
1089    /// 1-based line of the rule's first selector.
1090    pub line: u32,
1091    /// Declaration count in the rule (normal plus `!important`).
1092    pub declaration_count: u16,
1093}
1094
1095/// Located raw styling value authored directly in CSS rather than via a
1096/// custom property or design-token helper. Internal staging for the health
1097/// layer; public output adds actions and confidence.
1098#[derive(Debug, Clone, PartialEq, Eq)]
1099pub struct CssRawStyleValue {
1100    /// Value axis, e.g. `color`, `font-size`, `line-height`, `radius`, or `shadow`.
1101    pub axis: String,
1102    /// CSS property where the value appears.
1103    pub property: String,
1104    /// Rendered declaration value.
1105    pub value: String,
1106    /// 1-based line of the containing style rule.
1107    pub line: u32,
1108}
1109
1110/// Located CSS custom-property definition with its rendered value. Internal
1111/// staging for design-token reuse suggestions in the health layer.
1112#[derive(Debug, Clone, PartialEq, Eq)]
1113pub struct CssCustomPropertyDefinition {
1114    /// Custom property name, including the leading `--`.
1115    pub name: String,
1116    /// Rendered custom property value.
1117    pub value: String,
1118    /// 1-based line of the containing style rule.
1119    pub line: u32,
1120}
1121
1122/// Stylesheet-level structural CSS analytics, computed from the parsed CSS
1123/// syntax tree. Feeds `fallow health` penalty weights and located findings,
1124/// never a standalone CSS score.
1125#[derive(Debug, Clone, Default, serde::Serialize)]
1126#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1127pub struct CssAnalytics {
1128    /// Total declarations across every style rule (normal plus `!important`).
1129    pub total_declarations: u32,
1130    /// Total `!important` declarations across every style rule.
1131    pub important_declarations: u32,
1132    /// Number of style rules.
1133    pub rule_count: u32,
1134    /// Number of style rules with no declarations.
1135    pub empty_rule_count: u32,
1136    /// Deepest style-rule nesting depth observed (0 = no nesting).
1137    pub max_nesting_depth: u8,
1138    /// Rules that crossed the structural floor, in source order. Bounded; see
1139    /// [`Self::notable_truncated`]. The scalar aggregates above always reflect
1140    /// the full stylesheet regardless of truncation.
1141    pub notable_rules: Vec<CssRuleMetric>,
1142    /// `true` when more rules crossed the structural floor than `notable_rules`
1143    /// retains (compiled utility CSS can emit thousands of `!important` rules),
1144    /// so consumers can note that per-rule findings were capped.
1145    pub notable_truncated: bool,
1146    /// Distinct color VALUES in the stylesheet, sorted (a palette-size /
1147    /// design-token-sprawl signal). The parser canonicalizes notation, so the
1148    /// authored format is NOT preserved: `red`, `#f00`, `#ff0000`, and
1149    /// `rgb(255,0,0)` all collapse to one entry, and every legacy sRGB notation
1150    /// renders as hex. Notation-MIXING (hex vs rgb vs hsl) is therefore not
1151    /// detectable from this set; it would need a separate raw-token pass.
1152    pub colors: Vec<String>,
1153    /// Distinct `font-size` declaration values in the stylesheet, sorted.
1154    pub font_sizes: Vec<String>,
1155    /// Distinct `z-index` declaration values in the stylesheet, sorted.
1156    pub z_indexes: Vec<String>,
1157    /// Distinct `box-shadow` declaration values in the stylesheet, sorted. A
1158    /// high count signals an uncontrolled shadow scale (design-token sprawl).
1159    pub box_shadows: Vec<String>,
1160    /// Distinct `border-radius` declaration values in the stylesheet, sorted.
1161    pub border_radii: Vec<String>,
1162    /// Distinct `line-height` declaration values in the stylesheet, sorted.
1163    pub line_heights: Vec<String>,
1164    /// Bounded located raw styling values that bypass custom properties or
1165    /// token helpers. These are conservative declaration-level candidates for
1166    /// audit introduced-vs-base gating.
1167    #[serde(skip)]
1168    #[cfg_attr(feature = "schema", schemars(skip))]
1169    pub raw_style_values: Vec<CssRawStyleValue>,
1170    /// Located custom-property definitions with values. Internal staging
1171    /// consumed by the health layer for nearest-token suggestions.
1172    #[serde(skip)]
1173    #[cfg_attr(feature = "schema", schemars(skip))]
1174    pub custom_property_definitions: Vec<CssCustomPropertyDefinition>,
1175    /// Distinct custom properties (`--x`) DEFINED in the stylesheet, sorted.
1176    pub defined_custom_properties: Vec<String>,
1177    /// Distinct custom properties REFERENCED via `var()` in the stylesheet.
1178    pub referenced_custom_properties: Vec<String>,
1179    /// Distinct `@keyframes` names DEFINED in the stylesheet, sorted.
1180    pub defined_keyframes: Vec<String>,
1181    /// Distinct `@keyframes` names REFERENCED via `animation` / `animation-name`.
1182    pub referenced_keyframes: Vec<String>,
1183    /// Distinct custom properties REGISTERED via an `@property` rule, sorted.
1184    pub registered_custom_properties: Vec<String>,
1185    /// Distinct cascade layers DECLARED (via `@layer a, b;` statements or named
1186    /// `@layer a { }` blocks), sorted.
1187    pub declared_layers: Vec<String>,
1188    /// Distinct cascade layers POPULATED by a named `@layer a { }` block, sorted.
1189    /// A layer declared but never populated (and not imported into) is a
1190    /// cleanup candidate.
1191    pub populated_layers: Vec<String>,
1192    /// Distinct font families DECLARED by an `@font-face` rule in the stylesheet,
1193    /// sorted. A declared family referenced by no `font-family` anywhere is a
1194    /// dead web-font payload (cleanup candidate).
1195    pub defined_font_faces: Vec<String>,
1196    /// Distinct font families REFERENCED via `font-family` / `font` in the
1197    /// stylesheet, sorted (generic keywords like `serif` excluded).
1198    pub referenced_font_families: Vec<String>,
1199    /// Per-rule declaration-block fingerprints for rules at or above the minimum
1200    /// block size, used to detect duplicate declaration blocks across the
1201    /// project. Internal staging consumed by the health layer; never serialized
1202    /// (the public output is the grouped `duplicate_declaration_blocks`).
1203    #[serde(skip)]
1204    #[cfg_attr(feature = "schema", schemars(skip))]
1205    pub declaration_blocks: Vec<CssDeclarationBlock>,
1206}
1207
1208/// Which complexity metric a [`ComplexityContribution`] adds to.
1209#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
1210#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1211#[serde(rename_all = "kebab-case")]
1212pub enum ComplexityMetric {
1213    /// `McCabe` cyclomatic complexity (independent execution paths).
1214    Cyclomatic,
1215    /// `SonarSource` cognitive complexity (structural + nesting penalty).
1216    Cognitive,
1217}
1218
1219/// The syntactic construct that produced a single complexity increment.
1220///
1221/// Mirrors `SonarSource` cognitive-complexity vocabulary where it overlaps.
1222/// `Case` means a `case` label carrying a test; a bare `default` adds nothing
1223/// to cyclomatic complexity and so produces no contribution.
1224#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
1225#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1226#[serde(rename_all = "kebab-case")]
1227#[non_exhaustive]
1228pub enum ComplexityContributionKind {
1229    /// An `if` condition.
1230    If,
1231    /// A bare `else` branch (cognitive only).
1232    Else,
1233    /// An `else if` continuation (both metrics: cyclomatic +1, cognitive flat
1234    /// +1 with no nesting penalty).
1235    ElseIf,
1236    /// A `?:` conditional (ternary) expression.
1237    Ternary,
1238    /// A logical `&&` operator.
1239    LogicalAnd,
1240    /// A logical `||` operator.
1241    LogicalOr,
1242    /// A `??` nullish-coalescing operator.
1243    NullishCoalescing,
1244    /// A logical assignment operator (`&&=`, `||=`, `??=`); cyclomatic only.
1245    LogicalAssignment,
1246    /// An optional-chaining link (`?.`); cyclomatic only.
1247    OptionalChain,
1248    /// A `for` loop.
1249    For,
1250    /// A `for...in` loop.
1251    ForIn,
1252    /// A `for...of` loop.
1253    ForOf,
1254    /// A `while` loop.
1255    While,
1256    /// A `do...while` loop.
1257    DoWhile,
1258    /// A `switch` statement (cognitive only; each `case` adds cyclomatic).
1259    Switch,
1260    /// A `case` label carrying a test (cyclomatic only).
1261    Case,
1262    /// A `catch` clause.
1263    Catch,
1264    /// A labeled `break` (cognitive only).
1265    LabeledBreak,
1266    /// A labeled `continue` (cognitive only).
1267    LabeledContinue,
1268    /// Legacy JSX-depth contribution kind kept for schema compatibility. Current
1269    /// extraction records JSX nesting as descriptive `react_jsx_max_depth`
1270    /// context and does not emit this kind for layout depth.
1271    JsxDepth,
1272    /// React hook density (cognitive only). One contribution per hook call in a
1273    /// component body (`useState` / `useEffect` / `useMemo` / `useCallback` /
1274    /// custom `use*`); a hook-heavy component accrues cognitive load the same way
1275    /// branching does.
1276    HookDensity,
1277    /// React prop count past the comfortable floor (cognitive only). A component
1278    /// destructuring many props is doing many things; the props beyond the floor
1279    /// fold into cognitive so a wide-interface component surfaces as a hotspot.
1280    PropCount,
1281    /// A Svelte `{#await}` block.
1282    Await,
1283    /// A Svelte `{:then}` continuation.
1284    Then,
1285}
1286
1287/// A single complexity increment, located at its source line/column.
1288///
1289/// `weight` is the amount this construct added to `metric`; for nested
1290/// cognitive increments `weight == 1 + nesting`. Consumers that render inline
1291/// (the VS Code editor breakdown) group contributions by `line` and sum the
1292/// weights, deferring the per-kind list to a hover.
1293#[derive(Debug, Clone, serde::Serialize, bitcode::Encode, bitcode::Decode)]
1294#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1295pub struct ComplexityContribution {
1296    /// 1-based line number where the construct begins.
1297    pub line: u32,
1298    /// 0-based byte column where the construct begins.
1299    pub col: u32,
1300    /// Which metric this increment contributes to.
1301    pub metric: ComplexityMetric,
1302    /// The syntactic construct responsible for the increment.
1303    pub kind: ComplexityContributionKind,
1304    /// The amount added to `metric` at this site (`1 + nesting` for nested
1305    /// cognitive increments, otherwise `1`).
1306    pub weight: u16,
1307    /// The nesting depth at the increment site (`0` when not nested). Lets a
1308    /// consumer explain a cognitive `+3` as "+1 base, +2 nesting".
1309    pub nesting: u16,
1310}
1311
1312/// The kind of feature flag pattern detected.
1313#[derive(Debug, Clone, Copy, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
1314pub enum FlagUseKind {
1315    /// `process.env.FEATURE_X` pattern.
1316    EnvVar,
1317    /// SDK function call like `useFlag('name')`.
1318    SdkCall,
1319    /// Config object access like `config.features.x`.
1320    ConfigObject,
1321}
1322
1323/// A feature flag use site.
1324#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode)]
1325pub struct FlagUse {
1326    /// Flag identifier.
1327    pub flag_name: String,
1328    /// Detection kind.
1329    pub kind: FlagUseKind,
1330    /// 1-based line number.
1331    pub line: u32,
1332    /// 0-based byte column offset.
1333    pub col: u32,
1334    /// Start byte offset of the guarded block.
1335    pub guard_span_start: Option<u32>,
1336    /// End byte offset of the guarded block.
1337    pub guard_span_end: Option<u32>,
1338    /// SDK/provider name.
1339    pub sdk_name: Option<String>,
1340}
1341
1342const _: () = assert!(std::mem::size_of::<FlagUse>() <= 96);
1343
1344/// The runtime mechanism used to load a module.
1345#[derive(
1346    Debug,
1347    Clone,
1348    Copy,
1349    PartialEq,
1350    Eq,
1351    Hash,
1352    serde::Serialize,
1353    serde::Deserialize,
1354    bitcode::Encode,
1355    bitcode::Decode,
1356)]
1357#[repr(u8)]
1358pub enum ModuleLoadMechanism {
1359    /// ECMAScript module loading through imports, re-exports, or import globs.
1360    EsModule = 0,
1361    /// CommonJS module loading through `require()` or `require.context`.
1362    CommonJsRequire = 1,
1363}
1364
1365/// A dynamic import with a partially resolved pattern.
1366#[derive(Debug, Clone)]
1367pub struct DynamicImportPattern {
1368    /// Static prefix of the import path (e.g., "./locales/"). May contain glob characters.
1369    pub prefix: String,
1370    /// Static suffix of the import path (e.g., ".json"), if any.
1371    pub suffix: Option<String>,
1372    /// Source span in the original file.
1373    pub span: Span,
1374    /// Runtime mechanism used to load modules matching this pattern.
1375    pub mechanism: ModuleLoadMechanism,
1376}
1377
1378/// Visibility tag from JSDoc/TSDoc comments that suppresses unused-export detection.
1379#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
1380#[serde(rename_all = "lowercase")]
1381#[repr(u8)]
1382pub enum VisibilityTag {
1383    /// No visibility tag present.
1384    #[default]
1385    None = 0,
1386    /// `@public` or `@api public` -- part of the public API surface.
1387    Public = 1,
1388    /// `@internal` -- exported for internal use (sister packages, build tools).
1389    Internal = 2,
1390    /// `@beta` -- public but unstable, may change without notice.
1391    Beta = 3,
1392    /// `@alpha` -- early preview, may change drastically without notice.
1393    Alpha = 4,
1394    /// `@expected-unused` -- intentionally unused, should warn when it becomes used.
1395    ExpectedUnused = 5,
1396}
1397
1398impl VisibilityTag {
1399    /// Whether this tag permanently suppresses unused-export detection.
1400    /// `ExpectedUnused` is handled separately (conditionally suppresses,
1401    /// reports stale when the export becomes used).
1402    pub const fn suppresses_unused(self) -> bool {
1403        matches!(
1404            self,
1405            Self::Public | Self::Internal | Self::Beta | Self::Alpha
1406        )
1407    }
1408
1409    /// For serde `skip_serializing_if`.
1410    pub fn is_none(&self) -> bool {
1411        matches!(self, Self::None)
1412    }
1413}
1414
1415/// An export declaration.
1416#[derive(Debug, Clone, serde::Serialize)]
1417pub struct ExportInfo {
1418    /// The exported name (named or default).
1419    pub name: ExportName,
1420    /// The local binding name, if different from the exported name.
1421    pub local_name: Option<String>,
1422    /// Whether this is a type-only export (`export type`).
1423    pub is_type_only: bool,
1424    /// Whether this export is registered through a runtime side effect at module load time.
1425    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1426    pub is_side_effect_used: bool,
1427    /// Visibility tag from JSDoc/TSDoc comment.
1428    #[serde(default, skip_serializing_if = "VisibilityTag::is_none")]
1429    pub visibility: VisibilityTag,
1430    /// Human-authored reason on `@expected-unused -- <reason>`, when present.
1431    #[serde(default, skip_serializing_if = "Option::is_none")]
1432    pub expected_unused_reason: Option<String>,
1433    /// Source span of the export declaration.
1434    #[serde(serialize_with = "serialize_span")]
1435    pub span: Span,
1436    /// Members of this export (for enums, classes, and namespaces).
1437    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1438    pub members: Vec<MemberInfo>,
1439    /// The local name of the parent class from `extends` clause, if any.
1440    #[serde(default, skip_serializing_if = "Option::is_none")]
1441    pub super_class: Option<String>,
1442}
1443
1444/// Additional heritage metadata for an exported class.
1445#[derive(
1446    Debug,
1447    Clone,
1448    serde::Serialize,
1449    serde::Deserialize,
1450    bitcode::Encode,
1451    bitcode::Decode,
1452    PartialEq,
1453    Eq,
1454)]
1455pub struct ClassHeritageInfo {
1456    /// Export name (`default` for default-exported classes).
1457    pub export_name: String,
1458    /// Parent class name from the `extends` clause, if any.
1459    pub super_class: Option<String>,
1460    /// Interface names from the class `implements` clause.
1461    pub implements: Vec<String>,
1462    /// Ordered class type-parameter names used to compose concrete arguments
1463    /// through multi-hop inheritance.
1464    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1465    pub type_parameters: Vec<String>,
1466    /// Typed instance bindings used to resolve member-access chains in external templates.
1467    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1468    pub instance_bindings: Vec<(String, String)>,
1469    /// Positional type arguments on the `extends` clause (the `<DerivedClient>`
1470    /// in `extends BaseService<DerivedClient>`); an empty string marks a
1471    /// positional arg that is not a plain type reference. Lets the analyze layer
1472    /// substitute a base class's generic instance-binding field type with the
1473    /// subclass's concrete type argument (issue #1910).
1474    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1475    pub super_class_type_args: Vec<String>,
1476    /// Instance-binding fields whose annotation is exactly a class type
1477    /// parameter, as `(field_name, type_param_index)`. Lets an inherited generic
1478    /// property resolve to the subclass's concrete type argument rather than the
1479    /// constraint (issue #1910).
1480    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1481    pub generic_instance_bindings: Vec<(String, usize)>,
1482}
1483
1484/// An exported free-function factory proven to return one class instance.
1485///
1486/// `export function useApi() { return new RESTApi() }` records
1487/// `FactoryReturnExport { export_name: "useApi", class_local_name: "RESTApi" }`.
1488/// The `class_local_name` is the factory module's own LOCAL name, resolved at
1489/// analyze time through that module's imports/exports to the real class export,
1490/// so a cross-module `const x = useApi(); x.member` consumer credits the class
1491/// across the boundary. See issue #1441 (Part A).
1492#[derive(
1493    Debug,
1494    Clone,
1495    serde::Serialize,
1496    serde::Deserialize,
1497    bitcode::Encode,
1498    bitcode::Decode,
1499    PartialEq,
1500    Eq,
1501)]
1502pub struct FactoryReturnExport {
1503    /// Public export name (honors `export { useApi as useRestApi }`).
1504    pub export_name: String,
1505    /// The returned class's local name within the factory module.
1506    pub class_local_name: String,
1507}
1508
1509/// One resolved property of an object-literal factory return: a dotted property
1510/// path mapped to the class the value at that path is an instance of.
1511///
1512/// `return { invoke: { orders: factory.ordersPage } }` records
1513/// `{ property_path: "invoke.orders", class_local_name: "OrdersPage" }`. The class
1514/// name is the factory module's own LOCAL name, resolved at analyze time through the
1515/// factory module's imports to the real class export. See issue #1858.
1516#[derive(
1517    Debug,
1518    Clone,
1519    serde::Serialize,
1520    serde::Deserialize,
1521    bitcode::Encode,
1522    bitcode::Decode,
1523    PartialEq,
1524    Eq,
1525)]
1526pub struct FactoryReturnObjectProperty {
1527    /// Dotted property path from the returned object literal (`orders`, `invoke.orders`).
1528    pub property_path: String,
1529    /// The property value's class local name within the factory module.
1530    pub class_local_name: String,
1531}
1532
1533/// An exported factory function that returns an object literal whose property
1534/// values are class instances, joined to its public export name.
1535///
1536/// A cross-module `const ui = createUi(); ui.orders.member` consumer emits a
1537/// `FactoryReturnObjectPropertyAccess` fact; the analyze layer resolves `export_name`
1538/// through the consumer's imports to this module, matches `property_path`, and credits
1539/// `member` on the resolved class (gated on it being a class with members). See issue #1858.
1540#[derive(
1541    Debug,
1542    Clone,
1543    serde::Serialize,
1544    serde::Deserialize,
1545    bitcode::Encode,
1546    bitcode::Decode,
1547    PartialEq,
1548    Eq,
1549)]
1550pub struct FactoryReturnObjectShapeExport {
1551    /// Public export name (honors `export { createUi as createOrdersUi }`).
1552    pub export_name: String,
1553    /// Resolved `(property_path -> class_local_name)` entries for the returned literal.
1554    pub properties: Box<[FactoryReturnObjectProperty]>,
1555}
1556
1557/// A named-type property whose declared type is a named type reference.
1558///
1559/// `interface Opts { c: OptDep }` (or `type Opts = { c: OptDep }`) records
1560/// `TypeMemberTypeEntry { type_name: "Opts", property: "c", property_type: "OptDep" }`.
1561/// Both `type_name` and `property_type` are the DECLARING module's own local
1562/// names; resolution through that module's imports/exports is deferred to
1563/// analyze time, mirroring `FactoryReturnExport.class_local_name`. Consumed by
1564/// the `unused-class-member` typed-property-hop join so a consumer's
1565/// `this.opts.c.optM()` credits `OptDep.optM` across module boundaries.
1566/// See issue #1785.
1567#[derive(
1568    Debug,
1569    Clone,
1570    serde::Serialize,
1571    serde::Deserialize,
1572    bitcode::Encode,
1573    bitcode::Decode,
1574    PartialEq,
1575    Eq,
1576)]
1577pub struct TypeMemberTypeEntry {
1578    /// Local interface or type-alias name declaring the property.
1579    pub type_name: String,
1580    /// Property name declared on the type.
1581    pub property: String,
1582    /// The property's declared type name (local to the declaring module).
1583    pub property_type: String,
1584}
1585
1586/// A module-scope declaration that can be used as a TypeScript type.
1587#[derive(Debug, Clone, serde::Serialize, PartialEq, Eq)]
1588pub struct LocalTypeDeclaration {
1589    /// Local declaration name.
1590    pub name: String,
1591    /// Declaration identifier span.
1592    #[serde(serialize_with = "serialize_span")]
1593    pub span: Span,
1594}
1595
1596/// A reference from an exported symbol's public signature to a type name.
1597#[derive(Debug, Clone, serde::Serialize, PartialEq, Eq)]
1598pub struct PublicSignatureTypeReference {
1599    /// Exported symbol whose signature contains the reference.
1600    pub export_name: String,
1601    /// Referenced type name. Qualified names are reduced to their root identifier.
1602    pub type_name: String,
1603    /// Reference span.
1604    #[serde(serialize_with = "serialize_span")]
1605    pub span: Span,
1606}
1607
1608/// A member of an enum, class, or namespace.
1609#[derive(Debug, Clone, serde::Serialize)]
1610pub struct MemberInfo {
1611    /// Member name.
1612    pub name: String,
1613    /// The kind of member (enum, class method/property, or namespace member).
1614    pub kind: MemberKind,
1615    /// Source span of the member declaration.
1616    #[serde(serialize_with = "serialize_span")]
1617    pub span: Span,
1618    /// Whether this member has decorators (e.g., `@Column()`, `@Inject()`).
1619    /// Decorated members are used by frameworks at runtime and should not be
1620    /// flagged as unused class members, unless every decorator on the member
1621    /// is opted out via `FallowConfig.ignore_decorators`.
1622    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1623    pub has_decorator: bool,
1624    /// Full dotted path of each decorator on this member, in source order.
1625    /// `@step("x")` stores `"step"`; `@ns.foo` stores `"ns.foo"`. Empty for
1626    /// undecorated members, Angular signal-initializer properties (which set
1627    /// `has_decorator` without a literal decorator AST node), and decorators
1628    /// whose expression is not an identifier ladder (the entry is the empty
1629    /// string in that case, treated as never-matching by the predicate).
1630    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1631    pub decorator_names: Vec<String>,
1632    /// True when this is a static class method that returns a fresh instance
1633    /// of the same class: either via `return new this()` / `return new
1634    /// <SameClassName>()` in the body's last statement, or via a declared
1635    /// return type matching the class name. Consumers calling such a static
1636    /// method receive an instance, so the call result's member accesses are
1637    /// credited against the class. See issues #346, #387.
1638    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1639    pub is_instance_returning_static: bool,
1640    /// True when this is an instance class method whose call result is an
1641    /// instance of the same class. Qualifies when the declared return type
1642    /// matches the class name (`setX(): EventBuilder { ... }`) or when the
1643    /// body's last statement is `return this`. The analyze layer walks fluent
1644    /// chains (`Class.factory().setX().setY()`) only through methods carrying
1645    /// this flag, so the chain stops at a non-self-returning method like
1646    /// `.build()`. See issue #387.
1647    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1648    pub is_self_returning: bool,
1649}
1650
1651/// The kind of member.
1652#[derive(
1653    Debug,
1654    Clone,
1655    Copy,
1656    PartialEq,
1657    Eq,
1658    serde::Serialize,
1659    serde::Deserialize,
1660    bitcode::Encode,
1661    bitcode::Decode,
1662)]
1663#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1664#[serde(rename_all = "snake_case")]
1665pub enum MemberKind {
1666    /// A TypeScript enum member.
1667    EnumMember,
1668    /// A class method.
1669    ClassMethod,
1670    /// A class property.
1671    ClassProperty,
1672    /// A member exported from a TypeScript namespace.
1673    NamespaceMember,
1674    /// A member declared by a store object (Pinia `state` / `getters` /
1675    /// `actions` key, or a setup-store returned key). Cross-graph dead-member
1676    /// detection: a store member never accessed by any consumer project-wide.
1677    StoreMember,
1678}
1679
1680/// A static member access expression (e.g., `Status.Active`, `MyClass.create()`).
1681#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, bitcode::Encode, bitcode::Decode)]
1682pub struct MemberAccess {
1683    /// The identifier being accessed (the import name).
1684    pub object: String,
1685    /// The member being accessed.
1686    pub member: String,
1687}
1688
1689/// Direct export declarations that TypeScript treats as one merged symbol.
1690///
1691/// Spans identify the exact declaration slots without conflating unrelated
1692/// type/value declarations that happen to share a name.
1693#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
1694#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1695pub struct DeclarationMergeFact {
1696    /// Identifier spans for the declarations in this merge group.
1697    pub export_spans: Vec<(u32, u32)>,
1698}
1699
1700/// A typed extraction fact for cross-layer analysis.
1701#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
1702#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1703#[serde(tag = "kind", rename_all = "snake_case")]
1704pub enum SemanticFact {
1705    /// A class member referenced from an Angular template, host binding, or
1706    /// component metadata entry.
1707    AngularTemplateMemberAccess(AngularTemplateMemberAccessFact),
1708    /// An Angular component field whose value is an array of a class.
1709    AngularComponentFieldArrayType(AngularComponentFieldArrayTypeFact),
1710    /// An Angular component spreads `this` into an object literal, so component
1711    /// input/output usage is opaque.
1712    AngularThisSpread(AngularThisSpreadFact),
1713    /// A member access on a value returned by an imported static factory call.
1714    FactoryCallMemberAccess(FactoryCallMemberAccessFact),
1715    /// A member access on a value returned by an imported free-function factory
1716    /// (`const x = importedFactory(); x.member`). See issue #1441 (Part A).
1717    FactoryFnMemberAccess(FactoryFnMemberAccessFact),
1718    /// A member access reached through a property of a value whose declared
1719    /// type is an imported named type (`this.opts.c.optM()` where `opts` is
1720    /// typed by an imported interface). See issue #1785.
1721    TypedPropertyMemberAccess(TypedPropertyMemberAccessFact),
1722    /// A member access on a fluent chain rooted at an imported static factory.
1723    FluentChainMemberAccess(FluentChainMemberAccessFact),
1724    /// A member access on a fluent chain rooted at a `new` expression.
1725    FluentChainNewMemberAccess(FluentChainNewMemberAccessFact),
1726    /// A member access on a Playwright fixture object inside a test callback.
1727    PlaywrightFixtureUse(PlaywrightFixtureUseFact),
1728    /// A Playwright fixture definition declared by a typed `test.extend<T>()`.
1729    PlaywrightFixtureDefinition(PlaywrightFixtureDefinitionFact),
1730    /// A Playwright fixture wrapper alias declared by `mergeTests` or `.extend`.
1731    PlaywrightFixtureAlias(PlaywrightFixtureAliasFact),
1732    /// A nested Playwright fixture binding declared by a fixture type alias.
1733    PlaywrightFixtureType(PlaywrightFixtureTypeFact),
1734    /// An exported value whose runtime instance targets a local class or interface.
1735    InstanceExportBinding(InstanceExportBindingFact),
1736    /// A dynamic custom-element tag render that makes static Lit tag credit opaque.
1737    DynamicCustomElementRender(DynamicCustomElementRenderFact),
1738    /// A factory-returned value consumed in a way that can expose ANY property
1739    /// (`const { a, ...rest } = importedFactory()`, a computed destructure key).
1740    /// The returned class must be treated as wholly used: crediting only the
1741    /// visible keys would leave a live member reported as dead.
1742    ///
1743    /// Appended, never inserted: `bitcode` encodes an enum by ordinal, so moving an
1744    /// existing variant would make an old cache decode one fact as another.
1745    FactoryFnWholeObject(FactoryFnWholeObjectFact),
1746    /// A member access reached through a property of a value returned by an
1747    /// imported factory that returns an object literal (`const ui = createUi();
1748    /// ui.orders.member`). Appended after `FactoryFnWholeObject`, never inserted
1749    /// (bitcode encodes by ordinal). See issue #1858.
1750    FactoryReturnObjectPropertyAccess(FactoryReturnObjectPropertyAccessFact),
1751    /// A `this.<field>.<member>` access tied to its exact enclosing class.
1752    /// Appended because bitcode encodes enum variants by ordinal.
1753    ClassThisMemberAccess(ClassThisMemberAccessFact),
1754    /// A whole-object use of `this.<field>...` tied to its exact enclosing class.
1755    /// Appended because bitcode encodes enum variants by ordinal.
1756    ClassThisWholeObjectUse(ClassThisWholeObjectUseFact),
1757    /// An ordered Vitest module-mock operation with direct imported-`vi`
1758    /// provenance.
1759    ///
1760    /// Appended because bitcode encodes enum variants by ordinal. The ordinary
1761    /// dynamic-import fact for the same source remains authoritative for graph
1762    /// reachability and unresolved-import diagnostics.
1763    VitestModuleMockOperation(VitestModuleMockOperationFact),
1764    /// Direct declarations that form one legal TypeScript declaration merge.
1765    /// Appended because bitcode encodes enum variants by ordinal.
1766    DeclarationMerge(DeclarationMergeFact),
1767    /// A named type whose direct receiver surface is contributed by another
1768    /// named type (for example `Pick<Base, ...>` or a union constituent).
1769    /// Appended because bitcode encodes enum variants by ordinal.
1770    TypeAliasSurfaceTarget(TypeAliasSurfaceTargetFact),
1771    /// A string-valued TypeScript enum member available as a static property key.
1772    /// Appended because bitcode encodes enum variants by ordinal.
1773    StringEnumMemberValue(StringEnumMemberValueFact),
1774    /// A computed property access keyed by a static enum member.
1775    /// Appended because bitcode encodes enum variants by ordinal.
1776    ComputedEnumKeyUse(ComputedEnumKeyUseFact),
1777    /// A directly declared non-optional member required by a named interface
1778    /// or object type.
1779    /// Appended because bitcode encodes enum variants by ordinal.
1780    RequiredTypeMember(RequiredTypeMemberFact),
1781}
1782
1783/// Iterate Angular template member names from typed semantic facts.
1784fn angular_template_member_names_from_parts(
1785    semantic_facts: &[SemanticFact],
1786) -> impl Iterator<Item = &str> {
1787    semantic_facts.iter().filter_map(|fact| {
1788        if let SemanticFact::AngularTemplateMemberAccess(access) = fact {
1789            Some(access.member.as_str())
1790        } else {
1791            None
1792        }
1793    })
1794}
1795
1796/// Iterate Angular template member names from a module's typed facts.
1797pub fn angular_template_member_names(module: &ModuleInfo) -> impl Iterator<Item = &str> {
1798    angular_template_member_names_from_parts(&module.semantic_facts)
1799}
1800
1801/// Return true when the fact slice contains any Angular template member
1802/// reference.
1803#[must_use]
1804fn has_angular_template_members_from_parts(semantic_facts: &[SemanticFact]) -> bool {
1805    angular_template_member_names_from_parts(semantic_facts)
1806        .next()
1807        .is_some()
1808}
1809
1810/// Return true when the module contains any Angular template member reference.
1811#[must_use]
1812pub fn has_angular_template_members(module: &ModuleInfo) -> bool {
1813    has_angular_template_members_from_parts(&module.semantic_facts)
1814}
1815
1816/// Return true when a module spreads `this` in Angular template context.
1817#[must_use]
1818pub fn has_angular_this_spread(module: &ModuleInfo) -> bool {
1819    SemanticFactView::new(&module.semantic_facts, &module.member_accesses).has_angular_this_spread()
1820}
1821
1822/// Return true when a module contains a dynamic custom-element render.
1823#[must_use]
1824pub fn has_dynamic_custom_element_render(module: &ModuleInfo) -> bool {
1825    module
1826        .semantic_facts
1827        .iter()
1828        .any(|fact| matches!(fact, SemanticFact::DynamicCustomElementRender(_)))
1829}
1830
1831/// Typed-first view over semantic extraction facts.
1832///
1833/// Extraction populates `semantic_facts` directly. The `member_accesses` slice
1834/// remains available for consumers that need ordinary source member accesses,
1835/// but it is no longer decoded as a string protocol for semantic facts.
1836#[derive(Debug, Clone, Copy)]
1837pub struct SemanticFactView<'a> {
1838    semantic_facts: &'a [SemanticFact],
1839    member_accesses: &'a [MemberAccess],
1840}
1841
1842impl<'a> SemanticFactView<'a> {
1843    /// Create a typed semantic fact view from current semantic facts plus
1844    /// ordinary source member accesses.
1845    #[must_use]
1846    pub const fn new(
1847        semantic_facts: &'a [SemanticFact],
1848        member_accesses: &'a [MemberAccess],
1849    ) -> Self {
1850        Self {
1851            semantic_facts,
1852            member_accesses,
1853        }
1854    }
1855
1856    /// Iterate typed semantic facts.
1857    pub fn facts(self) -> impl Iterator<Item = &'a SemanticFact> + 'a {
1858        self.semantic_facts.iter()
1859    }
1860
1861    /// Iterate Angular template member references.
1862    pub fn angular_template_member_names(self) -> impl Iterator<Item = &'a str> + 'a {
1863        angular_template_member_names_from_parts(self.semantic_facts)
1864    }
1865
1866    /// Collect Angular component field array-type facts.
1867    pub fn angular_component_field_array_types(self) -> Vec<AngularComponentFieldArrayTypeFact> {
1868        angular_component_field_array_type_facts(self.semantic_facts)
1869            .cloned()
1870            .collect()
1871    }
1872
1873    /// Return true when any Angular template member reference exists.
1874    #[must_use]
1875    pub fn has_angular_template_members(self) -> bool {
1876        self.angular_template_member_names().next().is_some()
1877    }
1878
1879    /// Return true when a module spreads `this` in Angular template context.
1880    #[must_use]
1881    pub fn has_angular_this_spread(self) -> bool {
1882        self.semantic_facts
1883            .iter()
1884            .any(|fact| matches!(fact, SemanticFact::AngularThisSpread(_)))
1885    }
1886
1887    /// Iterate ordinary source member accesses.
1888    pub fn ordinary_member_accesses(self) -> impl Iterator<Item = &'a MemberAccess> + 'a {
1889        self.member_accesses.iter()
1890    }
1891
1892    /// Collect class-scoped `this` member-access facts.
1893    pub fn class_this_member_accesses(self) -> Vec<ClassThisMemberAccessFact> {
1894        class_this_member_access_facts(self.semantic_facts)
1895            .cloned()
1896            .collect()
1897    }
1898
1899    /// Collect class-scoped `this` whole-object-use facts.
1900    pub fn class_this_whole_object_uses(self) -> Vec<ClassThisWholeObjectUseFact> {
1901        class_this_whole_object_use_facts(self.semantic_facts)
1902            .cloned()
1903            .collect()
1904    }
1905
1906    /// Collect instance-export binding facts.
1907    pub fn instance_export_bindings(self) -> Vec<InstanceExportBindingFact> {
1908        instance_export_binding_facts(self.semantic_facts)
1909            .cloned()
1910            .collect()
1911    }
1912
1913    /// Collect static factory call member facts.
1914    pub fn factory_call_member_accesses(self) -> Vec<FactoryCallMemberAccessFact> {
1915        factory_call_member_access_facts(self.semantic_facts)
1916            .cloned()
1917            .collect()
1918    }
1919
1920    /// Collect free-function factory-return member facts.
1921    pub fn factory_fn_member_accesses(self) -> Vec<FactoryFnMemberAccessFact> {
1922        factory_fn_member_access_facts(self.semantic_facts)
1923            .cloned()
1924            .collect()
1925    }
1926
1927    /// Collect factory-return whole-object consumption facts.
1928    pub fn factory_fn_whole_objects(self) -> Vec<FactoryFnWholeObjectFact> {
1929        factory_fn_whole_object_facts(self.semantic_facts)
1930            .cloned()
1931            .collect()
1932    }
1933
1934    /// Collect object-literal factory-return property member facts.
1935    pub fn factory_return_object_property_accesses(
1936        self,
1937    ) -> Vec<FactoryReturnObjectPropertyAccessFact> {
1938        factory_return_object_property_access_facts(self.semantic_facts)
1939            .cloned()
1940            .collect()
1941    }
1942
1943    /// Collect typed-property-hop member facts.
1944    pub fn typed_property_member_accesses(self) -> Vec<TypedPropertyMemberAccessFact> {
1945        typed_property_member_access_facts(self.semantic_facts)
1946            .cloned()
1947            .collect()
1948    }
1949
1950    /// Collect members whose presence is required by a named structural type.
1951    pub fn required_type_members(self) -> impl Iterator<Item = &'a RequiredTypeMemberFact> + 'a {
1952        required_type_member_facts(self.semantic_facts)
1953    }
1954
1955    /// Collect type-alias receiver-surface edges.
1956    pub fn type_alias_surface_targets(self) -> Vec<TypeAliasSurfaceTargetFact> {
1957        type_alias_surface_target_facts(self.semantic_facts)
1958            .cloned()
1959            .collect()
1960    }
1961
1962    /// Collect string-valued enum member definitions.
1963    pub fn string_enum_member_values(self) -> Vec<StringEnumMemberValueFact> {
1964        string_enum_member_value_facts(self.semantic_facts)
1965            .cloned()
1966            .collect()
1967    }
1968
1969    /// Collect computed property accesses keyed by enum members.
1970    pub fn computed_enum_key_uses(self) -> Vec<ComputedEnumKeyUseFact> {
1971        computed_enum_key_use_facts(self.semantic_facts)
1972            .cloned()
1973            .collect()
1974    }
1975
1976    /// Collect static factory fluent-chain member facts.
1977    pub fn fluent_chain_member_accesses(self) -> Vec<FluentChainMemberAccessFact> {
1978        fluent_chain_member_access_facts(self.semantic_facts)
1979            .cloned()
1980            .collect()
1981    }
1982
1983    /// Collect constructor-rooted fluent-chain member facts.
1984    pub fn fluent_chain_new_member_accesses(self) -> Vec<FluentChainNewMemberAccessFact> {
1985        fluent_chain_new_member_access_facts(self.semantic_facts)
1986            .cloned()
1987            .collect()
1988    }
1989
1990    /// Collect Playwright fixture-use facts.
1991    pub fn playwright_fixture_uses(self) -> Vec<PlaywrightFixtureUseFact> {
1992        playwright_fixture_use_facts(self.semantic_facts)
1993            .cloned()
1994            .collect()
1995    }
1996
1997    /// Collect Playwright fixture-definition facts.
1998    pub fn playwright_fixture_definitions(self) -> Vec<PlaywrightFixtureDefinitionFact> {
1999        playwright_fixture_definition_facts(self.semantic_facts)
2000            .cloned()
2001            .collect()
2002    }
2003
2004    /// Collect Playwright fixture-alias facts.
2005    pub fn playwright_fixture_aliases(self) -> Vec<PlaywrightFixtureAliasFact> {
2006        playwright_fixture_alias_facts(self.semantic_facts)
2007            .cloned()
2008            .collect()
2009    }
2010
2011    /// Collect Playwright fixture-type facts.
2012    pub fn playwright_fixture_types(self) -> Vec<PlaywrightFixtureTypeFact> {
2013        playwright_fixture_type_facts(self.semantic_facts)
2014            .cloned()
2015            .collect()
2016    }
2017}
2018
2019/// Iterate ordinary whole-object uses.
2020pub fn ordinary_whole_object_uses(whole_object_uses: &[String]) -> impl Iterator<Item = &str> {
2021    whole_object_uses.iter().map(String::as_str)
2022}
2023
2024/// Iterate typed instance-export binding facts.
2025fn instance_export_binding_facts(
2026    semantic_facts: &[SemanticFact],
2027) -> impl Iterator<Item = &InstanceExportBindingFact> {
2028    semantic_facts.iter().filter_map(|fact| {
2029        if let SemanticFact::InstanceExportBinding(access) = fact {
2030            Some(access)
2031        } else {
2032            None
2033        }
2034    })
2035}
2036
2037fn class_this_member_access_facts(
2038    semantic_facts: &[SemanticFact],
2039) -> impl Iterator<Item = &ClassThisMemberAccessFact> {
2040    semantic_facts.iter().filter_map(|fact| {
2041        if let SemanticFact::ClassThisMemberAccess(access) = fact {
2042            Some(access)
2043        } else {
2044            None
2045        }
2046    })
2047}
2048
2049fn class_this_whole_object_use_facts(
2050    semantic_facts: &[SemanticFact],
2051) -> impl Iterator<Item = &ClassThisWholeObjectUseFact> {
2052    semantic_facts.iter().filter_map(|fact| {
2053        if let SemanticFact::ClassThisWholeObjectUse(access) = fact {
2054            Some(access)
2055        } else {
2056            None
2057        }
2058    })
2059}
2060
2061fn angular_component_field_array_type_facts(
2062    semantic_facts: &[SemanticFact],
2063) -> impl Iterator<Item = &AngularComponentFieldArrayTypeFact> {
2064    semantic_facts.iter().filter_map(|fact| {
2065        if let SemanticFact::AngularComponentFieldArrayType(access) = fact {
2066            Some(access)
2067        } else {
2068            None
2069        }
2070    })
2071}
2072
2073/// Iterate typed factory-call member facts.
2074fn factory_call_member_access_facts(
2075    semantic_facts: &[SemanticFact],
2076) -> impl Iterator<Item = &FactoryCallMemberAccessFact> {
2077    semantic_facts.iter().filter_map(|fact| {
2078        if let SemanticFact::FactoryCallMemberAccess(access) = fact {
2079            Some(access)
2080        } else {
2081            None
2082        }
2083    })
2084}
2085
2086/// Iterate typed free-function factory-return member facts.
2087fn factory_fn_member_access_facts(
2088    semantic_facts: &[SemanticFact],
2089) -> impl Iterator<Item = &FactoryFnMemberAccessFact> {
2090    semantic_facts.iter().filter_map(|fact| {
2091        if let SemanticFact::FactoryFnMemberAccess(access) = fact {
2092            Some(access)
2093        } else {
2094            None
2095        }
2096    })
2097}
2098
2099fn factory_fn_whole_object_facts(
2100    semantic_facts: &[SemanticFact],
2101) -> impl Iterator<Item = &FactoryFnWholeObjectFact> {
2102    semantic_facts.iter().filter_map(|fact| {
2103        if let SemanticFact::FactoryFnWholeObject(fact) = fact {
2104            Some(fact)
2105        } else {
2106            None
2107        }
2108    })
2109}
2110
2111/// Iterate object-literal factory-return property member facts.
2112fn factory_return_object_property_access_facts(
2113    semantic_facts: &[SemanticFact],
2114) -> impl Iterator<Item = &FactoryReturnObjectPropertyAccessFact> {
2115    semantic_facts.iter().filter_map(|fact| {
2116        if let SemanticFact::FactoryReturnObjectPropertyAccess(access) = fact {
2117            Some(access)
2118        } else {
2119            None
2120        }
2121    })
2122}
2123
2124/// Iterate typed fluent-chain member facts.
2125fn fluent_chain_member_access_facts(
2126    semantic_facts: &[SemanticFact],
2127) -> impl Iterator<Item = &FluentChainMemberAccessFact> {
2128    semantic_facts.iter().filter_map(|fact| {
2129        if let SemanticFact::FluentChainMemberAccess(access) = fact {
2130            Some(access)
2131        } else {
2132            None
2133        }
2134    })
2135}
2136
2137/// Iterate typed-property-hop member facts.
2138fn typed_property_member_access_facts(
2139    semantic_facts: &[SemanticFact],
2140) -> impl Iterator<Item = &TypedPropertyMemberAccessFact> {
2141    semantic_facts.iter().filter_map(|fact| {
2142        if let SemanticFact::TypedPropertyMemberAccess(access) = fact {
2143            Some(access)
2144        } else {
2145            None
2146        }
2147    })
2148}
2149
2150fn required_type_member_facts(
2151    semantic_facts: &[SemanticFact],
2152) -> impl Iterator<Item = &RequiredTypeMemberFact> {
2153    semantic_facts.iter().filter_map(|fact| {
2154        if let SemanticFact::RequiredTypeMember(required) = fact {
2155            Some(required)
2156        } else {
2157            None
2158        }
2159    })
2160}
2161
2162fn type_alias_surface_target_facts(
2163    semantic_facts: &[SemanticFact],
2164) -> impl Iterator<Item = &TypeAliasSurfaceTargetFact> {
2165    semantic_facts.iter().filter_map(|fact| {
2166        if let SemanticFact::TypeAliasSurfaceTarget(fact) = fact {
2167            Some(fact)
2168        } else {
2169            None
2170        }
2171    })
2172}
2173
2174fn string_enum_member_value_facts(
2175    semantic_facts: &[SemanticFact],
2176) -> impl Iterator<Item = &StringEnumMemberValueFact> {
2177    semantic_facts.iter().filter_map(|fact| {
2178        if let SemanticFact::StringEnumMemberValue(fact) = fact {
2179            Some(fact)
2180        } else {
2181            None
2182        }
2183    })
2184}
2185
2186fn computed_enum_key_use_facts(
2187    semantic_facts: &[SemanticFact],
2188) -> impl Iterator<Item = &ComputedEnumKeyUseFact> {
2189    semantic_facts.iter().filter_map(|fact| {
2190        if let SemanticFact::ComputedEnumKeyUse(fact) = fact {
2191            Some(fact)
2192        } else {
2193            None
2194        }
2195    })
2196}
2197
2198/// Iterate typed constructor-rooted fluent-chain member facts.
2199fn fluent_chain_new_member_access_facts(
2200    semantic_facts: &[SemanticFact],
2201) -> impl Iterator<Item = &FluentChainNewMemberAccessFact> {
2202    semantic_facts.iter().filter_map(|fact| {
2203        if let SemanticFact::FluentChainNewMemberAccess(access) = fact {
2204            Some(access)
2205        } else {
2206            None
2207        }
2208    })
2209}
2210
2211/// Iterate typed Playwright fixture-use facts.
2212fn playwright_fixture_use_facts(
2213    semantic_facts: &[SemanticFact],
2214) -> impl Iterator<Item = &PlaywrightFixtureUseFact> {
2215    semantic_facts.iter().filter_map(|fact| {
2216        if let SemanticFact::PlaywrightFixtureUse(access) = fact {
2217            Some(access)
2218        } else {
2219            None
2220        }
2221    })
2222}
2223
2224/// Iterate typed Playwright fixture-definition facts.
2225fn playwright_fixture_definition_facts(
2226    semantic_facts: &[SemanticFact],
2227) -> impl Iterator<Item = &PlaywrightFixtureDefinitionFact> {
2228    semantic_facts.iter().filter_map(|fact| {
2229        if let SemanticFact::PlaywrightFixtureDefinition(access) = fact {
2230            Some(access)
2231        } else {
2232            None
2233        }
2234    })
2235}
2236
2237/// Iterate typed Playwright fixture-alias facts.
2238fn playwright_fixture_alias_facts(
2239    semantic_facts: &[SemanticFact],
2240) -> impl Iterator<Item = &PlaywrightFixtureAliasFact> {
2241    semantic_facts.iter().filter_map(|fact| {
2242        if let SemanticFact::PlaywrightFixtureAlias(access) = fact {
2243            Some(access)
2244        } else {
2245            None
2246        }
2247    })
2248}
2249
2250/// Iterate typed Playwright fixture-type facts.
2251fn playwright_fixture_type_facts(
2252    semantic_facts: &[SemanticFact],
2253) -> impl Iterator<Item = &PlaywrightFixtureTypeFact> {
2254    semantic_facts.iter().filter_map(|fact| {
2255        if let SemanticFact::PlaywrightFixtureType(access) = fact {
2256            Some(access)
2257        } else {
2258            None
2259        }
2260    })
2261}
2262
2263/// A member name referenced from an Angular template surface.
2264#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2265#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2266pub struct AngularTemplateMemberAccessFact {
2267    /// Referenced class member name.
2268    pub member: String,
2269}
2270
2271/// A typed Angular component field that exposes array elements to templates.
2272#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2273#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2274pub struct AngularComponentFieldArrayTypeFact {
2275    /// Component field name used as the template iterable.
2276    pub field: String,
2277    /// Array element class name.
2278    pub element_class: String,
2279}
2280
2281/// Opaque Angular `{ ...this }` forwarding marker.
2282#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2283#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2284pub struct AngularThisSpreadFact;
2285
2286/// A member access on a static factory call result.
2287#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2288#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2289pub struct FactoryCallMemberAccessFact {
2290    /// Local imported class or namespace object used as the factory callee.
2291    pub callee_object: String,
2292    /// Static factory method invoked on the callee object.
2293    pub callee_method: String,
2294    /// Member accessed on the returned instance-like object.
2295    pub member: String,
2296}
2297
2298/// A member access on a value returned by an imported free-function factory.
2299///
2300/// `const x = importedFactory(); x.member` emits one fact per first-level read
2301/// on `x`. The analyze layer resolves `callee_name` through the consumer's
2302/// imports to the factory's origin module, reads that module's
2303/// `exported_factory_returns` to learn the returned class's local name, resolves
2304/// THAT through the factory module's own imports to the class export, and
2305/// credits `member` on the class. See issue #1441 (Part A).
2306#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2307#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2308pub struct FactoryFnMemberAccessFact {
2309    /// Local imported function used as the factory callee.
2310    pub callee_name: String,
2311    /// Member accessed on the returned instance-like object.
2312    pub member: String,
2313}
2314
2315/// A factory-returned value consumed opaquely, so every member of the class it
2316/// returns must be treated as used.
2317#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2318#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2319pub struct FactoryFnWholeObjectFact {
2320    /// Local imported function used as the factory callee.
2321    pub callee_name: String,
2322}
2323
2324/// A member access reached through a property of a value returned by an imported
2325/// factory that returns an object literal.
2326///
2327/// `const ui = createUi(); ui.orders.member` emits one fact per member read on a
2328/// factory-result property. The analyze layer resolves `callee_name` through the
2329/// consumer's imports to the factory's origin module, reads that module's
2330/// `exported_factory_return_object_shapes` to find the property whose path equals
2331/// `property_path` and its class local name, resolves THAT through the factory
2332/// module's own imports to the class export, and credits `member` on the class
2333/// (gated on the export actually being a class with members). See issue #1858.
2334#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2335#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2336pub struct FactoryReturnObjectPropertyAccessFact {
2337    /// Local imported function used as the factory callee.
2338    pub callee_name: String,
2339    /// Dotted property path between the factory-result local and the final member
2340    /// (e.g. `"orders"` for `ui.orders.member`, `"invoke.orders"` for `ui.invoke.orders.member`).
2341    pub property_path: String,
2342    /// Member accessed on the terminal property's instance.
2343    pub member: String,
2344}
2345
2346/// A member access reached through a typed property hop that the extraction
2347/// layer could not resolve locally.
2348///
2349/// `constructor(private opts: Opts) { ... this.opts.c.optM() }` where `Opts`
2350/// is NOT declared in this file emits
2351/// `TypedPropertyMemberAccessFact { type_name: "Opts", property_path: "c", member: "optM" }`.
2352/// The analyze layer resolves `type_name` through the consumer's imports to the
2353/// declaring module, walks `property_path` through that module's
2354/// `type_member_types`, resolves the terminal type name through the declaring
2355/// module's own imports, and credits `member` on the resolved class (gated on
2356/// the export actually being a class with members). See issue #1785.
2357#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2358#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2359pub struct TypedPropertyMemberAccessFact {
2360    /// Local (usually imported) named-type symbol the receiver is typed by.
2361    pub type_name: String,
2362    /// Remaining dotted property segments between the typed binding and the
2363    /// final member (e.g. `"c"` for `this.opts.c.optM()`).
2364    pub property_path: String,
2365    /// Member accessed on the terminal property's instance.
2366    pub member: String,
2367}
2368
2369/// A class member directly required by a named structural type.
2370///
2371/// Optional properties and methods are excluded: removing an optional
2372/// implementation can preserve assignability, while removing a required one
2373/// from an explicit `implements` contract cannot.
2374#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2375#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2376pub struct RequiredTypeMemberFact {
2377    /// Module-local interface or object-type alias name.
2378    pub type_name: String,
2379    /// Static required property or method name.
2380    pub member: String,
2381}
2382
2383/// One direct contributor to a named type alias's receiver surface.
2384///
2385/// Nested property types are deliberately excluded: in
2386/// `{ nested: Nested }`, `Alias.member` does not access `Nested.member`.
2387#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2388#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2389pub struct TypeAliasSurfaceTargetFact {
2390    /// Module-local alias declaration name.
2391    pub alias_name: String,
2392    /// Module-local or imported named type contributing the direct surface.
2393    pub target_name: String,
2394}
2395
2396/// A statically known string value of a TypeScript enum member.
2397#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2398#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2399pub struct StringEnumMemberValueFact {
2400    /// Module-local enum declaration name.
2401    pub enum_name: String,
2402    /// Static enum member name.
2403    pub member_name: String,
2404    /// Exact string initializer value.
2405    pub value: String,
2406}
2407
2408/// A computed property access whose key is a static enum member.
2409#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2410#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2411pub struct ComputedEnumKeyUseFact {
2412    /// Local enum object used as the key source.
2413    pub key_object: String,
2414    /// Static member selected from the enum object.
2415    pub key_member: String,
2416}
2417
2418/// A member access on a fluent chain rooted at a static factory call.
2419#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2420#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2421pub struct FluentChainMemberAccessFact {
2422    /// Local imported class or namespace object used as the chain root.
2423    pub root_object: String,
2424    /// Static factory method that starts the fluent chain.
2425    pub root_method: String,
2426    /// Intermediate fluent methods between the root method and final member.
2427    pub chain: Vec<String>,
2428    /// Member accessed at this chain step.
2429    pub member: String,
2430}
2431
2432/// A member access on a fluent chain rooted at a `new` expression.
2433#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2434#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2435pub struct FluentChainNewMemberAccessFact {
2436    /// Local imported class constructed by the `new` expression.
2437    pub class_name: String,
2438    /// Intermediate fluent methods between construction and final member.
2439    pub chain: Vec<String>,
2440    /// Member accessed at this chain step.
2441    pub member: String,
2442}
2443
2444/// A member access on a Playwright fixture object inside a test callback.
2445#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2446#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2447pub struct PlaywrightFixtureUseFact {
2448    /// Local test function or wrapper used as the callback callee.
2449    pub test_name: String,
2450    /// Fixture name or dotted fixture path referenced in the callback.
2451    pub fixture_name: String,
2452    /// Member accessed on the fixture target.
2453    pub member: String,
2454}
2455
2456/// A Playwright fixture definition declared by a typed `test.extend<T>()`.
2457#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2458#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2459pub struct PlaywrightFixtureDefinitionFact {
2460    /// Local test function or wrapper receiving the fixture definition.
2461    pub test_name: String,
2462    /// Fixture name or dotted fixture path declared by the fixture type.
2463    pub fixture_name: String,
2464    /// Local type symbol used as the fixture target.
2465    pub type_name: String,
2466}
2467
2468/// A Playwright fixture wrapper alias declared by `mergeTests` or `.extend`.
2469#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2470#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2471pub struct PlaywrightFixtureAliasFact {
2472    /// Local test function or wrapper that inherits fixture definitions.
2473    pub test_name: String,
2474    /// Local test function or wrapper inherited by `test_name`.
2475    pub base_name: String,
2476}
2477
2478/// A nested Playwright fixture binding declared by a fixture type alias.
2479#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2480#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2481pub struct PlaywrightFixtureTypeFact {
2482    /// Local type alias containing the nested fixture binding.
2483    pub alias_name: String,
2484    /// Fixture name or dotted fixture path declared inside the type alias.
2485    pub fixture_name: String,
2486    /// Local type symbol used as the nested fixture target.
2487    pub type_name: String,
2488}
2489
2490/// An exported value whose runtime instance targets a local class or interface.
2491#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2492#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2493pub struct InstanceExportBindingFact {
2494    /// Exported binding name.
2495    pub export_name: String,
2496    /// Local class or interface symbol used as the instance target.
2497    pub target_name: String,
2498}
2499
2500/// Opaque marker for a dynamic custom-element render site.
2501#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2502#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2503pub struct DynamicCustomElementRenderFact;
2504
2505/// The action performed by a Vitest module-mock operation.
2506#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2507#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2508#[serde(rename_all = "snake_case")]
2509pub enum VitestModuleMockAction {
2510    /// Register a mock. `factory_replaces_original` is true only when the
2511    /// factory is structurally closed and cannot load the original module.
2512    ///
2513    /// Automock (`vi.mock` / `jest.mock` without a factory) is always
2514    /// `factory_replaces_original: false` by decision (issue #2082). For
2515    /// Vitest, the runner derives the mocked shape by importing the original
2516    /// module, so its top-level code executes at collection time, and
2517    /// file-level masking cannot express "module evaluated but exports
2518    /// stubbed". For Jest, a `__mocks__` sibling takes precedence and the
2519    /// original is genuinely not required, but the manual mock itself may
2520    /// load the original (`jest.requireActual`), and proving it never does
2521    /// would need a cross-file factory proof. Both runners therefore keep
2522    /// coverage credit for the automock form.
2523    Mock {
2524        /// Whether the factory provably replaces the original module.
2525        factory_replaces_original: bool,
2526    },
2527    /// Remove a registered mock and restore the original module.
2528    Unmock,
2529}
2530
2531impl VitestModuleMockAction {
2532    /// Whether this operation registers a proven complete replacement.
2533    #[must_use]
2534    pub const fn replaces_original(self) -> bool {
2535        matches!(
2536            self,
2537            Self::Mock {
2538                factory_replaces_original: true
2539            }
2540        )
2541    }
2542}
2543
2544/// Ordered Vitest module-mock operation with a static source target.
2545///
2546/// The declaring [`ModuleInfo::file_id`] owns the test-root provenance. The
2547/// resolver consumes `source` through its canonical specifier pipeline; this
2548/// fact deliberately carries no resolved path or duplicate diagnostic span.
2549#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2550#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2551pub struct VitestModuleMockOperationFact {
2552    /// Static module specifier passed to `vi.mock` or `vi.unmock`.
2553    pub source: String,
2554    /// Source-order position of the call within the declaring module.
2555    pub call_start: u32,
2556    /// Typed mock or unmock action.
2557    pub action: VitestModuleMockAction,
2558}
2559
2560/// A `this`-rooted member access with exact enclosing-class provenance.
2561#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2562#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2563pub struct ClassThisMemberAccessFact {
2564    /// Enclosing class local name, or `default` for an anonymous default class.
2565    pub class_local_name: String,
2566    /// Dotted receiver spelling beginning with `this.`.
2567    pub object: String,
2568    /// Terminal member being accessed.
2569    pub member: String,
2570}
2571
2572/// A whole-object use of a `this`-rooted chain with enclosing-class provenance.
2573#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2574#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2575pub struct ClassThisWholeObjectUseFact {
2576    /// Enclosing class local name, or `default` for an anonymous default class.
2577    pub class_local_name: String,
2578    /// Dotted receiver spelling beginning with `this.`.
2579    pub object: String,
2580}
2581
2582/// A statically flattenable callee path invoked in a module (e.g. `execSync`,
2583/// `child_process.exec`, `console.log`). One entry per unique `callee_path`
2584/// per module; the span anchors the first occurrence. Consumed by the
2585/// `boundaries.calls.forbidden` detector.
2586#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode)]
2587pub struct CalleeUse {
2588    /// The dotted or bare callee path as written at the call site.
2589    pub callee_path: String,
2590    /// Start byte offset of the first call site using this path.
2591    pub span_start: u32,
2592}
2593
2594/// A `"use client"` / `"use server"` directive string written as an expression
2595/// statement in `program.body` (NOT the leading prologue), so the RSC bundler
2596/// silently ignores it. One entry per offending occurrence. Consumed by the
2597/// `misplaced-directive` detector.
2598#[derive(Debug, Clone, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
2599pub struct MisplacedDirectiveSite {
2600    /// `true` for `"use server"`, `false` for `"use client"`.
2601    pub is_server: bool,
2602    /// Start byte offset of the misplaced directive statement.
2603    pub span_start: u32,
2604}
2605
2606/// Which side of a dependency-injection link a call site represents.
2607#[derive(Debug, Clone, Copy, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
2608pub enum DiRole {
2609    /// `provide(KEY, value)` / `app.provide(KEY, value)` / `setContext(KEY, value)`.
2610    Provide,
2611    /// `inject(KEY)` / `getContext(KEY)`.
2612    Inject,
2613}
2614
2615/// Which framework's DI API a call site came from (drives the finding message).
2616#[derive(Debug, Clone, Copy, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
2617pub enum DiFramework {
2618    /// Vue `provide` / `inject` (from `vue` / `@vue/runtime-core`).
2619    Vue,
2620    /// Svelte `setContext` / `getContext` (from `svelte`).
2621    Svelte,
2622    /// Angular `inject(TOKEN)` / `@Inject(TOKEN)` (from `@angular/core`),
2623    /// matched against `{ provide: TOKEN, ... }` provider objects.
2624    Angular,
2625}
2626
2627/// A Vue `provide`/`inject` or Svelte `setContext`/`getContext` call site keyed
2628/// by an identifier symbol. The `key_local` is resolved at analyze time through
2629/// the consuming module's import/export tables to a canonical defining-site
2630/// export key, so a provide and an inject of the same shared symbol unify even
2631/// across barrel re-exports. Consumed by the `unprovided-inject` detector.
2632#[derive(Debug, Clone, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
2633pub struct DiKeySite {
2634    /// The key identifier as written at the call site.
2635    pub key_local: String,
2636    /// Whether this is a provide or an inject.
2637    pub role: DiRole,
2638    /// Which framework's API this came from.
2639    pub framework: DiFramework,
2640    /// Start byte offset of the call expression (anchors the finding).
2641    pub span_start: u32,
2642}
2643
2644/// A component prop declared by Vue `<script setup>` `defineProps` or Svelte 5
2645/// `$props()`. `used_in_script` / `used_in_template` are set during extraction;
2646/// the `unused-component-prop` detector flags a prop where neither is true. See
2647/// `harvest_define_props` and `harvest_svelte_props` in `sfc_props.rs`.
2648#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode)]
2649pub struct ComponentProp {
2650    /// The declared prop name.
2651    pub name: String,
2652    /// The template/script-visible local binding name: the destructure alias for
2653    /// `const { name: alias } = defineProps()` or
2654    /// `let { name: alias } = $props()`, otherwise the prop name itself. A
2655    /// renamed prop is read through this local, so usage must be checked against
2656    /// it, not the declared name.
2657    pub local: String,
2658    /// Start byte offset of the prop declaration (anchors the finding).
2659    pub span_start: u32,
2660    /// Whether this prop is referenced in the component's `<script>` (a
2661    /// destructured local binding with a resolved reference, or a `props.<name>`
2662    /// member access). For React, this is set-in-body: a resolved reference to the
2663    /// destructured local anywhere in the component function body.
2664    pub used_in_script: bool,
2665    /// Whether this prop name is referenced in the component's `<template>`.
2666    /// Set by `apply_template_usage` when the template scanner credits the name.
2667    /// Always false for React (no template; React uses `used_in_script`).
2668    pub used_in_template: bool,
2669    /// The enclosing component name. Empty for Vue SFCs (one component per file,
2670    /// the file stem is the component, set by the detector). For React this is the
2671    /// component function/arrow name a prop was declared on, so the detector can
2672    /// emit the right `component_name` and apply the per-component abstain ladder
2673    /// (a file can declare several React components).
2674    pub component: String,
2675    /// React-only: `true` when the destructured prop local is referenced at least
2676    /// once OUTSIDE a child-JSX attribute value expression (a substantive
2677    /// consumption: a hook arg, a host-element child, a non-JSX-attr read). When
2678    /// `used_in_script` is true but this is false, the prop is referenced ONLY as
2679    /// the root of forwarded child attribute values, i.e. a pure pass-through.
2680    /// Always `false` for Vue (no forward-vs-consume distinction is computed).
2681    pub used_outside_forward: bool,
2682}
2683
2684/// A Vue `<script setup>` `defineEmits` declared event, harvested from the type
2685/// tuple-call form (`defineEmits<{ (e: 'foo'): void }>()`), the type object form
2686/// (`defineEmits<{ foo: [x: string] }>()`), or the runtime array form
2687/// (`defineEmits(['foo'])`). `used` is set during extraction when the bound emit
2688/// name is called as `emit('<name>')`. The `unused-component-emit` detector flags
2689/// an event where `used` is false. See `harvest_define_emits` in `sfc_props.rs`.
2690#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode, PartialEq, Eq)]
2691pub struct ComponentEmit {
2692    /// The declared emit event name.
2693    pub name: String,
2694    /// Start byte offset of the emit declaration (anchors the finding).
2695    pub span_start: u32,
2696    /// Whether this event is emitted via `emit('<name>')` somewhere in the
2697    /// component's `<script>`.
2698    pub used: bool,
2699}
2700
2701/// A Svelte custom event dispatched via `dispatch('<name>')`, where `dispatch`
2702/// is the binding from a `const dispatch = createEventDispatcher()` call. Only
2703/// literal-first-arg dispatches are recorded; a `dispatch(<nonLiteral>)` sets
2704/// `ModuleInfo::has_dynamic_dispatch` instead. Consumed by the
2705/// `unused-svelte-event` detector, which flags an event dispatched here but
2706/// listened to nowhere project-wide (the cross-file dead-output direction). The
2707/// span is a byte offset (not an `oxc_span::Span`) so the type round-trips
2708/// through the bitcode cache directly, mirroring `ComponentEmit::span_start`.
2709#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode, PartialEq, Eq)]
2710pub struct DispatchedEvent {
2711    /// The dispatched event name (the literal first argument).
2712    pub name: String,
2713    /// Start byte offset of the `dispatch(...)` call (anchors the finding).
2714    pub span_start: u32,
2715}
2716
2717/// A declared Angular component/directive input, harvested from an `@Input()`
2718/// decorator or a signal `input()` / `input.required()` / `model()` initializer
2719/// on an Angular-decorated class. Consumed by the `unused-component-input`
2720/// detector, which flags an input read nowhere in its own component (neither the
2721/// template nor the class body). The span is stored as a byte offset (not an
2722/// `oxc_span::Span`) so the type is cheap to mirror onto the cache, matching
2723/// `ComponentEmit::span_start`. `ModuleInfo` is not serialized, so no serde
2724/// attrs are derived here. `bitcode` derives let the type be mirrored directly
2725/// onto `CachedModule` (the same pattern as `ComponentEmit`).
2726#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode, PartialEq, Eq)]
2727pub struct AngularInputMember {
2728    /// The declared input name (the property key).
2729    pub name: String,
2730    /// Start byte offset of the property key (anchors the finding).
2731    pub span_start: u32,
2732}
2733
2734/// A declared Angular component/directive output, harvested from an `@Output()`
2735/// decorator or a signal `output()` / `outputFromObservable()` initializer on an
2736/// Angular-decorated class. Consumed by the `unused-component-output` detector,
2737/// which flags an output emitted nowhere in its own component. A `model()` is an
2738/// input and a framework-driven output, so it is recorded ONLY as an input and
2739/// never appears here (the implicit `update:` emit is framework-managed). The
2740/// span is a byte offset for the same reason as `AngularInputMember`.
2741#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode, PartialEq, Eq)]
2742pub struct AngularOutputMember {
2743    /// The declared output name (the property key).
2744    pub name: String,
2745    /// Start byte offset of the property key (anchors the finding).
2746    pub span_start: u32,
2747}
2748
2749/// A declared Angular `@Component` and its `selector` value(s), harvested from a
2750/// `@Component({ selector: '...' })` decorator. Consumed by the Angular arm of
2751/// the `unrendered-component` detector, which flags a component whose every
2752/// element selector is used in NO template project-wide (and that is not
2753/// referenced by class name anywhere, e.g. routed / bootstrapped / dynamically
2754/// rendered). A multi-selector string (`'app-foo, [appBar]'`) is split into the
2755/// `selectors` list. The span is stored as a byte offset (not an
2756/// `oxc_span::Span`) so the type round-trips through the bitcode cache directly,
2757/// mirroring `AngularInputMember::span_start`. `@Directive` is intentionally NOT
2758/// harvested here (directives have no template render). `ModuleInfo` is not
2759/// serialized, so no serde attrs are derived.
2760#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode, PartialEq, Eq)]
2761pub struct AngularComponentSelector {
2762    /// The declared selector strings for this component, split on `,`. A purely
2763    /// element-selector component has only `app-foo`-shaped entries; attribute
2764    /// (`[appFoo]`) and class (`.foo`) selectors are retained verbatim so the
2765    /// detector can abstain when ANY non-element selector is present.
2766    pub selectors: Vec<String>,
2767    /// Start byte offset of the component class declaration (anchors the
2768    /// finding).
2769    pub span_start: u32,
2770    /// The component class name (used to credit routed / bootstrapped / dynamic
2771    /// class-name references project-wide).
2772    pub class_name: String,
2773}
2774
2775/// A Lit / web-component custom element registered in a module via
2776/// `@customElement('x-foo')` or `customElements.define('x-foo', C)`. Consumed by
2777/// the Lit arm of the `unrendered-component` detector. The span is stored as a
2778/// byte offset (not an `oxc_span::Span`) so the type round-trips through the
2779/// bitcode cache directly, mirroring `AngularComponentSelector::span_start`.
2780#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode, PartialEq, Eq)]
2781pub struct RegisteredCustomElement {
2782    /// The registered custom-element tag name (`x-foo`).
2783    pub tag: String,
2784    /// The registering class's local name, used for the public-API / export
2785    /// abstain (an exported / published element is rendered by a downstream
2786    /// consumer the scan cannot see). Empty for an anonymous
2787    /// `export default @customElement('x-foo') class extends LitElement {}`.
2788    pub class_local_name: String,
2789    /// Start byte offset of the registering class declaration (anchors the
2790    /// finding at the element, NOT line 1, since a `.ts` file can register
2791    /// several custom elements).
2792    pub span_start: u32,
2793}
2794
2795/// A key returned from a SvelteKit route `load()` function's terminal return
2796/// object literal. Harvested from `+page.{ts,server.ts,js,server.js}` files
2797/// exporting a `load` function. Consumed by the `unused-load-data-key` detector,
2798/// which flags a key read by no consumer. The span is stored as byte offsets
2799/// (not an `oxc_span::Span`) so the type round-trips through the bitcode cache
2800/// directly, mirroring `DiKeySite::span_start` / `ComponentEmit::span_start`.
2801#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode, PartialEq, Eq)]
2802pub struct LoadReturnKey {
2803    /// The returned-object property key name.
2804    pub name: String,
2805    /// Start byte offset of the key (anchors the finding).
2806    pub span_start: u32,
2807    /// End byte offset of the key.
2808    pub span_end: u32,
2809}
2810
2811/// The syntactic shape of an identified React component definition. Drives the
2812/// abstain ladder later phases apply: a `forwardRef` / `memo` wrapper whose
2813/// props come from an imported interface fallow cannot resolve must abstain
2814/// (ADR-001), not guess.
2815#[derive(Debug, Clone, Copy, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
2816pub enum ComponentFunctionKind {
2817    /// A `function Foo() { return <.../> }` declaration.
2818    FnDecl,
2819    /// A `const Foo = () => <.../>` arrow (or function-expression) binding.
2820    Arrow,
2821    /// A `const Foo = forwardRef((props, ref) => <.../>)` wrapper.
2822    ForwardRefWrapper,
2823    /// A `const Foo = memo((props) => <.../>)` wrapper.
2824    MemoWrapper,
2825}
2826
2827/// An identified React component: a function/arrow whose body returns JSX.
2828/// Captured by `visit_jsx_element`'s enclosing-component tracking. The
2829/// `unused-component-prop` (React arm) and complexity-fold phases consume this;
2830/// the abstain flags keep zero-FP on the cases ADR-001 cannot resolve.
2831#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode)]
2832pub struct ComponentFunction {
2833    /// The component name (the binding or declaration identifier).
2834    pub name: String,
2835    /// Start byte offset of the component definition (anchors findings).
2836    pub span_start: u32,
2837    /// The syntactic shape of the definition.
2838    pub kind: ComponentFunctionKind,
2839    /// Whether the component is exported from its module (a named export, a
2840    /// `export default`, or re-exported in the same module). Public-API
2841    /// components abstain in the prop phase.
2842    pub is_exported: bool,
2843    /// `true` when the component's props are not statically harvestable: a
2844    /// rest/spread in the signature (`{ ...rest }`), props passed wholesale to a
2845    /// hook/helper, or a `forwardRef` / `memo` wrapper whose props come from an
2846    /// imported interface generic fallow cannot resolve (ADR-001). The prop
2847    /// phase abstains on the whole component when set.
2848    pub has_unharvestable_props: bool,
2849    /// `true` when the component body calls `cloneElement` / `React.cloneElement`.
2850    /// `cloneElement` injects props by reflection, so the static forward-set is
2851    /// incomplete; the prop-drilling phase abstains on any chain through this
2852    /// component (ADR-001, zero-FP).
2853    pub uses_clone_element: bool,
2854    /// `true` when the component renders a `*.Provider` member-expression tag
2855    /// (`<FooContext.Provider>`). A context provider in the subtree means the
2856    /// drilling may be a deliberate non-context choice (or the prop is about to
2857    /// be provided); the prop-drilling phase downgrades/abstains.
2858    pub renders_provider: bool,
2859    /// `true` when the component passes a function as a child render value
2860    /// (render-props / children-as-function: `<Foo>{() => ...}</Foo>` or
2861    /// `<Foo render={() => ...}/>`). The forwarded shape is dynamic; the
2862    /// prop-drilling phase abstains on chains through this component.
2863    pub has_children_as_function: bool,
2864    /// `true` when the component body is pure structural indirection: a single
2865    /// statement returning exactly one capitalized/member-expression JSX element
2866    /// (no host wrapper, no extra children, optionally a fragment wrapping a
2867    /// single element) that forwards props via a bare spread of the component's
2868    /// own props binding / rest local (`<Child {...props}/>`), with NO named
2869    /// attributes alongside the spread and NO self-render. The cross-component
2870    /// `thin-wrapper` phase joins this with hook-density / cyclomatic checks and
2871    /// the resolved single render edge to flag a component that is a candidate
2872    /// for inlining. Computed from the component's own AST only, so it caches
2873    /// byte-identity-safe (ADR-001).
2874    pub is_pure_passthrough: bool,
2875}
2876
2877/// The kind of a React hook call. `Custom` covers any `use*`-named call that is
2878/// not one of the built-in hooks.
2879#[derive(Debug, Clone, Copy, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
2880pub enum HookUseKind {
2881    /// `useState(...)`.
2882    UseState,
2883    /// `useEffect(...)`.
2884    UseEffect,
2885    /// `useMemo(...)`.
2886    UseMemo,
2887    /// `useCallback(...)`.
2888    UseCallback,
2889    /// Any other `use*`-named call (a custom hook).
2890    Custom,
2891}
2892
2893/// A React hook call site inside a component. Consumed by the complexity-fold
2894/// phase (hook density) and surfaced as descriptive hotspot context.
2895#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode)]
2896pub struct HookUse {
2897    /// The hook kind.
2898    pub kind: HookUseKind,
2899    /// The dependency-array arity, recorded ONLY when a literal array is present
2900    /// at the dependency-array position (`[a, b]` -> `Some(2)`, `[]` ->
2901    /// `Some(0)`). `None` when the call has no dependency array argument or the
2902    /// argument is not a literal array (ADR-001: do not guess).
2903    pub dep_array_arity: Option<u32>,
2904    /// Start byte offset of the hook call (anchors findings).
2905    pub span_start: u32,
2906    /// The enclosing component name (the top of the visitor's component stack
2907    /// when the hook call was recorded). Lets the descriptive per-component hook
2908    /// summary attribute hooks exactly even when a file declares several
2909    /// components. A hook recorded outside any component carries an empty string
2910    /// (the visitor only records hooks inside a component, so this is the
2911    /// rare top-level / unattributed case).
2912    pub component: String,
2913}
2914
2915/// A render edge: one component rendering another (a capitalized or
2916/// member-expression JSX tag). Captured at extraction time with the child's
2917/// written name; resolution of `child_component_name` to a `FileId`/export is
2918/// deferred to graph build via the existing import map.
2919#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode)]
2920pub struct RenderEdge {
2921    /// The name of the component that renders the child (the enclosing
2922    /// component). Empty when the JSX is not inside an identified component (a
2923    /// top-level render expression).
2924    pub parent_component: String,
2925    /// The rendered child component name as written (`Foo` or the full
2926    /// member-expression path `Foo.Bar`).
2927    pub child_component_name: String,
2928    /// The attribute (prop) names passed at the render site, in source order.
2929    pub attr_names: Vec<String>,
2930    /// `true` when the render site contains a JSX spread (`{...x}`), so the
2931    /// passed-prop set is not statically complete.
2932    pub has_spread: bool,
2933    /// The forwarded attributes at this render site: each pairs the child
2934    /// attribute NAME with the identifier ROOT of its value expression
2935    /// (`userName={user.name}` -> `{ attr: "userName", root: "user" }`;
2936    /// `value={x}` -> `{ attr: "value", root: "x" }`). ONLY plain identifier or
2937    /// member-root access values are recorded (`{x}`, `{x.y}`, `{x.y.z}`); a value
2938    /// that is a call, an arrow/function, a conditional, a JSX element, or any
2939    /// other complex expression is NOT recorded here (its root would not be a pure
2940    /// forward) and sets `has_complex_forward` instead. The prop-drilling chain
2941    /// walk uses this pairing to map "this component forwards prop P" to "the
2942    /// child receives it as attribute A".
2943    pub forward_attrs: Vec<ForwardAttr>,
2944    /// `true` when at least one attribute value at this render site is a complex
2945    /// expression (a call, an arrow/function render-prop, a conditional, a JSX
2946    /// element-as-prop, a template literal, etc.) whose identifier root was NOT
2947    /// recorded in `forward_attrs`. The prop-drilling phase abstains on a chain
2948    /// whose forwarded prop flows through such a value (ADR-001, zero-FP).
2949    pub has_complex_forward: bool,
2950}
2951
2952/// One forwarded JSX attribute: the child attribute name plus the identifier
2953/// root of its value expression. See [`RenderEdge::forward_attrs`].
2954#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode)]
2955pub struct ForwardAttr {
2956    /// The child attribute (prop) name as written (`userName`).
2957    pub attr: String,
2958    /// The identifier root of the attribute value expression (`user` for
2959    /// `userName={user.name}`).
2960    pub root: String,
2961}
2962
2963#[expect(
2964    clippy::trivially_copy_pass_by_ref,
2965    reason = "serde serialize_with requires &T"
2966)]
2967fn serialize_span<S: serde::Serializer>(span: &Span, serializer: S) -> Result<S::Ok, S::Error> {
2968    use serde::ser::SerializeMap;
2969    let mut map = serializer.serialize_map(Some(2))?;
2970    map.serialize_entry("start", &span.start)?;
2971    map.serialize_entry("end", &span.end)?;
2972    map.end()
2973}
2974
2975/// Export identifier.
2976#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
2977pub enum ExportName {
2978    /// A named export (e.g., `export const foo`).
2979    Named(String),
2980    /// The default export.
2981    Default,
2982}
2983
2984impl ExportName {
2985    /// Compare against a string without allocating (avoids `to_string()`).
2986    #[must_use]
2987    pub fn matches_str(&self, s: &str) -> bool {
2988        match self {
2989            Self::Named(n) => n == s,
2990            Self::Default => s == "default",
2991        }
2992    }
2993}
2994
2995impl std::fmt::Display for ExportName {
2996    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2997        match self {
2998            Self::Named(n) => write!(f, "{n}"),
2999            Self::Default => write!(f, "default"),
3000        }
3001    }
3002}
3003
3004/// An import declaration.
3005#[derive(Debug, Clone)]
3006pub struct ImportInfo {
3007    /// The import specifier (e.g., `./utils` or `react`).
3008    pub source: String,
3009    /// How the symbol is imported (named, default, namespace, or side-effect).
3010    pub imported_name: ImportedName,
3011    /// The local binding name in the importing module.
3012    pub local_name: String,
3013    /// Whether this is a type-only import (`import type`).
3014    pub is_type_only: bool,
3015    /// Whether this import originated from a CSS-context.
3016    pub from_style: bool,
3017    /// Source span of the import declaration.
3018    pub span: Span,
3019    /// Span of the source string literal used by the LSP to highlight the specifier.
3020    pub source_span: Span,
3021}
3022
3023/// How a symbol is imported.
3024#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
3025pub enum ImportedName {
3026    /// A named import (e.g., `import { foo }`).
3027    Named(String),
3028    /// A default import (e.g., `import React`).
3029    Default,
3030    /// A namespace import (e.g., `import * as utils`).
3031    Namespace,
3032    /// A side-effect import (e.g., `import './styles.css'`).
3033    SideEffect,
3034}
3035
3036#[cfg(target_pointer_width = "64")]
3037const _: () = assert!(std::mem::size_of::<ExportInfo>() == 136);
3038#[cfg(target_pointer_width = "64")]
3039const _: () = assert!(std::mem::size_of::<ImportInfo>() == 96);
3040#[cfg(target_pointer_width = "64")]
3041const _: () = assert!(std::mem::size_of::<ExportName>() == 24);
3042#[cfg(target_pointer_width = "64")]
3043const _: () = assert!(std::mem::size_of::<ImportedName>() == 24);
3044#[cfg(target_pointer_width = "64")]
3045const _: () = assert!(std::mem::size_of::<MemberAccess>() == 48);
3046#[cfg(target_pointer_width = "64")]
3047const _: () = assert!(std::mem::size_of::<SemanticFact>() == 96);
3048#[cfg(target_pointer_width = "64")]
3049const _: () = assert!(std::mem::size_of::<SinkSite>() == 216);
3050#[cfg(target_pointer_width = "64")]
3051const _: () = assert!(std::mem::size_of::<ModuleInfo>() == 1336);
3052#[cfg(target_pointer_width = "64")]
3053const _: () = assert!(std::mem::size_of::<TypeMemberTypeEntry>() == 72);
3054
3055/// A re-export declaration.
3056#[derive(Debug, Clone)]
3057pub struct ReExportInfo {
3058    /// The module being re-exported from.
3059    pub source: String,
3060    /// The name imported from the source module (or `*` for star re-exports).
3061    pub imported_name: String,
3062    /// The name exported from this module.
3063    pub exported_name: String,
3064    /// Whether this is a type-only re-export.
3065    pub is_type_only: bool,
3066    /// Source span of the re-export declaration on this module.
3067    pub span: oxc_span::Span,
3068    /// Span of the whole re-export statement. A multi-binding statement
3069    /// yields one `ReExportInfo` per binding, each with a per-binding
3070    /// `span`; this field lets consumers reason about the enclosing
3071    /// statement (e.g. suppression coverage). Empty (`start == end`) for
3072    /// synthesized re-exports that have no single owning statement.
3073    pub statement_span: oxc_span::Span,
3074    /// Span of the source string literal (the specifier in quotes), used to
3075    /// anchor unresolved-import findings on the specifier. Empty
3076    /// (`start == end`) when no literal exists in the statement.
3077    pub source_span: oxc_span::Span,
3078}
3079
3080/// A dynamic `import()` call.
3081#[derive(Debug, Clone)]
3082pub struct DynamicImportInfo {
3083    /// The import specifier.
3084    pub source: String,
3085    /// Source span of the `import()` expression.
3086    pub span: Span,
3087    /// Names destructured from the dynamic import result.
3088    /// Non-empty means `const { a, b } = await import(...)` -> Named imports.
3089    /// Empty means simple `import(...)` or `const x = await import(...)` -> Namespace.
3090    pub destructured_names: Vec<String>,
3091    /// The local variable name for `const x = await import(...)`.
3092    /// Used for namespace import narrowing via member access tracking.
3093    pub local_name: Option<String>,
3094    /// True when this dynamic import was synthesised by fallow rather than appearing in user source.
3095    pub is_speculative: bool,
3096}
3097
3098/// A `require()` call.
3099#[derive(Debug, Clone)]
3100pub struct RequireCallInfo {
3101    /// The require specifier.
3102    pub source: String,
3103    /// Source span of the `require()` call.
3104    pub span: Span,
3105    /// Source span of the specifier string-literal argument (including its
3106    /// quotes), e.g. the `'./x'` in `require('./x')`. Used to anchor an
3107    /// `unresolved-import` diagnostic squiggly under the specifier rather than
3108    /// the `require` keyword. `Span::default()` when the argument is not a
3109    /// plain string literal.
3110    pub source_span: Span,
3111    /// Names destructured from the `require()` result.
3112    pub destructured_names: Vec<String>,
3113    /// The local variable name for `const x = require(...)`.
3114    pub local_name: Option<String>,
3115}
3116
3117/// Result of parsing all files, including incremental cache statistics.
3118pub struct ParseResult {
3119    /// Extracted module information for all successfully parsed files.
3120    pub modules: Vec<ModuleInfo>,
3121    /// Files discovered with stable IDs but unreadable by the parser.
3122    pub read_failures: Vec<SourceReadFailure>,
3123    /// Number of files whose parse results were loaded from cache (unchanged).
3124    pub cache_hits: usize,
3125    /// Number of files that required a full parse (new or changed).
3126    pub cache_misses: usize,
3127    /// Summed wall-clock time of the actual AST parses across all rayon workers.
3128    pub parse_cpu_ms: f64,
3129}
3130
3131/// A discovered source that could not be read as UTF-8 text.
3132#[derive(Debug, Clone, PartialEq, Eq)]
3133pub struct SourceReadFailure {
3134    /// Stable discovery identity retained even though no module was produced.
3135    pub file_id: FileId,
3136    /// Absolute discovered source path.
3137    pub path: PathBuf,
3138    /// Underlying filesystem or UTF-8 decoding error.
3139    pub error: String,
3140}
3141
3142#[cfg(test)]
3143mod tests {
3144    use super::*;
3145
3146    fn span() -> Span {
3147        Span::new(0, 1)
3148    }
3149
3150    macro_rules! assert_released {
3151        ($values:expr) => {{
3152            assert!($values.is_empty());
3153        }};
3154    }
3155
3156    #[test]
3157    fn public_env_var_includes_public_ci_metadata() {
3158        for name in ["TAG_REF", "GITHUB_SHA", "CI_COMMIT_BRANCH", "APP_MODE"] {
3159            assert!(is_public_env_var(name), "{name} should be public metadata");
3160        }
3161    }
3162
3163    #[test]
3164    fn public_env_var_keeps_secret_shaped_names_source_backed() {
3165        for name in ["GITHUB_TOKEN", "REFRESH_TOKEN", "API_KEY", "SECRET_SHA"] {
3166            assert!(
3167                !is_public_env_var(name),
3168                "{name} should remain secret-shaped"
3169            );
3170        }
3171    }
3172
3173    #[test]
3174    fn ordinary_access_helpers_keep_source_accesses() {
3175        let member_accesses = vec![
3176            MemberAccess {
3177                object: "this".to_string(),
3178                member: "render".to_string(),
3179            },
3180            MemberAccess {
3181                object: "service".to_string(),
3182                member: "run".to_string(),
3183            },
3184        ];
3185        let ordinary = SemanticFactView::new(&[], &member_accesses)
3186            .ordinary_member_accesses()
3187            .map(|access| (access.object.as_str(), access.member.as_str()))
3188            .collect::<Vec<_>>();
3189
3190        assert_eq!(ordinary, vec![("this", "render"), ("service", "run")]);
3191
3192        let whole_object_uses = vec!["model".to_string(), "service".to_string()];
3193
3194        assert_eq!(
3195            ordinary_whole_object_uses(&whole_object_uses).collect::<Vec<_>>(),
3196            vec!["model", "service"]
3197        );
3198    }
3199
3200    #[test]
3201    fn angular_template_member_names_use_typed_facts() {
3202        let mut module = minimal_module_info();
3203        push_semantic_fact(
3204            &mut module,
3205            SemanticFact::AngularTemplateMemberAccess(AngularTemplateMemberAccessFact {
3206                member: "typed".to_string(),
3207            }),
3208        );
3209
3210        let names: Vec<&str> = angular_template_member_names(&module).collect();
3211
3212        assert_eq!(names, vec!["typed"]);
3213        assert!(has_angular_template_members(&module));
3214    }
3215
3216    #[test]
3217    fn angular_this_spread_uses_typed_fact() {
3218        let mut typed = minimal_module_info();
3219        push_semantic_fact(
3220            &mut typed,
3221            SemanticFact::AngularThisSpread(AngularThisSpreadFact),
3222        );
3223
3224        assert!(has_angular_this_spread(&typed));
3225        assert!(!has_angular_this_spread(&minimal_module_info()));
3226    }
3227
3228    #[test]
3229    fn semantic_fact_view_iterates_typed_facts() {
3230        let mut module = minimal_module_info();
3231        push_semantic_fact(
3232            &mut module,
3233            SemanticFact::FactoryCallMemberAccess(FactoryCallMemberAccessFact {
3234                callee_object: "Svc".to_string(),
3235                callee_method: "make".to_string(),
3236                member: "run".to_string(),
3237            }),
3238        );
3239
3240        let facts = SemanticFactView::new(&module.semantic_facts, &module.member_accesses)
3241            .facts()
3242            .collect::<Vec<_>>();
3243
3244        assert_eq!(
3245            facts[0],
3246            &SemanticFact::FactoryCallMemberAccess(FactoryCallMemberAccessFact {
3247                callee_object: "Svc".to_string(),
3248                callee_method: "make".to_string(),
3249                member: "run".to_string(),
3250            })
3251        );
3252    }
3253
3254    #[test]
3255    fn typed_fact_helpers_collect_each_family() {
3256        let mut module = minimal_module_info();
3257        push_semantic_fact(
3258            &mut module,
3259            SemanticFact::InstanceExportBinding(InstanceExportBindingFact {
3260                export_name: "exported".to_string(),
3261                target_name: "target".to_string(),
3262            }),
3263        );
3264        push_semantic_fact(
3265            &mut module,
3266            SemanticFact::FactoryCallMemberAccess(FactoryCallMemberAccessFact {
3267                callee_object: "Svc".to_string(),
3268                callee_method: "create".to_string(),
3269                member: "run".to_string(),
3270            }),
3271        );
3272        push_semantic_fact(
3273            &mut module,
3274            SemanticFact::FluentChainMemberAccess(FluentChainMemberAccessFact {
3275                root_object: "Builder".to_string(),
3276                root_method: "start".to_string(),
3277                chain: vec!["next".to_string()],
3278                member: "value".to_string(),
3279            }),
3280        );
3281        push_semantic_fact(
3282            &mut module,
3283            SemanticFact::FluentChainNewMemberAccess(FluentChainNewMemberAccessFact {
3284                class_name: "Builder".to_string(),
3285                chain: vec!["next".to_string(), "finish".to_string()],
3286                member: "done".to_string(),
3287            }),
3288        );
3289
3290        assert_eq!(
3291            SemanticFactView::new(&module.semantic_facts, &module.member_accesses)
3292                .instance_export_bindings(),
3293            vec![InstanceExportBindingFact {
3294                export_name: "exported".to_string(),
3295                target_name: "target".to_string(),
3296            }]
3297        );
3298        assert_eq!(
3299            SemanticFactView::new(&module.semantic_facts, &module.member_accesses)
3300                .factory_call_member_accesses(),
3301            vec![FactoryCallMemberAccessFact {
3302                callee_object: "Svc".to_string(),
3303                callee_method: "create".to_string(),
3304                member: "run".to_string(),
3305            }]
3306        );
3307        assert_eq!(
3308            SemanticFactView::new(&module.semantic_facts, &module.member_accesses)
3309                .fluent_chain_member_accesses(),
3310            vec![FluentChainMemberAccessFact {
3311                root_object: "Builder".to_string(),
3312                root_method: "start".to_string(),
3313                chain: vec!["next".to_string()],
3314                member: "value".to_string(),
3315            }]
3316        );
3317        assert_eq!(
3318            SemanticFactView::new(&module.semantic_facts, &module.member_accesses)
3319                .fluent_chain_new_member_accesses(),
3320            vec![FluentChainNewMemberAccessFact {
3321                class_name: "Builder".to_string(),
3322                chain: vec!["next".to_string(), "finish".to_string()],
3323                member: "done".to_string(),
3324            }]
3325        );
3326    }
3327
3328    #[test]
3329    fn semantic_fact_view_exposes_typed_first_contract() {
3330        let mut module = minimal_module_info();
3331        push_semantic_fact(
3332            &mut module,
3333            SemanticFact::FactoryCallMemberAccess(FactoryCallMemberAccessFact {
3334                callee_object: "Svc".to_string(),
3335                callee_method: "create".to_string(),
3336                member: "run".to_string(),
3337            }),
3338        );
3339        push_semantic_fact(
3340            &mut module,
3341            SemanticFact::PlaywrightFixtureUse(PlaywrightFixtureUseFact {
3342                test_name: "test".to_string(),
3343                fixture_name: "page".to_string(),
3344                member: "goto".to_string(),
3345            }),
3346        );
3347        push_semantic_fact(
3348            &mut module,
3349            SemanticFact::InstanceExportBinding(InstanceExportBindingFact {
3350                export_name: "exported".to_string(),
3351                target_name: "target".to_string(),
3352            }),
3353        );
3354
3355        let view = SemanticFactView::new(&module.semantic_facts, &module.member_accesses);
3356
3357        assert_eq!(
3358            view.factory_call_member_accesses(),
3359            vec![FactoryCallMemberAccessFact {
3360                callee_object: "Svc".to_string(),
3361                callee_method: "create".to_string(),
3362                member: "run".to_string(),
3363            }]
3364        );
3365        assert_eq!(
3366            view.playwright_fixture_uses(),
3367            vec![PlaywrightFixtureUseFact {
3368                test_name: "test".to_string(),
3369                fixture_name: "page".to_string(),
3370                member: "goto".to_string(),
3371            }]
3372        );
3373        assert_eq!(
3374            view.instance_export_bindings(),
3375            vec![InstanceExportBindingFact {
3376                export_name: "exported".to_string(),
3377                target_name: "target".to_string(),
3378            }]
3379        );
3380    }
3381
3382    #[test]
3383    fn playwright_fixture_fact_helpers_select_each_fact_family() {
3384        let mut module = minimal_module_info();
3385        push_semantic_fact(
3386            &mut module,
3387            SemanticFact::PlaywrightFixtureUse(PlaywrightFixtureUseFact {
3388                test_name: "test".to_string(),
3389                fixture_name: "page".to_string(),
3390                member: "goto".to_string(),
3391            }),
3392        );
3393        push_semantic_fact(
3394            &mut module,
3395            SemanticFact::PlaywrightFixtureDefinition(PlaywrightFixtureDefinitionFact {
3396                test_name: "test".to_string(),
3397                fixture_name: "adminPage".to_string(),
3398                type_name: "AdminPage".to_string(),
3399            }),
3400        );
3401        push_semantic_fact(
3402            &mut module,
3403            SemanticFact::PlaywrightFixtureAlias(PlaywrightFixtureAliasFact {
3404                test_name: "mergedTest".to_string(),
3405                base_name: "test".to_string(),
3406            }),
3407        );
3408        push_semantic_fact(
3409            &mut module,
3410            SemanticFact::PlaywrightFixtureType(PlaywrightFixtureTypeFact {
3411                alias_name: "Pages".to_string(),
3412                fixture_name: "adminPage".to_string(),
3413                type_name: "AdminPage".to_string(),
3414            }),
3415        );
3416
3417        assert_eq!(
3418            playwright_fixture_use_facts(&module.semantic_facts)
3419                .map(|fact| fact.member.as_str())
3420                .collect::<Vec<_>>(),
3421            vec!["goto"]
3422        );
3423        assert_eq!(
3424            playwright_fixture_definition_facts(&module.semantic_facts)
3425                .map(|fact| fact.type_name.as_str())
3426                .collect::<Vec<_>>(),
3427            vec!["AdminPage"]
3428        );
3429        assert_eq!(
3430            playwright_fixture_alias_facts(&module.semantic_facts)
3431                .map(|fact| fact.base_name.as_str())
3432                .collect::<Vec<_>>(),
3433            vec!["test"]
3434        );
3435        assert_eq!(
3436            playwright_fixture_type_facts(&module.semantic_facts)
3437                .map(|fact| fact.fixture_name.as_str())
3438                .collect::<Vec<_>>(),
3439            vec!["adminPage"]
3440        );
3441    }
3442
3443    #[test]
3444    fn line_offsets_empty_string() {
3445        assert_eq!(compute_line_offsets(""), vec![0]);
3446    }
3447
3448    #[test]
3449    #[expect(
3450        clippy::too_many_lines,
3451        reason = "exhaustive field-by-field construction + release assertions for every ModuleInfo field"
3452    )]
3453    fn release_resolution_payload_drops_copied_vectors_only() {
3454        let mut module = ModuleInfo {
3455            file_id: FileId(7),
3456            exports: vec![ExportInfo {
3457                name: ExportName::Named("kept".to_string()),
3458                local_name: None,
3459                is_type_only: false,
3460                is_side_effect_used: false,
3461                visibility: VisibilityTag::None,
3462                expected_unused_reason: None,
3463                span: span(),
3464                members: Vec::new(),
3465                super_class: None,
3466            }]
3467            .into(),
3468            imports: vec![ImportInfo {
3469                source: "node:child_process".to_string(),
3470                imported_name: ImportedName::Default,
3471                local_name: "childProcess".to_string(),
3472                is_type_only: false,
3473                from_style: false,
3474                span: span(),
3475                source_span: span(),
3476            }],
3477            re_exports: vec![ReExportInfo {
3478                source: "./kept".to_string(),
3479                imported_name: "kept".to_string(),
3480                exported_name: "kept".to_string(),
3481                is_type_only: false,
3482                span: span(),
3483                statement_span: span(),
3484                source_span: span(),
3485            }],
3486            dynamic_imports: vec![DynamicImportInfo {
3487                source: "./dynamic".to_string(),
3488                span: span(),
3489                destructured_names: vec!["value".to_string()],
3490                local_name: None,
3491                is_speculative: false,
3492            }],
3493            dynamic_import_patterns: vec![DynamicImportPattern {
3494                prefix: "./pages/".to_string(),
3495                suffix: Some(".tsx".to_string()),
3496                span: span(),
3497                mechanism: ModuleLoadMechanism::EsModule,
3498            }],
3499            require_calls: vec![RequireCallInfo {
3500                source: "./required".to_string(),
3501                span: span(),
3502                source_span: span(),
3503                destructured_names: Vec::new(),
3504                local_name: Some("required".to_string()),
3505            }],
3506            package_path_references: vec!["react".to_string()].into(),
3507            member_accesses: vec![MemberAccess {
3508                object: "Status".to_string(),
3509                member: "Active".to_string(),
3510            }]
3511            .into(),
3512            semantic_facts: std::sync::Arc::default(),
3513            whole_object_uses: vec!["Status".to_string()].into(),
3514            has_cjs_exports: true,
3515            has_angular_component_template_url: true,
3516            content_hash: 42,
3517            suppressions: Vec::new(),
3518            unknown_suppression_kinds: Vec::new(),
3519            unused_import_bindings: vec!["unused".to_string()],
3520            type_referenced_import_bindings: vec!["TypeOnly".to_string()],
3521            value_referenced_import_bindings: vec!["Value".to_string()],
3522            line_offsets: vec![0, 8],
3523            complexity: vec![FunctionComplexity {
3524                name: "work".to_string(),
3525                line: 1,
3526                col: 0,
3527                cyclomatic: 2,
3528                cognitive: 3,
3529                line_count: 4,
3530                param_count: 1,
3531                react_hook_count: 0,
3532                react_jsx_max_depth: 0,
3533                react_prop_count: 0,
3534                source_hash: Some("hash".to_string()),
3535                contributions: Vec::new(),
3536            }],
3537            flag_uses: vec![FlagUse {
3538                flag_name: "FEATURE_X".to_string(),
3539                kind: FlagUseKind::EnvVar,
3540                line: 1,
3541                col: 0,
3542                guard_span_start: None,
3543                guard_span_end: None,
3544                sdk_name: None,
3545            }],
3546            class_heritage: vec![ClassHeritageInfo {
3547                export_name: "Child".to_string(),
3548                super_class: Some("Parent".to_string()),
3549                implements: vec!["Contract".to_string()],
3550                type_parameters: Vec::new(),
3551                instance_bindings: Vec::new(),
3552                super_class_type_args: Vec::new(),
3553                generic_instance_bindings: Vec::new(),
3554            }],
3555            exported_factory_returns: std::sync::Arc::from([FactoryReturnExport {
3556                export_name: "useApi".to_string(),
3557                class_local_name: "RESTApi".to_string(),
3558            }]),
3559            exported_factory_return_object_shapes: std::sync::Arc::from([
3560                FactoryReturnObjectShapeExport {
3561                    export_name: "createUi".to_string(),
3562                    properties: Box::from([FactoryReturnObjectProperty {
3563                        property_path: "orders".to_string(),
3564                        class_local_name: "OrdersPage".to_string(),
3565                    }]),
3566                },
3567            ]),
3568            type_member_types: std::sync::Arc::from([TypeMemberTypeEntry {
3569                type_name: "Opts".to_string(),
3570                property: "c".to_string(),
3571                property_type: "OptDep".to_string(),
3572            }]),
3573            injection_tokens: vec![("TOKEN".to_string(), "Contract".to_string())],
3574            local_type_declarations: vec![LocalTypeDeclaration {
3575                name: "Contract".to_string(),
3576                span: span(),
3577            }],
3578            public_signature_type_references: vec![PublicSignatureTypeReference {
3579                export_name: "kept".to_string(),
3580                type_name: "Contract".to_string(),
3581                span: span(),
3582            }],
3583            namespace_object_aliases: vec![NamespaceObjectAlias {
3584                via_export_name: "api".to_string(),
3585                suffix: "read".to_string(),
3586                namespace_local: "ns".to_string(),
3587            }],
3588            iconify_prefixes: vec!["hero".to_string()],
3589            iconify_icon_names: vec!["hero-home".to_string()],
3590            auto_import_candidates: vec!["useState".to_string()],
3591            directives: vec!["use client".to_string()],
3592            client_only_dynamic_import_spans: Vec::new(),
3593            security_sinks: Vec::new(),
3594            security_sinks_skipped: 1,
3595            security_unresolved_callee_sites: Vec::new(),
3596            tainted_bindings: Vec::new(),
3597            sanitized_sink_args: Vec::new(),
3598            security_control_sites: Vec::new(),
3599            callee_uses: Vec::new(),
3600            misplaced_directives: Vec::new(),
3601            inline_server_action_exports: Vec::new(),
3602            di_key_sites: Vec::new(),
3603            has_dynamic_provide: false,
3604            referenced_import_bindings: Vec::new(),
3605            component_props: Vec::new(),
3606            has_props_attrs_fallthrough: false,
3607            has_define_expose: false,
3608            has_define_model: false,
3609            has_unharvestable_props: false,
3610            component_emits: Vec::new(),
3611            angular_inputs: Vec::new(),
3612            angular_outputs: Vec::new(),
3613            angular_component_selectors: Vec::new(),
3614            registered_custom_elements: Vec::new(),
3615            used_custom_element_tags: Vec::new(),
3616            angular_used_selectors: Vec::new(),
3617            angular_entry_component_refs: Vec::new(),
3618            has_dynamic_component_render: false,
3619            has_unharvestable_emits: false,
3620            has_dynamic_emit: false,
3621            has_emit_whole_object_use: false,
3622            load_return_keys: Vec::new(),
3623            has_unharvestable_load: false,
3624            has_load_data_whole_use: false,
3625            has_page_data_store_whole_use: false,
3626            has_route_loader_data_whole_use: false,
3627            component_functions: Vec::new(),
3628            react_props: Vec::new(),
3629            hook_uses: Vec::new(),
3630            render_edges: Vec::new(),
3631            svelte_dispatched_events: Vec::new(),
3632            svelte_listened_events: Vec::new(),
3633            has_dynamic_dispatch: false,
3634        };
3635
3636        module.release_resolution_payload();
3637
3638        assert_eq!(module.file_id, FileId(7));
3639        assert_eq!(module.content_hash, 42);
3640        assert_eq!(module.line_offsets, vec![0, 8]);
3641        assert_eq!(module.imports.len(), 1);
3642        assert_eq!(module.exports.len(), 1);
3643        assert_eq!(module.re_exports.len(), 1);
3644        assert_eq!(module.dynamic_import_patterns.len(), 1);
3645        assert_eq!(module.member_accesses.len(), 1);
3646        assert_eq!(module.complexity.len(), 1);
3647        assert_eq!(module.flag_uses.len(), 1);
3648        assert_eq!(module.class_heritage.len(), 1);
3649        assert_eq!(module.exported_factory_returns.len(), 1);
3650        assert_eq!(module.injection_tokens.len(), 1);
3651        assert_eq!(module.local_type_declarations.len(), 1);
3652        assert_eq!(module.public_signature_type_references.len(), 1);
3653        assert_eq!(module.iconify_prefixes.len(), 1);
3654        assert_eq!(module.iconify_icon_names.len(), 1);
3655        assert_eq!(module.directives.len(), 1);
3656        assert_eq!(module.security_sinks_skipped, 1);
3657        assert_released!(module.dynamic_imports);
3658        assert_released!(module.require_calls);
3659        assert_released!(module.package_path_references);
3660        assert_released!(module.whole_object_uses);
3661        assert_released!(module.unused_import_bindings);
3662        assert_released!(module.type_referenced_import_bindings);
3663        assert_released!(module.value_referenced_import_bindings);
3664        assert_released!(module.namespace_object_aliases);
3665        assert_released!(module.auto_import_candidates);
3666        assert_eq!(
3667            module.referenced_import_bindings,
3668            vec!["childProcess".to_string()]
3669        );
3670    }
3671
3672    #[test]
3673    fn sink_shape_bitcode_roundtrip() {
3674        for shape in [
3675            SinkShape::Call,
3676            SinkShape::MemberCall,
3677            SinkShape::MemberAssign,
3678            SinkShape::TaggedTemplate,
3679            SinkShape::JsxAttr,
3680            SinkShape::NewExpression,
3681            SinkShape::SecretLiteral,
3682        ] {
3683            let encoded = bitcode::encode(&shape);
3684            let decoded: SinkShape = bitcode::decode(&encoded).expect("decode sink shape");
3685            assert_eq!(shape, decoded);
3686        }
3687    }
3688
3689    #[test]
3690    fn sink_arg_kind_bitcode_roundtrip() {
3691        for kind in [
3692            SinkArgKind::TemplateWithSubst,
3693            SinkArgKind::Concat,
3694            SinkArgKind::Object,
3695            SinkArgKind::Call,
3696            SinkArgKind::Literal,
3697            SinkArgKind::NoArg,
3698            SinkArgKind::Other,
3699        ] {
3700            let encoded = bitcode::encode(&kind);
3701            let decoded: SinkArgKind = bitcode::decode(&encoded).expect("decode sink arg kind");
3702            assert_eq!(kind, decoded);
3703        }
3704    }
3705
3706    #[test]
3707    fn security_url_shape_bitcode_roundtrip() {
3708        for shape in [
3709            SecurityUrlShape::FixedOriginDynamicPath,
3710            SecurityUrlShape::DynamicOrigin,
3711        ] {
3712            let encoded = bitcode::encode(&shape);
3713            let decoded: SecurityUrlShape =
3714                bitcode::decode(&encoded).expect("decode security url shape");
3715            assert_eq!(shape, decoded);
3716        }
3717    }
3718
3719    #[test]
3720    fn sink_site_bitcode_roundtrip() {
3721        let site = SinkSite {
3722            sink_shape: SinkShape::MemberAssign,
3723            callee_path: "el.innerHTML".to_string(),
3724            arg_index: 0,
3725            arg_is_non_literal: true,
3726            arg_kind: SinkArgKind::Other,
3727            arg_literal: Some(SinkLiteralValue::Integer(511)),
3728            regex_pattern: None,
3729            object_properties: vec![SinkObjectProperty {
3730                key: "origin".to_string(),
3731                value: SinkLiteralValue::String("*".to_string()),
3732            }],
3733            object_property_keys: vec!["origin".to_string()],
3734            object_property_keys_complete: true,
3735            arg_idents: vec!["userInput".to_string()],
3736            arg_source_paths: vec!["req.body.email".to_string(), "req.body".to_string()],
3737            span_start: 10,
3738            span_end: 20,
3739            url_arg_literal: Some("https://api.example.com".to_string()),
3740            url_shape: Some(SecurityUrlShape::FixedOriginDynamicPath),
3741        };
3742        let encoded = bitcode::encode(&site);
3743        let decoded: SinkSite = bitcode::decode(&encoded).expect("decode sink site");
3744        assert_eq!(decoded.sink_shape, site.sink_shape);
3745        assert_eq!(decoded.callee_path, site.callee_path);
3746        assert_eq!(decoded.arg_index, site.arg_index);
3747        assert_eq!(decoded.arg_is_non_literal, site.arg_is_non_literal);
3748        assert_eq!(decoded.arg_kind, site.arg_kind);
3749        assert_eq!(decoded.arg_literal, site.arg_literal);
3750        assert_eq!(decoded.object_properties, site.object_properties);
3751        assert_eq!(decoded.object_property_keys, site.object_property_keys);
3752        assert_eq!(
3753            decoded.object_property_keys_complete,
3754            site.object_property_keys_complete
3755        );
3756        assert_eq!(decoded.arg_idents, site.arg_idents);
3757        assert_eq!(decoded.arg_source_paths, site.arg_source_paths);
3758        assert_eq!(decoded.url_shape, site.url_shape);
3759        assert_eq!(decoded.span(), site.span());
3760    }
3761
3762    #[test]
3763    fn line_offsets_single_line_no_newline() {
3764        assert_eq!(compute_line_offsets("hello"), vec![0]);
3765    }
3766
3767    #[test]
3768    fn line_offsets_single_line_with_newline() {
3769        assert_eq!(compute_line_offsets("hello\n"), vec![0, 6]);
3770    }
3771
3772    #[test]
3773    fn line_offsets_multiple_lines() {
3774        assert_eq!(compute_line_offsets("abc\ndef\nghi"), vec![0, 4, 8]);
3775    }
3776
3777    #[test]
3778    fn line_offsets_trailing_newline() {
3779        assert_eq!(compute_line_offsets("abc\ndef\n"), vec![0, 4, 8]);
3780    }
3781
3782    #[test]
3783    fn line_offsets_consecutive_newlines() {
3784        assert_eq!(compute_line_offsets("\n\n\n"), vec![0, 1, 2, 3]);
3785    }
3786
3787    #[test]
3788    fn line_offsets_multibyte_utf8() {
3789        assert_eq!(compute_line_offsets("á\n"), vec![0, 3]);
3790    }
3791
3792    #[test]
3793    fn line_col_offset_zero() {
3794        let offsets = compute_line_offsets("abc\ndef\nghi");
3795        let (line, col) = byte_offset_to_line_col(&offsets, 0);
3796        assert_eq!((line, col), (1, 0));
3797    }
3798
3799    #[test]
3800    fn line_col_middle_of_first_line() {
3801        let offsets = compute_line_offsets("abc\ndef\nghi");
3802        let (line, col) = byte_offset_to_line_col(&offsets, 2);
3803        assert_eq!((line, col), (1, 2));
3804    }
3805
3806    #[test]
3807    fn line_col_start_of_second_line() {
3808        let offsets = compute_line_offsets("abc\ndef\nghi");
3809        let (line, col) = byte_offset_to_line_col(&offsets, 4);
3810        assert_eq!((line, col), (2, 0));
3811    }
3812
3813    #[test]
3814    fn line_col_middle_of_second_line() {
3815        let offsets = compute_line_offsets("abc\ndef\nghi");
3816        let (line, col) = byte_offset_to_line_col(&offsets, 5);
3817        assert_eq!((line, col), (2, 1));
3818    }
3819
3820    #[test]
3821    fn line_col_start_of_third_line() {
3822        let offsets = compute_line_offsets("abc\ndef\nghi");
3823        let (line, col) = byte_offset_to_line_col(&offsets, 8);
3824        assert_eq!((line, col), (3, 0));
3825    }
3826
3827    #[test]
3828    fn line_col_end_of_file() {
3829        let offsets = compute_line_offsets("abc\ndef\nghi");
3830        let (line, col) = byte_offset_to_line_col(&offsets, 10);
3831        assert_eq!((line, col), (3, 2));
3832    }
3833
3834    #[test]
3835    fn line_col_single_line() {
3836        let offsets = compute_line_offsets("hello");
3837        let (line, col) = byte_offset_to_line_col(&offsets, 3);
3838        assert_eq!((line, col), (1, 3));
3839    }
3840
3841    #[test]
3842    fn line_col_at_newline_byte() {
3843        let offsets = compute_line_offsets("abc\ndef");
3844        let (line, col) = byte_offset_to_line_col(&offsets, 3);
3845        assert_eq!((line, col), (1, 3));
3846    }
3847
3848    #[test]
3849    fn export_name_matches_str_named() {
3850        let name = ExportName::Named("foo".to_string());
3851        assert!(name.matches_str("foo"));
3852        assert!(!name.matches_str("bar"));
3853        assert!(!name.matches_str("default"));
3854    }
3855
3856    #[test]
3857    fn export_name_matches_str_default() {
3858        let name = ExportName::Default;
3859        assert!(name.matches_str("default"));
3860        assert!(!name.matches_str("foo"));
3861    }
3862
3863    #[test]
3864    fn export_name_display_named() {
3865        let name = ExportName::Named("myExport".to_string());
3866        assert_eq!(name.to_string(), "myExport");
3867    }
3868
3869    #[test]
3870    fn export_name_display_default() {
3871        let name = ExportName::Default;
3872        assert_eq!(name.to_string(), "default");
3873    }
3874
3875    #[test]
3876    fn export_name_equality_named() {
3877        let a = ExportName::Named("foo".to_string());
3878        let b = ExportName::Named("foo".to_string());
3879        let c = ExportName::Named("bar".to_string());
3880        assert_eq!(a, b);
3881        assert_ne!(a, c);
3882    }
3883
3884    #[test]
3885    fn export_name_equality_default() {
3886        let a = ExportName::Default;
3887        let b = ExportName::Default;
3888        assert_eq!(a, b);
3889    }
3890
3891    #[test]
3892    fn export_name_named_not_equal_to_default() {
3893        let named = ExportName::Named("default".to_string());
3894        let default = ExportName::Default;
3895        assert_ne!(named, default);
3896    }
3897
3898    #[test]
3899    fn export_name_hash_consistency() {
3900        use std::collections::hash_map::DefaultHasher;
3901        use std::hash::{Hash, Hasher};
3902
3903        let mut h1 = DefaultHasher::new();
3904        let mut h2 = DefaultHasher::new();
3905        ExportName::Named("foo".to_string()).hash(&mut h1);
3906        ExportName::Named("foo".to_string()).hash(&mut h2);
3907        assert_eq!(h1.finish(), h2.finish());
3908    }
3909
3910    #[test]
3911    fn export_name_matches_str_empty_string() {
3912        let name = ExportName::Named(String::new());
3913        assert!(name.matches_str(""));
3914        assert!(!name.matches_str("foo"));
3915    }
3916
3917    #[test]
3918    fn export_name_default_does_not_match_empty() {
3919        let name = ExportName::Default;
3920        assert!(!name.matches_str(""));
3921    }
3922
3923    #[test]
3924    fn imported_name_equality() {
3925        assert_eq!(
3926            ImportedName::Named("foo".to_string()),
3927            ImportedName::Named("foo".to_string())
3928        );
3929        assert_ne!(
3930            ImportedName::Named("foo".to_string()),
3931            ImportedName::Named("bar".to_string())
3932        );
3933        assert_eq!(ImportedName::Default, ImportedName::Default);
3934        assert_eq!(ImportedName::Namespace, ImportedName::Namespace);
3935        assert_eq!(ImportedName::SideEffect, ImportedName::SideEffect);
3936        assert_ne!(ImportedName::Default, ImportedName::Namespace);
3937        assert_ne!(
3938            ImportedName::Named("default".to_string()),
3939            ImportedName::Default
3940        );
3941    }
3942
3943    #[test]
3944    fn member_kind_equality() {
3945        assert_eq!(MemberKind::EnumMember, MemberKind::EnumMember);
3946        assert_eq!(MemberKind::ClassMethod, MemberKind::ClassMethod);
3947        assert_eq!(MemberKind::ClassProperty, MemberKind::ClassProperty);
3948        assert_eq!(MemberKind::NamespaceMember, MemberKind::NamespaceMember);
3949        assert_ne!(MemberKind::EnumMember, MemberKind::ClassMethod);
3950        assert_ne!(MemberKind::ClassMethod, MemberKind::ClassProperty);
3951        assert_ne!(MemberKind::NamespaceMember, MemberKind::EnumMember);
3952    }
3953
3954    #[test]
3955    fn member_kind_bitcode_roundtrip() {
3956        let kinds = [
3957            MemberKind::EnumMember,
3958            MemberKind::ClassMethod,
3959            MemberKind::ClassProperty,
3960            MemberKind::NamespaceMember,
3961        ];
3962        for kind in &kinds {
3963            let bytes = bitcode::encode(kind);
3964            let decoded: MemberKind = bitcode::decode(&bytes).unwrap();
3965            assert_eq!(&decoded, kind);
3966        }
3967    }
3968
3969    #[test]
3970    fn member_access_bitcode_roundtrip() {
3971        let access = MemberAccess {
3972            object: "Status".to_string(),
3973            member: "Active".to_string(),
3974        };
3975        let bytes = bitcode::encode(&access);
3976        let decoded: MemberAccess = bitcode::decode(&bytes).unwrap();
3977        assert_eq!(decoded.object, "Status");
3978        assert_eq!(decoded.member, "Active");
3979    }
3980
3981    #[test]
3982    fn line_offsets_crlf_only_counts_lf() {
3983        let offsets = compute_line_offsets("ab\r\ncd");
3984        assert_eq!(offsets, vec![0, 4]);
3985    }
3986
3987    #[test]
3988    fn line_col_empty_file_offset_zero() {
3989        let offsets = compute_line_offsets("");
3990        let (line, col) = byte_offset_to_line_col(&offsets, 0);
3991        assert_eq!((line, col), (1, 0));
3992    }
3993
3994    // --- VisibilityTag ---
3995
3996    #[test]
3997    fn visibility_tag_default_is_none_variant() {
3998        assert_eq!(VisibilityTag::default(), VisibilityTag::None);
3999    }
4000
4001    #[test]
4002    fn visibility_tag_is_none_only_for_none_variant() {
4003        assert!(VisibilityTag::None.is_none());
4004        assert!(!VisibilityTag::Public.is_none());
4005        assert!(!VisibilityTag::Internal.is_none());
4006        assert!(!VisibilityTag::Beta.is_none());
4007        assert!(!VisibilityTag::Alpha.is_none());
4008        assert!(!VisibilityTag::ExpectedUnused.is_none());
4009    }
4010
4011    #[test]
4012    fn visibility_tag_suppresses_unused_for_api_tags() {
4013        assert!(VisibilityTag::Public.suppresses_unused());
4014        assert!(VisibilityTag::Internal.suppresses_unused());
4015        assert!(VisibilityTag::Beta.suppresses_unused());
4016        assert!(VisibilityTag::Alpha.suppresses_unused());
4017    }
4018
4019    #[test]
4020    fn visibility_tag_does_not_suppress_none_or_expected_unused() {
4021        assert!(!VisibilityTag::None.suppresses_unused());
4022        assert!(!VisibilityTag::ExpectedUnused.suppresses_unused());
4023    }
4024
4025    // --- is_public_env_path ---
4026
4027    #[test]
4028    fn is_public_env_path_process_env_public_prefix() {
4029        assert!(is_public_env_path("process.env.NEXT_PUBLIC_API_URL"));
4030        assert!(is_public_env_path("process.env.VITE_APP_KEY"));
4031        assert!(is_public_env_path("process.env.REACT_APP_TITLE"));
4032        assert!(is_public_env_path("process.env.NODE_ENV"));
4033    }
4034
4035    #[test]
4036    fn is_public_env_path_import_meta_env_public_prefix() {
4037        assert!(is_public_env_path("import.meta.env.VITE_BASE_URL"));
4038        assert!(is_public_env_path("import.meta.env.PUBLIC_API"));
4039    }
4040
4041    #[test]
4042    fn is_public_env_path_secret_env_vars_are_not_public() {
4043        assert!(!is_public_env_path("process.env.SECRET_KEY"));
4044        assert!(!is_public_env_path("process.env.DATABASE_PASSWORD"));
4045        assert!(!is_public_env_path("import.meta.env.API_TOKEN"));
4046    }
4047
4048    #[test]
4049    fn is_public_env_path_non_env_paths_are_not_public() {
4050        assert!(!is_public_env_path("req.query.id"));
4051        assert!(!is_public_env_path("process.argv"));
4052        assert!(!is_public_env_path("window.location.href"));
4053    }
4054
4055    // --- is_public_env_var edge cases ---
4056
4057    #[test]
4058    fn is_public_env_var_exact_matches() {
4059        assert!(is_public_env_var("NODE_ENV"));
4060    }
4061
4062    #[test]
4063    fn is_public_env_var_all_known_prefixes() {
4064        assert!(is_public_env_var("NUXT_PUBLIC_API_URL"));
4065        assert!(is_public_env_var("PUBLIC_API_KEY"));
4066        assert!(is_public_env_var("GATSBY_APP_ID"));
4067        assert!(is_public_env_var("EXPO_PUBLIC_SENTRY_DSN"));
4068        assert!(is_public_env_var("STORYBOOK_ENV"));
4069    }
4070
4071    #[test]
4072    fn is_public_env_var_secret_token_beats_metadata_token() {
4073        // "SECRET_SHA": has SECRET (wins) and SHA (metadata); should NOT be public
4074        assert!(!is_public_env_var("SECRET_SHA"));
4075        // "REF_TOKEN": has TOKEN (secret) and REF (metadata); should NOT be public
4076        assert!(!is_public_env_var("REF_TOKEN"));
4077    }
4078
4079    #[test]
4080    fn is_public_env_var_plain_unknown_names_are_not_public() {
4081        assert!(!is_public_env_var("MY_SERVICE_URL"));
4082        assert!(!is_public_env_var("FEATURE_FLAG"));
4083        assert!(!is_public_env_var("DATABASE_URL"));
4084    }
4085
4086    // --- SinkSite::span ---
4087
4088    #[test]
4089    fn sink_site_span_reconstructs_from_offsets() {
4090        let site = SinkSite {
4091            sink_shape: SinkShape::Call,
4092            callee_path: "eval".to_string(),
4093            arg_index: 0,
4094            arg_is_non_literal: true,
4095            arg_kind: SinkArgKind::Other,
4096            arg_literal: None,
4097            regex_pattern: None,
4098            object_properties: Vec::new(),
4099            object_property_keys: Vec::new(),
4100            object_property_keys_complete: false,
4101            arg_idents: Vec::new(),
4102            arg_source_paths: Vec::new(),
4103            span_start: 5,
4104            span_end: 15,
4105            url_arg_literal: None,
4106            url_shape: None,
4107        };
4108        let s = site.span();
4109        assert_eq!(s.start, 5);
4110        assert_eq!(s.end, 15);
4111    }
4112
4113    // --- SecurityControlKind ---
4114
4115    #[test]
4116    fn security_control_kind_equality_and_ordering() {
4117        assert_eq!(
4118            SecurityControlKind::Sanitization,
4119            SecurityControlKind::Sanitization
4120        );
4121        assert_eq!(
4122            SecurityControlKind::Validation,
4123            SecurityControlKind::Validation
4124        );
4125        assert_ne!(
4126            SecurityControlKind::Sanitization,
4127            SecurityControlKind::Validation
4128        );
4129        assert!(SecurityControlKind::Sanitization < SecurityControlKind::Validation);
4130        assert!(SecurityControlKind::Authentication < SecurityControlKind::Authorization);
4131    }
4132
4133    // --- SanitizerScope ---
4134
4135    #[test]
4136    fn sanitizer_scope_equality_and_ordering() {
4137        assert_eq!(SanitizerScope::Html, SanitizerScope::Html);
4138        assert_eq!(SanitizerScope::Url, SanitizerScope::Url);
4139        assert_eq!(SanitizerScope::Path, SanitizerScope::Path);
4140        assert_eq!(SanitizerScope::SqlIdentifier, SanitizerScope::SqlIdentifier);
4141        assert_ne!(SanitizerScope::Html, SanitizerScope::Url);
4142        assert!(SanitizerScope::Html < SanitizerScope::Url);
4143    }
4144
4145    // --- SkippedSecurityCalleeReason ---
4146
4147    #[test]
4148    fn skipped_security_callee_reason_equality() {
4149        assert_eq!(
4150            SkippedSecurityCalleeReason::ComputedMember,
4151            SkippedSecurityCalleeReason::ComputedMember
4152        );
4153        assert_ne!(
4154            SkippedSecurityCalleeReason::ComputedMember,
4155            SkippedSecurityCalleeReason::DynamicDispatch
4156        );
4157        assert_ne!(
4158            SkippedSecurityCalleeReason::DynamicDispatch,
4159            SkippedSecurityCalleeReason::UnsupportedAssignmentObject
4160        );
4161    }
4162
4163    // --- SkippedSecurityCalleeExpressionKind ---
4164
4165    #[test]
4166    fn skipped_security_callee_expression_kind_equality() {
4167        use SkippedSecurityCalleeExpressionKind as K;
4168        assert_eq!(K::StaticMemberExpression, K::StaticMemberExpression);
4169        assert_eq!(K::ComputedMemberExpression, K::ComputedMemberExpression);
4170        assert_eq!(K::Identifier, K::Identifier);
4171        assert_eq!(K::Other, K::Other);
4172        assert_ne!(K::StaticMemberExpression, K::ComputedMemberExpression);
4173        assert_ne!(K::Identifier, K::Other);
4174    }
4175
4176    // --- SinkLiteralValue ---
4177
4178    #[test]
4179    fn sink_literal_value_equality() {
4180        assert_eq!(
4181            SinkLiteralValue::String("x".to_string()),
4182            SinkLiteralValue::String("x".to_string())
4183        );
4184        assert_ne!(
4185            SinkLiteralValue::String("x".to_string()),
4186            SinkLiteralValue::String("y".to_string())
4187        );
4188        assert_eq!(SinkLiteralValue::Integer(42), SinkLiteralValue::Integer(42));
4189        assert_ne!(SinkLiteralValue::Integer(1), SinkLiteralValue::Integer(2));
4190        assert_eq!(
4191            SinkLiteralValue::Boolean(true),
4192            SinkLiteralValue::Boolean(true)
4193        );
4194        assert_ne!(
4195            SinkLiteralValue::Boolean(true),
4196            SinkLiteralValue::Boolean(false)
4197        );
4198        assert_eq!(SinkLiteralValue::Null, SinkLiteralValue::Null);
4199        assert_ne!(SinkLiteralValue::Null, SinkLiteralValue::Boolean(false));
4200    }
4201
4202    // --- SecurityUrlShape ---
4203
4204    #[test]
4205    fn security_url_shape_equality() {
4206        assert_eq!(
4207            SecurityUrlShape::FixedOriginDynamicPath,
4208            SecurityUrlShape::FixedOriginDynamicPath
4209        );
4210        assert_eq!(
4211            SecurityUrlShape::DynamicOrigin,
4212            SecurityUrlShape::DynamicOrigin
4213        );
4214        assert_ne!(
4215            SecurityUrlShape::FixedOriginDynamicPath,
4216            SecurityUrlShape::DynamicOrigin
4217        );
4218    }
4219
4220    // --- FlagUseKind ---
4221
4222    #[test]
4223    fn flag_use_kind_equality() {
4224        assert_eq!(FlagUseKind::EnvVar, FlagUseKind::EnvVar);
4225        assert_eq!(FlagUseKind::SdkCall, FlagUseKind::SdkCall);
4226        assert_eq!(FlagUseKind::ConfigObject, FlagUseKind::ConfigObject);
4227        assert_ne!(FlagUseKind::EnvVar, FlagUseKind::SdkCall);
4228        assert_ne!(FlagUseKind::SdkCall, FlagUseKind::ConfigObject);
4229    }
4230
4231    // --- ComplexityMetric ---
4232
4233    #[test]
4234    fn complexity_metric_equality() {
4235        assert_eq!(ComplexityMetric::Cyclomatic, ComplexityMetric::Cyclomatic);
4236        assert_eq!(ComplexityMetric::Cognitive, ComplexityMetric::Cognitive);
4237        assert_ne!(ComplexityMetric::Cyclomatic, ComplexityMetric::Cognitive);
4238    }
4239
4240    // --- ComplexityContributionKind ---
4241
4242    #[test]
4243    fn complexity_contribution_kind_equality_spot_check() {
4244        use ComplexityContributionKind as K;
4245        assert_eq!(K::If, K::If);
4246        assert_eq!(K::Else, K::Else);
4247        assert_eq!(K::ElseIf, K::ElseIf);
4248        assert_eq!(K::Ternary, K::Ternary);
4249        assert_eq!(K::LogicalAnd, K::LogicalAnd);
4250        assert_eq!(K::LogicalOr, K::LogicalOr);
4251        assert_eq!(K::NullishCoalescing, K::NullishCoalescing);
4252        assert_eq!(K::LogicalAssignment, K::LogicalAssignment);
4253        assert_eq!(K::OptionalChain, K::OptionalChain);
4254        assert_eq!(K::For, K::For);
4255        assert_eq!(K::ForIn, K::ForIn);
4256        assert_eq!(K::ForOf, K::ForOf);
4257        assert_eq!(K::While, K::While);
4258        assert_eq!(K::DoWhile, K::DoWhile);
4259        assert_eq!(K::Switch, K::Switch);
4260        assert_eq!(K::Case, K::Case);
4261        assert_eq!(K::Catch, K::Catch);
4262        assert_eq!(K::LabeledBreak, K::LabeledBreak);
4263        assert_eq!(K::LabeledContinue, K::LabeledContinue);
4264        assert_eq!(K::JsxDepth, K::JsxDepth);
4265        assert_eq!(K::HookDensity, K::HookDensity);
4266        assert_eq!(K::PropCount, K::PropCount);
4267        assert_eq!(K::Await, K::Await);
4268        assert_eq!(K::Then, K::Then);
4269        assert_ne!(K::If, K::Else);
4270        assert_ne!(K::For, K::While);
4271        assert_ne!(K::Switch, K::Case);
4272    }
4273
4274    // --- MisplacedDirectiveSite ---
4275
4276    #[test]
4277    fn misplaced_directive_site_equality() {
4278        let client = MisplacedDirectiveSite {
4279            is_server: false,
4280            span_start: 10,
4281        };
4282        let server = MisplacedDirectiveSite {
4283            is_server: true,
4284            span_start: 10,
4285        };
4286        let client2 = MisplacedDirectiveSite {
4287            is_server: false,
4288            span_start: 10,
4289        };
4290        assert_eq!(client, client2);
4291        assert_ne!(client, server);
4292    }
4293
4294    #[test]
4295    fn misplaced_directive_site_is_server_flag() {
4296        let site = MisplacedDirectiveSite {
4297            is_server: true,
4298            span_start: 42,
4299        };
4300        assert!(site.is_server);
4301        assert_eq!(site.span_start, 42);
4302
4303        let client_site = MisplacedDirectiveSite {
4304            is_server: false,
4305            span_start: 0,
4306        };
4307        assert!(!client_site.is_server);
4308    }
4309
4310    // --- DiRole / DiFramework ---
4311
4312    #[test]
4313    fn di_role_equality() {
4314        assert_eq!(DiRole::Provide, DiRole::Provide);
4315        assert_eq!(DiRole::Inject, DiRole::Inject);
4316        assert_ne!(DiRole::Provide, DiRole::Inject);
4317    }
4318
4319    #[test]
4320    fn di_framework_equality() {
4321        assert_eq!(DiFramework::Vue, DiFramework::Vue);
4322        assert_eq!(DiFramework::Svelte, DiFramework::Svelte);
4323        assert_eq!(DiFramework::Angular, DiFramework::Angular);
4324        assert_ne!(DiFramework::Vue, DiFramework::Svelte);
4325        assert_ne!(DiFramework::Svelte, DiFramework::Angular);
4326    }
4327
4328    // --- ComponentEmit ---
4329
4330    #[test]
4331    fn component_emit_equality() {
4332        let a = ComponentEmit {
4333            name: "close".to_string(),
4334            span_start: 10,
4335            used: true,
4336        };
4337        let b = ComponentEmit {
4338            name: "close".to_string(),
4339            span_start: 10,
4340            used: true,
4341        };
4342        let different_used = ComponentEmit {
4343            name: "close".to_string(),
4344            span_start: 10,
4345            used: false,
4346        };
4347        let different_name = ComponentEmit {
4348            name: "open".to_string(),
4349            span_start: 10,
4350            used: true,
4351        };
4352        assert_eq!(a, b);
4353        assert_ne!(a, different_used);
4354        assert_ne!(a, different_name);
4355    }
4356
4357    // --- DispatchedEvent ---
4358
4359    #[test]
4360    fn dispatched_event_equality() {
4361        let a = DispatchedEvent {
4362            name: "myEvent".to_string(),
4363            span_start: 20,
4364        };
4365        let b = DispatchedEvent {
4366            name: "myEvent".to_string(),
4367            span_start: 20,
4368        };
4369        let c = DispatchedEvent {
4370            name: "otherEvent".to_string(),
4371            span_start: 20,
4372        };
4373        let d = DispatchedEvent {
4374            name: "myEvent".to_string(),
4375            span_start: 99,
4376        };
4377        assert_eq!(a, b);
4378        assert_ne!(a, c);
4379        assert_ne!(a, d);
4380    }
4381
4382    // --- AngularInputMember / AngularOutputMember ---
4383
4384    #[test]
4385    fn angular_input_member_equality() {
4386        let a = AngularInputMember {
4387            name: "title".to_string(),
4388            span_start: 5,
4389        };
4390        let b = AngularInputMember {
4391            name: "title".to_string(),
4392            span_start: 5,
4393        };
4394        let c = AngularInputMember {
4395            name: "label".to_string(),
4396            span_start: 5,
4397        };
4398        assert_eq!(a, b);
4399        assert_ne!(a, c);
4400    }
4401
4402    #[test]
4403    fn angular_output_member_equality() {
4404        let a = AngularOutputMember {
4405            name: "clicked".to_string(),
4406            span_start: 8,
4407        };
4408        let b = AngularOutputMember {
4409            name: "clicked".to_string(),
4410            span_start: 8,
4411        };
4412        let c = AngularOutputMember {
4413            name: "hovered".to_string(),
4414            span_start: 8,
4415        };
4416        assert_eq!(a, b);
4417        assert_ne!(a, c);
4418    }
4419
4420    // --- AngularComponentSelector ---
4421
4422    #[test]
4423    fn angular_component_selector_fields() {
4424        let s = AngularComponentSelector {
4425            selectors: vec!["app-foo".to_string(), "[appFoo]".to_string()],
4426            span_start: 100,
4427            class_name: "FooComponent".to_string(),
4428        };
4429        assert_eq!(s.selectors.len(), 2);
4430        assert_eq!(s.selectors[0], "app-foo");
4431        assert_eq!(s.selectors[1], "[appFoo]");
4432        assert_eq!(s.class_name, "FooComponent");
4433    }
4434
4435    #[test]
4436    fn angular_component_selector_equality() {
4437        let a = AngularComponentSelector {
4438            selectors: vec!["app-bar".to_string()],
4439            span_start: 0,
4440            class_name: "BarComponent".to_string(),
4441        };
4442        let b = AngularComponentSelector {
4443            selectors: vec!["app-bar".to_string()],
4444            span_start: 0,
4445            class_name: "BarComponent".to_string(),
4446        };
4447        let c = AngularComponentSelector {
4448            selectors: vec!["app-baz".to_string()],
4449            span_start: 0,
4450            class_name: "BazComponent".to_string(),
4451        };
4452        assert_eq!(a, b);
4453        assert_ne!(a, c);
4454    }
4455
4456    // --- LoadReturnKey ---
4457
4458    #[test]
4459    fn load_return_key_equality() {
4460        let a = LoadReturnKey {
4461            name: "user".to_string(),
4462            span_start: 50,
4463            span_end: 54,
4464        };
4465        let b = LoadReturnKey {
4466            name: "user".to_string(),
4467            span_start: 50,
4468            span_end: 54,
4469        };
4470        let c = LoadReturnKey {
4471            name: "posts".to_string(),
4472            span_start: 50,
4473            span_end: 55,
4474        };
4475        assert_eq!(a, b);
4476        assert_ne!(a, c);
4477    }
4478
4479    #[test]
4480    fn load_return_key_span_fields() {
4481        let key = LoadReturnKey {
4482            name: "data".to_string(),
4483            span_start: 10,
4484            span_end: 14,
4485        };
4486        assert_eq!(key.span_start, 10);
4487        assert_eq!(key.span_end, 14);
4488        assert_eq!(key.name, "data");
4489    }
4490
4491    // --- ComponentFunctionKind ---
4492
4493    #[test]
4494    fn component_function_kind_equality() {
4495        assert_eq!(ComponentFunctionKind::FnDecl, ComponentFunctionKind::FnDecl);
4496        assert_eq!(ComponentFunctionKind::Arrow, ComponentFunctionKind::Arrow);
4497        assert_eq!(
4498            ComponentFunctionKind::ForwardRefWrapper,
4499            ComponentFunctionKind::ForwardRefWrapper
4500        );
4501        assert_eq!(
4502            ComponentFunctionKind::MemoWrapper,
4503            ComponentFunctionKind::MemoWrapper
4504        );
4505        assert_ne!(ComponentFunctionKind::FnDecl, ComponentFunctionKind::Arrow);
4506        assert_ne!(
4507            ComponentFunctionKind::ForwardRefWrapper,
4508            ComponentFunctionKind::MemoWrapper
4509        );
4510    }
4511
4512    // --- HookUseKind ---
4513
4514    #[test]
4515    fn hook_use_kind_equality() {
4516        assert_eq!(HookUseKind::UseState, HookUseKind::UseState);
4517        assert_eq!(HookUseKind::UseEffect, HookUseKind::UseEffect);
4518        assert_eq!(HookUseKind::UseMemo, HookUseKind::UseMemo);
4519        assert_eq!(HookUseKind::UseCallback, HookUseKind::UseCallback);
4520        assert_eq!(HookUseKind::Custom, HookUseKind::Custom);
4521        assert_ne!(HookUseKind::UseState, HookUseKind::UseEffect);
4522        assert_ne!(HookUseKind::UseMemo, HookUseKind::Custom);
4523    }
4524
4525    // --- HookUse ---
4526
4527    #[test]
4528    fn hook_use_fields() {
4529        let h = HookUse {
4530            kind: HookUseKind::UseEffect,
4531            dep_array_arity: Some(2),
4532            span_start: 30,
4533            component: "Widget".to_string(),
4534        };
4535        assert_eq!(h.kind, HookUseKind::UseEffect);
4536        assert_eq!(h.dep_array_arity, Some(2));
4537        assert_eq!(h.span_start, 30);
4538        assert_eq!(h.component, "Widget");
4539    }
4540
4541    #[test]
4542    fn hook_use_no_dep_array() {
4543        let h = HookUse {
4544            kind: HookUseKind::UseCallback,
4545            dep_array_arity: None,
4546            span_start: 0,
4547            component: String::new(),
4548        };
4549        assert!(h.dep_array_arity.is_none());
4550    }
4551
4552    // --- MemberKind::StoreMember (missed in existing bitcode test) ---
4553
4554    #[test]
4555    fn member_kind_store_member_bitcode_roundtrip() {
4556        let kind = MemberKind::StoreMember;
4557        let bytes = bitcode::encode(&kind);
4558        let decoded: MemberKind = bitcode::decode(&bytes).unwrap();
4559        assert_eq!(decoded, kind);
4560    }
4561
4562    // --- RenderEdge / ForwardAttr ---
4563
4564    #[test]
4565    fn render_edge_fields() {
4566        let edge = RenderEdge {
4567            parent_component: "Parent".to_string(),
4568            child_component_name: "Child".to_string(),
4569            attr_names: vec!["title".to_string(), "onClick".to_string()],
4570            has_spread: false,
4571            forward_attrs: vec![ForwardAttr {
4572                attr: "title".to_string(),
4573                root: "props".to_string(),
4574            }],
4575            has_complex_forward: false,
4576        };
4577        assert_eq!(edge.parent_component, "Parent");
4578        assert_eq!(edge.child_component_name, "Child");
4579        assert_eq!(edge.attr_names.len(), 2);
4580        assert!(!edge.has_spread);
4581        assert_eq!(edge.forward_attrs.len(), 1);
4582        assert_eq!(edge.forward_attrs[0].attr, "title");
4583        assert_eq!(edge.forward_attrs[0].root, "props");
4584        assert!(!edge.has_complex_forward);
4585    }
4586
4587    #[test]
4588    fn render_edge_with_spread() {
4589        let edge = RenderEdge {
4590            parent_component: "Wrapper".to_string(),
4591            child_component_name: "Inner".to_string(),
4592            attr_names: Vec::new(),
4593            has_spread: true,
4594            forward_attrs: Vec::new(),
4595            has_complex_forward: true,
4596        };
4597        assert!(edge.has_spread);
4598        assert!(edge.has_complex_forward);
4599    }
4600
4601    // --- ComponentFunction ---
4602
4603    #[test]
4604    fn component_function_fields() {
4605        let cf = ComponentFunction {
4606            name: "MyButton".to_string(),
4607            span_start: 0,
4608            kind: ComponentFunctionKind::Arrow,
4609            is_exported: true,
4610            has_unharvestable_props: false,
4611            uses_clone_element: false,
4612            renders_provider: false,
4613            has_children_as_function: false,
4614            is_pure_passthrough: false,
4615        };
4616        assert_eq!(cf.name, "MyButton");
4617        assert_eq!(cf.kind, ComponentFunctionKind::Arrow);
4618        assert!(cf.is_exported);
4619        assert!(!cf.has_unharvestable_props);
4620        assert!(!cf.is_pure_passthrough);
4621    }
4622
4623    #[test]
4624    fn component_function_passthrough_flag() {
4625        let cf = ComponentFunction {
4626            name: "Passthrough".to_string(),
4627            span_start: 5,
4628            kind: ComponentFunctionKind::FnDecl,
4629            is_exported: false,
4630            has_unharvestable_props: false,
4631            uses_clone_element: false,
4632            renders_provider: false,
4633            has_children_as_function: false,
4634            is_pure_passthrough: true,
4635        };
4636        assert!(cf.is_pure_passthrough);
4637        assert!(!cf.is_exported);
4638    }
4639
4640    // --- DiKeySite ---
4641
4642    #[test]
4643    fn di_key_site_fields() {
4644        let site = DiKeySite {
4645            key_local: "MY_KEY".to_string(),
4646            role: DiRole::Provide,
4647            framework: DiFramework::Vue,
4648            span_start: 77,
4649        };
4650        assert_eq!(site.key_local, "MY_KEY");
4651        assert_eq!(site.role, DiRole::Provide);
4652        assert_eq!(site.framework, DiFramework::Vue);
4653        assert_eq!(site.span_start, 77);
4654    }
4655
4656    #[test]
4657    fn di_key_site_inject_svelte() {
4658        let site = DiKeySite {
4659            key_local: "ctx_key".to_string(),
4660            role: DiRole::Inject,
4661            framework: DiFramework::Svelte,
4662            span_start: 0,
4663        };
4664        assert_eq!(site.role, DiRole::Inject);
4665        assert_eq!(site.framework, DiFramework::Svelte);
4666    }
4667
4668    // --- release_resolution_payload: page data store whole-use derivation ---
4669
4670    #[test]
4671    fn release_payload_derives_page_data_store_whole_use_from_page_data() {
4672        let mut m = minimal_module_info();
4673        m.whole_object_uses = vec!["page.data".to_string()].into();
4674        m.release_resolution_payload();
4675        assert!(m.has_page_data_store_whole_use);
4676    }
4677
4678    #[test]
4679    fn release_payload_derives_page_data_store_whole_use_from_dollar_page_data() {
4680        let mut m = minimal_module_info();
4681        m.whole_object_uses = vec!["$page.data".to_string()].into();
4682        m.release_resolution_payload();
4683        assert!(m.has_page_data_store_whole_use);
4684    }
4685
4686    #[test]
4687    fn release_payload_does_not_set_page_data_store_whole_use_for_other_names() {
4688        let mut m = minimal_module_info();
4689        m.whole_object_uses = vec!["data".to_string(), "page".to_string()].into();
4690        m.release_resolution_payload();
4691        assert!(!m.has_page_data_store_whole_use);
4692    }
4693
4694    #[test]
4695    fn release_payload_derives_route_loader_data_whole_use() {
4696        let mut m = minimal_module_info();
4697        m.whole_object_uses = vec!["$fallow.routeLoaderData".to_string()].into();
4698        m.release_resolution_payload();
4699        assert!(m.has_route_loader_data_whole_use);
4700    }
4701
4702    // --- release_resolution_payload: referenced_import_bindings derivation ---
4703
4704    #[test]
4705    fn release_payload_referenced_bindings_excludes_empty_local_names() {
4706        let mut m = minimal_module_info();
4707        m.imports = vec![
4708            ImportInfo {
4709                source: "./styles.css".to_string(),
4710                imported_name: ImportedName::SideEffect,
4711                local_name: String::new(), // empty = side-effect import
4712                is_type_only: false,
4713                from_style: true,
4714                span: span(),
4715                source_span: span(),
4716            },
4717            ImportInfo {
4718                source: "react".to_string(),
4719                imported_name: ImportedName::Default,
4720                local_name: "React".to_string(),
4721                is_type_only: false,
4722                from_style: false,
4723                span: span(),
4724                source_span: span(),
4725            },
4726        ];
4727        m.unused_import_bindings = vec!["React".to_string()];
4728        m.release_resolution_payload();
4729        // "React" was unused, empty local is filtered; result should be empty
4730        assert!(m.referenced_import_bindings.is_empty());
4731    }
4732
4733    #[test]
4734    fn release_payload_referenced_bindings_sorted_and_deduped() {
4735        let mut m = minimal_module_info();
4736        // Two imports with the same local name (unusual but possible via re-exports)
4737        m.imports = vec![
4738            ImportInfo {
4739                source: "a".to_string(),
4740                imported_name: ImportedName::Named("foo".to_string()),
4741                local_name: "foo".to_string(),
4742                is_type_only: false,
4743                from_style: false,
4744                span: span(),
4745                source_span: span(),
4746            },
4747            ImportInfo {
4748                source: "b".to_string(),
4749                imported_name: ImportedName::Named("bar".to_string()),
4750                local_name: "bar".to_string(),
4751                is_type_only: false,
4752                from_style: false,
4753                span: span(),
4754                source_span: span(),
4755            },
4756            ImportInfo {
4757                source: "c".to_string(),
4758                imported_name: ImportedName::Named("foo".to_string()),
4759                local_name: "foo".to_string(),
4760                is_type_only: false,
4761                from_style: false,
4762                span: span(),
4763                source_span: span(),
4764            },
4765        ];
4766        m.unused_import_bindings = Vec::new();
4767        m.release_resolution_payload();
4768        // sorted: ["bar", "foo"] with "foo" deduped
4769        assert_eq!(
4770            m.referenced_import_bindings,
4771            vec!["bar".to_string(), "foo".to_string()]
4772        );
4773    }
4774
4775    // --- CalleeUse ---
4776
4777    #[test]
4778    fn callee_use_fields() {
4779        let cu = CalleeUse {
4780            callee_path: "child_process.exec".to_string(),
4781            span_start: 100,
4782        };
4783        assert_eq!(cu.callee_path, "child_process.exec");
4784        assert_eq!(cu.span_start, 100);
4785    }
4786
4787    // --- Helper to build a minimal ModuleInfo for targeted tests ---
4788
4789    fn minimal_module_info() -> ModuleInfo {
4790        ModuleInfo::empty(FileId(0))
4791    }
4792
4793    fn push_semantic_fact(module: &mut ModuleInfo, fact: SemanticFact) {
4794        let mut facts = std::mem::take(&mut module.semantic_facts).to_vec();
4795        facts.push(fact);
4796        module.semantic_facts = facts.into();
4797    }
4798
4799    #[test]
4800    fn dynamic_custom_element_render_helper_prefers_typed_fact() {
4801        let mut module = minimal_module_info();
4802        push_semantic_fact(
4803            &mut module,
4804            SemanticFact::DynamicCustomElementRender(DynamicCustomElementRenderFact),
4805        );
4806
4807        assert!(has_dynamic_custom_element_render(&module));
4808    }
4809
4810    #[test]
4811    fn function_complexity_bitcode_roundtrip() {
4812        let fc = FunctionComplexity {
4813            name: "processData".to_string(),
4814            line: 42,
4815            col: 4,
4816            cyclomatic: 15,
4817            cognitive: 25,
4818            line_count: 80,
4819            param_count: 3,
4820            react_hook_count: 0,
4821            react_jsx_max_depth: 0,
4822            react_prop_count: 0,
4823            source_hash: Some("0123456789abcdef".to_string()),
4824            contributions: vec![
4825                ComplexityContribution {
4826                    line: 43,
4827                    col: 8,
4828                    metric: ComplexityMetric::Cyclomatic,
4829                    kind: ComplexityContributionKind::If,
4830                    weight: 1,
4831                    nesting: 0,
4832                },
4833                ComplexityContribution {
4834                    line: 45,
4835                    col: 12,
4836                    metric: ComplexityMetric::Cognitive,
4837                    kind: ComplexityContributionKind::ElseIf,
4838                    weight: 3,
4839                    nesting: 2,
4840                },
4841            ],
4842        };
4843        let bytes = bitcode::encode(&fc);
4844        let decoded: FunctionComplexity = bitcode::decode(&bytes).unwrap();
4845        assert_eq!(decoded.name, "processData");
4846        assert_eq!(decoded.line, 42);
4847        assert_eq!(decoded.col, 4);
4848        assert_eq!(decoded.cyclomatic, 15);
4849        assert_eq!(decoded.cognitive, 25);
4850        assert_eq!(decoded.line_count, 80);
4851        assert_eq!(decoded.source_hash.as_deref(), Some("0123456789abcdef"));
4852        assert_eq!(decoded.contributions.len(), 2);
4853        assert_eq!(
4854            decoded.contributions[1].kind,
4855            ComplexityContributionKind::ElseIf
4856        );
4857        assert_eq!(decoded.contributions[1].weight, 3);
4858        assert_eq!(decoded.contributions[1].nesting, 2);
4859        assert_eq!(decoded.contributions[1].metric, ComplexityMetric::Cognitive);
4860    }
4861}