Skip to main content

euv_cli/hot/
fn.rs

1use super::*;
2
3/// Builds a complete static documentation site from all `.md` files beneath `src_dir` into `out_dir`.
4///
5/// # Arguments
6///
7/// - `&Path` - Project or Markdown source root directory.
8/// - `&Path` - Destination output directory.
9/// - `&DocsBuildOptions` - Site title, base URL, clean URL, asset copy, and optional dev HMR configuration.
10///
11/// # Returns
12///
13/// - `io::Result<GeneratedSiteReport>` - Summary report of generated pages or I/O error.
14pub fn build_docs_site(
15    src_dir: &Path,
16    out_dir: &Path,
17    options: &DocsBuildOptions,
18) -> io::Result<GeneratedSiteReport> {
19    build_docs_bundle(src_dir, out_dir, options)
20}
21
22/// Compiles a fresh signed Dynamic WASM OTA hot-update bundle for version `version`.
23///
24/// # Arguments
25///
26/// - `u64` - Monotonic OTA bundle version number.
27/// - `&str` - Human-readable title embedded into the executable `.wasm` module.
28/// - `Vec<String>` - Source file paths triggering this hot update.
29///
30/// # Returns
31///
32/// - `OtaBundleState` - Signed manifest and executable `.wasm` bytes.
33#[must_use]
34pub fn build_dev_ota_state(
35    version: u64,
36    title: &str,
37    changed_files: Vec<String>,
38) -> OtaBundleState {
39    let accent_hex: u32 = if version.is_multiple_of(2) {
40        0x2563EB
41    } else {
42        0x059669
43    };
44    let wasm_bytes: Vec<u8> = build_partial_widget_wasm(title, version, accent_hex);
45    let checksum: u64 = compute_wasm_checksum(&wasm_bytes);
46    let signature: String = compute_wasm_signature(&wasm_bytes, version, OTA_DEV_SIGNING_KEY);
47    let manifest: OtaManifest = OtaManifest::new(
48        version,
49        OTA_SLOT_DEV.to_string(),
50        OTA_MODULE_ENDPOINT.to_string(),
51        checksum,
52        signature,
53        wasm_bytes.len(),
54        changed_files,
55    );
56    OtaBundleState::new(manifest, wasm_bytes)
57}
58
59/// Injects the dev-only SSE hot-reload script right before `</body>` in an HTML document.
60///
61/// # Arguments
62///
63/// - `&str` - Original HTML source string.
64/// - `&str` - SSE HMR endpoint URL path.
65///
66/// # Returns
67///
68/// - `String` - HTML document containing the live-reload client snippet.
69#[must_use]
70pub fn inject_dev_hmr_into_html(html: &str, hmr_endpoint: &str) -> String {
71    if html.contains(hmr_endpoint) {
72        return html.to_string();
73    }
74    let snippet: String = format!("{DEV_HMR_SCRIPT_PREFIX}{hmr_endpoint}{DEV_HMR_SCRIPT_SUFFIX}");
75    if let Some(pos) = html.rfind(HTML_BODY_CLOSE_TAG) {
76        let mut out: String = String::with_capacity(html.len() + snippet.len());
77        out.push_str(&html[..pos]);
78        out.push_str(&snippet);
79        out.push_str(&html[pos..]);
80        out
81    } else {
82        format!("{html}{snippet}")
83    }
84}
85
86/// Starts a live HTTP, SSE hot-reload, file-watcher, and Dynamic WASM OTA dev server in background threads.
87///
88/// # Arguments
89///
90/// - `DevServerConfig` - Full dev server configuration.
91///
92/// # Returns
93///
94/// - `io::Result<DevServerHandle>` - Running server handle or startup error.
95pub fn start_dev_server(config: DevServerConfig) -> io::Result<DevServerHandle> {
96    if config.get_target() != DevTargetArg::Native {
97        fs::create_dir_all(config.get_out_dir())?;
98    }
99    let mut initial_pages: usize = 0;
100    let mode_label: String = match config.get_target() {
101        DevTargetArg::Docs => {
102            let docs_opts: DocsBuildOptions = docs_options_for_dev(&config);
103            let report: GeneratedSiteReport =
104                build_docs_site(config.get_src_dir(), config.get_out_dir(), &docs_opts)?;
105            initial_pages = report.get_page_count();
106            MODE_LABEL_DOCS.to_string()
107        }
108        DevTargetArg::Web => {
109            rebuild_web_dev_bundle(&config)?;
110            MODE_LABEL_WEB.to_string()
111        }
112        DevTargetArg::Native => MODE_LABEL_NATIVE.to_string(),
113    };
114    let initial_ota: OtaBundleState = build_dev_ota_state(1, OTA_INITIAL_TITLE, Vec::new());
115    let hub: Arc<HmrHub> = Arc::new(HmrHub::new(initial_ota));
116    let bind_addr: String = format!("{}:{}", config.get_host(), config.get_port());
117    let listener: TcpListener = TcpListener::bind(&bind_addr)?;
118    let address: SocketAddr = listener.local_addr()?;
119    listener.set_nonblocking(true)?;
120    let serve_ctx: HttpServeContext = HttpServeContext {
121        out_dir: config.get_out_dir().clone(),
122        base_url: config.get_base_url().clone(),
123        enable_ota: config.get_enable_ota(),
124        hub: Arc::clone(&hub),
125    };
126    let http_thread: JoinHandle<()> = thread::spawn(move || {
127        run_http_accept_loop(listener, serve_ctx);
128    });
129    let watch_hub: Arc<HmrHub> = Arc::clone(&hub);
130    let watch_cfg: DevServerConfig = config.clone();
131    let dev_url: String = format!("http://{address}");
132    let watch_thread: JoinHandle<()> = thread::spawn(move || {
133        run_watch_rebuild_loop(watch_cfg, dev_url, watch_hub);
134    });
135    Ok(DevServerHandle {
136        address,
137        out_dir: config.get_out_dir().clone(),
138        mode: mode_label,
139        page_count: initial_pages,
140        hub,
141        http_thread: Some(http_thread),
142        watch_thread: Some(watch_thread),
143    })
144}
145
146/// Starts the dev server and either exits immediately (`once=true`) or serves continuously until interrupted.
147///
148/// # Arguments
149///
150/// - `DevServerConfig` - Dev server configuration.
151///
152/// # Returns
153///
154/// - `io::Result<DevServerReport>` - Server startup summary report or I/O error.
155pub fn run_dev_blocking(config: DevServerConfig) -> io::Result<DevServerReport> {
156    let once: bool = config.get_once();
157    let mut handle: DevServerHandle = start_dev_server(config)?;
158    let report: DevServerReport = handle.report();
159    if once {
160        handle.shutdown();
161        return Ok(report);
162    }
163    eprintln!(
164        "[euv-dev] mode={} url={} hmr={} ota={}",
165        report.get_mode(),
166        report.get_url(),
167        report.get_hmr_url(),
168        report.get_ota_manifest_url()
169    );
170    while handle.hub.is_running() {
171        thread::sleep(Duration::from_millis(250));
172    }
173    handle.shutdown();
174    Ok(report)
175}
176
177/// Constructs `DocsBuildOptions` wired for live dev hot reload from a `DevServerConfig`.
178///
179/// # Arguments
180///
181/// - `&DevServerConfig` - Active dev server configuration.
182///
183/// # Returns
184///
185/// - `DocsBuildOptions` - Populated docs build options with dev HMR endpoint.
186fn docs_options_for_dev(config: &DevServerConfig) -> DocsBuildOptions {
187    let mut opts: DocsBuildOptions = DocsBuildOptions::default();
188    opts.set_title(config.try_get_title().clone())
189        .set_base_url(config.get_base_url().clone())
190        .set_hmr_endpoint(Some(HMR_ENDPOINT.to_string()))
191        .set_assets_root(Some(config.get_src_dir().clone()))
192        .set_clean_urls(true);
193    opts
194}
195
196/// Runs the non-blocking HTTP accept loop dispatching static files, SSE `/__euv_hmr`, and OTA endpoints.
197///
198/// # Arguments
199///
200/// - `TcpListener` - Bound non-blocking TCP listener.
201/// - `HttpServeContext` - Output directory, base prefix, OTA gate, and shared HMR hub.
202fn run_http_accept_loop(listener: TcpListener, ctx: HttpServeContext) {
203    while ctx.get_hub().is_running() {
204        match listener.accept() {
205            Ok((stream, _)) => {
206                if !ctx.get_hub().is_running() {
207                    break;
208                }
209                let conn_ctx: HttpServeContext = ctx.clone();
210                drop(thread::spawn(move || {
211                    serve_http_connection(stream, &conn_ctx);
212                }));
213            }
214            Err(err) if err.kind() == ErrorKind::WouldBlock => {
215                thread::sleep(Duration::from_millis(20));
216            }
217            Err(_) => {
218                thread::sleep(Duration::from_millis(50));
219            }
220        }
221    }
222}
223
224/// Runs the recursive file watcher loop rebuilding docs, web bundles, or native binaries on file changes.
225///
226/// # Arguments
227///
228/// - `DevServerConfig` - Active dev server configuration.
229/// - `String` - Base HTTP URL of the active dev server forwarded to native child processes.
230/// - `Arc<HmrHub>` - Shared HMR and OTA hub.
231fn run_watch_rebuild_loop(config: DevServerConfig, dev_url: String, hub: Arc<HmrHub>) {
232    let allowed_exts: &[&str] = match config.get_target() {
233        DevTargetArg::Docs => &WATCH_EXTS_DOCS,
234        DevTargetArg::Web | DevTargetArg::Native => &WATCH_EXTS_CODE,
235    };
236    let exclude_out: Option<&Path> = if config.get_target() == DevTargetArg::Native {
237        None
238    } else {
239        Some(config.get_out_dir().as_path())
240    };
241    let mut prev_snap: WatchSnapshot =
242        WatchSnapshot::scan_excluding(config.get_src_dir(), allowed_exts, exclude_out)
243            .unwrap_or_default();
244    let mut native_child: Option<Child> =
245        if config.get_target() == DevTargetArg::Native && !config.get_once() {
246            spawn_native_app_child(&config, &dev_url).ok()
247        } else {
248            None
249        };
250    let poll_dur: Duration = Duration::from_millis(config.get_poll_ms().clamp(50, 5000));
251    while hub.is_running() {
252        thread::sleep(poll_dur);
253        if !hub.is_running() {
254            break;
255        }
256        let Ok(next_snap) =
257            WatchSnapshot::scan_excluding(config.get_src_dir(), allowed_exts, exclude_out)
258        else {
259            continue;
260        };
261        let changes: FileChangeSet = prev_snap.diff(&next_snap);
262        if changes.is_empty() {
263            continue;
264        }
265        prev_snap = next_snap;
266        let changed_files: Vec<String> = changes.all_paths();
267        match config.get_target() {
268            DevTargetArg::Docs => {
269                let docs_opts: DocsBuildOptions = docs_options_for_dev(&config);
270                match build_docs_site(config.get_src_dir(), config.get_out_dir(), &docs_opts) {
271                    Ok(report) => {
272                        let next_ver: u64 = hub.revision() + 1;
273                        if config.get_enable_ota() {
274                            let ota_title: String = format!(
275                                "Docs Hot Update v{next_ver} ({} pages)",
276                                report.get_page_count()
277                            );
278                            hub.set_ota_state(build_dev_ota_state(
279                                next_ver,
280                                &ota_title,
281                                changed_files.clone(),
282                            ));
283                        }
284                        let _: u64 = hub.publish(
285                            HmrEventKind::Reload,
286                            format!("{MSG_DOCS_REBUILT} ({} pages)", report.get_page_count()),
287                            changed_files,
288                        );
289                    }
290                    Err(err) => {
291                        let _: u64 =
292                            hub.publish(HmrEventKind::BuildError, err.to_string(), changed_files);
293                    }
294                }
295            }
296            DevTargetArg::Web => match rebuild_web_dev_bundle(&config) {
297                Ok(()) => {
298                    let next_ver: u64 = hub.revision() + 1;
299                    if config.get_enable_ota() {
300                        let ota_title: String = format!("Web WASM Hot Update v{next_ver}");
301                        hub.set_ota_state(build_dev_ota_state(
302                            next_ver,
303                            &ota_title,
304                            changed_files.clone(),
305                        ));
306                    }
307                    let _: u64 = hub.publish(
308                        HmrEventKind::Reload,
309                        MSG_WEB_REBUILT.to_string(),
310                        changed_files,
311                    );
312                }
313                Err(err) => {
314                    let _: u64 =
315                        hub.publish(HmrEventKind::BuildError, err.to_string(), changed_files);
316                }
317            },
318            DevTargetArg::Native => {
319                if let Some(mut old_child) = native_child.take() {
320                    drop(old_child.kill());
321                    drop(old_child.wait());
322                }
323                match spawn_native_app_child(&config, &dev_url) {
324                    Ok(child) => {
325                        native_child = Some(child);
326                        let next_ver: u64 = hub.revision() + 1;
327                        if config.get_enable_ota() {
328                            let ota_title: String = format!("Native OTA Hot Update v{next_ver}");
329                            hub.set_ota_state(build_dev_ota_state(
330                                next_ver,
331                                &ota_title,
332                                changed_files.clone(),
333                            ));
334                        }
335                        let _: u64 = hub.publish(
336                            HmrEventKind::OtaUpdate,
337                            MSG_NATIVE_RESTARTED.to_string(),
338                            changed_files,
339                        );
340                    }
341                    Err(err) => {
342                        let _: u64 =
343                            hub.publish(HmrEventKind::BuildError, err.to_string(), changed_files);
344                    }
345                }
346            }
347        }
348    }
349    if let Some(mut child) = native_child.take() {
350        drop(child.kill());
351        drop(child.wait());
352    }
353}
354
355/// Rebuilds the WebAssembly bundle into `config.out_dir` and injects the dev SSE hot-reload script.
356///
357/// # Arguments
358///
359/// - `&DevServerConfig` - Active web dev configuration.
360///
361/// # Returns
362///
363/// - `io::Result<()>` - Build result.
364fn rebuild_web_dev_bundle(config: &DevServerConfig) -> io::Result<()> {
365    let out_dir: &Path = config.get_out_dir();
366    let mut wp_args: Vec<String> = vec![
367        ARG_BUILD.to_string(),
368        ARG_TARGET.to_string(),
369        ARG_TARGET_WEB.to_string(),
370        ARG_OUT_DIR.to_string(),
371        out_dir.display().to_string(),
372    ];
373    if config.get_release() {
374        wp_args.push(ARG_RELEASE.to_string());
375    }
376    let output: Output = Command::new(BIN_WASM_PACK)
377        .args(&wp_args)
378        .current_dir(config.get_src_dir())
379        .output()?;
380    if !output.status.success() {
381        let stderr: String = String::from_utf8_lossy(&output.stderr).into_owned();
382        return Err(Error::other(format!("{ERR_STEP_FAILED}: {stderr}")));
383    }
384    if out_dir.exists() {
385        let index_path: PathBuf = package_zero_js_web_bundle(out_dir, WEB_BUNDLE_TITLE)?;
386        let html: String = fs::read_to_string(&index_path)?;
387        let with_hmr: String = inject_dev_hmr_into_html(&html, HMR_ENDPOINT);
388        fs::write(&index_path, with_hmr)?;
389    }
390    Ok(())
391}
392
393/// Spawns a fresh native `cargo run` child process with live HMR/OTA endpoint env vars.
394///
395/// # Arguments
396///
397/// - `&DevServerConfig` - Active native dev configuration.
398/// - `&str` - Base HTTP URL of the active dev server.
399///
400/// # Returns
401///
402/// - `io::Result<Child>` - Spawned child process handle or error.
403fn spawn_native_app_child(config: &DevServerConfig, dev_url: &str) -> io::Result<Child> {
404    let step: BuildStep = resolve_run_step(
405        TargetArg::Native,
406        config.get_render(),
407        config.get_release(),
408        config.try_get_package().as_deref(),
409    );
410    let mut cmd: Command = Command::new(step.get_program());
411    let _: &mut Command = cmd
412        .args(step.get_args())
413        .current_dir(config.get_src_dir())
414        .stdin(Stdio::null())
415        .env(ENV_DEV_URL, dev_url)
416        .env(ENV_HMR_URL, format!("{dev_url}{HMR_ENDPOINT}"));
417    if config.get_enable_ota() {
418        let _: &mut Command = cmd
419            .env(
420                ENV_OTA_MANIFEST_URL,
421                format!("{dev_url}{OTA_MANIFEST_ENDPOINT}"),
422            )
423            .env(
424                ENV_OTA_MODULE_URL,
425                format!("{dev_url}{OTA_MODULE_ENDPOINT}"),
426            );
427    }
428    cmd.spawn()
429}
430
431/// Handles a single incoming HTTP/1.1 connection for static files, SSE `/__euv_hmr`, or Dynamic WASM OTA.
432///
433/// # Arguments
434///
435/// - `TcpStream` - Connected client socket.
436/// - `&HttpServeContext` - Output directory, base prefix, OTA gate, and shared HMR hub.
437fn serve_http_connection(mut stream: TcpStream, ctx: &HttpServeContext) {
438    drop(stream.set_nonblocking(false));
439    drop(stream.set_read_timeout(Some(Duration::from_secs(3))));
440    let req_line: String = {
441        let mut reader: BufReader<&TcpStream> = BufReader::new(&stream);
442        let mut line: String = String::new();
443        if reader.read_line(&mut line).is_err() || line.is_empty() {
444            return;
445        }
446        let mut header_count: usize = 0;
447        while header_count < 64 {
448            let mut hdr: String = String::new();
449            match reader.read_line(&mut hdr) {
450                Ok(0) => break,
451                Ok(_) if hdr == "\r\n" || hdr == "\n" => break,
452                Ok(_) => header_count += 1,
453                Err(_) => break,
454            }
455        }
456        line
457    };
458    let mut parts: SplitWhitespace<'_> = req_line.split_whitespace();
459    let method: &str = parts.next().unwrap_or("");
460    let raw_target: &str = parts.next().unwrap_or("/");
461    if method.eq_ignore_ascii_case(HTTP_METHOD_OPTIONS) {
462        drop(stream.write_all(HTTP_204_OPTIONS_RESP.as_bytes()));
463        drop(stream.flush());
464        return;
465    }
466    let head_only: bool = method.eq_ignore_ascii_case(HTTP_METHOD_HEAD);
467    let path_only: &str = raw_target.split('?').next().unwrap_or("/");
468    let hub: &Arc<HmrHub> = ctx.get_hub();
469    if path_only == HMR_ENDPOINT {
470        serve_sse_stream(stream, hub);
471        return;
472    }
473    if path_only == OTA_MANIFEST_ENDPOINT {
474        if ctx.get_enable_ota()
475            && let Some(ota) = hub.ota_snapshot()
476            && let Ok(json) = to_string_pretty(ota.get_manifest())
477        {
478            write_http_response(&mut stream, MIME_JSON, json.as_bytes(), head_only);
479            return;
480        }
481        drop(stream.write_all(HTTP_404_RESP.as_bytes()));
482        return;
483    }
484    if path_only == OTA_MODULE_ENDPOINT {
485        if ctx.get_enable_ota()
486            && let Some(ota) = hub.ota_snapshot()
487        {
488            write_http_response(
489                &mut stream,
490                MIME_WASM,
491                ota.get_wasm_bytes().as_slice(),
492                head_only,
493            );
494            return;
495        }
496        drop(stream.write_all(HTTP_404_RESP.as_bytes()));
497        return;
498    }
499    if path_only == DEV_STATUS_ENDPOINT {
500        let payload: String = match hub.current_event() {
501            Some(ev) => to_string_pretty(&ev).unwrap_or_else(|_| EMPTY_JSON_OBJECT.to_string()),
502            None => format!("{{\"revision\":{}}}", hub.revision()),
503        };
504        write_http_response(&mut stream, MIME_JSON, payload.as_bytes(), head_only);
505        return;
506    }
507    let decoded_path: String = percent_decode_path(path_only);
508    let stripped_path: &str = strip_base_prefix(&decoded_path, ctx.get_base_url());
509    if let Some(file_path) = resolve_static_file(ctx.get_out_dir(), stripped_path)
510        && let Ok(bytes) = fs::read(&file_path)
511    {
512        let mime: &str = mime_type_for_path(&file_path);
513        write_http_response(&mut stream, mime, &bytes, head_only);
514        return;
515    }
516    drop(stream.write_all(HTTP_404_RESP.as_bytes()));
517}
518
519/// Streams live Server-Sent Events (`event: reload` / `ota` / `error`) whenever `hub` increments revision.
520///
521/// # Arguments
522///
523/// - `TcpStream` - Long-lived client TCP stream.
524/// - `&Arc<HmrHub>` - Shared HMR hub.
525fn serve_sse_stream(mut stream: TcpStream, hub: &Arc<HmrHub>) {
526    if stream.write_all(HTTP_SSE_HEADERS.as_bytes()).is_err() || stream.flush().is_err() {
527        return;
528    }
529    let mut last_sent_rev: u64 = hub.revision();
530    let mut idle_ticks: u32 = 0;
531    while hub.is_running() {
532        thread::sleep(Duration::from_millis(50));
533        let cur_rev: u64 = hub.revision();
534        if cur_rev != last_sent_rev {
535            last_sent_rev = cur_rev;
536            idle_ticks = 0;
537            if let Some(ev) = hub.current_event() {
538                let ev_name: &str = match ev.get_kind() {
539                    HmrEventKind::Reload => HMR_EVENT_RELOAD,
540                    HmrEventKind::OtaUpdate => HMR_EVENT_OTA,
541                    HmrEventKind::BuildError => HMR_EVENT_ERROR,
542                };
543                let data: String = to_string_pretty(&ev)
544                    .unwrap_or_else(|_| format!("{{\"revision\":{cur_rev}}}"))
545                    .replace('\n', " ");
546                let frame: String = format!("event: {ev_name}\ndata: {data}\n\n");
547                if stream.write_all(frame.as_bytes()).is_err() || stream.flush().is_err() {
548                    return;
549                }
550            }
551        } else {
552            idle_ticks += 1;
553            if idle_ticks >= 100 {
554                idle_ticks = 0;
555                if stream.write_all(SSE_PING_LINE.as_bytes()).is_err() || stream.flush().is_err() {
556                    return;
557                }
558            }
559        }
560    }
561}
562
563/// Writes an HTTP/1.1 200 response with CORS and no-cache headers, omitting the body on `HEAD` requests.
564///
565/// # Arguments
566///
567/// - `&mut TcpStream` - Client socket.
568/// - `&str` - Content-Type header value.
569/// - `&[u8]` - Response payload bytes.
570/// - `bool` - When `true`, writes headers only (`HEAD`).
571fn write_http_response(stream: &mut TcpStream, mime: &str, body: &[u8], head_only: bool) {
572    let header: String = format!(
573        "{HTTP_200_PREFIX}{mime}{HTTP_CORS_HEADERS}{}{HTTP_CONN_CLOSE_SEP}",
574        body.len()
575    );
576    drop(stream.write_all(header.as_bytes()));
577    if !head_only {
578        drop(stream.write_all(body));
579    }
580    drop(stream.flush());
581}
582
583/// Strips a configured `base_url` prefix from an incoming request path when present.
584///
585/// # Arguments
586///
587/// - `&'a str` - Percent-decoded HTTP request path.
588/// - `&str` - Configured base URL prefix (for example `""` or `"/docs"`).
589///
590/// # Returns
591///
592/// - `&'a str` - Relative path rooted at the output directory.
593fn strip_base_prefix<'a>(path: &'a str, base_url: &str) -> &'a str {
594    let normalized: &str = base_url.trim_matches('/');
595    if normalized.is_empty() {
596        return path;
597    }
598    let trimmed: &str = path.trim_start_matches('/');
599    if let Some(rest) = trimmed.strip_prefix(normalized)
600        && (rest.is_empty() || rest.starts_with('/'))
601    {
602        return rest;
603    }
604    path
605}
606
607/// Decodes `%XX` percent-encoded byte sequences in a URL path into UTF-8 text.
608///
609/// # Arguments
610///
611/// - `&str` - Raw URL path component.
612///
613/// # Returns
614///
615/// - `String` - Decoded UTF-8 URL path.
616fn percent_decode_path(input: &str) -> String {
617    if !input.contains('%') {
618        return input.to_string();
619    }
620    let bytes: &[u8] = input.as_bytes();
621    let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
622    let mut i: usize = 0;
623    while i < bytes.len() {
624        if bytes[i] == b'%'
625            && i + 2 < bytes.len()
626            && let (Some(hi), Some(lo)) = (hex_nibble(bytes[i + 1]), hex_nibble(bytes[i + 2]))
627        {
628            out.push((hi << 4) | lo);
629            i += 3;
630            continue;
631        }
632        out.push(bytes[i]);
633        i += 1;
634    }
635    String::from_utf8(out).unwrap_or_else(|_| input.to_string())
636}
637
638/// Converts a single ASCII hexadecimal byte into its 4-bit value.
639///
640/// # Arguments
641///
642/// - `u8` - Candidate ASCII hex byte.
643///
644/// # Returns
645///
646/// - `Option<u8>` - Numeric nibble (`0..=15`) when valid.
647fn hex_nibble(byte: u8) -> Option<u8> {
648    match byte {
649        b'0'..=b'9' => Some(byte - b'0'),
650        b'a'..=b'f' => Some(byte - b'a' + 10),
651        b'A'..=b'F' => Some(byte - b'A' + 10),
652        _ => None,
653    }
654}
655
656/// Resolves an HTTP request path safely within `out_dir` supporting clean URLs and `index.html` fallbacks.
657///
658/// # Arguments
659///
660/// - `&Path` - Served output directory root.
661/// - `&str` - Sanitized URL path component.
662///
663/// # Returns
664///
665/// - `Option<PathBuf>` - Existing file path inside `out_dir`, if found.
666fn resolve_static_file(out_dir: &Path, url_path: &str) -> Option<PathBuf> {
667    let trimmed: &str = url_path.trim_matches('/');
668    let mut safe_rel: PathBuf = PathBuf::new();
669    for seg in trimmed.split('/') {
670        if seg.is_empty() || seg == "." || seg == ".." {
671            continue;
672        }
673        safe_rel.push(seg);
674    }
675    if safe_rel.as_os_str().is_empty() {
676        let root_idx: PathBuf = out_dir.join(INDEX_HTML_NAME);
677        return root_idx.is_file().then_some(root_idx);
678    }
679    let direct: PathBuf = out_dir.join(&safe_rel);
680    if direct.is_file() {
681        return Some(direct);
682    }
683    let clean_idx: PathBuf = direct.join(INDEX_HTML_NAME);
684    if clean_idx.is_file() {
685        return Some(clean_idx);
686    }
687    let html_file: PathBuf = out_dir.join(format!("{}.html", safe_rel.display()));
688    if html_file.is_file() {
689        return Some(html_file);
690    }
691    None
692}
693
694/// Determines the HTTP `Content-Type` header for a static file path by extension.
695///
696/// # Arguments
697///
698/// - `&Path` - File path.
699///
700/// # Returns
701///
702/// - `&'static str` - Appropriate MIME type string.
703#[must_use]
704pub fn mime_type_for_path(path: &Path) -> &'static str {
705    let Some(ext) = path.extension().and_then(|s: &OsStr| s.to_str()) else {
706        return MIME_OCTET;
707    };
708    if ext.eq_ignore_ascii_case(EXT_HTML) {
709        MIME_HTML
710    } else if ext.eq_ignore_ascii_case(EXT_JSON) {
711        MIME_JSON
712    } else if ext.eq_ignore_ascii_case(EXT_XML) {
713        MIME_XML
714    } else if ext.eq_ignore_ascii_case(EXT_CSS) {
715        MIME_CSS
716    } else if ext.eq_ignore_ascii_case(EXT_WASM) {
717        MIME_WASM
718    } else if ext.eq_ignore_ascii_case(EXT_SVG) {
719        MIME_SVG
720    } else if ext.eq_ignore_ascii_case(EXT_PNG) {
721        MIME_PNG
722    } else if ext.eq_ignore_ascii_case(EXT_JPG) || ext.eq_ignore_ascii_case(EXT_JPEG) {
723        MIME_JPEG
724    } else if ext.eq_ignore_ascii_case(EXT_WEBP) {
725        MIME_WEBP
726    } else {
727        MIME_OCTET
728    }
729}
730
731/// Recursively populates `entries` with modification stamps for all watched files under `dir`.
732///
733/// # Arguments
734///
735/// - `&Path` - Current directory to scan.
736/// - `&[&str]` - Allowed lowercase file extensions.
737/// - `Option<&Path>` - Optional canonical output directory excluded from watching.
738/// - `Option<&Path>` - Canonical path of `dir` when `exclude_dir` lies within `dir`.
739/// - `bool` - Whether non-symlink child directories must be tested against `exclude_dir`.
740/// - `&mut BTreeMap<PathBuf, FileStamp>` - Accumulator map.
741///
742/// # Returns
743///
744/// - `io::Result<()>` - Scan result.
745pub(crate) fn scan_dir_stamps(
746    dir: &Path,
747    allowed_exts: &[&str],
748    exclude_dir: Option<&Path>,
749    canon_dir: Option<&Path>,
750    check_real_exclude: bool,
751    entries: &mut BTreeMap<PathBuf, FileStamp>,
752) -> io::Result<()> {
753    for entry_res in fs::read_dir(dir)? {
754        let entry: DirEntry = entry_res?;
755        let path: PathBuf = entry.path();
756        if let Ok(ft) = entry.file_type() {
757            if ft.is_dir() {
758                let file_name: OsString = entry.file_name();
759                let name: Cow<'_, str> = file_name.to_string_lossy();
760                if should_skip_watch_dir(&name) {
761                    continue;
762                }
763                if check_real_exclude && let Some(excluded) = exclude_dir {
764                    if let Some(cur_canon) = canon_dir {
765                        let child_canon: PathBuf = cur_canon.join(&file_name);
766                        if child_canon == excluded || child_canon.starts_with(excluded) {
767                            continue;
768                        }
769                        let recurse_check: bool = excluded.starts_with(&child_canon);
770                        let next_canon: Option<&Path> =
771                            recurse_check.then_some(child_canon.as_path());
772                        scan_dir_stamps(
773                            &path,
774                            allowed_exts,
775                            exclude_dir,
776                            next_canon,
777                            recurse_check,
778                            entries,
779                        )?;
780                        continue;
781                    }
782                    let canon: PathBuf = fs::canonicalize(&path).unwrap_or_else(|_| path.clone());
783                    if canon == excluded || canon.starts_with(excluded) {
784                        continue;
785                    }
786                }
787                scan_dir_stamps(
788                    &path,
789                    allowed_exts,
790                    exclude_dir,
791                    None,
792                    check_real_exclude,
793                    entries,
794                )?;
795                continue;
796            }
797            if ft.is_file() {
798                if has_allowed_extension(&path, allowed_exts)
799                    && let Ok(meta) = entry.metadata()
800                {
801                    let _: Option<FileStamp> = entries.insert(path, stamp_from_metadata(&meta));
802                }
803                continue;
804            }
805        }
806        let Ok(meta) = fs::metadata(&path) else {
807            continue;
808        };
809        if meta.is_dir() {
810            let file_name: OsString = entry.file_name();
811            let name: Cow<'_, str> = file_name.to_string_lossy();
812            if should_skip_watch_dir(&name) {
813                continue;
814            }
815            if let Some(excluded) = exclude_dir {
816                let canon: PathBuf = fs::canonicalize(&path).unwrap_or_else(|_| path.clone());
817                if canon == excluded || canon.starts_with(excluded) {
818                    continue;
819                }
820                let recurse_check: bool = excluded.starts_with(&canon);
821                let next_canon: Option<&Path> = recurse_check.then_some(canon.as_path());
822                scan_dir_stamps(
823                    &path,
824                    allowed_exts,
825                    exclude_dir,
826                    next_canon,
827                    recurse_check,
828                    entries,
829                )?;
830                continue;
831            }
832            scan_dir_stamps(&path, allowed_exts, None, None, false, entries)?;
833        } else if meta.is_file() && has_allowed_extension(&path, allowed_exts) {
834            let _: Option<FileStamp> = entries.insert(path, stamp_from_metadata(&meta));
835        }
836    }
837    Ok(())
838}
839
840/// Returns `true` when directory `name` should be excluded from file watching.
841///
842/// # Arguments
843///
844/// - `&str` - Directory name.
845///
846/// # Returns
847///
848/// - `bool` - Whether the watcher skips this directory.
849fn should_skip_watch_dir(name: &str) -> bool {
850    name.starts_with('.')
851        || WATCH_IGNORED_DIRS
852            .iter()
853            .any(|ignored: &&str| name.eq_ignore_ascii_case(ignored))
854}
855
856/// Returns `true` when `path` has an extension listed in `allowed_exts`.
857///
858/// # Arguments
859///
860/// - `&Path` - Candidate file path.
861/// - `&[&str]` - Allowed lowercase extensions.
862///
863/// # Returns
864///
865/// - `bool` - Whether the file should be watched.
866fn has_allowed_extension(path: &Path, allowed_exts: &[&str]) -> bool {
867    path.extension()
868        .and_then(|s: &OsStr| s.to_str())
869        .is_some_and(|ext: &str| {
870            allowed_exts
871                .iter()
872                .any(|allowed: &&str| ext.eq_ignore_ascii_case(allowed))
873        })
874}
875
876/// Extracts a deterministic `FileStamp` from filesystem `Metadata`.
877///
878/// # Arguments
879///
880/// - `&Metadata` - File metadata.
881///
882/// # Returns
883///
884/// - `FileStamp` - Modification timestamp and byte size pair.
885fn stamp_from_metadata(meta: &Metadata) -> FileStamp {
886    let nanos: u128 = meta
887        .modified()
888        .ok()
889        .and_then(|t: SystemTime| t.duration_since(UNIX_EPOCH).ok())
890        .map(|d: Duration| d.as_nanos())
891        .unwrap_or(0);
892    FileStamp::new(nanos, meta.len())
893}