fallow-graph 2.88.0

Module graph construction and import resolution for fallow codebase intelligence
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
//! Import specifier resolution using `oxc_resolver`.
//!
//! Orchestrates the resolution pipeline: for every extracted module, resolves all
//! import specifiers in parallel (via rayon) to an [`ResolveResult`] — internal file,
//! npm package, external file, or unresolvable. The entry point is [`resolve_all_imports`].
//!
//! Resolution is split into submodules by import kind:
//! - `static_imports` — ES `import` declarations
//! - `dynamic_imports` — `import()` expressions and glob-based dynamic patterns
//! - `require_imports` — CommonJS `require()` calls
//! - `re_exports` — `export { x } from './y'` re-export sources
//! - `upgrades` — post-resolution pass fixing non-deterministic bare specifier results
//!
//! Handles tsconfig path aliases (auto-discovered per file), pnpm virtual store paths,
//! React Native platform extensions, and package.json `exports` subpath resolution with
//! output-to-source directory fallback.

mod dynamic_imports;
pub(crate) mod fallbacks;
mod path_info;
mod re_exports;
mod react_native;
mod require_imports;
mod specifier;
mod static_imports;
#[cfg(test)]
mod tests;
mod types;
mod upgrades;

pub use fallbacks::extract_package_name_from_node_modules_path;
pub use path_info::{
    extract_package_name, is_bare_specifier, is_path_alias, is_valid_package_name,
};
pub use types::{
    ResolveResult, ResolvedImport, ResolvedModule, ResolvedReExport, ResolvedSourceEdge,
};

use std::path::{Path, PathBuf};
use std::sync::Mutex;

use rayon::prelude::*;
use rustc_hash::{FxHashMap, FxHashSet};

use fallow_config::{AutoImportKind, AutoImportRule};
use fallow_types::discover::{DiscoveredFile, FileId};
use fallow_types::extract::{ImportInfo, ImportedName, ModuleInfo};
use oxc_span::Span;

use dynamic_imports::{resolve_dynamic_imports, resolve_dynamic_patterns};
use re_exports::resolve_re_exports;
use react_native::{build_condition_names, build_extensions};
use require_imports::resolve_require_imports;
use specifier::create_resolver;
use static_imports::resolve_static_imports;
use types::{PackageManifestInfo, ResolveContext};
use upgrades::apply_specifier_upgrades;

