1use std::path::Path;
25
26use super::relativize;
27
28use fallow_types::discover::FileId;
29use rustc_hash::FxHashSet;
30
31use super::{EffectiveExportBinding, EffectiveExportResolution, ExportNamespace, ModuleGraph};
32
33#[derive(Debug, Clone, PartialEq, Eq, Hash)]
35pub struct PublicExportOrigin {
36 file_id: FileId,
37 export_name: String,
38}
39
40impl PublicExportOrigin {
41 #[must_use]
43 pub const fn file_id(&self) -> FileId {
44 self.file_id
45 }
46
47 #[must_use]
49 pub fn export_name(&self) -> &str {
50 &self.export_name
51 }
52}
53
54impl ModuleGraph {
55 #[must_use]
62 pub fn public_export_keys(
63 &self,
64 public_api_entry_points: &FxHashSet<FileId>,
65 root: &Path,
66 ) -> FxHashSet<String> {
67 let candidate_names = self.public_value_export_names(public_api_entry_points);
68 let mut keys: FxHashSet<String> = FxHashSet::default();
69
70 for entry_id in public_api_entry_points {
71 let Some(entry) = self.modules.get(entry_id.0 as usize) else {
72 continue;
73 };
74 let rel = relativize(&entry.path, root);
75 for name in &candidate_names {
76 if matches!(
77 self.resolve_export(*entry_id, name, ExportNamespace::Value),
78 EffectiveExportResolution::Unique(_)
79 ) {
80 keys.insert(format!("{rel}::{name}"));
81 }
82 }
83 }
84 keys
85 }
86
87 #[must_use]
90 pub fn public_export_origins(
91 &self,
92 public_api_entry_points: &FxHashSet<FileId>,
93 ) -> FxHashSet<PublicExportOrigin> {
94 self.public_export_origins_in_namespace(public_api_entry_points, ExportNamespace::Value)
95 }
96
97 #[must_use]
104 pub fn public_export_origins_in_namespace(
105 &self,
106 public_api_entry_points: &FxHashSet<FileId>,
107 namespace: ExportNamespace,
108 ) -> FxHashSet<PublicExportOrigin> {
109 self.public_export_declaration_bindings_in_namespace(public_api_entry_points, namespace)
110 .into_iter()
111 .filter_map(|binding| self.export_binding_origin(binding))
112 .map(|origin| PublicExportOrigin {
113 file_id: origin.file_id(),
114 export_name: origin.export().name.to_string(),
115 })
116 .collect()
117 }
118
119 #[must_use]
121 pub fn public_export_bindings(
122 &self,
123 public_api_entry_points: &FxHashSet<FileId>,
124 ) -> FxHashSet<EffectiveExportBinding> {
125 self.public_export_bindings_in_namespace(public_api_entry_points, ExportNamespace::Value)
126 }
127
128 fn public_export_bindings_in_namespace(
129 &self,
130 public_api_entry_points: &FxHashSet<FileId>,
131 namespace: ExportNamespace,
132 ) -> FxHashSet<EffectiveExportBinding> {
133 let candidate_names = self.public_export_names(public_api_entry_points, namespace);
134 public_api_entry_points
135 .iter()
136 .flat_map(|entry| {
137 candidate_names.iter().filter_map(|name| {
138 match self.resolve_export(*entry, name, namespace) {
139 EffectiveExportResolution::Unique(binding) => Some(binding),
140 EffectiveExportResolution::Missing
141 | EffectiveExportResolution::Ambiguous => None,
142 }
143 })
144 })
145 .collect()
146 }
147
148 fn public_export_declaration_bindings_in_namespace(
151 &self,
152 public_api_entry_points: &FxHashSet<FileId>,
153 namespace: ExportNamespace,
154 ) -> FxHashSet<EffectiveExportBinding> {
155 let mut declarations = FxHashSet::default();
156 let mut visited = FxHashSet::default();
157 let mut stack: Vec<_> = self
158 .public_export_bindings_in_namespace(public_api_entry_points, namespace)
159 .into_iter()
160 .collect();
161 while let Some(binding) = stack.pop() {
162 if !visited.insert(binding) {
163 continue;
164 }
165 if let Some(source) = binding.namespace_source() {
166 stack.extend(self.unique_export_bindings(source, namespace));
167 } else if self.export_binding_origin(binding).is_some() {
168 declarations.insert(binding);
169 }
170 }
171 declarations
172 }
173
174 fn public_value_export_names(
175 &self,
176 public_api_entry_points: &FxHashSet<FileId>,
177 ) -> FxHashSet<String> {
178 self.public_export_names(public_api_entry_points, ExportNamespace::Value)
179 }
180
181 fn public_export_names(
182 &self,
183 public_api_entry_points: &FxHashSet<FileId>,
184 namespace: ExportNamespace,
185 ) -> FxHashSet<String> {
186 let star_targets = self.public_star_re_export_targets(public_api_entry_points);
187 let mut names: FxHashSet<String> = public_api_entry_points
188 .iter()
189 .chain(star_targets.iter())
190 .filter_map(|id| self.modules.get(id.0 as usize))
191 .flat_map(|module| &module.exports)
192 .filter(|export| namespace == ExportNamespace::Type || !export.is_type_only)
193 .map(|export| export.name.to_string())
194 .collect();
195 names.insert("default".to_string());
196 names
197 }
198
199 fn public_star_re_export_targets(
204 &self,
205 public_api_entry_points: &FxHashSet<FileId>,
206 ) -> FxHashSet<FileId> {
207 let mut targets: FxHashSet<FileId> = public_api_entry_points
208 .iter()
209 .filter_map(|id| self.modules.get(id.0 as usize))
210 .flat_map(|module| {
211 module
212 .re_exports
213 .iter()
214 .filter(|re| re.exported_name == "*")
215 .map(|re| re.source_file)
216 })
217 .collect();
218
219 let mut stack: Vec<FileId> = targets.iter().copied().collect();
220 while let Some(id) = stack.pop() {
221 let Some(module) = self.modules.get(id.0 as usize) else {
222 continue;
223 };
224 for re in module
225 .re_exports
226 .iter()
227 .filter(|re| re.exported_name == "*")
228 {
229 if targets.insert(re.source_file) {
230 stack.push(re.source_file);
231 }
232 }
233 }
234 targets
235 }
236}
237
238#[cfg(test)]
239mod tests {
240 use super::*;
241 use crate::resolve::{ResolveResult, ResolvedImport, ResolvedModule, ResolvedReExport};
242 use fallow_types::discover::{DiscoveredFile, EntryPoint, EntryPointSource};
243 use fallow_types::extract::{
244 ExportInfo, ExportName, ImportInfo, ImportedName, ReExportInfo, VisibilityTag,
245 };
246 use std::path::PathBuf;
247
248 fn file(id: u32, path: &str) -> DiscoveredFile {
249 DiscoveredFile {
250 id: FileId(id),
251 path: PathBuf::from(path),
252 size_bytes: 10,
253 }
254 }
255
256 fn named_export(name: &str) -> ExportInfo {
257 ExportInfo {
258 name: ExportName::Named(name.to_string()),
259 local_name: Some(name.to_string()),
260 is_type_only: false,
261 visibility: VisibilityTag::None,
262 expected_unused_reason: None,
263 span: oxc_span::Span::new(0, 20),
264 members: vec![],
265 is_side_effect_used: false,
266 super_class: None,
267 deprecated: false,
268 deprecated_reason: None,
269 }
270 }
271
272 fn re_export(imported: &str, exported: &str, target: FileId) -> ResolvedReExport {
273 ResolvedReExport {
274 info: ReExportInfo {
275 source: "./impl".to_string(),
276 imported_name: imported.to_string(),
277 exported_name: exported.to_string(),
278 is_type_only: false,
279 span: oxc_span::Span::new(0, 10),
280 statement_span: oxc_span::Span::new(0, 0),
281 source_span: oxc_span::Span::new(0, 0),
282 visibility: VisibilityTag::None,
283 expected_unused_reason: None,
284 },
285 target: ResolveResult::InternalModule(target),
286 }
287 }
288
289 fn named_import(name: &str, target: FileId) -> ResolvedImport {
290 ResolvedImport {
291 info: ImportInfo {
292 source: "./x".to_string(),
293 imported_name: ImportedName::Named(name.to_string()),
294 local_name: name.to_string(),
295 is_type_only: false,
296 is_type_only_star: false,
297 from_style: false,
298 span: oxc_span::Span::new(0, 10),
299 source_span: oxc_span::Span::default(),
300 },
301 target: ResolveResult::InternalModule(target),
302 }
303 }
304
305 fn build_graph() -> (ModuleGraph, FxHashSet<FileId>) {
308 let files = vec![
309 file(0, "/p/index.js"),
310 file(1, "/p/src/impl.ts"),
311 file(2, "/p/src/internal.ts"),
312 file(3, "/p/src/consumer.ts"),
313 ];
314 let entry_points = vec![EntryPoint {
315 path: PathBuf::from("/p/index.js"),
316 source: EntryPointSource::PackageJsonExports,
317 }];
318 let resolved = vec![
319 ResolvedModule {
320 file_id: FileId(0),
321 path: PathBuf::from("/p/index.js"),
322 re_exports: vec![re_export("pub", "pub", FileId(1))],
323 ..Default::default()
324 },
325 ResolvedModule {
326 file_id: FileId(1),
327 path: PathBuf::from("/p/src/impl.ts"),
328 exports: vec![named_export("pub"), named_export("priv")].into(),
329 ..Default::default()
330 },
331 ResolvedModule {
332 file_id: FileId(2),
333 path: PathBuf::from("/p/src/internal.ts"),
334 re_exports: vec![re_export("priv", "priv", FileId(1))],
335 ..Default::default()
336 },
337 ResolvedModule {
338 file_id: FileId(3),
339 path: PathBuf::from("/p/src/consumer.ts"),
340 resolved_imports: vec![
341 named_import("pub", FileId(0)),
342 named_import("priv", FileId(2)),
343 ],
344 ..Default::default()
345 },
346 ];
347 let graph = ModuleGraph::build(&resolved, &entry_points, &files);
348 let public_entries: FxHashSet<FileId> = std::iter::once(FileId(0)).collect();
350 (graph, public_entries)
351 }
352
353 #[test]
354 fn export_reexported_through_exports_path_is_public() {
355 let (graph, public_entries) = build_graph();
356 let keys = graph.public_export_keys(&public_entries, Path::new("/p"));
357 assert!(
361 keys.contains("index.js::pub"),
362 "exports-reachable symbol must be public: {keys:?}"
363 );
364 }
365
366 #[test]
367 fn export_reexported_only_through_internal_barrel_is_not_public() {
368 let (graph, public_entries) = build_graph();
369 let keys = graph.public_export_keys(&public_entries, Path::new("/p"));
370 assert!(
374 !keys.iter().any(|k| k.ends_with("::priv")),
375 "internal-barrel-only symbol must NOT be public: {keys:?}"
376 );
377 }
378
379 fn build_aisha_graph(
383 impl_exports: &[&str],
384 exports_reexported: &[&str],
385 internal_reexported: &[&str],
386 ) -> (ModuleGraph, FxHashSet<FileId>) {
387 let files = vec![
388 file(0, "/p/index.js"),
389 file(1, "/p/src/impl.ts"),
390 file(2, "/p/src/internal.ts"),
391 ];
392 let entry_points = vec![EntryPoint {
393 path: PathBuf::from("/p/index.js"),
394 source: EntryPointSource::PackageJsonExports,
395 }];
396 let resolved = vec![
397 ResolvedModule {
398 file_id: FileId(0),
399 path: PathBuf::from("/p/index.js"),
400 re_exports: exports_reexported
401 .iter()
402 .map(|n| re_export(n, n, FileId(1)))
403 .collect(),
404 ..Default::default()
405 },
406 ResolvedModule {
407 file_id: FileId(1),
408 path: PathBuf::from("/p/src/impl.ts"),
409 exports: impl_exports.iter().map(|n| named_export(n)).collect(),
410 ..Default::default()
411 },
412 ResolvedModule {
413 file_id: FileId(2),
414 path: PathBuf::from("/p/src/internal.ts"),
415 re_exports: internal_reexported
416 .iter()
417 .map(|n| re_export(n, n, FileId(1)))
418 .collect(),
419 ..Default::default()
420 },
421 ];
422 let graph = ModuleGraph::build(&resolved, &entry_points, &files);
423 let public_entries: FxHashSet<FileId> = std::iter::once(FileId(0)).collect();
424 (graph, public_entries)
425 }
426
427 #[test]
428 fn done_condition_internal_zero_exports_one() {
429 let root = Path::new("/p");
430 let (base_graph, base_entries) = build_aisha_graph(&["pub"], &["pub"], &[]);
432 let base = base_graph.public_export_keys(&base_entries, root);
433
434 let (head_a_graph, head_a_entries) =
436 build_aisha_graph(&["pub", "internalOnly"], &["pub"], &["internalOnly"]);
437 let head_a = head_a_graph.public_export_keys(&head_a_entries, root);
438 let internal_delta: Vec<_> = head_a.difference(&base).collect();
439 assert!(
440 internal_delta.is_empty(),
441 "internal-barrel symbol must yield ZERO public-API delta: {internal_delta:?}"
442 );
443
444 let (head_b_graph, head_b_entries) =
446 build_aisha_graph(&["pub", "widget"], &["pub", "widget"], &[]);
447 let head_b = head_b_graph.public_export_keys(&head_b_entries, root);
448 let exports_delta: Vec<_> = head_b.difference(&base).collect();
449 assert_eq!(
450 exports_delta.len(),
451 1,
452 "exports-reachable symbol must yield EXACTLY ONE public-API delta: {exports_delta:?}"
453 );
454 assert_eq!(exports_delta[0], "index.js::widget");
455 }
456
457 #[test]
458 fn type_only_exports_are_skipped() {
459 let files = vec![file(0, "/p/index.ts")];
460 let entry_points = vec![EntryPoint {
461 path: PathBuf::from("/p/index.ts"),
462 source: EntryPointSource::PackageJsonExports,
463 }];
464 let mut type_export = named_export("T");
465 type_export.is_type_only = true;
466 let resolved = vec![ResolvedModule {
467 file_id: FileId(0),
468 path: PathBuf::from("/p/index.ts"),
469 exports: vec![type_export, named_export("v")].into(),
470 ..Default::default()
471 }];
472 let graph = ModuleGraph::build(&resolved, &entry_points, &files);
473 let public_entries: FxHashSet<FileId> = std::iter::once(FileId(0)).collect();
474 let keys = graph.public_export_keys(&public_entries, Path::new("/p"));
475 assert!(keys.contains("index.ts::v"));
476 assert!(!keys.contains("index.ts::T"), "type-only export skipped");
477
478 let type_origins =
479 graph.public_export_origins_in_namespace(&public_entries, ExportNamespace::Type);
480 assert!(
481 type_origins
482 .iter()
483 .any(|origin| origin.export_name() == "T"),
484 "type namespace keeps the public declaration"
485 );
486 assert!(
487 graph
488 .public_export_origins(&public_entries)
489 .iter()
490 .all(|origin| origin.export_name() != "T"),
491 "value-only consumers still exclude type-only declarations"
492 );
493 }
494
495 #[test]
496 fn public_namespace_objects_expand_to_declaration_bindings() {
497 let (graph, public_entries) = build_star_surface_graph(
498 vec![re_export("*", "SDK", FileId(1))],
499 vec![ResolvedModule {
500 file_id: FileId(1),
501 path: PathBuf::from("/p/sdk.ts"),
502 exports: vec![named_export("Client")].into(),
503 ..Default::default()
504 }],
505 );
506
507 let declarations = graph.public_export_declaration_bindings_in_namespace(
508 &public_entries,
509 ExportNamespace::Value,
510 );
511
512 assert_eq!(declarations.len(), 1);
513 let binding = *declarations.iter().next().expect("public Client binding");
514 let origin = graph.export_binding_origin(binding).expect("direct origin");
515 assert_eq!(origin.file_id(), FileId(1));
516 assert_eq!(origin.export().name.to_string(), "Client");
517 }
518
519 fn build_star_surface_graph(
520 entry_re_exports: Vec<ResolvedReExport>,
521 source_modules: Vec<ResolvedModule>,
522 ) -> (ModuleGraph, FxHashSet<FileId>) {
523 let mut files = vec![file(0, "/p/index.ts")];
524 files.extend(source_modules.iter().map(|module| {
525 file(
526 module.file_id.0,
527 module.path.to_str().expect("test path is UTF-8"),
528 )
529 }));
530 let entry_points = vec![EntryPoint {
531 path: PathBuf::from("/p/index.ts"),
532 source: EntryPointSource::PackageJsonExports,
533 }];
534 let mut resolved = vec![ResolvedModule {
535 file_id: FileId(0),
536 path: PathBuf::from("/p/index.ts"),
537 re_exports: entry_re_exports,
538 ..Default::default()
539 }];
540 resolved.extend(source_modules);
541 let graph = ModuleGraph::build(&resolved, &entry_points, &files);
542 (graph, std::iter::once(FileId(0)).collect())
543 }
544
545 #[test]
546 fn explicit_export_hides_shadowed_star_binding_from_public_surface() {
547 let (graph, public_entries) = build_star_surface_graph(
548 vec![
549 re_export("*", "*", FileId(1)),
550 re_export("foo", "foo", FileId(2)),
551 ],
552 vec![
553 ResolvedModule {
554 file_id: FileId(1),
555 path: PathBuf::from("/p/star-source.ts"),
556 exports: vec![named_export("foo")].into(),
557 ..Default::default()
558 },
559 ResolvedModule {
560 file_id: FileId(2),
561 path: PathBuf::from("/p/explicit-source.ts"),
562 exports: vec![named_export("foo")].into(),
563 ..Default::default()
564 },
565 ],
566 );
567
568 let keys = graph.public_export_keys(&public_entries, Path::new("/p"));
569
570 assert_eq!(keys, FxHashSet::from_iter(["index.ts::foo".to_string()]));
571 }
572
573 #[test]
574 fn ambiguous_star_binding_is_absent_from_public_surface() {
575 let (graph, public_entries) = build_star_surface_graph(
576 vec![
577 re_export("*", "*", FileId(1)),
578 re_export("*", "*", FileId(2)),
579 ],
580 vec![
581 ResolvedModule {
582 file_id: FileId(1),
583 path: PathBuf::from("/p/left.ts"),
584 exports: vec![named_export("foo")].into(),
585 ..Default::default()
586 },
587 ResolvedModule {
588 file_id: FileId(2),
589 path: PathBuf::from("/p/right.ts"),
590 exports: vec![named_export("foo")].into(),
591 ..Default::default()
592 },
593 ],
594 );
595
596 let keys = graph.public_export_keys(&public_entries, Path::new("/p"));
597
598 assert!(
599 keys.is_empty(),
600 "ambiguous foo is not a public binding: {keys:?}"
601 );
602 }
603
604 #[test]
605 fn convergent_star_diamond_has_one_exposed_public_key() {
606 let (graph, public_entries) = build_star_surface_graph(
607 vec![
608 re_export("*", "*", FileId(1)),
609 re_export("*", "*", FileId(2)),
610 ],
611 vec![
612 ResolvedModule {
613 file_id: FileId(1),
614 path: PathBuf::from("/p/left.ts"),
615 re_exports: vec![re_export("*", "*", FileId(3))],
616 ..Default::default()
617 },
618 ResolvedModule {
619 file_id: FileId(2),
620 path: PathBuf::from("/p/right.ts"),
621 re_exports: vec![re_export("*", "*", FileId(3))],
622 ..Default::default()
623 },
624 ResolvedModule {
625 file_id: FileId(3),
626 path: PathBuf::from("/p/source.ts"),
627 exports: vec![named_export("foo")].into(),
628 ..Default::default()
629 },
630 ],
631 );
632
633 let keys = graph.public_export_keys(&public_entries, Path::new("/p"));
634
635 assert_eq!(keys, FxHashSet::from_iter(["index.ts::foo".to_string()]));
636 }
637
638 #[test]
639 fn public_surface_preserves_aliases_default_and_value_namespace() {
640 let mut default_export = named_export("Widget");
641 default_export.name = ExportName::Default;
642 let mut type_export = named_export("T");
643 type_export.is_type_only = true;
644 let mut type_re_export = re_export("T", "PublicType", FileId(1));
645 type_re_export.info.is_type_only = true;
646 let (graph, public_entries) = build_star_surface_graph(
647 vec![
648 re_export("default", "default", FileId(1)),
649 re_export("default", "Widget", FileId(1)),
650 type_re_export,
651 ],
652 vec![ResolvedModule {
653 file_id: FileId(1),
654 path: PathBuf::from("/p/widget.ts"),
655 exports: vec![default_export, type_export].into(),
656 ..Default::default()
657 }],
658 );
659
660 let keys = graph.public_export_keys(&public_entries, Path::new("/p"));
661
662 assert_eq!(
663 keys,
664 FxHashSet::from_iter([
665 "index.ts::default".to_string(),
666 "index.ts::Widget".to_string(),
667 ])
668 );
669 }
670}