Unverified Commit b50ecb7e authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

add support for static implicit metadata in turbopack (#48823)

### What?

* support local static metadata files; opengraph-image, twitter-image,
favicon, manifest, icon, apple-icon
* support global static metadata files: robots.txt, sitemap.xml,
favicon.ico
* dynamic metadata is not yet implemented, but yields a warning

It's implemented a bit different compared to the webpack version.
All images will use the usual image machinery, so they are emitted to
output directory, content hashed and the url is shared with the same
import import in the app.

### Why?

Unsupported, and we want to have that.

### How?

see also https://github.com/vercel/turbo/pull/4692

fixes WEB-524
parent 0cfa3fce
......@@ -8,7 +8,7 @@ use napi::{
};
use next_core::app_structure::{
find_app_dir, get_entrypoints as get_entrypoints_impl, Components, ComponentsVc, Entrypoint,
EntrypointsVc, LoaderTree, LoaderTreeVc,
EntrypointsVc, LoaderTree, LoaderTreeVc, MetadataWithAltItem,
};
use serde::{Deserialize, Serialize};
use turbo_binding::{
......@@ -41,7 +41,8 @@ async fn project_fs(project_dir: &str, watching: bool) -> Result<FileSystemVc> {
struct LoaderTreeForJs {
segment: String,
parallel_routes: HashMap<String, LoaderTreeForJsReadRef>,
components: serde_json::Value,
#[turbo_tasks(trace_ignore)]
components: ComponentsForJs,
}
#[derive(PartialEq, Eq, Serialize, Deserialize, ValueDebugFormat, TraceRawVcs)]
......@@ -69,10 +70,57 @@ async fn fs_path_to_path(project_path: FileSystemPathVc, path: FileSystemPathVc)
}
}
#[derive(Default, Deserialize, Serialize, PartialEq, Eq, ValueDebugFormat)]
#[serde(rename_all = "camelCase")]
struct ComponentsForJs {
#[serde(skip_serializing_if = "Option::is_none")]
page: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
layout: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
error: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
loading: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
template: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
default: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
route: Option<String>,
metadata: MetadataForJs,
}
#[derive(Default, Deserialize, Serialize, PartialEq, Eq, ValueDebugFormat)]
#[serde(rename_all = "camelCase")]
struct MetadataForJs {
#[serde(skip_serializing_if = "Vec::is_empty")]
icon: Vec<MetadataForJsItem>,
#[serde(skip_serializing_if = "Vec::is_empty")]
apple: Vec<MetadataForJsItem>,
#[serde(skip_serializing_if = "Vec::is_empty")]
twitter: Vec<MetadataForJsItem>,
#[serde(skip_serializing_if = "Vec::is_empty")]
open_graph: Vec<MetadataForJsItem>,
#[serde(skip_serializing_if = "Vec::is_empty")]
favicon: Vec<MetadataForJsItem>,
}
#[derive(Deserialize, Serialize, PartialEq, Eq, ValueDebugFormat)]
#[serde(tag = "type", rename_all = "camelCase")]
enum MetadataForJsItem {
Static {
path: String,
alt_path: Option<String>,
},
Dynamic {
path: String,
},
}
async fn prepare_components_for_js(
project_path: FileSystemPathVc,
components: ComponentsVc,
) -> Result<serde_json::Value> {
) -> Result<ComponentsForJs> {
let Components {
page,
layout,
......@@ -83,59 +131,66 @@ async fn prepare_components_for_js(
route,
metadata,
} = &*components.await?;
let mut map = serde_json::value::Map::new();
let mut result = ComponentsForJs::default();
async fn add(
map: &mut serde_json::value::Map<String, serde_json::Value>,
result: &mut Option<String>,
project_path: FileSystemPathVc,
key: &str,
value: &Option<FileSystemPathVc>,
) -> Result<()> {
if let Some(value) = value {
map.insert(
key.to_string(),
fs_path_to_path(project_path, *value).await?.into(),
);
*result = Some(fs_path_to_path(project_path, *value).await?);
}
Ok::<_, anyhow::Error>(())
}
add(&mut map, project_path, "page", page).await?;
add(&mut map, project_path, "layout", layout).await?;
add(&mut map, project_path, "error", error).await?;
add(&mut map, project_path, "loading", loading).await?;
add(&mut map, project_path, "template", template).await?;
add(&mut map, project_path, "default", default).await?;
add(&mut map, project_path, "route", route).await?;
let mut meta = serde_json::value::Map::new();
async fn add_meta(
meta: &mut serde_json::value::Map<String, serde_json::Value>,
add(&mut result.page, project_path, page).await?;
add(&mut result.layout, project_path, layout).await?;
add(&mut result.error, project_path, error).await?;
add(&mut result.loading, project_path, loading).await?;
add(&mut result.template, project_path, template).await?;
add(&mut result.default, project_path, default).await?;
add(&mut result.route, project_path, route).await?;
async fn add_meta<'a>(
meta: &mut Vec<MetadataForJsItem>,
project_path: FileSystemPathVc,
key: &str,
value: &Vec<FileSystemPathVc>,
value: impl Iterator<Item = &'a MetadataWithAltItem>,
) -> Result<()> {
if !value.is_empty() {
meta.insert(
key.to_string(),
value
.iter()
let mut value = value.peekable();
if value.peek().is_some() {
*meta = value
.map(|value| async move {
Ok(serde_json::Value::from(
fs_path_to_path(project_path, *value).await?,
))
Ok(match value {
MetadataWithAltItem::Static { path, alt_path } => {
let path = fs_path_to_path(project_path, *path).await?;
let alt_path = if let Some(alt_path) = alt_path {
Some(fs_path_to_path(project_path, *alt_path).await?)
} else {
None
};
MetadataForJsItem::Static { path, alt_path }
}
MetadataWithAltItem::Dynamic { path } => {
let path = fs_path_to_path(project_path, *path).await?;
MetadataForJsItem::Dynamic { path }
}
})
})
.try_join()
.await?
.into(),
);
.await?;
}
Ok::<_, anyhow::Error>(())
}
add_meta(&mut meta, project_path, "icon", &metadata.icon).await?;
add_meta(&mut meta, project_path, "apple", &metadata.apple).await?;
add_meta(&mut meta, project_path, "twitter", &metadata.twitter).await?;
add_meta(&mut meta, project_path, "openGraph", &metadata.open_graph).await?;
add_meta(&mut meta, project_path, "favicon", &metadata.favicon).await?;
map.insert("metadata".to_string(), meta.into());
Ok(map.into())
let meta = &mut result.metadata;
add_meta(&mut meta.icon, project_path, metadata.icon.iter()).await?;
add_meta(&mut meta.apple, project_path, metadata.apple.iter()).await?;
add_meta(&mut meta.twitter, project_path, metadata.twitter.iter()).await?;
add_meta(
&mut meta.open_graph,
project_path,
metadata.open_graph.iter(),
)
.await?;
add_meta(&mut meta.favicon, project_path, metadata.favicon.iter()).await?;
Ok(result)
}
#[tasks::function]
......
use std::{collections::HashMap, io::Write};
use std::{collections::HashMap, io::Write, iter::once};
use anyhow::Result;
use async_recursion::async_recursion;
......@@ -30,6 +30,7 @@ use turbo_binding::{
dev_server::{
html::DevHtmlAssetVc,
source::{
asset_graph::AssetGraphContentSourceVc,
combined::CombinedContentSource,
specificity::{Specificity, SpecificityElementType, SpecificityVc},
ContentSourceData, ContentSourceVc, NoContentSourceVc,
......@@ -37,6 +38,7 @@ use turbo_binding::{
},
ecmascript::{
magic_identifier,
text::TextContentSourceAssetVc,
utils::{FormatIter, StringifyJs},
EcmascriptInputTransformsVc, EcmascriptModuleAssetType, EcmascriptModuleAssetVc,
InnerAssetsVc,
......@@ -50,6 +52,7 @@ use turbo_binding::{
},
NodeEntry, NodeEntryVc, NodeRenderingEntry, NodeRenderingEntryVc,
},
r#static::{fixed::FixedStaticAssetVc, StaticModuleAssetVc},
turbopack::{
ecmascript::EcmascriptInputTransform,
transition::{TransitionVc, TransitionsByNameVc},
......@@ -62,8 +65,10 @@ use turbo_tasks::{TryJoinIterExt, ValueToString};
use crate::{
app_render::next_layout_entry_transition::NextServerComponentTransition,
app_structure::{
get_entrypoints, Components, Entrypoint, LoaderTree, LoaderTreeVc, Metadata, OptionAppDirVc,
get_entrypoints, get_global_metadata, Components, Entrypoint, GlobalMetadataVc, LoaderTree,
LoaderTreeVc, Metadata, MetadataItem, MetadataWithAltItem, OptionAppDirVc,
},
asset_helpers::as_es_module_asset,
embed_js::{next_js_file, next_js_file_path},
env::env_for_js,
fallback::get_fallback_page,
......@@ -85,6 +90,7 @@ use crate::{
context::{get_edge_compile_time_info, get_edge_resolve_options_context},
transition::NextEdgeTransition,
},
next_image::module::StructuredImageModuleType,
next_route_matcher::NextParamsMatcherVc,
next_server::context::{
get_server_compile_time_info, get_server_module_options_context,
......@@ -370,6 +376,7 @@ pub async fn create_app_source(
return Ok(NoContentSourceVc::new().into());
};
let entrypoints = get_entrypoints(app_dir, next_config.page_extensions());
let metadata = get_global_metadata(app_dir, next_config.page_extensions());
let client_compile_time_info = get_client_compile_time_info(browserslist_query);
......@@ -444,11 +451,58 @@ pub async fn create_app_source(
output_path,
),
})
.chain(once(create_global_metadata_source(
app_dir,
metadata,
server_root,
)))
.collect();
Ok(CombinedContentSource { sources }.cell().into())
}
#[turbo_tasks::function]
async fn create_global_metadata_source(
app_dir: FileSystemPathVc,
metadata: GlobalMetadataVc,
server_root: FileSystemPathVc,
) -> Result<ContentSourceVc> {
let metadata = metadata.await?;
let mut unsupported_metadata = Vec::new();
let mut sources = Vec::new();
for (server_path, item) in [
("robots.txt", metadata.robots),
("favicon.ico", metadata.favicon),
("sitemap.xml", metadata.sitemap),
] {
let Some(item) = item else {
continue;
};
match item {
MetadataItem::Static { path } => {
let asset = FixedStaticAssetVc::new(
server_root.join(server_path),
SourceAssetVc::new(path).into(),
);
sources.push(AssetGraphContentSourceVc::new_eager(server_root, asset.into()).into())
}
MetadataItem::Dynamic { path } => {
unsupported_metadata.push(path);
}
}
}
if !unsupported_metadata.is_empty() {
UnsupportedDynamicMetadataIssue {
app_dir,
files: unsupported_metadata,
}
.cell()
.as_issue()
.emit();
}
Ok(CombinedContentSource { sources }.cell().into())
}
#[allow(clippy::too_many_arguments)]
#[turbo_tasks::function]
async fn create_app_page_source_for_route(
......@@ -576,6 +630,14 @@ impl AppRendererVc {
unsupported_metadata: Vec<FileSystemPathVc>,
}
impl State {
fn unique_number(&mut self) -> usize {
let i = self.counter;
self.counter += 1;
i
}
}
let mut state = State {
inner_assets: IndexMap::new(),
counter: 0,
......@@ -593,8 +655,7 @@ impl AppRendererVc {
use std::fmt::Write;
if let Some(component) = component {
let i = state.counter;
state.counter += 1;
let i = state.unique_number();
let identifier = magic_identifier::mangle(&format!("{name} #{i}"));
let chunks_identifier = magic_identifier::mangle(&format!("chunks of {name} #{i}"));
writeln!(
......@@ -622,11 +683,137 @@ import {}, {{ chunks as {} }} from "COMPONENT_{}";
Ok(())
}
fn emit_metadata_warning(state: &mut State, files: &[FileSystemPathVc]) {
for file in files {
state.unsupported_metadata.push(*file);
fn write_metadata(state: &mut State, metadata: &Metadata) -> Result<()> {
if metadata.is_empty() {
return Ok(());
}
let Metadata {
icon,
apple,
twitter,
open_graph,
favicon,
manifest,
} = metadata;
state.loader_tree_code += " metadata: {";
write_metadata_items(state, "icon", favicon.iter().chain(icon.iter()))?;
write_metadata_items(state, "apple", apple.iter())?;
write_metadata_items(state, "twitter", twitter.iter())?;
write_metadata_items(state, "openGraph", open_graph.iter())?;
write_metadata_manifest(state, *manifest)?;
state.loader_tree_code += " },";
Ok(())
}
fn write_metadata_manifest(
state: &mut State,
manifest: Option<MetadataItem>,
) -> Result<()> {
let Some(manifest) = manifest else {
return Ok(());
};
match manifest {
MetadataItem::Static { path } => {
use std::fmt::Write;
let i = state.unique_number();
let identifier = magic_identifier::mangle(&format!("manifest #{i}"));
let inner_module_id = format!("METADATA_{i}");
state
.imports
.push(format!("import {identifier} from \"{inner_module_id}\";"));
state.inner_assets.insert(
inner_module_id,
StaticModuleAssetVc::new(SourceAssetVc::new(path).into(), state.context)
.into(),
);
writeln!(state.loader_tree_code, " manifest: {identifier},")?;
}
MetadataItem::Dynamic { path } => {
state.unsupported_metadata.push(path);
}
}
Ok(())
}
fn write_metadata_items<'a>(
state: &mut State,
name: &str,
it: impl Iterator<Item = &'a MetadataWithAltItem>,
) -> Result<()> {
use std::fmt::Write;
let mut it = it.peekable();
if it.peek().is_none() {
return Ok(());
}
writeln!(state.loader_tree_code, " {name}: [")?;
for item in it {
write_metadata_item(state, name, item)?;
}
writeln!(state.loader_tree_code, " ],")?;
Ok(())
}
fn write_metadata_item(
state: &mut State,
name: &str,
item: &MetadataWithAltItem,
) -> Result<()> {
use std::fmt::Write;
let i = state.unique_number();
let identifier = magic_identifier::mangle(&format!("{name} #{i}"));
let inner_module_id = format!("METADATA_{i}");
state
.imports
.push(format!("import {identifier} from \"{inner_module_id}\";"));
let s = " ";
match item {
MetadataWithAltItem::Static { path, alt_path } => {
state.inner_assets.insert(
inner_module_id,
StructuredImageModuleType::create_module(
SourceAssetVc::new(*path).into(),
state.context,
)
.into(),
);
writeln!(state.loader_tree_code, "{s}(async (props) => [{{")?;
writeln!(state.loader_tree_code, "{s} url: {identifier}.src,")?;
let numeric_sizes = name == "twitter" || name == "openGraph";
if numeric_sizes {
writeln!(state.loader_tree_code, "{s} width: {identifier}.width,")?;
writeln!(state.loader_tree_code, "{s} height: {identifier}.height,")?;
} else {
writeln!(
state.loader_tree_code,
"{s} sizes: `${{{identifier}.width}}x${{{identifier}.height}}`,"
)?;
}
if let Some(alt_path) = alt_path {
let identifier = magic_identifier::mangle(&format!("{name} alt text #{i}"));
let inner_module_id = format!("METADATA_ALT_{i}");
state
.imports
.push(format!("import {identifier} from \"{inner_module_id}\";"));
state.inner_assets.insert(
inner_module_id,
as_es_module_asset(
TextContentSourceAssetVc::new(SourceAssetVc::new(*alt_path).into())
.into(),
state.context,
)
.into(),
);
writeln!(state.loader_tree_code, "{s} alt: {identifier},")?;
}
writeln!(state.loader_tree_code, "{s}}}]),")?;
}
MetadataWithAltItem::Dynamic { path, .. } => {
state.unsupported_metadata.push(*path);
}
}
Ok(())
}
#[async_recursion]
async fn walk_tree(state: &mut State, loader_tree: LoaderTreeVc) -> Result<()> {
......@@ -658,14 +845,7 @@ import {}, {{ chunks as {} }} from "COMPONENT_{}";
layout,
loading,
template,
metadata:
Metadata {
icon,
apple,
twitter,
open_graph,
favicon,
},
metadata,
route: _,
} = &*components.await?;
write_component(state, "page", *page)?;
......@@ -674,12 +854,7 @@ import {}, {{ chunks as {} }} from "COMPONENT_{}";
write_component(state, "layout", *layout)?;
write_component(state, "loading", *loading)?;
write_component(state, "template", *template)?;
// TODO something useful for metadata
emit_metadata_warning(state, icon);
emit_metadata_warning(state, apple);
emit_metadata_warning(state, twitter);
emit_metadata_warning(state, open_graph);
emit_metadata_warning(state, favicon);
write_metadata(state, metadata)?;
write!(state.loader_tree_code, "}}]")?;
Ok(())
}
......@@ -695,7 +870,7 @@ import {}, {{ chunks as {} }} from "COMPONENT_{}";
} = state;
if !unsupported_metadata.is_empty() {
UnsupportedImplicitMetadataIssue {
UnsupportedDynamicMetadataIssue {
app_dir,
files: unsupported_metadata,
}
......@@ -877,13 +1052,13 @@ impl NodeEntry for AppRoute {
}
#[turbo_tasks::value]
struct UnsupportedImplicitMetadataIssue {
struct UnsupportedDynamicMetadataIssue {
app_dir: FileSystemPathVc,
files: Vec<FileSystemPathVc>,
}
#[turbo_tasks::value_impl]
impl Issue for UnsupportedImplicitMetadataIssue {
impl Issue for UnsupportedDynamicMetadataIssue {
#[turbo_tasks::function]
fn severity(&self) -> IssueSeverityVc {
IssueSeverity::Warning.into()
......@@ -902,7 +1077,7 @@ impl Issue for UnsupportedImplicitMetadataIssue {
#[turbo_tasks::function]
fn title(&self) -> StringVc {
StringVc::cell(
"Implicit metadata from filesystem is currently not supported in Turbopack".to_string(),
"Dynamic metadata from filesystem is currently not supported in Turbopack".to_string(),
)
}
......
......@@ -82,18 +82,40 @@ impl ComponentsVc {
}
}
/// A single metadata file plus an optional "alt" text file.
#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq, Eq, TraceRawVcs)]
pub enum MetadataWithAltItem {
Static {
path: FileSystemPathVc,
alt_path: Option<FileSystemPathVc>,
},
Dynamic {
path: FileSystemPathVc,
},
}
/// A single metadata file.
#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq, Eq, TraceRawVcs)]
pub enum MetadataItem {
Static { path: FileSystemPathVc },
Dynamic { path: FileSystemPathVc },
}
/// Metadata file that can be placed in any segment of the app directory.
#[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq, Eq, TraceRawVcs)]
pub struct Metadata {
#[serde(skip_serializing_if = "Vec::is_empty")]
pub icon: Vec<FileSystemPathVc>,
pub icon: Vec<MetadataWithAltItem>,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub apple: Vec<FileSystemPathVc>,
pub apple: Vec<MetadataWithAltItem>,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub twitter: Vec<FileSystemPathVc>,
pub twitter: Vec<MetadataWithAltItem>,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub open_graph: Vec<FileSystemPathVc>,
pub open_graph: Vec<MetadataWithAltItem>,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub favicon: Vec<FileSystemPathVc>,
pub favicon: Vec<MetadataWithAltItem>,
#[serde(skip_serializing_if = "Option::is_none")]
pub manifest: Option<MetadataItem>,
}
impl Metadata {
......@@ -104,12 +126,14 @@ impl Metadata {
twitter,
open_graph,
favicon,
manifest,
} = self;
icon.is_empty()
&& apple.is_empty()
&& twitter.is_empty()
&& open_graph.is_empty()
&& favicon.is_empty()
&& manifest.is_none()
}
fn merge(a: &Self, b: &Self) -> Self {
......@@ -124,7 +148,31 @@ impl Metadata {
.copied()
.collect(),
favicon: a.favicon.iter().chain(b.favicon.iter()).copied().collect(),
manifest: a.manifest.or(b.manifest),
}
}
}
/// 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 sitemap: Option<MetadataItem>,
}
impl GlobalMetadata {
pub fn is_empty(&self) -> bool {
let GlobalMetadata {
favicon,
robots,
sitemap,
} = self;
favicon.is_none() && robots.is_none() && sitemap.is_none()
}
}
......@@ -203,7 +251,7 @@ pub async fn find_app_dir_if_enabled(
Ok(find_app_dir(project_path))
}
static STATIC_METADATA_IMAGES: Lazy<HashMap<&'static str, &'static [&'static str]>> =
static STATIC_LOCAL_METADATA: Lazy<HashMap<&'static str, &'static [&'static str]>> =
Lazy::new(|| {
HashMap::from([
(
......@@ -211,18 +259,36 @@ static STATIC_METADATA_IMAGES: Lazy<HashMap<&'static str, &'static [&'static str
&["ico", "jpg", "jpeg", "png", "svg"] as &'static [&'static str],
),
("apple-icon", &["jpg", "jpeg", "png"]),
("favicon", &["ico"]),
("opengraph-image", &["jpg", "jpeg", "png", "gif"]),
("twitter-image", &["jpg", "jpeg", "png", "gif"]),
("favicon", &["ico"]),
("manifest", &["webmanifest", "json"]),
])
});
static STATIC_GLOBAL_METADATA: Lazy<HashMap<&'static str, &'static [&'static str]>> =
Lazy::new(|| {
HashMap::from([
("favicon", &["ico"] as &'static [&'static str]),
("robots", &["txt"]),
("sitemap", &["xml"]),
])
});
fn match_metadata_file(basename: &str) -> Option<&'static str> {
fn match_metadata_file<'a>(
basename: &'a str,
page_extensions: &[String],
) -> Option<(&'a str, i32, bool)> {
let (stem, ext) = basename.split_once('.')?;
static REGEX: Lazy<Regex> = Lazy::new(|| Regex::new("\\d*$").unwrap());
let stem = REGEX.replace(stem, "");
let (key, exts) = STATIC_METADATA_IMAGES.get_key_value(stem.as_ref())?;
exts.contains(&ext).then_some(key)
static REGEX: Lazy<Regex> = Lazy::new(|| Regex::new("^(.*?)(\\d*)$").unwrap());
let captures = REGEX.captures(stem).expect("the regex will always match");
let stem = captures.get(1).unwrap().as_str();
let num: i32 = captures.get(2).unwrap().as_str().parse().unwrap_or(-1);
if page_extensions.iter().any(|e| e == ext) {
return Some((stem, num, true));
}
let exts = STATIC_LOCAL_METADATA.get(stem)?;
exts.contains(&ext).then_some((stem, num, false))
}
#[turbo_tasks::function]
......@@ -233,14 +299,22 @@ async fn get_directory_tree(
let DirectoryContent::Entries(entries) = &*app_dir.read_dir().await? else {
bail!("app_dir must be a directory")
};
let page_extensions_value = page_extensions.await?;
let mut subdirectories = BTreeMap::new();
let mut components = Components::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();
let mut metadata_favicon = Vec::new();
for (basename, entry) in entries {
match *entry {
DirectoryEntry::File(file) => {
if let Some((stem, ext)) = basename.split_once('.') {
if page_extensions.await?.iter().any(|e| e == ext) {
if page_extensions_value.iter().any(|e| e == ext) {
match stem {
"page" => components.page = Some(file),
"layout" => components.layout = Some(file),
......@@ -249,24 +323,57 @@ async fn get_directory_tree(
"template" => components.template = Some(file),
"default" => components.default = Some(file),
"route" => components.route = Some(file),
"manifest" => {
components.metadata.manifest =
Some(MetadataItem::Dynamic { path: file });
continue;
}
_ => {}
}
}
}
if let Some(metadata_type) = match_metadata_file(basename.as_str()) {
let metadata = &mut components.metadata;
if let Some((metadata_type, num, dynamic)) =
match_metadata_file(basename.as_str(), &page_extensions_value)
{
if metadata_type == "manifest" {
if num == -1 {
components.metadata.manifest =
Some(MetadataItem::Static { path: file });
}
continue;
}
let entry = match metadata_type {
"icon" => Some(&mut metadata.icon),
"apple-icon" => Some(&mut metadata.apple),
"twitter-image" => Some(&mut metadata.twitter),
"opengraph-image" => Some(&mut metadata.open_graph),
"favicon" => Some(&mut metadata.favicon),
"icon" => Some(&mut metadata_icon),
"apple-icon" => Some(&mut metadata_apple),
"twitter-image" => Some(&mut metadata_twitter),
"opengraph-image" => Some(&mut metadata_open_graph),
"favicon" => Some(&mut metadata_favicon),
_ => None,
};
if let Some(entry) = entry {
entry.push(file)
if dynamic {
entry.push((num, MetadataWithAltItem::Dynamic { path: file }));
} else {
let file_value = file.await?;
let file_name = file_value.file_name();
let basename = file_name
.rsplit_once('.')
.map_or(file_name, |(basename, _)| basename);
let alt_path = file.parent().join(&format!("{}.alt.txt", basename));
let alt_path =
matches!(&*alt_path.get_type().await?, FileSystemEntryType::File)
.then_some(alt_path);
entry.push((
num,
MetadataWithAltItem::Static {
path: file,
alt_path,
},
));
}
}
}
}
......@@ -274,11 +381,22 @@ async fn get_directory_tree(
let result = get_directory_tree(dir, page_extensions);
subdirectories.insert(basename.to_string(), result);
}
// TODO handle symlinks in app dir
// TODO(WEB-952) handle symlinks in app dir
_ => {}
}
}
fn sort<T>(mut list: Vec<(i32, T)>) -> Vec<T> {
list.sort_by_key(|(num, _)| *num);
list.into_iter().map(|(_, item)| item).collect()
}
components.metadata.icon = sort(metadata_icon);
components.metadata.apple = sort(metadata_apple);
components.metadata.twitter = sort(metadata_twitter);
components.metadata.open_graph = sort(metadata_open_graph);
components.metadata.favicon = sort(metadata_favicon);
Ok(DirectoryTree {
subdirectories,
components: components.cell(),
......@@ -576,6 +694,42 @@ async fn directory_tree_to_entrypoints_internal(
Ok(EntrypointsVc::cell(result))
}
/// Returns the global metadata for an app directory.
#[turbo_tasks::function]
pub async fn get_global_metadata(
app_dir: FileSystemPathVc,
page_extensions: StringsVc,
) -> Result<GlobalMetadataVc> {
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 {
if let DirectoryEntry::File(file) = *entry {
if let Some((stem, ext)) = basename.split_once('.') {
let list = match stem {
"favicon" => Some(&mut metadata.favicon),
"sitemap" => Some(&mut metadata.sitemap),
"robots" => Some(&mut metadata.robots),
_ => None,
};
if let Some(list) = list {
if page_extensions.await?.iter().any(|e| e == ext) {
*list = Some(MetadataItem::Dynamic { path: file });
}
if STATIC_GLOBAL_METADATA.get(stem).unwrap().contains(&ext) {
*list = Some(MetadataItem::Static { path: file });
}
}
}
}
// TODO(WEB-952) handle symlinks in app dir
}
Ok(metadata.cell())
}
#[turbo_tasks::value(shared)]
struct DirectoryTreeIssue {
pub severity: IssueSeverityVc,
......
use turbo_binding::turbopack::{
core::{
asset::AssetVc,
context::{AssetContext, AssetContextVc},
},
ecmascript::{
EcmascriptInputTransform, EcmascriptInputTransformsVc, EcmascriptModuleAssetType,
EcmascriptModuleAssetVc,
},
};
use turbo_tasks::Value;
pub(crate) fn as_es_module_asset(
asset: AssetVc,
context: AssetContextVc,
) -> EcmascriptModuleAssetVc {
EcmascriptModuleAssetVc::new(
asset,
context,
Value::new(EcmascriptModuleAssetType::Typescript),
EcmascriptInputTransformsVc::cell(vec![EcmascriptInputTransform::TypeScript {
use_define_for_class_fields: false,
}]),
Default::default(),
context.compile_time_info(),
)
}
......@@ -5,6 +5,7 @@
mod app_render;
mod app_source;
pub mod app_structure;
mod asset_helpers;
mod babel;
mod embed_js;
pub mod env;
......
......@@ -24,25 +24,13 @@ use super::source_asset::StructuredImageSourceAsset;
#[turbo_tasks::value]
pub struct StructuredImageModuleType {}
#[turbo_tasks::value_impl]
impl StructuredImageModuleTypeVc {
#[turbo_tasks::function]
pub fn new() -> Self {
StructuredImageModuleTypeVc::cell(StructuredImageModuleType {})
}
}
#[turbo_tasks::value_impl]
impl CustomModuleType for StructuredImageModuleType {
#[turbo_tasks::function]
async fn create_module(
&self,
impl StructuredImageModuleType {
pub(crate) fn create_module(
source: AssetVc,
context: AssetContextVc,
_part: Option<ModulePartVc>,
) -> Result<AssetVc> {
) -> EcmascriptModuleAssetVc {
let static_asset = StaticModuleAssetVc::new(source, context);
Ok(EcmascriptModuleAssetVc::new_with_inner_assets(
EcmascriptModuleAssetVc::new_with_inner_assets(
StructuredImageSourceAsset { image: source }.cell().into(),
context,
Value::new(EcmascriptModuleAssetType::Ecmascript),
......@@ -55,6 +43,26 @@ impl CustomModuleType for StructuredImageModuleType {
"IMAGE".to_string() => static_asset.into()
)),
)
.into())
}
}
#[turbo_tasks::value_impl]
impl StructuredImageModuleTypeVc {
#[turbo_tasks::function]
pub fn new() -> Self {
StructuredImageModuleTypeVc::cell(StructuredImageModuleType {})
}
}
#[turbo_tasks::value_impl]
impl CustomModuleType for StructuredImageModuleType {
#[turbo_tasks::function]
fn create_module(
&self,
source: AssetVc,
context: AssetContextVc,
_part: Option<ModulePartVc>,
) -> AssetVc {
StructuredImageModuleType::create_module(source, context).into()
}
}
......@@ -45,6 +45,7 @@ use turbo_tasks::{
use turbo_tasks_fs::json::parse_json_with_source_context;
use crate::{
asset_helpers::as_es_module_asset,
embed_js::{next_asset, next_js_file},
next_config::NextConfigVc,
next_edge::{
......@@ -156,19 +157,6 @@ async fn get_config(
Ok(OptionEcmascriptModuleAssetVc::cell(config_asset))
}
fn as_es_module_asset(asset: AssetVc, context: AssetContextVc) -> EcmascriptModuleAssetVc {
EcmascriptModuleAssetVc::new(
asset,
context,
Value::new(EcmascriptModuleAssetType::Typescript),
EcmascriptInputTransformsVc::cell(vec![EcmascriptInputTransform::TypeScript {
use_define_for_class_fields: false,
}]),
Default::default(),
context.compile_time_info(),
)
}
#[turbo_tasks::function]
async fn next_config_changed(
context: AssetContextVc,
......
{
"name": "Next.js Static Manifest",
"short_name": "Next.js App",
"description": "Next.js App",
"start_url": "/",
"display": "standalone",
"background_color": "#fff",
"theme_color": "#fff"
}
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>https://vercel.com/</loc>
<lastmod>2023-03-06T18:04:14.008Z</lastmod>
</url>
</urlset>
......@@ -5,7 +5,84 @@ import { useEffect } from 'react'
export default function Test() {
useEffect(() => {
import('@turbo/pack-test-harness').then(() => {
it('should run', () => {})
it('should have the correct link tags', () => {
let links = Array.from(document.querySelectorAll('link'))
expect(
links.map((l) => ({
href: l.getAttribute('href'),
rel: l.getAttribute('rel'),
sizes: l.getAttribute('sizes'),
}))
).toEqual([
expect.objectContaining({
rel: 'manifest',
href: expect.stringMatching(/^\/_next\/static\/.+\.webmanifest$/),
sizes: null,
}),
expect.objectContaining({
rel: 'icon',
href: expect.stringMatching(/^\/_next\/static\/.+\.ico$/),
sizes: '48x48',
}),
expect.objectContaining({
rel: 'icon',
href: expect.stringMatching(/^\/_next\/static\/.+\.png$/),
sizes: '32x32',
}),
expect.objectContaining({
rel: 'icon',
href: expect.stringMatching(/^\/_next\/static\/.+\.png$/),
sizes: '64x64',
}),
expect.objectContaining({
rel: 'apple-touch-icon',
href: expect.stringMatching(/^\/_next\/static\/.+\.png$/),
sizes: '114x114',
}),
])
})
it('should have the correct meta tags', () => {
const meta = Array.from(document.querySelectorAll('meta'))
const metaObject = Object.fromEntries(
meta
.filter((l) => l.getAttribute('property'))
.map((l) => [l.getAttribute('property'), l.getAttribute('content')])
)
expect(metaObject).toEqual({
'og:image': expect.stringMatching(/^.+\/_next\/static\/.+\.png$/),
'og:image:width': '114',
'og:image:height': '114',
'og:image:alt': 'This is an alt text.',
})
})
it('should provide a robots.txt', async () => {
const res = await fetch('/robots.txt')
expect(res.status).toBe(200)
expect(await res.text()).toBe('User-Agent: *\nDisallow:\n')
})
it('should provide a sitemap.xml', async () => {
const res = await fetch('/sitemap.xml')
expect(res.status).toBe(200)
expect(await res.text()).toBe(
`<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>https://vercel.com/</loc>
<lastmod>2023-03-06T18:04:14.008Z</lastmod>
</url>
</urlset>
`
)
})
it('should provide a favicon.ico', async () => {
const res = await fetch('/favicon.ico')
expect(res.status).toBe(200)
expect(res.headers.get('content-type')).toBe('image/x-icon')
})
})
return () => {}
}, [])
......
PlainIssue {
severity: Warning,
context: "[project]/packages/next-swc/crates/next-dev-tests/tests/integration/next/app/implicit-metadata/input/app",
category: "unsupported",
title: "Implicit metadata from filesystem is currently not supported in Turbopack",
description: "The following files were found in the app directory, but are not supported by Turbopack. They are ignored:\n\n- [project]/packages/next-swc/crates/next-dev-tests/tests/integration/next/app/implicit-metadata/input/app/apple-icon.png\n- [project]/packages/next-swc/crates/next-dev-tests/tests/integration/next/app/implicit-metadata/input/app/icon1234.png\n- [project]/packages/next-swc/crates/next-dev-tests/tests/integration/next/app/implicit-metadata/input/app/icon234.png",
detail: "",
documentation_link: "",
source: None,
sub_issues: [],
processing_path: Some(
[
PlainIssueProcessingPathItem {
context: Some(
"[project]/packages/next-swc/crates/next-dev-tests/tests/integration/next/app/implicit-metadata/input/app",
),
description: "Next.js App Page Route /",
},
],
),
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment