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; a
249                // side-effect edge is enough to keep the sibling reachable.
250                extra.push(ResolvedImport {
251                    info: ImportInfo {
252                        source: re_export.info.source.clone(),
253                        imported_name: ImportedName::SideEffect,
254                        local_name: String::new(),
255                        is_type_only: re_export.info.is_type_only,
256                        is_type_only_star: false,
257                        from_style: false,
258                        span: oxc_span::Span::default(),
259                        source_span: oxc_span::Span::default(),
260                    },
261                    target: ResolveResult::InternalModule(*sibling),
262                });
263            }
264        }
265
266        module.resolved_imports.extend(extra);
267    }
268}
269
270/// Whether `resolved` can be the importing file itself only because of a
271/// Metro platform extension.
272///
273/// The check is syntactic: `resolved` carries a platform segment, the
274/// specifier does not name one, and both paths have the same file name.
275/// The caller confirms that the two paths are the same file.
276pub(super) fn may_be_platform_self_resolution(
277    from_file: &Path,
278    specifier: &str,
279    resolved: &Path,
280) -> bool {
281    resolved.file_name() == from_file.file_name()
282        && platform_family_key(resolved).is_some_and(|key| key.is_platform_variant)
283        && !specifier_names_platform_variant(specifier)
284}
285
286/// Remove the Metro platform extensions from `options`.
287///
288/// The result resolves a specifier the same way as TypeScript without
289/// `moduleSuffixes`: `./UserMenu` resolves to `UserMenu.tsx`, not to
290/// `UserMenu.ios.tsx`.
291pub(super) fn without_platform_extensions(mut options: ResolveOptions) -> ResolveOptions {
292    options.extensions.retain(|extension| {
293        !RN_PLATFORM_PREFIXES
294            .iter()
295            .any(|platform| extension.starts_with(platform))
296    });
297    options
298}
299
300/// Build the resolver extension list, optionally prepending React Native platform
301/// extensions when the RN/Expo plugin is active.
302pub(super) fn build_extensions(active_plugins: &[String]) -> Vec<String> {
303    let base: Vec<String> = vec![
304        ".ts".into(),
305        ".tsx".into(),
306        ".mts".into(),
307        ".cts".into(),
308        ".gts".into(),
309        ".js".into(),
310        ".jsx".into(),
311        ".mjs".into(),
312        ".cjs".into(),
313        ".gjs".into(),
314        ".d.ts".into(),
315        ".d.mts".into(),
316        ".d.cts".into(),
317        ".json".into(),
318        ".vue".into(),
319        ".svelte".into(),
320        ".astro".into(),
321        ".mdx".into(),
322        ".css".into(),
323        ".scss".into(),
324        ".graphql".into(),
325        ".gql".into(),
326    ];
327
328    if has_react_native_plugin(active_plugins) {
329        let source_exts = [".ts", ".tsx", ".js", ".jsx"];
330        let mut rn_extensions: Vec<String> = Vec::new();
331        for platform in RN_PLATFORM_PREFIXES {
332            for ext in &source_exts {
333                rn_extensions.push(format!("{platform}{ext}"));
334            }
335        }
336        rn_extensions.extend(base);
337        rn_extensions
338    } else {
339        base
340    }
341}
342
343/// Build the resolver `condition_names` list.
344///
345/// Baseline conditions (in priority order): `development`, `import`, `require`,
346/// `default`, `types`, `node`. `development` is included so that package.json
347/// `exports` / `imports` entries declaring a `development` branch (a widely
348/// used community condition, supported by Vite, Vitest, esbuild, and Rollup)
349/// resolve to their source files instead of compiled `dist/` output. See
350/// <https://nodejs.org/api/packages.html#community-conditions-definitions>.
351///
352/// When the React Native or Expo plugin is active, `react-native` and
353/// `browser` are prepended ahead of the baseline for Metro-style resolution.
354/// User-supplied `extra_conditions` are prepended ahead of everything else
355/// so they take highest priority.
356pub(super) fn build_condition_names(
357    active_plugins: &[String],
358    extra_conditions: &[String],
359) -> Vec<String> {
360    let mut names = vec![
361        "development".into(),
362        "import".into(),
363        "require".into(),
364        "default".into(),
365        "types".into(),
366        "node".into(),
367    ];
368    if has_react_native_plugin(active_plugins) {
369        names.insert(0, "react-native".into());
370        names.insert(1, "browser".into());
371    }
372    for extra in extra_conditions.iter().rev() {
373        names.insert(0, extra.clone());
374    }
375    let mut seen: rustc_hash::FxHashSet<String> = rustc_hash::FxHashSet::default();
376    names.retain(|name| seen.insert(name.clone()));
377    names
378}
379
380#[cfg(test)]
381mod tests {
382    use super::*;
383
384    #[test]
385    fn test_has_react_native_plugin_active() {
386        let plugins = vec!["react-native".to_string(), "typescript".to_string()];
387        assert!(has_react_native_plugin(&plugins));
388    }
389
390    #[test]
391    fn test_has_expo_plugin_active() {
392        let plugins = vec!["expo".to_string(), "typescript".to_string()];
393        assert!(has_react_native_plugin(&plugins));
394    }
395
396    #[test]
397    fn test_has_react_native_plugin_inactive() {
398        let plugins = vec!["nextjs".to_string(), "typescript".to_string()];
399        assert!(!has_react_native_plugin(&plugins));
400    }
401
402    #[test]
403    fn test_rn_platform_extensions_prepended() {
404        let no_rn = build_extensions(&[]);
405        let rn_plugins = vec!["react-native".to_string()];
406        let with_rn = build_extensions(&rn_plugins);
407
408        assert_eq!(no_rn[0], ".ts");
409
410        assert_eq!(with_rn[0], ".web.ts");
411        assert_eq!(with_rn[1], ".web.tsx");
412        assert_eq!(with_rn[2], ".web.js");
413        assert_eq!(with_rn[3], ".web.jsx");
414
415        assert!(with_rn.len() > no_rn.len());
416        assert_eq!(
417            with_rn.len(),
418            no_rn.len() + 16,
419            "should add 16 platform extensions (4 platforms x 4 exts)"
420        );
421    }
422
423    #[test]
424    fn test_rn_condition_names_prepended() {
425        let no_rn = build_condition_names(&[], &[]);
426        let rn_plugins = vec!["react-native".to_string()];
427        let with_rn = build_condition_names(&rn_plugins, &[]);
428
429        assert_eq!(no_rn[0], "development");
430
431        assert_eq!(with_rn[0], "react-native");
432        assert_eq!(with_rn[1], "browser");
433        assert_eq!(with_rn[2], "development");
434    }
435
436    #[test]
437    fn test_development_condition_in_baseline() {
438        let names = build_condition_names(&[], &[]);
439        assert!(
440            names.contains(&"development".to_string()),
441            "`development` must be part of the default condition set"
442        );
443    }
444
445    #[test]
446    fn test_extra_conditions_prepended_before_baseline() {
447        let names = build_condition_names(&[], &["worker".to_string(), "edge-light".to_string()]);
448        assert_eq!(names[0], "worker");
449        assert_eq!(names[1], "edge-light");
450        assert_eq!(names[2], "development");
451    }
452
453    #[test]
454    fn test_extra_conditions_prepended_before_rn() {
455        let rn_plugins = vec!["react-native".to_string()];
456        let names = build_condition_names(&rn_plugins, &["worker".to_string()]);
457        assert_eq!(names[0], "worker");
458        assert_eq!(names[1], "react-native");
459        assert_eq!(names[2], "browser");
460        assert_eq!(names[3], "development");
461    }
462
463    #[test]
464    fn test_duplicate_baseline_condition_from_user_is_deduped() {
465        let names = build_condition_names(&[], &["development".to_string()]);
466        let dev_count = names.iter().filter(|n| *n == "development").count();
467        assert_eq!(dev_count, 1, "`development` should appear exactly once");
468        assert_eq!(
469            names[0], "development",
470            "user-supplied entry keeps its position"
471        );
472    }
473
474    #[test]
475    fn test_specifier_names_platform_variant() {
476        assert!(specifier_names_platform_variant("./UserMenu.ios"));
477        assert!(specifier_names_platform_variant("./UserMenu.android.tsx"));
478        assert!(specifier_names_platform_variant("../deep/UserMenu.native"));
479        assert!(!specifier_names_platform_variant("./UserMenu"));
480        assert!(!specifier_names_platform_variant("./UserMenu.tsx"));
481        assert!(!specifier_names_platform_variant("./ios/UserMenu"));
482    }
483
484    #[test]
485    fn test_platform_family_key_marks_platform_variants() {
486        let key = platform_family_key(Path::new("src/components/UserMenu.ios.tsx"))
487            .expect("source file has a family key");
488        assert_eq!(key.parent, Path::new("src/components"));
489        assert_eq!(key.base, "UserMenu");
490        assert!(key.is_platform_variant);
491
492        let key = platform_family_key(Path::new("src/components/UserMenu.tsx"))
493            .expect("source file has a family key");
494        assert_eq!(key.parent, Path::new("src/components"));
495        assert_eq!(key.base, "UserMenu");
496        assert!(!key.is_platform_variant);
497    }
498
499    #[test]
500    fn test_platform_family_key_covers_every_platform_and_source_extension() {
501        for platform in RN_PLATFORM_PREFIXES {
502            for ext in RN_SOURCE_EXTS {
503                let path = format!("src/Button{platform}{ext}");
504                let key = platform_family_key(Path::new(&path)).expect("family key");
505                assert_eq!(key.base, "Button", "{path}");
506                assert!(key.is_platform_variant, "{path}");
507            }
508        }
509    }
510
511    #[test]
512    fn test_platform_family_key_rejects_non_source_files() {
513        assert_eq!(platform_family_key(Path::new("src/UserMenu.css")), None);
514        assert_eq!(
515            platform_family_key(Path::new("src/UserMenu.ios.json")),
516            None
517        );
518        assert_eq!(platform_family_key(Path::new("src/UserMenu.ios")), None);
519        assert_eq!(
520            platform_family_key(Path::new("src/.ios.tsx")),
521            None,
522            "a bare platform segment has no base stem"
523        );
524    }
525
526    fn discovered(id: u32, path: &str) -> DiscoveredFile {
527        DiscoveredFile {
528            id: FileId(id),
529            path: std::path::PathBuf::from(path),
530            size_bytes: 0,
531        }
532    }
533
534    #[test]
535    fn test_platform_families_group_base_and_variants() {
536        let files = vec![
537            discovered(0, "src/UserMenu.tsx"),
538            discovered(1, "src/UserMenu.ios.tsx"),
539            discovered(2, "src/UserMenu.android.tsx"),
540            discovered(3, "src/Other.tsx"),
541            discovered(4, "src/nested/UserMenu.tsx"),
542        ];
543        let families = PlatformFamilies::build(&files);
544
545        assert_eq!(families.members.len(), 1);
546        assert_eq!(
547            families.siblings(FileId(0)),
548            Some([FileId(0), FileId(1), FileId(2)].as_slice())
549        );
550        assert_eq!(families.siblings(FileId(1)), families.siblings(FileId(0)));
551        assert_eq!(families.siblings(FileId(3)), None);
552        assert_eq!(
553            families.siblings(FileId(4)),
554            None,
555            "same stem in a different directory is not part of the family"
556        );
557    }
558
559    #[test]
560    fn test_family_edges_skip_the_importing_member() {
561        let files = vec![
562            discovered(0, "src/Badge.tsx"),
563            discovered(1, "src/Badge.ios.tsx"),
564            discovered(2, "src/Badge.android.tsx"),
565        ];
566        let ios_import = ResolvedImport {
567            info: ImportInfo {
568                source: "./Badge".to_string(),
569                imported_name: ImportedName::Named("BadgeProps".to_string()),
570                local_name: "BadgeProps".to_string(),
571                is_type_only: true,
572                is_type_only_star: false,
573                from_style: false,
574                span: oxc_span::Span::default(),
575                source_span: oxc_span::Span::default(),
576            },
577            target: ResolveResult::InternalModule(FileId(0)),
578        };
579        let android_re_export = super::super::types::ResolvedReExport {
580            info: fallow_types::extract::ReExportInfo {
581                source: "./Badge".to_string(),
582                imported_name: "BadgeProps".to_string(),
583                exported_name: "BadgeProps".to_string(),
584                is_type_only: true,
585                span: oxc_span::Span::default(),
586                statement_span: oxc_span::Span::default(),
587                source_span: oxc_span::Span::default(),
588                visibility: fallow_types::extract::VisibilityTag::None,
589                expected_unused_reason: None,
590            },
591            target: ResolveResult::InternalModule(FileId(0)),
592        };
593        let mut resolved = vec![
594            ResolvedModule {
595                file_id: FileId(1),
596                path: std::path::PathBuf::from("src/Badge.ios.tsx"),
597                resolved_imports: vec![ios_import],
598                ..ResolvedModule::default()
599            },
600            ResolvedModule {
601                file_id: FileId(2),
602                path: std::path::PathBuf::from("src/Badge.android.tsx"),
603                re_exports: vec![android_re_export],
604                ..ResolvedModule::default()
605            },
606        ];
607
608        synthesize_platform_family_edges(&mut resolved, &files, &["expo".to_string()]);
609
610        let targets = |module: &ResolvedModule| -> Vec<Option<FileId>> {
611            module
612                .resolved_imports
613                .iter()
614                .map(|import| import.target.internal_file_id())
615                .collect()
616        };
617        assert_eq!(
618            targets(&resolved[0]),
619            vec![Some(FileId(0)), Some(FileId(2))],
620            "an import must not give the importing member an edge to itself"
621        );
622        assert_eq!(
623            targets(&resolved[1]),
624            vec![Some(FileId(1))],
625            "a re-export must not give the importing member an edge to itself"
626        );
627    }
628
629    #[test]
630    fn test_platform_families_require_a_platform_variant() {
631        let files = vec![
632            discovered(0, "src/Button.ts"),
633            discovered(1, "src/Button.tsx"),
634        ];
635        let families = PlatformFamilies::build(&files);
636        assert!(
637            families.members.is_empty(),
638            "same-stem files without a platform variant are not a Metro family"
639        );
640    }
641
642    #[test]
643    fn test_duplicate_user_conditions_are_deduped_preserving_first() {
644        let names = build_condition_names(
645            &[],
646            &[
647                "worker".to_string(),
648                "edge-light".to_string(),
649                "worker".to_string(),
650            ],
651        );
652        let worker_count = names.iter().filter(|n| *n == "worker").count();
653        assert_eq!(worker_count, 1);
654        assert_eq!(names[0], "worker");
655        assert_eq!(names[1], "edge-light");
656    }
657}