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