1use super::*;
2
3pub(crate) fn set_global_state(state: Arc<AppState>) -> Result<(), EuvError> {
13 APP_STATE.set(state).map_err(|_: Arc<AppState>| {
14 EuvError::Message(ERROR_GLOBAL_STATE_ALREADY_INITIALIZED.to_string())
15 })
16}
17
18pub(crate) fn get_global_state() -> Option<Arc<AppState>> {
24 APP_STATE.get().cloned()
25}
26
27async fn resolve_inline_js(config: &HtmlConfig) -> Result<String, EuvError> {
50 let (pkg_dir, wasm_url): (PathBuf, String) = resolve_bridge_location(config)?;
51 let js_name: String = config
52 .get_import_path()
53 .rsplit('/')
54 .next()
55 .unwrap_or_default()
56 .to_string();
57 let js_path: PathBuf = pkg_dir.join(&js_name);
58 if !js_path.is_file() {
59 return Err(EuvError::IoPath {
60 message: format!(
61 "wasm-pack wrote no JS bridge to inline; {} is missing, so this build \
62 cannot produce a JavaScript-free page",
63 js_path.display()
64 ),
65 path: js_path,
66 error: io::Error::new(io::ErrorKind::NotFound, "no wasm-bindgen JS bridge"),
67 });
68 }
69 build_inline_bridge(&pkg_dir, &js_name, &wasm_url).await
70}
71
72fn resolve_bridge_location(config: &HtmlConfig) -> Result<(PathBuf, String), EuvError> {
90 let import_path: &str = config.get_import_path();
91 let Some((relative_dir, js_name)) = import_path.rsplit_once('/') else {
92 return Err(EuvError::Message(format!(
93 "import path '{import_path}' does not name a generated bridge, so this build \
94 cannot produce a JavaScript-free page"
95 )));
96 };
97 let js_name: &str = js_name.split(['?', '#']).next().unwrap_or(js_name);
98 let Some(stem) = js_name.strip_suffix(JS_EXTENSION) else {
99 return Err(EuvError::Message(format!(
100 "import path '{import_path}' does not name a JavaScript bridge, so this build \
101 cannot produce a JavaScript-free page"
102 )));
103 };
104 let pkg_dir: PathBuf = config.get_serving_root().join(relative_dir);
105 let wasm_url: String = format!("{relative_dir}/{stem}{WASM_FILE_SUFFIX}");
106 Ok((pkg_dir, wasm_url))
107}
108
109pub(crate) fn normalize_bootstrap(template: &str) -> Result<String, EuvError> {
131 let script_tag: String = format!("<script>{INLINE_JS_PLACEHOLDER}</script>");
132 let template: String = replace_module_bootstrap(template, &script_tag);
133 if template.contains(IMPORT_PATH_PLACEHOLDER) {
134 return Err(EuvError::Message(String::from(
135 "the index.html template still carries __IMPORT_PATH__ outside a bootstrap \
136 script; replace it with __EUV_INLINE_JS__",
137 )));
138 }
139 match template.matches(INLINE_JS_PLACEHOLDER).count() {
140 1 => return Ok(template),
141 0 => {}
142 _ => {
143 return Err(EuvError::Message(String::from(
144 "the index.html template must contain exactly one WASM bootstrap",
145 )));
146 }
147 }
148 let body_close: usize = template.rfind("</body>").ok_or_else(|| {
149 EuvError::Message(String::from(
150 "the index.html template has no __EUV_INLINE_JS__ placeholder and no </body> to \
151 inject one before; add the placeholder so the page boots its WASM module",
152 ))
153 })?;
154 let mut out: String = String::with_capacity(template.len() + script_tag.len());
155 out.push_str(&template[..body_close]);
156 out.push_str(&script_tag);
157 out.push('\n');
158 out.push_str(&template[body_close..]);
159 Ok(out)
160}
161
162fn replace_module_bootstrap(template: &str, replacement: &str) -> String {
173 let lowered: String = template.to_ascii_lowercase();
174 let mut out: String = String::with_capacity(template.len());
175 let mut cursor: usize = 0;
176 while let Some(open_offset) = lowered[cursor..].find("<script") {
177 let open: usize = cursor + open_offset;
178 let Some(open_end) = lowered[open..].find('>').map(|end: usize| open + end + 1) else {
179 break;
180 };
181 let tag: &str = &template[open..open_end];
182 let tag_end: Option<usize> = lowered[open_end..]
183 .find("</script")
184 .map(|end: usize| open_end + end);
185 let Some(close_end) = tag_end
186 .and_then(|close: usize| lowered[close..].find('>').map(|end: usize| close + end + 1))
187 else {
188 break;
189 };
190 let body: &str = &template[open_end..tag_end.unwrap_or(close_end)];
191 out.push_str(&template[cursor..open]);
192 if body.contains(IMPORT_PATH_PLACEHOLDER) && !tag.contains("src=") && !tag.contains("src =")
193 {
194 out.push_str(replacement);
195 } else {
196 out.push_str(&template[open..close_end]);
197 }
198 cursor = close_end;
199 }
200 out.push_str(&template[cursor..]);
201 out
202}
203
204pub(crate) async fn generate_html(config: &HtmlConfig) -> Result<String, EuvError> {
230 let template_content: String = if let Some(custom_path) = config.try_get_custom_index_html() {
231 let bytes: Vec<u8> =
232 read(custom_path)
233 .await
234 .map_err(|error: io::Error| EuvError::IoPath {
235 message: ERROR_READ_CUSTOM_INDEX_HTML.to_string(),
236 path: custom_path.to_path_buf(),
237 error,
238 })?;
239 String::from_utf8(bytes).map_err(|error: FromUtf8Error| EuvError::Utf8 {
240 message: ERROR_CUSTOM_INDEX_HTML_NOT_UTF8.to_string(),
241 error,
242 })?
243 } else if config.get_is_release() {
244 INDEX_HTML_RELEASE.to_string()
245 } else {
246 INDEX_HTML_DEV.to_string()
247 };
248 let inline_js: String = resolve_inline_js(config).await?;
249 let template_content: String = normalize_bootstrap(&template_content)?;
250 let base_href_tag: String = if let Some(prefix) = config.try_get_serving_route_prefix() {
251 let path: String = format!("/{prefix}");
252 format!("<base href=\"{}/\" />", path.trim_end_matches('/'))
253 } else {
254 String::new()
255 };
256 let html: String = template_content
257 .replace(BASE_HREF_PLACEHOLDER, &base_href_tag)
258 .replace(RELOAD_ROUTE_PLACEHOLDER, RELOAD_ROUTE)
259 .replace(INLINE_JS_PLACEHOLDER, &inline_js)
260 .replace(LOADING_STYLE_PLACEHOLDER, LOADING_STYLE)
261 .replace(LOADING_ELEMENT_PLACEHOLDER, LOADING_ELEMENT)
262 .replace(LOADING_REMOVAL_PLACEHOLDER, LOADING_REMOVAL_SCRIPT);
263 let index_path: PathBuf = config.get_serving_root().join(INDEX_HTML_FILE_NAME);
264 create_dir_all(config.get_serving_root())
265 .await
266 .map_err(|error: io::Error| EuvError::Io {
267 message: ERROR_CREATE_STATIC_DIRECTORY.to_string(),
268 error,
269 })?;
270 write(&index_path, &html)
271 .await
272 .map_err(|error: io::Error| EuvError::Io {
273 message: ERROR_WRITE_INDEX_HTML.to_string(),
274 error,
275 })?;
276 Ok(html)
277}
278
279pub async fn resolve_www_dir(www_dir: &Path) -> PathBuf {
289 if metadata(www_dir.join(INDEX_HTML_FILE_NAME)).await.is_ok() {
290 return www_dir.to_path_buf();
291 }
292 let parent_name: Option<&str> = www_dir
293 .file_name()
294 .and_then(|file_name_os_str: &ffi::OsStr| file_name_os_str.to_str());
295 if let Some(name) = parent_name {
296 let nested: PathBuf = www_dir.join(name);
297 if metadata(nested.join(INDEX_HTML_FILE_NAME)).await.is_ok() {
298 return nested;
299 }
300 }
301 www_dir.to_path_buf()
302}
303
304pub fn resolve_pkg_dir(args: &ModeArgs) -> PathBuf {
317 resolve_out_dir(args)
318}
319
320pub async fn resolve_file_in_base(base: &Path, path: &str) -> Option<PathBuf> {
334 let file_path: PathBuf = base.join(path);
335 let canonical_path: PathBuf = canonicalize(&file_path).await.ok()?;
336 let base_canonical: PathBuf = canonicalize(base).await.ok()?;
337 canonical_path
338 .starts_with(&base_canonical)
339 .then_some(file_path)
340}