/
manifest.rs
233 lines (205 loc) · 7.28 KB
/
manifest.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
use anyhow::{Context, Result};
use indexmap::IndexMap;
use mime::{APPLICATION_JAVASCRIPT_UTF_8, APPLICATION_JSON};
use serde::Serialize;
use turbo_binding::{
turbo::{tasks::TryJoinIterExt, tasks_fs::File},
turbopack::{
core::{
asset::AssetContentVc,
introspect::{Introspectable, IntrospectableVc},
},
dev_server::source::{
ContentSource, ContentSourceContentVc, ContentSourceData, ContentSourceResultVc,
ContentSourceVc,
},
node::render::{
node_api_source::NodeApiContentSourceVc, rendered_source::NodeRenderContentSourceVc,
},
},
};
use turbo_tasks::{
graph::{GraphTraversal, NonDeterministic},
primitives::{StringReadRef, StringVc, StringsVc},
};
use crate::{
embed_js::next_js_file,
next_config::{NextConfigVc, RewritesReadRef},
util::get_asset_path_from_route,
};
/// A content source which creates the next.js `_devPagesManifest.json` and
/// `_devMiddlewareManifest.json` which are used for client side navigation.
#[turbo_tasks::value(shared)]
pub struct DevManifestContentSource {
pub page_roots: Vec<ContentSourceVc>,
pub next_config: NextConfigVc,
}
#[turbo_tasks::value_impl]
impl DevManifestContentSourceVc {
/// Recursively find all routes in the `page_roots` content sources.
#[turbo_tasks::function]
async fn find_routes(self) -> Result<StringsVc> {
let this = &*self.await?;
async fn content_source_to_pathname(
content_source: ContentSourceVc,
) -> Result<Option<StringReadRef>> {
// TODO This shouldn't use casts but an public api instead
if let Some(api_source) = NodeApiContentSourceVc::resolve_from(content_source).await? {
return Ok(Some(api_source.get_pathname().await?));
}
if let Some(page_source) =
NodeRenderContentSourceVc::resolve_from(content_source).await?
{
return Ok(Some(page_source.get_pathname().await?));
}
Ok(None)
}
async fn get_content_source_children(
content_source: ContentSourceVc,
) -> Result<Vec<ContentSourceVc>> {
Ok(content_source.get_children().await?.clone_value())
}
let routes = NonDeterministic::new()
.visit(this.page_roots.iter().copied(), get_content_source_children)
.await
.completed()?
.into_iter()
.map(content_source_to_pathname)
.try_join()
.await?;
let mut routes = routes
.into_iter()
.flatten()
.map(|s| {
if !s.starts_with('/') {
format!("/{}", s)
} else {
s.to_string()
}
})
.collect::<Vec<_>>();
routes.sort_by_cached_key(|s| s.split('/').map(PageSortKey::from).collect::<Vec<_>>());
routes.dedup();
Ok(StringsVc::cell(routes))
}
/// Recursively find all pages in the `page_roots` content sources
/// (excluding api routes).
#[turbo_tasks::function]
async fn find_pages(self) -> Result<StringsVc> {
let routes = &*self.find_routes().await?;
// we don't need to sort as it's already sorted by `find_routes`
let pages = routes
.iter()
.filter(|s| !s.starts_with("/api"))
.cloned()
.collect();
Ok(StringsVc::cell(pages))
}
/// Create a build manifest with all pages.
#[turbo_tasks::function]
async fn create_build_manifest(self) -> Result<StringVc> {
let this = &*self.await?;
let sorted_pages = &*self.find_pages().await?;
let routes = sorted_pages
.iter()
.map(|p| {
(
p,
vec![format!(
"_next/static/chunks/pages/{}",
get_asset_path_from_route(p, ".js")
)],
)
})
.collect();
let manifest = BuildManifest {
rewrites: this.next_config.rewrites().await?,
sorted_pages,
routes,
};
let manifest = next_js_file("entry/manifest/buildManifest.js")
.await?
.as_content()
.context("embedded buildManifest file missing")?
.content()
.to_str()?
.replace("$$MANIFEST$$", &serde_json::to_string(&manifest)?);
Ok(StringVc::cell(manifest))
}
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct BuildManifest<'a> {
#[serde(rename = "__rewrites")]
rewrites: RewritesReadRef,
sorted_pages: &'a Vec<String>,
#[serde(flatten)]
routes: IndexMap<&'a String, Vec<String>>,
}
#[turbo_tasks::value_impl]
impl ContentSource for DevManifestContentSource {
#[turbo_tasks::function]
async fn get(
self_vc: DevManifestContentSourceVc,
path: &str,
_data: turbo_tasks::Value<ContentSourceData>,
) -> Result<ContentSourceResultVc> {
let manifest_file = match path {
"_next/static/development/_devPagesManifest.json" => {
let pages = &*self_vc.find_routes().await?;
File::from(serde_json::to_string(&serde_json::json!({
"pages": pages,
}))?)
.with_content_type(APPLICATION_JSON)
}
"_next/static/development/_buildManifest.js" => {
let build_manifest = &*self_vc.create_build_manifest().await?;
File::from(build_manifest.as_str()).with_content_type(APPLICATION_JAVASCRIPT_UTF_8)
}
"_next/static/development/_devMiddlewareManifest.json" => {
// empty middleware manifest
File::from("[]").with_content_type(APPLICATION_JSON)
}
_ => return Ok(ContentSourceResultVc::not_found()),
};
Ok(ContentSourceResultVc::exact(
ContentSourceContentVc::static_content(AssetContentVc::from(manifest_file).into())
.into(),
))
}
}
#[turbo_tasks::value_impl]
impl Introspectable for DevManifestContentSource {
#[turbo_tasks::function]
fn ty(&self) -> StringVc {
StringVc::cell("dev manifest source".to_string())
}
#[turbo_tasks::function]
fn details(&self) -> StringVc {
StringVc::cell(
"provides _devPagesManifest.json, _buildManifest.js and _devMiddlewareManifest.json."
.to_string(),
)
}
}
/// PageSortKey is necessary because the next.js client code looks for matches
/// in the order the pages are sent in the manifest,if they're sorted
/// alphabetically this means \[slug] and \[\[catchall]] routes are prioritized
/// over fixed paths, so we have to override the ordering with this.
#[derive(Ord, PartialOrd, Eq, PartialEq)]
enum PageSortKey {
Static(String),
Slug,
CatchAll,
}
impl From<&str> for PageSortKey {
fn from(value: &str) -> Self {
if value.starts_with("[[") && value.ends_with("]]") {
PageSortKey::CatchAll
} else if value.starts_with('[') && value.ends_with(']') {
PageSortKey::Slug
} else {
PageSortKey::Static(value.to_string())
}
}
}