Unverified Commit 3cf225c8 authored by Donny/강동윤's avatar Donny/강동윤 Committed by GitHub

feat(turbopack): Introduce `RcStr` (#66262)

# Turbopack

* https://github.com/vercel/turbo/pull/8272 <!-- Donny/강동윤 - feat:
Update `swc_core` to `v0.92.8` -->
* https://github.com/vercel/turbo/pull/8262 <!-- Alexander Lyon - add
crate to calculate prehashes -->
* https://github.com/vercel/turbo/pull/8174 <!-- Tobias Koppers - use
prehash to avoid rehashing the key in the task cache -->
* https://github.com/vercel/turbo/pull/7674 <!-- Alexander Lyon - [turbo
trace] add ability to filter by value and occurences -->
* https://github.com/vercel/turbo/pull/8287 <!-- Donny/강동윤 - feat:
Update `swc_core` to `v0.92.10` -->
* https://github.com/vercel/turbo/pull/8037 <!-- Alexander Lyon - create
turbo-static for compile time graph analysis -->
* https://github.com/vercel/turbo/pull/8293 <!-- Will Binns-Smith - Sync
Cargo.lock with Next.js -->
* https://github.com/vercel/turbo/pull/8239 <!-- Benjamin Woodruff -
Reduce amount of code generated by ValueDebugFormat -->
* https://github.com/vercel/turbo/pull/8304 <!-- Benjamin Woodruff -
Minor optimizations to the codegen of TaskFnInputFunction -->
* https://github.com/vercel/turbo/pull/8221 <!-- Donny/강동윤 - perf:
Introduce `RcStr` -->


### What?

I tried using `Arc<String>` in
https://github.com/vercel/turbo/pull/7772, but a team member suggested
creating a new type so we can replace underlying implementation easily
in the future.

### Why?

To reduce memory usage.

### How?

