Skip to main content

fallow_types/
extract.rs

1//! Module extraction types.
2
3use std::path::PathBuf;
4use std::sync::Arc;
5
6use oxc_span::Span;
7
8pub use crate::complexity_contribution::{
9    ComplexityContribution, ComplexityContributionKind, ComplexityMetric,
10};
11use crate::discover::FileId;
12use crate::suppress::{Suppression, UnknownSuppressionKind};
13#[path = "extract_playwright_facts.rs"]
14mod playwright_facts;
15use playwright_facts::{
16    playwright_fixture_alias_facts, playwright_fixture_definition_facts,
17    playwright_fixture_type_facts, playwright_fixture_use_facts,
18};
19
20/// Extracted module information from a single file.
21///
22/// The `Arc<[T]>` fields are immutable after extraction and are shared by
23/// refcount with the resolver's per-file output, so the resolve/graph path
24/// does not deep-copy per-file extraction payloads.
25#[derive(Debug, Clone)]
26pub struct ModuleInfo {
27    /// Unique identifier for this file.
28    pub file_id: FileId,
29    /// All export declarations in this module.
30    pub exports: Arc<[ExportInfo]>,
31    /// All import declarations in this module.
32    pub imports: Vec<ImportInfo>,
33    /// All re-export declarations (e.g., `export { foo } from './bar'`).
34    pub re_exports: Vec<ReExportInfo>,
35    /// All dynamic `import()` calls with string literal sources.
36    pub dynamic_imports: Vec<DynamicImportInfo>,
37    /// Dynamic import patterns.
38    pub dynamic_import_patterns: Vec<DynamicImportPattern>,
39    /// All `require()` calls.
40    pub require_calls: Vec<RequireCallInfo>,
41    /// Package names statically referenced through package path resolution.
42    pub package_path_references: Box<[String]>,
43    /// Package names that a module augmentation (`declare module 'pkg'` in a
44    /// module file) names. They credit the package as a type-only use.
45    pub type_package_references: Box<[String]>,
46    /// Binary names found in `node_modules/.bin/<name>` paths in string
47    /// literals and template quasis. The analysis maps each name to the
48    /// package that declares the binary.
49    pub bin_path_references: Box<[String]>,
50    /// Package names from direct `require.resolve('pkg')` calls, each with the
51    /// byte offset of its call. A name from a resolver function, a loop
52    /// binding or a static table has no site, because it is a heuristic
53    /// credit. The unlisted-dependency check reports a site like an import.
54    pub package_resolve_sites: Box<[(String, u32)]>,
55    /// Static member access expressions (e.g., `Status.Active`).
56    pub member_accesses: Arc<[MemberAccess]>,
57    /// Typed semantic facts produced by extraction for cross-layer analysis.
58    ///
59    /// This carries facts that were previously encoded as synthetic
60    /// `member_accesses` strings. Extraction and analysis now use typed facts.
61    pub semantic_facts: Arc<[SemanticFact]>,
62    /// Identifiers used in whole-object access patterns.
63    pub whole_object_uses: Arc<[String]>,
64    /// Whether this module uses CommonJS exports.
65    pub has_cjs_exports: bool,
66    /// Whether this module declares an Angular component `templateUrl`.
67    pub has_angular_component_template_url: bool,
68    /// xxh3 hash of the file content for incremental caching.
69    pub content_hash: u64,
70    /// Number of parser diagnostics the parse of this file produced. Non-zero
71    /// means imports, exports and references after the first error may be
72    /// missing (`source-parse-degraded`, which never withholds a finding).
73    /// Zero for non-JS extraction paths, which do not run the oxc parser.
74    pub parse_error_count: u32,
75    /// `true` when the parser abandoned the file instead of recovering. The
76    /// extracted module is then a fragment of the real one at best.
77    pub parse_panicked: bool,
78    /// `true` when the file nests too deep to parse, so it was not parsed.
79    pub parse_nesting_too_deep: bool,
80    /// Inline suppression directives parsed from comments.
81    pub suppressions: Vec<Suppression>,
82    /// Suppression tokens that did not parse to any known `IssueKind`.
83    /// Surfaced as `StaleSuppression` findings via `find_stale` so users see
84    /// typos or obsolete kind names instead of having the entire marker
85    /// silently discarded. See issue #449.
86    pub unknown_suppression_kinds: Vec<UnknownSuppressionKind>,
87    /// Local names of import bindings that are never referenced in this file.
88    /// Populated via `oxc_semantic` scope analysis. Used at graph-build time
89    /// to skip adding references for imports whose binding is never read,
90    /// improving unused-export detection precision.
91    pub unused_import_bindings: Vec<String>,
92    /// Local import bindings that are referenced from TypeScript type positions.
93    /// Used to distinguish value-namespace and type-namespace references when a
94    /// module exports both `const X` and `type X`.
95    pub type_referenced_import_bindings: Vec<String>,
96    /// Local import bindings referenced from runtime/value positions.
97    pub value_referenced_import_bindings: Vec<String>,
98    /// Pre-computed byte offsets where each line starts.
99    pub line_offsets: Vec<u32>,
100    /// Per-function complexity metrics.
101    pub complexity: Vec<FunctionComplexity>,
102    /// Feature flag use sites.
103    pub flag_uses: Vec<FlagUse>,
104    /// Flag-key registries this module exports, and flag reads that name a
105    /// member of an imported registry. `None` for the common module with
106    /// neither.
107    pub flag_registry_facts: Option<Box<FlagRegistryFacts>>,
108    /// Heritage metadata for exported classes that declare `implements`.
109    pub class_heritage: Vec<ClassHeritageInfo>,
110    /// Exported free-function factories that provably return one class instance
111    /// (`export function useApi() { return new RESTApi() }`). Origin-module proof
112    /// that an exported function returns a class instance, so a cross-module
113    /// `const x = useApi(); x.member` consumer can credit the returned class.
114    /// See issue #1441 (Part A).
115    pub exported_factory_returns: Arc<[FactoryReturnExport]>,
116    /// Exported factories that return an OBJECT LITERAL whose property values are
117    /// class instances (`export function createUi() { return { orders: factory.ordersPage } }`).
118    /// Each entry maps a dotted property path (`orders`, `invoke.dashboard`) to the
119    /// returned class's local name within the factory module, so a cross-module
120    /// `const ui = createUi(); ui.orders.member` consumer can credit the class. Names
121    /// are local to this module; resolution is deferred to analyze time. See issue #1858.
122    pub exported_factory_return_object_shapes: Arc<[FactoryReturnObjectShapeExport]>,
123    /// Named-type property types declared by this module's top-level interfaces
124    /// and type-literal aliases (`interface Opts { c: OptDep }`). Names are
125    /// local to this module; resolution is deferred to analyze time. Consumed
126    /// by the `unused-class-member` typed-property-hop join and the Playwright
127    /// fixture-type resolution. See issue #1785.
128    pub type_member_types: Arc<[TypeMemberTypeEntry]>,
129    /// Angular `InjectionToken<Interface>` declarations, as
130    /// `(token_export_name, interface_name)` pairs. Recorded only for
131    /// `new InjectionToken<I>(...)` initializers whose `InjectionToken` is
132    /// imported from `@angular/core`. The analyze layer follows the token's
133    /// interface type argument to the classes that `implement` it so a template
134    /// member call through `inject(TOKEN)` credits the concrete implementation.
135    /// See issue #920 (follow-up to #911 / #913).
136    pub injection_tokens: Vec<(String, String)>,
137    /// Local type-capable declarations.
138    pub local_type_declarations: Vec<LocalTypeDeclaration>,
139    /// Type references in exported public signatures.
140    pub public_signature_type_references: Vec<PublicSignatureTypeReference>,
141    /// Aliases of namespace imports re-exported through an object literal.
142    pub namespace_object_aliases: Vec<NamespaceObjectAlias>,
143    /// Deduped Iconify collection prefixes found in static icon props.
144    pub iconify_prefixes: Vec<String>,
145    /// Deduped Nuxt UI `i-<collection>-<icon>` icon class suffixes found in
146    /// static script-side icon properties.
147    pub iconify_icon_names: Vec<String>,
148    /// Bare identifiers that may be resolved by framework auto-imports.
149    pub auto_import_candidates: Vec<String>,
150    /// File-level string directives in source order (e.g. `"use client"`,
151    /// `"use server"`, `"use strict"`). Captured from `Program::directives`.
152    /// Consumed by the security `client-server-leak` detector to identify
153    /// React Server Component client boundaries.
154    pub directives: Vec<String>,
155    /// Byte-offset starts of dynamic `import()` expressions wrapped in
156    /// `next/dynamic(() => import('./X'), { ssr: false })`. The ssr:false option
157    /// is Next.js's sanctioned way to pull a client-only module, so a server-only
158    /// module reached ONLY through such an import is NOT a client-server leak. The
159    /// security `client-server-leak` BFS resolves each dynamic import to a graph
160    /// edge; these span starts let the BFS exclude exactly those edges (matched
161    /// against the edge's `import_span`). Empty for files with no ssr:false
162    /// dynamic import. Captured only by JS/TS extraction.
163    pub client_only_dynamic_import_spans: Vec<u32>,
164    /// Captured security sink sites (category-blind). Consumed by the
165    /// catalogue-driven `tainted_sink` detector. Captured only by JS/TS
166    /// extraction; empty for CSS/MDX/etc. See `security_matchers.toml`.
167    pub security_sinks: Vec<SinkSite>,
168    /// Count of sink-shaped nodes whose callee could not be flattened to a
169    /// static path (dynamic dispatch, computed members, aliased bindings).
170    /// Surfaced in-band so an empty catalogue result with a non-zero count is
171    /// not a clean bill.
172    pub security_sinks_skipped: u32,
173    /// Compact span-level diagnostics for skipped security sink callees. Kept
174    /// next to `security_sinks_skipped` so warm-cache and cold-cache security
175    /// output can explain where the blind spots are concentrated without source
176    /// snippets.
177    pub security_unresolved_callee_sites: Vec<SkippedSecurityCalleeSite>,
178    /// Local bindings whose initializer (or destructured object) is a flattened
179    /// member-access path. Used by the security `tainted_sink` detector to
180    /// back-trace a sink argument to a known untrusted source: the analyze layer
181    /// matches each binding's `source_path` against the data-driven source
182    /// catalogue (`security_matchers.toml` `[[source]]` rows) and treats the
183    /// matching `local` names as source-tainted. Intra-module and name-based
184    /// (no scope analysis); a conservative association, never a taint proof.
185    pub tainted_bindings: Vec<TaintedBinding>,
186    /// Sink arguments that were recognized as sanitizer calls at extraction
187    /// time. Used for direct sink calls such as
188    /// `el.innerHTML = DOMPurify.sanitize(input)`.
189    pub sanitized_sink_args: Vec<SanitizedSinkArg>,
190    /// Control patterns observed in this module. Surface context only: their
191    /// presence does not establish input identity, execution order, or protection.
192    pub security_control_sites: Vec<SecurityControlSite>,
193    /// Statically flattenable callee paths invoked in this module, one entry
194    /// per path and form with the start of every site. Consumed by
195    /// `boundaries.calls.forbidden`, `banned-call` and `banned-effect`.
196    /// Captured unconditionally because extraction is config-blind; each path
197    /// string is stored once, and each extra site costs 4 bytes.
198    pub callee_uses: Vec<CalleeUse>,
199    /// Literal commands that process-spawning calls run (`spawn("git")`,
200    /// `execSync("make build")`, `` $`ffmpeg -i a` ``). Read by the
201    /// `unlisted-binaries` detector.
202    pub command_invocations: Vec<CommandInvocation>,
203    /// Per-call references to actual runtime ESM import bindings.
204    pub imported_call_sites: Arc<[ImportedCallSite]>,
205    /// Value references to runtime ESM import bindings that are not admitted
206    /// call sites, plus admitted calls that initialize a top-level declarator.
207    /// Sorted by `span_start`. Read by `fallow trace --dependency`.
208    pub import_binding_references: Arc<[ImportBindingReference]>,
209    /// `"use client"` / `"use server"` directive strings written as expression
210    /// statements in `program.body` (misplaced, NOT in the leading
211    /// prologue), so the RSC bundler silently ignores them. One entry per
212    /// occurrence. Consumed by the `misplaced-directive` detector. Captured
213    /// only by JS/TS extraction.
214    pub misplaced_directives: Vec<MisplacedDirectiveSite>,
215    /// Export LOCAL NAMES of exported functions / const-arrows whose body has an
216    /// inline `"use server"` directive (`export async function f() { "use server"
217    /// }`), captured in a NON-`"use server"` file. Consumed by the
218    /// `unused-server-action` detector to reclassify an unused inline Server
219    /// Action export out of `unused-export`. Captured only by JS/TS extraction.
220    pub inline_server_action_exports: Vec<String>,
221    /// Vue `provide`/`inject` and Svelte `setContext`/`getContext` call sites
222    /// keyed by an identifier symbol. Consumed by the `unprovided-inject`
223    /// detector to find an inject/getContext whose key is provided nowhere
224    /// project-wide. Only identifier-keyed sites are recorded (string-literal
225    /// and computed keys abstain). Captured by JS/TS and SFC extraction.
226    pub di_key_sites: Vec<DiKeySite>,
227    /// `true` when this module contains a `provide(...)` / `*.provide(...)` /
228    /// `setContext(...)` call whose key argument is NOT a plain identifier
229    /// (spread, computed, member, loop variable). Such a call can provide an
230    /// unknowable key, so the `unprovided-inject` detector abstains on ALL
231    /// inject findings project-wide when any reachable module sets this flag.
232    /// Mirrors the spread-return whole-object abstain used for Pinia stores.
233    pub has_dynamic_provide: bool,
234    /// `true` when the prologue holds `"use server"` and every value export
235    /// is an async function (a Server Action). A `"use client"` import of
236    /// such a module becomes an action reference, so the security
237    /// `client-server-leak` BFS stops at the module. `false` for every other
238    /// module, including a `"use server"` file with a non-action value
239    /// export. Captured only by JS/TS extraction.
240    pub is_server_action_module: bool,
241    /// `true` when TypeScript reads this file as adding to the global scope:
242    /// a script file (no top-level import or export), or a module file with a
243    /// top-level `declare global` block or string-named `declare module`
244    /// block. Read only for declaration files (`.d.ts`, `.d.mts`, `.d.cts`):
245    /// a declaration file without global declarations is seeded as an entry
246    /// point only when something points to it. Captured only by JS/TS
247    /// extraction; `false` for every other module.
248    pub has_global_declarations: bool,
249    /// Raw `path` values of `/// <reference path="..." />` directives in this
250    /// file, in source order. A declaration file named by one stays an entry
251    /// point. Captured only by JS/TS extraction.
252    pub triple_slash_reference_paths: Box<[String]>,
253    /// `true` when the file has a JSX element or fragment and no
254    /// `@jsxImportSource` or `@jsxRuntime classic` pragma. A bundler or test
255    /// config can then select the automatic JSX runtime for the file, so the
256    /// resolver adds the runtime edge from a plugin rule. Captured only by
257    /// JS/TS extraction; `false` for every other module.
258    pub jsx_runtime_from_config: bool,
259    /// Local names of import bindings that ARE referenced somewhere in this file
260    /// (script value/type position OR template/markup). The complement of
261    /// `unused_import_bindings` among `imports`. Derived by
262    /// `prepare_analysis_facts` while both source vectors are still present, so
263    /// it remains readable after the owned release path clears them. It is never
264    /// cached and is recomputed on every cache load. Consumed by the
265    /// `unrendered-component` detector to credit a
266    /// Vue/Svelte SFC that some file actually imports-and-uses, distinguishing it
267    /// from a component reachable only through a barrel re-export.
268    pub referenced_import_bindings: Vec<String>,
269    /// Vue `<script setup>` `defineProps` and Svelte 5 `$props()` declared
270    /// props. Consumed by the `unused-component-prop` detector to flag a prop
271    /// referenced nowhere in its own SFC. Each entry carries `used_in_script` /
272    /// `used_in_template`.
273    pub component_props: Vec<ComponentProp>,
274    /// Cached framework-neutral component input contracts and inspected callers.
275    pub component_contracts: Option<Box<ComponentContractFacts>>,
276    /// Effect layer, tagged error and `catchTag` facts. Set only for a module
277    /// that imports `effect` or an `@effect/*` package.
278    pub effect_facts: Option<Box<EffectFacts>>,
279    /// Parameter contracts of module-scope functions, direct calls of
280    /// admitted callees and escapes of local functions. `None` when the
281    /// module has none of these facts.
282    pub function_contracts: Option<Box<FunctionContractFacts>>,
283    /// `true` when the template spreads the whole props/attrs object
284    /// (`v-bind="$attrs"` / `v-bind="$props"` / `v-bind="props"`) or the props
285    /// return is destructured with a rest element. Either form can consume a prop
286    /// indirectly, so the detector abstains on the whole file.
287    pub has_props_attrs_fallthrough: bool,
288    /// `true` when the SFC calls `defineExpose(...)`. A prop may be re-exposed,
289    /// so the detector conservatively abstains on the whole file.
290    pub has_define_expose: bool,
291    /// `true` when the SFC calls `defineModel(...)`. Two-way model props are out
292    /// of scope for v1, so the detector abstains on the whole file.
293    pub has_define_model: bool,
294    /// `true` when props were declared through an unharvestable shape, such as a
295    /// Vue type-reference argument or an opaque Svelte `$props()` destructure.
296    /// The detector abstains on the whole file so a prop is never falsely
297    /// flagged.
298    pub has_unharvestable_props: bool,
299    /// Vue `<script setup>` `defineEmits` declared events. Consumed by the
300    /// `unused-component-emit` detector to flag an event emitted nowhere in its
301    /// own SFC. Each entry carries `used`.
302    pub component_emits: Vec<ComponentEmit>,
303    /// Angular component/directive inputs declared via `@Input()` decorators or
304    /// signal `input()` / `input.required()` / `model()` initializers. Consumed
305    /// by the `unused-component-input` detector to flag an input read nowhere in
306    /// its own component. Empty for every non-Angular class.
307    pub angular_inputs: Vec<AngularInputMember>,
308    /// Angular component/directive outputs declared via `@Output()` decorators or
309    /// signal `output()` / `outputFromObservable()` initializers. Consumed by the
310    /// `unused-component-output` detector to flag an output emitted nowhere in its
311    /// own component. A `model()` is recorded as an input only (see
312    /// `AngularOutputMember`). Empty for every non-Angular class.
313    pub angular_outputs: Vec<AngularOutputMember>,
314    /// Angular `@Component` declarations with their `selector` value(s), harvested
315    /// from `@Component({ selector: '...' })` decorators. Consumed by the Angular
316    /// arm of the `unrendered-component` detector. Empty for every non-Angular
317    /// class and for `@Directive`. See `AngularComponentSelector`.
318    pub angular_component_selectors: Vec<AngularComponentSelector>,
319    /// Lit / web-component custom elements REGISTERED in this file via
320    /// `@customElement('x-foo')` or `customElements.define('x-foo', C)`. Consumed
321    /// by the Lit arm of the `unrendered-component` detector, which flags a
322    /// registered element whose tag is rendered in NO `html` template
323    /// project-wide. Empty for non-Lit / non-web-component files. See
324    /// `RegisteredCustomElement`.
325    pub registered_custom_elements: Vec<RegisteredCustomElement>,
326    /// Custom-element tag names USED (rendered) in this file's `html` tagged
327    /// templates, e.g. `` html`<x-foo></x-foo>` `` -> `x-foo`. Only hyphenated
328    /// (custom-element) tags are recorded; native HTML tags are excluded by the
329    /// hyphen requirement. The detector unions these project-wide into the
330    /// rendered-tag set. Empty for files with no `html` templates.
331    pub used_custom_element_tags: Vec<String>,
332    /// Custom element selector tag names referenced in this file's Angular
333    /// templates (inline `@Component({ template })` and the linked external
334    /// `templateUrl` `.html` module), e.g. `<app-foo>` -> `app-foo`. Native HTML
335    /// tag names are excluded at harvest. The detector unions these project-wide
336    /// into the used-selector set. Empty for non-Angular files.
337    pub angular_used_selectors: Vec<String>,
338    /// Angular component class names referenced as a route entry or bootstrap
339    /// target: a route `component: Foo` / `loadComponent: () => import().then(m =>
340    /// m.Foo)` value, a `bootstrapApplication(Foo)` argument, or a
341    /// `bootstrap: [Foo]` NgModule entry. These are render-equivalent entry points
342    /// (Angular instantiates them without a template `<tag>`), so the Angular
343    /// `unrendered-component` detector abstains on a component whose class name is
344    /// in the project-wide union. A plain `declarations: [...]` / `imports: [...]`
345    /// registration is intentionally NOT harvested here (that is the dead case the
346    /// rule catches). Empty for non-Angular files.
347    pub angular_entry_component_refs: Vec<String>,
348    /// `true` when this file dynamically renders an Angular component fallow
349    /// cannot attribute to a literal class reference: a
350    /// `ViewContainerRef.createComponent(...)` / `*.createComponent(<ident>)`
351    /// call, or an `*ngComponentOutlet` template binding. The Angular
352    /// `unrendered-component` detector abstains project-wide when ANY reachable
353    /// module sets this (mirroring `unprovided-inject`'s `has_dynamic_provide`),
354    /// since a component could be rendered by a non-literal class reference.
355    pub has_dynamic_component_render: bool,
356    /// `true` when `defineEmits` was called with an unharvestable argument (a
357    /// type-reference type argument such as `defineEmits<MyEmits>()`, a
358    /// non-literal runtime form, or an unbound `defineEmits([...])`). The
359    /// detector abstains on the whole file so an emit is never falsely flagged.
360    pub has_unharvestable_emits: bool,
361    /// `true` when an `emit(<nonLiteral>)` call was seen (the emitted event name
362    /// cannot be known statically). The detector abstains on the whole file.
363    pub has_dynamic_emit: bool,
364    /// `true` when the `defineEmits` return binding was used as a WHOLE value
365    /// (passed to a function, returned, or spread), which can emit any event
366    /// opaquely. The detector abstains on the whole file.
367    pub has_emit_whole_object_use: bool,
368    /// SvelteKit `load()` return-object keys harvested from a
369    /// `+page.{ts,server.ts,js,server.js}` file's terminal return literal.
370    /// Consumed by the `unused-load-data-key` detector. Empty for every file
371    /// that is not a page-load producer (gated by basename at harvest time).
372    pub load_return_keys: Vec<LoadReturnKey>,
373    /// `true` when this file's `load()` body could not be harvested safely (a
374    /// spread return, a non-object/non-literal return, more than one top-level
375    /// `return`, a computed key, or a wrapped/re-exported `load`). The detector
376    /// abstains on the whole file so a key is never falsely flagged.
377    pub has_unharvestable_load: bool,
378    /// `true` when this file passes the whole `data` object opaquely (script
379    /// `const X = data`, `fn(data)` / `fn(...data)`, or template `data={data}` /
380    /// `{...data}` in a route component), so a child can read arbitrary keys the
381    /// detector cannot see. Name-gated on the `data` binding. Read ONLY by the
382    /// `unused-load-data-key` detector, so capturing it for all files is
383    /// byte-identity-safe. See FP-1 in the plan.
384    pub has_load_data_whole_use: bool,
385    /// `true` when this file uses the whole `page.data` / `$page.data` store
386    /// object opaquely (e.g. `Object.values(page.data)`, `{...$page.data}`), so a
387    /// reflective read could consume any route's key. Drives the
388    /// `unused-load-data-key` detector's project-wide abstain. Derived by
389    /// `prepare_analysis_facts` from `whole_object_uses` before the owned release
390    /// path clears that vector. It is never cached and is recomputed each run from
391    /// the cached `whole_object_uses`. Reassignment forms
392    /// (`const all = $page.data`) are not whole-object-tracked and stay out of
393    /// scope, matching the syntactic analyzer's conservative posture.
394    pub has_page_data_store_whole_use: bool,
395    /// `true` when a React Router or Remix route consumes the whole
396    /// `useLoaderData()` result opaquely. Derived by `prepare_analysis_facts`
397    /// from the synthetic route-loader marker before the owned release path
398    /// clears `whole_object_uses`. It is recomputed from cached extraction data.
399    pub has_route_loader_data_whole_use: bool,
400    /// React/JSX component definitions: functions/arrows whose body returns JSX.
401    /// Captured only for `.jsx`/`.tsx` files when a React/Preact dependency is
402    /// plausible. Consumed by the React `unused-component-prop` arm and the
403    /// complexity-fold phase. Empty for non-React files.
404    pub component_functions: Vec<ComponentFunction>,
405    /// React component props (reuses the shared `ComponentProp` struct). For
406    /// React, `used_in_template` is always false and `used_in_script` means
407    /// used-in-body. Empty for non-React files.
408    pub react_props: Vec<ComponentProp>,
409    /// React hook call sites (`useState` / `useEffect` / `useMemo` /
410    /// `useCallback` / custom `use*`). Drives hook-density complexity context.
411    /// Empty for non-React files.
412    pub hook_uses: Vec<HookUse>,
413    /// React render edges: one component rendering another. Captured with the
414    /// child's written name; child-to-`FileId` resolution is deferred to graph
415    /// build. Empty for non-React files.
416    pub render_edges: Vec<RenderEdge>,
417    /// Svelte custom events dispatched via `dispatch('<name>')` where `dispatch`
418    /// is the binding from `const dispatch = createEventDispatcher()`. Consumed
419    /// by the `unused-svelte-event` detector to flag an event dispatched here but
420    /// listened to nowhere project-wide. Each entry carries the literal event
421    /// name and its span. Empty for every non-Svelte file.
422    pub svelte_dispatched_events: Vec<DispatchedEvent>,
423    /// Svelte custom-event listener names harvested from template `on:<name>`
424    /// bindings on COMPONENT tags (PascalCase tag names). Lowercase DOM-element
425    /// `on:click` is a DOM event, not a custom event, and is excluded. Unioned
426    /// project-wide by the `unused-svelte-event` detector to build the liberal
427    /// "listened" set. Empty for every non-Svelte file.
428    pub svelte_listened_events: Vec<String>,
429    /// `true` when a `dispatch(<nonLiteral>)` call was seen (the dispatched event
430    /// name cannot be known statically), or the `dispatch` binding was used as a
431    /// whole value (passed / returned). The `unused-svelte-event` detector
432    /// abstains on the whole component so an event is never falsely flagged.
433    pub has_dynamic_dispatch: bool,
434}
435
436impl ModuleInfo {
437    /// A fully-zeroed `ModuleInfo` for the given file.
438    ///
439    /// Fixture builders and non-JS extraction paths start from this and set
440    /// only the fields they care about via struct-update syntax:
441    /// `ModuleInfo { exports: vec![..], ..ModuleInfo::empty(file_id) }`.
442    #[must_use]
443    pub fn empty(file_id: FileId) -> Self {
444        Self {
445            file_id,
446            exports: Arc::default(),
447            imports: Vec::new(),
448            re_exports: Vec::new(),
449            dynamic_imports: Vec::new(),
450            dynamic_import_patterns: Vec::new(),
451            require_calls: Vec::new(),
452            package_path_references: Box::default(),
453            type_package_references: Box::default(),
454            bin_path_references: Box::default(),
455            package_resolve_sites: Box::default(),
456            member_accesses: Arc::default(),
457            semantic_facts: Arc::default(),
458            whole_object_uses: Arc::default(),
459            has_cjs_exports: false,
460            has_angular_component_template_url: false,
461            content_hash: 0,
462            parse_error_count: 0,
463            parse_panicked: false,
464            parse_nesting_too_deep: false,
465            suppressions: Vec::new(),
466            unknown_suppression_kinds: Vec::new(),
467            unused_import_bindings: Vec::new(),
468            type_referenced_import_bindings: Vec::new(),
469            value_referenced_import_bindings: Vec::new(),
470            line_offsets: Vec::new(),
471            complexity: Vec::new(),
472            flag_uses: Vec::new(),
473            flag_registry_facts: None,
474            class_heritage: Vec::new(),
475            exported_factory_returns: Arc::default(),
476            exported_factory_return_object_shapes: Arc::default(),
477            type_member_types: Arc::default(),
478            injection_tokens: Vec::new(),
479            local_type_declarations: Vec::new(),
480            public_signature_type_references: Vec::new(),
481            namespace_object_aliases: Vec::new(),
482            iconify_prefixes: Vec::new(),
483            iconify_icon_names: Vec::new(),
484            auto_import_candidates: Vec::new(),
485            directives: Vec::new(),
486            client_only_dynamic_import_spans: Vec::new(),
487            security_sinks: Vec::new(),
488            security_sinks_skipped: 0,
489            security_unresolved_callee_sites: Vec::new(),
490            tainted_bindings: Vec::new(),
491            sanitized_sink_args: Vec::new(),
492            security_control_sites: Vec::new(),
493            callee_uses: Vec::new(),
494            command_invocations: Vec::new(),
495            imported_call_sites: Arc::default(),
496            import_binding_references: Arc::default(),
497            misplaced_directives: Vec::new(),
498            inline_server_action_exports: Vec::new(),
499            di_key_sites: Vec::new(),
500            has_dynamic_provide: false,
501            is_server_action_module: false,
502            has_global_declarations: false,
503            triple_slash_reference_paths: Box::default(),
504            jsx_runtime_from_config: false,
505            referenced_import_bindings: Vec::new(),
506            component_props: Vec::new(),
507            component_contracts: None,
508            effect_facts: None,
509            function_contracts: None,
510            has_props_attrs_fallthrough: false,
511            has_define_expose: false,
512            has_define_model: false,
513            has_unharvestable_props: false,
514            component_emits: Vec::new(),
515            angular_inputs: Vec::new(),
516            angular_outputs: Vec::new(),
517            has_unharvestable_emits: false,
518            has_dynamic_emit: false,
519            has_emit_whole_object_use: false,
520            load_return_keys: Vec::new(),
521            has_unharvestable_load: false,
522            has_load_data_whole_use: false,
523            has_page_data_store_whole_use: false,
524            has_route_loader_data_whole_use: false,
525            component_functions: Vec::new(),
526            react_props: Vec::new(),
527            hook_uses: Vec::new(),
528            render_edges: Vec::new(),
529            svelte_dispatched_events: Vec::new(),
530            svelte_listened_events: Vec::new(),
531            angular_component_selectors: Vec::new(),
532            registered_custom_elements: Vec::new(),
533            used_custom_element_tags: Vec::new(),
534            angular_used_selectors: Vec::new(),
535            angular_entry_component_refs: Vec::new(),
536            has_dynamic_component_render: false,
537            has_dynamic_dispatch: false,
538        }
539    }
540
541    /// Derive compact detector facts from resolution payload before sharing.
542    ///
543    /// Shared analysis sessions keep the source payload for later graph runs,
544    /// but detectors still require the same derived facts that the owned
545    /// release path computes before clearing that payload.
546    #[doc(hidden)]
547    pub fn prepare_analysis_facts(&mut self) {
548        // The analyze-layer `unrendered-component` detector needs the compact
549        // complement of imports and unused bindings after resolution.
550        self.referenced_import_bindings = self
551            .imports
552            .iter()
553            .map(|import| import.local_name.clone())
554            .filter(|name| !name.is_empty() && !self.unused_import_bindings.contains(name))
555            .collect();
556        self.referenced_import_bindings.sort_unstable();
557        self.referenced_import_bindings.dedup();
558
559        // The `unused-load-data-key` detector needs the project-wide signal
560        // after `whole_object_uses` is released from owned artifacts.
561        self.has_page_data_store_whole_use = self
562            .whole_object_uses
563            .iter()
564            .any(|name| name == "page.data" || name == "$page.data");
565        self.has_route_loader_data_whole_use = self
566            .whole_object_uses
567            .iter()
568            .any(|name| name == "$fallow.routeLoaderData");
569    }
570
571    /// Release extraction payload that resolution has already copied into the graph.
572    ///
573    /// This keeps fields needed by analysis, health, security, LSP, coverage,
574    /// and hash drift checks, while dropping vectors that otherwise duplicate
575    /// data owned by `ResolvedModule` or already credited into the module graph.
576    pub fn release_resolution_payload(&mut self) {
577        self.prepare_analysis_facts();
578        Self::release_vec(&mut self.dynamic_imports);
579        Self::release_vec(&mut self.require_calls);
580        Self::release_boxed_slice(&mut self.package_path_references);
581        Self::release_boxed_slice(&mut self.type_package_references);
582        Self::release_boxed_slice(&mut self.bin_path_references);
583        Self::release_arc_slice(&mut self.whole_object_uses);
584        Self::release_arc_slice(&mut self.import_binding_references);
585        Self::release_vec(&mut self.unused_import_bindings);
586        Self::release_vec(&mut self.type_referenced_import_bindings);
587        Self::release_vec(&mut self.value_referenced_import_bindings);
588        Self::release_vec(&mut self.namespace_object_aliases);
589        Self::release_vec(&mut self.auto_import_candidates);
590    }
591
592    fn release_vec<T>(values: &mut Vec<T>) {
593        *values = Vec::new();
594    }
595
596    fn release_boxed_slice<T>(values: &mut Box<[T]>) {
597        *values = Box::default();
598    }
599
600    /// Drop this module's refcount; the allocation itself is freed only once
601    /// the sharing `ResolvedModule` releases its clone too.
602    fn release_arc_slice<T>(values: &mut Arc<[T]>) {
603        *values = Arc::default();
604    }
605}
606
607/// Family of a control pattern observed in a file on an import trace.
608#[derive(
609    Debug,
610    Clone,
611    Copy,
612    PartialEq,
613    Eq,
614    PartialOrd,
615    Ord,
616    serde::Serialize,
617    serde::Deserialize,
618    bitcode::Encode,
619    bitcode::Decode,
620)]
621#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
622#[serde(rename_all = "kebab-case")]
623pub enum SecurityControlKind {
624    /// Sanitization or escaping before a sink.
625    Sanitization,
626    /// Input validation or schema parsing.
627    Validation,
628    /// Authentication check or middleware.
629    Authentication,
630    /// Authorization or permission check.
631    Authorization,
632}
633
634/// An observed control call or guard pattern, without proof that it protects a sink.
635#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, bitcode::Encode, bitcode::Decode)]
636pub struct SecurityControlSite {
637    /// Control family.
638    pub kind: SecurityControlKind,
639    /// Flattened callee path or a stable synthetic name for guard-derived
640    /// controls.
641    pub callee_path: String,
642    /// Byte offset of the control span start.
643    pub span_start: u32,
644    /// Byte offset of the control span end.
645    pub span_end: u32,
646}
647
648/// Sanitizer output domain. Kept intentionally narrow so a sanitizer for one
649/// domain cannot suppress a different sink family.
650#[derive(
651    Debug,
652    Clone,
653    Copy,
654    PartialEq,
655    Eq,
656    PartialOrd,
657    Ord,
658    serde::Serialize,
659    serde::Deserialize,
660    bitcode::Encode,
661    bitcode::Decode,
662)]
663pub enum SanitizerScope {
664    /// HTML markup sanitized by DOMPurify-compatible APIs.
665    Html,
666    /// URL or redirect target checked against a literal-backed allowlist.
667    Url,
668    /// Path value checked against a high-confidence containment guard.
669    Path,
670    /// SQL identifier quoted with a helper that doubles embedded identifier quotes.
671    SqlIdentifier,
672}
673
674/// A captured sink argument that is itself a recognized sanitizer call.
675#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, bitcode::Encode, bitcode::Decode)]
676pub struct SanitizedSinkArg {
677    /// Byte offset of the owning sink span start.
678    pub span_start: u32,
679    /// The positional argument index on the owning sink.
680    pub arg_index: u32,
681    /// The sanitizer output domain for this argument.
682    pub scope: SanitizerScope,
683}
684
685/// A local binding tied to the flattened member-access path it was initialized
686/// from. The analyze layer matches `source_path` against the data-driven source
687/// catalogue; when it matches, `local` is treated as carrying untrusted input.
688///
689/// Captured for two shapes: a direct assignment (`const id = req.query.id` ->
690/// `{ local: "id", source_path: "req.query" }`, the literal-key tail dropped so
691/// the path matches a catalogue prefix) and an object destructure
692/// (`const { id } = req.query` -> `{ local: "id", source_path: "req.query" }`).
693#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, bitcode::Encode, bitcode::Decode)]
694pub struct TaintedBinding {
695    /// The local binding name introduced by the declarator.
696    pub local: String,
697    /// The flattened object member-access path the binding was sourced from.
698    pub source_path: String,
699    /// Byte offset of the source read (the member-access expression the binding
700    /// was sourced from), so the analyze layer can anchor a taint trace's source
701    /// node at the real read line instead of the module import line. Stored as a
702    /// `u32` (not `Span`) to stay bitcode-encodable for the cache. `0` when no
703    /// concrete read expression is available (synthetic framework-param /
704    /// helper-return bindings), in which case the analyze layer falls back to the
705    /// sink site rather than claiming a spurious line.
706    pub source_span_start: u32,
707}
708
709/// Why a sink-shaped callee could not be flattened into a static catalogue
710/// path.
711#[derive(
712    Debug,
713    Clone,
714    Copy,
715    PartialEq,
716    Eq,
717    PartialOrd,
718    Ord,
719    serde::Serialize,
720    serde::Deserialize,
721    bitcode::Encode,
722    bitcode::Decode,
723)]
724#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
725#[serde(rename_all = "kebab-case")]
726pub enum SkippedSecurityCalleeReason {
727    /// A computed member access such as `client[method](input)`.
728    ComputedMember,
729    /// A dynamic non-member callee such as `(factory())(input)`.
730    DynamicDispatch,
731    /// An assignment target whose object could not be flattened.
732    UnsupportedAssignmentObject,
733}
734
735/// Syntactic expression shape for a skipped security callee.
736#[derive(
737    Debug,
738    Clone,
739    Copy,
740    PartialEq,
741    Eq,
742    PartialOrd,
743    Ord,
744    serde::Serialize,
745    serde::Deserialize,
746    bitcode::Encode,
747    bitcode::Decode,
748)]
749#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
750#[serde(rename_all = "kebab-case")]
751pub enum SkippedSecurityCalleeExpressionKind {
752    /// `obj.prop(...)`.
753    StaticMemberExpression,
754    /// `obj[prop](...)`.
755    ComputedMemberExpression,
756    /// A bare identifier or private identifier callee.
757    Identifier,
758    /// Any other call-like expression that cannot be represented compactly.
759    Other,
760}
761
762/// Span-only diagnostic for a skipped security callee inside one module.
763#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, bitcode::Encode, bitcode::Decode)]
764pub struct SkippedSecurityCalleeSite {
765    /// Why the callee was skipped.
766    pub reason: SkippedSecurityCalleeReason,
767    /// Compact expression shape of the skipped callee.
768    pub expression_kind: SkippedSecurityCalleeExpressionKind,
769    /// Start byte offset of the skipped callee expression.
770    pub span_start: u32,
771    /// End byte offset of the skipped callee expression.
772    pub span_end: u32,
773}
774
775/// The syntactic shape of a captured security sink site. Category-blind: the
776/// extractor records the shape and the dotted/bare callee path; the analyze
777/// layer matches it against the data-driven catalogue. See
778/// `crates/security/data/security_matchers.toml`.
779#[derive(
780    Debug,
781    Clone,
782    Copy,
783    PartialEq,
784    Eq,
785    serde::Serialize,
786    serde::Deserialize,
787    bitcode::Encode,
788    bitcode::Decode,
789)]
790pub enum SinkShape {
791    /// A call to a bare identifier (e.g. `eval(x)`).
792    Call,
793    /// A call to a dotted member path (e.g. `child_process.exec(x)`).
794    MemberCall,
795    /// An assignment to a member target (e.g. `el.innerHTML = x`).
796    MemberAssign,
797    /// A tagged template expression (e.g. ``sql`...${x}...` ``).
798    TaggedTemplate,
799    /// A JSX attribute value (e.g. `dangerouslySetInnerHTML={x}`).
800    JsxAttr,
801    /// A constructor call (e.g. `new Function("return x")`).
802    NewExpression,
803    /// A static string literal assigned to a secret-shaped identifier or known
804    /// provider credential prefix.
805    SecretLiteral,
806}
807
808/// The shape of the argument captured at a sink site. Category-blind like
809/// [`SinkShape`], but finer-grained: it lets the catalogue matcher require or
810/// exclude specific argument shapes. The discriminator is what distinguishes an
811/// unsafe SQL string concatenation or template-into-`.execute()` from a
812/// safely-parameterized `` sql`${x}` `` tagged template, an object-literal
813/// `.execute({ sql, args })` argument, or a literal-aware sink argument.
814#[derive(
815    Debug,
816    Clone,
817    Copy,
818    PartialEq,
819    Eq,
820    serde::Serialize,
821    serde::Deserialize,
822    bitcode::Encode,
823    bitcode::Decode,
824)]
825pub enum SinkArgKind {
826    /// A template literal with at least one `${...}` substitution (e.g.
827    /// `` `SELECT ${x}` ``). On a `tagged-template` shape this is the tag's
828    /// quasi; on a `call`/`member-call` shape it is the positional argument.
829    TemplateWithSubst,
830    /// A binary `+` string concatenation (e.g. `"SELECT " + x`).
831    Concat,
832    /// An object literal (e.g. `.execute({ sql, args })`, the parameterized form).
833    Object,
834    /// A call expression argument (e.g. `query(buildSql())`).
835    Call,
836    /// A literal argument admitted by a literal-aware security matcher.
837    Literal,
838    /// A zero-argument sink captured because the callee itself is the signal.
839    NoArg,
840    /// Any other non-literal expression (bare identifier, member access, etc.).
841    Other,
842}
843
844/// Static URL construction shape captured for URL-shaped security sinks.
845#[derive(
846    Debug,
847    Clone,
848    Copy,
849    PartialEq,
850    Eq,
851    serde::Serialize,
852    serde::Deserialize,
853    bitcode::Encode,
854    bitcode::Decode,
855)]
856#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
857#[serde(rename_all = "kebab-case")]
858pub enum SecurityUrlShape {
859    /// The sink target has a fixed origin, scheme, or relative root while only
860    /// path or query components are dynamic.
861    FixedOriginDynamicPath,
862    /// The sink target's scheme or origin is dynamic or opaque.
863    DynamicOrigin,
864}
865
866#[path = "extract_sink_values.rs"]
867mod sink_values;
868pub use sink_values::{SinkCallOptions, SinkLiteralValue, SinkObjectProperty};
869
870/// A captured sink site. The visitor records every existing non-literal call /
871/// member-assign / member-call / tagged-template / jsx-attr sink site, and a
872/// small allowlist of literal-aware sites where the literal value is the signal.
873/// It knows nothing about CWE categories.
874#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, bitcode::Encode, bitcode::Decode)]
875pub struct SinkSite {
876    /// The syntactic shape of the sink site.
877    pub sink_shape: SinkShape,
878    /// The flattened dotted/bare callee or member path.
879    pub callee_path: String,
880    /// The positional argument index. For zero-argument captures this is 0.
881    pub arg_index: u32,
882    /// Whether the relevant argument is non-literal. Existing non-literal
883    /// catalogue rows require this to remain true.
884    pub arg_is_non_literal: bool,
885    /// The finer-grained shape of the captured argument. Lets the catalogue
886    /// require unsafe shapes (concat / template-with-substitution / literal /
887    /// no-arg) and exclude safe ones (object literal, the parameterized form).
888    /// See [`SinkArgKind`].
889    pub arg_kind: SinkArgKind,
890    /// Literal argument value for literal-aware rows.
891    pub arg_literal: Option<SinkLiteralValue>,
892    /// Risky regex fragment for structural ReDoS candidates.
893    pub regex_pattern: Option<String>,
894    /// Static object-literal properties for option-object rows.
895    pub object_properties: Vec<SinkObjectProperty>,
896    /// Static top-level object-literal keys, including keys whose values are not
897    /// literal. Used by missing-option rows that only need key presence.
898    pub object_property_keys: Vec<String>,
899    /// Whether [`object_property_keys`](Self::object_property_keys) is complete.
900    /// False for non-object arguments and object literals with spread or
901    /// non-static keys, where a missing-key claim would be speculative.
902    pub object_property_keys_complete: bool,
903    /// Identifier names referenced anywhere inside the captured non-literal sink
904    /// argument, or contextual names for zero-argument captures such as a
905    /// token-like `Math.random()` assignment target. Deduped in source order.
906    /// Used by the analyze layer to back-trace the sink argument to a known
907    /// untrusted source or to apply narrow context gates. Intra-module,
908    /// name-based, conservative; it is never a taint proof.
909    pub arg_idents: Vec<String>,
910    /// Flattened static member paths referenced inside the captured non-literal
911    /// sink argument. Includes both the full path and source-object path for
912    /// leaf reads (`process.env.SECRET` records `process.env.SECRET` and
913    /// `process.env`) so direct source expressions can be matched without an
914    /// intermediate local binding.
915    pub arg_source_paths: Vec<String>,
916    /// Byte offset of the sink span start. Stored as `u32` (not `Span`) so the
917    /// struct is bitcode-encodable and can be persisted directly in the cache.
918    pub span_start: u32,
919    /// Byte offset of the sink span end.
920    pub span_end: u32,
921    /// The arg-0 URL string literal of a network-shaped call (`fetch`, `axios.*`,
922    /// `got`, ...), captured so the `secret-to-network` category (#890) can carry
923    /// a destination-host signal on its candidate: `Some(literal)` when the
924    /// destination is a static string literal (almost always intended auth, e.g.
925    /// the credential's own provider), `None` when it is dynamic (the suspicious
926    /// case). `None` for non-call sinks and calls with no arg 0.
927    pub url_arg_literal: Option<String>,
928    /// URL construction shape for URL-like sink arguments when the extractor can
929    /// classify it syntactically. `None` for non-URL sinks and URL expressions
930    /// whose shape is not visible at the sink.
931    pub url_shape: Option<SecurityUrlShape>,
932    /// Options-object metadata of the call, on the command argument of a call
933    /// whose options position the extractor knows. `None` for every other
934    /// sink, which means that the options are unknown.
935    pub call_options: Option<Box<SinkCallOptions>>,
936}
937
938impl SinkSite {
939    /// Reconstruct the source span from the stored byte offsets.
940    #[must_use]
941    pub fn span(&self) -> Span {
942        Span::new(self.span_start, self.span_end)
943    }
944}
945
946#[path = "extract_env.rs"]
947mod env;
948pub use env::{
949    PUBLIC_ENV_EXACT, PUBLIC_ENV_METADATA_TOKENS, PUBLIC_ENV_PREFIXES, SECRET_ENV_TOKENS,
950    is_public_env_path, is_public_env_var,
951};
952
953/// One alias entry tying an exported object's dotted property path to a namespace import.
954#[derive(Debug, Clone)]
955pub struct NamespaceObjectAlias {
956    /// Canonical export name.
957    pub via_export_name: String,
958    /// Dotted suffix of the property path relative to the export.
959    pub suffix: String,
960    /// Local name of the namespace import.
961    pub namespace_local: String,
962}
963
964/// Compute a table of line-start byte offsets from source text.
965#[must_use]
966#[expect(
967    clippy::cast_possible_truncation,
968    reason = "source files are practically < 4GB"
969)]
970pub fn compute_line_offsets(source: &str) -> Vec<u32> {
971    let mut offsets = vec![0u32];
972    for (i, byte) in source.bytes().enumerate() {
973        if byte == b'\n' {
974            debug_assert!(
975                u32::try_from(i + 1).is_ok(),
976                "source file exceeds u32::MAX bytes: line offsets would overflow"
977            );
978            offsets.push((i + 1) as u32);
979        }
980    }
981    offsets
982}
983
984/// Convert a byte offset to a 1-based line number and 0-based byte column.
985#[must_use]
986#[expect(
987    clippy::cast_possible_truncation,
988    reason = "line count is bounded by source size"
989)]
990pub fn byte_offset_to_line_col(line_offsets: &[u32], byte_offset: u32) -> (u32, u32) {
991    let line_idx = match line_offsets.binary_search(&byte_offset) {
992        Ok(idx) => idx,
993        Err(idx) => idx.saturating_sub(1),
994    };
995    let line = line_idx as u32 + 1;
996    let col = byte_offset - line_offsets[line_idx];
997    (line, col)
998}
999
1000/// True when `name` identifies a synthetic template-family complexity unit:
1001/// the per-file `<template>` unit every framework template scanner emits, or a
1002/// Svelte `<snippet:NAME>` unit. These units are exercised only through their
1003/// component, carry no directly measurable test coverage, and are therefore
1004/// excluded from the CRAP dimension. The `<component>` rollup is NOT part of
1005/// this family: it is an aggregate over class + template findings, not an
1006/// extracted unit.
1007#[must_use]
1008pub fn is_synthetic_template_unit(name: &str) -> bool {
1009    name == "<template>" || name.starts_with("<snippet:")
1010}
1011
1012/// Placeholder name of a function expression that has no name from its
1013/// declaration, its binding, a key, or its call context.
1014pub const ANONYMOUS_FUNCTION_NAME: &str = "<anonymous>";
1015
1016/// Placeholder name of an arrow function that has no name from its binding, a
1017/// key, or its call context.
1018pub const ANONYMOUS_ARROW_NAME: &str = "<arrow>";
1019
1020/// True when `name` is the placeholder of a function without a name. Two
1021/// functions that share a placeholder are not the same function.
1022#[must_use]
1023pub fn is_anonymous_function_name(name: &str) -> bool {
1024    name == ANONYMOUS_FUNCTION_NAME || name == ANONYMOUS_ARROW_NAME
1025}
1026
1027/// Emitted name of the synthetic module-scope complexity unit.
1028pub const MODULE_UNIT_NAME: &str = "<module>";
1029
1030/// True when `name` identifies the synthetic per-file module-scope unit.
1031///
1032/// Extraction pushes one root frame per program so decision points outside
1033/// every function (an environment guard, a top-level `??` / `||` default, an
1034/// `?.` access on a config object) are counted instead of silently dropped.
1035/// The unit is emitted only when it actually branches, and it is
1036/// aggregate-only: it feeds vital signs, file scores, and branching
1037/// conservation, and never becomes a user-facing finding. "Extract a helper"
1038/// is not advice that applies to module scope, so the unit reports the
1039/// quantity without asking anyone to act on it.
1040///
1041/// Deliberately NOT part of [`is_synthetic_template_unit`]. That predicate
1042/// carries template-family CRAP, suppression, and display semantics, and
1043/// [`FileBranching::from_units`] filters on it: folding `<module>` in would
1044/// exclude module-scope branching from the branching totals, which is the
1045/// blind spot this unit exists to close.
1046#[must_use]
1047pub fn is_synthetic_module_unit(name: &str) -> bool {
1048    name == MODULE_UNIT_NAME
1049}
1050
1051/// Branching totals for one file: the quantity that survives extraction, and
1052/// the number of units now holding it.
1053///
1054/// A per-function cyclomatic ceiling constrains a partition, not a quantity.
1055/// `McCabe` gives a function `1 + one increment per decision point`, so across
1056/// a set of units the summed cyclomatic score is `functions + branch_points`.
1057/// Moving an `if` from one function into a new one removes an increment from
1058/// the first and adds it to the second: `branch_points` is unchanged and
1059/// `functions` rises. Reporting the two terms separately is what distinguishes
1060/// branching that left from branching that only moved.
1061///
1062/// Module scope is accounted for. Extraction pushes a root frame per program
1063/// and emits it as a synthetic `<module>` unit whenever it branches, so a
1064/// branch hoisted out of a function to the top level of the module keeps its
1065/// increment in `branch_points` and adds one to `functions`, exactly as moving
1066/// it into a new function would. A fall in `branch_points` is therefore a
1067/// statement about the file's measured decision points, not about a partition.
1068#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
1069pub struct FileBranching {
1070    /// Summed weight of `Cyclomatic` contributions. The conserved quantity.
1071    pub branch_points: u32,
1072    /// Number of accounted units. The tax a split adds.
1073    pub functions: u32,
1074    /// Highest single-unit cyclomatic score. Reported, never a verdict input:
1075    /// a split lowers it by construction.
1076    pub peak_cyclomatic: u16,
1077    /// Summed weight of `Cognitive` contributions, excluding `PropCount` and
1078    /// `HookDensity`. Both are cognitive-only with no cyclomatic counterpart,
1079    /// and `PropCount` records the excess over a floor, so it is superlinear in
1080    /// a split: one 14-prop component contributes `+10` while the same props
1081    /// across two 7-prop components contribute `+3` and `+3`. Including them
1082    /// would move this number with both `branch_points` and nesting flat.
1083    /// This therefore does NOT equal the sum of `FunctionComplexity::cognitive`.
1084    pub cognitive: u32,
1085    /// Summed `nesting` over the same cognitive contributions. Extraction
1086    /// rebases nesting to zero on every new frame, so a cognitive improvement
1087    /// that shows up here and not in `branch_points` came from repartitioning,
1088    /// not from removing branching.
1089    pub cognitive_nesting_weight: u32,
1090    /// Whether one of the counted units is the module body. Its branching is
1091    /// real and belongs in `branch_points`, but it is not a function anyone
1092    /// split into, so a consumer judging whether a file was split must not
1093    /// count it towards the function tax.
1094    pub has_module_unit: bool,
1095    /// Whether the file carried a synthetic template unit that these counts
1096    /// exclude. When it did, the numbers describe the file's script only, so a
1097    /// consumer must not present them as describing the whole file. The
1098    /// synthetic `<module>` unit is NOT a template unit and does not set this
1099    /// flag: it is counted like any other unit, because module-scope branching
1100    /// is part of the script the numbers describe.
1101    pub has_synthetic_units: bool,
1102}
1103
1104impl FileBranching {
1105    /// Aggregate one file's units.
1106    ///
1107    /// Synthetic template units are excluded: they are suppressed entirely when
1108    /// trivial, which would silently move any denominator that counted them.
1109    /// Suppression is deliberately not consulted, so a
1110    /// `fallow-ignore-next-line complexity` comment cannot remove a unit's
1111    /// branches from the total.
1112    ///
1113    /// The synthetic `<module>` unit IS counted. It carries the file's
1114    /// module-scope decision points, and leaving it out would restore the blind
1115    /// spot that let a branch disappear from the total by being hoisted out of
1116    /// every function.
1117    #[must_use]
1118    pub fn from_units(units: &[FunctionComplexity]) -> Self {
1119        let mut totals = Self {
1120            has_module_unit: units
1121                .iter()
1122                .any(|unit| is_synthetic_module_unit(&unit.name)),
1123            has_synthetic_units: units
1124                .iter()
1125                .any(|unit| is_synthetic_template_unit(&unit.name)),
1126            ..Self::default()
1127        };
1128        for unit in units
1129            .iter()
1130            .filter(|unit| !is_synthetic_template_unit(&unit.name))
1131        {
1132            totals.functions += 1;
1133            totals.peak_cyclomatic = totals.peak_cyclomatic.max(unit.cyclomatic);
1134            for contribution in &unit.contributions {
1135                match contribution.metric {
1136                    ComplexityMetric::Cyclomatic => {
1137                        totals.branch_points += u32::from(contribution.weight);
1138                    }
1139                    ComplexityMetric::Cognitive => {
1140                        if matches!(
1141                            contribution.kind,
1142                            ComplexityContributionKind::PropCount
1143                                | ComplexityContributionKind::HookDensity
1144                        ) {
1145                            continue;
1146                        }
1147                        totals.cognitive += u32::from(contribution.weight);
1148                        totals.cognitive_nesting_weight += u32::from(contribution.nesting);
1149                    }
1150                }
1151            }
1152        }
1153        totals
1154    }
1155
1156    /// Summed cyclomatic score implied by the identity `functions + branch_points`.
1157    ///
1158    /// Equals the direct sum of `FunctionComplexity::cyclomatic` over the same
1159    /// units unless a unit saturated `u16`, which is the one way the identity
1160    /// can break.
1161    #[must_use]
1162    pub const fn implied_cyclomatic(&self) -> u32 {
1163        self.functions + self.branch_points
1164    }
1165}
1166
1167/// The kind of function that has no name of its own, which selects its
1168/// placeholder name.
1169#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
1170pub enum AnonymousFunctionKind {
1171    /// A function expression: `<anonymous>`.
1172    Function,
1173    /// An arrow function: `<arrow>`.
1174    Arrow,
1175}
1176
1177impl AnonymousFunctionKind {
1178    /// The placeholder name of this kind.
1179    #[must_use]
1180    pub const fn placeholder(self) -> &'static str {
1181        match self {
1182            Self::Function => ANONYMOUS_FUNCTION_NAME,
1183            Self::Arrow => ANONYMOUS_ARROW_NAME,
1184        }
1185    }
1186}
1187
1188/// Complexity metrics for a single function/method/arrow.
1189#[derive(Debug, Clone, serde::Serialize, bitcode::Encode, bitcode::Decode)]
1190pub struct FunctionComplexity {
1191    /// Function name, or a placeholder (`"<anonymous>"`, `"<arrow>"`) for a
1192    /// function that has no name.
1193    pub name: String,
1194    /// Whether this function is an ECMAScript `#`-private class member.
1195    ///
1196    /// Kept separately from `name` because a public string-named method may
1197    /// legally begin with `#` and remains eligible for runtime coverage.
1198    pub is_private_member: bool,
1199    /// `Some` when `name` comes from the call or the function that holds this
1200    /// function, not from its own declaration, binding, or key. Examples:
1201    /// `Command.make("setup")` for a callback argument, the `Effect.fn` span
1202    /// name, or the name of the function that returns `Effect.gen(...)`. The
1203    /// value is the kind of placeholder that the function had before.
1204    ///
1205    /// Coverage producers and runtime identities record such a function
1206    /// without a name, so they use [`Self::identity_name`].
1207    pub context_named: Option<AnonymousFunctionKind>,
1208    /// 1-based line number where the function starts.
1209    pub line: u32,
1210    /// 0-based byte column where the function starts.
1211    pub col: u32,
1212    /// `McCabe` cyclomatic complexity (1 + decision points).
1213    pub cyclomatic: u16,
1214    /// `SonarSource` cognitive complexity (structural + nesting penalty).
1215    pub cognitive: u16,
1216    /// Number of lines in the function body.
1217    pub line_count: u32,
1218    /// Number of parameters (excluding TypeScript's `this` parameter).
1219    pub param_count: u8,
1220    /// Number of React hook calls (`useState` / `useEffect` / `useMemo` /
1221    /// `useCallback` / custom `use*`) made directly in this function's body.
1222    /// Non-zero only for React components/hooks; descriptive context surfaced in
1223    /// the hotspot drill-down, never a tunable threshold (anti-numerology).
1224    pub react_hook_count: u16,
1225    /// Maximum JSX element nesting depth reached in this function's body (the
1226    /// deepest chain of element-inside-element). `0` when the function renders
1227    /// no JSX. Descriptive context surfaced in the hotspot drill-down, never a
1228    /// tunable threshold (anti-numerology).
1229    pub react_jsx_max_depth: u16,
1230    /// Number of props destructured from this component's first parameter (the
1231    /// `{ a, b, c }` props object). `0` for non-component functions and for
1232    /// components taking a bare `props` identifier (not statically countable).
1233    /// Descriptive context surfaced in the hotspot drill-down, never a tunable
1234    /// threshold (anti-numerology).
1235    pub react_prop_count: u16,
1236    /// Content digest of the function's full-span source slice.
1237    pub source_hash: Option<String>,
1238    /// Per-decision-point breakdown explaining WHICH constructs drove the
1239    /// cyclomatic and cognitive scores. One entry per increment event (an `if`
1240    /// emits one cyclomatic and one cognitive entry at the same line, because
1241    /// the two metrics accrue at different granularities). Always computed and
1242    /// cached; surfaced in JSON only behind `health --complexity-breakdown`.
1243    pub contributions: Vec<ComplexityContribution>,
1244}
1245
1246impl FunctionComplexity {
1247    /// The name that coverage producers and runtime identities use: the
1248    /// placeholder for a function with a context name, else `name`.
1249    #[must_use]
1250    pub fn identity_name(&self) -> &str {
1251        match self.context_named {
1252            Some(kind) => kind.placeholder(),
1253            None => &self.name,
1254        }
1255    }
1256}
1257
1258/// Structural CSS metrics for one style rule of the parsed CSS. Only a rule
1259/// over a structural floor (an id selector, a complex selector, `!important`,
1260/// or deep nesting) is recorded, so the vector stays bounded. Not cached:
1261/// `fallow health` computes these from the CSS source (no `bitcode` derive).
1262#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
1263#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1264pub struct CssRuleMetric {
1265    /// 1-based line of the rule's first selector.
1266    pub line: u32,
1267    /// 1-based column of the rule's first selector.
1268    pub col: u32,
1269    /// Specificity component `a` (id selectors), max across the rule's selectors.
1270    pub specificity_a: u16,
1271    /// Specificity component `b` (class / attribute / pseudo-class selectors).
1272    pub specificity_b: u16,
1273    /// Specificity component `c` (type / pseudo-element selectors).
1274    pub specificity_c: u16,
1275    /// Largest selector component count across the rule's selector list.
1276    pub complexity: u16,
1277    /// Declaration count in the rule (normal plus `!important`).
1278    pub declaration_count: u16,
1279    /// `!important` declaration count in the rule.
1280    pub important_count: u16,
1281    /// Style-rule nesting depth (0 = top level).
1282    pub nesting_depth: u8,
1283    /// Selector list of a notable rule, for audit keys. Never serialized.
1284    #[serde(skip)]
1285    pub selector: String,
1286}
1287
1288/// A style rule's declaration-block fingerprint and location, for cross-file
1289/// duplicate-block detection. Only rules with a meaningful number of
1290/// declarations are recorded (small blocks repeat legitimately). Internal
1291/// staging only: this is consumed in-process by the health layer to build the
1292/// grouped `duplicate_declaration_blocks` output and is never serialized.
1293#[derive(Debug, Clone)]
1294pub struct CssDeclarationBlock {
1295    /// xxh3 fingerprint over the rule's normalized (sorted, `!important`-tagged)
1296    /// declaration set.
1297    pub fingerprint: u64,
1298    /// 1-based line of the rule's first selector.
1299    pub line: u32,
1300    /// Declaration count in the rule (normal plus `!important`).
1301    pub declaration_count: u16,
1302}
1303
1304/// Located raw styling value authored directly in CSS rather than via a
1305/// custom property or design-token helper. Internal staging for the health
1306/// layer; public output adds actions and confidence.
1307#[derive(Debug, Clone, PartialEq, Eq)]
1308pub struct CssRawStyleValue {
1309    /// Value axis, e.g. `color`, `font-size`, `line-height`, `radius`, or `shadow`.
1310    pub axis: String,
1311    /// CSS property where the value appears.
1312    pub property: String,
1313    /// Rendered declaration value.
1314    pub value: String,
1315    /// 1-based line of the containing style rule.
1316    pub line: u32,
1317}
1318
1319/// Located CSS custom-property definition with its rendered value. Internal
1320/// staging for design-token reuse suggestions in the health layer.
1321#[derive(Debug, Clone, PartialEq, Eq)]
1322pub struct CssCustomPropertyDefinition {
1323    /// Custom property name, including the leading `--`.
1324    pub name: String,
1325    /// Rendered custom property value.
1326    pub value: String,
1327    /// 1-based line of the containing style rule.
1328    pub line: u32,
1329}
1330
1331/// Stylesheet-level structural CSS analytics, computed from the parsed CSS
1332/// syntax tree. Feeds `fallow health` penalty weights and located findings,
1333/// never a standalone CSS score.
1334#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
1335#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1336pub struct CssAnalytics {
1337    /// Total declarations across every style rule (normal plus `!important`).
1338    pub total_declarations: u32,
1339    /// Total `!important` declarations across every style rule.
1340    pub important_declarations: u32,
1341    /// Number of style rules.
1342    pub rule_count: u32,
1343    /// Number of style rules with no declarations.
1344    pub empty_rule_count: u32,
1345    /// Deepest style-rule nesting depth observed (0 = no nesting).
1346    pub max_nesting_depth: u8,
1347    /// Rules that crossed the structural floor, in source order. Bounded; see
1348    /// [`Self::notable_truncated`]. The scalar aggregates above always reflect
1349    /// the full stylesheet regardless of truncation.
1350    pub notable_rules: Vec<CssRuleMetric>,
1351    /// `true` when more rules crossed the structural floor than `notable_rules`
1352    /// retains (compiled utility CSS can emit thousands of `!important` rules),
1353    /// so consumers can note that per-rule findings were capped.
1354    pub notable_truncated: bool,
1355    /// Distinct color VALUES in the stylesheet, sorted (a palette-size /
1356    /// design-token-sprawl signal). The parser canonicalizes notation, so the
1357    /// authored format is NOT preserved: `red`, `#f00`, `#ff0000`, and
1358    /// `rgb(255,0,0)` all collapse to one entry, and every legacy sRGB notation
1359    /// renders as hex. Notation-MIXING (hex vs rgb vs hsl) is therefore not
1360    /// detectable from this set; it would need a separate raw-token pass.
1361    pub colors: Vec<String>,
1362    /// Distinct `font-size` declaration values in the stylesheet, sorted.
1363    pub font_sizes: Vec<String>,
1364    /// Distinct `z-index` declaration values in the stylesheet, sorted.
1365    pub z_indexes: Vec<String>,
1366    /// Distinct `box-shadow` declaration values in the stylesheet, sorted. A
1367    /// high count signals an uncontrolled shadow scale (design-token sprawl).
1368    pub box_shadows: Vec<String>,
1369    /// Distinct `border-radius` declaration values in the stylesheet, sorted.
1370    pub border_radii: Vec<String>,
1371    /// Distinct `line-height` declaration values in the stylesheet, sorted.
1372    pub line_heights: Vec<String>,
1373    /// Bounded located raw styling values that bypass custom properties or
1374    /// token helpers. These are conservative declaration-level candidates for
1375    /// audit introduced-vs-base gating.
1376    #[serde(skip)]
1377    #[cfg_attr(feature = "schema", schemars(skip))]
1378    pub raw_style_values: Vec<CssRawStyleValue>,
1379    /// Located custom-property definitions with values. Internal staging
1380    /// consumed by the health layer for nearest-token suggestions.
1381    #[serde(skip)]
1382    #[cfg_attr(feature = "schema", schemars(skip))]
1383    pub custom_property_definitions: Vec<CssCustomPropertyDefinition>,
1384    /// Distinct custom properties (`--x`) DEFINED in the stylesheet, sorted.
1385    pub defined_custom_properties: Vec<String>,
1386    /// Distinct custom properties REFERENCED via `var()` in the stylesheet.
1387    pub referenced_custom_properties: Vec<String>,
1388    /// Distinct `@keyframes` names DEFINED in the stylesheet, sorted.
1389    pub defined_keyframes: Vec<String>,
1390    /// Distinct `@keyframes` names REFERENCED via `animation` / `animation-name`.
1391    pub referenced_keyframes: Vec<String>,
1392    /// Distinct custom properties REGISTERED via an `@property` rule, sorted.
1393    pub registered_custom_properties: Vec<String>,
1394    /// Distinct cascade layers DECLARED (via `@layer a, b;` statements or named
1395    /// `@layer a { }` blocks), sorted.
1396    pub declared_layers: Vec<String>,
1397    /// Distinct cascade layers POPULATED by a named `@layer a { }` block, sorted.
1398    /// A layer declared but never populated (and not imported into) is a
1399    /// cleanup candidate.
1400    pub populated_layers: Vec<String>,
1401    /// Distinct font families DECLARED by an `@font-face` rule in the stylesheet,
1402    /// sorted. A declared family referenced by no `font-family` anywhere is a
1403    /// dead web-font payload (cleanup candidate).
1404    pub defined_font_faces: Vec<String>,
1405    /// Distinct font families REFERENCED via `font-family` / `font` in the
1406    /// stylesheet, sorted (generic keywords like `serif` excluded).
1407    pub referenced_font_families: Vec<String>,
1408    /// Per-rule declaration-block fingerprints for rules at or above the minimum
1409    /// block size, used to detect duplicate declaration blocks across the
1410    /// project. Internal staging consumed by the health layer; never serialized
1411    /// (the public output is the grouped `duplicate_declaration_blocks`).
1412    #[serde(skip)]
1413    #[cfg_attr(feature = "schema", schemars(skip))]
1414    pub declaration_blocks: Vec<CssDeclarationBlock>,
1415}
1416
1417/// The kind of feature flag pattern detected.
1418#[derive(Debug, Clone, Copy, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
1419pub enum FlagUseKind {
1420    /// `process.env.FEATURE_X` pattern.
1421    EnvVar,
1422    /// SDK function call like `useFlag('name')`.
1423    SdkCall,
1424    /// Config object access like `config.features.x`.
1425    ConfigObject,
1426}
1427
1428/// A feature flag use site.
1429#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode)]
1430pub struct FlagUse {
1431    /// Flag identifier.
1432    pub flag_name: String,
1433    /// Detection kind.
1434    pub kind: FlagUseKind,
1435    /// 1-based line number.
1436    pub line: u32,
1437    /// 0-based byte column offset.
1438    pub col: u32,
1439    /// Start byte offset of the guarded block.
1440    pub guard_span_start: Option<u32>,
1441    /// End byte offset of the guarded block.
1442    pub guard_span_end: Option<u32>,
1443    /// SDK/provider name.
1444    pub sdk_name: Option<String>,
1445    /// Facts about the site, for the retirement report and the confidence
1446    /// mapping.
1447    pub facts: FlagSiteFacts,
1448}
1449
1450const _: () = assert!(std::mem::size_of::<FlagUse>() <= 96);
1451
1452/// Facts about a flag site that the flag retirement report and the
1453/// confidence mapping read.
1454///
1455/// The branch facts describe the `if`, ternary or JSX `&&` that the site
1456/// guards. A site without a guard has no branch facts.
1457#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
1458pub struct FlagSiteFacts(u8);
1459
1460impl FlagSiteFacts {
1461    const IDENTICAL_BRANCHES: u8 = 1;
1462    const EMPTY_BRANCH: u8 = 1 << 1;
1463    const DEFINITION: u8 = 1 << 2;
1464    const UNCONFIRMED_SDK: u8 = 1 << 3;
1465
1466    /// Both branches of the guard are the same code, ignoring whitespace
1467    /// and comments.
1468    #[must_use]
1469    pub const fn identical_branches(self) -> bool {
1470        self.0 & Self::IDENTICAL_BRANCHES != 0
1471    }
1472
1473    /// No branch of the guard holds code, so the flag does nothing. An
1474    /// empty branch is `{}`, `;`, `null`, `undefined`, `void 0`, `<></>`, or
1475    /// `false` next to JSX. A missing `else` is an empty branch. Code in one
1476    /// branch, for the on case or for the off case, clears this fact.
1477    #[must_use]
1478    pub const fn empty_branch(self) -> bool {
1479        self.0 & Self::EMPTY_BRANCH != 0
1480    }
1481
1482    /// The site defines the flag, as in `export const x = flag({ key })`,
1483    /// and does not read it.
1484    #[must_use]
1485    pub const fn definition(self) -> bool {
1486        self.0 & Self::DEFINITION != 0
1487    }
1488
1489    /// The site calls a generic SDK name, such as `isEnabled` or
1490    /// `getValue`, and its file imports no flag SDK or flag module. Other
1491    /// libraries use the same names, so the site is less certain.
1492    #[must_use]
1493    pub const fn unconfirmed_sdk(self) -> bool {
1494        self.0 & Self::UNCONFIRMED_SDK != 0
1495    }
1496
1497    /// These facts with `unconfirmed_sdk` set to `value`.
1498    #[must_use]
1499    pub const fn with_unconfirmed_sdk(self, value: bool) -> Self {
1500        Self::set(self, Self::UNCONFIRMED_SDK, value)
1501    }
1502
1503    /// These facts with `definition` set to `value`.
1504    #[must_use]
1505    pub const fn with_definition(self, value: bool) -> Self {
1506        Self::set(self, Self::DEFINITION, value)
1507    }
1508
1509    /// These facts with `identical_branches` set to `value`.
1510    #[must_use]
1511    pub const fn with_identical_branches(self, value: bool) -> Self {
1512        Self::set(self, Self::IDENTICAL_BRANCHES, value)
1513    }
1514
1515    /// These facts with `empty_branch` set to `value`.
1516    #[must_use]
1517    pub const fn with_empty_branch(self, value: bool) -> Self {
1518        Self::set(self, Self::EMPTY_BRANCH, value)
1519    }
1520
1521    const fn set(self, bit: u8, value: bool) -> Self {
1522        if value {
1523            Self(self.0 | bit)
1524        } else {
1525            Self(self.0 & !bit)
1526        }
1527    }
1528}
1529
1530/// User flag patterns from the `flags` config section that detection
1531/// applies during the parse. The default holds the built-in patterns only.
1532///
1533/// The parse cache keys on these patterns, so every parse that writes the
1534/// cache must use the patterns of the resolved config.
1535#[derive(Debug, Clone, Default, PartialEq, Eq)]
1536pub struct FlagPatterns {
1537    /// Extra SDK calls: function name, zero-based name argument, provider label.
1538    pub sdk_patterns: Vec<(String, usize, String)>,
1539    /// Extra environment variable prefixes.
1540    pub env_prefixes: Vec<String>,
1541    /// Whether an access on a config object with a flag-like name is a flag.
1542    pub config_object_heuristics: bool,
1543}
1544
1545impl FlagPatterns {
1546    /// Whether no user pattern is present.
1547    #[must_use]
1548    pub fn is_builtin_only(&self) -> bool {
1549        self.sdk_patterns.is_empty()
1550            && self.env_prefixes.is_empty()
1551            && !self.config_object_heuristics
1552    }
1553}
1554
1555/// A flag-key registry that a module exports: a module-level `as const`
1556/// object or a TypeScript enum whose members hold string flag keys.
1557#[derive(Debug, Clone, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
1558pub struct FlagKeyRegistry {
1559    /// Name the module exports the registry under.
1560    pub export_name: String,
1561    /// Member name and flag key of each string member, in declaration order.
1562    pub members: Vec<(String, String)>,
1563}
1564
1565/// A flag read whose key is a member of an imported registry, as in
1566/// `useFlag(FLAGS.X)` where `FLAGS` is imported.
1567///
1568/// Extraction sees one file only, so project analysis resolves the key
1569/// through the import of `registry`.
1570#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode)]
1571pub struct FlagRegistryRead {
1572    /// Local name of the imported registry binding.
1573    pub registry: String,
1574    /// Registry member that holds the flag key.
1575    pub member: String,
1576    /// The read site. `flag_name` stays empty until analysis resolves the key.
1577    pub flag_use: FlagUse,
1578}
1579
1580/// A module-level `const` with a flag-style name and a literal value, such
1581/// as `const FEATURE_NEW_UI = true`, that a guard in the same module tests.
1582///
1583/// The flag retirement report reads these. They are not in the per-site
1584/// flag findings.
1585#[derive(Debug, Clone, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
1586pub struct FlagConstant {
1587    /// Binding name.
1588    pub name: String,
1589    /// The literal value as source code: `true`, `0` or `'on'`.
1590    pub value: String,
1591    /// 1-based line of the binding.
1592    pub line: u32,
1593    /// 0-based byte column of the binding.
1594    pub col: u32,
1595    /// Guard tests that read the binding, in source order.
1596    pub reads: Vec<FlagConstantRead>,
1597}
1598
1599/// A guard test that reads a [`FlagConstant`].
1600#[derive(Debug, Clone, Copy, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
1601pub struct FlagConstantRead {
1602    /// 1-based line.
1603    pub line: u32,
1604    /// 0-based byte column.
1605    pub col: u32,
1606    /// Facts about the guard.
1607    pub facts: FlagSiteFacts,
1608}
1609
1610/// A flag definition bound to a `const`, as in
1611/// `export const showBanner = flag({ key: 'show-banner' })`.
1612#[derive(Debug, Clone, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
1613pub struct FlagDefinition {
1614    /// The binding that holds the definition.
1615    pub binding: String,
1616    /// 1-based line of the definition call, as on its [`FlagUse`].
1617    pub line: u32,
1618    /// 0-based byte column of the definition call, as on its [`FlagUse`].
1619    pub col: u32,
1620}
1621
1622/// Registry facts, and other flag facts outside the per-site findings, that
1623/// a module gives to feature flag analysis.
1624#[derive(Debug, Clone, Default, bitcode::Encode, bitcode::Decode)]
1625pub struct FlagRegistryFacts {
1626    /// Registries this module exports.
1627    pub registries: Vec<FlagKeyRegistry>,
1628    /// Flag reads that name a member of an imported registry.
1629    pub reads: Vec<FlagRegistryRead>,
1630    /// Literal `const` flags that a guard in the module tests.
1631    pub constants: Vec<FlagConstant>,
1632    /// Flag definitions bound to a `const`.
1633    pub definitions: Vec<FlagDefinition>,
1634}
1635
1636impl FlagRegistryFacts {
1637    /// Whether the module contributes no fact.
1638    #[must_use]
1639    pub fn is_empty(&self) -> bool {
1640        self.registries.is_empty()
1641            && self.reads.is_empty()
1642            && self.constants.is_empty()
1643            && self.definitions.is_empty()
1644    }
1645}
1646
1647/// The runtime mechanism used to load a module.
1648#[derive(
1649    Debug,
1650    Clone,
1651    Copy,
1652    PartialEq,
1653    Eq,
1654    Hash,
1655    serde::Serialize,
1656    serde::Deserialize,
1657    bitcode::Encode,
1658    bitcode::Decode,
1659)]
1660#[repr(u8)]
1661pub enum ModuleLoadMechanism {
1662    /// ECMAScript module loading through imports, re-exports, or import globs.
1663    EsModule = 0,
1664    /// CommonJS module loading through `require()` or `require.context`.
1665    CommonJsRequire = 1,
1666}
1667
1668/// When the target of an import edge loads, relative to the importing module.
1669///
1670/// The startup weight report follows only `Static` edges to find the code that
1671/// loads before the entry module runs. The other kinds load later, or outside
1672/// the importing thread, except `PathReference` and `AssetReference`. These
1673/// two edges keep their target in use but do not run it: see
1674/// [`Self::loads_target`]. Only an asset reference also stops reachability:
1675/// see [`Self::runs_target_code`].
1676#[derive(
1677    Debug,
1678    Clone,
1679    Copy,
1680    Default,
1681    PartialEq,
1682    Eq,
1683    PartialOrd,
1684    Ord,
1685    Hash,
1686    serde::Serialize,
1687    serde::Deserialize,
1688    bitcode::Encode,
1689    bitcode::Decode,
1690)]
1691#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1692#[serde(rename_all = "snake_case")]
1693#[repr(u8)]
1694pub enum ImportLoadKind {
1695    /// The target loads before the importer runs: `import`, `export ... from`,
1696    /// `require()`, `require.context` and `import.meta.glob(..., { eager: true })`.
1697    #[default]
1698    Static = 0,
1699    /// The target loads on demand through `import('./literal')`.
1700    Dynamic = 1,
1701    /// The target is one match of an on-demand pattern: a template `import()`
1702    /// or a lazy `import.meta.glob`.
1703    DynamicPattern = 2,
1704    /// The target runs on another thread or in another process: a
1705    /// `new URL(..., import.meta.url)` reference (for example a worker URL),
1706    /// a webpack worker loader request (`worker-loader!./work.js`),
1707    /// `child_process.fork`, a pino transport or a `module.register` hook.
1708    OutOfThread = 3,
1709    /// The importer gets only the path of the target and does not load it:
1710    /// `require.resolve('./file')` or ``require.resolve(`./file`)``. The edge
1711    /// keeps the target in use. The consumer of the path can run the target
1712    /// later, so the imports of the target stay reachable.
1713    PathReference = 4,
1714    /// The importer reads the target as text, bytes or a URL through a
1715    /// webpack asset loader, such as `raw-loader!./file.js`. The bundle never
1716    /// runs the target as code, so the imports of the target are not
1717    /// reachable through this edge. The graph sets this kind; extraction
1718    /// never records it.
1719    AssetReference = 5,
1720}
1721
1722impl ImportLoadKind {
1723    /// Whether the target loads before the importing module runs.
1724    #[must_use]
1725    pub const fn is_eager(self) -> bool {
1726        matches!(self, Self::Static)
1727    }
1728
1729    /// Whether the target loads on demand on the importing thread.
1730    #[must_use]
1731    pub const fn is_deferred(self) -> bool {
1732        matches!(self, Self::Dynamic | Self::DynamicPattern)
1733    }
1734
1735    /// Whether the edge runs its target. A path reference and an asset
1736    /// reference keep the target in use but do not run it, so the edge does
1737    /// not close a cycle, is not in the entry load closure, does not cross an
1738    /// architecture boundary and does not carry server code into a client
1739    /// bundle.
1740    #[must_use]
1741    pub const fn loads_target(self) -> bool {
1742        !matches!(self, Self::PathReference | Self::AssetReference)
1743    }
1744
1745    /// Whether the target can run as code at all, through this edge or
1746    /// through the consumer of a path reference. Only an asset reference never
1747    /// runs its target, so reachability does not continue through it.
1748    #[must_use]
1749    pub const fn runs_target_code(self) -> bool {
1750        !matches!(self, Self::AssetReference)
1751    }
1752
1753    /// Whether an import with this load kind puts a runtime value of the
1754    /// target on the startup path: the target loads before the importer runs
1755    /// and the import is not type-only.
1756    #[must_use]
1757    pub const fn is_eager_value(self, is_type_only: bool) -> bool {
1758        self.is_eager() && !is_type_only
1759    }
1760}
1761
1762/// A dynamic import with a partially resolved pattern.
1763#[derive(Debug, Clone)]
1764pub struct DynamicImportPattern {
1765    /// Glob prefix of the import path (e.g., "./locales/"). An
1766    /// `import.meta.glob` pattern is the full glob. For a template literal, a
1767    /// string concatenation, or `require.context`, each glob metacharacter of
1768    /// the literal text is escaped as a one-character class, such as `[[]`.
1769    pub prefix: String,
1770    /// Glob suffix of the import path (e.g., ".json"), if any.
1771    pub suffix: Option<String>,
1772    /// Globs of the files that the pattern does not load. Vite reads a
1773    /// negative `import.meta.glob` array entry, such as `'!./a/skip.js'`, as
1774    /// an exclude for every positive entry of the same call.
1775    pub excludes: Vec<String>,
1776    /// Source span in the original file.
1777    pub span: Span,
1778    /// Runtime mechanism used to load modules matching this pattern.
1779    pub mechanism: ModuleLoadMechanism,
1780}
1781
1782/// Visibility tag from JSDoc/TSDoc comments that suppresses unused-export detection.
1783#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
1784#[serde(rename_all = "lowercase")]
1785#[repr(u8)]
1786pub enum VisibilityTag {
1787    /// No visibility tag present.
1788    #[default]
1789    None = 0,
1790    /// `@public` or `@api public` -- part of the public API surface.
1791    Public = 1,
1792    /// `@internal` -- exported for internal use (sister packages, build tools).
1793    Internal = 2,
1794    /// `@beta` -- public but unstable, may change without notice.
1795    Beta = 3,
1796    /// `@alpha` -- early preview, may change drastically without notice.
1797    Alpha = 4,
1798    /// `@expected-unused` -- intentionally unused, should warn when it becomes used.
1799    ExpectedUnused = 5,
1800}
1801
1802impl VisibilityTag {
1803    /// Whether this tag permanently suppresses unused-export detection.
1804    /// `ExpectedUnused` is handled separately (conditionally suppresses,
1805    /// reports stale when the export becomes used).
1806    pub const fn suppresses_unused(self) -> bool {
1807        matches!(
1808            self,
1809            Self::Public | Self::Internal | Self::Beta | Self::Alpha
1810        )
1811    }
1812
1813    /// For serde `skip_serializing_if`.
1814    pub fn is_none(&self) -> bool {
1815        matches!(self, Self::None)
1816    }
1817}
1818
1819/// An export declaration.
1820#[derive(Debug, Clone, serde::Serialize)]
1821pub struct ExportInfo {
1822    /// The exported name (named or default).
1823    pub name: ExportName,
1824    /// The local binding name, if different from the exported name.
1825    pub local_name: Option<String>,
1826    /// Whether this is a type-only export (`export type`).
1827    pub is_type_only: bool,
1828    /// Whether this export is registered through a runtime side effect at module load time.
1829    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1830    pub is_side_effect_used: bool,
1831    /// Visibility tag from JSDoc/TSDoc comment.
1832    #[serde(default, skip_serializing_if = "VisibilityTag::is_none")]
1833    pub visibility: VisibilityTag,
1834    /// Human-authored reason on `@expected-unused -- <reason>`, when present.
1835    #[serde(default, skip_serializing_if = "Option::is_none")]
1836    pub expected_unused_reason: Option<String>,
1837    /// Whether the leading JSDoc carries a `@deprecated` tag. Orthogonal to
1838    /// `visibility`: `@public @deprecated` is a normal combination.
1839    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1840    pub deprecated: bool,
1841    /// Plain-text `@deprecated` message, capped at
1842    /// `DEPRECATED_REASON_MAX_CHARS` characters. `None` for a bare tag.
1843    #[serde(default, skip_serializing_if = "Option::is_none")]
1844    pub deprecated_reason: Option<Box<str>>,
1845    /// Source span of the export declaration.
1846    #[serde(serialize_with = "serialize_span")]
1847    pub span: Span,
1848    /// Members of this export (for enums, classes, and namespaces).
1849    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1850    pub members: Vec<MemberInfo>,
1851    /// The local name of the parent class from `extends` clause, if any.
1852    #[serde(default, skip_serializing_if = "Option::is_none")]
1853    pub super_class: Option<String>,
1854}
1855
1856/// Additional heritage metadata for an exported class.
1857#[derive(
1858    Debug,
1859    Clone,
1860    serde::Serialize,
1861    serde::Deserialize,
1862    bitcode::Encode,
1863    bitcode::Decode,
1864    PartialEq,
1865    Eq,
1866)]
1867pub struct ClassHeritageInfo {
1868    /// Export name (`default` for default-exported classes).
1869    pub export_name: String,
1870    /// Parent class name from the `extends` clause, if any.
1871    pub super_class: Option<String>,
1872    /// Interface names from the class `implements` clause.
1873    pub implements: Vec<String>,
1874    /// Ordered class type-parameter names for multi-hop type arguments.
1875    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1876    pub type_parameters: Vec<String>,
1877    /// Typed instance bindings used to resolve member-access chains in external templates.
1878    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1879    pub instance_bindings: Vec<(String, String)>,
1880    /// Positional type arguments on the `extends` clause, such as
1881    /// `<DerivedClient>`. An empty string marks an argument that is not a
1882    /// plain type reference (issue #1910).
1883    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1884    pub super_class_type_args: Vec<String>,
1885    /// Instance-binding fields typed as exactly a class type parameter, as
1886    /// `(field_name, type_param_index)` (issue #1910).
1887    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1888    pub generic_instance_bindings: Vec<(String, usize)>,
1889    /// The outer `extends` target and its type arguments after the fold of
1890    /// unexported local bases (issue #4199). The walk for inherited bindings
1891    /// reads it. `super_class` keeps the declared name.
1892    #[serde(default, skip_serializing_if = "Option::is_none")]
1893    pub binding_super_class: Option<(String, Vec<String>)>,
1894}
1895
1896/// One resolved property of an object-literal factory return: a dotted property
1897/// path mapped to the class the value at that path is an instance of.
1898///
1899/// `return { invoke: { orders: factory.ordersPage } }` records
1900/// `{ property_path: "invoke.orders", class_local_name: "OrdersPage" }`. The class
1901/// name is the factory module's own LOCAL name, resolved at analyze time through the
1902/// factory module's imports to the real class export. See issue #1858.
1903#[derive(
1904    Debug,
1905    Clone,
1906    serde::Serialize,
1907    serde::Deserialize,
1908    bitcode::Encode,
1909    bitcode::Decode,
1910    PartialEq,
1911    Eq,
1912)]
1913pub struct FactoryReturnObjectProperty {
1914    /// Dotted property path from the returned object literal (`orders`, `invoke.orders`).
1915    pub property_path: String,
1916    /// The property value's class local name within the factory module.
1917    pub class_local_name: String,
1918}
1919
1920/// An exported factory function that returns an object literal whose property
1921/// values are class instances, joined to its public export name.
1922///
1923/// A cross-module `const ui = createUi(); ui.orders.member` consumer emits a
1924/// `FactoryReturnObjectPropertyAccess` fact; the analyze layer resolves `export_name`
1925/// through the consumer's imports to this module, matches `property_path`, and credits
1926/// `member` on the resolved class (gated on it being a class with members). See issue #1858.
1927#[derive(
1928    Debug,
1929    Clone,
1930    serde::Serialize,
1931    serde::Deserialize,
1932    bitcode::Encode,
1933    bitcode::Decode,
1934    PartialEq,
1935    Eq,
1936)]
1937pub struct FactoryReturnObjectShapeExport {
1938    /// Public export name (honors `export { createUi as createOrdersUi }`).
1939    pub export_name: String,
1940    /// Resolved `(property_path -> class_local_name)` entries for the returned literal.
1941    pub properties: Box<[FactoryReturnObjectProperty]>,
1942}
1943
1944/// A named-type property whose declared type is a named type reference.
1945///
1946/// `interface Opts { c: OptDep }` (or `type Opts = { c: OptDep }`) records
1947/// `TypeMemberTypeEntry { type_name: "Opts", property: "c", property_type: "OptDep" }`.
1948/// Both `type_name` and `property_type` are the DECLARING module's own local
1949/// names; resolution through that module's imports/exports is deferred to
1950/// analyze time, mirroring `FactoryReturnExport.class_local_name`. Consumed by
1951/// the `unused-class-member` typed-property-hop join so a consumer's
1952/// `this.opts.c.optM()` credits `OptDep.optM` across module boundaries.
1953/// See issue #1785.
1954#[derive(
1955    Debug,
1956    Clone,
1957    serde::Serialize,
1958    serde::Deserialize,
1959    bitcode::Encode,
1960    bitcode::Decode,
1961    PartialEq,
1962    Eq,
1963)]
1964pub struct TypeMemberTypeEntry {
1965    /// Local interface or type-alias name declaring the property.
1966    pub type_name: String,
1967    /// Property name declared on the type.
1968    pub property: String,
1969    /// The property's declared type name (local to the declaring module).
1970    pub property_type: String,
1971}
1972
1973/// A module-scope declaration that can be used as a TypeScript type.
1974#[derive(Debug, Clone, serde::Serialize, PartialEq, Eq)]
1975pub struct LocalTypeDeclaration {
1976    /// Local declaration name.
1977    pub name: String,
1978    /// Declaration identifier span.
1979    #[serde(serialize_with = "serialize_span")]
1980    pub span: Span,
1981}
1982
1983/// A reference from an exported symbol's public signature to a type name.
1984#[derive(Debug, Clone, serde::Serialize, PartialEq, Eq)]
1985pub struct PublicSignatureTypeReference {
1986    /// Exported symbol whose signature contains the reference.
1987    pub export_name: String,
1988    /// Referenced type name. Qualified names are reduced to their root identifier.
1989    pub type_name: String,
1990    /// Reference span.
1991    #[serde(serialize_with = "serialize_span")]
1992    pub span: Span,
1993    /// True when the reference comes from a `satisfies` clause. The clause
1994    /// checks the value but does not change the exported type, so the type is
1995    /// in use but is not a private type leak.
1996    #[serde(skip_serializing_if = "std::ops::Not::not")]
1997    pub from_satisfies: bool,
1998}
1999
2000/// A member of an enum, class, or namespace.
2001#[derive(Debug, Clone, serde::Serialize)]
2002pub struct MemberInfo {
2003    /// Member name.
2004    pub name: String,
2005    /// The kind of member (enum, class method/property, or namespace member).
2006    pub kind: MemberKind,
2007    /// Source span of the member declaration.
2008    #[serde(serialize_with = "serialize_span")]
2009    pub span: Span,
2010    /// Whether this member has decorators (e.g., `@Column()`, `@Inject()`).
2011    /// Decorated members are used by frameworks at runtime and should not be
2012    /// flagged as unused class members, unless every decorator on the member
2013    /// is opted out via `FallowConfig.ignore_decorators`.
2014    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
2015    pub has_decorator: bool,
2016    /// Full dotted path of each decorator on this member, in source order.
2017    /// `@step("x")` stores `"step"`; `@ns.foo` stores `"ns.foo"`. Empty for
2018    /// undecorated members, Angular signal-initializer properties (which set
2019    /// `has_decorator` without a literal decorator AST node), and decorators
2020    /// whose expression is not an identifier ladder (the entry is the empty
2021    /// string in that case, treated as never-matching by the predicate).
2022    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2023    pub decorator_names: Vec<String>,
2024    /// True when this is a static class method that returns a fresh instance
2025    /// of the same class: either via `return new this()` / `return new
2026    /// <SameClassName>()` in the body's last statement, or via a declared
2027    /// return type matching the class name. Consumers calling such a static
2028    /// method receive an instance, so the call result's member accesses are
2029    /// credited against the class. See issues #346, #387.
2030    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
2031    pub is_instance_returning_static: bool,
2032    /// True when this is an instance class method whose call result is an
2033    /// instance of the same class. Qualifies when the declared return type
2034    /// matches the class name (`setX(): EventBuilder { ... }`) or when the
2035    /// body's last statement is `return this`. The analyze layer walks fluent
2036    /// chains (`Class.factory().setX().setY()`) only through methods carrying
2037    /// this flag, so the chain stops at a non-self-returning method like
2038    /// `.build()`. See issue #387.
2039    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
2040    pub is_self_returning: bool,
2041    /// Root identifier of the class `extends` expression, set only when the
2042    /// member has the `override` modifier: `Container` in
2043    /// `extends Container<Env>`, `Schema` in `extends Schema.TaggedError<E>()(...)`.
2044    /// The analysis credits the member when this root names code outside the
2045    /// project, because that code calls the overridden member.
2046    #[serde(default, skip_serializing_if = "Option::is_none")]
2047    pub override_base: Option<String>,
2048}
2049
2050/// The kind of member.
2051#[derive(
2052    Debug,
2053    Clone,
2054    Copy,
2055    PartialEq,
2056    Eq,
2057    serde::Serialize,
2058    serde::Deserialize,
2059    bitcode::Encode,
2060    bitcode::Decode,
2061)]
2062#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2063#[serde(rename_all = "snake_case")]
2064pub enum MemberKind {
2065    /// A TypeScript enum member.
2066    EnumMember,
2067    /// A class method.
2068    ClassMethod,
2069    /// A class property.
2070    ClassProperty,
2071    /// A member exported from a TypeScript namespace.
2072    NamespaceMember,
2073    /// A member declared by a store object (Pinia `state` / `getters` /
2074    /// `actions` key, or a setup-store returned key). Cross-graph dead-member
2075    /// detection: a store member never accessed by any consumer project-wide.
2076    StoreMember,
2077}
2078
2079/// A static member access expression (e.g., `Status.Active`, `MyClass.create()`).
2080#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, bitcode::Encode, bitcode::Decode)]
2081pub struct MemberAccess {
2082    /// The identifier being accessed (the import name).
2083    pub object: String,
2084    /// The member being accessed.
2085    pub member: String,
2086}
2087
2088/// Direct export declarations that TypeScript treats as one merged symbol.
2089///
2090/// Spans identify the exact declaration slots without conflating unrelated
2091/// type/value declarations that happen to share a name.
2092#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2093#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2094pub struct DeclarationMergeFact {
2095    /// Identifier spans for the declarations in this merge group.
2096    pub export_spans: Vec<(u32, u32)>,
2097}
2098
2099/// A default import binding consumed outside a statically known member access.
2100///
2101/// Resolution decides whether the target is an object-shaped module such as a
2102/// CSS Module or a proven static CommonJS object map. Keeping this fact
2103/// target-agnostic lets aliases and extensionless specifiers use the resolved
2104/// target path without broadening ordinary default-import behavior.
2105#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2106#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2107pub struct DefaultImportWholeObjectUseFact {
2108    /// Local binding name in the importing module.
2109    pub local_name: String,
2110}
2111
2112#[path = "extract_semantic.rs"]
2113mod semantic;
2114pub use semantic::SemanticFact;
2115
2116pub use crate::extract_namespace_member_uses::NamespaceMemberUseFact;
2117
2118/// A static member name that a runtime probe checks on an untyped value.
2119#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2120#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2121pub struct MemberNameProbeFact {
2122    /// The probed member name.
2123    pub name: String,
2124}
2125
2126/// Deferred class provenance owned by the module declaring an object factory.
2127#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2128#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2129pub enum FactoryPropertySource {
2130    /// A property path through a named type in the factory's module.
2131    TypedProperty {
2132        /// Named receiver type in the producer module.
2133        type_name: String,
2134        /// Remaining path through the receiver type.
2135        property_path: String,
2136    },
2137    /// A synchronous function call in the factory's module.
2138    FunctionReturn {
2139        /// Function binding in the producer module.
2140        callee_name: String,
2141    },
2142    /// A proven instance-returning static class method.
2143    StaticFactoryReturn {
2144        /// Class binding in the producer module.
2145        callee_object: String,
2146        /// Statically named instance-returning method.
2147        callee_method: String,
2148    },
2149    /// A class proven in the object factory's own module.
2150    LocalClass {
2151        /// Local class binding resolved relative to the factory module.
2152        class_local_name: String,
2153    },
2154    /// Return of the callback at this ordinal in the proven helper declaration.
2155    CallbackParameterReturn {
2156        /// Zero-based formal parameter ordinal.
2157        parameter_index: u32,
2158    },
2159}
2160
2161/// Callback-origin member use, joined with the callee module's property source.
2162#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2163#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2164pub struct CallbackFactoryPropertyAccessFact {
2165    /// Callee import binding in the caller module.
2166    pub callee_name: String,
2167    /// Static export selected from a namespace import, if present.
2168    pub callee_member: Option<String>,
2169    /// Requested path in the wrapper's returned value.
2170    pub property_path: String,
2171    /// Requested member on the callback result.
2172    pub member: String,
2173    /// A property write permits only the canonical Vue getter contract.
2174    pub vue_only: bool,
2175    /// Ordinary assigned value, ignored by a canonical Vue setter contract.
2176    pub assigned_class: Option<String>,
2177    /// Callback ordinal and class origin interpreted in the caller module.
2178    pub arguments: Vec<CallbackFactoryArgument>,
2179}
2180
2181/// Proven callback result owned by a factory consumer's module.
2182#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2183#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2184pub struct CallbackFactoryArgument {
2185    /// Zero-based actual argument ordinal.
2186    pub parameter_index: u32,
2187    /// Class binding resolved in the consumer module.
2188    pub class_local_name: String,
2189    /// This argument is an options object with a proven `get` callback.
2190    pub getter: bool,
2191    /// No mutable capture makes a lazy invocation select another class.
2192    pub lazy_safe: bool,
2193}
2194
2195/// An exported object factory's deferred property receiver.
2196#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2197#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2198pub struct FactoryReturnObjectPropertySourceFact {
2199    /// Public factory export name.
2200    pub factory_export_name: String,
2201    /// Path within the returned object, separate from any source property path.
2202    pub property_path: String,
2203    /// Names interpreted relative to this fact's owning module.
2204    pub source: FactoryPropertySource,
2205}
2206
2207/// The load kind of the dynamic imports or patterns that start at `span_start`.
2208#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2209#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2210pub struct ImportLoadKindOverrideFact {
2211    /// Byte offset of the call or `new` expression that records the edge.
2212    pub span_start: u32,
2213    /// The load kind of every edge that the expression records.
2214    pub kind: ImportLoadKind,
2215}
2216
2217/// The Module Federation runtime function that a call names.
2218#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2219#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2220#[serde(rename_all = "camelCase")]
2221pub enum FederationRuntimeCall {
2222    /// `registerRemotes([{ name, entry }])`.
2223    RegisterRemotes,
2224    /// `loadRemote('remote/module')`.
2225    LoadRemote,
2226    /// `init({ remotes: [{ name, entry }] })`.
2227    /// Appended because bitcode encodes enum variants by ordinal.
2228    Init,
2229    /// `createInstance({ remotes: [{ name, entry }] })`.
2230    CreateInstance,
2231}
2232
2233impl FederationRuntimeCall {
2234    /// The function name as the source writes it.
2235    #[must_use]
2236    pub const fn name(self) -> &'static str {
2237        match self {
2238            Self::RegisterRemotes => "registerRemotes",
2239            Self::LoadRemote => "loadRemote",
2240            Self::Init => "init",
2241            Self::CreateInstance => "createInstance",
2242        }
2243    }
2244}
2245
2246/// One remote that a Module Federation runtime call names.
2247///
2248/// `remote` is the remote alias when the argument is a static literal, and
2249/// `None` when the call receives a value that static analysis cannot read.
2250#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2251#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2252pub struct FederationRuntimeRemoteFact {
2253    /// The runtime function the call names.
2254    pub call: FederationRuntimeCall,
2255    /// The remote alias the call names, or `None` for a non-literal argument.
2256    pub remote: Option<String>,
2257}
2258
2259/// Iterate Angular template member names from typed semantic facts.
2260fn angular_template_member_names_from_parts(
2261    semantic_facts: &[SemanticFact],
2262) -> impl Iterator<Item = &str> {
2263    semantic_facts.iter().filter_map(|fact| {
2264        if let SemanticFact::AngularTemplateMemberAccess(access) = fact {
2265            Some(access.member.as_str())
2266        } else {
2267            None
2268        }
2269    })
2270}
2271
2272/// Iterate Angular template member names from a module's typed facts.
2273pub fn angular_template_member_names(module: &ModuleInfo) -> impl Iterator<Item = &str> {
2274    angular_template_member_names_from_parts(&module.semantic_facts)
2275}
2276
2277/// Return true when the fact slice contains any Angular template member
2278/// reference.
2279#[must_use]
2280fn has_angular_template_members_from_parts(semantic_facts: &[SemanticFact]) -> bool {
2281    angular_template_member_names_from_parts(semantic_facts)
2282        .next()
2283        .is_some()
2284}
2285
2286/// Return true when the module contains any Angular template member reference.
2287#[must_use]
2288pub fn has_angular_template_members(module: &ModuleInfo) -> bool {
2289    has_angular_template_members_from_parts(&module.semantic_facts)
2290}
2291
2292/// Return true when a module spreads `this` in Angular template context.
2293#[must_use]
2294pub fn has_angular_this_spread(module: &ModuleInfo) -> bool {
2295    SemanticFactView::new(&module.semantic_facts, &module.member_accesses).has_angular_this_spread()
2296}
2297
2298/// Return true when a module contains a dynamic custom-element render.
2299#[must_use]
2300pub fn has_dynamic_custom_element_render(module: &ModuleInfo) -> bool {
2301    module
2302        .semantic_facts
2303        .iter()
2304        .any(|fact| matches!(fact, SemanticFact::DynamicCustomElementRender(_)))
2305}
2306
2307/// Typed-first view over semantic extraction facts.
2308///
2309/// Extraction populates `semantic_facts` directly. The `member_accesses` slice
2310/// remains available for consumers that need ordinary source member accesses,
2311/// but it is no longer decoded as a string protocol for semantic facts.
2312#[derive(Debug, Clone, Copy)]
2313pub struct SemanticFactView<'a> {
2314    semantic_facts: &'a [SemanticFact],
2315    member_accesses: &'a [MemberAccess],
2316}
2317
2318impl<'a> SemanticFactView<'a> {
2319    /// Create a typed semantic fact view from current semantic facts plus
2320    /// ordinary source member accesses.
2321    #[must_use]
2322    pub const fn new(
2323        semantic_facts: &'a [SemanticFact],
2324        member_accesses: &'a [MemberAccess],
2325    ) -> Self {
2326        Self {
2327            semantic_facts,
2328            member_accesses,
2329        }
2330    }
2331
2332    /// Iterate typed semantic facts.
2333    pub fn facts(self) -> impl Iterator<Item = &'a SemanticFact> + 'a {
2334        self.semantic_facts.iter()
2335    }
2336
2337    /// Iterate Angular template member references.
2338    pub fn angular_template_member_names(self) -> impl Iterator<Item = &'a str> + 'a {
2339        angular_template_member_names_from_parts(self.semantic_facts)
2340    }
2341
2342    /// Collect Angular component field array-type facts.
2343    pub fn angular_component_field_array_types(self) -> Vec<AngularComponentFieldArrayTypeFact> {
2344        angular_component_field_array_type_facts(self.semantic_facts)
2345            .cloned()
2346            .collect()
2347    }
2348
2349    /// Return true when any Angular template member reference exists.
2350    #[must_use]
2351    pub fn has_angular_template_members(self) -> bool {
2352        self.angular_template_member_names().next().is_some()
2353    }
2354
2355    /// Return true when a module spreads `this` in Angular template context.
2356    #[must_use]
2357    pub fn has_angular_this_spread(self) -> bool {
2358        self.semantic_facts
2359            .iter()
2360            .any(|fact| matches!(fact, SemanticFact::AngularThisSpread(_)))
2361    }
2362
2363    /// Iterate ordinary source member accesses.
2364    pub fn ordinary_member_accesses(self) -> impl Iterator<Item = &'a MemberAccess> + 'a {
2365        self.member_accesses.iter()
2366    }
2367
2368    /// Collect class-scoped `this` member-access facts.
2369    pub fn class_this_member_accesses(self) -> Vec<ClassThisMemberAccessFact> {
2370        class_this_member_access_facts(self.semantic_facts)
2371            .cloned()
2372            .collect()
2373    }
2374
2375    /// Collect class-scoped `this` whole-object-use facts.
2376    pub fn class_this_whole_object_uses(self) -> Vec<ClassThisWholeObjectUseFact> {
2377        class_this_whole_object_use_facts(self.semantic_facts)
2378            .cloned()
2379            .collect()
2380    }
2381
2382    /// Collect instance-export binding facts.
2383    pub fn instance_export_bindings(self) -> Vec<InstanceExportBindingFact> {
2384        instance_export_binding_facts(self.semantic_facts)
2385            .cloned()
2386            .collect()
2387    }
2388
2389    /// Iterate exported object properties that contain class instances.
2390    pub fn exported_object_instance_properties(
2391        self,
2392    ) -> impl Iterator<Item = &'a ExportedObjectInstancePropertyFact> + 'a {
2393        exported_object_instance_property_facts(self.semantic_facts)
2394    }
2395
2396    /// Iterate proven namespace-qualified class member accesses.
2397    pub fn qualified_class_member_accesses(
2398        self,
2399    ) -> impl Iterator<Item = &'a QualifiedClassMemberAccessFact> + 'a {
2400        qualified_class_member_access_facts(self.semantic_facts)
2401    }
2402
2403    /// Collect static factory call member facts.
2404    pub fn factory_call_member_accesses(self) -> Vec<FactoryCallMemberAccessFact> {
2405        factory_call_member_access_facts(self.semantic_facts)
2406            .cloned()
2407            .collect()
2408    }
2409
2410    /// Collect free-function factory-return member facts.
2411    pub fn factory_fn_member_accesses(self) -> Vec<FactoryFnMemberAccessFact> {
2412        factory_fn_member_access_facts(self.semantic_facts)
2413            .cloned()
2414            .collect()
2415    }
2416
2417    /// Collect factory-return whole-object consumption facts.
2418    pub fn factory_fn_whole_objects(self) -> Vec<FactoryFnWholeObjectFact> {
2419        factory_fn_whole_object_facts(self.semantic_facts)
2420            .cloned()
2421            .collect()
2422    }
2423
2424    /// Collect object-literal factory-return property member facts.
2425    pub fn factory_return_object_property_accesses(
2426        self,
2427    ) -> Vec<FactoryReturnObjectPropertyAccessFact> {
2428        factory_return_object_property_access_facts(self.semantic_facts)
2429            .cloned()
2430            .collect()
2431    }
2432
2433    /// Iterate deferred object-factory property sources without copying their names.
2434    pub fn factory_return_object_property_sources(
2435        self,
2436    ) -> impl Iterator<Item = &'a FactoryReturnObjectPropertySourceFact> + 'a {
2437        self.semantic_facts.iter().filter_map(|fact| match fact {
2438            SemanticFact::FactoryReturnObjectPropertySource(source) => Some(source.as_ref()),
2439            _ => None,
2440        })
2441    }
2442
2443    /// Property accesses with source-owned receiver admission.
2444    pub fn proven_factory_return_object_property_accesses(
2445        self,
2446    ) -> impl Iterator<Item = &'a FactoryReturnObjectPropertyAccessFact> + 'a {
2447        self.semantic_facts.iter().filter_map(|fact| match fact {
2448            SemanticFact::ProvenFactoryReturnObjectPropertyAccess(access) => Some(access),
2449            _ => None,
2450        })
2451    }
2452
2453    /// Iterate caller-owned callback property projections.
2454    pub fn callback_factory_property_accesses(
2455        self,
2456    ) -> impl Iterator<Item = &'a CallbackFactoryPropertyAccessFact> + 'a {
2457        self.semantic_facts.iter().filter_map(|fact| match fact {
2458            SemanticFact::CallbackFactoryPropertyAccess(access) => Some(access.as_ref()),
2459            _ => None,
2460        })
2461    }
2462
2463    /// Collect typed-property-hop member facts.
2464    pub fn typed_property_member_accesses(self) -> Vec<TypedPropertyMemberAccessFact> {
2465        typed_property_member_access_facts(self.semantic_facts)
2466            .cloned()
2467            .collect()
2468    }
2469
2470    /// Collect members whose presence is required by a named structural type.
2471    pub fn required_type_members(self) -> impl Iterator<Item = &'a RequiredTypeMemberFact> + 'a {
2472        required_type_member_facts(self.semantic_facts)
2473    }
2474
2475    /// Collect type-alias receiver-surface edges.
2476    pub fn type_alias_surface_targets(self) -> Vec<TypeAliasSurfaceTargetFact> {
2477        type_alias_surface_target_facts(self.semantic_facts)
2478            .cloned()
2479            .collect()
2480    }
2481
2482    /// Collect string-valued enum member definitions.
2483    pub fn string_enum_member_values(self) -> Vec<StringEnumMemberValueFact> {
2484        string_enum_member_value_facts(self.semantic_facts)
2485            .cloned()
2486            .collect()
2487    }
2488
2489    /// Collect computed property accesses keyed by enum members.
2490    pub fn computed_enum_key_uses(self) -> Vec<ComputedEnumKeyUseFact> {
2491        computed_enum_key_use_facts(self.semantic_facts)
2492            .cloned()
2493            .collect()
2494    }
2495
2496    /// Collect static factory fluent-chain member facts.
2497    pub fn fluent_chain_member_accesses(self) -> Vec<FluentChainMemberAccessFact> {
2498        fluent_chain_member_access_facts(self.semantic_facts)
2499            .cloned()
2500            .collect()
2501    }
2502
2503    /// Collect constructor-rooted fluent-chain member facts.
2504    pub fn fluent_chain_new_member_accesses(self) -> Vec<FluentChainNewMemberAccessFact> {
2505        fluent_chain_new_member_access_facts(self.semantic_facts)
2506            .cloned()
2507            .collect()
2508    }
2509
2510    /// Collect Playwright fixture-use facts.
2511    pub fn playwright_fixture_uses(self) -> Vec<PlaywrightFixtureUseFact> {
2512        playwright_fixture_use_facts(self.semantic_facts)
2513            .cloned()
2514            .collect()
2515    }
2516
2517    /// Collect Playwright fixture-definition facts.
2518    pub fn playwright_fixture_definitions(self) -> Vec<PlaywrightFixtureDefinitionFact> {
2519        playwright_fixture_definition_facts(self.semantic_facts)
2520            .cloned()
2521            .collect()
2522    }
2523
2524    /// Collect Playwright fixture-alias facts.
2525    pub fn playwright_fixture_aliases(self) -> Vec<PlaywrightFixtureAliasFact> {
2526        playwright_fixture_alias_facts(self.semantic_facts)
2527            .cloned()
2528            .collect()
2529    }
2530
2531    /// Collect conditional Playwright fixture-definition facts.
2532    pub fn playwright_conditional_fixture_definitions(
2533        self,
2534    ) -> Vec<PlaywrightConditionalFixtureDefinitionFact> {
2535        self.semantic_facts
2536            .iter()
2537            .filter_map(|fact| match fact {
2538                SemanticFact::PlaywrightConditionalFixtureDefinition(access) => {
2539                    Some(access.as_ref().clone())
2540                }
2541                _ => None,
2542            })
2543            .collect()
2544    }
2545
2546    /// Collect the names of proven Playwright test bindings.
2547    pub fn playwright_test_bindings(self) -> Vec<PlaywrightTestBindingFact> {
2548        self.semantic_facts
2549            .iter()
2550            .filter_map(|fact| match fact {
2551                SemanticFact::PlaywrightTestBinding(binding) => Some(binding.clone()),
2552                _ => None,
2553            })
2554            .collect()
2555    }
2556
2557    /// Collect Playwright fixture-type facts.
2558    pub fn playwright_fixture_types(self) -> Vec<PlaywrightFixtureTypeFact> {
2559        playwright_fixture_type_facts(self.semantic_facts)
2560            .cloned()
2561            .collect()
2562    }
2563}
2564
2565/// Iterate ordinary whole-object uses.
2566pub fn ordinary_whole_object_uses(whole_object_uses: &[String]) -> impl Iterator<Item = &str> {
2567    whole_object_uses.iter().map(String::as_str)
2568}
2569
2570/// Iterate typed instance-export binding facts.
2571fn instance_export_binding_facts(
2572    semantic_facts: &[SemanticFact],
2573) -> impl Iterator<Item = &InstanceExportBindingFact> {
2574    semantic_facts.iter().filter_map(|fact| {
2575        if let SemanticFact::InstanceExportBinding(access) = fact {
2576            Some(access)
2577        } else {
2578            None
2579        }
2580    })
2581}
2582
2583fn exported_object_instance_property_facts(
2584    semantic_facts: &[SemanticFact],
2585) -> impl Iterator<Item = &ExportedObjectInstancePropertyFact> {
2586    semantic_facts.iter().filter_map(|fact| {
2587        if let SemanticFact::ExportedObjectInstanceProperty(property) = fact {
2588            Some(property)
2589        } else {
2590            None
2591        }
2592    })
2593}
2594
2595fn qualified_class_member_access_facts(
2596    semantic_facts: &[SemanticFact],
2597) -> impl Iterator<Item = &QualifiedClassMemberAccessFact> {
2598    semantic_facts.iter().filter_map(|fact| {
2599        if let SemanticFact::QualifiedClassMemberAccess(access) = fact {
2600            Some(access)
2601        } else {
2602            None
2603        }
2604    })
2605}
2606
2607fn class_this_member_access_facts(
2608    semantic_facts: &[SemanticFact],
2609) -> impl Iterator<Item = &ClassThisMemberAccessFact> {
2610    semantic_facts.iter().filter_map(|fact| {
2611        if let SemanticFact::ClassThisMemberAccess(access) = fact {
2612            Some(access)
2613        } else {
2614            None
2615        }
2616    })
2617}
2618
2619fn class_this_whole_object_use_facts(
2620    semantic_facts: &[SemanticFact],
2621) -> impl Iterator<Item = &ClassThisWholeObjectUseFact> {
2622    semantic_facts.iter().filter_map(|fact| {
2623        if let SemanticFact::ClassThisWholeObjectUse(access) = fact {
2624            Some(access)
2625        } else {
2626            None
2627        }
2628    })
2629}
2630
2631fn angular_component_field_array_type_facts(
2632    semantic_facts: &[SemanticFact],
2633) -> impl Iterator<Item = &AngularComponentFieldArrayTypeFact> {
2634    semantic_facts.iter().filter_map(|fact| {
2635        if let SemanticFact::AngularComponentFieldArrayType(access) = fact {
2636            Some(access)
2637        } else {
2638            None
2639        }
2640    })
2641}
2642
2643/// Iterate typed factory-call member facts.
2644fn factory_call_member_access_facts(
2645    semantic_facts: &[SemanticFact],
2646) -> impl Iterator<Item = &FactoryCallMemberAccessFact> {
2647    semantic_facts.iter().filter_map(|fact| {
2648        if let SemanticFact::FactoryCallMemberAccess(access) = fact {
2649            Some(access)
2650        } else {
2651            None
2652        }
2653    })
2654}
2655
2656/// Iterate typed free-function factory-return member facts.
2657fn factory_fn_member_access_facts(
2658    semantic_facts: &[SemanticFact],
2659) -> impl Iterator<Item = &FactoryFnMemberAccessFact> {
2660    semantic_facts.iter().filter_map(|fact| {
2661        if let SemanticFact::FactoryFnMemberAccess(access) = fact {
2662            Some(access)
2663        } else {
2664            None
2665        }
2666    })
2667}
2668
2669fn factory_fn_whole_object_facts(
2670    semantic_facts: &[SemanticFact],
2671) -> impl Iterator<Item = &FactoryFnWholeObjectFact> {
2672    semantic_facts.iter().filter_map(|fact| {
2673        if let SemanticFact::FactoryFnWholeObject(fact) = fact {
2674            Some(fact)
2675        } else {
2676            None
2677        }
2678    })
2679}
2680
2681/// Iterate object-literal factory-return property member facts.
2682fn factory_return_object_property_access_facts(
2683    semantic_facts: &[SemanticFact],
2684) -> impl Iterator<Item = &FactoryReturnObjectPropertyAccessFact> {
2685    semantic_facts.iter().filter_map(|fact| {
2686        if let SemanticFact::FactoryReturnObjectPropertyAccess(access) = fact {
2687            Some(access)
2688        } else {
2689            None
2690        }
2691    })
2692}
2693
2694/// Iterate typed fluent-chain member facts.
2695fn fluent_chain_member_access_facts(
2696    semantic_facts: &[SemanticFact],
2697) -> impl Iterator<Item = &FluentChainMemberAccessFact> {
2698    semantic_facts.iter().filter_map(|fact| {
2699        if let SemanticFact::FluentChainMemberAccess(access) = fact {
2700            Some(access)
2701        } else {
2702            None
2703        }
2704    })
2705}
2706
2707/// Iterate typed-property-hop member facts.
2708fn typed_property_member_access_facts(
2709    semantic_facts: &[SemanticFact],
2710) -> impl Iterator<Item = &TypedPropertyMemberAccessFact> {
2711    semantic_facts.iter().filter_map(|fact| {
2712        if let SemanticFact::TypedPropertyMemberAccess(access) = fact {
2713            Some(access)
2714        } else {
2715            None
2716        }
2717    })
2718}
2719
2720fn required_type_member_facts(
2721    semantic_facts: &[SemanticFact],
2722) -> impl Iterator<Item = &RequiredTypeMemberFact> {
2723    semantic_facts.iter().filter_map(|fact| {
2724        if let SemanticFact::RequiredTypeMember(required) = fact {
2725            Some(required)
2726        } else {
2727            None
2728        }
2729    })
2730}
2731
2732fn type_alias_surface_target_facts(
2733    semantic_facts: &[SemanticFact],
2734) -> impl Iterator<Item = &TypeAliasSurfaceTargetFact> {
2735    semantic_facts.iter().filter_map(|fact| {
2736        if let SemanticFact::TypeAliasSurfaceTarget(fact) = fact {
2737            Some(fact)
2738        } else {
2739            None
2740        }
2741    })
2742}
2743
2744fn string_enum_member_value_facts(
2745    semantic_facts: &[SemanticFact],
2746) -> impl Iterator<Item = &StringEnumMemberValueFact> {
2747    semantic_facts.iter().filter_map(|fact| {
2748        if let SemanticFact::StringEnumMemberValue(fact) = fact {
2749            Some(fact)
2750        } else {
2751            None
2752        }
2753    })
2754}
2755
2756fn computed_enum_key_use_facts(
2757    semantic_facts: &[SemanticFact],
2758) -> impl Iterator<Item = &ComputedEnumKeyUseFact> {
2759    semantic_facts.iter().filter_map(|fact| {
2760        if let SemanticFact::ComputedEnumKeyUse(fact) = fact {
2761            Some(fact)
2762        } else {
2763            None
2764        }
2765    })
2766}
2767
2768/// Iterate typed constructor-rooted fluent-chain member facts.
2769fn fluent_chain_new_member_access_facts(
2770    semantic_facts: &[SemanticFact],
2771) -> impl Iterator<Item = &FluentChainNewMemberAccessFact> {
2772    semantic_facts.iter().filter_map(|fact| {
2773        if let SemanticFact::FluentChainNewMemberAccess(access) = fact {
2774            Some(access)
2775        } else {
2776            None
2777        }
2778    })
2779}
2780
2781/// A member name referenced from an Angular template surface.
2782#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2783#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2784pub struct AngularTemplateMemberAccessFact {
2785    /// Referenced class member name.
2786    pub member: String,
2787}
2788
2789/// A typed Angular component field that exposes array elements to templates.
2790#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2791#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2792pub struct AngularComponentFieldArrayTypeFact {
2793    /// Component field name used as the template iterable.
2794    pub field: String,
2795    /// Array element class name.
2796    pub element_class: String,
2797}
2798
2799/// Opaque Angular `{ ...this }` forwarding marker.
2800#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2801#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2802pub struct AngularThisSpreadFact;
2803
2804/// A member access on a static factory call result.
2805#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2806#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2807pub struct FactoryCallMemberAccessFact {
2808    /// Local imported class or namespace object used as the factory callee.
2809    pub callee_object: String,
2810    /// Static factory method invoked on the callee object.
2811    pub callee_method: String,
2812    /// Member accessed on the returned instance-like object.
2813    pub member: String,
2814}
2815
2816/// A factory-returned value consumed opaquely, so every member of the class it
2817/// returns must be treated as used.
2818#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2819#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2820pub struct FactoryFnWholeObjectFact {
2821    /// Local imported function used as the factory callee.
2822    pub callee_name: String,
2823}
2824
2825/// A member access reached through a property of a value returned by an imported
2826/// factory that returns an object literal.
2827///
2828/// `const ui = createUi(); ui.orders.member` emits one fact per member read on a
2829/// factory-result property. The analyze layer resolves `callee_name` through the
2830/// consumer's imports to the factory's origin module, reads that module's
2831/// `exported_factory_return_object_shapes` to find the property whose path equals
2832/// `property_path` and its class local name, resolves THAT through the factory
2833/// module's own imports to the class export, and credits `member` on the class
2834/// (gated on the export actually being a class with members). See issue #1858.
2835#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2836#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2837pub struct FactoryReturnObjectPropertyAccessFact {
2838    /// Local imported function used as the factory callee.
2839    pub callee_name: String,
2840    /// Dotted property path between the factory-result local and the final member
2841    /// (e.g. `"orders"` for `ui.orders.member`, `"invoke.orders"` for `ui.invoke.orders.member`).
2842    pub property_path: String,
2843    /// Member accessed on the terminal property's instance.
2844    pub member: String,
2845}
2846
2847/// A member access reached through a typed property hop that the extraction
2848/// layer could not resolve locally.
2849///
2850/// `constructor(private opts: Opts) { ... this.opts.c.optM() }` where `Opts`
2851/// is NOT declared in this file emits
2852/// `TypedPropertyMemberAccessFact { type_name: "Opts", property_path: "c", member: "optM" }`.
2853/// The analyze layer resolves `type_name` through the consumer's imports to the
2854/// declaring module, walks `property_path` through that module's
2855/// `type_member_types`, resolves the terminal type name through the declaring
2856/// module's own imports, and credits `member` on the resolved class (gated on
2857/// the export actually being a class with members). See issue #1785.
2858#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2859#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2860pub struct TypedPropertyMemberAccessFact {
2861    /// Local (usually imported) named-type symbol the receiver is typed by.
2862    pub type_name: String,
2863    /// Remaining dotted property segments between the typed binding and the
2864    /// final member (e.g. `"c"` for `this.opts.c.optM()`).
2865    pub property_path: String,
2866    /// Member accessed on the terminal property's instance.
2867    pub member: String,
2868}
2869
2870/// A class member directly required by a named structural type.
2871///
2872/// Optional properties and methods are excluded: removing an optional
2873/// implementation can preserve assignability, while removing a required one
2874/// from an explicit `implements` contract cannot.
2875#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2876#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2877pub struct RequiredTypeMemberFact {
2878    /// Module-local interface or object-type alias name.
2879    pub type_name: String,
2880    /// Static required property or method name.
2881    pub member: String,
2882}
2883
2884/// One direct contributor to a named type alias's receiver surface.
2885///
2886/// Nested property types are deliberately excluded: in
2887/// `{ nested: Nested }`, `Alias.member` does not access `Nested.member`.
2888#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2889#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2890pub struct TypeAliasSurfaceTargetFact {
2891    /// Module-local alias declaration name.
2892    pub alias_name: String,
2893    /// Module-local or imported named type contributing the direct surface.
2894    pub target_name: String,
2895}
2896
2897/// A statically known string value of a TypeScript enum member.
2898#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2899#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2900pub struct StringEnumMemberValueFact {
2901    /// Module-local enum declaration name.
2902    pub enum_name: String,
2903    /// Static enum member name.
2904    pub member_name: String,
2905    /// Exact string initializer value.
2906    pub value: String,
2907}
2908
2909/// A computed property access whose key is a static enum member.
2910#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2911#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2912pub struct ComputedEnumKeyUseFact {
2913    /// Local enum object used as the key source.
2914    pub key_object: String,
2915    /// Static member selected from the enum object.
2916    pub key_member: String,
2917}
2918
2919/// A fluent chain rooted at a static factory call, one fact per chain. A step is
2920/// used when the root method is a factory and each earlier step returns `this`.
2921#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2922#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2923pub struct FluentChainMemberAccessFact {
2924    /// Local imported class or namespace object used as the chain root.
2925    pub root_object: String,
2926    /// Static factory method that starts the fluent chain.
2927    pub root_method: String,
2928    /// The methods called after the root method, each once, in first-call order.
2929    pub steps: Vec<String>,
2930}
2931
2932/// A fluent chain rooted at a `new` expression, one fact per chain. A step is
2933/// used when the first method and each earlier step return `this`.
2934#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2935#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2936pub struct FluentChainNewMemberAccessFact {
2937    /// Local imported class constructed by the `new` expression.
2938    pub class_name: String,
2939    /// The method called on the new instance.
2940    pub first_method: String,
2941    /// The methods called after the first method, each once, in first-call order.
2942    pub steps: Vec<String>,
2943}
2944
2945/// A member access on a Playwright fixture object inside a test callback.
2946#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2947#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2948pub struct PlaywrightFixtureUseFact {
2949    /// Local test function or wrapper used as the callback callee.
2950    pub test_name: String,
2951    /// Fixture name or dotted fixture path referenced in the callback.
2952    pub fixture_name: String,
2953    /// Member accessed on the fixture target.
2954    pub member: String,
2955}
2956
2957/// A Playwright fixture definition declared by a typed `test.extend<T>()`.
2958#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2959#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2960pub struct PlaywrightFixtureDefinitionFact {
2961    /// Local test function or wrapper receiving the fixture definition.
2962    pub test_name: String,
2963    /// Fixture name or dotted fixture path declared by the fixture type.
2964    pub fixture_name: String,
2965    /// Local type symbol used as the fixture target.
2966    pub type_name: String,
2967}
2968
2969/// A Playwright fixture definition from `<base>.extend<T>()` where `base` is
2970/// an imported name. The extractor cannot prove that `base` holds a Playwright
2971/// test, so analysis applies the definition only when `base` resolves to one.
2972#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2973#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2974pub struct PlaywrightConditionalFixtureDefinitionFact {
2975    /// Local test function or wrapper receiving the fixture definition.
2976    pub test_name: String,
2977    /// Imported local name that `.extend<T>()` is called on.
2978    pub base_name: String,
2979    /// Fixture name or dotted fixture path declared by the fixture type.
2980    pub fixture_name: String,
2981    /// Local type symbol used as the fixture target.
2982    pub type_name: String,
2983}
2984
2985/// A local name that holds a Playwright test: the result of an `.extend()` on
2986/// the `@playwright/test` `test` import or of a `mergeTests(...)` call.
2987#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2988#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2989pub struct PlaywrightTestBindingFact {
2990    /// Local name of the Playwright test.
2991    pub test_name: String,
2992}
2993
2994/// A Playwright fixture wrapper alias declared by `mergeTests` or `.extend`.
2995#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
2996#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
2997pub struct PlaywrightFixtureAliasFact {
2998    /// Local test function or wrapper that inherits fixture definitions.
2999    pub test_name: String,
3000    /// Local test function or wrapper inherited by `test_name`.
3001    pub base_name: String,
3002}
3003
3004/// A nested Playwright fixture binding declared by a fixture type alias.
3005#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
3006#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3007pub struct PlaywrightFixtureTypeFact {
3008    /// Local type alias containing the nested fixture binding.
3009    pub alias_name: String,
3010    /// Fixture name or dotted fixture path declared inside the type alias.
3011    pub fixture_name: String,
3012    /// Local type symbol used as the nested fixture target.
3013    pub type_name: String,
3014}
3015
3016/// An exported value whose runtime instance targets a local class or interface.
3017#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
3018#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3019pub struct InstanceExportBindingFact {
3020    /// Exported binding name.
3021    pub export_name: String,
3022    /// Local class or interface symbol used as the instance target.
3023    pub target_name: String,
3024}
3025
3026/// A property of an exported object whose value is an instance of a local class.
3027#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
3028#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3029pub struct ExportedObjectInstancePropertyFact {
3030    /// Public export name of the containing object.
3031    pub export_name: String,
3032    /// Dotted path from the exported object to the instance property.
3033    pub property_path: String,
3034    /// Local class symbol instantiated at that property.
3035    pub class_local_name: String,
3036}
3037
3038/// A proven class member read through a namespace-qualified constructor or local subclass.
3039#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
3040#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3041pub struct QualifiedClassMemberAccessFact {
3042    /// Local namespace-import binding.
3043    pub namespace_local: String,
3044    /// Class export selected from that namespace.
3045    pub class_export_name: String,
3046    /// Member accessed through the proven class or instance binding.
3047    pub member: String,
3048}
3049
3050/// Opaque marker for a dynamic custom-element render site.
3051#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
3052#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3053pub struct DynamicCustomElementRenderFact;
3054
3055/// The action performed by a Vitest module-mock operation.
3056#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
3057#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3058#[serde(rename_all = "snake_case")]
3059pub enum VitestModuleMockAction {
3060    /// Register a mock. `factory_replaces_original` is true only when the
3061    /// factory is structurally closed and cannot load the original module.
3062    ///
3063    /// Automock (`vi.mock` / `jest.mock` without a factory) is always
3064    /// `factory_replaces_original: false` by decision (issue #2082). For
3065    /// Vitest, the runner derives the mocked shape by importing the original
3066    /// module, so its top-level code executes at collection time, and
3067    /// file-level masking cannot express "module evaluated but exports
3068    /// stubbed". For Jest, a `__mocks__` sibling takes precedence and the
3069    /// original is genuinely not required, but the manual mock itself may
3070    /// load the original (`jest.requireActual`), and proving it never does
3071    /// would need a cross-file factory proof. Both runners therefore keep
3072    /// coverage credit for the automock form.
3073    Mock {
3074        /// Whether the factory provably replaces the original module.
3075        factory_replaces_original: bool,
3076    },
3077    /// Remove a registered mock and restore the original module.
3078    Unmock,
3079}
3080
3081impl VitestModuleMockAction {
3082    /// Whether this operation registers a proven complete replacement.
3083    #[must_use]
3084    pub const fn replaces_original(self) -> bool {
3085        matches!(
3086            self,
3087            Self::Mock {
3088                factory_replaces_original: true
3089            }
3090        )
3091    }
3092}
3093
3094/// Ordered Vitest module-mock operation with a static source target.
3095///
3096/// The declaring [`ModuleInfo::file_id`] owns the test-root provenance. The
3097/// resolver consumes `source` through its canonical specifier pipeline; this
3098/// fact deliberately carries no resolved path or duplicate diagnostic span.
3099#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
3100#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3101pub struct VitestModuleMockOperationFact {
3102    /// Static module specifier passed to `vi.mock` or `vi.unmock`.
3103    pub source: String,
3104    /// Source-order position of the call within the declaring module.
3105    pub call_start: u32,
3106    /// Typed mock or unmock action.
3107    pub action: VitestModuleMockAction,
3108}
3109
3110/// A `this`-rooted member access with exact enclosing-class provenance.
3111#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
3112#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3113pub struct ClassThisMemberAccessFact {
3114    /// Enclosing class local name, or `default` for an anonymous default class.
3115    pub class_local_name: String,
3116    /// Dotted receiver spelling beginning with `this.`.
3117    pub object: String,
3118    /// Terminal member being accessed.
3119    pub member: String,
3120}
3121
3122/// A whole-object use of a `this`-rooted chain with enclosing-class provenance.
3123#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, bitcode::Encode, bitcode::Decode)]
3124#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
3125pub struct ClassThisWholeObjectUseFact {
3126    /// Enclosing class local name, or `default` for an anonymous default class.
3127    pub class_local_name: String,
3128    /// Dotted receiver spelling beginning with `this.`.
3129    pub object: String,
3130}
3131
3132/// A `"use client"` / `"use server"` directive string written as an expression
3133/// statement in `program.body` (NOT the leading prologue), so the RSC bundler
3134/// silently ignores it. One entry per offending occurrence. Consumed by the
3135/// `misplaced-directive` detector.
3136#[derive(Debug, Clone, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
3137pub struct MisplacedDirectiveSite {
3138    /// `true` for `"use server"`, `false` for `"use client"`.
3139    pub is_server: bool,
3140    /// Start byte offset of the misplaced directive statement.
3141    pub span_start: u32,
3142}
3143
3144/// Which side of a dependency-injection link a call site represents.
3145#[derive(Debug, Clone, Copy, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
3146pub enum DiRole {
3147    /// `provide(KEY, value)` / `app.provide(KEY, value)` / `setContext(KEY, value)`.
3148    Provide,
3149    /// `inject(KEY)` / `getContext(KEY)`.
3150    Inject,
3151}
3152
3153/// Which framework's DI API a call site came from (drives the finding message).
3154#[derive(Debug, Clone, Copy, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
3155pub enum DiFramework {
3156    /// Vue `provide` / `inject` (from `vue` / `@vue/runtime-core`).
3157    Vue,
3158    /// Svelte `setContext` / `getContext` (from `svelte`).
3159    Svelte,
3160    /// Angular `inject(TOKEN)` / `@Inject(TOKEN)` (from `@angular/core`),
3161    /// matched against `{ provide: TOKEN, ... }` provider objects.
3162    Angular,
3163}
3164
3165/// A Vue `provide`/`inject` or Svelte `setContext`/`getContext` call site keyed
3166/// by an identifier symbol. The `key_local` is resolved at analyze time through
3167/// the consuming module's import/export tables to a canonical defining-site
3168/// export key, so a provide and an inject of the same shared symbol unify even
3169/// across barrel re-exports. Consumed by the `unprovided-inject` detector.
3170#[derive(Debug, Clone, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
3171pub struct DiKeySite {
3172    /// The key identifier as written at the call site.
3173    pub key_local: String,
3174    /// Whether this is a provide or an inject.
3175    pub role: DiRole,
3176    /// Which framework's API this came from.
3177    pub framework: DiFramework,
3178    /// Start byte offset of the call expression (anchors the finding).
3179    pub span_start: u32,
3180}
3181
3182/// A component prop declared by Vue `<script setup>` `defineProps` or Svelte 5
3183/// `$props()`. `used_in_script` / `used_in_template` are set during extraction;
3184/// the `unused-component-prop` detector flags a prop where neither is true. See
3185/// `harvest_define_props` and `harvest_svelte_props` in `sfc_props.rs`.
3186#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode)]
3187pub struct ComponentProp {
3188    /// The declared prop name.
3189    pub name: String,
3190    /// The template/script-visible local binding name: the destructure alias for
3191    /// `const { name: alias } = defineProps()` or
3192    /// `let { name: alias } = $props()`, otherwise the prop name itself. A
3193    /// renamed prop is read through this local, so usage must be checked against
3194    /// it, not the declared name.
3195    pub local: String,
3196    /// Start byte offset of the prop declaration (anchors the finding).
3197    pub span_start: u32,
3198    /// Whether this prop is referenced in the component's `<script>` (a
3199    /// destructured local binding with a resolved reference, or a `props.<name>`
3200    /// member access). For React, this is set-in-body: a resolved reference to the
3201    /// destructured local anywhere in the component function body.
3202    pub used_in_script: bool,
3203    /// Whether this prop name is referenced in the component's `<template>`.
3204    /// Set by `apply_template_usage` when the template scanner credits the name.
3205    /// Always false for React (no template; React uses `used_in_script`).
3206    pub used_in_template: bool,
3207    /// The enclosing component name. Empty for Vue SFCs (one component per file,
3208    /// the file stem is the component, set by the detector). For React this is the
3209    /// component function/arrow name a prop was declared on, so the detector can
3210    /// emit the right `component_name` and apply the per-component abstain ladder
3211    /// (a file can declare several React components).
3212    pub component: String,
3213    /// React-only: `true` when the destructured prop local is referenced at least
3214    /// once OUTSIDE a child-JSX attribute value expression (a substantive
3215    /// consumption: a hook arg, a host-element child, a non-JSX-attr read). When
3216    /// `used_in_script` is true but this is false, the prop is referenced ONLY as
3217    /// the root of forwarded child attribute values, i.e. a pure pass-through.
3218    /// Always `false` for Vue (no forward-vs-consume distinction is computed).
3219    pub used_outside_forward: bool,
3220}
3221
3222/// A Vue `<script setup>` `defineEmits` declared event, harvested from the type
3223/// tuple-call form (`defineEmits<{ (e: 'foo'): void }>()`), the type object form
3224/// (`defineEmits<{ foo: [x: string] }>()`), or the runtime array form
3225/// (`defineEmits(['foo'])`). `used` is set during extraction when the bound emit
3226/// name is called as `emit('<name>')`. The `unused-component-emit` detector flags
3227/// an event where `used` is false. See `harvest_define_emits` in `sfc_props.rs`.
3228#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode, PartialEq, Eq)]
3229pub struct ComponentEmit {
3230    /// The declared emit event name.
3231    pub name: String,
3232    /// Start byte offset of the emit declaration (anchors the finding).
3233    pub span_start: u32,
3234    /// Whether this event is emitted via `emit('<name>')` somewhere in the
3235    /// component's `<script>`.
3236    pub used: bool,
3237}
3238
3239/// A Svelte custom event dispatched via `dispatch('<name>')`, where `dispatch`
3240/// is the binding from a `const dispatch = createEventDispatcher()` call. Only
3241/// literal-first-arg dispatches are recorded; a `dispatch(<nonLiteral>)` sets
3242/// `ModuleInfo::has_dynamic_dispatch` instead. Consumed by the
3243/// `unused-svelte-event` detector, which flags an event dispatched here but
3244/// listened to nowhere project-wide (the cross-file dead-output direction). The
3245/// span is a byte offset (not an `oxc_span::Span`) so the type round-trips
3246/// through the bitcode cache directly, mirroring `ComponentEmit::span_start`.
3247#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode, PartialEq, Eq)]
3248pub struct DispatchedEvent {
3249    /// The dispatched event name (the literal first argument).
3250    pub name: String,
3251    /// Start byte offset of the `dispatch(...)` call (anchors the finding).
3252    pub span_start: u32,
3253}
3254
3255/// A declared Angular component/directive input, harvested from an `@Input()`
3256/// decorator or a signal `input()` / `input.required()` / `model()` initializer
3257/// on an Angular-decorated class. Consumed by the `unused-component-input`
3258/// detector, which flags an input read nowhere in its own component (neither the
3259/// template nor the class body). The span is stored as a byte offset (not an
3260/// `oxc_span::Span`) so the type is cheap to mirror onto the cache, matching
3261/// `ComponentEmit::span_start`. `ModuleInfo` is not serialized, so no serde
3262/// attrs are derived here. `bitcode` derives let the type be mirrored directly
3263/// onto `CachedModule` (the same pattern as `ComponentEmit`).
3264#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode, PartialEq, Eq)]
3265pub struct AngularInputMember {
3266    /// The declared input name (the property key).
3267    pub name: String,
3268    /// Start byte offset of the property key (anchors the finding).
3269    pub span_start: u32,
3270}
3271
3272/// A declared Angular component/directive output, harvested from an `@Output()`
3273/// decorator or a signal `output()` / `outputFromObservable()` initializer on an
3274/// Angular-decorated class. Consumed by the `unused-component-output` detector,
3275/// which flags an output emitted nowhere in its own component. A `model()` is an
3276/// input and a framework-driven output, so it is recorded ONLY as an input and
3277/// never appears here (the implicit `update:` emit is framework-managed). The
3278/// span is a byte offset for the same reason as `AngularInputMember`.
3279#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode, PartialEq, Eq)]
3280pub struct AngularOutputMember {
3281    /// The declared output name (the property key).
3282    pub name: String,
3283    /// Start byte offset of the property key (anchors the finding).
3284    pub span_start: u32,
3285}
3286
3287/// A declared Angular `@Component` and its `selector` value(s), harvested from a
3288/// `@Component({ selector: '...' })` decorator. Consumed by the Angular arm of
3289/// the `unrendered-component` detector, which flags a component whose every
3290/// element selector is used in NO template project-wide (and that is not
3291/// referenced by class name anywhere, e.g. routed / bootstrapped / dynamically
3292/// rendered). A multi-selector string (`'app-foo, [appBar]'`) is split into the
3293/// `selectors` list. The span is stored as a byte offset (not an
3294/// `oxc_span::Span`) so the type round-trips through the bitcode cache directly,
3295/// mirroring `AngularInputMember::span_start`. `@Directive` is intentionally NOT
3296/// harvested here (directives have no template render). `ModuleInfo` is not
3297/// serialized, so no serde attrs are derived.
3298#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode, PartialEq, Eq)]
3299pub struct AngularComponentSelector {
3300    /// The declared selector strings for this component, split on `,`. A purely
3301    /// element-selector component has only `app-foo`-shaped entries; attribute
3302    /// (`[appFoo]`) and class (`.foo`) selectors are retained verbatim so the
3303    /// detector can abstain when ANY non-element selector is present.
3304    pub selectors: Vec<String>,
3305    /// Start byte offset of the component class declaration (anchors the
3306    /// finding).
3307    pub span_start: u32,
3308    /// The component class name (used to credit routed / bootstrapped / dynamic
3309    /// class-name references project-wide).
3310    pub class_name: String,
3311}
3312
3313/// A Lit / web-component custom element registered in a module via
3314/// `@customElement('x-foo')` or `customElements.define('x-foo', C)`. Consumed by
3315/// the Lit arm of the `unrendered-component` detector. The span is stored as a
3316/// byte offset (not an `oxc_span::Span`) so the type round-trips through the
3317/// bitcode cache directly, mirroring `AngularComponentSelector::span_start`.
3318#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode, PartialEq, Eq)]
3319pub struct RegisteredCustomElement {
3320    /// The registered custom-element tag name (`x-foo`).
3321    pub tag: String,
3322    /// The registering class's local name, used for the public-API / export
3323    /// abstain (an exported / published element is rendered by a downstream
3324    /// consumer the scan cannot see). Empty for an anonymous
3325    /// `export default @customElement('x-foo') class extends LitElement {}`.
3326    pub class_local_name: String,
3327    /// Start byte offset of the registering class declaration (anchors the
3328    /// finding at the element, NOT line 1, since a `.ts` file can register
3329    /// several custom elements).
3330    pub span_start: u32,
3331}
3332
3333/// A key returned from a SvelteKit route `load()` function's terminal return
3334/// object literal. Harvested from `+page.{ts,server.ts,js,server.js}` files
3335/// exporting a `load` function. Consumed by the `unused-load-data-key` detector,
3336/// which flags a key read by no consumer. The span is stored as byte offsets
3337/// (not an `oxc_span::Span`) so the type round-trips through the bitcode cache
3338/// directly, mirroring `DiKeySite::span_start` / `ComponentEmit::span_start`.
3339#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode, PartialEq, Eq)]
3340pub struct LoadReturnKey {
3341    /// The returned-object property key name.
3342    pub name: String,
3343    /// Start byte offset of the key (anchors the finding).
3344    pub span_start: u32,
3345    /// End byte offset of the key.
3346    pub span_end: u32,
3347}
3348
3349/// The syntactic shape of an identified React component definition. Drives the
3350/// abstain ladder later phases apply: a `forwardRef` / `memo` wrapper whose
3351/// props come from an imported interface fallow cannot resolve must abstain
3352/// (ADR-001), not guess.
3353#[derive(Debug, Clone, Copy, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
3354pub enum ComponentFunctionKind {
3355    /// A `function Foo() { return <.../> }` declaration.
3356    FnDecl,
3357    /// A `const Foo = () => <.../>` arrow (or function-expression) binding.
3358    Arrow,
3359    /// A `const Foo = forwardRef((props, ref) => <.../>)` wrapper.
3360    ForwardRefWrapper,
3361    /// A `const Foo = memo((props) => <.../>)` wrapper.
3362    MemoWrapper,
3363}
3364
3365/// An identified React component: a function/arrow whose body returns JSX.
3366/// Captured by `visit_jsx_element`'s enclosing-component tracking. The
3367/// `unused-component-prop` (React arm) and complexity-fold phases consume this;
3368/// the abstain flags keep zero-FP on the cases ADR-001 cannot resolve.
3369#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode)]
3370pub struct ComponentFunction {
3371    /// The component name (the binding or declaration identifier).
3372    pub name: String,
3373    /// Start byte offset of the component definition (anchors findings).
3374    pub span_start: u32,
3375    /// The syntactic shape of the definition.
3376    pub kind: ComponentFunctionKind,
3377    /// Whether the component is exported from its module (a named export, a
3378    /// `export default`, or re-exported in the same module). Public-API
3379    /// components abstain in the prop phase.
3380    pub is_exported: bool,
3381    /// `true` when the component's props are not statically harvestable: a
3382    /// rest/spread in the signature (`{ ...rest }`), props passed wholesale to a
3383    /// hook/helper, or a `forwardRef` / `memo` wrapper whose props come from an
3384    /// imported interface generic fallow cannot resolve (ADR-001). The prop
3385    /// phase abstains on the whole component when set.
3386    pub has_unharvestable_props: bool,
3387    /// `true` when the component body calls `cloneElement` / `React.cloneElement`.
3388    /// `cloneElement` injects props by reflection, so the static forward-set is
3389    /// incomplete; the prop-drilling phase abstains on any chain through this
3390    /// component (ADR-001, zero-FP).
3391    pub uses_clone_element: bool,
3392    /// `true` when the component renders a `*.Provider` member-expression tag
3393    /// (`<FooContext.Provider>`). A context provider in the subtree means the
3394    /// drilling may be a deliberate non-context choice (or the prop is about to
3395    /// be provided); the prop-drilling phase downgrades/abstains.
3396    pub renders_provider: bool,
3397    /// `true` when the component passes a function as a child render value
3398    /// (render-props / children-as-function: `<Foo>{() => ...}</Foo>` or
3399    /// `<Foo render={() => ...}/>`). The forwarded shape is dynamic; the
3400    /// prop-drilling phase abstains on chains through this component.
3401    pub has_children_as_function: bool,
3402    /// `true` when the component body is pure structural indirection: a single
3403    /// statement returning exactly one capitalized/member-expression JSX element
3404    /// (no host wrapper, no extra children, optionally a fragment wrapping a
3405    /// single element) that forwards props via a bare spread of the component's
3406    /// own props binding / rest local (`<Child {...props}/>`), with NO named
3407    /// attributes alongside the spread and NO self-render. The cross-component
3408    /// `thin-wrapper` phase joins this with hook-density / cyclomatic checks and
3409    /// the resolved single render edge to flag a component that is a candidate
3410    /// for inlining. Computed from the component's own AST only, so it caches
3411    /// byte-identity-safe (ADR-001).
3412    pub is_pure_passthrough: bool,
3413}
3414
3415/// The kind of a React hook call. `Custom` covers any `use*`-named call that is
3416/// not one of the built-in hooks.
3417#[derive(Debug, Clone, Copy, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
3418pub enum HookUseKind {
3419    /// `useState(...)`.
3420    UseState,
3421    /// `useEffect(...)`.
3422    UseEffect,
3423    /// `useMemo(...)`.
3424    UseMemo,
3425    /// `useCallback(...)`.
3426    UseCallback,
3427    /// Any other `use*`-named call (a custom hook).
3428    Custom,
3429}
3430
3431/// A React hook call site inside a component. Consumed by the complexity-fold
3432/// phase (hook density) and surfaced as descriptive hotspot context.
3433#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode)]
3434pub struct HookUse {
3435    /// The hook kind.
3436    pub kind: HookUseKind,
3437    /// The dependency-array arity, recorded ONLY when a literal array is present
3438    /// at the dependency-array position (`[a, b]` -> `Some(2)`, `[]` ->
3439    /// `Some(0)`). `None` when the call has no dependency array argument or the
3440    /// argument is not a literal array (ADR-001: do not guess).
3441    pub dep_array_arity: Option<u32>,
3442    /// Start byte offset of the hook call (anchors findings).
3443    pub span_start: u32,
3444    /// The enclosing component name (the top of the visitor's component stack
3445    /// when the hook call was recorded). Lets the descriptive per-component hook
3446    /// summary attribute hooks exactly even when a file declares several
3447    /// components. A hook recorded outside any component carries an empty string
3448    /// (the visitor only records hooks inside a component, so this is the
3449    /// rare top-level / unattributed case).
3450    pub component: String,
3451}
3452
3453/// A render edge: one component rendering another (a capitalized or
3454/// member-expression JSX tag). Captured at extraction time with the child's
3455/// written name; resolution of `child_component_name` to a `FileId`/export is
3456/// deferred to graph build via the existing import map.
3457#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode)]
3458pub struct RenderEdge {
3459    /// The name of the component that renders the child (the enclosing
3460    /// component). Empty when the JSX is not inside an identified component (a
3461    /// top-level render expression).
3462    pub parent_component: String,
3463    /// The rendered child component name as written (`Foo` or the full
3464    /// member-expression path `Foo.Bar`).
3465    pub child_component_name: String,
3466    /// The attribute (prop) names passed at the render site, in source order.
3467    pub attr_names: Vec<String>,
3468    /// `true` when the render site contains a JSX spread (`{...x}`), so the
3469    /// passed-prop set is not statically complete.
3470    pub has_spread: bool,
3471    /// The forwarded attributes at this render site: each pairs the child
3472    /// attribute NAME with the identifier ROOT of its value expression
3473    /// (`userName={user.name}` -> `{ attr: "userName", root: "user" }`;
3474    /// `value={x}` -> `{ attr: "value", root: "x" }`). ONLY plain identifier or
3475    /// member-root access values are recorded (`{x}`, `{x.y}`, `{x.y.z}`); a value
3476    /// that is a call, an arrow/function, a conditional, a JSX element, or any
3477    /// other complex expression is NOT recorded here (its root would not be a pure
3478    /// forward) and sets `has_complex_forward` instead. The prop-drilling chain
3479    /// walk uses this pairing to map "this component forwards prop P" to "the
3480    /// child receives it as attribute A".
3481    pub forward_attrs: Vec<ForwardAttr>,
3482    /// `true` when at least one attribute value at this render site is a complex
3483    /// expression (a call, an arrow/function render-prop, a conditional, a JSX
3484    /// element-as-prop, a template literal, etc.) whose identifier root was NOT
3485    /// recorded in `forward_attrs`. The prop-drilling phase abstains on a chain
3486    /// whose forwarded prop flows through such a value (ADR-001, zero-FP).
3487    pub has_complex_forward: bool,
3488}
3489
3490/// One forwarded JSX attribute: the child attribute name plus the identifier
3491/// root of its value expression. See [`RenderEdge::forward_attrs`].
3492#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode)]
3493pub struct ForwardAttr {
3494    /// The child attribute (prop) name as written (`userName`).
3495    pub attr: String,
3496    /// The identifier root of the attribute value expression (`user` for
3497    /// `userName={user.name}`).
3498    pub root: String,
3499}
3500
3501#[expect(
3502    clippy::trivially_copy_pass_by_ref,
3503    reason = "serde serialize_with requires &T"
3504)]
3505fn serialize_span<S: serde::Serializer>(span: &Span, serializer: S) -> Result<S::Ok, S::Error> {
3506    use serde::ser::SerializeMap;
3507    let mut map = serializer.serialize_map(Some(2))?;
3508    map.serialize_entry("start", &span.start)?;
3509    map.serialize_entry("end", &span.end)?;
3510    map.end()
3511}
3512
3513/// Export identifier.
3514#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
3515pub enum ExportName {
3516    /// A named export (e.g., `export const foo`).
3517    Named(String),
3518    /// The default export.
3519    Default,
3520}
3521
3522impl ExportName {
3523    /// Compare against a string without allocating (avoids `to_string()`).
3524    #[must_use]
3525    pub fn matches_str(&self, s: &str) -> bool {
3526        match self {
3527            Self::Named(n) => n == s,
3528            Self::Default => s == "default",
3529        }
3530    }
3531}
3532
3533impl std::fmt::Display for ExportName {
3534    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3535        match self {
3536            Self::Named(n) => write!(f, "{n}"),
3537            Self::Default => write!(f, "default"),
3538        }
3539    }
3540}
3541
3542/// An import declaration.
3543#[derive(Debug, Clone)]
3544pub struct ImportInfo {
3545    /// The import specifier (e.g., `./utils` or `react`).
3546    pub source: String,
3547    /// How the symbol is imported (named, default, namespace, or side-effect).
3548    pub imported_name: ImportedName,
3549    /// The local binding name in the importing module.
3550    pub local_name: String,
3551    /// Whether this is a type-only import (`import type`).
3552    pub is_type_only: bool,
3553    /// Whether this whole-module import forwards type meanings only.
3554    ///
3555    /// Set for `export type *` and `export type * as ns` inside a
3556    /// `declare module '...'` body (issue #2375). Those forms record the same
3557    /// bindingless whole-module shape the plain ambient star records
3558    /// (issue #2357), but the star they stand for erases every value meaning,
3559    /// so the graph credits the target's star surface in the type namespace
3560    /// alone. Every other import leaves this false: `is_type_only` already
3561    /// decides their namespace on its own.
3562    pub is_type_only_star: bool,
3563    /// Whether this import originated from a CSS-context.
3564    pub from_style: bool,
3565    /// Source span of the import declaration.
3566    pub span: Span,
3567    /// Span of the source string literal used by the LSP to highlight the specifier.
3568    pub source_span: Span,
3569}
3570
3571/// How a symbol is imported.
3572#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
3573pub enum ImportedName {
3574    /// A named import (e.g., `import { foo }`).
3575    Named(String),
3576    /// A default import (e.g., `import React`).
3577    Default,
3578    /// A namespace import (e.g., `import * as utils`).
3579    Namespace,
3580    /// A side-effect import (e.g., `import './styles.css'`).
3581    SideEffect,
3582}
3583
3584#[cfg(target_pointer_width = "64")]
3585const _: () = assert!(std::mem::size_of::<ExportInfo>() == 152);
3586#[cfg(target_pointer_width = "64")]
3587const _: () = assert!(std::mem::size_of::<ImportInfo>() == 96);
3588#[cfg(target_pointer_width = "64")]
3589const _: () = assert!(std::mem::size_of::<ExportName>() == 24);
3590#[cfg(target_pointer_width = "64")]
3591const _: () = assert!(std::mem::size_of::<ImportedName>() == 24);
3592#[cfg(target_pointer_width = "64")]
3593const _: () = assert!(std::mem::size_of::<MemberAccess>() == 48);
3594#[cfg(target_pointer_width = "64")]
3595const _: () = assert!(std::mem::size_of::<SemanticFact>() == 80);
3596#[cfg(target_pointer_width = "64")]
3597const _: () = assert!(std::mem::size_of::<SinkSite>() == 224);
3598#[cfg(target_pointer_width = "64")]
3599const _: () = assert!(std::mem::size_of::<ModuleInfo>() == 1504);
3600#[cfg(target_pointer_width = "64")]
3601const _: () = assert!(std::mem::size_of::<ImportBindingReference>() == 64);
3602#[cfg(target_pointer_width = "64")]
3603const _: () = assert!(std::mem::size_of::<TypeMemberTypeEntry>() == 72);
3604
3605#[path = "extract_re_export.rs"]
3606mod re_export;
3607pub use re_export::ReExportInfo;
3608
3609/// A dynamic `import()` call.
3610#[derive(Debug, Clone)]
3611pub struct DynamicImportInfo {
3612    /// The import specifier.
3613    pub source: String,
3614    /// Source span of the `import()` expression.
3615    pub span: Span,
3616    /// Names destructured from the dynamic import result.
3617    /// Non-empty means `const { a, b } = await import(...)` -> Named imports.
3618    /// Empty means simple `import(...)` or `const x = await import(...)` -> Namespace.
3619    pub destructured_names: Vec<String>,
3620    /// The local variable name for `const x = await import(...)`.
3621    /// Used for namespace import narrowing via member access tracking.
3622    pub local_name: Option<String>,
3623    /// True when this dynamic import was synthesised by fallow rather than appearing in user source.
3624    pub is_speculative: bool,
3625    /// True when the value of an `import()` without a binding escapes, for
3626    /// example as a return value, a call argument, or an array element.
3627    /// The consumer can then read any export, so the edge credits the whole
3628    /// module namespace. False for a discarded `import()` statement, which
3629    /// only loads the module.
3630    pub value_escapes: bool,
3631}
3632
3633/// A `require()` call.
3634#[derive(Debug, Clone)]
3635pub struct RequireCallInfo {
3636    /// The require specifier.
3637    pub source: String,
3638    /// Source span of the `require()` call.
3639    pub span: Span,
3640    /// Span of the string-literal argument with quotes (`'./x'`), which anchors an
3641    /// `unresolved-import` diagnostic. `Span::default()` for a non-literal argument.
3642    pub source_span: Span,
3643    /// Names destructured from the `require()` result.
3644    pub destructured_names: Vec<String>,
3645    /// The `(key, local)` pair of each destructured identifier property:
3646    /// `const { exec: run } = require(...)` gives `("exec", "run")`.
3647    pub destructured_locals: Vec<(String, String)>,
3648    /// The local variable name for `const x = require(...)`.
3649    pub local_name: Option<String>,
3650    /// `true` for `import type X = require('...')`, the one require spelling
3651    /// TypeScript erases entirely: the emitted JavaScript contains no
3652    /// `require` call, so the target is a type-space reference and never a
3653    /// runtime dependency. Always `false` for `const x = require(...)`, which
3654    /// has no type-only spelling. Read by dependency classification so a
3655    /// type-only devDependency is not reported as production usage.
3656    pub is_type_only: bool,
3657}
3658
3659/// Result of parsing all files, including incremental cache statistics.
3660pub struct ParseResult {
3661    /// Extracted module information for all successfully parsed files.
3662    pub modules: Vec<ModuleInfo>,
3663    /// Files discovered with stable IDs but unreadable by the parser.
3664    pub read_failures: Vec<SourceReadFailure>,
3665    /// Files that parsed with diagnostics, so their extracted module may be
3666    /// incomplete. Reported, never used to withhold findings.
3667    pub parse_degradations: Vec<SourceParseDegradation>,
3668    /// Number of files whose parse results were loaded from cache (unchanged).
3669    pub cache_hits: usize,
3670    /// Number of files that required a full parse (new or changed).
3671    pub cache_misses: usize,
3672    /// Summed wall-clock time of the actual AST parses across all rayon workers.
3673    pub parse_cpu_ms: f64,
3674    /// Files whose bytes were read from disk: every parse, plus every cache
3675    /// hit that had to compare the content hash.
3676    pub files_read: u64,
3677    /// Bytes of source read from disk across all files.
3678    pub source_bytes_read: u64,
3679    /// Source bytes that the CSS comment mask read across all parsed files.
3680    pub css_masked_bytes: u64,
3681}
3682
3683/// A discovered source that could not be read as UTF-8 text.
3684#[derive(Debug, Clone, PartialEq, Eq)]
3685pub struct SourceReadFailure {
3686    /// Stable discovery identity retained even though no module was produced.
3687    pub file_id: FileId,
3688    /// Absolute discovered source path.
3689    pub path: PathBuf,
3690    /// Underlying filesystem or UTF-8 decoding error.
3691    pub error: String,
3692}
3693
3694/// A discovered source that was read but did not parse cleanly.
3695///
3696/// The module it produced is still analyzed: dropping it would turn one broken
3697/// file into project-wide silence. The point of carrying the degradation is
3698/// that the imports the file failed to parse credited nothing, so its targets
3699/// can be reported as unused with full confidence unless a consumer is told the
3700/// parse was partial.
3701#[derive(Debug, Clone, PartialEq, Eq)]
3702pub struct SourceParseDegradation {
3703    /// Stable discovery identity of the degraded source.
3704    pub file_id: FileId,
3705    /// Absolute discovered source path.
3706    pub path: PathBuf,
3707    /// Number of parser diagnostics reported for the file.
3708    pub error_count: u32,
3709    /// `true` when the parser abandoned the file instead of recovering.
3710    pub panicked: bool,
3711    /// The nesting cap when the file nests too deep to parse.
3712    pub nesting_limit: Option<u32>,
3713}
3714
3715#[path = "extract_effect.rs"]
3716mod effect;
3717pub use effect::*;
3718#[path = "extract_calls.rs"]
3719mod calls;
3720pub use calls::*;
3721#[path = "extract_function_contracts.rs"]
3722mod function_contracts;
3723pub use function_contracts::*;
3724#[path = "extract_factory.rs"]
3725mod factory;
3726pub use factory::*;
3727#[path = "extract_component_contracts.rs"]
3728mod component_contracts;
3729pub use component_contracts::*;
3730
3731#[cfg(test)]
3732#[path = "extract_tests.rs"]
3733mod tests;