1#![allow(clippy::question_mark)]
2use std::{collections::HashMap, path::Path, sync::Arc};
3use vertigo::dev::{
4 VERTIGO_MOUNT_POINT_ENV, VERTIGO_PUBLIC_BUILD_PATH_PLACEHOLDER, VERTIGO_PUBLIC_PATH_ENV,
5};
6
7use crate::commons::{ErrorCode, models::IndexModel};
8
9pub struct MountConfigBuilder {
10 pub mount_point: String,
11 pub dest_dir: String,
12 pub env: Vec<(String, String)>,
13 pub wasm_preload: bool,
14 pub disable_hydration: bool,
15 pub ssr_fetch_base: Option<String>,
16 pub ssr_cookies: Vec<String>,
17 pub pretty_html: bool,
18 pub precompress: bool,
19}
20
21impl MountConfigBuilder {
22 pub fn new(mount_point: impl Into<String>, dest_dir: impl Into<String>) -> MountConfigBuilder {
23 MountConfigBuilder {
24 mount_point: mount_point.into(),
25 dest_dir: dest_dir.into(),
26 env: vec![],
27 wasm_preload: false,
28 disable_hydration: false,
29 ssr_fetch_base: None,
30 ssr_cookies: vec![],
31 pretty_html: false,
32 precompress: false,
33 }
34 }
35
36 pub fn envs(mut self, envs: Vec<(String, String)>) -> Self {
37 self.env = envs;
38 self
39 }
40
41 pub fn env(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
42 self.env.push((key.into(), value.into()));
43 self
44 }
45
46 pub fn wasm_preload(mut self, wasm_preload: bool) -> Self {
47 self.wasm_preload = wasm_preload;
48 self
49 }
50
51 pub fn disable_hydration(mut self, disable_hydration: bool) -> Self {
52 self.disable_hydration = disable_hydration;
53 self
54 }
55
56 pub fn ssr_fetch_base(mut self, origin: impl Into<String>) -> Self {
60 self.ssr_fetch_base = Some(origin.into());
61 self
62 }
63
64 pub fn ssr_cookie(mut self, name: impl Into<String>) -> Self {
71 self.ssr_cookies.push(name.into());
72 self
73 }
74
75 pub fn pretty_html(mut self, pretty_html: bool) -> Self {
81 self.pretty_html = pretty_html;
82 self
83 }
84
85 pub fn precompress(mut self, precompress: bool) -> Self {
94 self.precompress = precompress;
95 self
96 }
97
98 pub fn precompress_in_release(self) -> Self {
105 self.precompress(!cfg!(debug_assertions))
106 }
107
108 pub fn build(self) -> Result<MountConfig, ErrorCode> {
109 let mut config = MountConfig::new(
110 self.mount_point,
111 self.dest_dir,
112 self.env,
113 self.wasm_preload,
114 self.disable_hydration,
115 )?;
116 config.ssr_fetch_base = self.ssr_fetch_base;
117 config.ssr_cookies = self.ssr_cookies;
118 config.pretty_html = self.pretty_html;
119 config.precompress = self.precompress;
120 Ok(config)
121 }
122}
123
124#[derive(Clone, Debug)]
125pub struct MountConfig {
126 mount_point: String,
128 dest_dir: String,
130 run_js: String,
132 wasm_path: String,
134 pub env: Arc<HashMap<String, String>>,
137 pub wasm_preload: bool,
139 pub disable_hydration: bool,
141 pub ssr_fetch_base: Option<String>,
143 pub ssr_cookies: Vec<String>,
145 pub pretty_html: bool,
147 pub precompress: bool,
149}
150
151impl MountConfig {
152 pub fn new(
153 public_mount_point: impl Into<String>,
154 dest_dir: impl Into<String>,
155 env: Vec<(String, String)>,
156 wasm_preload: bool,
157 disable_hydration: bool,
158 ) -> Result<MountConfig, ErrorCode> {
159 let dest_dir = dest_dir.into();
160 let index_model = read_index(&dest_dir)?;
161
162 let mut config = MountConfig {
163 dest_dir,
164 mount_point: public_mount_point.into(),
165 run_js: index_model.run_js,
166 wasm_path: index_model.wasm,
167 env: Arc::default(),
168 wasm_preload,
169 disable_hydration,
170 ssr_fetch_base: None,
171 ssr_cookies: vec![],
172 pretty_html: false,
173 precompress: false,
174 };
175
176 let mut env: HashMap<String, String> = env.into_iter().collect();
180 env.insert(VERTIGO_MOUNT_POINT_ENV.into(), config.mount_point.clone());
181 env.insert(VERTIGO_PUBLIC_PATH_ENV.into(), config.dest_http_root());
182 config.env = Arc::new(env);
183
184 Ok(config)
185 }
186
187 pub fn mount_point(&self) -> &str {
188 self.mount_point.as_str()
189 }
190
191 pub fn dest_dir(&self) -> &str {
192 self.dest_dir.trim_start_matches("./")
193 }
194
195 pub fn dest_http_root(&self) -> String {
196 Path::new(&self.mount_point)
197 .join(self.dest_dir())
198 .components()
199 .as_path()
200 .to_string_lossy()
201 .into_owned()
202 }
203
204 pub fn get_wasm_http_path(&self) -> String {
205 self.translate_to_http(&self.wasm_path)
206 }
207
208 pub fn get_run_js_http_path(&self) -> String {
209 self.translate_to_http(&self.run_js)
210 }
211
212 pub fn get_wasm_fs_path(&self) -> String {
213 self.translate_to_fs(&self.wasm_path)
214 }
215
216 fn translate_to_http(&self, fs_path: impl Into<String>) -> String {
217 let fs_path = fs_path.into();
218 fs_path.replace(
219 VERTIGO_PUBLIC_BUILD_PATH_PLACEHOLDER,
220 &self.dest_http_root(),
221 )
222 }
223
224 fn translate_to_fs(&self, http_path: impl Into<String>) -> String {
225 let http_path = http_path.into();
226 replace_prefix(&self.dest_dir, &http_path)
227 }
228}
229
230fn read_index(dest_dir: &str) -> Result<IndexModel, ErrorCode> {
231 let index_path = Path::new(dest_dir).join("index.json");
232 let index_html = match std::fs::read_to_string(&index_path) {
233 Ok(data) => data,
234 Err(err) => {
235 log::error!("File read error: file={index_path:?}, error={err}, dest_dir={dest_dir}");
236 return Err(ErrorCode::ServeCantReadIndexFile);
237 }
238 };
239
240 serde_json::from_str::<IndexModel>(&index_html).map_err(|err| {
241 log::error!("File read error 2: file={index_path:?}, error={err}, dest_dir={dest_dir}");
242 ErrorCode::ServeCantReadIndexFile
243 })
244}
245
246fn replace_prefix(dest_dir: &str, path: &str) -> String {
247 if path.starts_with(VERTIGO_PUBLIC_BUILD_PATH_PLACEHOLDER) {
248 path.replace(VERTIGO_PUBLIC_BUILD_PATH_PLACEHOLDER, dest_dir)
250 } else {
251 path.to_string()
253 }
254}
255
256#[cfg(test)]
257mod tests {
258 use vertigo::dev::VERTIGO_PUBLIC_BUILD_PATH_PLACEHOLDER;
259
260 use super::{MountConfig, MountConfigBuilder, replace_prefix};
261
262 #[test]
263 fn html_is_indented_only_when_asked() -> std::io::Result<()> {
264 let dest_dir = std::env::temp_dir().join(format!("vertigo-pretty-{}", std::process::id()));
265 std::fs::create_dir_all(&dest_dir)?;
266 std::fs::write(
267 dest_dir.join("index.json"),
268 r#"{"run_js": "wasm_run.js", "wasm": "app.wasm"}"#,
269 )?;
270
271 let builder = || MountConfigBuilder::new("/", dest_dir.to_string_lossy());
272 let (Ok(default), Ok(pretty)) = (builder().build(), builder().pretty_html(true).build())
273 else {
274 panic!("index.json in {dest_dir:?} should read");
275 };
276
277 assert!(!default.pretty_html);
278 assert!(pretty.pretty_html);
279
280 std::fs::remove_dir_all(&dest_dir)
281 }
282
283 #[test]
284 fn precompress_in_release_follows_the_build() {
285 let builder = MountConfigBuilder::new("/", "build").precompress_in_release();
286
287 assert_eq!(builder.precompress, !cfg!(debug_assertions));
289 }
290
291 #[test]
292 fn env_carries_mount_point_and_public_path() -> std::io::Result<()> {
293 let dest_dir = std::env::temp_dir().join(format!("vertigo-mount-{}", std::process::id()));
294 std::fs::create_dir_all(&dest_dir)?;
295 std::fs::write(
296 dest_dir.join("index.json"),
297 r#"{"run_js": "wasm_run.js", "wasm": "app.wasm"}"#,
298 )?;
299
300 let Ok(config) = MountConfig::new(
301 "/panel",
302 dest_dir.to_string_lossy(),
303 vec![
304 ("api_url".into(), "/api".into()),
305 ("vertigo-mount-point".into(), "/elsewhere".into()),
307 ],
308 false,
309 false,
310 ) else {
311 panic!("index.json in {dest_dir:?} should read");
312 };
313
314 assert_eq!(config.env["api_url"], "/api");
315 assert_eq!(config.env["vertigo-mount-point"], "/panel");
316 assert_eq!(config.env["vertigo-public-path"], config.dest_http_root());
317
318 std::fs::remove_dir_all(&dest_dir)
319 }
320
321 #[test]
322 fn test_replace_prefix() {
323 assert_eq!(
324 replace_prefix("demo_build", "build/vertigo_demo.33.wasm"),
325 "build/vertigo_demo.33.wasm".to_string()
326 );
327
328 assert_eq!(
329 replace_prefix("demo_build", "build/vertigo_demo.33.wasm"),
330 "build/vertigo_demo.33.wasm".to_string()
331 );
332
333 assert_eq!(
334 replace_prefix(
335 "demo_build",
336 &format!("{VERTIGO_PUBLIC_BUILD_PATH_PLACEHOLDER}/vertigo_demo.33.wasm")
337 ),
338 "demo_build/vertigo_demo.33.wasm".to_string()
339 );
340 }
341}