这是indexloc提供的服务,不要输入任何密码
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 15 additions & 2 deletions crates/turbopack-cli/src/dev/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ use turbo_tasks_memory::MemoryBackend;
use turbopack::evaluate_context::node_build_environment;
use turbopack_cli_utils::issue::{ConsoleUi, LogOptions};
use turbopack_core::{
environment::ServerAddr,
issue::{IssueReporter, IssueSeverity},
resolve::parse::Request,
server_fs::ServerFileSystem,
Expand Down Expand Up @@ -367,7 +366,21 @@ pub async fn start_server(args: &DevArguments) -> Result<()> {
let server = server.build().await?;

{
let index_uri = ServerAddr::new(server.addr).to_string()?;
let addr = &server.addr;
let hostname = if addr.ip().is_loopback() || addr.ip().is_unspecified() {
"localhost".to_string()
} else if addr.is_ipv6() {
// When using an IPv6 address, we need to surround the IP in brackets to
// distinguish it from the port's `:`.
format!("[{}]", addr.ip())
} else {
addr.ip().to_string()
};
let index_uri = match addr.port() {
443 => format!("https://{hostname}"),
80 => format!("http://{hostname}"),
port => format!("http://{hostname}:{port}"),
};
println!(
"{} - started server on {}, url: {}",
"ready".green(),
Expand Down
136 changes: 7 additions & 129 deletions crates/turbopack-core/src/environment.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
use std::{
fmt,
net::SocketAddr,
process::{Command, Stdio},
str::FromStr,
};

use anyhow::{anyhow, bail, Context, Result};
use serde::{Deserialize, Serialize};
use anyhow::{anyhow, Context, Result};
use swc_core::ecma::preset_env::{Version, Versions};
use turbo_tasks::{Value, Vc};
use turbo_tasks_env::ProcessEnv;
Expand All @@ -15,124 +12,13 @@ use crate::target::CompileTarget;

static DEFAULT_NODEJS_VERSION: &str = "16.0.0";

#[turbo_tasks::value(shared)]
#[derive(Default)]
pub struct ServerAddr(#[turbo_tasks(trace_ignore)] Option<SocketAddr>);

impl ServerAddr {
pub fn new(addr: SocketAddr) -> Self {
Self(Some(addr))
}

/// The hostname portion of the address, without the port. Prefers
/// "localhost" when using a loopback address.
pub fn hostname(&self) -> Option<String> {
self.0.map(|addr| {
if addr.ip().is_loopback() || addr.ip().is_unspecified() {
"localhost".to_string()
} else if addr.is_ipv6() {
// When using an IPv6 address, we need to surround the IP in brackets to
// distinguish it from the port's `:`.
format!("[{}]", addr.ip())
} else {
addr.ip().to_string()
}
})
}

pub fn ip(&self) -> Option<String> {
self.0.map(|addr| addr.ip().to_string())
}

pub fn port(&self) -> Option<u16> {
self.0.map(|addr| addr.port())
}

/// Constructs a URL out of the address.
pub fn to_string(&self) -> Result<String> {
let (hostname, port) = self
.hostname()
.zip(self.port())
.context("expected some server address")?;
let protocol = Protocol::from(port);
Ok(match port {
80 | 443 => format!("{protocol}://{hostname}"),
_ => format!("{protocol}://{hostname}:{port}"),
})
}
}

#[turbo_tasks::value_impl]
impl ServerAddr {
#[turbo_tasks::function]
pub fn empty() -> Vc<Self> {
ServerAddr(None).cell()
}
}

/// A simple serializable structure meant to carry information about Turbopack's
/// server to node rendering processes.
#[derive(Debug, Serialize, Deserialize)]
pub struct ServerInfo {
pub ip: String,
pub port: u16,

/// The protocol, either `http` or `https`
pub protocol: Protocol,

/// A formatted hostname (eg, "localhost") or the IP address of the server
pub hostname: String,
}

#[derive(Copy, Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Protocol {
HTTP,
HTTPS,
}

impl From<u16> for Protocol {
fn from(value: u16) -> Self {
match value {
443 => Self::HTTPS,
_ => Self::HTTP,
}
}
}

impl fmt::Display for Protocol {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::HTTP => f.write_str("http"),
Self::HTTPS => f.write_str("https"),
}
}
}

impl TryFrom<&ServerAddr> for ServerInfo {
type Error = anyhow::Error;

fn try_from(addr: &ServerAddr) -> Result<Self> {
if addr.0.is_none() {
bail!("cannot unwrap ServerAddr");
};
let port = addr.port().unwrap();
Ok(ServerInfo {
ip: addr.ip().unwrap(),
hostname: addr.hostname().unwrap(),
port,
protocol: Protocol::from(port),
})
}
}

#[turbo_tasks::value]
#[derive(Default)]
pub enum Rendering {
#[default]
None,
Client,
Server(Vc<ServerAddr>),
Server,
}

impl Rendering {
Expand Down Expand Up @@ -308,13 +194,10 @@ impl Environment {
pub async fn rendering(self: Vc<Self>) -> Result<Vc<Rendering>> {
let env = self.await?;
Ok(match env.execution {
ExecutionEnvironment::NodeJsBuildTime(env)
| ExecutionEnvironment::NodeJsLambda(env) => {
Rendering::Server(env.await?.server_addr).cell()
}
ExecutionEnvironment::EdgeWorker(env) => {
Rendering::Server(env.await?.server_addr).cell()
ExecutionEnvironment::NodeJsBuildTime(_) | ExecutionEnvironment::NodeJsLambda(_) => {
Rendering::Server.cell()
}
ExecutionEnvironment::EdgeWorker(_) => Rendering::Server.cell(),
ExecutionEnvironment::Browser(_) => Rendering::Client.cell(),
_ => Rendering::None.cell(),
})
Expand Down Expand Up @@ -344,7 +227,6 @@ pub struct NodeJsEnvironment {
pub node_version: Vc<NodeJsVersion>,
// user specified process.cwd
pub cwd: Vc<Option<String>>,
pub server_addr: Vc<ServerAddr>,
}

impl Default for NodeJsEnvironment {
Expand All @@ -353,7 +235,6 @@ impl Default for NodeJsEnvironment {
compile_target: CompileTarget::current(),
node_version: NodeJsVersion::default().cell(),
cwd: Vc::cell(None),
server_addr: ServerAddr::empty(),
}
}
}
Expand All @@ -377,12 +258,11 @@ impl NodeJsEnvironment {
}

#[turbo_tasks::function]
pub fn current(process_env: Vc<Box<dyn ProcessEnv>>, server_addr: Vc<ServerAddr>) -> Vc<Self> {
pub fn current(process_env: Vc<Box<dyn ProcessEnv>>) -> Vc<Self> {
Self::cell(NodeJsEnvironment {
compile_target: CompileTarget::current(),
node_version: NodeJsVersion::cell(NodeJsVersion::Current(process_env)),
cwd: Vc::cell(None),
server_addr,
})
}
}
Expand All @@ -408,9 +288,7 @@ pub struct BrowserEnvironment {
}

#[turbo_tasks::value(shared)]
pub struct EdgeWorkerEnvironment {
pub server_addr: Vc<ServerAddr>,
}
pub struct EdgeWorkerEnvironment {}

#[turbo_tasks::value(transparent)]
pub struct RuntimeVersions(#[turbo_tasks(trace_ignore)] pub Versions);
Expand Down
2 changes: 1 addition & 1 deletion crates/turbopack-ecmascript/src/references/esm/url.rs
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ impl CodeGenerateable for UrlAssetReference {
// `import.meta.url`.
let rewrite_url_base = match &*this.rendering.await? {
Rendering::Client => Some(quote!("location.origin" as Expr)),
Rendering::None | Rendering::Server(..) => None,
Rendering::None | Rendering::Server => None,
};

match &*referenced_asset {
Expand Down