/// Resolve all imports across all modules in parallel.
#[must_use]
#[expect(
    clippy::too_many_arguments,
    reason = "resolver inputs come from disjoint sources (config, plugins, workspace, filesystem); \
              bundling them into a struct would be a cross-cutting refactor outside this task"
)]
pub fn resolve_all_imports(
    modules: &[ModuleInfo],
    files: &[DiscoveredFile],
    workspaces: &[fallow_config::WorkspaceInfo],
    active_plugins: &[String],
    path_aliases: &[(String, String)],
    auto_imports: &[AutoImportRule],
    scss_include_paths: &[PathBuf],
    static_dir_mappings: &[(PathBuf, String)],
    root: &Path,
    extra_conditions: &[String],
) -> Vec<ResolvedModule> {
    let canonical_ws_roots: Vec<PathBuf> = workspaces
        .par_iter()
        .map(|ws| dunce::canonicalize(&ws.root).unwrap_or_else(|_| ws.root.clone()))
        .collect();
    let workspace_roots: FxHashMap<&str, &Path> = workspaces
        .iter()
        .zip(canonical_ws_roots.iter())
        .map(|(ws, canonical)| (ws.name.as_str(), canonical.as_path()))
        .collect();
    let root_canonical = dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
    let mut package_manifests = Vec::new();
    if let Ok(package_json) = fallow_config::PackageJson::load(&root.join("package.json")) {
        package_manifests.push(PackageManifestInfo {
            root: root.to_path_buf(),
            canonical_root: root_canonical,
            name: package_json.name.clone(),
            package_json,
        });
    }
    for (ws, canonical_root) in workspaces.iter().zip(canonical_ws_roots.iter()) {
        if let Ok(package_json) = fallow_config::PackageJson::load(&ws.root.join("package.json")) {
            package_manifests.push(PackageManifestInfo {
                root: ws.root.clone(),
                canonical_root: canonical_root.clone(),
                name: package_json.name.clone().or_else(|| Some(ws.name.clone())),
                package_json,
            });
        }
    }

    let root_is_canonical = dunce::canonicalize(root).is_ok_and(|c| c == root);

    let canonical_paths: Vec<PathBuf> = if root_is_canonical {
        Vec::new()
    } else {
        files
            .par_iter()
            .map(|f| dunce::canonicalize(&f.path).unwrap_or_else(|_| f.path.clone()))
            .collect()
    };

    let path_to_id: FxHashMap<&Path, FileId> = if root_is_canonical {
        files.iter().map(|f| (f.path.as_path(), f.id)).collect()
    } else {
        canonical_paths
            .iter()
            .enumerate()
            .map(|(idx, canonical)| (canonical.as_path(), files[idx].id))
            .collect()
    };

    let raw_path_to_id: FxHashMap<&Path, FileId> =
        files.iter().map(|f| (f.path.as_path(), f.id)).collect();

    let file_paths: Vec<&Path> = files.iter().map(|f| f.path.as_path()).collect();

    let extensions = build_extensions(active_plugins);
    let condition_names = build_condition_names(active_plugins, extra_conditions);
    let resolver = create_resolver(active_plugins, extra_conditions);
    let mut style_conditions = extra_conditions.to_vec();
    style_conditions.push("sass".to_string());
    style_conditions.push("style".to_string());
    let style_resolver = create_resolver(active_plugins, &style_conditions);

    let canonical_fallback = if root_is_canonical {
        Some(types::CanonicalFallback::new(files))
    } else {
        None
    };

    let tsconfig_warned: Mutex<FxHashSet<String>> = Mutex::new(FxHashSet::default());

    let ctx = ResolveContext {
        resolver: &resolver,
        style_resolver: &style_resolver,
        extensions: &extensions,
        path_to_id: &path_to_id,
        raw_path_to_id: &raw_path_to_id,
        workspace_roots: &workspace_roots,
        package_manifests: &package_manifests,
        condition_names: &condition_names,
        path_aliases,
        scss_include_paths,
        static_dir_mappings,
        root,
        canonical_fallback: canonical_fallback.as_ref(),
        tsconfig_warned: &tsconfig_warned,
    };

    let mut resolved: Vec<ResolvedModule> = modules
        .par_iter()
        .filter_map(|module| {
            let Some(file_path) = file_paths.get(module.file_id.0 as usize) else {
                tracing::warn!(
                    file_id = module.file_id.0,
                    "Skipping module with unknown file_id during resolution"
                );
                return None;
            };

            let mut all_imports = resolve_static_imports(&ctx, file_path, &module.imports);
            all_imports.extend(resolve_require_imports(
                &ctx,
                file_path,
                &module.require_calls,
            ));

            let from_dir = if canonical_paths.is_empty() {
                file_path.parent().unwrap_or(file_path)
            } else {
                canonical_paths
                    .get(module.file_id.0 as usize)
                    .and_then(|p| p.parent())
                    .unwrap_or(file_path)
            };

            Some(ResolvedModule {
                file_id: module.file_id,
                path: file_path.to_path_buf(),
                exports: module.exports.clone(),
                re_exports: resolve_re_exports(&ctx, file_path, &module.re_exports),
                resolved_imports: all_imports,
                resolved_dynamic_imports: resolve_dynamic_imports(
                    &ctx,
                    file_path,
                    &module.dynamic_imports,
                ),
                resolved_dynamic_patterns: resolve_dynamic_patterns(
                    from_dir,
                    &module.dynamic_import_patterns,
                    &canonical_paths,
                    files,
                ),
                member_accesses: module.member_accesses.clone(),
                whole_object_uses: module.whole_object_uses.clone(),
                has_cjs_exports: module.has_cjs_exports,
                has_angular_component_template_url: module.has_angular_component_template_url,
                unused_import_bindings: module.unused_import_bindings.iter().cloned().collect(),
                type_referenced_import_bindings: module.type_referenced_import_bindings.clone(),
                value_referenced_import_bindings: module.value_referenced_import_bindings.clone(),
                namespace_object_aliases: module.namespace_object_aliases.clone(),
            })
        })
        .collect();

    apply_specifier_upgrades(&mut resolved);

    synthesize_auto_import_edges(
        &mut resolved,
        modules,
        auto_imports,
        &path_to_id,
        &raw_path_to_id,
    );

    resolved
}

