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