Skip to main content

fallow_types/
extract.rs

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