/// Synthesize module-graph edges for convention auto-imports.
///
/// For each module, every captured `auto_import_candidates` name is matched
/// against the active plugins' auto-import table; on a hit a synthetic
/// [`ResolvedImport`] is added so the existing graph builder credits the edge.
/// Name collisions across files over-credit every match, keeping each provider
/// reachable. Resolution is recomputed from the live file index each run.
fn synthesize_auto_import_edges(
    resolved: &mut [ResolvedModule],
    modules: &[ModuleInfo],
    auto_imports: &[AutoImportRule],
    path_to_id: &FxHashMap<&Path, FileId>,
    raw_path_to_id: &FxHashMap<&Path, FileId>,
) {
    if auto_imports.is_empty() {
        return;
    }

    let mut table: FxHashMap<&str, Vec<(FileId, AutoImportKind)>> = FxHashMap::default();
    for rule in auto_imports {
        let source = rule.source.as_path();
        let Some(file_id) = raw_path_to_id
            .get(source)
            .or_else(|| path_to_id.get(source))
            .copied()
        else {
            continue;
        };
        table
            .entry(rule.name.as_str())
            .or_default()
            .push((file_id, rule.kind));
    }
    if table.is_empty() {
        return;
    }

    let candidates: FxHashMap<FileId, &[String]> = modules
        .iter()
        .filter(|module| !module.auto_import_candidates.is_empty())
        .map(|module| (module.file_id, module.auto_import_candidates.as_slice()))
        .collect();
    if candidates.is_empty() {
        return;
    }

    for module in resolved.iter_mut() {
        let Some(names) = candidates.get(&module.file_id) else {
            continue;
        };
        for name in *names {
            if is_auto_import_builtin(name) {
                continue;
            }
            let Some(targets) = table.get(name.as_str()) else {
                continue;
            };
            for (target_id, kind) in targets {
                if *target_id == module.file_id {
                    continue;
                }
                module.resolved_imports.push(ResolvedImport {
                    info: synthetic_auto_import_info(name, *kind),
                    target: ResolveResult::InternalModule(*target_id),
                });
            }
        }
    }
}

fn is_auto_import_builtin(name: &str) -> bool {
    matches!(
        name,
        "AbortController"
            | "AbortSignal"
            | "Array"
            | "ArrayBuffer"
            | "BigInt"
            | "Blob"
            | "Boolean"
            | "Buffer"
            | "CSS"
            | "DOMParser"
            | "Date"
            | "Document"
            | "Error"
            | "Event"
            | "EventTarget"
            | "File"
            | "FormData"
            | "Intl"
            | "JSON"
            | "Map"
            | "Math"
            | "Number"
            | "Object"
            | "Promise"
            | "Reflect"
            | "RegExp"
            | "Response"
            | "Set"
            | "String"
            | "Symbol"
            | "URL"
            | "URLSearchParams"
            | "WeakMap"
            | "WeakSet"
            | "Window"
            | "alert"
            | "clearInterval"
            | "clearTimeout"
            | "console"
            | "document"
            | "fetch"
            | "global"
            | "globalThis"
            | "localStorage"
            | "navigator"
            | "process"
            | "requestAnimationFrame"
            | "sessionStorage"
            | "setInterval"
            | "setTimeout"
            | "window"
            | "computed"
            | "customRef"
            | "defineAsyncComponent"
            | "defineComponent"
            | "effectScope"
            | "getCurrentInstance"
            | "h"
            | "inject"
            | "isProxy"
            | "isReactive"
            | "isReadonly"
            | "isRef"
            | "markRaw"
            | "nextTick"
            | "onActivated"
            | "onBeforeMount"
            | "onBeforeUnmount"
            | "onBeforeUpdate"
            | "onDeactivated"
            | "onErrorCaptured"
            | "onMounted"
            | "onRenderTracked"
            | "onRenderTriggered"
            | "onScopeDispose"
            | "onServerPrefetch"
            | "onUnmounted"
            | "onUpdated"
            | "provide"
            | "reactive"
            | "readonly"
            | "ref"
            | "resolveComponent"
            | "shallowReactive"
            | "shallowReadonly"
            | "shallowRef"
            | "toRaw"
            | "toRef"
            | "toRefs"
            | "triggerRef"
            | "unref"
            | "watch"
            | "watchEffect"
            | "watchPostEffect"
            | "watchSyncEffect"
            | "useAsyncData"
            | "useCookie"
            | "useError"
            | "useFetch"
            | "useHead"
            | "useLazyAsyncData"
            | "useLazyFetch"
            | "useNuxtApp"
            | "useRequestEvent"
            | "useRequestHeaders"
            | "useRoute"
            | "useRouter"
            | "useRuntimeConfig"
            | "useSeoMeta"
            | "useState"
    )
}

/// Build a synthetic [`ImportInfo`] for a convention auto-import. Component and
/// default kinds credit the default export; named kinds credit the named export.
fn synthetic_auto_import_info(name: &str, kind: AutoImportKind) -> ImportInfo {
    let imported_name = match kind {
        AutoImportKind::Named => ImportedName::Named(name.to_string()),
        AutoImportKind::Default | AutoImportKind::DefaultComponent => ImportedName::Default,
    };
    ImportInfo {
        source: format!("<auto-import:{name}>"),
        imported_name,
        local_name: name.to_string(),
        is_type_only: false,
        from_style: false,
        span: Span::default(),
        source_span: Span::default(),
    }
}