Unverified Commit e989fcb8 authored by Benjamin Woodruff's avatar Benjamin Woodruff Committed by GitHub

Turbopack: chore: Remove dead RouteMatcher stuff (#85784)

Turns out this is all dead code, so delete it!

It looks like this was added back in https://github.com/vercel/turborepo/pull/3448, probably when Turbopack was trying to rewrite larger parts of Next.js than ended up happening.
parent 67aa5f3d
......@@ -27,7 +27,6 @@ mod next_import_map;
pub mod next_manifests;
pub mod next_pages;
mod next_root_params;
mod next_route_matcher;
pub mod next_server;
pub mod next_server_component;
pub mod next_server_utility;
......
use serde::{Deserialize, Serialize};
use turbopack_node::route_matcher::{Params, RouteMatcherRef};
#[derive(Debug, Serialize, Deserialize, Eq, PartialEq)]
pub struct AllMatch;
impl RouteMatcherRef for AllMatch {
fn matches(&self, _path: &str) -> bool {
true
}
fn params(&self, _path: &str) -> Params {
Params(Some(Default::default()))
}
}
use anyhow::{Result, bail};
use turbo_rcstr::RcStr;
use turbo_tasks::{ResolvedVc, Vc};
use turbopack_node::route_matcher::{Params, RouteMatcher, RouteMatcherRef};
use self::{
all::AllMatch,
path_regex::{PathRegex, PathRegexBuilder},
prefix_suffix::PrefixSuffixMatcher,
};
mod all;
mod path_regex;
mod prefix_suffix;
/// A route matcher that matches a path against an exact route.
#[turbo_tasks::value]
pub(crate) struct NextExactMatcher {
path: ResolvedVc<RcStr>,
}
#[turbo_tasks::value_impl]
impl NextExactMatcher {
#[turbo_tasks::function]
pub fn new(path: ResolvedVc<RcStr>) -> Vc<Self> {
Self::cell(NextExactMatcher { path })
}
}
#[turbo_tasks::value_impl]
impl RouteMatcher for NextExactMatcher {
#[turbo_tasks::function]
async fn matches(&self, path: RcStr) -> Result<Vc<bool>> {
Ok(Vc::cell(path == *self.path.await?))
}
#[turbo_tasks::function]
async fn params(&self, path: RcStr) -> Result<Vc<Params>> {
Ok(Vc::cell(if path == *self.path.await? {
Some(Default::default())
} else {
None
}))
}
}
/// A route matcher that matches a path against a route regex.
#[turbo_tasks::value]
pub(crate) struct NextParamsMatcher {
#[turbo_tasks(trace_ignore)]
matcher: PathRegex,
}
#[turbo_tasks::value_impl]
impl NextParamsMatcher {
#[turbo_tasks::function]
pub async fn new(path: ResolvedVc<RcStr>) -> Result<Vc<Self>> {
Ok(Self::cell(NextParamsMatcher {
matcher: build_path_regex(path.await?.as_str())?,
}))
}
}
#[turbo_tasks::value_impl]
impl RouteMatcher for NextParamsMatcher {
#[turbo_tasks::function]
fn matches(&self, path: RcStr) -> Vc<bool> {
Vc::cell(self.matcher.matches(&path))
}
#[turbo_tasks::function]
fn params(&self, path: RcStr) -> Vc<Params> {
Params::cell(self.matcher.params(&path))
}
}
/// A route matcher that strips a prefix and a suffix from a path before
/// matching it against a route regex.
#[turbo_tasks::value]
pub(crate) struct NextPrefixSuffixParamsMatcher {
#[turbo_tasks(trace_ignore)]
matcher: PrefixSuffixMatcher<PathRegex>,
}
#[turbo_tasks::value_impl]
impl NextPrefixSuffixParamsMatcher {
/// Converts a filename within the server root into a regular expression
/// with named capture groups for every dynamic segment.
#[turbo_tasks::function]
pub async fn new(path: ResolvedVc<RcStr>, prefix: RcStr, suffix: RcStr) -> Result<Vc<Self>> {
Ok(Self::cell(NextPrefixSuffixParamsMatcher {
matcher: PrefixSuffixMatcher::new(
prefix.to_string(),
suffix.to_string(),
build_path_regex(path.await?.as_str())?,
),
}))
}
}
#[turbo_tasks::value_impl]
impl RouteMatcher for NextPrefixSuffixParamsMatcher {
#[turbo_tasks::function]
fn matches(&self, path: RcStr) -> Vc<bool> {
Vc::cell(self.matcher.matches(&path))
}
#[turbo_tasks::function]
fn params(&self, path: RcStr) -> Vc<Params> {
Params::cell(self.matcher.params(&path))
}
}
/// A route matcher that matches against all paths.
#[turbo_tasks::value]
pub(crate) struct NextFallbackMatcher {
#[turbo_tasks(trace_ignore)]
matcher: AllMatch,
}
#[turbo_tasks::value_impl]
impl NextFallbackMatcher {
#[turbo_tasks::function]
pub fn new() -> Vc<Self> {
Self::cell(NextFallbackMatcher { matcher: AllMatch })
}
}
#[turbo_tasks::value_impl]
impl RouteMatcher for NextFallbackMatcher {
#[turbo_tasks::function]
fn matches(&self, path: RcStr) -> Vc<bool> {
Vc::cell(self.matcher.matches(&path))
}
#[turbo_tasks::function]
fn params(&self, path: RcStr) -> Vc<Params> {
Params::cell(self.matcher.params(&path))
}
}
/// Converts a filename within the server root into a regular expression
/// with named capture groups for every dynamic segment.
fn build_path_regex(path: &str) -> Result<PathRegex> {
let mut path_regex = PathRegexBuilder::new();
for segment in path.split('/') {
if let Some(segment) = segment.strip_prefix('[') {
if let Some(segment) = segment.strip_prefix("[...") {
if let Some((placeholder, rem)) = segment.split_once("]]") {
path_regex.push_optional_catch_all(placeholder, rem);
} else {
bail!(
"path ({}) contains '[[' without matching ']]' at '[[...{}'",
path,
segment
);
}
} else if let Some(segment) = segment.strip_prefix("...") {
if let Some((placeholder, rem)) = segment.split_once(']') {
path_regex.push_catch_all(placeholder, rem);
} else {
bail!(
"path ({}) contains '[' without matching ']' at '[...{}'",
path,
segment
);
}
} else if let Some((placeholder, rem)) = segment.split_once(']') {
path_regex.push_dynamic_segment(placeholder, rem);
} else {
bail!(
"path ({}) contains '[' without matching ']' at '[{}'",
path,
segment
);
}
} else {
path_regex.push_static_segment(segment);
}
}
path_regex.build()
}
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use turbo_tasks::primitives::Regex;
use turbopack_node::route_matcher::{Param, Params, RouteMatcherRef};
/// A regular expression that matches a path, with named capture groups for the
/// dynamic parts of the path.
#[derive(Debug, Serialize, Deserialize, Eq, PartialEq)]
pub struct PathRegex {
regex: Regex,
named_params: Vec<NamedParam>,
}
#[derive(Debug, Serialize, Deserialize, Eq, PartialEq)]
struct NamedParam {
name: String,
kind: NamedParamKind,
}
#[derive(Debug, Serialize, Deserialize, Eq, PartialEq)]
enum NamedParamKind {
Single,
Multi,
}
impl std::fmt::Display for PathRegex {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.regex.as_str())
}
}
impl RouteMatcherRef for PathRegex {
fn matches(&self, path: &str) -> bool {
self.regex.is_match(path)
}
fn params(&self, path: &str) -> Params {
Params(self.regex.captures(path).map(|capture| {
self.named_params
.iter()
.enumerate()
.filter_map(|(idx, param)| {
if param.name.is_empty() {
return None;
}
let value = capture.get(idx + 1)?;
Some((
param.name.as_str().into(),
match param.kind {
NamedParamKind::Single => Param::Single(value.as_str().into()),
NamedParamKind::Multi => Param::Multi(
value
.as_str()
.split('/')
.map(|segment| segment.into())
.collect(),
),
},
))
})
.collect()
}))
}
}
/// Builder for [PathRegex].
pub struct PathRegexBuilder {
regex_str: String,
named_params: Vec<NamedParam>,
}
impl PathRegexBuilder {
/// Creates a new [PathRegexBuilder].
pub fn new() -> Self {
Self {
regex_str: "^".to_string(),
named_params: Default::default(),
}
}
fn include_slash(&self) -> bool {
self.regex_str.len() > 1
}
fn push_str(&mut self, str: &str) {
self.regex_str.push_str(str);
}
/// Pushes an optional catch all segment to the regex.
pub fn push_optional_catch_all<N, R>(&mut self, name: N, rem: R)
where
N: Into<String>,
R: AsRef<str>,
{
self.push_str(if self.include_slash() {
"(?:/([^?]+))?"
} else {
"([^?]+)?"
});
self.push_str(&regex::escape(rem.as_ref()));
self.named_params.push(NamedParam {
name: name.into(),
kind: NamedParamKind::Multi,
});
}
/// Pushes a catch all segment to the regex.
pub fn push_catch_all<N, R>(&mut self, name: N, rem: R)
where
N: Into<String>,
R: AsRef<str>,
{
if self.include_slash() {
self.push_str("/");
}
self.push_str("([^?]+)");
self.push_str(&regex::escape(rem.as_ref()));
self.named_params.push(NamedParam {
name: name.into(),
kind: NamedParamKind::Multi,
});
}
/// Pushes a dynamic segment to the regex.
pub fn push_dynamic_segment<N, R>(&mut self, name: N, rem: R)
where
N: Into<String>,
R: AsRef<str>,
{
if self.include_slash() {
self.push_str("/");
}
self.push_str("([^?/]+)");
self.push_str(&regex::escape(rem.as_ref()));
self.named_params.push(NamedParam {
name: name.into(),
kind: NamedParamKind::Single,
});
}
/// Pushes a static segment to the regex.
pub fn push_static_segment<S>(&mut self, segment: S)
where
S: AsRef<str>,
{
if self.include_slash() {
self.push_str("/");
}
self.push_str(&regex::escape(segment.as_ref()));
}
/// Builds and returns the [PathRegex].
pub fn build(mut self) -> Result<PathRegex> {
self.regex_str += "$";
Ok(PathRegex {
regex: Regex(regex::Regex::new(&self.regex_str).with_context(|| "invalid path regex")?),
named_params: self.named_params,
})
}
}
impl Default for PathRegexBuilder {
fn default() -> Self {
Self::new()
}
}
use serde::{Deserialize, Serialize};
use turbopack_node::route_matcher::{Params, RouteMatcherRef};
/// A composite route matcher that matches a path if it has a given prefix and
/// suffix.
#[derive(Debug, Serialize, Deserialize, Eq, PartialEq)]
pub struct PrefixSuffixMatcher<T>
where
T: RouteMatcherRef,
{
prefix: String,
suffix: String,
inner: T,
}
impl<T> PrefixSuffixMatcher<T>
where
T: RouteMatcherRef,
{
/// Creates a new [PrefixSuffixMatcher].
pub fn new(prefix: String, suffix: String, inner: T) -> Self {
Self {
prefix,
suffix,
inner,
}
}
fn strip_prefix_and_suffix<'b>(&self, path: &'b str) -> Option<&'b str> {
path.strip_prefix(self.prefix.as_str())?
.strip_suffix(self.suffix.as_str())
}
}
impl<T> RouteMatcherRef for PrefixSuffixMatcher<T>
where
T: RouteMatcherRef,
{
fn matches(&self, path: &str) -> bool {
if let Some(path) = self.strip_prefix_and_suffix(path) {
self.inner.matches(path)
} else {
false
}
}
fn params(&self, path: &str) -> Params {
if let Some(path) = self.strip_prefix_and_suffix(path) {
self.inner.params(path)
} else {
Params(None)
}
}
}
......@@ -32,7 +32,6 @@ pub mod evaluate;
pub mod execution_context;
mod heap_queue;
mod pool;
pub mod route_matcher;
pub mod source_map;
pub mod transforms;
......
use turbo_rcstr::RcStr;
use turbo_tasks::{FxIndexMap, Vc};
#[turbo_tasks::value]
#[derive(Debug, Clone)]
#[serde(untagged)]
pub enum Param {
Single(RcStr),
Multi(Vec<RcStr>),
}
#[turbo_tasks::value(transparent)]
#[derive(Debug, Clone)]
pub struct Params(pub Option<FxIndexMap<RcStr, Param>>);
/// Extracts parameters from a URL path.
pub trait RouteMatcherRef {
/// Returns whether the given path is a match for the route.
fn matches(&self, path: &str) -> bool;
/// Returns the parameters extracted from the given path.
fn params(&self, path: &str) -> Params;
}
/// Extracts parameters from a URL path (Vc version)
#[turbo_tasks::value_trait]
pub trait RouteMatcher {
/// Returns whether the given path is a match for the route.
#[turbo_tasks::function]
fn matches(self: Vc<Self>, path: RcStr) -> Vc<bool>;
/// Returns the parameters extracted from the given path.
#[turbo_tasks::function]
fn params(self: Vc<Self>, path: RcStr) -> Vc<Params>;
}
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