Skip to main content

fallow_graph/resolve/
react_native.rs

1//! React Native and Expo platform extension support.
2
3use std::path::Path;
4
5use oxc_resolver::ResolveOptions;
6use rustc_hash::FxHashMap;
7
8use super::types::{RN_PLATFORM_PREFIXES, ResolveResult, ResolvedImport, ResolvedModule};
9use fallow_types::discover::{DiscoveredFile, FileId};
10use fallow_types::extract::{ImportInfo, ImportedName};
11
12/// Whether the React Native or Expo plugin is active, the gate for every
13/// Metro platform-extension behavior in the resolver and its consumers.
14pub fn has_react_native_plugin(active_plugins: &[String]) -> bool {
15    active_plugins
16        .iter()
17        .any(|p| p == "react-native" || p == "expo")
18}
19
20/// Source extensions that participate in Metro platform-extension resolution.
21const RN_SOURCE_EXTS: &[&str] = &[".ts", ".tsx", ".js", ".jsx"];
22
23/// Split a file or specifier basename into its stem and a Metro source
24/// extension, when one is present.
25fn split_source_ext(name: &str) -> (&str, Option<&str>) {
26    for ext in RN_SOURCE_EXTS {
27        if let Some(stem) = name.strip_suffix(ext) {
28            return (stem, Some(ext));
29        }
30    }
31    (name, None)
32}
33
34/// Strip a trailing platform segment (`.ios`, `.android`, ...) from a stem.
35/// Returns the family base stem and whether a platform segment was present.
36fn strip_platform_segment(stem: &str) -> (&str, bool) {
37    for platform in RN_PLATFORM_PREFIXES {
38        if let Some(base) = stem.strip_suffix(platform) {
39            return (base, true);
40        }
41    }
42    (stem, false)
43}
44
45/// Where a source file sits in a Metro platform-extension family: the
46/// directory and base stem shared by `<stem>.<platform><ext>` and
47/// `<stem><ext>`, plus whether this member carries a platform segment.
48#[derive(Debug, Clone, Copy, PartialEq, Eq)]
49pub struct PlatformFamilyKey<'a> {
50    /// Directory containing the file.
51    pub parent: &'a Path,
52    /// File stem with the source extension and any platform segment removed.
53    pub base: &'a str,
54    /// Whether the file name carries a platform segment (`.ios`, `.web`, ...).
55    pub is_platform_variant: bool,
56}
57
58/// Classify `path` by its Metro platform-extension family.
59///
60/// Membership is syntactic: files sharing `parent` and `base` belong to the
61/// same family, and the caller decides whether enough members exist for the
62/// family to matter. Returns `None` for files outside the Metro source
63/// extensions, names without a stem, and paths without a parent directory.
64pub fn platform_family_key(path: &Path) -> Option<PlatformFamilyKey<'_>> {
65    let name = path.file_name()?.to_str()?;
66    let (stem, ext) = split_source_ext(name);
67    ext?;
68    let (base, is_platform_variant) = strip_platform_segment(stem);
69    if base.is_empty() {
70        return None;
71    }
72    let parent = path.parent()?;
73    Some(PlatformFamilyKey {
74        parent,
75        base,
76        is_platform_variant,
77    })
78}
79
80/// Whether an import specifier explicitly names a platform variant
81/// (e.g. `./UserMenu.ios` or `./UserMenu.ios.tsx`), in which case the author
82/// targeted one variant and the family must not be credited as a whole.
83fn specifier_names_platform_variant(specifier: &str) -> bool {
84    let basename = specifier.rsplit('/').next().unwrap_or(specifier);
85    let (stem, _) = split_source_ext(basename);
86    strip_platform_segment(stem).1
87}
88
89/// Metro platform-extension families among the discovered files, keyed by the
90/// member [`FileId`]. A family is every file in one directory sharing a base
91/// stem across `<stem>.<platform><ext>` and `<stem><ext>`, and only counts
92/// when at least one platform variant exists alongside another member.
93struct PlatformFamilies {
94    family_of: FxHashMap<FileId, usize>,
95    members: Vec<Vec<FileId>>,
96}
97
98impl PlatformFamilies {
99    fn build(files: &[DiscoveredFile]) -> Self {
100        let mut grouped: FxHashMap<(&Path, &str), Vec<(FileId, bool)>> = FxHashMap::default();
101        for file in files {
102            let Some(key) = platform_family_key(&file.path) else {
103                continue;
104            };
105            grouped
106                .entry((key.parent, key.base))
107                .or_default()
108                .push((file.id, key.is_platform_variant));
109        }
110
111        let mut family_of = FxHashMap::default();
112        let mut members = Vec::new();
113        for group in grouped.into_values() {
114            if group.len() < 2 || !group.iter().any(|(_, is_platform)| *is_platform) {
115                continue;
116            }
117            let mut ids: Vec<FileId> = group.into_iter().map(|(id, _)| id).collect();
118            ids.sort_unstable_by_key(|id| id.0);
119            let index = members.len();
120            for id in &ids {
121                family_of.insert(*id, index);
122            }
123            members.push(ids);
124        }
125        Self { family_of, members }
126    }
127
128    fn siblings(&self, target: FileId) -> Option<&[FileId]> {
129        self.family_of
130            .get(&target)
131            .map(|index| self.members[*index].as_slice())
132    }
133}
134
135/// Rebuild a project-internal [`ResolveResult`] against a sibling file,
136/// preserving the original edge kind and package attribution.
137pub(super) fn retarget(result: &ResolveResult, sibling: FileId) -> Option<ResolveResult> {
138    match result {
139        ResolveResult::InternalModule(_) => Some(ResolveResult::InternalModule(sibling)),
140        ResolveResult::CommonJsInternalModule(_) => {
141            Some(ResolveResult::CommonJsInternalModule(sibling))
142        }
143        ResolveResult::SyntheticAutoImport(_) => Some(ResolveResult::SyntheticAutoImport(sibling)),
144        ResolveResult::InternalPackageModule { package_name, .. } => {
145            Some(ResolveResult::InternalPackageModule {
146                file_id: sibling,
147                package_name: package_name.clone(),
148            })
149        }
150        ResolveResult::CommonJsInternalPackageModule { package_name, .. } => {
151            Some(ResolveResult::CommonJsInternalPackageModule {
152                file_id: sibling,
153                package_name: package_name.clone(),
154            })
155        }
156        ResolveResult::ExternalFile(_)
157        | ResolveResult::NpmPackage(_)
158        | ResolveResult::CommonJsNpmPackage(_)
159        | ResolveResult::Unresolvable(_) => None,
160    }
161}
162
163/// Expand `imports` with sibling edges for every platform-extension family
164/// member, appending the extra edges to `extra`.
165fn expand_family_imports(
166    importer: FileId,
167    imports: &[ResolvedImport],
168    families: &PlatformFamilies,
169    extra: &mut Vec<ResolvedImport>,
170) {
171    for import in imports {
172        if specifier_names_platform_variant(&import.info.source) {
173            continue;
174        }
175        let Some(target) = import.target.internal_file_id() else {
176            continue;
177        };
178        let Some(siblings) = families.siblings(target) else {
179            continue;
180        };
181        for sibling in siblings {
182            if *sibling == target || *sibling == importer {
183                continue;
184            }
185            if let Some(retargeted) = retarget(&import.target, *sibling) {
186                extra.push(ResolvedImport {
187                    info: import.info.clone(),
188                    target: retargeted,
189                });
190            }
191        }
192    }
193}
194
195/// Credit whole Metro platform-extension families when the RN/Expo plugin is
196/// active.
197///
198/// Metro resolves `./UserMenu` to `UserMenu.ios.tsx` on iOS and to
199/// `UserMenu.tsx` (or `.android.tsx`, `.native.tsx`, ...) elsewhere, so a
200/// specifier that resolved to one family member reaches every member at
201/// runtime. The resolver picks a single winner per platform-extension order;
202/// this pass appends edges to the remaining family members so none are
203/// reported as unused files and their matching exports stay credited. Imports
204/// that explicitly name a platform variant keep their single edge. A family
205/// member never gets an edge to itself.
206pub(super) fn synthesize_platform_family_edges(
207    resolved: &mut [ResolvedModule],
208    files: &[DiscoveredFile],
209    active_plugins: &[String],
210) {
211    if !has_react_native_plugin(active_plugins) {
212        return;
213    }
214    let families = PlatformFamilies::build(files);
215    if families.members.is_empty() {
216        return;
217    }
218
219    for module in resolved.iter_mut() {
220        let mut extra = Vec::new();
221        expand_family_imports(
222            module.file_id,
223            &module.resolved_imports,
224            &families,
225            &mut extra,
226        );
227        expand_family_imports(
228            module.file_id,
229            &module.resolved_dynamic_imports,
230            &families,
231            &mut extra,
232        );
233
234        for re_export in &module.re_exports {
235            if specifier_names_platform_variant(&re_export.info.source) {
236                continue;
237            }
238            let Some(target) = re_export.target.internal_file_id() else {
239                continue;
240            };
241            let Some(siblings) = families.siblings(target) else {
242                continue;
243            };
244            for sibling in siblings {
245                if *sibling == target || *sibling == module.file_id {
246                    continue;
247                }
248                // Re-export propagation keeps its single resolved source. The
249                // side-effect edge keeps the sibling reachable, and the graph
250                // copies the re-exported names of the target to the sibling
251                // (`credit_platform_family_re_exports`).
252                extra.push(ResolvedImport {
253                    info: ImportInfo {
254                        source: re_export.info.source.clone(),
255                        imported_name: ImportedName::SideEffect,
256                        local_name: String::new(),
257                        is_type_only: re_export.info.is_type_only,
258                        is_type_only_star: false,
259                        from_style: false,
260                        span: oxc_span::Span::default(),
261                        source_span: oxc_span::Span::default(),
262                    },
263                    target: ResolveResult::InternalModule(*sibling),
264                });
265            }
266        }
267
268        module.resolved_imports.extend(extra);
269    }
270}
271
272/// Whether `resolved` can be the importing file itself only because of a
273/// Metro platform extension.
274///
275/// The check is syntactic: `resolved` carries a platform segment, the
276/// specifier does not name one, and both paths have the same file name.
277/// The caller confirms that the two paths are the same file.
278pub(super) fn may_be_platform_self_resolution(
279    from_file: &Path,
280    specifier: &str,
281    resolved: &Path,
282) -> bool {
283    resolved.file_name() == from_file.file_name()
284        && platform_family_key(resolved).is_some_and(|key| key.is_platform_variant)
285        && !specifier_names_platform_variant(specifier)
286}
287
288/// Remove the Metro platform extensions from `options`.
289///
290/// The result resolves a specifier the same way as TypeScript without
291/// `moduleSuffixes`: `./UserMenu` resolves to `UserMenu.tsx`, not to
292/// `UserMenu.ios.tsx`.
293pub(super) fn without_platform_extensions(mut options: ResolveOptions) -> ResolveOptions {
294    options.extensions.retain(|extension| {
295        !RN_PLATFORM_PREFIXES
296            .iter()
297            .any(|platform| extension.starts_with(platform))
298    });
299    options
300}
301
302/// Build the resolver extension list, optionally prepending React Native platform
303/// extensions when the RN/Expo plugin is active.
304pub(super) fn build_extensions(active_plugins: &[String]) -> Vec<String> {
305    let base: Vec<String> = vec![
306        ".ts".into(),
307        ".tsx".into(),
308        ".mts".into(),
309        ".cts".into(),
310        ".gts".into(),
311        ".js".into(),
312        ".jsx".into(),
313        ".mjs".into(),
314        ".cjs".into(),
315        ".gjs".into(),
316        ".d.ts".into(),
317        ".d.mts".into(),
318        ".d.cts".into(),
319        ".json".into(),
320        ".vue".into(),
321        ".svelte".into(),
322        ".astro".into(),
323        ".mdx".into(),
324        ".css".into(),
325        ".scss".into(),
326        ".graphql".into(),
327        ".gql".into(),
328    ];
329
330    if has_react_native_plugin(active_plugins) {
331        let source_exts = [".ts", ".tsx", ".js", ".jsx"];
332        let mut rn_extensions: Vec<String> = Vec::new();
333        for platform in RN_PLATFORM_PREFIXES {
334            for ext in &source_exts {
335                rn_extensions.push(format!("{platform}{ext}"));
336            }
337        }
338        rn_extensions.extend(base);
339        rn_extensions
340    } else {
341        base
342    }
343}
344
345/// Build the resolver `condition_names` list.
346///
347/// Baseline conditions (in priority order): `development`, `import`, `require`,
348/// `default`, `types`, `node`. `development` is included so that package.json
349/// `exports` / `imports` entries declaring a `development` branch (a widely
350/// used community condition, supported by Vite, Vitest, esbuild, and Rollup)
351/// resolve to their source files instead of compiled `dist/` output. See
352/// <https://nodejs.org/api/packages.html#community-conditions-definitions>.
353///
354/// When the React Native or Expo plugin is active, `react-native` and
355/// `browser` are prepended ahead of the baseline for Metro-style resolution.
356/// User-supplied `extra_conditions` are prepended ahead of everything else
357/// so they take highest priority.
358pub(super) fn build_condition_names(
359    active_plugins: &[String],
360    extra_conditions: &[String],
361) -> Vec<String> {
362    let mut names = vec![
363        "development".into(),
364        "import".into(),
365        "require".into(),
366        "default".into(),
367        "types".into(),
368        "node".into(),
369    ];
370    if has_react_native_plugin(active_plugins) {
371        names.insert(0, "react-native".into());
372        names.insert(1, "browser".into());
373    }
374    for extra in extra_conditions.iter().rev() {
375        names.insert(0, extra.clone());
376    }
377    let mut seen: rustc_hash::FxHashSet<String> = rustc_hash::FxHashSet::default();
378    names.retain(|name| seen.insert(name.clone()));
379    names
380}
381
382#[cfg(test)]
383mod tests {
384    use super::*;
385
386    #[test]
387    fn test_has_react_native_plugin_active() {
388        let plugins = vec!["react-native".to_string(), "typescript".to_string()];
389        assert!(has_react_native_plugin(&plugins));
390    }
391
392    #[test]
393    fn test_has_expo_plugin_active() {
394        let plugins = vec!["expo".to_string(), "typescript".to_string()];
395        assert!(has_react_native_plugin(&plugins));
396    }
397
398    #[test]
399    fn test_has_react_native_plugin_inactive() {
400        let plugins = vec!["nextjs".to_string(), "typescript".to_string()];
401        assert!(!has_react_native_plugin(&plugins));
402    }
403
404    #[test]
405    fn test_rn_platform_extensions_prepended() {
406        let no_rn = build_extensions(&[]);
407        let rn_plugins = vec!["react-native".to_string()];
408        let with_rn = build_extensions(&rn_plugins);
409
410        assert_eq!(no_rn[0], ".ts");
411
412        assert_eq!(with_rn[0], ".web.ts");
413        assert_eq!(with_rn[1], ".web.tsx");
414        assert_eq!(with_rn[2], ".web.js");
415        assert_eq!(with_rn[3], ".web.jsx");
416
417        assert!(with_rn.len() > no_rn.len());
418        assert_eq!(
419            with_rn.len(),
420            no_rn.len() + 16,
421            "should add 16 platform extensions (4 platforms x 4 exts)"
422        );
423    }
424
425    #[test]
426    fn test_rn_condition_names_prepended() {
427        let no_rn = build_condition_names(&[], &[]);
428        let rn_plugins = vec!["react-native".to_string()];
429        let with_rn = build_condition_names(&rn_plugins, &[]);
430
431        assert_eq!(no_rn[0], "development");
432
433        assert_eq!(with_rn[0], "react-native");
434        assert_eq!(with_rn[1], "browser");
435        assert_eq!(with_rn[2], "development");
436    }
437
438    #[test]
439    fn test_development_condition_in_baseline() {
440        let names = build_condition_names(&[], &[]);
441        assert!(
442            names.contains(&"development".to_string()),
443            "`development` must be part of the default condition set"
444        );
445    }
446
447    #[test]
448    fn test_extra_conditions_prepended_before_baseline() {
449        let names = build_condition_names(&[], &["worker".to_string(), "edge-light".to_string()]);
450        assert_eq!(names[0], "worker");
451        assert_eq!(names[1], "edge-light");
452        assert_eq!(names[2], "development");
453    }
454
455    #[test]
456    fn test_extra_conditions_prepended_before_rn() {
457        let rn_plugins = vec!["react-native".to_string()];
458        let names = build_condition_names(&rn_plugins, &["worker".to_string()]);
459        assert_eq!(names[0], "worker");
460        assert_eq!(names[1], "react-native");
461        assert_eq!(names[2], "browser");
462        assert_eq!(names[3], "development");
463    }
464
465    #[test]
466    fn test_duplicate_baseline_condition_from_user_is_deduped() {
467        let names = build_condition_names(&[], &["development".to_string()]);
468        let dev_count = names.iter().filter(|n| *n == "development").count();
469        assert_eq!(dev_count, 1, "`development` should appear exactly once");
470        assert_eq!(
471            names[0], "development",
472            "user-supplied entry keeps its position"
473        );
474    }
475
476    #[test]
477    fn test_specifier_names_platform_variant() {
478        assert!(specifier_names_platform_variant("./UserMenu.ios"));
479        assert!(specifier_names_platform_variant("./UserMenu.android.tsx"));
480        assert!(specifier_names_platform_variant("../deep/UserMenu.native"));
481        assert!(!specifier_names_platform_variant("./UserMenu"));
482        assert!(!specifier_names_platform_variant("./UserMenu.tsx"));
483        assert!(!specifier_names_platform_variant("./ios/UserMenu"));
484    }
485
486    #[test]
487    fn test_platform_family_key_marks_platform_variants() {
488        let key = platform_family_key(Path::new("src/components/UserMenu.ios.tsx"))
489            .expect("source file has a family key");
490        assert_eq!(key.parent, Path::new("src/components"));
491        assert_eq!(key.base, "UserMenu");
492        assert!(key.is_platform_variant);
493
494        let key = platform_family_key(Path::new("src/components/UserMenu.tsx"))
495            .expect("source file has a family key");
496        assert_eq!(key.parent, Path::new("src/components"));
497        assert_eq!(key.base, "UserMenu");
498        assert!(!key.is_platform_variant);
499    }
500
501    #[test]
502    fn test_platform_family_key_covers_every_platform_and_source_extension() {
503        for platform in RN_PLATFORM_PREFIXES {
504            for ext in RN_SOURCE_EXTS {
505                let path = format!("src/Button{platform}{ext}");
506                let key = platform_family_key(Path::new(&path)).expect("family key");
507                assert_eq!(key.base, "Button", "{path}");
508                assert!(key.is_platform_variant, "{path}");
509            }
510        }
511    }
512
513    #[test]
514    fn test_platform_family_key_rejects_non_source_files() {
515        assert_eq!(platform_family_key(Path::new("src/UserMenu.css")), None);
516        assert_eq!(
517            platform_family_key(Path::new("src/UserMenu.ios.json")),
518            None
519        );
520        assert_eq!(platform_family_key(Path::new("src/UserMenu.ios")), None);
521        assert_eq!(
522            platform_family_key(Path::new("src/.ios.tsx")),
523            None,
524            "a bare platform segment has no base stem"
525        );
526    }
527
528    fn discovered(id: u32, path: &str) -> DiscoveredFile {
529        DiscoveredFile {
530            id: FileId(id),
531            path: std::path::PathBuf::from(path),
532            size_bytes: 0,
533        }
534    }
535
536    #[test]
537    fn test_platform_families_group_base_and_variants() {
538        let files = vec![
539            discovered(0, "src/UserMenu.tsx"),
540            discovered(1, "src/UserMenu.ios.tsx"),
541            discovered(2, "src/UserMenu.android.tsx"),
542            discovered(3, "src/Other.tsx"),
543            discovered(4, "src/nested/UserMenu.tsx"),
544        ];
545        let families = PlatformFamilies::build(&files);
546
547        assert_eq!(families.members.len(), 1);
548        assert_eq!(
549            families.siblings(FileId(0)),
550            Some([FileId(0), FileId(1), FileId(2)].as_slice())
551        );
552        assert_eq!(families.siblings(FileId(1)), families.siblings(FileId(0)));
553        assert_eq!(families.siblings(FileId(3)), None);
554        assert_eq!(
555            families.siblings(FileId(4)),
556            None,
557            "same stem in a different directory is not part of the family"
558        );
559    }
560
561    #[test]
562    fn test_family_edges_skip_the_importing_member() {
563        let files = vec![
564            discovered(0, "src/Badge.tsx"),
565            discovered(1, "src/Badge.ios.tsx"),
566            discovered(2, "src/Badge.android.tsx"),
567        ];
568        let ios_import = ResolvedImport {
569            info: ImportInfo {
570                source: "./Badge".to_string(),
571                imported_name: ImportedName::Named("BadgeProps".to_string()),
572                local_name: "BadgeProps".to_string(),
573                is_type_only: true,
574                is_type_only_star: false,
575                from_style: false,
576                span: oxc_span::Span::default(),
577                source_span: oxc_span::Span::default(),
578            },
579            target: ResolveResult::InternalModule(FileId(0)),
580        };
581        let android_re_export = super::super::types::ResolvedReExport {
582            info: fallow_types::extract::ReExportInfo {
583                source: "./Badge".to_string(),
584                imported_name: "BadgeProps".to_string(),
585                exported_name: "BadgeProps".to_string(),
586                is_type_only: true,
587                span: oxc_span::Span::default(),
588                statement_span: oxc_span::Span::default(),
589                source_span: oxc_span::Span::default(),
590                visibility: fallow_types::extract::VisibilityTag::None,
591                expected_unused_reason: None,
592            },
593            target: ResolveResult::InternalModule(FileId(0)),
594        };
595        let mut resolved = vec![
596            ResolvedModule {
597                file_id: FileId(1),
598                path: std::path::PathBuf::from("src/Badge.ios.tsx"),
599                resolved_imports: vec![ios_import],
600                ..ResolvedModule::default()
601            },
602            ResolvedModule {
603                file_id: FileId(2),
604                path: std::path::PathBuf::from("src/Badge.android.tsx"),
605                re_exports: vec![android_re_export],
606                ..ResolvedModule::default()
607            },
608        ];
609
610        synthesize_platform_family_edges(&mut resolved, &files, &["expo".to_string()]);
611
612        let targets = |module: &ResolvedModule| -> Vec<Option<FileId>> {
613            module
614                .resolved_imports
615                .iter()
616                .map(|import| import.target.internal_file_id())
617                .collect()
618        };
619        assert_eq!(
620            targets(&resolved[0]),
621            vec![Some(FileId(0)), Some(FileId(2))],
622            "an import must not give the importing member an edge to itself"
623        );
624        assert_eq!(
625            targets(&resolved[1]),
626            vec![Some(FileId(1))],
627            "a re-export must not give the importing member an edge to itself"
628        );
629    }
630
631    #[test]
632    fn test_platform_families_require_a_platform_variant() {
633        let files = vec![
634            discovered(0, "src/Button.ts"),
635            discovered(1, "src/Button.tsx"),
636        ];
637        let families = PlatformFamilies::build(&files);
638        assert!(
639            families.members.is_empty(),
640            "same-stem files without a platform variant are not a Metro family"
641        );
642    }
643
644    #[test]
645    fn test_duplicate_user_conditions_are_deduped_preserving_first() {
646        let names = build_condition_names(
647            &[],
648            &[
649                "worker".to_string(),
650                "edge-light".to_string(),
651                "worker".to_string(),
652            ],
653        );
654        let worker_count = names.iter().filter(|n| *n == "worker").count();
655        assert_eq!(worker_count, 1);
656        assert_eq!(names[0], "worker");
657        assert_eq!(names[1], "edge-light");
658    }
659}