File size: 51,206 Bytes
1e92f2d |
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 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 |
use std::collections::BTreeMap;
use anyhow::{Context, Result, bail};
use indexmap::map::{Entry, OccupiedEntry};
use rustc_hash::FxHashMap;
use serde::{Deserialize, Serialize};
use tracing::Instrument;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{
FxIndexMap, NonLocalValue, ResolvedVc, TaskInput, TryJoinIterExt, ValueDefault, Vc,
debug::ValueDebugFormat, fxindexmap, trace::TraceRawVcs,
};
use turbo_tasks_fs::{DirectoryContent, DirectoryEntry, FileSystemEntryType, FileSystemPath};
use turbopack_core::issue::{
Issue, IssueExt, IssueSeverity, IssueStage, OptionStyledString, StyledString,
};
use crate::{
next_app::{
AppPage, AppPath, PageSegment, PageType,
metadata::{
GlobalMetadataFileMatch, MetadataFileMatch, match_global_metadata_file,
match_local_metadata_file, normalize_metadata_route,
},
},
next_import_map::get_next_package,
};
// Next.js ignores underscores for routes but you can use %5f to still serve an underscored
// route.
fn normalize_underscore(string: &str) -> String {
string.replace("%5F", "_")
}
/// A final route in the app directory.
#[turbo_tasks::value]
#[derive(Default, Debug, Clone)]
pub struct AppDirModules {
#[serde(skip_serializing_if = "Option::is_none")]
pub page: Option<FileSystemPath>,
#[serde(skip_serializing_if = "Option::is_none")]
pub layout: Option<FileSystemPath>,
#[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<FileSystemPath>,
#[serde(skip_serializing_if = "Option::is_none")]
pub global_error: Option<FileSystemPath>,
#[serde(skip_serializing_if = "Option::is_none")]
pub global_not_found: Option<FileSystemPath>,
#[serde(skip_serializing_if = "Option::is_none")]
pub loading: Option<FileSystemPath>,
#[serde(skip_serializing_if = "Option::is_none")]
pub template: Option<FileSystemPath>,
#[serde(skip_serializing_if = "Option::is_none")]
pub forbidden: Option<FileSystemPath>,
#[serde(skip_serializing_if = "Option::is_none")]
pub unauthorized: Option<FileSystemPath>,
#[serde(skip_serializing_if = "Option::is_none")]
pub not_found: Option<FileSystemPath>,
#[serde(skip_serializing_if = "Option::is_none")]
pub default: Option<FileSystemPath>,
#[serde(skip_serializing_if = "Option::is_none")]
pub route: Option<FileSystemPath>,
#[serde(skip_serializing_if = "Metadata::is_empty", default)]
pub metadata: Metadata,
}
impl AppDirModules {
fn without_leaves(&self) -> Self {
Self {
page: None,
layout: self.layout.clone(),
error: self.error.clone(),
global_error: self.global_error.clone(),
global_not_found: self.global_not_found.clone(),
loading: self.loading.clone(),
template: self.template.clone(),
not_found: self.not_found.clone(),
forbidden: self.forbidden.clone(),
unauthorized: self.unauthorized.clone(),
default: None,
route: None,
metadata: self.metadata.clone(),
}
}
}
/// A single metadata file plus an optional "alt" text file.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, TraceRawVcs, NonLocalValue)]
pub enum MetadataWithAltItem {
Static {
path: FileSystemPath,
alt_path: Option<FileSystemPath>,
},
Dynamic {
path: FileSystemPath,
},
}
/// A single metadata file.
#[derive(
Clone, Debug, Hash, Serialize, Deserialize, PartialEq, Eq, TaskInput, TraceRawVcs, NonLocalValue,
)]
pub enum MetadataItem {
Static { path: FileSystemPath },
Dynamic { path: FileSystemPath },
}
#[turbo_tasks::function]
pub async fn get_metadata_route_name(meta: MetadataItem) -> Result<Vc<RcStr>> {
Ok(match meta {
MetadataItem::Static { path } => Vc::cell(path.file_name().into()),
MetadataItem::Dynamic { path } => {
let Some(stem) = path.file_stem() else {
bail!(
"unable to resolve file stem for metadata item at {}",
path.value_to_string().await?
);
};
match stem {
"manifest" => Vc::cell(rcstr!("manifest.webmanifest")),
_ => Vc::cell(RcStr::from(stem)),
}
}
})
}
impl MetadataItem {
pub fn into_path(self) -> FileSystemPath {
match self {
MetadataItem::Static { path } => path,
MetadataItem::Dynamic { path } => path,
}
}
}
impl From<MetadataWithAltItem> for MetadataItem {
fn from(value: MetadataWithAltItem) -> Self {
match value {
MetadataWithAltItem::Static { path, .. } => MetadataItem::Static { path },
MetadataWithAltItem::Dynamic { path } => MetadataItem::Dynamic { path },
}
}
}
/// Metadata file that can be placed in any segment of the app directory.
#[derive(
Default, Clone, Debug, Serialize, Deserialize, PartialEq, Eq, TraceRawVcs, NonLocalValue,
)]
pub struct Metadata {
#[serde(skip_serializing_if = "Vec::is_empty", default)]
pub icon: Vec<MetadataWithAltItem>,
#[serde(skip_serializing_if = "Vec::is_empty", default)]
pub apple: Vec<MetadataWithAltItem>,
#[serde(skip_serializing_if = "Vec::is_empty", default)]
pub twitter: Vec<MetadataWithAltItem>,
#[serde(skip_serializing_if = "Vec::is_empty", default)]
pub open_graph: Vec<MetadataWithAltItem>,
#[serde(skip_serializing_if = "Option::is_none")]
pub sitemap: Option<MetadataItem>,
// The page indicates where the metadata is defined and captured.
// The steps for capturing metadata (get_directory_tree) and constructing
// LoaderTree (directory_tree_to_entrypoints) is separated,
// and child loader tree can trickle down metadata when clone / merge components calculates
// the actual path incorrectly with fillMetadataSegment.
//
// This is only being used for the static metadata files.
#[serde(skip_serializing_if = "Option::is_none")]
pub base_page: Option<AppPage>,
}
impl Metadata {
pub fn is_empty(&self) -> bool {
let Metadata {
icon,
apple,
twitter,
open_graph,
sitemap,
base_page: _,
} = self;
icon.is_empty()
&& apple.is_empty()
&& twitter.is_empty()
&& open_graph.is_empty()
&& sitemap.is_none()
}
}
/// Metadata files that can be placed in the root of the app directory.
#[turbo_tasks::value]
#[derive(Default, Clone, Debug)]
pub struct GlobalMetadata {
#[serde(skip_serializing_if = "Option::is_none")]
pub favicon: Option<MetadataItem>,
#[serde(skip_serializing_if = "Option::is_none")]
pub robots: Option<MetadataItem>,
#[serde(skip_serializing_if = "Option::is_none")]
pub manifest: Option<MetadataItem>,
}
impl GlobalMetadata {
pub fn is_empty(&self) -> bool {
let GlobalMetadata {
favicon,
robots,
manifest,
} = self;
favicon.is_none() && robots.is_none() && manifest.is_none()
}
}
#[turbo_tasks::value]
#[derive(Debug)]
pub struct DirectoryTree {
/// key is e.g. "dashboard", "(dashboard)", "@slot"
pub subdirectories: BTreeMap<RcStr, ResolvedVc<DirectoryTree>>,
pub modules: AppDirModules,
}
#[turbo_tasks::value]
#[derive(Clone, Debug)]
struct PlainDirectoryTree {
/// key is e.g. "dashboard", "(dashboard)", "@slot"
pub subdirectories: BTreeMap<RcStr, PlainDirectoryTree>,
pub modules: AppDirModules,
}
#[turbo_tasks::value_impl]
impl DirectoryTree {
#[turbo_tasks::function]
pub async fn into_plain(&self) -> Result<Vc<PlainDirectoryTree>> {
let mut subdirectories = BTreeMap::new();
for (name, subdirectory) in &self.subdirectories {
subdirectories.insert(name.clone(), subdirectory.into_plain().owned().await?);
}
Ok(PlainDirectoryTree {
subdirectories,
modules: self.modules.clone(),
}
.cell())
}
}
#[turbo_tasks::value(transparent)]
pub struct OptionAppDir(Option<FileSystemPath>);
/// Finds and returns the [DirectoryTree] of the app directory if existing.
#[turbo_tasks::function]
pub async fn find_app_dir(project_path: FileSystemPath) -> Result<Vc<OptionAppDir>> {
let app = project_path.join("app")?;
let src_app = project_path.join("src/app")?;
let app_dir = if *app.get_type().await? == FileSystemEntryType::Directory {
app
} else if *src_app.get_type().await? == FileSystemEntryType::Directory {
src_app
} else {
return Ok(Vc::cell(None));
};
Ok(Vc::cell(Some(app_dir)))
}
#[turbo_tasks::function]
async fn get_directory_tree(
dir: FileSystemPath,
page_extensions: Vc<Vec<RcStr>>,
) -> Result<Vc<DirectoryTree>> {
let span = {
let dir = dir.value_to_string().await?.to_string();
tracing::info_span!("read app directory tree", name = dir)
};
get_directory_tree_internal(dir, page_extensions)
.instrument(span)
.await
}
async fn get_directory_tree_internal(
dir: FileSystemPath,
page_extensions: Vc<Vec<RcStr>>,
) -> Result<Vc<DirectoryTree>> {
let DirectoryContent::Entries(entries) = &*dir.read_dir().await? else {
// the file watcher might invalidate things in the wrong order,
// and we have to account for the eventual consistency of turbo-tasks
// so we just return an empty tree here.
return Ok(DirectoryTree {
subdirectories: Default::default(),
modules: AppDirModules::default(),
}
.cell());
};
let page_extensions_value = page_extensions.await?;
let mut subdirectories = BTreeMap::new();
let mut modules = AppDirModules::default();
let mut metadata_icon = Vec::new();
let mut metadata_apple = Vec::new();
let mut metadata_open_graph = Vec::new();
let mut metadata_twitter = Vec::new();
for (basename, entry) in entries {
let entry = entry.clone().resolve_symlink().await?;
match entry {
DirectoryEntry::File(file) => {
// Do not process .d.ts files as routes
if basename.ends_with(".d.ts") {
continue;
}
if let Some((stem, ext)) = basename.split_once('.')
&& page_extensions_value.iter().any(|e| e == ext)
{
match stem {
"page" => modules.page = Some(file.clone()),
"layout" => modules.layout = Some(file.clone()),
"error" => modules.error = Some(file.clone()),
"global-error" => modules.global_error = Some(file.clone()),
"global-not-found" => modules.global_not_found = Some(file.clone()),
"loading" => modules.loading = Some(file.clone()),
"template" => modules.template = Some(file.clone()),
"forbidden" => modules.forbidden = Some(file.clone()),
"unauthorized" => modules.unauthorized = Some(file.clone()),
"not-found" => modules.not_found = Some(file.clone()),
"default" => modules.default = Some(file.clone()),
"route" => modules.route = Some(file.clone()),
_ => {}
}
}
let Some(MetadataFileMatch {
metadata_type,
number,
dynamic,
}) = match_local_metadata_file(basename.as_str(), &page_extensions_value)
else {
continue;
};
let entry = match metadata_type {
"icon" => &mut metadata_icon,
"apple-icon" => &mut metadata_apple,
"twitter-image" => &mut metadata_twitter,
"opengraph-image" => &mut metadata_open_graph,
"sitemap" => {
if dynamic {
modules.metadata.sitemap = Some(MetadataItem::Dynamic { path: file });
} else {
modules.metadata.sitemap = Some(MetadataItem::Static { path: file });
}
continue;
}
_ => continue,
};
if dynamic {
entry.push((number, MetadataWithAltItem::Dynamic { path: file }));
continue;
}
let file_name = file.file_name();
let basename = file_name
.rsplit_once('.')
.map_or(file_name, |(basename, _)| basename);
let alt_path = file.parent().join(&format!("{basename}.alt.txt"))?;
let alt_path = matches!(&*alt_path.get_type().await?, FileSystemEntryType::File)
.then_some(alt_path);
entry.push((
number,
MetadataWithAltItem::Static {
path: file,
alt_path,
},
));
}
DirectoryEntry::Directory(dir) => {
// appDir ignores paths starting with an underscore
if !basename.starts_with('_') {
let result = get_directory_tree(dir.clone(), page_extensions)
.to_resolved()
.await?;
subdirectories.insert(basename.clone(), result);
}
}
// TODO(WEB-952) handle symlinks in app dir
_ => {}
}
}
fn sort<T>(mut list: Vec<(Option<u32>, T)>) -> Vec<T> {
list.sort_by_key(|(num, _)| *num);
list.into_iter().map(|(_, item)| item).collect()
}
modules.metadata.icon = sort(metadata_icon);
modules.metadata.apple = sort(metadata_apple);
modules.metadata.twitter = sort(metadata_twitter);
modules.metadata.open_graph = sort(metadata_open_graph);
Ok(DirectoryTree {
subdirectories,
modules,
}
.cell())
}
#[turbo_tasks::value]
#[derive(Debug, Clone)]
pub struct AppPageLoaderTree {
pub page: AppPage,
pub segment: RcStr,
pub parallel_routes: FxIndexMap<RcStr, AppPageLoaderTree>,
pub modules: AppDirModules,
pub global_metadata: ResolvedVc<GlobalMetadata>,
}
impl AppPageLoaderTree {
/// Returns true if there's a page match in this loader tree.
pub fn has_page(&self) -> bool {
if &*self.segment == "__PAGE__" {
return true;
}
for (_, tree) in &self.parallel_routes {
if tree.has_page() {
return true;
}
}
false
}
/// Returns whether the only match in this tree is for a catch-all
/// route.
pub fn has_only_catchall(&self) -> bool {
if &*self.segment == "__PAGE__" && !self.page.is_catchall() {
return false;
}
for (_, tree) in &self.parallel_routes {
if !tree.has_only_catchall() {
return false;
}
}
true
}
/// Returns true if this loader tree contains an intercepting route match.
pub fn is_intercepting(&self) -> bool {
if self.page.is_intercepting() && self.has_page() {
return true;
}
for (_, tree) in &self.parallel_routes {
if tree.is_intercepting() {
return true;
}
}
false
}
/// Returns the specificity of the page (i.e. the number of segments
/// affecting the path)
pub fn get_specificity(&self) -> usize {
if &*self.segment == "__PAGE__" {
return AppPath::from(self.page.clone()).len();
}
let mut specificity = 0;
for (_, tree) in &self.parallel_routes {
specificity = specificity.max(tree.get_specificity());
}
specificity
}
}
#[turbo_tasks::value(transparent)]
pub struct FileSystemPathVec(Vec<FileSystemPath>);
#[turbo_tasks::value_impl]
impl ValueDefault for FileSystemPathVec {
#[turbo_tasks::function]
fn value_default() -> Vc<Self> {
Vc::cell(Vec::new())
}
}
#[derive(
Clone,
PartialEq,
Eq,
Hash,
Serialize,
Deserialize,
TraceRawVcs,
ValueDebugFormat,
Debug,
TaskInput,
NonLocalValue,
)]
pub enum Entrypoint {
AppPage {
pages: Vec<AppPage>,
loader_tree: ResolvedVc<AppPageLoaderTree>,
},
AppRoute {
page: AppPage,
path: FileSystemPath,
root_layouts: ResolvedVc<FileSystemPathVec>,
},
AppMetadata {
page: AppPage,
metadata: MetadataItem,
},
}
impl Entrypoint {
pub fn page(&self) -> &AppPage {
match self {
Entrypoint::AppPage { pages, .. } => pages.first().unwrap(),
Entrypoint::AppRoute { page, .. } => page,
Entrypoint::AppMetadata { page, .. } => page,
}
}
}
#[turbo_tasks::value(transparent)]
pub struct Entrypoints(FxIndexMap<AppPath, Entrypoint>);
fn is_parallel_route(name: &str) -> bool {
name.starts_with('@')
}
fn is_group_route(name: &str) -> bool {
name.starts_with('(') && name.ends_with(')')
}
fn match_parallel_route(name: &str) -> Option<&str> {
name.strip_prefix('@')
}
fn conflict_issue(
app_dir: FileSystemPath,
e: &'_ OccupiedEntry<'_, AppPath, Entrypoint>,
a: &str,
b: &str,
value_a: &AppPage,
value_b: &AppPage,
) {
let item_names = if a == b {
format!("{a}s")
} else {
format!("{a} and {b}")
};
DirectoryTreeIssue {
app_dir,
message: StyledString::Text(
format!(
"Conflicting {} at {}: {a} at {value_a} and {b} at {value_b}",
item_names,
e.key(),
)
.into(),
)
.resolved_cell(),
severity: IssueSeverity::Error,
}
.resolved_cell()
.emit();
}
fn add_app_page(
app_dir: FileSystemPath,
result: &mut FxIndexMap<AppPath, Entrypoint>,
page: AppPage,
loader_tree: ResolvedVc<AppPageLoaderTree>,
) {
let mut e = match result.entry(page.clone().into()) {
Entry::Occupied(e) => e,
Entry::Vacant(e) => {
e.insert(Entrypoint::AppPage {
pages: vec![page],
loader_tree,
});
return;
}
};
let conflict = |existing_name: &str, existing_page: &AppPage| {
conflict_issue(app_dir, &e, "page", existing_name, &page, existing_page);
};
let value = e.get();
match value {
Entrypoint::AppPage {
pages: existing_pages,
loader_tree: existing_loader_tree,
} => {
// loader trees should always match for the same path as they are generated by a
// turbo tasks function
if *existing_loader_tree != loader_tree {
conflict("page", existing_pages.first().unwrap());
}
let Entrypoint::AppPage {
pages: stored_pages,
..
} = e.get_mut()
else {
unreachable!("Entrypoint::AppPage was already matched");
};
stored_pages.push(page);
stored_pages.sort();
}
Entrypoint::AppRoute {
page: existing_page,
..
} => {
conflict("route", existing_page);
}
Entrypoint::AppMetadata {
page: existing_page,
..
} => {
conflict("metadata", existing_page);
}
}
}
fn add_app_route(
app_dir: FileSystemPath,
result: &mut FxIndexMap<AppPath, Entrypoint>,
page: AppPage,
path: FileSystemPath,
root_layouts: ResolvedVc<FileSystemPathVec>,
) {
let e = match result.entry(page.clone().into()) {
Entry::Occupied(e) => e,
Entry::Vacant(e) => {
e.insert(Entrypoint::AppRoute {
page,
path,
root_layouts,
});
return;
}
};
let conflict = |existing_name: &str, existing_page: &AppPage| {
conflict_issue(app_dir, &e, "route", existing_name, &page, existing_page);
};
let value = e.get();
match value {
Entrypoint::AppPage { pages, .. } => {
conflict("page", pages.first().unwrap());
}
Entrypoint::AppRoute {
page: existing_page,
..
} => {
conflict("route", existing_page);
}
Entrypoint::AppMetadata {
page: existing_page,
..
} => {
conflict("metadata", existing_page);
}
}
}
fn add_app_metadata_route(
app_dir: FileSystemPath,
result: &mut FxIndexMap<AppPath, Entrypoint>,
page: AppPage,
metadata: MetadataItem,
) {
let e = match result.entry(page.clone().into()) {
Entry::Occupied(e) => e,
Entry::Vacant(e) => {
e.insert(Entrypoint::AppMetadata { page, metadata });
return;
}
};
let conflict = |existing_name: &str, existing_page: &AppPage| {
conflict_issue(app_dir, &e, "metadata", existing_name, &page, existing_page);
};
let value = e.get();
match value {
Entrypoint::AppPage { pages, .. } => {
conflict("page", pages.first().unwrap());
}
Entrypoint::AppRoute {
page: existing_page,
..
} => {
conflict("route", existing_page);
}
Entrypoint::AppMetadata {
page: existing_page,
..
} => {
conflict("metadata", existing_page);
}
}
}
#[turbo_tasks::function]
pub fn get_entrypoints(
app_dir: FileSystemPath,
page_extensions: Vc<Vec<RcStr>>,
is_global_not_found_enabled: Vc<bool>,
) -> Vc<Entrypoints> {
directory_tree_to_entrypoints(
app_dir.clone(),
get_directory_tree(app_dir.clone(), page_extensions),
get_global_metadata(app_dir, page_extensions),
is_global_not_found_enabled,
Default::default(),
)
}
#[turbo_tasks::function]
fn directory_tree_to_entrypoints(
app_dir: FileSystemPath,
directory_tree: Vc<DirectoryTree>,
global_metadata: Vc<GlobalMetadata>,
is_global_not_found_enabled: Vc<bool>,
root_layouts: Vc<FileSystemPathVec>,
) -> Vc<Entrypoints> {
directory_tree_to_entrypoints_internal(
app_dir,
global_metadata,
is_global_not_found_enabled,
rcstr!(""),
directory_tree,
AppPage::new(),
root_layouts,
)
}
#[turbo_tasks::value]
struct DuplicateParallelRouteIssue {
app_dir: FileSystemPath,
previously_inserted_page: AppPage,
page: AppPage,
}
#[turbo_tasks::value_impl]
impl Issue for DuplicateParallelRouteIssue {
#[turbo_tasks::function]
fn file_path(&self) -> Result<Vc<FileSystemPath>> {
Ok(self.app_dir.join(&self.page.to_string())?.cell())
}
#[turbo_tasks::function]
fn stage(self: Vc<Self>) -> Vc<IssueStage> {
IssueStage::ProcessModule.cell()
}
#[turbo_tasks::function]
async fn title(self: Vc<Self>) -> Result<Vc<StyledString>> {
let this = self.await?;
Ok(StyledString::Text(
format!(
"You cannot have two parallel pages that resolve to the same path. Please check \
{} and {}.",
this.previously_inserted_page, this.page
)
.into(),
)
.cell())
}
}
fn page_path_except_parallel(loader_tree: &AppPageLoaderTree) -> Option<AppPage> {
if loader_tree.page.iter().any(|v| {
matches!(
v,
PageSegment::CatchAll(..)
| PageSegment::OptionalCatchAll(..)
| PageSegment::Parallel(..)
)
}) {
return None;
}
if loader_tree.modules.page.is_some() {
return Some(loader_tree.page.clone());
}
if let Some(children) = loader_tree.parallel_routes.get("children") {
return page_path_except_parallel(children);
}
None
}
async fn check_duplicate(
duplicate: &mut FxHashMap<AppPath, AppPage>,
loader_tree: &AppPageLoaderTree,
app_dir: FileSystemPath,
) -> Result<()> {
let page_path = page_path_except_parallel(loader_tree);
if let Some(page_path) = page_path
&& let Some(prev) = duplicate.insert(AppPath::from(page_path.clone()), page_path.clone())
&& prev != page_path
{
DuplicateParallelRouteIssue {
app_dir: app_dir.clone(),
previously_inserted_page: prev.clone(),
page: loader_tree.page.clone(),
}
.resolved_cell()
.emit();
}
Ok(())
}
#[turbo_tasks::value(transparent)]
struct AppPageLoaderTreeOption(Option<ResolvedVc<AppPageLoaderTree>>);
/// creates the loader tree for a specific route (pathname / [AppPath])
#[turbo_tasks::function]
async fn directory_tree_to_loader_tree(
app_dir: FileSystemPath,
global_metadata: Vc<GlobalMetadata>,
directory_name: RcStr,
directory_tree: Vc<DirectoryTree>,
app_page: AppPage,
// the page this loader tree is constructed for
for_app_path: AppPath,
) -> Result<Vc<AppPageLoaderTreeOption>> {
let plain_tree = &*directory_tree.into_plain().await?;
let tree = directory_tree_to_loader_tree_internal(
app_dir,
global_metadata,
directory_name,
plain_tree,
app_page,
for_app_path,
AppDirModules::default(),
)
.await?;
Ok(Vc::cell(tree.map(AppPageLoaderTree::resolved_cell)))
}
/// Checks the current module if it needs to be updated with the default page.
/// If the module is already set, update the parent module to the same value.
/// If the parent module is set and module is not set, set the module to the parent module.
/// If the module and the parent module are not set, set them to the default value.
///
/// # Arguments
/// * `app_dir` - The application directory.
/// * `module` - The current module to check and update if it is not set.
/// * `parent_module` - The parent module to update if the current module is set or both are not
/// set.
/// * `file_path` - The file path to the default page if neither the current module nor the parent
/// module is set.
async fn check_and_update_module_references(
app_dir: FileSystemPath,
module: &mut Option<FileSystemPath>,
parent_module: &mut Option<FileSystemPath>,
file_path: &str,
) -> Result<()> {
match (module.as_mut(), parent_module.as_mut()) {
(Some(module), _) => *parent_module = Some(module.clone()),
(None, Some(parent_module)) => *module = Some(parent_module.clone()),
(None, None) => {
let default_page = get_next_package(app_dir.clone()).await?.join(file_path)?;
*module = Some(default_page.clone());
*parent_module = Some(default_page);
}
}
Ok(())
}
async fn directory_tree_to_loader_tree_internal(
app_dir: FileSystemPath,
global_metadata: Vc<GlobalMetadata>,
directory_name: RcStr,
directory_tree: &PlainDirectoryTree,
app_page: AppPage,
// the page this loader tree is constructed for
for_app_path: AppPath,
mut parent_modules: AppDirModules,
) -> Result<Option<AppPageLoaderTree>> {
let app_path = AppPath::from(app_page.clone());
if !for_app_path.contains(&app_path) {
return Ok(None);
}
let mut modules = directory_tree.modules.clone();
// Capture the current page for the metadata to calculate segment relative to
// the corresponding page for the static metadata files.
modules.metadata.base_page = Some(app_page.clone());
// the root directory in the app dir.
let is_root_directory = app_page.is_root();
// an alternative root layout (in a route group which affects the page, but not
// the path).
let is_root_layout = app_path.is_root() && modules.layout.is_some();
if is_root_directory || is_root_layout {
check_and_update_module_references(
app_dir.clone(),
&mut modules.not_found,
&mut parent_modules.not_found,
"dist/client/components/builtin/not-found.js",
)
.await?;
check_and_update_module_references(
app_dir.clone(),
&mut modules.forbidden,
&mut parent_modules.forbidden,
"dist/client/components/builtin/forbidden.js",
)
.await?;
check_and_update_module_references(
app_dir.clone(),
&mut modules.unauthorized,
&mut parent_modules.unauthorized,
"dist/client/components/builtin/unauthorized.js",
)
.await?;
check_and_update_module_references(
app_dir.clone(),
&mut modules.global_error,
&mut parent_modules.global_error,
"dist/client/components/builtin/global-error.js",
)
.await?;
}
let mut tree = AppPageLoaderTree {
page: app_page.clone(),
segment: directory_name.clone(),
parallel_routes: FxIndexMap::default(),
modules: modules.without_leaves(),
global_metadata: global_metadata.to_resolved().await?,
};
let current_level_is_parallel_route = is_parallel_route(&directory_name);
if current_level_is_parallel_route {
tree.segment = rcstr!("children");
}
if let Some(page) = (app_path == for_app_path || app_path.is_catchall())
.then_some(modules.page)
.flatten()
{
tree.parallel_routes.insert(
rcstr!("children"),
AppPageLoaderTree {
page: app_page.clone(),
segment: rcstr!("__PAGE__"),
parallel_routes: FxIndexMap::default(),
modules: AppDirModules {
page: Some(page),
metadata: modules.metadata,
..Default::default()
},
global_metadata: global_metadata.to_resolved().await?,
},
);
if current_level_is_parallel_route {
tree.segment = rcstr!("page$");
}
}
let mut duplicate = FxHashMap::default();
for (subdir_name, subdirectory) in &directory_tree.subdirectories {
let parallel_route_key = match_parallel_route(subdir_name);
let mut child_app_page = app_page.clone();
let mut illegal_path_error = None;
// When constructing the app_page fails (e. g. due to limitations of the order),
// we only want to emit the error when there are actual pages below that
// directory.
if let Err(e) = child_app_page.push_str(&normalize_underscore(subdir_name)) {
illegal_path_error = Some(e);
}
let subtree = Box::pin(directory_tree_to_loader_tree_internal(
app_dir.clone(),
global_metadata,
subdir_name.clone(),
subdirectory,
child_app_page.clone(),
for_app_path.clone(),
parent_modules.clone(),
))
.await?;
if let Some(illegal_path) = subtree.as_ref().and(illegal_path_error) {
return Err(illegal_path);
}
if let Some(subtree) = subtree {
if let Some(key) = parallel_route_key {
tree.parallel_routes.insert(key.into(), subtree);
continue;
}
// skip groups which don't have a page match.
if is_group_route(subdir_name) && !subtree.has_page() {
continue;
}
if subtree.has_page() {
check_duplicate(&mut duplicate, &subtree, app_dir.clone()).await?;
}
if let Some(current_tree) = tree.parallel_routes.get("children") {
if current_tree.has_only_catchall()
&& (!subtree.has_only_catchall()
|| current_tree.get_specificity() < subtree.get_specificity())
{
tree.parallel_routes
.insert(rcstr!("children"), subtree.clone());
}
} else {
tree.parallel_routes.insert(rcstr!("children"), subtree);
}
} else if let Some(key) = parallel_route_key {
bail!(
"missing page or default for parallel route `{}` (page: {})",
key,
app_page
);
}
}
// make sure we don't have a match for other slots if there's an intercepting route match
// we only check subtrees as the current level could trigger `is_intercepting`
if tree
.parallel_routes
.iter()
.any(|(_, parallel_tree)| parallel_tree.is_intercepting())
{
let mut keys_to_replace = Vec::new();
for (key, parallel_tree) in &tree.parallel_routes {
if !parallel_tree.is_intercepting() {
keys_to_replace.push(key.clone());
}
}
for key in keys_to_replace {
let subdir_name: RcStr = format!("@{key}").into();
let default = if key == "children" {
modules.default.clone()
} else if let Some(subdirectory) = directory_tree.subdirectories.get(&subdir_name) {
subdirectory.modules.default.clone()
} else {
None
};
tree.parallel_routes.insert(
key,
default_route_tree(app_dir.clone(), global_metadata, app_page.clone(), default)
.await?,
);
}
}
if tree.parallel_routes.is_empty() {
if modules.default.is_some() || current_level_is_parallel_route {
tree = default_route_tree(
app_dir.clone(),
global_metadata,
app_page,
modules.default.clone(),
)
.await?;
} else {
return Ok(None);
}
} else if tree.parallel_routes.get("children").is_none() {
tree.parallel_routes.insert(
rcstr!("children"),
default_route_tree(
app_dir.clone(),
global_metadata,
app_page,
modules.default.clone(),
)
.await?,
);
}
if tree.parallel_routes.len() > 1
&& tree.parallel_routes.keys().next().map(|s| s.as_str()) != Some("children")
{
// children must go first for next.js to work correctly
tree.parallel_routes
.move_index(tree.parallel_routes.len() - 1, 0);
}
Ok(Some(tree))
}
async fn default_route_tree(
app_dir: FileSystemPath,
global_metadata: Vc<GlobalMetadata>,
app_page: AppPage,
default_component: Option<FileSystemPath>,
) -> Result<AppPageLoaderTree> {
Ok(AppPageLoaderTree {
page: app_page.clone(),
segment: rcstr!("__DEFAULT__"),
parallel_routes: FxIndexMap::default(),
modules: if let Some(default) = default_component {
AppDirModules {
default: Some(default),
..Default::default()
}
} else {
// default fallback component
AppDirModules {
default: Some(
get_next_package(app_dir)
.await?
.join("dist/client/components/builtin/default.js")?,
),
..Default::default()
}
},
global_metadata: global_metadata.to_resolved().await?,
})
}
#[turbo_tasks::function]
async fn directory_tree_to_entrypoints_internal(
app_dir: FileSystemPath,
global_metadata: ResolvedVc<GlobalMetadata>,
is_global_not_found_enabled: Vc<bool>,
directory_name: RcStr,
directory_tree: Vc<DirectoryTree>,
app_page: AppPage,
root_layouts: ResolvedVc<FileSystemPathVec>,
) -> Result<Vc<Entrypoints>> {
let span = tracing::info_span!("build layout trees", name = display(&app_page));
directory_tree_to_entrypoints_internal_untraced(
app_dir,
global_metadata,
is_global_not_found_enabled,
directory_name,
directory_tree,
app_page,
root_layouts,
)
.instrument(span)
.await
}
async fn directory_tree_to_entrypoints_internal_untraced(
app_dir: FileSystemPath,
global_metadata: ResolvedVc<GlobalMetadata>,
is_global_not_found_enabled: Vc<bool>,
directory_name: RcStr,
directory_tree: Vc<DirectoryTree>,
app_page: AppPage,
root_layouts: ResolvedVc<FileSystemPathVec>,
) -> Result<Vc<Entrypoints>> {
let mut result = FxIndexMap::default();
let directory_tree_vc = directory_tree;
let directory_tree = &*directory_tree.await?;
let subdirectories = &directory_tree.subdirectories;
let modules = &directory_tree.modules;
// Route can have its own segment config, also can inherit from the layout root
// segment config. https://nextjs.org/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes#segment-runtime-option
// Pass down layouts from each tree to apply segment config when adding route.
let root_layouts = if let Some(layout) = &modules.layout {
let mut layouts = root_layouts.owned().await?;
layouts.push(layout.clone());
ResolvedVc::cell(layouts)
} else {
root_layouts
};
if modules.page.is_some() {
let app_path = AppPath::from(app_page.clone());
let loader_tree = *directory_tree_to_loader_tree(
app_dir.clone(),
*global_metadata,
directory_name.clone(),
directory_tree_vc,
app_page.clone(),
app_path,
)
.await?;
add_app_page(
app_dir.clone(),
&mut result,
app_page.complete(PageType::Page)?,
loader_tree.context("loader tree should be created for a page/default")?,
);
}
if let Some(route) = &modules.route {
add_app_route(
app_dir.clone(),
&mut result,
app_page.complete(PageType::Route)?,
route.clone(),
root_layouts,
);
}
let Metadata {
icon,
apple,
twitter,
open_graph,
sitemap,
base_page: _,
} = &modules.metadata;
for meta in sitemap
.iter()
.cloned()
.chain(icon.iter().cloned().map(MetadataItem::from))
.chain(apple.iter().cloned().map(MetadataItem::from))
.chain(twitter.iter().cloned().map(MetadataItem::from))
.chain(open_graph.iter().cloned().map(MetadataItem::from))
{
let app_page = app_page.clone_push_str(&get_metadata_route_name(meta.clone()).await?)?;
add_app_metadata_route(
app_dir.clone(),
&mut result,
normalize_metadata_route(app_page)?,
meta,
);
}
// root path: /
if app_page.is_root() {
let GlobalMetadata {
favicon,
robots,
manifest,
} = &*global_metadata.await?;
for meta in favicon.iter().chain(robots.iter()).chain(manifest.iter()) {
let app_page =
app_page.clone_push_str(&get_metadata_route_name(meta.clone()).await?)?;
add_app_metadata_route(
app_dir.clone(),
&mut result,
normalize_metadata_route(app_page)?,
meta.clone(),
);
}
let mut modules = directory_tree.modules.clone();
// fill in the default modules for the not-found entrypoint
if modules.layout.is_none() {
modules.layout = Some(
get_next_package(app_dir.clone())
.await?
.join("dist/client/components/builtin/layout.js")?,
);
}
if modules.not_found.is_none() {
modules.not_found = Some(
get_next_package(app_dir.clone())
.await?
.join("dist/client/components/builtin/not-found.js")?,
);
}
if modules.forbidden.is_none() {
modules.forbidden = Some(
get_next_package(app_dir.clone())
.await?
.join("dist/client/components/builtin/forbidden.js")?,
);
}
if modules.unauthorized.is_none() {
modules.unauthorized = Some(
get_next_package(app_dir.clone())
.await?
.join("dist/client/components/builtin/unauthorized.js")?,
);
}
// Next.js has this logic in "collect-app-paths", where the root not-found page
// is considered as its own entry point.
// Determine if we enable the global not-found feature.
let is_global_not_found_enabled = *is_global_not_found_enabled.await?;
let use_global_not_found =
is_global_not_found_enabled || modules.global_not_found.is_some();
let not_found_root_modules = modules.without_leaves();
let not_found_tree = AppPageLoaderTree {
page: app_page.clone(),
segment: directory_name.clone(),
parallel_routes: fxindexmap! {
rcstr!("children") => AppPageLoaderTree {
page: app_page.clone(),
segment: rcstr!("/_not-found"),
parallel_routes: fxindexmap! {
rcstr!("children") => AppPageLoaderTree {
page: app_page.clone(),
segment: rcstr!("__PAGE__"),
parallel_routes: FxIndexMap::default(),
modules: if use_global_not_found {
// if global-not-found.js is present:
// we use it for the page and no layout, since layout is included in global-not-found.js;
AppDirModules {
layout: None,
page: match modules.global_not_found {
Some(v) => Some(v),
None => Some(get_next_package(app_dir.clone())
.await?
.join("dist/client/components/builtin/global-not-found.js")?,
),
},
..Default::default()
}
} else {
// if global-not-found.js is not present:
// we search if we can compose root layout with the root not-found.js;
AppDirModules {
page: match modules.not_found {
Some(v) => Some(v),
None => Some(get_next_package(app_dir.clone())
.await?
.join("dist/client/components/builtin/not-found.js")?,
),
},
..Default::default()
}
},
global_metadata,
}
},
modules: AppDirModules {
..Default::default()
},
global_metadata,
},
},
modules: AppDirModules {
// `global-not-found.js` does not need a layout since it's included.
// Skip it if it's present.
// Otherwise, we need to compose it with the root layout to compose with
// not-found.js boundary.
layout: if use_global_not_found {
None
} else {
modules.layout
},
..not_found_root_modules
},
global_metadata,
}
.resolved_cell();
{
let app_page = app_page
.clone_push_str("_not-found")?
.complete(PageType::Page)?;
add_app_page(app_dir.clone(), &mut result, app_page, not_found_tree);
}
}
let app_page = &app_page;
let directory_name = &directory_name;
let subdirectories = subdirectories
.iter()
.map(|(subdir_name, &subdirectory)| {
let app_dir = app_dir.clone();
async move {
let mut child_app_page = app_page.clone();
let mut illegal_path = None;
// When constructing the app_page fails (e. g. due to limitations of the order),
// we only want to emit the error when there are actual pages below that
// directory.
if let Err(e) = child_app_page.push_str(&normalize_underscore(subdir_name)) {
illegal_path = Some(e);
}
let map = directory_tree_to_entrypoints_internal(
app_dir.clone(),
*global_metadata,
is_global_not_found_enabled,
subdir_name.clone(),
*subdirectory,
child_app_page.clone(),
*root_layouts,
)
.await?;
if let Some(illegal_path) = illegal_path
&& !map.is_empty()
{
return Err(illegal_path);
}
let mut loader_trees = Vec::new();
for (_, entrypoint) in map.iter() {
if let Entrypoint::AppPage {
ref pages,
loader_tree: _,
} = *entrypoint
{
for page in pages {
let app_path = AppPath::from(page.clone());
let loader_tree = directory_tree_to_loader_tree(
app_dir.clone(),
*global_metadata,
directory_name.clone(),
directory_tree_vc,
app_page.clone(),
app_path,
);
loader_trees.push(loader_tree);
}
}
}
Ok((map, loader_trees))
}
})
.try_join()
.await?;
for (map, loader_trees) in subdirectories.iter() {
let mut i = 0;
for (_, entrypoint) in map.iter() {
match entrypoint {
Entrypoint::AppPage {
pages,
loader_tree: _,
} => {
for page in pages {
let loader_tree = *loader_trees[i].await?;
i += 1;
add_app_page(
app_dir.clone(),
&mut result,
page.clone(),
loader_tree
.context("loader tree should be created for a page/default")?,
);
}
}
Entrypoint::AppRoute {
page,
path,
root_layouts,
} => {
add_app_route(
app_dir.clone(),
&mut result,
page.clone(),
path.clone(),
*root_layouts,
);
}
Entrypoint::AppMetadata { page, metadata } => {
add_app_metadata_route(
app_dir.clone(),
&mut result,
page.clone(),
metadata.clone(),
);
}
}
}
}
Ok(Vc::cell(result))
}
/// Returns the global metadata for an app directory.
#[turbo_tasks::function]
pub async fn get_global_metadata(
app_dir: FileSystemPath,
page_extensions: Vc<Vec<RcStr>>,
) -> Result<Vc<GlobalMetadata>> {
let DirectoryContent::Entries(entries) = &*app_dir.read_dir().await? else {
bail!("app_dir must be a directory")
};
let mut metadata = GlobalMetadata::default();
for (basename, entry) in entries {
let DirectoryEntry::File(file) = entry else {
continue;
};
let Some(GlobalMetadataFileMatch {
metadata_type,
dynamic,
}) = match_global_metadata_file(basename, &page_extensions.await?)
else {
continue;
};
let entry = match metadata_type {
"favicon" => &mut metadata.favicon,
"manifest" => &mut metadata.manifest,
"robots" => &mut metadata.robots,
_ => continue,
};
if dynamic {
*entry = Some(MetadataItem::Dynamic { path: file.clone() });
} else {
*entry = Some(MetadataItem::Static { path: file.clone() });
}
// TODO(WEB-952) handle symlinks in app dir
}
Ok(metadata.cell())
}
#[turbo_tasks::value(shared)]
struct DirectoryTreeIssue {
pub severity: IssueSeverity,
pub app_dir: FileSystemPath,
pub message: ResolvedVc<StyledString>,
}
#[turbo_tasks::value_impl]
impl Issue for DirectoryTreeIssue {
fn severity(&self) -> IssueSeverity {
self.severity
}
#[turbo_tasks::function]
fn title(&self) -> Vc<StyledString> {
StyledString::Text(rcstr!("An issue occurred while preparing your Next.js app")).cell()
}
#[turbo_tasks::function]
fn stage(&self) -> Vc<IssueStage> {
IssueStage::AppStructure.cell()
}
#[turbo_tasks::function]
fn file_path(&self) -> Vc<FileSystemPath> {
self.app_dir.clone().cell()
}
#[turbo_tasks::function]
fn description(&self) -> Vc<OptionStyledString> {
Vc::cell(Some(self.message))
}
}
|