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