Closes PACK-2776
parent 750ae91e
This diff is collapsed.
......@@ -37,11 +37,11 @@ swc_core = { version = "0.92.10", features = [
testing = { version = "0.35.25" }
# Turbo crates
turbopack-binding = { git = "https://github.com/vercel/turbo.git", tag = "turbopack-240531.2" }
turbopack-binding = { git = "https://github.com/vercel/turbo.git", tag = "turbopack-240605.1" }
# [TODO]: need to refactor embed_directory! macro usages, as well as resolving turbo_tasks::function, macros..
turbo-tasks = { git = "https://github.com/vercel/turbo.git", tag = "turbopack-240531.2" }
turbo-tasks = { git = "https://github.com/vercel/turbo.git", tag = "turbopack-240605.1" }
# [TODO]: need to refactor embed_directory! macro usage in next-core
turbo-tasks-fs = { git = "https://github.com/vercel/turbo.git", tag = "turbopack-240531.2" }
turbo-tasks-fs = { git = "https://github.com/vercel/turbo.git", tag = "turbopack-240605.1" }
# General Deps
......
......@@ -12,7 +12,7 @@ use next_core::app_structure::{
LoaderTree, MetadataItem, MetadataWithAltItem,
};
use serde::{Deserialize, Serialize};
use turbo_tasks::{ReadRef, Vc};
use turbo_tasks::{RcStr, ReadRef, Vc};
use turbopack_binding::{
turbo::{
tasks::{
......@@ -27,12 +27,8 @@ use turbopack_binding::{
use crate::register;
#[turbo_tasks::function]
async fn project_fs(project_dir: String, watching: bool) -> Result<Vc<Box<dyn FileSystem>>> {
let disk_fs = DiskFileSystem::new(
PROJECT_FILESYSTEM_NAME.to_string(),
project_dir.to_string(),
vec![],
);
async fn project_fs(project_dir: RcStr, watching: bool) -> Result<Vc<Box<dyn FileSystem>>> {
let disk_fs = DiskFileSystem::new(PROJECT_FILESYSTEM_NAME.into(), project_dir, vec![]);
if watching {
disk_fs.await?.start_watching_with_invalidation_reason()?;
}
......@@ -42,8 +38,8 @@ async fn project_fs(project_dir: String, watching: bool) -> Result<Vc<Box<dyn Fi
#[turbo_tasks::value]
#[serde(rename_all = "camelCase")]
struct LoaderTreeForJs {
segment: String,
parallel_routes: IndexMap<String, ReadRef<LoaderTreeForJs>>,
segment: RcStr,
parallel_routes: IndexMap<RcStr, ReadRef<LoaderTreeForJs>>,
#[turbo_tasks(trace_ignore)]
components: ComponentsForJs,
#[turbo_tasks(trace_ignore)]
......@@ -57,13 +53,13 @@ enum EntrypointForJs {
loader_tree: ReadRef<LoaderTreeForJs>,
},
AppRoute {
path: String,
path: RcStr,
},
}
#[turbo_tasks::value(transparent)]
#[serde(rename_all = "camelCase")]
struct EntrypointsForJs(HashMap<String, EntrypointForJs>);
struct EntrypointsForJs(HashMap<RcStr, EntrypointForJs>);
#[turbo_tasks::value(transparent)]
struct OptionEntrypointsForJs(Option<Vc<EntrypointsForJs>>);
......@@ -71,14 +67,14 @@ struct OptionEntrypointsForJs(Option<Vc<EntrypointsForJs>>);
async fn fs_path_to_path(
project_path: Vc<FileSystemPath>,
path: Vc<FileSystemPath>,
) -> Result<String> {
) -> Result<RcStr> {
match project_path.await?.get_path_to(&*path.await?) {
None => Err(anyhow!(
"Path {} is not inside of the project path {}",
path.to_string().await?,
project_path.to_string().await?
)),
Some(p) => Ok(p.to_string()),
Some(p) => Ok(p.into()),
}
}
......@@ -86,21 +82,21 @@ async fn fs_path_to_path(
#[serde(rename_all = "camelCase")]
struct ComponentsForJs {
#[serde(skip_serializing_if = "Option::is_none")]
page: Option<String>,
page: Option<RcStr>,
#[serde(skip_serializing_if = "Option::is_none")]
layout: Option<String>,
layout: Option<RcStr>,
#[serde(skip_serializing_if = "Option::is_none")]
error: Option<String>,
error: Option<RcStr>,
#[serde(skip_serializing_if = "Option::is_none")]
loading: Option<String>,
loading: Option<RcStr>,
#[serde(skip_serializing_if = "Option::is_none")]
template: Option<String>,
template: Option<RcStr>,
#[serde(skip_serializing_if = "Option::is_none", rename = "not-found")]
not_found: Option<String>,
not_found: Option<RcStr>,
#[serde(skip_serializing_if = "Option::is_none")]
default: Option<String>,
default: Option<RcStr>,
#[serde(skip_serializing_if = "Option::is_none")]
route: Option<String>,
route: Option<RcStr>,
metadata: MetadataForJs,
}
......@@ -134,19 +130,19 @@ struct GlobalMetadataForJs {
#[serde(tag = "type", rename_all = "camelCase")]
enum MetadataWithAltItemForJs {
Static {
path: String,
alt_path: Option<String>,
path: RcStr,
alt_path: Option<RcStr>,
},
Dynamic {
path: String,
path: RcStr,
},
}
#[derive(Deserialize, Serialize, PartialEq, Eq, ValueDebugFormat)]
#[serde(tag = "type", rename_all = "camelCase")]
enum MetadataItemForJs {
Static { path: String },
Dynamic { path: String },
Static { path: RcStr },
Dynamic { path: RcStr },
}
async fn prepare_components_for_js(
......@@ -166,7 +162,7 @@ async fn prepare_components_for_js(
} = &*components.await?;
let mut result = ComponentsForJs::default();
async fn add(
result: &mut Option<String>,
result: &mut Option<RcStr>,
project_path: Vc<FileSystemPath>,
value: &Option<Vc<FileSystemPath>>,
) -> Result<()> {
......@@ -305,7 +301,7 @@ async fn prepare_entrypoints_for_js(
.await?
.iter()
.map(|(key, value)| {
let key = key.to_string();
let key = key.to_string().into();
async move {
let value = match *value {
Entrypoint::AppPage { loader_tree, .. } => EntrypointForJs::AppPage {
......@@ -330,19 +326,19 @@ async fn prepare_entrypoints_for_js(
#[turbo_tasks::function]
async fn get_value(
root_dir: String,
project_dir: String,
page_extensions: Vec<String>,
root_dir: RcStr,
project_dir: RcStr,
page_extensions: Vec<RcStr>,
watching: bool,
) -> Result<Vc<OptionEntrypointsForJs>> {
let page_extensions = Vc::cell(page_extensions);
let fs = project_fs(root_dir.clone(), watching);
let project_relative = project_dir.strip_prefix(&root_dir).unwrap();
let project_relative = project_dir.strip_prefix(&*root_dir).unwrap();
let project_relative = project_relative
.strip_prefix(MAIN_SEPARATOR)
.unwrap_or(project_relative)
.replace(MAIN_SEPARATOR, "/");
let project_path = fs.root().join(project_relative);
let project_path = fs.root().join(project_relative.into());
let app_dir = find_app_dir(project_path);
......@@ -373,8 +369,8 @@ pub fn stream_entrypoints(
let value = serde_json::to_value(value)?;
Ok(vec![value])
})?;
let root_dir = Arc::new(root_dir);
let project_dir = Arc::new(project_dir);
let root_dir = RcStr::from(root_dir);
let project_dir = RcStr::from(project_dir);
let page_extensions = Arc::new(page_extensions);
turbo_tasks.spawn_root_task(move || {
let func: ThreadsafeFunction<Option<ReadRef<EntrypointsForJs>>> = func.clone();
......@@ -383,9 +379,9 @@ pub fn stream_entrypoints(
let page_extensions: Arc<Vec<String>> = page_extensions.clone();
Box::pin(async move {
if let Some(entrypoints) = &*get_value(
(*root_dir).clone(),
(*project_dir).clone(),
page_extensions.iter().map(|s| s.to_string()).collect(),
root_dir.clone(),
project_dir.clone(),
page_extensions.iter().map(|s| s.as_str().into()).collect(),
true,
)
.await?
......@@ -415,9 +411,9 @@ pub async fn get_entrypoints(
let result = turbo_tasks
.run_once(async move {
let value = if let Some(entrypoints) = &*get_value(
root_dir,
project_dir,
page_extensions.iter().map(|s| s.to_string()).collect(),
root_dir.into(),
project_dir.into(),
page_extensions.iter().map(|s| s.as_str().into()).collect(),
false,
)
.await?
......
......@@ -57,7 +57,7 @@ impl From<WrittenEndpoint> for NapiWrittenEndpoint {
} => Self {
r#type: "nodejs".to_string(),
entry_path: Some(server_entry_path),
client_paths,
client_paths: client_paths.into_iter().map(From::from).collect(),
server_paths: server_paths.into_iter().map(From::from).collect(),
..Default::default()
},
......@@ -66,7 +66,7 @@ impl From<WrittenEndpoint> for NapiWrittenEndpoint {
client_paths,
} => Self {
r#type: "edge".to_string(),
client_paths,
client_paths: client_paths.into_iter().map(From::from).collect(),
server_paths: server_paths.into_iter().map(From::from).collect(),
..Default::default()
},
......
......@@ -22,7 +22,7 @@ use rand::Rng;
use tokio::{io::AsyncWriteExt, time::Instant};
use tracing::Instrument;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter, Registry};
use turbo_tasks::{Completion, ReadRef, TransientInstance, TurboTasks, UpdateInfo, Vc};
use turbo_tasks::{Completion, RcStr, ReadRef, TransientInstance, TurboTasks, UpdateInfo, Vc};
use turbopack_binding::{
turbo::{
tasks_fs::{DiskFileSystem, FileContent, FileSystem, FileSystemPath},
......@@ -77,9 +77,9 @@ pub struct NapiDraftModeOptions {
impl From<NapiDraftModeOptions> for DraftModeOptions {
fn from(val: NapiDraftModeOptions) -> Self {
DraftModeOptions {
preview_mode_id: val.preview_mode_id,
preview_mode_encryption_key: val.preview_mode_encryption_key,
preview_mode_signing_key: val.preview_mode_signing_key,
preview_mode_id: val.preview_mode_id.into(),
preview_mode_encryption_key: val.preview_mode_encryption_key.into(),
preview_mode_signing_key: val.preview_mode_signing_key.into(),
}
}
}
......@@ -186,20 +186,20 @@ pub struct NapiTurboEngineOptions {
impl From<NapiProjectOptions> for ProjectOptions {
fn from(val: NapiProjectOptions) -> Self {
ProjectOptions {
root_path: val.root_path,
project_path: val.project_path,
root_path: val.root_path.into(),
project_path: val.project_path.into(),
watch: val.watch,
next_config: val.next_config,
js_config: val.js_config,
next_config: val.next_config.into(),
js_config: val.js_config.into(),
env: val
.env
.into_iter()
.map(|var| (var.name, var.value))
.map(|var| (var.name.into(), var.value.into()))
.collect(),
define_env: val.define_env.into(),
dev: val.dev,
encryption_key: val.encryption_key,
build_id: val.build_id,
encryption_key: val.encryption_key.into(),
build_id: val.build_id.into(),
preview_props: val.preview_props.into(),
}
}
......@@ -208,18 +208,20 @@ impl From<NapiProjectOptions> for ProjectOptions {
impl From<NapiPartialProjectOptions> for PartialProjectOptions {
fn from(val: NapiPartialProjectOptions) -> Self {
PartialProjectOptions {
root_path: val.root_path,
project_path: val.project_path,
root_path: val.root_path.map(From::from),
project_path: val.project_path.map(From::from),
watch: val.watch,
next_config: val.next_config,
js_config: val.js_config,
env: val
.env
.map(|env| env.into_iter().map(|var| (var.name, var.value)).collect()),
next_config: val.next_config.map(From::from),
js_config: val.js_config.map(From::from),
env: val.env.map(|env| {
env.into_iter()
.map(|var| (var.name.into(), var.value.into()))
.collect()
}),
define_env: val.define_env.map(|env| env.into()),
dev: val.dev,
encryption_key: val.encryption_key,
build_id: val.build_id,
encryption_key: val.encryption_key.map(From::from),
build_id: val.build_id.map(From::from),
preview_props: val.preview_props.map(|props| props.into()),
}
}
......@@ -231,17 +233,17 @@ impl From<NapiDefineEnv> for DefineEnv {
client: val
.client
.into_iter()
.map(|var| (var.name, var.value))
.map(|var| (var.name.into(), var.value.into()))
.collect(),
edge: val
.edge
.into_iter()
.map(|var| (var.name, var.value))
.map(|var| (var.name.into(), var.value.into()))
.collect(),
nodejs: val
.nodejs
.into_iter()
.map(|var| (var.name, var.value))
.map(|var| (var.name.into(), var.value.into()))
.collect(),
}
}
......@@ -357,10 +359,8 @@ pub async fn project_new(
/// - https://github.com/oven-sh/bun/blob/06a9aa80c38b08b3148bfeabe560/src/install/install.zig#L3038
#[tracing::instrument]
async fn benchmark_file_io(directory: Vc<FileSystemPath>) -> Result<Vc<Completion>> {
let temp_path = directory.join(format!(
"tmp_file_io_benchmark_{:x}",
rand::random::<u128>()
));
let temp_path =
directory.join(format!("tmp_file_io_benchmark_{:x}", rand::random::<u128>()).into());
// try to get the real file path on disk so that we can use it with tokio
let fs = Vc::try_resolve_downcast_type::<DiskFileSystem>(directory.fs())
......@@ -624,7 +624,11 @@ pub fn project_entrypoints_subscribe(
.routes
.iter()
.map(|(pathname, route)| {
NapiRoute::from_route(pathname.clone(), route.clone(), &turbo_tasks)
NapiRoute::from_route(
pathname.clone().into(),
route.clone(),
&turbo_tasks,
)
})
.collect::<Vec<_>>(),
middleware: entrypoints
......@@ -670,7 +674,7 @@ struct HmrUpdateWithIssues {
#[turbo_tasks::function]
async fn hmr_update(
project: Vc<Project>,
identifier: String,
identifier: RcStr,
state: Vc<VersionState>,
) -> Result<Vc<HmrUpdateWithIssues>> {
let update_operation = project.hmr_update(identifier, state);
......@@ -701,7 +705,7 @@ pub fn project_hmr_events(
let outer_identifier = identifier.clone();
let session = session.clone();
move || {
let identifier = outer_identifier.clone();
let identifier: RcStr = outer_identifier.clone().into();
let session = session.clone();
async move {
let project = project.project().resolve().await?;
......@@ -773,7 +777,7 @@ struct HmrIdentifiers {
#[turbo_tasks::value(serialization = "none")]
struct HmrIdentifiersWithIssues {
identifiers: ReadRef<Vec<String>>,
identifiers: ReadRef<Vec<RcStr>>,
issues: Arc<Vec<ReadRef<PlainIssue>>>,
diagnostics: Arc<Vec<ReadRef<PlainDiagnostic>>>,
}
......@@ -967,7 +971,9 @@ pub async fn project_trace_source(
(
path,
match module {
Some(module) => Some(urlencoding::decode(&module.1)?.into_owned()),
Some(module) => {
Some(urlencoding::decode(&module.1)?.into_owned().into())
}
None => None,
},
)
......@@ -992,13 +998,13 @@ pub async fn project_trace_source(
.container
.project()
.node_root()
.join(chunk_base.to_owned());
.join(chunk_base.into());
let client_path = project
.container
.project()
.client_relative_path()
.join(chunk_base.to_owned());
.join(chunk_base.into());
let mut map_result = project
.container
......@@ -1053,7 +1059,7 @@ pub async fn project_trace_source(
Ok(Some(StackFrame {
file: source_file.to_string(),
method_name: name,
method_name: name.as_ref().map(ToString::to_string),
line,
column,
is_server: frame.is_server,
......@@ -1079,7 +1085,7 @@ pub async fn project_get_source_for_asset(
.project_path()
.fs()
.root()
.join(file_path.to_string())
.join(file_path.clone().into())
.read()
.await?;
......
......@@ -120,12 +120,12 @@ impl From<&PlainIssue> for NapiIssue {
.as_ref()
.map(|styled| serde_json::to_value(StyledStringSerialize::from(styled)).unwrap()),
stage: issue.stage.to_string(),
file_path: issue.file_path.clone(),
file_path: issue.file_path.to_string(),
detail: issue
.detail
.as_ref()
.map(|styled| serde_json::to_value(StyledStringSerialize::from(styled)).unwrap()),
documentation_link: issue.documentation_link.clone(),
documentation_link: issue.documentation_link.to_string(),
severity: issue.severity.as_str().to_string(),
source: issue.source.as_deref().map(|source| source.into()),
title: serde_json::to_value(StyledStringSerialize::from(&issue.title)).unwrap(),
......@@ -255,9 +255,13 @@ pub struct NapiDiagnostic {
impl NapiDiagnostic {
pub fn from(diagnostic: &PlainDiagnostic) -> Self {
Self {
category: diagnostic.category.clone(),
name: diagnostic.name.clone(),
payload: diagnostic.payload.clone(),
category: diagnostic.category.to_string(),
name: diagnostic.name.to_string(),
payload: diagnostic
.payload
.iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect(),
}
}
}
......
......@@ -190,10 +190,21 @@ impl FromNapiValue for NapiRouteHas {
impl From<NapiRouteHas> for RouteHas {
fn from(val: NapiRouteHas) -> Self {
match val {
NapiRouteHas::Header { key, value } => RouteHas::Header { key, value },
NapiRouteHas::Query { key, value } => RouteHas::Query { key, value },
NapiRouteHas::Cookie { key, value } => RouteHas::Cookie { key, value },
NapiRouteHas::Host { value } => RouteHas::Host { value },
NapiRouteHas::Header { key, value } => RouteHas::Header {
key: key.into(),
value: value.map(From::from),
},
NapiRouteHas::Query { key, value } => RouteHas::Query {
key: key.into(),
value: value.map(From::from),
},
NapiRouteHas::Cookie { key, value } => RouteHas::Cookie {
key: key.into(),
value: value.map(From::from),
},
NapiRouteHas::Host { value } => RouteHas::Host {
value: value.into(),
},
}
}
}
......
......@@ -40,5 +40,5 @@ pub async fn run_turbo_tracing(
}),
)
.await?;
Ok(files)
Ok(files.into_iter().map(|f| f.to_string()).collect())
}
......@@ -6,7 +6,7 @@ use indexmap::IndexMap;
use tracing::Level;
use turbo_tasks::{
graph::{GraphTraversal, NonDeterministic, VisitControlFlow},
ReadRef, TryJoinIterExt, Value, ValueToString, Vc,
RcStr, ReadRef, TryJoinIterExt, Value, ValueToString, Vc,
};
use turbopack_binding::{
swc::core::ecma::{
......@@ -39,7 +39,7 @@ where
F: FnMut(Vc<Box<dyn ChunkableModule>>) -> Fu,
Fu: Future<Output = Result<Vc<OutputAssets>>> + Send,
{
let mut chunks_hash: HashMap<String, Vc<OutputAssets>> = HashMap::new();
let mut chunks_hash: HashMap<RcStr, Vc<OutputAssets>> = HashMap::new();
let mut dynamic_import_chunks = IndexMap::new();
// Iterate over the collected import mappings, and create a chunk for each
......@@ -62,7 +62,7 @@ where
// chunks in case if there are same modules being imported in differnt
// origins.
let chunk_group = build_chunk(module).await?;
chunks_hash.insert(imported_raw_str.to_string(), chunk_group);
chunks_hash.insert(imported_raw_str.clone(), chunk_group);
chunk_group
};
......@@ -178,22 +178,19 @@ pub(crate) async fn collect_next_dynamic_imports(
struct NextDynamicVisit;
impl turbo_tasks::graph::Visit<(Vc<Box<dyn Module>>, ReadRef<String>)> for NextDynamicVisit {
type Edge = (Vc<Box<dyn Module>>, ReadRef<String>);
impl turbo_tasks::graph::Visit<(Vc<Box<dyn Module>>, ReadRef<RcStr>)> for NextDynamicVisit {
type Edge = (Vc<Box<dyn Module>>, ReadRef<RcStr>);
type EdgesIntoIter = Vec<Self::Edge>;
type EdgesFuture = impl Future<Output = Result<Self::EdgesIntoIter>>;
fn visit(
&mut self,
edge: Self::Edge,
) -> VisitControlFlow<(Vc<Box<dyn Module>>, ReadRef<String>)> {
) -> VisitControlFlow<(Vc<Box<dyn Module>>, ReadRef<RcStr>)> {
VisitControlFlow::Continue(edge)
}
fn edges(
&mut self,
&(parent, _): &(Vc<Box<dyn Module>>, ReadRef<String>),
) -> Self::EdgesFuture {
fn edges(&mut self, &(parent, _): &(Vc<Box<dyn Module>>, ReadRef<RcStr>)) -> Self::EdgesFuture {
async move {
primary_referenced_modules(parent)
.await?
......@@ -204,7 +201,7 @@ impl turbo_tasks::graph::Visit<(Vc<Box<dyn Module>>, ReadRef<String>)> for NextD
}
}
fn span(&mut self, (_, name): &(Vc<Box<dyn Module>>, ReadRef<String>)) -> tracing::Span {
fn span(&mut self, (_, name): &(Vc<Box<dyn Module>>, ReadRef<RcStr>)) -> tracing::Span {
tracing::span!(Level::INFO, "next/dynamic visit", name = display(name))
}
}
......@@ -244,7 +241,7 @@ async fn build_dynamic_imports_map_for_module(
client_asset_context,
server_module.ident().path(),
)),
Request::parse(Value::new(Pattern::Constant(import.to_string()))),
Request::parse(Value::new(Pattern::Constant(import.clone()))),
Value::new(EcmaScriptModulesReferenceSubType::DynamicImport),
IssueSeverity::Error.cell(),
None,
......@@ -264,7 +261,7 @@ async fn build_dynamic_imports_map_for_module(
/// import wrapped with dynamic() via CollectImportSourceVisitor.
struct DynamicImportVisitor {
dynamic_ident: Option<Ident>,
pub import_sources: Vec<String>,
pub import_sources: Vec<RcStr>,
}
impl DynamicImportVisitor {
......@@ -309,7 +306,7 @@ impl Visit for DynamicImportVisitor {
/// A visitor to collect import source string from import('path/to/module')
struct CollectImportSourceVisitor {
import_source: Option<String>,
import_source: Option<RcStr>,
}
impl CollectImportSourceVisitor {
......@@ -329,7 +326,7 @@ impl Visit for CollectImportSourceVisitor {
if let Callee::Import(_import) = call_expr.callee {
if let Some(arg) = call_expr.args.first() {
if let Expr::Lit(Lit::Str(str_)) = &*arg.expr {
self.import_source = Some(str_.value.to_string());
self.import_source = Some(str_.value.as_str().into());
}
}
}
......@@ -339,8 +336,8 @@ impl Visit for CollectImportSourceVisitor {
}
}
pub type DynamicImportedModules = Vec<(String, Vc<Box<dyn Module>>)>;
pub type DynamicImportedOutputAssets = Vec<(String, Vc<OutputAssets>)>;
pub type DynamicImportedModules = Vec<(RcStr, Vc<Box<dyn Module>>)>;
pub type DynamicImportedOutputAssets = Vec<(RcStr, Vc<OutputAssets>)>;
/// A struct contains mapping for the dynamic imports to construct chunk per
/// each individual module (Origin Module, Vec<(ImportSourceString, Module)>)
......
use indexmap::IndexMap;
use turbo_tasks::Vc;
use turbo_tasks::{RcStr, Vc};
use crate::{
project::{Instrumentation, Middleware},
......@@ -8,7 +8,7 @@ use crate::{
#[turbo_tasks::value(shared)]
pub struct Entrypoints {
pub routes: IndexMap<String, Route>,
pub routes: IndexMap<RcStr, Route>,
pub middleware: Option<Middleware>,
pub instrumentation: Option<Instrumentation>,
pub pages_document_endpoint: Vc<Box<dyn Endpoint>>,
......
use anyhow::Result;
use next_core::{all_assets_from_entries, next_manifests::NextFontManifest};
use turbo_tasks::{ValueToString, Vc};
use turbo_tasks::{RcStr, ValueToString, Vc};
use turbopack_binding::{
turbo::tasks_fs::{File, FileSystemPath},
turbopack::core::{
......@@ -34,13 +34,9 @@ pub(crate) async fn create_font_manifest(
.collect();
let path = if app_dir {
node_root.join(format!(
"server/app{manifest_path_prefix}/next-font-manifest.json",
))
node_root.join(format!("server/app{manifest_path_prefix}/next-font-manifest.json",).into())
} else {
node_root.join(format!(
"server/pages{manifest_path_prefix}/next-font-manifest.json"
))
node_root.join(format!("server/pages{manifest_path_prefix}/next-font-manifest.json").into())
};
let has_fonts = !font_paths.is_empty();
......@@ -49,13 +45,14 @@ pub(crate) async fn create_font_manifest(
let font_paths = font_paths
.into_iter()
.filter(|path| path.contains(".p."))
.map(RcStr::from)
.collect::<Vec<_>>();
let next_font_manifest = if !has_fonts {
Default::default()
} else if app_dir {
let dir_str = dir.to_string().await?;
let page_path = format!("{}{}", dir_str, original_name);
let page_path = format!("{}{}", dir_str, original_name).into();
NextFontManifest {
app: [(page_path, font_paths)].into_iter().collect(),
......@@ -64,7 +61,7 @@ pub(crate) async fn create_font_manifest(
}
} else {
NextFontManifest {
pages: [(pathname.to_string(), font_paths)].into_iter().collect(),
pages: [(pathname.into(), font_paths)].into_iter().collect(),
pages_using_size_adjust: using_size_adjust,
..Default::default()
}
......
......@@ -73,7 +73,7 @@ impl InstrumentationEndpoint {
self.context,
self.project.project_path(),
userland_module,
"instrumentation".to_string(),
"instrumentation".into(),
);
let mut evaluatable_assets = get_server_runtime_entries(
......@@ -126,7 +126,7 @@ impl InstrumentationEndpoint {
.entry_chunk_group(
self.project
.node_root()
.join("server/instrumentation.js".to_string()),
.join("server/instrumentation.js".into()),
module,
get_server_runtime_entries(
Value::new(ServerContextType::Instrumentation),
......@@ -161,7 +161,7 @@ impl InstrumentationEndpoint {
let instrumentation_definition = InstrumentationDefinition {
files: file_paths_from_root,
wasm: wasm_paths_to_bindings(wasm_paths_from_root),
name: "instrumentation".to_string(),
name: "instrumentation".into(),
..Default::default()
};
let middleware_manifest_v2 = MiddlewaresManifestV2 {
......@@ -169,7 +169,7 @@ impl InstrumentationEndpoint {
..Default::default()
};
let middleware_manifest_v2 = Vc::upcast(VirtualOutputAsset::new(
node_root.join("server/instrumentation/middleware-manifest.json".to_string()),
node_root.join("server/instrumentation/middleware-manifest.json".into()),
AssetContent::file(
FileContent::Content(File::from(serde_json::to_string_pretty(
&middleware_manifest_v2,
......
......@@ -2,7 +2,7 @@ use std::collections::HashMap;
use anyhow::Result;
use next_core::next_manifests::LoadableManifest;
use turbo_tasks::{TryFlatJoinIterExt, Vc};
use turbo_tasks::{RcStr, TryFlatJoinIterExt, Vc};
use turbopack_binding::{
turbo::tasks_fs::{File, FileContent, FileSystemPath},
turbopack::core::{
......@@ -24,7 +24,7 @@ pub async fn create_react_loadable_manifest(
let dynamic_import_entries = &*dynamic_import_entries.await?;
let mut output = vec![];
let mut loadable_manifest: HashMap<String, LoadableManifest> = Default::default();
let mut loadable_manifest: HashMap<RcStr, LoadableManifest> = Default::default();
for (origin, dynamic_imports) in dynamic_import_entries.into_iter() {
let origin_path = &*origin.ident().path().await?;
......@@ -33,7 +33,7 @@ pub async fn create_react_loadable_manifest(
let chunk_output = chunk_output.await?;
output.extend(chunk_output.iter().copied());
let id = format!("{} -> {}", origin_path, import);
let id: RcStr = format!("{} -> {}", origin_path, import).into();
let client_relative_path_value = client_relative_path.await?;
let files = chunk_output
......@@ -43,7 +43,7 @@ pub async fn create_react_loadable_manifest(
async move {
Ok(client_relative_path_value
.get_path_to(&*file.ident().path().await?)
.map(|path| path.to_string()))
.map(|path| path.into()))
}
})
.try_flat_join()
......
......@@ -75,7 +75,7 @@ impl MiddlewareEndpoint {
self.context,
self.project.project_path(),
module,
"middleware".to_string(),
"middleware".into(),
);
let mut evaluatable_assets = get_server_runtime_entries(
......@@ -140,7 +140,7 @@ impl MiddlewareEndpoint {
.iter()
.map(|matcher| match matcher {
MiddlewareMatcherKind::Str(matchers) => MiddlewareMatcher {
original_source: matchers.to_string(),
original_source: matchers.as_str().into(),
..Default::default()
},
MiddlewareMatcherKind::Matcher(matcher) => matcher.clone(),
......@@ -148,8 +148,8 @@ impl MiddlewareEndpoint {
.collect()
} else {
vec![MiddlewareMatcher {
regexp: Some("^/.*$".to_string()),
original_source: "/:path*".to_string(),
regexp: Some("^/.*$".into()),
original_source: "/:path*".into(),
..Default::default()
}]
};
......@@ -157,21 +157,21 @@ impl MiddlewareEndpoint {
let edge_function_definition = EdgeFunctionDefinition {
files: file_paths_from_root,
wasm: wasm_paths_to_bindings(wasm_paths_from_root),
name: "middleware".to_string(),
page: "/".to_string(),
name: "middleware".into(),
page: "/".into(),
regions: None,
matchers,
env: this.project.edge_env().await?.clone_value(),
..Default::default()
};
let middleware_manifest_v2 = MiddlewaresManifestV2 {
middleware: [("/".to_string(), edge_function_definition)]
middleware: [("/".into(), edge_function_definition)]
.into_iter()
.collect(),
..Default::default()
};
let middleware_manifest_v2 = Vc::upcast(VirtualOutputAsset::new(
node_root.join("server/middleware/middleware-manifest.json".to_string()),
node_root.join("server/middleware/middleware-manifest.json".into()),
AssetContent::file(
FileContent::Content(File::from(serde_json::to_string_pretty(
&middleware_manifest_v2,
......
use anyhow::Result;
use next_core::{all_assets_from_entries, next_manifests::AssetBinding};
use serde::{Deserialize, Serialize};
use turbo_tasks::{trace::TraceRawVcs, TryFlatJoinIterExt, Vc};
use turbo_tasks::{trace::TraceRawVcs, RcStr, TryFlatJoinIterExt, Vc};
use turbopack_binding::{
turbo::tasks_fs::FileSystemPath,
turbopack::core::{
......@@ -62,7 +62,7 @@ pub async fn all_server_paths(
pub async fn all_paths_in_root(
assets: Vc<OutputAssets>,
root: Vc<FileSystemPath>,
) -> Result<Vc<Vec<String>>> {
) -> Result<Vc<Vec<RcStr>>> {
let all_assets = &*all_assets_from_entries(assets).await?;
let root = &*root.await?;
......@@ -75,7 +75,7 @@ pub(crate) async fn get_paths_from_root(
root: &FileSystemPath,
output_assets: &[Vc<Box<dyn OutputAsset>>],
filter: impl FnOnce(&str) -> bool + Copy,
) -> Result<Vec<String>> {
) -> Result<Vec<RcStr>> {
output_assets
.iter()
.map({
......@@ -86,7 +86,7 @@ pub(crate) async fn get_paths_from_root(
};
Ok(if filter(relative) {
Some(relative.to_string())
Some(relative.into())
} else {
None
})
......@@ -99,21 +99,21 @@ pub(crate) async fn get_paths_from_root(
pub(crate) async fn get_js_paths_from_root(
root: &FileSystemPath,
output_assets: &[Vc<Box<dyn OutputAsset>>],
) -> Result<Vec<String>> {
) -> Result<Vec<RcStr>> {
get_paths_from_root(root, output_assets, |path| path.ends_with(".js")).await
}
pub(crate) async fn get_wasm_paths_from_root(
root: &FileSystemPath,
output_assets: &[Vc<Box<dyn OutputAsset>>],
) -> Result<Vec<String>> {
) -> Result<Vec<RcStr>> {
get_paths_from_root(root, output_assets, |path| path.ends_with(".wasm")).await
}
pub(crate) async fn get_font_paths_from_root(
root: &FileSystemPath,
output_assets: &[Vc<Box<dyn OutputAsset>>],
) -> Result<Vec<String>> {
) -> Result<Vec<RcStr>> {
get_paths_from_root(root, output_assets, |path| {
path.ends_with(".woff")
|| path.ends_with(".woff2")
......@@ -142,7 +142,7 @@ fn get_file_stem(path: &str) -> &str {
}
}
pub(crate) fn wasm_paths_to_bindings(paths: Vec<String>) -> Vec<AssetBinding> {
pub(crate) fn wasm_paths_to_bindings(paths: Vec<RcStr>) -> Vec<AssetBinding> {
paths
.into_iter()
.map(|path| {
......@@ -155,7 +155,7 @@ pub(crate) fn wasm_paths_to_bindings(paths: Vec<String>) -> Vec<AssetBinding> {
);
AssetBinding {
name: format!("wasm_{}", escaped),
name: format!("wasm_{}", escaped).into(),
file_path: path,
}
})
......
use anyhow::Result;
use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
use turbo_tasks::{debug::ValueDebugFormat, trace::TraceRawVcs, Completion, Vc};
use turbo_tasks::{debug::ValueDebugFormat, trace::TraceRawVcs, Completion, RcStr, Vc};
use crate::paths::ServerPath;
......@@ -84,15 +84,15 @@ pub enum WrittenEndpoint {
/// Relative to the root_path
server_entry_path: String,
server_paths: Vec<ServerPath>,
client_paths: Vec<String>,
client_paths: Vec<RcStr>,
},
Edge {
server_paths: Vec<ServerPath>,
client_paths: Vec<String>,
client_paths: Vec<RcStr>,
},
}
/// The routes as map from pathname to route. (pathname includes the leading
/// slash)
#[turbo_tasks::value(transparent)]
pub struct Routes(IndexMap<String, Route>);
pub struct Routes(IndexMap<RcStr, Route>);
......@@ -9,7 +9,7 @@ use next_core::{
use tracing::Instrument;
use turbo_tasks::{
graph::{GraphTraversal, NonDeterministic},
TryFlatJoinIterExt, Value, ValueToString, Vc,
RcStr, TryFlatJoinIterExt, Value, ValueToString, Vc,
};
use turbopack_binding::{
swc::core::{common::comments::Comments, ecma::ast::Program},
......@@ -54,7 +54,7 @@ pub(crate) async fn create_server_actions_manifest(
) -> Result<(Vc<Box<dyn EvaluatableAsset>>, Vc<Box<dyn OutputAsset>>)> {
let actions = get_actions(rsc_entry, server_reference_modules, asset_context);
let loader =
build_server_actions_loader(project_path, page_name.to_string(), actions, asset_context);
build_server_actions_loader(project_path, page_name.into(), actions, asset_context);
let evaluable = Vc::try_resolve_sidecast::<Box<dyn EvaluatableAsset>>(loader)
.await?
.context("loader module must be evaluatable")?;
......@@ -76,7 +76,7 @@ pub(crate) async fn create_server_actions_manifest(
#[turbo_tasks::function]
async fn build_server_actions_loader(
project_path: Vc<FileSystemPath>,
page_name: String,
page_name: RcStr,
actions: Vc<AllActions>,
asset_context: Vc<Box<dyn AssetContext>>,
) -> Result<Vc<Box<dyn EcmascriptChunkPlaceable>>> {
......@@ -92,7 +92,7 @@ async fn build_server_actions_loader(
let index = import_map.len();
let module_name = import_map
.entry(*module)
.or_insert_with(|| format!("ACTIONS_MODULE{index}"));
.or_insert_with(|| format!("ACTIONS_MODULE{index}").into());
writeln!(
contents,
" '{hash_id}': (...args) => Promise.resolve(require('{module_name}')).then(mod => \
......@@ -101,7 +101,8 @@ async fn build_server_actions_loader(
}
write!(contents, "}});")?;
let output_path = project_path.join(format!(".next-internal/server/app{page_name}/actions.js"));
let output_path =
project_path.join(format!(".next-internal/server/app{page_name}/actions.js").into());
let file = File::from(contents.build());
let source = VirtualSource::new(output_path, AssetContent::file(file.into()));
let import_map = import_map.into_iter().map(|(k, v)| (v, k)).collect();
......@@ -128,12 +129,11 @@ async fn build_manifest(
page_name: &str,
runtime: NextRuntime,
actions: Vc<AllActions>,
loader_id: Vc<String>,
loader_id: Vc<RcStr>,
) -> Result<Vc<Box<dyn OutputAsset>>> {
let manifest_path_prefix = page_name;
let manifest_path = node_root.join(format!(
"server/app{manifest_path_prefix}/server-reference-manifest.json",
));
let manifest_path = node_root
.join(format!("server/app{manifest_path_prefix}/server-reference-manifest.json",).into());
let mut manifest = ServerReferenceManifest {
..Default::default()
};
......@@ -163,8 +163,8 @@ async fn build_manifest(
}
#[turbo_tasks::function]
fn action_modifier() -> Vc<String> {
Vc::cell("action".to_string())
fn action_modifier() -> Vc<RcStr> {
Vc::cell("action".into())
}
/// Traverses the entire module graph starting from [Module], looking for magic
......
......@@ -4,7 +4,7 @@ use anyhow::{bail, Result};
use next_core::emit_client_assets;
use serde::{Deserialize, Serialize};
use turbo_tasks::{
debug::ValueDebugFormat, trace::TraceRawVcs, Completion, State, TryFlatJoinIterExt,
debug::ValueDebugFormat, trace::TraceRawVcs, Completion, RcStr, State, TryFlatJoinIterExt,
TryJoinIterExt, ValueDefault, ValueToString, Vc,
};
use turbopack_binding::{
......@@ -124,7 +124,7 @@ impl VersionedContentMap {
pub async fn get_source_map(
self: Vc<Self>,
path: Vc<FileSystemPath>,
section: Option<String>,
section: Option<RcStr>,
) -> Result<Vc<OptionSourceMap>> {
if let Some(generate_source_map) =
Vc::try_resolve_sidecast::<Box<dyn GenerateSourceMap>>(self.get_asset(path)).await?
......@@ -169,7 +169,7 @@ impl VersionedContentMap {
}
#[turbo_tasks::function]
pub async fn keys_in_path(&self, root: Vc<FileSystemPath>) -> Result<Vc<Vec<String>>> {
pub async fn keys_in_path(&self, root: Vc<FileSystemPath>) -> Result<Vc<Vec<RcStr>>> {
let keys = {
let map = self.map_path_to_op.get();
map.keys().copied().collect::<Vec<_>>()
......@@ -177,7 +177,7 @@ impl VersionedContentMap {
let root = &root.await?;
let keys = keys
.into_iter()
.map(|path| async move { Ok(root.get_path_to(&*path.await?).map(|p| p.to_string())) })
.map(|path| async move { Ok(root.get_path_to(&*path.await?).map(RcStr::from)) })
.try_flat_join()
.await?;
Ok(Vc::cell(keys))
......
......@@ -3,7 +3,7 @@ use std::ops::Deref;
use anyhow::{bail, Result};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use turbo_tasks::{trace::TraceRawVcs, TryJoinIterExt, ValueDefault, Vc};
use turbo_tasks::{trace::TraceRawVcs, RcStr, TryJoinIterExt, ValueDefault, Vc};
use turbo_tasks_fs::FileSystemPath;
use turbopack_binding::{
swc::core::{
......@@ -71,7 +71,7 @@ pub struct NextSegmentConfig {
pub revalidate: Option<NextRevalidate>,
pub fetch_cache: Option<NextSegmentFetchCache>,
pub runtime: Option<NextRuntime>,
pub preferred_region: Option<Vec<String>>,
pub preferred_region: Option<Vec<RcStr>>,
pub experimental_ppr: Option<bool>,
}
......@@ -178,7 +178,7 @@ impl Issue for NextSegmentConfigParsingIssue {
#[turbo_tasks::function]
fn title(&self) -> Vc<StyledString> {
StyledString::Text("Unable to parse config export in source file".to_string()).cell()
StyledString::Text("Unable to parse config export in source file".into()).cell()
}
#[turbo_tasks::function]
......@@ -197,7 +197,7 @@ impl Issue for NextSegmentConfigParsingIssue {
StyledString::Text(
"The exported configuration object in a source file need to have a very specific \
format from which some properties can be statically parsed at compiled-time."
.to_string(),
.into(),
)
.cell(),
))
......@@ -209,10 +209,10 @@ impl Issue for NextSegmentConfigParsingIssue {
}
#[turbo_tasks::function]
fn documentation_link(&self) -> Vc<String> {
fn documentation_link(&self) -> Vc<RcStr> {
Vc::cell(
"https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config"
.to_string(),
.into(),
)
}
......@@ -312,7 +312,7 @@ fn parse_config_value(
let (explainer, hints) = value.explain(2, 0);
NextSegmentConfigParsingIssue {
ident: source.ident(),
detail: StyledString::Text(format!("{detail} Got {explainer}.{hints}")).cell(),
detail: StyledString::Text(format!("{detail} Got {explainer}.{hints}").into()).cell(),
source: issue_source(source, span),
}
.cell()
......@@ -402,14 +402,14 @@ fn parse_config_value(
let preferred_region = match value {
// Single value is turned into a single-element Vec.
JsValue::Constant(ConstantValue::Str(str)) => vec![str.to_string()],
JsValue::Constant(ConstantValue::Str(str)) => vec![str.to_string().into()],
// Array of strings is turned into a Vec. If one of the values in not a String it
// will error.
JsValue::Array { items, .. } => {
let mut regions = Vec::new();
for item in items {
if let JsValue::Constant(ConstantValue::Str(str)) = item {
regions.push(str.to_string());
regions.push(str.to_string().into());
} else {
invalid_config(
"Values of the `preferredRegion` array need to static strings",
......
......@@ -80,7 +80,7 @@ pub async fn bootstrap(
let config_asset = context
.process(
Vc::upcast(VirtualSource::new(
asset.ident().path().join("bootstrap-config.ts".to_string()),
asset.ident().path().join("bootstrap-config.ts".into()),
AssetContent::file(
File::from(
config
......@@ -97,8 +97,8 @@ pub async fn bootstrap(
.module();
let mut inner_assets = inner_assets.await?.clone_value();
inner_assets.insert("ENTRY".to_string(), asset);
inner_assets.insert("BOOTSTRAP_CONFIG".to_string(), config_asset);
inner_assets.insert("ENTRY".into(), asset);
inner_assets.insert("BOOTSTRAP_CONFIG".into(), config_asset);
let asset = context
.process(
......
use turbo_tasks::Vc;
use turbo_tasks::{RcStr, Vc};
use turbopack_binding::{
turbo::tasks_fs::{FileContent, FileSystem, FileSystemPath},
turbopack::core::{file_source::FileSource, source::Source},
......@@ -13,16 +13,16 @@ pub(crate) fn next_js_fs() -> Vc<Box<dyn FileSystem>> {
}
#[turbo_tasks::function]
pub(crate) fn next_js_file(path: String) -> Vc<FileContent> {
pub(crate) fn next_js_file(path: RcStr) -> Vc<FileContent> {
next_js_fs().root().join(path).read()
}
#[turbo_tasks::function]
pub(crate) fn next_js_file_path(path: String) -> Vc<FileSystemPath> {
pub(crate) fn next_js_file_path(path: RcStr) -> Vc<FileSystemPath> {
next_js_fs().root().join(path)
}
#[turbo_tasks::function]
pub(crate) fn next_asset(path: String) -> Vc<Box<dyn Source>> {
pub(crate) fn next_asset(path: RcStr) -> Vc<Box<dyn Source>> {
Vc::upcast(FileSource::new(next_js_file_path(path)))
}
use anyhow::Result;
use turbo_tasks::Vc;
use turbo_tasks::{RcStr, Vc};
#[turbo_tasks::function]
pub async fn instrumentation_files(page_extensions: Vc<Vec<String>>) -> Result<Vc<Vec<String>>> {
pub async fn instrumentation_files(page_extensions: Vc<Vec<RcStr>>) -> Result<Vc<Vec<RcStr>>> {
let extensions = page_extensions.await?;
let files = ["instrumentation.", "src/instrumentation."]
.into_iter()
......@@ -10,6 +10,7 @@ pub async fn instrumentation_files(page_extensions: Vc<Vec<String>>) -> Result<V
extensions
.iter()
.map(move |ext| String::from(f) + ext.as_str())
.map(RcStr::from)
})
.collect();
Ok(Vc::cell(files))
......
......@@ -7,7 +7,7 @@ use anyhow::Result;
use async_recursion::async_recursion;
use indexmap::IndexMap;
use indoc::formatdoc;
use turbo_tasks::{Value, ValueToString, Vc};
use turbo_tasks::{RcStr, Value, ValueToString, Vc};
use turbo_tasks_fs::FileSystemPath;
use turbopack_binding::turbopack::{
core::{
......@@ -33,15 +33,15 @@ use crate::{
};
pub struct LoaderTreeBuilder {
inner_assets: IndexMap<String, Vc<Box<dyn Module>>>,
inner_assets: IndexMap<RcStr, Vc<Box<dyn Module>>>,
counter: usize,
imports: Vec<String>,
imports: Vec<RcStr>,
loader_tree_code: String,
context: Vc<ModuleAssetContext>,
server_component_transition: Vc<Box<dyn Transition>>,
pages: Vec<Vc<FileSystemPath>>,
/// next.config.js' basePath option to construct og metadata.
base_path: Option<String>,
base_path: Option<RcStr>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
......@@ -73,7 +73,7 @@ impl LoaderTreeBuilder {
fn new(
context: Vc<ModuleAssetContext>,
server_component_transition: Vc<Box<dyn Transition>>,
base_path: Option<String>,
base_path: Option<RcStr>,
) -> Self {
LoaderTreeBuilder {
inner_assets: IndexMap::new(),
......@@ -123,15 +123,19 @@ impl LoaderTreeBuilder {
path = StringifyJs(&module.ident().path().to_string().await?)
)?;
self.imports.push(formatdoc!(
r#"
self.imports.push(
formatdoc!(
r#"
import {} from "COMPONENT_{}";
"#,
identifier,
i
));
identifier,
i
)
.into(),
);
self.inner_assets.insert(format!("COMPONENT_{i}"), module);
self.inner_assets
.insert(format!("COMPONENT_{i}").into(), module);
}
Ok(())
}
......@@ -240,12 +244,12 @@ impl LoaderTreeBuilder {
let inner_module_id = format!("METADATA_{i}");
self.imports
.push(format!("import {identifier} from \"{inner_module_id}\";"));
.push(format!("import {identifier} from \"{inner_module_id}\";").into());
let source = dynamic_image_metadata_source(
Vc::upcast(self.context),
*path,
name.to_string(),
name.into(),
app_page.clone(),
);
......@@ -258,7 +262,7 @@ impl LoaderTreeBuilder {
)),
)
.module();
self.inner_assets.insert(inner_module_id, module);
self.inner_assets.insert(inner_module_id.into(), module);
let s = " ";
writeln!(self.loader_tree_code, "{s}{identifier},")?;
......@@ -279,18 +283,18 @@ impl LoaderTreeBuilder {
let identifier = magic_identifier::mangle(&format!("{name} #{i}"));
let inner_module_id = format!("METADATA_{i}");
let helper_import = "import { fillMetadataSegment } from \
\"next/dist/lib/metadata/get-metadata-route\""
.to_string();
let helper_import: RcStr = "import { fillMetadataSegment } from \
\"next/dist/lib/metadata/get-metadata-route\""
.into();
if !self.imports.contains(&helper_import) {
self.imports.push(helper_import);
}
self.imports
.push(format!("import {identifier} from \"{inner_module_id}\";"));
.push(format!("import {identifier} from \"{inner_module_id}\";").into());
self.inner_assets.insert(
inner_module_id,
inner_module_id.into(),
Vc::upcast(StructuredImageModuleType::create_module(
Vc::upcast(FileSource::new(path)),
BlurPlaceholderMode::None,
......@@ -332,7 +336,7 @@ impl LoaderTreeBuilder {
let identifier = magic_identifier::mangle(&format!("{name} alt text #{i}"));
let inner_module_id = format!("METADATA_ALT_{i}");
self.imports
.push(format!("import {identifier} from \"{inner_module_id}\";"));
.push(format!("import {identifier} from \"{inner_module_id}\";").into());
let module = self
.context
.process(
......@@ -342,7 +346,7 @@ impl LoaderTreeBuilder {
Value::new(ReferenceType::Internal(InnerAssets::empty())),
)
.module();
self.inner_assets.insert(inner_module_id, module);
self.inner_assets.insert(inner_module_id.into(), module);
writeln!(self.loader_tree_code, "{s} alt: {identifier},")?;
}
......@@ -425,7 +429,7 @@ impl LoaderTreeBuilder {
self.walk_tree(loader_tree, true).await?;
Ok(LoaderTreeModule {
imports: self.imports,
loader_tree_code: self.loader_tree_code,
loader_tree_code: self.loader_tree_code.into(),
inner_assets: self.inner_assets,
pages: self.pages,
})
......@@ -433,9 +437,9 @@ impl LoaderTreeBuilder {
}
pub struct LoaderTreeModule {
pub imports: Vec<String>,
pub loader_tree_code: String,
pub inner_assets: IndexMap<String, Vc<Box<dyn Module>>>,
pub imports: Vec<RcStr>,
pub loader_tree_code: RcStr,
pub inner_assets: IndexMap<RcStr, Vc<Box<dyn Module>>>,
pub pages: Vec<Vc<FileSystemPath>>,
}
......@@ -444,7 +448,7 @@ impl LoaderTreeModule {
loader_tree: Vc<LoaderTree>,
context: Vc<ModuleAssetContext>,
server_component_transition: Vc<Box<dyn Transition>>,
base_path: Option<String>,
base_path: Option<RcStr>,
) -> Result<Self> {
LoaderTreeBuilder::new(context, server_component_transition, base_path)
.build(loader_tree)
......
use anyhow::Result;
use indexmap::indexmap;
use turbo_tasks::{Value, Vc};
use turbo_tasks::{RcStr, Value, Vc};
use turbo_tasks_fs::FileSystemPath;
use turbopack_binding::turbopack::core::{
context::AssetContext, module::Module, reference_type::ReferenceType,
......@@ -9,7 +9,7 @@ use turbopack_binding::turbopack::core::{
use crate::util::load_next_js_template;
#[turbo_tasks::function]
pub async fn middleware_files(page_extensions: Vc<Vec<String>>) -> Result<Vc<Vec<String>>> {
pub async fn middleware_files(page_extensions: Vc<Vec<RcStr>>) -> Result<Vc<Vec<RcStr>>> {
let extensions = page_extensions.await?;
let files = ["middleware.", "src/middleware."]
.into_iter()
......@@ -17,6 +17,7 @@ pub async fn middleware_files(page_extensions: Vc<Vec<String>>) -> Result<Vc<Vec
extensions
.iter()
.map(move |ext| String::from(f) + ext.as_str())
.map(RcStr::from)
})
.collect();
Ok(Vc::cell(files))
......@@ -35,8 +36,8 @@ pub async fn get_middleware_module(
"middleware.js",
project_root,
indexmap! {
"VAR_USERLAND" => INNER.to_string(),
"VAR_DEFINITION_PAGE" => "/middleware".to_string(),
"VAR_USERLAND" => INNER.into(),
"VAR_DEFINITION_PAGE" => "/middleware".into(),
},
indexmap! {},
indexmap! {},
......@@ -44,7 +45,7 @@ pub async fn get_middleware_module(
.await?;
let inner_assets = indexmap! {
INNER.to_string() => userland_module
INNER.into() => userland_module
};
let module = context
......
use anyhow::Result;
use indexmap::IndexMap;
use tracing::Instrument;
use turbo_tasks::{TryFlatJoinIterExt, TryJoinIterExt, Value, ValueToString, Vc};
use turbo_tasks::{RcStr, TryFlatJoinIterExt, TryJoinIterExt, Value, ValueToString, Vc};
use turbopack_binding::turbopack::core::{
chunk::{availability_info::AvailabilityInfo, ChunkingContext, ChunkingContextExt},
module::Module,
......@@ -18,13 +18,13 @@ use crate::{
};
#[turbo_tasks::function]
fn client_modules_modifier() -> Vc<String> {
Vc::cell("client modules".to_string())
fn client_modules_modifier() -> Vc<RcStr> {
Vc::cell("client modules".into())
}
#[turbo_tasks::function]
fn client_modules_ssr_modifier() -> Vc<String> {
Vc::cell("client modules ssr".to_string())
fn client_modules_ssr_modifier() -> Vc<RcStr> {
Vc::cell("client modules ssr".into())
}
#[turbo_tasks::value]
......
use turbo_tasks::Vc;
use turbo_tasks::{RcStr, Vc};
use turbopack_binding::turbopack::ecmascript::chunk::EcmascriptChunkPlaceable;
use crate::app_segment_config::NextSegmentConfig;
......@@ -7,10 +7,10 @@ use crate::app_segment_config::NextSegmentConfig;
#[turbo_tasks::value(shared)]
pub struct AppEntry {
/// The pathname of the route or page.
pub pathname: String,
pub pathname: RcStr,
/// The original Next.js name of the route or page. This is used instead of
/// the pathname to refer to this entry.
pub original_name: String,
pub original_name: RcStr,
/// The RSC module asset for the route or page.
pub rsc_entry: Vc<Box<dyn EcmascriptChunkPlaceable>>,
/// The source code config for this entry.
......
......@@ -2,7 +2,7 @@ use std::io::Write;
use anyhow::{bail, Result};
use indexmap::indexmap;
use turbo_tasks::{TryJoinIterExt, Value, ValueToString, Vc};
use turbo_tasks::{RcStr, TryJoinIterExt, Value, ValueToString, Vc};
use turbopack_binding::{
turbo::tasks_fs::{rope::RopeBuilder, File, FileSystemPath},
turbopack::{
......@@ -71,25 +71,25 @@ pub async fn get_app_page_entry(
let pages = pages.iter().map(|page| page.to_string()).try_join().await?;
let original_name = page.to_string();
let pathname = AppPath::from(page.clone()).to_string();
let original_name: RcStr = page.to_string().into();
let pathname: RcStr = AppPath::from(page.clone()).to_string().into();
// Load the file from the next.js codebase.
let source = load_next_js_template(
"app-page.js",
project_root,
indexmap! {
"VAR_DEFINITION_PAGE" => page.to_string(),
"VAR_DEFINITION_PAGE" => page.to_string().into(),
"VAR_DEFINITION_PATHNAME" => pathname.clone(),
"VAR_ORIGINAL_PATHNAME" => original_name.clone(),
// TODO(alexkirsz) Support custom global error.
"VAR_MODULE_GLOBAL_ERROR" => "next/dist/client/components/error-boundary".to_string(),
"VAR_MODULE_GLOBAL_ERROR" => "next/dist/client/components/error-boundary".into(),
},
indexmap! {
"tree" => loader_tree_code,
"pages" => StringifyJs(&pages).to_string(),
"__next_app_require__" => "__turbopack_require__".to_string(),
"__next_app_load_chunk__" => " __turbopack_load__".to_string(),
"pages" => StringifyJs(&pages).to_string().into(),
"__next_app_require__" => "__turbopack_require__".into(),
"__next_app_load_chunk__" => " __turbopack_load__".into(),
},
indexmap! {},
)
......@@ -103,7 +103,9 @@ pub async fn get_app_page_entry(
let file = File::from(result.build());
let source = VirtualSource::new_with_ident(
source.ident().with_query(Vc::cell(query.to_string())),
source
.ident()
.with_query(Vc::cell(query.to_string().into())),
AssetContent::file(file.into()),
);
......@@ -171,15 +173,15 @@ async fn wrap_edge_page(
"edge-ssr-app.js",
project_root,
indexmap! {
"VAR_USERLAND" => INNER.to_string(),
"VAR_PAGE" => page.to_string(),
"VAR_USERLAND" => INNER.into(),
"VAR_PAGE" => page.to_string().into(),
},
indexmap! {
"sriEnabled" => serde_json::Value::Bool(sri_enabled).to_string(),
"nextConfig" => serde_json::to_string(next_config)?,
"isServerComponent" => serde_json::Value::Bool(is_server_component).to_string(),
"dev" => serde_json::Value::Bool(dev).to_string(),
"serverActions" => serde_json::to_string(&server_actions)?
"sriEnabled" => serde_json::Value::Bool(sri_enabled).to_string().into(),
"nextConfig" => serde_json::to_string(next_config)?.into(),
"isServerComponent" => serde_json::Value::Bool(is_server_component).to_string().into(),
"dev" => serde_json::Value::Bool(dev).to_string().into(),
"serverActions" => serde_json::to_string(&server_actions)?.into(),
},
indexmap! {
"incrementalCacheHandler" => None,
......@@ -188,7 +190,7 @@ async fn wrap_edge_page(
.await?;
let inner_assets = indexmap! {
INNER.to_string() => entry
INNER.into() => entry
};
let wrapped = context
......@@ -202,6 +204,6 @@ async fn wrap_edge_page(
context,
project_root,
wrapped,
AppPath::from(page).to_string(),
AppPath::from(page).to_string().into(),
))
}
use anyhow::{bail, Result};
use indexmap::indexmap;
use turbo_tasks::{Value, ValueToString, Vc};
use turbo_tasks::{RcStr, Value, ValueToString, Vc};
use turbopack_binding::{
turbo::tasks_fs::FileSystemPath,
turbopack::{
......@@ -57,14 +57,14 @@ pub async fn get_app_route_entry(
nodejs_context
};
let original_name = page.to_string();
let pathname = AppPath::from(page.clone()).to_string();
let original_name: RcStr = page.to_string().into();
let pathname: RcStr = AppPath::from(page.clone()).to_string().into();
let path = source.ident().path();
const INNER: &str = "INNER_APP_ROUTE";
let output_type = next_config
let output_type: RcStr = next_config
.await?
.output
.as_ref()
......@@ -72,21 +72,22 @@ pub async fn get_app_route_entry(
OutputType::Standalone => "\"standalone\"".to_string(),
OutputType::Export => "\"export\"".to_string(),
})
.unwrap_or_else(|| "\"\"".to_string());
.map(RcStr::from)
.unwrap_or_else(|| "\"\"".into());
// Load the file from the next.js codebase.
let virtual_source = load_next_js_template(
"app-route.js",
project_root,
indexmap! {
"VAR_DEFINITION_PAGE" => page.to_string(),
"VAR_DEFINITION_PAGE" => page.to_string().into(),
"VAR_DEFINITION_PATHNAME" => pathname.clone(),
"VAR_DEFINITION_FILENAME" => path.file_stem().await?.as_ref().unwrap().clone(),
"VAR_DEFINITION_FILENAME" => path.file_stem().await?.as_ref().unwrap().as_str().into(),
// TODO(alexkirsz) Is this necessary?
"VAR_DEFINITION_BUNDLE_PATH" => "".to_string(),
"VAR_DEFINITION_BUNDLE_PATH" => "".into(),
"VAR_ORIGINAL_PATHNAME" => original_name.clone(),
"VAR_RESOLVED_PAGE_PATH" => path.to_string().await?.clone_value(),
"VAR_USERLAND" => INNER.to_string(),
"VAR_USERLAND" => INNER.into(),
},
indexmap! {
"nextConfigOutput" => output_type
......@@ -103,7 +104,7 @@ pub async fn get_app_route_entry(
.module();
let inner_assets = indexmap! {
INNER.to_string() => userland_module
INNER.into() => userland_module
};
let mut rsc_entry = context
......@@ -142,7 +143,7 @@ async fn wrap_edge_route(
context: Vc<Box<dyn AssetContext>>,
project_root: Vc<FileSystemPath>,
entry: Vc<Box<dyn Module>>,
pathname: String,
pathname: RcStr,
) -> Result<Vc<Box<dyn Module>>> {
const INNER: &str = "INNER_ROUTE_ENTRY";
......@@ -150,7 +151,7 @@ async fn wrap_edge_route(
"edge-app-route.js",
project_root,
indexmap! {
"VAR_USERLAND" => INNER.to_string(),
"VAR_USERLAND" => INNER.into(),
},
indexmap! {},
indexmap! {},
......@@ -158,7 +159,7 @@ async fn wrap_edge_route(
.await?;
let inner_assets = indexmap! {
INNER.to_string() => entry
INNER.into() => entry
};
let wrapped = context
......
use anyhow::Result;
use turbo_tasks::{TryJoinIterExt, ValueToString, Vc};
use turbo_tasks::{RcStr, TryJoinIterExt, ValueToString, Vc};
use turbo_tasks_fs::glob::Glob;
use turbopack_binding::turbopack::{
core::{
......@@ -159,8 +159,8 @@ impl IncludedModuleReference {
#[turbo_tasks::value_impl]
impl ValueToString for IncludedModuleReference {
#[turbo_tasks::function]
fn to_string(&self) -> Vc<String> {
Vc::cell("module".to_string())
fn to_string(&self) -> Vc<RcStr> {
Vc::cell("module".into())
}
}
......
......@@ -4,7 +4,7 @@
use anyhow::{bail, Result};
use indoc::formatdoc;
use turbo_tasks::{ValueToString, Vc};
use turbo_tasks::{RcStr, ValueToString, Vc};
use turbo_tasks_fs::{File, FileContent, FileSystemPath};
use turbopack_binding::{
turbo::tasks_hash::hash_xxh3_hash64,
......@@ -46,7 +46,7 @@ async fn hash_file_content(path: Vc<FileSystemPath>) -> Result<u64> {
pub async fn dynamic_image_metadata_source(
asset_context: Vc<Box<dyn AssetContext>>,
path: Vc<FileSystemPath>,
ty: String,
ty: RcStr,
page: AppPage,
) -> Result<Vc<Box<dyn Source>>> {
let stem = path.file_stem().await?;
......@@ -126,7 +126,7 @@ pub async fn dynamic_image_metadata_source(
let file = File::from(code);
let source = VirtualSource::new(
path.parent().join(format!("{stem}--metadata.js")),
path.parent().join(format!("{stem}--metadata.js").into()),
AssetContent::file(file.into()),
);
......@@ -134,7 +134,7 @@ pub async fn dynamic_image_metadata_source(
}
#[turbo_tasks::function]
async fn collect_direct_exports(module: Vc<Box<dyn Module>>) -> Result<Vc<Vec<String>>> {
async fn collect_direct_exports(module: Vc<Box<dyn Module>>) -> Result<Vc<Vec<RcStr>>> {
let Some(ecmascript_asset) =
Vc::try_resolve_downcast_type::<EcmascriptModuleAsset>(module).await?
else {
......
......@@ -2,7 +2,7 @@ use std::{collections::HashMap, ops::Deref};
use anyhow::Result;
use once_cell::sync::Lazy;
use turbo_tasks::Vc;
use turbo_tasks::{RcStr, Vc};
use turbo_tasks_fs::FileSystemPath;
use crate::next_app::{AppPage, PageSegment, PageType};
......@@ -50,7 +50,7 @@ fn match_numbered_metadata(stem: &str) -> Option<(&str, &str)> {
fn match_metadata_file<'a>(
filename: &'a str,
page_extensions: &[String],
page_extensions: &[RcStr],
metadata: &HashMap<&str, &[&str]>,
) -> Option<MetadataFileMatch<'a>> {
let (stem, ext) = filename.split_once('.')?;
......@@ -115,7 +115,7 @@ pub(crate) async fn get_content_type(path: Vc<FileSystemPath>) -> Result<String>
pub fn match_local_metadata_file<'a>(
basename: &'a str,
page_extensions: &[String],
page_extensions: &[RcStr],
) -> Option<MetadataFileMatch<'a>> {
match_metadata_file(basename, page_extensions, STATIC_LOCAL_METADATA.deref())
}
......@@ -127,7 +127,7 @@ pub struct GlobalMetadataFileMatch<'a> {
pub fn match_global_metadata_file<'a>(
basename: &'a str,
page_extensions: &[String],
page_extensions: &[RcStr],
) -> Option<GlobalMetadataFileMatch<'a>> {
match_metadata_file(basename, page_extensions, STATIC_GLOBAL_METADATA.deref()).map(|m| {
GlobalMetadataFileMatch {
......@@ -183,7 +183,7 @@ fn file_stem(path: &str) -> &str {
/// /favicon, /manifest, use to match dynamic API routes like app/robots.ts.
pub fn is_metadata_route_file(
app_dir_relative_path: &str,
page_extensions: &[String],
page_extensions: &[RcStr],
with_extension: bool,
) -> bool {
let (dir, filename) = split_directory(app_dir_relative_path);
......@@ -326,17 +326,20 @@ pub fn normalize_metadata_route(mut page: AppPage) -> Result<AppPage> {
page.0.pop();
page.push(PageSegment::Static(format!(
"{}{}{}",
base_name,
suffix
.map(|suffix| format!("-{suffix}"))
.unwrap_or_default(),
ext.map(|ext| format!(".{ext}")).unwrap_or_default(),
)))?;
page.push(PageSegment::Static(
format!(
"{}{}{}",
base_name,
suffix
.map(|suffix| format!("-{suffix}"))
.unwrap_or_default(),
ext.map(|ext| format!(".{ext}")).unwrap_or_default(),
)
.into(),
))?;
if !is_static_route {
page.push(PageSegment::OptionalCatchAll("__metadata_id__".to_string()))?;
page.push(PageSegment::OptionalCatchAll("__metadata_id__".into()))?;
}
page.push(PageSegment::PageType(PageType::Route))?;
......
......@@ -145,7 +145,7 @@ async fn static_route_source(
let file = File::from(code);
let source = VirtualSource::new(
path.parent().join(format!("{stem}--route-entry.js")),
path.parent().join(format!("{stem}--route-entry.js").into()),
AssetContent::file(file.into()),
);
......@@ -197,7 +197,7 @@ async fn dynamic_text_route_source(path: Vc<FileSystemPath>) -> Result<Vc<Box<dy
let file = File::from(code);
let source = VirtualSource::new(
path.parent().join(format!("{stem}--route-entry.js")),
path.parent().join(format!("{stem}--route-entry.js").into()),
AssetContent::file(file.into()),
);
......@@ -218,8 +218,7 @@ async fn dynamic_site_map_route_source(
let mut static_generation_code = "";
if mode.is_production() && page.contains(&PageSegment::Dynamic("[__metadata_id__]".to_string()))
{
if mode.is_production() && page.contains(&PageSegment::Dynamic("[__metadata_id__]".into())) {
static_generation_code = indoc! {
r#"
export async function generateStaticParams() {
......@@ -297,7 +296,7 @@ async fn dynamic_site_map_route_source(
let file = File::from(code);
let source = VirtualSource::new(
path.parent().join(format!("{stem}--route-entry.js")),
path.parent().join(format!("{stem}--route-entry.js").into()),
AssetContent::file(file.into()),
);
......@@ -355,7 +354,7 @@ async fn dynamic_image_route_source(path: Vc<FileSystemPath>) -> Result<Vc<Box<d
let file = File::from(code);
let source = VirtualSource::new(
path.parent().join(format!("{stem}--route-entry.js")),
path.parent().join(format!("{stem}--route-entry.js").into()),
AssetContent::file(file.into()),
);
......
......@@ -14,7 +14,7 @@ use std::{
use anyhow::{bail, Result};
use serde::{Deserialize, Serialize};
use turbo_tasks::{trace::TraceRawVcs, TaskInput};
use turbo_tasks::{trace::TraceRawVcs, RcStr, TaskInput};
pub use crate::next_app::{
app_client_references_chunks::{get_app_client_references_chunks, ClientReferencesChunks},
......@@ -40,17 +40,17 @@ pub use crate::next_app::{
)]
pub enum PageSegment {
/// e.g. `/dashboard`
Static(String),
Static(RcStr),
/// e.g. `/[id]`
Dynamic(String),
Dynamic(RcStr),
/// e.g. `/[...slug]`
CatchAll(String),
CatchAll(RcStr),
/// e.g. `/[[...slug]]`
OptionalCatchAll(String),
OptionalCatchAll(RcStr),
/// e.g. `/(shop)`
Group(String),
Group(RcStr),
/// e.g. `/@auth`
Parallel(String),
Parallel(RcStr),
/// The final page type appended. (e.g. `/dashboard/page`,
/// `/api/hello/route`)
PageType(PageType),
......@@ -67,32 +67,32 @@ impl PageSegment {
}
if let Some(s) = segment.strip_prefix('(').and_then(|s| s.strip_suffix(')')) {
return Ok(PageSegment::Group(s.to_string()));
return Ok(PageSegment::Group(s.into()));
}
if let Some(s) = segment.strip_prefix('@') {
return Ok(PageSegment::Parallel(s.to_string()));
return Ok(PageSegment::Parallel(s.into()));
}
if let Some(s) = segment
.strip_prefix("[[...")
.and_then(|s| s.strip_suffix("]]"))
{
return Ok(PageSegment::OptionalCatchAll(s.to_string()));
return Ok(PageSegment::OptionalCatchAll(s.into()));
}
if let Some(s) = segment
.strip_prefix("[...")
.and_then(|s| s.strip_suffix(']'))
{
return Ok(PageSegment::CatchAll(s.to_string()));
return Ok(PageSegment::CatchAll(s.into()));
}
if let Some(s) = segment.strip_prefix('[').and_then(|s| s.strip_suffix(']')) {
return Ok(PageSegment::Dynamic(s.to_string()));
return Ok(PageSegment::Dynamic(s.into()));
}
Ok(PageSegment::Static(segment.to_string()))
Ok(PageSegment::Static(segment.into()))
}
}
......@@ -308,13 +308,13 @@ impl PartialOrd for AppPage {
)]
pub enum PathSegment {
/// e.g. `/dashboard`
Static(String),
Static(RcStr),
/// e.g. `/[id]`
Dynamic(String),
Dynamic(RcStr),
/// e.g. `/[...slug]`
CatchAll(String),
CatchAll(RcStr),
/// e.g. `/[[...slug]]`
OptionalCatchAll(String),
OptionalCatchAll(RcStr),
}
impl Display for PathSegment {
......
use anyhow::Result;
use turbo_tasks::Vc;
use turbo_tasks::{RcStr, Vc};
use turbopack_binding::{
turbo::tasks_fs::FileSystemPath,
turbopack::core::resolve::{options::ImportMapping, ExternalType},
......@@ -13,22 +13,19 @@ pub async fn get_postcss_package_mapping(
) -> Result<Vc<ImportMapping>> {
Ok(ImportMapping::Alternatives(vec![
// Prefer the local installed version over the next.js version
ImportMapping::PrimaryAlternative("postcss".to_string(), Some(project_path)).cell(),
ImportMapping::PrimaryAlternative(
"postcss".to_string(),
Some(get_next_package(project_path)),
)
.cell(),
ImportMapping::PrimaryAlternative("postcss".into(), Some(project_path)).cell(),
ImportMapping::PrimaryAlternative("postcss".into(), Some(get_next_package(project_path)))
.cell(),
])
.cell())
}
#[turbo_tasks::function]
pub async fn get_external_next_compiled_package_mapping(
package_name: Vc<String>,
package_name: Vc<RcStr>,
) -> Result<Vc<ImportMapping>> {
Ok(ImportMapping::Alternatives(vec![ImportMapping::External(
Some(format!("next/dist/compiled/{}", &*package_name.await?)),
Some(format!("next/dist/compiled/{}", &*package_name.await?).into()),
ExternalType::CommonJs,
)
.into()])
......
......@@ -2,7 +2,7 @@ use std::iter::once;
use anyhow::Result;
use indexmap::IndexMap;
use turbo_tasks::{Value, Vc};
use turbo_tasks::{RcStr, Value, Vc};
use turbo_tasks_fs::FileSystem;
use turbopack_binding::{
turbo::{tasks_env::EnvMap, tasks_fs::FileSystemPath},
......@@ -66,17 +66,17 @@ use crate::{
util::foreign_code_context_condition,
};
fn defines(define_env: &IndexMap<String, String>) -> CompileTimeDefines {
fn defines(define_env: &IndexMap<RcStr, RcStr>) -> CompileTimeDefines {
let mut defines = IndexMap::new();
for (k, v) in define_env {
defines
.entry(k.split('.').map(|s| s.to_string()).collect::<Vec<String>>())
.entry(k.split('.').map(|s| s.into()).collect::<Vec<RcStr>>())
.or_insert_with(|| {
let val = serde_json::from_str(v);
match val {
Ok(serde_json::Value::Bool(v)) => CompileTimeDefineValue::Bool(v),
Ok(serde_json::Value::String(v)) => CompileTimeDefineValue::String(v),
Ok(serde_json::Value::String(v)) => CompileTimeDefineValue::String(v.into()),
_ => CompileTimeDefineValue::JSON(v.clone()),
}
});
......@@ -95,14 +95,14 @@ async fn next_client_free_vars(define_env: Vc<EnvMap>) -> Result<Vc<FreeVarRefer
Ok(free_var_references!(
..defines(&*define_env.await?).into_iter(),
Buffer = FreeVarReference::EcmaScriptModule {
request: "node:buffer".to_string(),
request: "node:buffer".into(),
lookup_path: None,
export: Some("Buffer".to_string()),
export: Some("Buffer".into()),
},
process = FreeVarReference::EcmaScriptModule {
request: "node:process".to_string(),
request: "node:process".into(),
lookup_path: None,
export: Some("default".to_string()),
export: Some("default".into()),
}
)
.cell())
......@@ -110,7 +110,7 @@ async fn next_client_free_vars(define_env: Vc<EnvMap>) -> Result<Vc<FreeVarRefer
#[turbo_tasks::function]
pub fn get_client_compile_time_info(
browserslist_query: String,
browserslist_query: RcStr,
define_env: Vc<EnvMap>,
) -> Vc<CompileTimeInfo> {
CompileTimeInfo::builder(Environment::new(Value::new(ExecutionEnvironment::Browser(
......@@ -149,7 +149,7 @@ pub async fn get_client_resolve_options_context(
let next_client_fallback_import_map = get_next_client_fallback_import_map(ty);
let next_client_resolved_map =
get_next_client_resolved_map(project_path, project_path, *mode.await?);
let custom_conditions = vec![mode.await?.condition().to_string()];
let custom_conditions = vec![mode.await?.condition().into()];
let module_options_context = ResolveOptionsContext {
enable_node_modules: Some(project_path.root().resolve().await?),
custom_conditions,
......@@ -218,7 +218,7 @@ pub async fn get_client_module_options_context(
// foreign_code_context_condition. This allows to import codes from
// node_modules that requires webpack loaders, which next-dev implicitly
// does by default.
let conditions = vec!["browser".to_string(), mode.await?.condition().to_string()];
let conditions = vec!["browser".into(), mode.await?.condition().into()];
let foreign_enable_webpack_loaders = webpack_loader_options(
project_path,
next_config,
......@@ -226,7 +226,7 @@ pub async fn get_client_module_options_context(
conditions
.iter()
.cloned()
.chain(once("foreign".to_string()))
.chain(once("foreign".into()))
.collect(),
)
.await?;
......@@ -326,7 +326,7 @@ pub async fn get_client_module_options_context(
pub async fn get_client_chunking_context(
project_path: Vc<FileSystemPath>,
client_root: Vc<FileSystemPath>,
asset_prefix: Vc<Option<String>>,
asset_prefix: Vc<Option<RcStr>>,
environment: Vc<Environment>,
mode: Vc<NextMode>,
) -> Result<Vc<Box<dyn ChunkingContext>>> {
......@@ -335,7 +335,7 @@ pub async fn get_client_chunking_context(
project_path,
client_root,
client_root,
client_root.join("static/chunks".to_string()),
client_root.join("static/chunks".into()),
get_client_assets_path(client_root),
environment,
next_mode.runtime_type(),
......@@ -353,7 +353,7 @@ pub async fn get_client_chunking_context(
#[turbo_tasks::function]
pub fn get_client_assets_path(client_root: Vc<FileSystemPath>) -> Vc<FileSystemPath> {
client_root.join("static/media".to_string())
client_root.join("static/media".into())
}
#[turbo_tasks::function]
......@@ -379,7 +379,7 @@ pub async fn get_client_runtime_entries(
// functions to be available.
if let Some(request) = enable_react_refresh {
runtime_entries
.push(RuntimeEntry::Request(request, project_root.join("_".to_string())).cell())
.push(RuntimeEntry::Request(request, project_root.join("_".into())).cell())
};
}
......@@ -387,9 +387,9 @@ pub async fn get_client_runtime_entries(
runtime_entries.push(
RuntimeEntry::Request(
Request::parse(Value::new(Pattern::Constant(
"next/dist/client/app-next-turbopack.js".to_string(),
"next/dist/client/app-next-turbopack.js".into(),
))),
project_root.join("_".to_string()),
project_root.join("_".into()),
)
.cell(),
);
......
use anyhow::{bail, Context, Result};
use turbo_tasks::Vc;
use turbo_tasks::{RcStr, Vc};
use turbopack_binding::turbopack::{
core::{
asset::{Asset, AssetContent},
......@@ -31,8 +31,8 @@ impl CssClientReferenceModule {
}
#[turbo_tasks::function]
fn css_client_reference_modifier() -> Vc<String> {
Vc::cell("css client reference".to_string())
fn css_client_reference_modifier() -> Vc<RcStr> {
Vc::cell("css client reference".into())
}
#[turbo_tasks::value_impl]
......
#![allow(rustdoc::private_intra_doc_links)]
use anyhow::{bail, Result};
use turbo_tasks::Vc;
use turbo_tasks::{RcStr, Vc};
use turbopack_binding::turbopack::{
core::{
asset::{Asset, AssetContent},
......@@ -46,8 +46,8 @@ impl EcmascriptClientReferenceModule {
}
#[turbo_tasks::function]
fn ecmascript_client_reference_modifier() -> Vc<String> {
Vc::cell("ecmascript client reference".to_string())
fn ecmascript_client_reference_modifier() -> Vc<RcStr> {
Vc::cell("ecmascript client reference".into())
}
#[turbo_tasks::value_impl]
......
......@@ -2,7 +2,7 @@ use std::{io::Write, iter::once};
use anyhow::{bail, Context, Result};
use indoc::writedoc;
use turbo_tasks::{Value, ValueToString, Vc};
use turbo_tasks::{RcStr, Value, ValueToString, Vc};
use turbo_tasks_fs::File;
use turbopack_binding::turbopack::{
core::{
......@@ -143,7 +143,7 @@ impl EcmascriptClientReferenceProxyModule {
AssetContent::file(File::from(code.source_code().clone()).into());
let proxy_source = VirtualSource::new(
self.server_module_ident.path().join("proxy.js".to_string()),
self.server_module_ident.path().join("proxy.js".into()),
proxy_module_content,
);
......@@ -253,13 +253,13 @@ struct ProxyModuleChunkItem {
}
#[turbo_tasks::function]
fn client_proxy_modifier() -> Vc<String> {
Vc::cell("client proxy".to_string())
fn client_proxy_modifier() -> Vc<RcStr> {
Vc::cell("client proxy".into())
}
#[turbo_tasks::function]
fn client_reference_description() -> Vc<String> {
Vc::cell("client references".to_string())
fn client_reference_description() -> Vc<RcStr> {
Vc::cell("client references".into())
}
#[turbo_tasks::value_impl]
......
use anyhow::{bail, Result};
use turbo_tasks::{Value, Vc};
use turbo_tasks::{RcStr, Value, Vc};
use turbopack_binding::turbopack::{
core::{
context::ProcessResult,
......@@ -40,7 +40,7 @@ impl NextEcmascriptClientReferenceTransition {
#[turbo_tasks::value_impl]
impl Transition for NextEcmascriptClientReferenceTransition {
#[turbo_tasks::function]
fn process_layer(self: Vc<Self>, layer: Vc<String>) -> Vc<String> {
fn process_layer(self: Vc<Self>, layer: Vc<RcStr>) -> Vc<RcStr> {
layer
}
......@@ -58,10 +58,12 @@ impl Transition for NextEcmascriptClientReferenceTransition {
let ident = source.ident().await?;
let ident_path = ident.path.await?;
let client_source = if ident_path.path.contains("next/dist/esm/") {
let path = ident
.path
.root()
.join(ident_path.path.replace("next/dist/esm/", "next/dist/"));
let path = ident.path.root().join(
ident_path
.path
.replace("next/dist/esm/", "next/dist/")
.into(),
);
Vc::upcast(FileSource::new_with_query(path, ident.query))
} else {
source
......
......@@ -8,7 +8,7 @@ use turbo_tasks::{
debug::ValueDebugFormat,
graph::{AdjacencyMap, GraphTraversal, Visit, VisitControlFlow},
trace::TraceRawVcs,
ReadRef, TryJoinIterExt, ValueToString, Vc,
RcStr, ReadRef, TryJoinIterExt, ValueToString, Vc,
};
use turbopack_binding::turbopack::core::{
module::{Module, Modules},
......@@ -170,9 +170,9 @@ struct VisitClientReferenceNode {
Clone, Eq, PartialEq, Hash, Serialize, Deserialize, Debug, ValueDebugFormat, TraceRawVcs,
)]
enum VisitClientReferenceNodeType {
ClientReference(ClientReference, ReadRef<String>),
ServerComponentEntry(Vc<NextServerComponentModule>, ReadRef<String>),
Internal(Vc<Box<dyn Module>>, ReadRef<String>),
ClientReference(ClientReference, ReadRef<RcStr>),
ServerComponentEntry(Vc<NextServerComponentModule>, ReadRef<RcStr>),
Internal(Vc<Box<dyn Module>>, ReadRef<RcStr>),
}
impl Visit<VisitClientReferenceNode> for VisitClientReference {
......@@ -269,13 +269,13 @@ impl Visit<VisitClientReferenceNode> for VisitClientReference {
fn span(&mut self, node: &VisitClientReferenceNode) -> tracing::Span {
match &node.ty {
VisitClientReferenceNodeType::ClientReference(_, name) => {
tracing::info_span!("client reference", name = **name)
tracing::info_span!("client reference", name = name.to_string())
}
VisitClientReferenceNodeType::Internal(_, name) => {
tracing::info_span!("module", name = **name)
tracing::info_span!("module", name = name.to_string())
}
VisitClientReferenceNodeType::ServerComponentEntry(_, name) => {
tracing::info_span!("layout segment", name = **name)
tracing::info_span!("layout segment", name = name.to_string())
}
}
}
......
use anyhow::{bail, Result};
use turbo_tasks::Vc;
use turbo_tasks::{RcStr, Vc};
use turbopack_binding::turbopack::core::{
asset::{Asset, AssetContent},
chunk::{ChunkableModule, ChunkingContext, ChunkingContextExt},
......@@ -46,8 +46,8 @@ impl NextDynamicEntryModule {
}
#[turbo_tasks::function]
fn dynamic_modifier() -> Vc<String> {
Vc::cell("dynamic".to_string())
fn dynamic_modifier() -> Vc<RcStr> {
Vc::cell("dynamic".into())
}
#[turbo_tasks::value_impl]
......
use anyhow::Result;
use turbo_tasks::{Value, Vc};
use turbo_tasks::{RcStr, Value, Vc};
use turbopack_binding::turbopack::{
core::{context::ProcessResult, reference_type::ReferenceType, source::Source},
turbopack::{transition::Transition, ModuleAssetContext},
......@@ -26,7 +26,7 @@ impl NextDynamicTransition {
#[turbo_tasks::value_impl]
impl Transition for NextDynamicTransition {
#[turbo_tasks::function]
fn process_layer(self: Vc<Self>, layer: Vc<String>) -> Vc<String> {
fn process_layer(self: Vc<Self>, layer: Vc<RcStr>) -> Vc<RcStr> {
layer
}
......
......@@ -4,7 +4,7 @@ use anyhow::Result;
use tracing::Instrument;
use turbo_tasks::{
graph::{AdjacencyMap, GraphTraversal, Visit, VisitControlFlow},
ReadRef, TryJoinIterExt, ValueToString, Vc,
RcStr, ReadRef, TryJoinIterExt, ValueToString, Vc,
};
use turbopack_binding::turbopack::core::{
module::{Module, Modules},
......@@ -66,8 +66,8 @@ struct VisitDynamic;
#[derive(Clone, Eq, PartialEq, Hash)]
enum VisitDynamicNode {
Dynamic(Vc<NextDynamicEntryModule>, ReadRef<String>),
Internal(Vc<Box<dyn Module>>, ReadRef<String>),
Dynamic(Vc<NextDynamicEntryModule>, ReadRef<RcStr>),
Internal(Vc<Box<dyn Module>>, ReadRef<RcStr>),
}
impl Visit<VisitDynamicNode> for VisitDynamic {
......@@ -117,10 +117,10 @@ impl Visit<VisitDynamicNode> for VisitDynamic {
fn span(&mut self, node: &VisitDynamicNode) -> tracing::Span {
match node {
VisitDynamicNode::Dynamic(_, name) => {
tracing::info_span!("dynamic module", name = **name)
tracing::info_span!("dynamic module", name = name.to_string())
}
VisitDynamicNode::Internal(_, name) => {
tracing::info_span!("module", name = **name)
tracing::info_span!("module", name = name.to_string())
}
}
}
......
use anyhow::Result;
use indexmap::IndexMap;
use turbo_tasks::{Value, Vc};
use turbo_tasks::{RcStr, Value, Vc};
use turbopack_binding::{
turbo::{tasks_env::EnvMap, tasks_fs::FileSystemPath},
turbopack::{
......@@ -33,17 +33,17 @@ use crate::{
util::{foreign_code_context_condition, NextRuntime},
};
fn defines(define_env: &IndexMap<String, String>) -> CompileTimeDefines {
fn defines(define_env: &IndexMap<RcStr, RcStr>) -> CompileTimeDefines {
let mut defines = IndexMap::new();
for (k, v) in define_env {
defines
.entry(k.split('.').map(|s| s.to_string()).collect::<Vec<String>>())
.entry(k.split('.').map(|s| s.into()).collect::<Vec<RcStr>>())
.or_insert_with(|| {
let val = serde_json::from_str(v);
match val {
Ok(serde_json::Value::Bool(v)) => CompileTimeDefineValue::Bool(v),
Ok(serde_json::Value::String(v)) => CompileTimeDefineValue::String(v),
Ok(serde_json::Value::String(v)) => CompileTimeDefineValue::String(v.into()),
_ => CompileTimeDefineValue::JSON(v.clone()),
}
});
......@@ -67,9 +67,9 @@ async fn next_edge_free_vars(
Ok(free_var_references!(
..defines(&*define_env.await?).into_iter(),
Buffer = FreeVarReference::EcmaScriptModule {
request: "buffer".to_string(),
request: "buffer".into(),
lookup_path: Some(project_path),
export: Some("Buffer".to_string()),
export: Some("Buffer".into()),
},
)
.cell())
......@@ -141,16 +141,17 @@ pub async fn get_edge_resolve_options_context(
after_resolve_plugins.extend_from_slice(&base_plugins);
// https://github.com/vercel/next.js/blob/bf52c254973d99fed9d71507a2e818af80b8ade7/packages/next/src/build/webpack-config.ts#L96-L102
let mut custom_conditions = vec![mode.await?.condition().to_string()];
let mut custom_conditions = vec![mode.await?.condition().into()];
custom_conditions.extend(
NextRuntime::Edge
.conditions()
.iter()
.map(ToString::to_string),
.map(ToString::to_string)
.map(RcStr::from),
);
if ty.supports_react_server() {
custom_conditions.push("react-server".to_string());
custom_conditions.push("react-server".into());
};
let resolve_options_context = ResolveOptionsContext {
......@@ -186,18 +187,18 @@ pub async fn get_edge_chunking_context_with_client_assets(
project_path: Vc<FileSystemPath>,
node_root: Vc<FileSystemPath>,
client_root: Vc<FileSystemPath>,
asset_prefix: Vc<Option<String>>,
asset_prefix: Vc<Option<RcStr>>,
environment: Vc<Environment>,
) -> Result<Vc<Box<dyn ChunkingContext>>> {
let output_root = node_root.join("server/edge".to_string());
let output_root = node_root.join("server/edge".into());
let next_mode = mode.await?;
Ok(Vc::upcast(
BrowserChunkingContext::builder(
project_path,
output_root,
client_root,
output_root.join("chunks/ssr".to_string()),
client_root.join("static/media".to_string()),
output_root.join("chunks/ssr".into()),
client_root.join("static/media".into()),
environment,
next_mode.runtime_type(),
)
......@@ -214,15 +215,15 @@ pub async fn get_edge_chunking_context(
node_root: Vc<FileSystemPath>,
environment: Vc<Environment>,
) -> Result<Vc<Box<dyn ChunkingContext>>> {
let output_root = node_root.join("server/edge".to_string());
let output_root = node_root.join("server/edge".into());
let next_mode = mode.await?;
Ok(Vc::upcast(
BrowserChunkingContext::builder(
project_path,
output_root,
output_root,
output_root.join("chunks".to_string()),
output_root.join("assets".to_string()),
output_root.join("chunks".into()),
output_root.join("assets".into()),
environment,
next_mode.runtime_type(),
)
......@@ -230,7 +231,7 @@ pub async fn get_edge_chunking_context(
// instead. This special blob url is handled by the custom fetch
// implementation in the edge sandbox. It will respond with the
// asset from the output directory.
.asset_base_path(Vc::cell(Some("blob:server/edge/".to_string())))
.asset_base_path(Vc::cell(Some("blob:server/edge/".into())))
.minify_type(next_mode.minify_type())
.build(),
))
......
use anyhow::Result;
use indexmap::indexmap;
use indoc::formatdoc;
use turbo_tasks::{Value, Vc};
use turbo_tasks::{RcStr, Value, Vc};
use turbo_tasks_fs::{File, FileSystemPath};
use turbopack_binding::turbopack::{
core::{
......@@ -16,7 +16,7 @@ pub async fn wrap_edge_entry(
context: Vc<Box<dyn AssetContext>>,
project_root: Vc<FileSystemPath>,
entry: Vc<Box<dyn Module>>,
pathname: String,
pathname: RcStr,
) -> Result<Vc<Box<dyn Module>>> {
// The wrapped module could be an async module, we handle that with the proxy
// here. The comma expression makes sure we don't call the function with the
......@@ -32,12 +32,12 @@ pub async fn wrap_edge_entry(
// TODO(alexkirsz) Figure out how to name this virtual asset.
let virtual_source = VirtualSource::new(
project_root.join("edge-wrapper.js".to_string()),
project_root.join("edge-wrapper.js".into()),
AssetContent::file(file.into()),
);
let inner_assets = indexmap! {
"MODULE".to_string() => entry
"MODULE".into() => entry
};
let module = context
......
use anyhow::Result;
use indoc::formatdoc;
use turbo_tasks::Vc;
use turbo_tasks::{RcStr, Vc};
use turbo_tasks_fs::File;
use turbopack_binding::{
turbo::tasks_fs::FileSystemPath,
......@@ -46,7 +46,7 @@ impl NextEdgeUnsupportedModuleReplacer {
#[turbo_tasks::value_impl]
impl ImportMappingReplacement for NextEdgeUnsupportedModuleReplacer {
#[turbo_tasks::function]
fn replace(&self, _capture: String) -> Vc<ImportMapping> {
fn replace(&self, _capture: RcStr) -> Vc<ImportMapping> {
ImportMapping::Ignore.into()
}
......
use anyhow::Result;
use once_cell::sync::Lazy;
use serde::{Deserialize, Serialize};
use turbo_tasks::Vc;
use turbo_tasks::{RcStr, Vc};
use turbopack_binding::turbo::tasks::trace::TraceRawVcs;
pub(crate) struct DefaultFallbackFont {
pub name: String,
pub capsize_key: String,
pub name: RcStr,
pub capsize_key: RcStr,
pub az_avg_width: f64,
pub units_per_em: u32,
}
......@@ -14,16 +14,16 @@ pub(crate) struct DefaultFallbackFont {
// From https://github.com/vercel/next.js/blob/a3893bf69c83fb08e88c87bf8a21d987a0448c8e/packages/font/src/utils.ts#L4
pub(crate) static DEFAULT_SANS_SERIF_FONT: Lazy<DefaultFallbackFont> =
Lazy::new(|| DefaultFallbackFont {
name: "Arial".to_owned(),
capsize_key: "arial".to_owned(),
name: "Arial".into(),
capsize_key: "arial".into(),
az_avg_width: 934.5116279069767,
units_per_em: 2048,
});
pub(crate) static DEFAULT_SERIF_FONT: Lazy<DefaultFallbackFont> =
Lazy::new(|| DefaultFallbackFont {
name: "Times New Roman".to_owned(),
capsize_key: "timesNewRoman".to_owned(),
name: "Times New Roman".into(),
capsize_key: "timesNewRoman".into(),
az_avg_width: 854.3953488372093,
units_per_em: 2048,
});
......@@ -32,9 +32,9 @@ pub(crate) static DEFAULT_SERIF_FONT: Lazy<DefaultFallbackFont> =
#[turbo_tasks::value(shared)]
pub(crate) struct AutomaticFontFallback {
/// e.g. `__Roboto_Fallback_c123b8`
pub scoped_font_family: Vc<String>,
pub scoped_font_family: Vc<RcStr>,
/// The name of font locally, used in `src: local("{}")`
pub local_font_family: Vc<String>,
pub local_font_family: Vc<RcStr>,
pub adjustment: Option<FontAdjustment>,
}
......@@ -48,7 +48,7 @@ pub(crate) enum FontFallback {
/// return this and omit fallback information instead.
Error,
/// A list of manually provided font names to use a fallback, as-is.
Manual(Vec<String>),
Manual(Vec<RcStr>),
}
#[turbo_tasks::value_impl]
......
......@@ -4,7 +4,7 @@ use anyhow::{Context, Result};
use once_cell::sync::Lazy;
use regex::Regex;
use serde::{Deserialize, Serialize};
use turbo_tasks::{trace::TraceRawVcs, Vc};
use turbo_tasks::{trace::TraceRawVcs, RcStr, Vc};
use turbopack_binding::{
turbo::tasks_fs::FileSystemPath,
turbopack::core::issue::{IssueExt, IssueSeverity, StyledString},
......@@ -27,7 +27,7 @@ use crate::{
#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub(super) struct FontMetricsMapEntry {
category: String,
category: RcStr,
ascent: i32,
descent: i32,
line_gap: u32,
......@@ -36,11 +36,11 @@ pub(super) struct FontMetricsMapEntry {
}
#[derive(Deserialize, Debug)]
pub(super) struct FontMetricsMap(pub HashMap<String, FontMetricsMapEntry>);
pub(super) struct FontMetricsMap(pub HashMap<RcStr, FontMetricsMapEntry>);
#[derive(Debug, PartialEq, Serialize, Deserialize, TraceRawVcs)]
struct Fallback {
pub font_family: String,
pub font_family: RcStr,
pub adjustment: Option<FontAdjustment>,
}
......@@ -53,11 +53,9 @@ pub(super) async fn get_font_fallback(
Ok(match &options.fallback {
Some(fallback) => FontFallback::Manual(fallback.clone()).cell(),
None => {
let metrics_json = load_next_js_templateon(
context,
"dist/server/capsize-font-metrics.json".to_string(),
)
.await?;
let metrics_json =
load_next_js_templateon(context, "dist/server/capsize-font-metrics.json".into())
.await?;
let fallback = lookup_fallback(
&options.font_family,
metrics_json,
......@@ -77,13 +75,16 @@ pub(super) async fn get_font_fallback(
Err(_) => {
NextFontIssue {
path: context,
title: StyledString::Text(format!(
"Failed to find font override values for font `{}`",
&options.font_family,
))
title: StyledString::Text(
format!(
"Failed to find font override values for font `{}`",
&options.font_family,
)
.into(),
)
.cell(),
description: StyledString::Text(
"Skipping generating a fallback font.".to_owned(),
"Skipping generating a fallback font.".into(),
)
.cell(),
severity: IssueSeverity::Warning.cell(),
......@@ -100,7 +101,7 @@ pub(super) async fn get_font_fallback(
static FALLBACK_FONT_NAME: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?:^\w|[A-Z]|\b\w)").unwrap());
// From https://github.com/vercel/next.js/blob/1628260b88ce3052ac307a1607b6e8470188ab83/packages/next/src/server/font-utils.ts#L101
fn format_fallback_font_name(font_family: &str) -> String {
fn format_fallback_font_name(font_family: &str) -> RcStr {
let mut fallback_name = FALLBACK_FONT_NAME
.replace(font_family, |caps: &regex::Captures| {
caps.iter()
......@@ -118,7 +119,7 @@ fn format_fallback_font_name(font_family: &str) -> String {
})
.to_string();
fallback_name.retain(|c| !c.is_whitespace());
fallback_name
fallback_name.into()
}
fn lookup_fallback(
......@@ -208,7 +209,7 @@ mod tests {
assert_eq!(
lookup_fallback("Inter", font_metrics, true)?,
Fallback {
font_family: "Arial".to_owned(),
font_family: "Arial".into(),
adjustment: Some(FontAdjustment {
ascent: 0.901_989_700_374_532,
descent: -0.224_836_142_322_097_4,
......@@ -254,7 +255,7 @@ mod tests {
assert_eq!(
lookup_fallback("Roboto Slab", font_metrics, true)?,
Fallback {
font_family: "Times New Roman".to_owned(),
font_family: "Times New Roman".into(),
adjustment: Some(FontAdjustment {
ascent: 0.885_645_438_273_993_8,
descent: -0.229_046_234_036_377_7,
......
use anyhow::{anyhow, Context, Result};
use indexmap::{indexset, IndexMap, IndexSet};
use serde::{Deserialize, Serialize};
use turbo_tasks::Vc;
use turbo_tasks::{RcStr, Vc};
use turbopack_binding::turbo::tasks::{trace::TraceRawVcs, Value};
use super::request::{NextFontRequest, OneOrManyStrings};
const ALLOWED_DISPLAY_VALUES: &[&str] = &["auto", "block", "swap", "fallback", "optional"];
pub(super) type FontData = IndexMap<String, FontDataEntry>;
pub(super) type FontData = IndexMap<RcStr, FontDataEntry>;
#[turbo_tasks::value(serialization = "auto_for_input")]
#[derive(Clone, Debug, PartialOrd, Ord, Hash)]
pub(super) struct NextFontGoogleOptions {
/// Name of the requested font from Google. Contains literal spaces.
pub font_family: String,
pub font_family: RcStr,
pub weights: FontWeights,
pub styles: Vec<String>,
pub display: String,
pub styles: Vec<RcStr>,
pub display: RcStr,
pub preload: bool,
pub selected_variable_axes: Option<Vec<String>>,
pub fallback: Option<Vec<String>>,
pub selected_variable_axes: Option<Vec<RcStr>>,
pub fallback: Option<Vec<RcStr>>,
pub adjust_font_fallback: bool,
/// An optional name for a css custom property (css variable) that applies
/// the font family when used.
pub variable: Option<String>,
pub subsets: Option<Vec<String>>,
pub variable: Option<RcStr>,
pub subsets: Option<Vec<RcStr>>,
}
#[turbo_tasks::value_impl]
......@@ -36,8 +36,8 @@ impl NextFontGoogleOptions {
}
#[turbo_tasks::function]
pub async fn font_family(self: Vc<Self>) -> Result<Vc<String>> {
Ok(Vc::cell((*self.await?.font_family).to_owned()))
pub async fn font_family(self: Vc<Self>) -> Result<Vc<RcStr>> {
Ok(Vc::cell((*self.await?.font_family).into()))
}
}
......@@ -51,15 +51,15 @@ pub(super) enum FontWeights {
#[derive(Debug, PartialEq, Eq, Deserialize, Serialize, TraceRawVcs)]
pub(super) struct FontDataEntry {
pub weights: Vec<String>,
pub styles: Vec<String>,
pub weights: Vec<RcStr>,
pub styles: Vec<RcStr>,
pub axes: Option<Vec<Axis>>,
}
#[derive(Debug, PartialEq, Deserialize, Serialize, TraceRawVcs)]
#[serde(rename_all = "camelCase")]
pub(super) struct Axis {
pub tag: String,
pub tag: RcStr,
pub min: f64,
pub max: f64,
}
......@@ -71,7 +71,7 @@ impl Eq for Axis {}
// https://github.com/vercel/next.js/blob/28454c6ddbc310419467e5415aee26e48d079b46/packages/font/src/google/utils.ts#L22
pub(super) fn options_from_request(
request: &NextFontRequest,
data: &IndexMap<String, FontDataEntry>,
data: &IndexMap<RcStr, FontDataEntry>,
) -> Result<NextFontGoogleOptions> {
if request.arguments.len() > 1 {
return Err(anyhow!(
......@@ -82,10 +82,10 @@ pub(super) fn options_from_request(
let argument = request.arguments.last().cloned().unwrap_or_default();
// `import` comes from the imported symbol in JS, which separates with _
let font_family = request.import.replace('_', " ");
let font_family: RcStr = request.import.replace('_', " ").into();
let font_data = data.get(&font_family).context("Unknown font")?;
let requested_weights: IndexSet<String> = argument
let requested_weights: IndexSet<RcStr> = argument
.weight
.map(|w| match w {
OneOrManyStrings::One(one) => indexset! {one},
......@@ -102,7 +102,7 @@ pub(super) fn options_from_request(
.unwrap_or_default();
let weights = if requested_weights.is_empty() {
if !font_data.weights.contains(&"variable".to_owned()) {
if !font_data.weights.contains(&"variable".into()) {
return Err(anyhow!(
"Missing weight for {}. Available weights: {}",
font_family,
......@@ -145,7 +145,7 @@ pub(super) fn options_from_request(
if font_data.styles.len() == 1 {
styles.push(font_data.styles[0].clone());
} else {
styles.push("normal".to_owned());
styles.push("normal".into());
}
}
......@@ -160,9 +160,9 @@ pub(super) fn options_from_request(
}
}
let display = argument.display.unwrap_or_else(|| "swap".to_owned());
let display = argument.display.unwrap_or_else(|| "swap".into());
if !ALLOWED_DISPLAY_VALUES.contains(&display.as_ref()) {
if !ALLOWED_DISPLAY_VALUES.contains(&display.as_str()) {
return Err(anyhow!(
"Invalid display value {} for font {}.\nAvailable display values: {}",
display,
......@@ -195,6 +195,7 @@ pub(super) fn options_from_request(
mod tests {
use anyhow::Result;
use indexmap::IndexMap;
use turbo_tasks::RcStr;
use turbopack_binding::turbo::tasks_fs::json::parse_json_with_source_context;
use super::{options_from_request, FontDataEntry, NextFontGoogleOptions};
......@@ -202,7 +203,7 @@ mod tests {
#[test]
fn test_errors_on_unknown_font() -> Result<()> {
let data: IndexMap<String, FontDataEntry> = parse_json_with_source_context(
let data: IndexMap<RcStr, FontDataEntry> = parse_json_with_source_context(
r#"
{
"ABeeZee": {
......@@ -235,7 +236,7 @@ mod tests {
#[test]
fn test_default_values_when_no_arguments() -> Result<()> {
let data: IndexMap<String, FontDataEntry> = parse_json_with_source_context(
let data: IndexMap<RcStr, FontDataEntry> = parse_json_with_source_context(
r#"
{
"ABeeZee": {
......@@ -260,10 +261,10 @@ mod tests {
assert_eq!(
options_from_request(&request, &data)?,
NextFontGoogleOptions {
font_family: "ABeeZee".to_owned(),
font_family: "ABeeZee".into(),
weights: FontWeights::Variable,
styles: vec!["normal".to_owned()],
display: "swap".to_owned(),
styles: vec!["normal".into()],
display: "swap".into(),
preload: true,
selected_variable_axes: None,
fallback: None,
......@@ -278,7 +279,7 @@ mod tests {
#[test]
fn test_errors_when_no_weights_chosen_no_variable() -> Result<()> {
let data: IndexMap<String, FontDataEntry> = parse_json_with_source_context(
let data: IndexMap<RcStr, FontDataEntry> = parse_json_with_source_context(
r#"
{
"ABeeZee": {
......@@ -314,7 +315,7 @@ mod tests {
#[test]
fn test_errors_on_unnecessary_weights() -> Result<()> {
let data: IndexMap<String, FontDataEntry> = parse_json_with_source_context(
let data: IndexMap<RcStr, FontDataEntry> = parse_json_with_source_context(
r#"
{
"ABeeZee": {
......@@ -353,7 +354,7 @@ mod tests {
#[test]
fn test_errors_on_unvavailable_weights() -> Result<()> {
let data: IndexMap<String, FontDataEntry> = parse_json_with_source_context(
let data: IndexMap<RcStr, FontDataEntry> = parse_json_with_source_context(
r#"
{
"ABeeZee": {
......@@ -391,7 +392,7 @@ mod tests {
#[test]
fn test_defaults_to_only_style_when_one_available() -> Result<()> {
let data: IndexMap<String, FontDataEntry> = parse_json_with_source_context(
let data: IndexMap<RcStr, FontDataEntry> = parse_json_with_source_context(
r#"
{
"ABeeZee": {
......@@ -416,14 +417,14 @@ mod tests {
)?;
let options = options_from_request(&request, &data)?;
assert_eq!(options.styles, vec!["italic".to_owned()]);
assert_eq!(options.styles, vec![RcStr::from("italic")]);
Ok(())
}
#[test]
fn test_defaults_to_normal_style_when_multiple() -> Result<()> {
let data: IndexMap<String, FontDataEntry> = parse_json_with_source_context(
let data: IndexMap<RcStr, FontDataEntry> = parse_json_with_source_context(
r#"
{
"ABeeZee": {
......@@ -448,14 +449,14 @@ mod tests {
)?;
let options = options_from_request(&request, &data)?;
assert_eq!(options.styles, vec!["normal".to_owned()]);
assert_eq!(options.styles, vec![RcStr::from("normal")]);
Ok(())
}
#[test]
fn test_errors_on_unknown_styles() -> Result<()> {
let data: IndexMap<String, FontDataEntry> = parse_json_with_source_context(
let data: IndexMap<RcStr, FontDataEntry> = parse_json_with_source_context(
r#"
{
"ABeeZee": {
......@@ -495,7 +496,7 @@ mod tests {
#[test]
fn test_errors_on_unknown_display() -> Result<()> {
let data: IndexMap<String, FontDataEntry> = parse_json_with_source_context(
let data: IndexMap<RcStr, FontDataEntry> = parse_json_with_source_context(
r#"
{
"ABeeZee": {
......@@ -536,7 +537,7 @@ mod tests {
#[test]
fn test_errors_on_axes_without_variable() -> Result<()> {
let data: IndexMap<String, FontDataEntry> = parse_json_with_source_context(
let data: IndexMap<RcStr, FontDataEntry> = parse_json_with_source_context(
r#"
{
"ABeeZee": {
......
This diff is collapsed.
This diff is collapsed.
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