Skip to main content

vertigo_cli/serve/
mount_path.rs

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 pretty_html: bool,
17}
18
19impl MountConfigBuilder {
20    pub fn new(mount_point: impl Into<String>, dest_dir: impl Into<String>) -> MountConfigBuilder {
21        MountConfigBuilder {
22            mount_point: mount_point.into(),
23            dest_dir: dest_dir.into(),
24            env: vec![],
25            wasm_preload: false,
26            disable_hydration: false,
27            ssr_fetch_base: None,
28            pretty_html: false,
29        }
30    }
31
32    pub fn envs(mut self, envs: Vec<(String, String)>) -> Self {
33        self.env = envs;
34        self
35    }
36
37    pub fn env(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
38        self.env.push((key.into(), value.into()));
39        self
40    }
41
42    pub fn wasm_preload(mut self, wasm_preload: bool) -> Self {
43        self.wasm_preload = wasm_preload;
44        self
45    }
46
47    pub fn disable_hydration(mut self, disable_hydration: bool) -> Self {
48        self.disable_hydration = disable_hydration;
49        self
50    }
51
52    /// Origin against which SSR resolves relative fetch URLs (`/api/posts`), e.g. `http://127.0.0.1:8080`.
53    ///
54    /// Without it, fetching a relative URL during SSR fails.
55    pub fn ssr_fetch_base(mut self, origin: impl Into<String>) -> Self {
56        self.ssr_fetch_base = Some(origin.into());
57        self
58    }
59
60    /// Indent the server-rendered HTML, to read it in the page source.
61    ///
62    /// Off by default: the indentation is whitespace between elements, which the app's own tree
63    /// doesn't have - until the app starts it shows as gaps between inline elements, and
64    /// hydration then takes it out, one node at a time.
65    pub fn pretty_html(mut self, pretty_html: bool) -> Self {
66        self.pretty_html = pretty_html;
67        self
68    }
69
70    pub fn build(self) -> Result<MountConfig, ErrorCode> {
71        let mut config = MountConfig::new(
72            self.mount_point,
73            self.dest_dir,
74            self.env,
75            self.wasm_preload,
76            self.disable_hydration,
77        )?;
78        config.ssr_fetch_base = self.ssr_fetch_base;
79        config.pretty_html = self.pretty_html;
80        Ok(config)
81    }
82}
83
84#[derive(Clone, Debug)]
85pub struct MountConfig {
86    /// Mount point in URL
87    mount_point: String,
88    /// Build destination directory (where wasm file and wasm_run.js are stored)
89    dest_dir: String,
90    /// waasm_run.js taken from index.json
91    run_js: String,
92    /// path to wasm-file taken from index.json
93    wasm_path: String,
94    /// Environment variables passed to WASM runtime - together with the mount point and the
95    /// public path of the build (`vertigo-mount-point`, `vertigo-public-path`)
96    pub env: Arc<HashMap<String, String>>,
97    /// Whether to preload wasm script using <link rel="preload">
98    pub wasm_preload: bool,
99    /// Whether to disable hydration
100    pub disable_hydration: bool,
101    /// See [`MountConfigBuilder::ssr_fetch_base`]
102    pub ssr_fetch_base: Option<String>,
103    /// See [`MountConfigBuilder::pretty_html`]
104    pub pretty_html: bool,
105}
106
107impl MountConfig {
108    pub fn new(
109        public_mount_point: impl Into<String>,
110        dest_dir: impl Into<String>,
111        env: Vec<(String, String)>,
112        wasm_preload: bool,
113        disable_hydration: bool,
114    ) -> Result<MountConfig, ErrorCode> {
115        let dest_dir = dest_dir.into();
116        let index_model = read_index(&dest_dir)?;
117
118        let mut config = MountConfig {
119            dest_dir,
120            mount_point: public_mount_point.into(),
121            run_js: index_model.run_js,
122            wasm_path: index_model.wasm,
123            env: Arc::default(),
124            wasm_preload,
125            disable_hydration,
126            ssr_fetch_base: None,
127            pretty_html: false,
128        };
129
130        // The app gets them wherever it runs - in the browser as `data-env-*`, during SSR from
131        // the host - so both sides build the same paths (`Driver::route_to_public`,
132        // `Driver::public_build_path`)
133        let mut env: HashMap<String, String> = env.into_iter().collect();
134        env.insert(VERTIGO_MOUNT_POINT_ENV.into(), config.mount_point.clone());
135        env.insert(VERTIGO_PUBLIC_PATH_ENV.into(), config.dest_http_root());
136        config.env = Arc::new(env);
137
138        Ok(config)
139    }
140
141    pub fn mount_point(&self) -> &str {
142        self.mount_point.as_str()
143    }
144
145    pub fn dest_dir(&self) -> &str {
146        self.dest_dir.trim_start_matches("./")
147    }
148
149    pub fn dest_http_root(&self) -> String {
150        Path::new(&self.mount_point)
151            .join(self.dest_dir())
152            .components()
153            .as_path()
154            .to_string_lossy()
155            .into_owned()
156    }
157
158    pub fn get_wasm_http_path(&self) -> String {
159        self.translate_to_http(&self.wasm_path)
160    }
161
162    pub fn get_run_js_http_path(&self) -> String {
163        self.translate_to_http(&self.run_js)
164    }
165
166    pub fn get_wasm_fs_path(&self) -> String {
167        self.translate_to_fs(&self.wasm_path)
168    }
169
170    fn translate_to_http(&self, fs_path: impl Into<String>) -> String {
171        let fs_path = fs_path.into();
172        fs_path.replace(
173            VERTIGO_PUBLIC_BUILD_PATH_PLACEHOLDER,
174            &self.dest_http_root(),
175        )
176    }
177
178    fn translate_to_fs(&self, http_path: impl Into<String>) -> String {
179        let http_path = http_path.into();
180        replace_prefix(&self.dest_dir, &http_path)
181    }
182}
183
184fn read_index(dest_dir: &str) -> Result<IndexModel, ErrorCode> {
185    let index_path = Path::new(dest_dir).join("index.json");
186    let index_html = match std::fs::read_to_string(&index_path) {
187        Ok(data) => data,
188        Err(err) => {
189            log::error!("File read error: file={index_path:?}, error={err}, dest_dir={dest_dir}");
190            return Err(ErrorCode::ServeCantReadIndexFile);
191        }
192    };
193
194    serde_json::from_str::<IndexModel>(&index_html).map_err(|err| {
195        log::error!("File read error 2: file={index_path:?}, error={err}, dest_dir={dest_dir}");
196        ErrorCode::ServeCantReadIndexFile
197    })
198}
199
200fn replace_prefix(dest_dir: &str, path: &str) -> String {
201    if path.starts_with(VERTIGO_PUBLIC_BUILD_PATH_PLACEHOLDER) {
202        // Dynamic path resolution
203        path.replace(VERTIGO_PUBLIC_BUILD_PATH_PLACEHOLDER, dest_dir)
204    } else {
205        // Static path resolution
206        path.to_string()
207    }
208}
209
210#[cfg(test)]
211mod tests {
212    use vertigo::dev::VERTIGO_PUBLIC_BUILD_PATH_PLACEHOLDER;
213
214    use super::{MountConfig, MountConfigBuilder, replace_prefix};
215
216    #[test]
217    fn html_is_indented_only_when_asked() -> std::io::Result<()> {
218        let dest_dir = std::env::temp_dir().join(format!("vertigo-pretty-{}", std::process::id()));
219        std::fs::create_dir_all(&dest_dir)?;
220        std::fs::write(
221            dest_dir.join("index.json"),
222            r#"{"run_js": "wasm_run.js", "wasm": "app.wasm"}"#,
223        )?;
224
225        let builder = || MountConfigBuilder::new("/", dest_dir.to_string_lossy());
226        let (Ok(default), Ok(pretty)) = (builder().build(), builder().pretty_html(true).build())
227        else {
228            panic!("index.json in {dest_dir:?} should read");
229        };
230
231        assert!(!default.pretty_html);
232        assert!(pretty.pretty_html);
233
234        std::fs::remove_dir_all(&dest_dir)
235    }
236
237    #[test]
238    fn env_carries_mount_point_and_public_path() -> std::io::Result<()> {
239        let dest_dir = std::env::temp_dir().join(format!("vertigo-mount-{}", std::process::id()));
240        std::fs::create_dir_all(&dest_dir)?;
241        std::fs::write(
242            dest_dir.join("index.json"),
243            r#"{"run_js": "wasm_run.js", "wasm": "app.wasm"}"#,
244        )?;
245
246        let Ok(config) = MountConfig::new(
247            "/panel",
248            dest_dir.to_string_lossy(),
249            vec![
250                ("api_url".into(), "/api".into()),
251                // the server knows better where it mounted the app
252                ("vertigo-mount-point".into(), "/elsewhere".into()),
253            ],
254            false,
255            false,
256        ) else {
257            panic!("index.json in {dest_dir:?} should read");
258        };
259
260        assert_eq!(config.env["api_url"], "/api");
261        assert_eq!(config.env["vertigo-mount-point"], "/panel");
262        assert_eq!(config.env["vertigo-public-path"], config.dest_http_root());
263
264        std::fs::remove_dir_all(&dest_dir)
265    }
266
267    #[test]
268    fn test_replace_prefix() {
269        assert_eq!(
270            replace_prefix("demo_build", "build/vertigo_demo.33.wasm"),
271            "build/vertigo_demo.33.wasm".to_string()
272        );
273
274        assert_eq!(
275            replace_prefix("demo_build", "build/vertigo_demo.33.wasm"),
276            "build/vertigo_demo.33.wasm".to_string()
277        );
278
279        assert_eq!(
280            replace_prefix(
281                "demo_build",
282                &format!("{VERTIGO_PUBLIC_BUILD_PATH_PLACEHOLDER}/vertigo_demo.33.wasm")
283            ),
284            "demo_build/vertigo_demo.33.wasm".to_string()
285        );
286    }
287}