Skip to main content

euv_cli/server/
fn.rs

1use crate::*;
2
3/// Sets the global application state.
4///
5/// # Arguments
6///
7/// - `Arc<AppState>` - The shared application state to store globally.
8///
9/// # Returns
10///
11/// - `Result<(), EuvError>` - Indicates success or failure of the initialization.
12pub fn set_global_state(state: Arc<AppState>) -> Result<(), EuvError> {
13    APP_STATE.set(state).map_err(|_: Arc<AppState>| {
14        EuvError::Message(String::from("Global state already initialized"))
15    })
16}
17
18/// Retrieves the global application state.
19///
20/// # Returns
21///
22/// - `Option<Arc<AppState>>` - The global state if initialized.
23pub fn get_global_state() -> Option<Arc<AppState>> {
24    APP_STATE.get().cloned()
25}
26
27/// Generates `index.html` based on the build profile.
28///
29/// Uses `INDEX_HTML_RELEASE` when `is_release` is `true` (no live-reload script),
30/// otherwise uses `INDEX_HTML_DEV` (includes live-reload instrumentation).
31///
32/// Then writes the template with the import path placeholder replaced to disk.
33///
34/// # Arguments
35///
36/// - `&Path` - The path to the www directory where `index.html` will be written.
37/// - `&str` - The JS import path relative to the www directory (e.g. `./pkg/euv` or `./euv`).
38/// - `bool` - Whether to use the release template (no live-reload).
39///
40/// # Returns
41///
42/// - `Result<String, EuvError>` - The generated HTML content written to disk.
43pub async fn generate_html(
44    www_dir: &Path,
45    import_path: &str,
46    is_release: bool,
47    custom_index_html: &Option<PathBuf>,
48) -> Result<String, EuvError> {
49    let template_content: String = if let Some(custom_path) = custom_index_html {
50        let bytes: Vec<u8> =
51            read(custom_path)
52                .await
53                .map_err(|error: io::Error| EuvError::IoPath {
54                    message: String::from("Failed to read custom index.html"),
55                    path: custom_path.to_path_buf(),
56                    error,
57                })?;
58        String::from_utf8(bytes).map_err(|error: std::string::FromUtf8Error| EuvError::Utf8 {
59            message: String::from("Custom index.html is not valid UTF-8"),
60            error,
61        })?
62    } else if is_release {
63        INDEX_HTML_RELEASE.to_string()
64    } else {
65        INDEX_HTML_DEV.to_string()
66    };
67    let html: String = template_content
68        .replace(IMPORT_PATH_PLACEHOLDER, import_path)
69        .replace(RELOAD_ROUTE_PLACEHOLDER, RELOAD_ROUTE);
70    let index_path: PathBuf = www_dir.join(INDEX_HTML_FILE_NAME);
71    create_dir_all(www_dir)
72        .await
73        .map_err(|error: io::Error| EuvError::Io {
74            message: String::from("Failed to create static directory"),
75            error,
76        })?;
77    write(&index_path, &html)
78        .await
79        .map_err(|error: io::Error| EuvError::Io {
80            message: String::from("Failed to write index.html"),
81            error,
82        })?;
83    Ok(html)
84}
85
86/// Resolves the effective www directory, handling wasm-pack nested output.
87///
88/// # Arguments
89///
90/// - `&Path` - The candidate www directory path.
91///
92/// # Returns
93///
94/// - `PathBuf` - The resolved www directory containing `index.html`.
95pub async fn resolve_www_dir(www_dir: &Path) -> PathBuf {
96    if metadata(www_dir.join(INDEX_HTML_FILE_NAME)).await.is_ok() {
97        return www_dir.to_path_buf();
98    }
99    let parent_name: Option<&str> = www_dir
100        .file_name()
101        .and_then(|file_name_os_str: &ffi::OsStr| file_name_os_str.to_str());
102    if let Some(name) = parent_name {
103        let nested: PathBuf = www_dir.join(name);
104        if metadata(nested.join(INDEX_HTML_FILE_NAME)).await.is_ok() {
105            return nested;
106        }
107    }
108    www_dir.to_path_buf()
109}
110
111/// Resolves the pkg directory for serving WASM artifacts.
112///
113/// Delegates to `resolve_out_dir` which respects `--out-dir`
114/// from wasm-pack args or defaults to `{www_dir}/pkg`.
115///
116/// # Arguments
117///
118/// - `&ModeArgs` - The CLI arguments for resolving out_dir.
119///
120/// # Returns
121///
122/// - `PathBuf` - The resolved pkg directory containing WASM build artifacts.
123pub fn resolve_pkg_dir(args: &ModeArgs) -> PathBuf {
124    resolve_out_dir(args)
125}