Skip to main content

euv_cli/build/
fn.rs

1use super::*;
2
3/// Checks whether `wasm_pack_args` already contains a build mode flag.
4///
5/// Returns `true` if any of `--dev`, `--release`, or `--profiling`
6/// is present in the arguments list.
7///
8/// # Arguments
9///
10/// - `&[String]` - The wasm-pack arguments to search.
11///
12/// # Returns
13///
14/// - `bool` - Whether a build mode flag is already present.
15pub fn has_build_mode_flag(wasm_pack_args: &[String]) -> bool {
16    wasm_pack_args
17        .iter()
18        .any(|arg: &String| arg == DEV_FLAG || arg == RELEASE_FLAG || arg == PROFILING_FLAG)
19}
20
21/// Filters out euv-specific arguments from the wasm-pack arguments.
22///
23/// First locates the genuine passthrough arguments by taking everything
24/// after the last `--` separator (or the full list if no `--` is present).
25/// Then removes all known euv-specific flags and their values so that
26/// only wasm-pack-compatible arguments remain.
27///
28/// # Arguments
29///
30/// - `&[String]` - The raw wasm-pack arguments to filter.
31///
32/// # Returns
33///
34/// - `Vec<String>` - The filtered arguments safe for wasm-pack.
35pub fn filter_euv_args(wasm_pack_args: &[String]) -> Vec<String> {
36    let raw_args: &[String] = if let Some(position) = wasm_pack_args
37        .iter()
38        .rposition(|arg: &String| arg == DOUBLE_DASH)
39    {
40        &wasm_pack_args[position + 1..]
41    } else {
42        wasm_pack_args
43    };
44    let mut filtered: Vec<String> = Vec::new();
45    let mut skip_next: bool = false;
46    for arg in raw_args {
47        if skip_next {
48            skip_next = false;
49            continue;
50        }
51        // Compare the flag NAME, not the whole argument: clap accepts both
52        // `--port 3000` and `--port=3000`, and only the first form ever
53        // matched `EUV_ARGS` exactly. Without the split, `--port=3000` was
54        // forwarded to wasm-pack even though `reconcile_args` had already
55        // consumed its value — the same string both used and leaked.
56        let name: &str = arg.split('=').next().unwrap_or(arg.as_str());
57        if EUV_ARGS.contains(&name) {
58            if arg.contains('=') || name == NO_GITIGNORE_ARG {
59                // `--no-gitignore` is a bare boolean: there is no value to
60                // skip, so treating it like `--port 3000` ate whatever
61                // argument followed it.
62                continue;
63            }
64            skip_next = true;
65            continue;
66        }
67        filtered.push(arg.clone());
68    }
69    filtered
70}
71
72/// Reconciles euv-specific arguments that may have been collected into
73/// `wasm_pack_args` (e.g. when placed after `--`) back into the
74/// corresponding `ModeArgs` fields.
75///
76/// Because clap's `trailing_var_arg` collects all unrecognized arguments
77/// into `wasm_pack_args`, any euv flag placed after `--` is not parsed
78/// by clap into its dedicated field. This function scans `wasm_pack_args`
79/// for known euv flags and overwrites the `ModeArgs` fields so that the
80/// rest of the codebase can rely on the typed accessors regardless of
81/// argument order.
82///
83/// # Arguments
84///
85/// - `&mut ModeArgs` - The CLI arguments to reconcile in-place.
86pub fn reconcile_args(args: &mut ModeArgs) {
87    let wasm_pack_args: Vec<String> = args.get_wasm_pack_args().clone();
88    let mut crate_path: Option<PathBuf> = None;
89    let mut port: Option<u16> = None;
90    let mut www_dir: Option<String> = None;
91    let mut index_html: Option<Option<PathBuf>> = None;
92    let mut no_gitignore: Option<bool> = None;
93    let mut dev: Option<bool> = None;
94    let mut release: Option<bool> = None;
95    let mut profiling: Option<bool> = None;
96    let mut iter: Iter<String> = wasm_pack_args.iter();
97    while let Some(arg) = iter.next() {
98        match arg.as_str() {
99            CRATE_PATH_ARG | CRATE_PATH_ARG_SHORT => {
100                if let Some(value) = iter.next() {
101                    crate_path = Some(PathBuf::from(value));
102                }
103            }
104            PORT_ARG | PORT_ARG_SHORT => {
105                if let Some(value) = iter.next()
106                    && let Ok(parsed_port) = value.parse::<u16>()
107                {
108                    port = Some(parsed_port);
109                }
110            }
111            WWW_DIR_ARG => {
112                if let Some(value) = iter.next() {
113                    www_dir = Some(value.clone());
114                }
115            }
116            INDEX_HTML_ARG => {
117                if let Some(value) = iter.next() {
118                    index_html = Some(Some(PathBuf::from(value)));
119                }
120            }
121            NO_GITIGNORE_ARG => {
122                no_gitignore = Some(true);
123            }
124            DEV_FLAG => {
125                dev = Some(true);
126            }
127            RELEASE_FLAG => {
128                release = Some(true);
129            }
130            PROFILING_FLAG => {
131                profiling = Some(true);
132            }
133            other => {
134                if let Some(value) = other.strip_prefix(&format!("{CRATE_PATH_ARG}=")) {
135                    crate_path = Some(PathBuf::from(value));
136                } else if let Some(value) = other.strip_prefix(&format!("{PORT_ARG}=")) {
137                    if let Ok(parsed_port) = value.parse::<u16>() {
138                        port = Some(parsed_port);
139                    }
140                } else if let Some(value) = other.strip_prefix(&format!("{WWW_DIR_ARG}=")) {
141                    www_dir = Some(value.to_string());
142                } else if let Some(value) = other.strip_prefix(&format!("{INDEX_HTML_ARG}=")) {
143                    index_html = Some(Some(PathBuf::from(value)));
144                }
145            }
146        }
147    }
148    if let Some(value) = crate_path {
149        args.set_crate_path(value);
150    }
151    if let Some(value) = port {
152        args.set_port(value);
153    }
154    if let Some(value) = www_dir {
155        args.set_www_dir(value);
156    }
157    if let Some(value) = index_html {
158        args.set_index_html(value);
159    }
160    if let Some(value) = no_gitignore {
161        args.set_no_gitignore(value);
162    }
163    if let Some(value) = dev {
164        args.set_dev(value);
165    }
166    if let Some(value) = release {
167        args.set_release(value);
168    }
169    if let Some(value) = profiling {
170        args.set_profiling(value);
171    }
172}
173
174/// Resolves the build mode from CLI arguments.
175///
176/// First checks the explicit `--dev`, `--release`, and `--profiling` flags on `ModeArgs`.
177/// If none of those are set, inspects `wasm_pack_args` for any build mode flag
178/// that may have been forwarded by the user.
179/// Defaults to `BuildMode::Dev` if no build mode flag is found anywhere.
180///
181/// # Arguments
182///
183/// - `&ModeArgs` - The CLI arguments containing the build mode flags and wasm_pack_args.
184///
185/// # Returns
186///
187/// - `BuildMode` - The resolved build mode.
188pub fn resolve_build_mode(args: &ModeArgs) -> BuildMode {
189    if args.get_profiling() {
190        BuildMode::Profiling
191    } else if args.get_release() {
192        BuildMode::Release
193    } else if args.get_dev() {
194        BuildMode::Dev
195    } else if args
196        .get_wasm_pack_args()
197        .iter()
198        .any(|arg: &String| arg == PROFILING_FLAG)
199    {
200        BuildMode::Profiling
201    } else if args
202        .get_wasm_pack_args()
203        .iter()
204        .any(|arg: &String| arg == RELEASE_FLAG)
205    {
206        BuildMode::Release
207    } else {
208        BuildMode::Dev
209    }
210}
211
212/// Converts a `BuildMode` to the corresponding wasm-pack flag string.
213///
214/// # Arguments
215///
216/// - `BuildMode` - The build mode to convert.
217///
218/// # Returns
219///
220/// - `&'static str` - The wasm-pack command-line flag.
221pub fn build_mode_to_flag(build_mode: BuildMode) -> &'static str {
222    match build_mode {
223        BuildMode::Dev => DEV_FLAG,
224        BuildMode::Release => RELEASE_FLAG,
225        BuildMode::Profiling => PROFILING_FLAG,
226    }
227}
228
229/// Builds a `Gitignore` matcher from the `.gitignore` file at the given root path.
230///
231/// # Arguments
232///
233/// - `&PathBuf` - The root directory where `.gitignore` is located.
234///
235/// # Returns
236///
237/// - `Gitignore` - The compiled gitignore matcher.
238async fn build_gitignore(root: &PathBuf) -> Gitignore {
239    let gitignore_path: PathBuf = root.join(GITIGNORE_FILE_NAME);
240    let mut builder: GitignoreBuilder = GitignoreBuilder::new(root);
241    let gitignore_exists: bool = metadata(&gitignore_path).await.is_ok();
242    if gitignore_exists && let Some(error) = builder.add(&gitignore_path) {
243        log::warn!("Failed to load .gitignore: {error}");
244    }
245    match builder.build() {
246        Ok(gitignore) => {
247            if gitignore_exists {
248                log::info!("Loaded .gitignore to filter file change events");
249            }
250            gitignore
251        }
252        Err(error) => {
253            log::warn!("Failed to build gitignore matcher: {error}");
254            GitignoreBuilder::new(root)
255                .build()
256                .unwrap_or_else(|_error: ignore::Error| Gitignore::empty())
257        }
258    }
259}
260
261/// Extracts the value of `--out-name` from the wasm-pack arguments.
262///
263/// Returns `None` if `--out-name` is not specified.
264///
265/// # Arguments
266///
267/// - `&[String]` - The wasm-pack arguments to search.
268///
269/// # Returns
270///
271/// - `Option<String>` - The value of `--out-name` if found.
272fn extract_out_name(wasm_pack_args: &[String]) -> Option<String> {
273    let mut iter: Iter<'_, String> = wasm_pack_args.iter();
274    while let Some(arg) = iter.next() {
275        if arg == OUT_NAME_ARG {
276            return iter.next().cloned();
277        }
278        if let Some(value) = arg.strip_prefix(&format!("{OUT_NAME_ARG}=")) {
279            return Some(value.to_string());
280        }
281    }
282    None
283}
284
285/// Extracts the value of `--out-dir` from the wasm-pack arguments.
286///
287/// Returns `None` if `--out-dir` is not specified.
288///
289/// # Arguments
290///
291/// - `&[String]` - The wasm-pack arguments to search.
292///
293/// # Returns
294///
295/// - `Option<String>` - The value of `--out-dir` if found.
296fn extract_out_dir(wasm_pack_args: &[String]) -> Option<String> {
297    let mut iter: Iter<'_, String> = wasm_pack_args.iter();
298    while let Some(arg) = iter.next() {
299        if arg == OUT_DIR_ARG {
300            return iter.next().cloned();
301        }
302        if let Some(value) = arg.strip_prefix(&format!("{OUT_DIR_ARG}=")) {
303            return Some(value.to_string());
304        }
305    }
306    None
307}
308
309/// Resolves the output JS filename for HTML generation.
310///
311/// Uses `--out-name` from wasm-pack args if specified,
312/// otherwise reads the crate name from `Cargo.toml` `[package] name` field
313/// and replaces hyphens with underscores (matching wasm-pack behavior).
314/// Appends `.js` extension to form the complete JS filename.
315///
316/// # Arguments
317///
318/// - `&ModeArgs` - The CLI arguments containing crate_path and wasm_pack_args.
319///
320/// # Returns
321///
322/// - `String` - The resolved JS filename with `.js` extension (e.g. `euv_example.js`).
323pub fn resolve_out_name(args: &ModeArgs) -> String {
324    let name: String = if let Some(out_name) = extract_out_name(args.get_wasm_pack_args()) {
325        out_name.replace(STR_HYPHEN, STR_UNDERSCORE)
326    } else {
327        let cargo_toml_path: PathBuf = args.get_crate_path().join(CARGO_TOML_FILE_NAME);
328        read_crate_name_from_toml(&cargo_toml_path)
329            .unwrap_or_else(|| {
330                args.get_crate_path()
331                    .file_name()
332                    .unwrap_or_default()
333                    .to_string_lossy()
334                    .to_string()
335            })
336            .replace(STR_HYPHEN, STR_UNDERSCORE)
337    };
338    format!("{name}{JS_EXTENSION}")
339}
340
341/// Reads the `name` field from a Cargo.toml file.
342///
343/// Parses the file line-by-line looking for `name = "..."` within the `[package]` section.
344///
345/// # Arguments
346///
347/// - `&Path` - The path to the Cargo.toml file.
348///
349/// # Returns
350///
351/// - `Option<String>` - The crate name if found.
352fn read_crate_name_from_toml(path: &Path) -> Option<String> {
353    let content: String = sync_read_to_string(path).ok()?;
354    let mut in_package: bool = false;
355    for line in content.lines() {
356        let trimmed: &str = line.trim();
357        if trimmed.starts_with('[') {
358            in_package = trimmed == "[package]";
359            continue;
360        }
361        if in_package
362            && trimmed.starts_with("name")
363            && let Some(value) = trimmed.strip_prefix("name")
364        {
365            let value: &str = value.trim().strip_prefix('=')?.trim();
366            let value: &str = value.strip_prefix('"')?.strip_suffix('"')?;
367            return Some(value.to_string());
368        }
369    }
370    None
371}
372
373/// Computes the relative path from a base directory to a target directory.
374///
375/// Compares the component sequences of both paths to find the common prefix,
376/// then emits `..` for each remaining base component followed by the remaining
377/// target components.
378///
379/// # Arguments
380///
381/// - `&Path` - The base directory path.
382///
383/// # Returns
384///
385/// - `PathBuf` - The relative path from base to target.
386fn compute_relative_path(base: &Path, target: &Path) -> PathBuf {
387    let base_components: Vec<Component> = base.components().collect();
388    let target_components: Vec<Component> = target.components().collect();
389    let common_len: usize = base_components
390        .iter()
391        .zip(target_components.iter())
392        .take_while(
393            |(base_component, target_component): &(&Component, &Component)| {
394                base_component == target_component
395            },
396        )
397        .count();
398    let mut result: PathBuf = PathBuf::new();
399    for _ in &base_components[common_len..] {
400        result.push("..");
401    }
402    for component in &target_components[common_len..] {
403        if let Component::Normal(os_str) = component {
404            result.push(os_str);
405        }
406    }
407    result
408}
409
410/// Resolves the serving root directory for the development server.
411///
412/// When the output directory is inside the www directory, returns the resolved www directory.
413/// When the output directory is outside the www directory, returns the parent of the output directory
414/// so that `index.html` and WASM artifacts are co-located under the same serving root.
415///
416/// # Arguments
417///
418/// - `&ModeArgs` - The CLI arguments containing crate_path, www_dir, wasm_pack_args.
419///
420/// # Returns
421///
422/// - `PathBuf` - The resolved serving root directory.
423pub async fn resolve_serving_root(args: &ModeArgs) -> PathBuf {
424    let www_absolute: PathBuf = args.get_crate_path().join(args.get_www_dir());
425    let out_dir_absolute: PathBuf = resolve_out_dir(args);
426    if out_dir_absolute.strip_prefix(&www_absolute).is_ok() {
427        resolve_www_dir(&www_absolute).await
428    } else {
429        out_dir_absolute
430            .parent()
431            .map(|p: &Path| p.to_path_buf())
432            .unwrap_or_else(|| www_absolute)
433    }
434}
435
436/// Resolves the serving route prefix relative to the crate path.
437///
438/// Returns the forward-slash-separated path of the serving root relative to the crate path.
439/// Used for server route registration and URL display.
440///
441/// # Arguments
442///
443/// - `&ModeArgs` - The CLI arguments containing crate_path, www_dir, wasm_pack_args.
444///
445/// # Returns
446///
447/// - `String` - The serving route prefix (e.g. `www` or `wwws`).
448pub fn resolve_serving_route_prefix(args: &ModeArgs) -> String {
449    let www_absolute: PathBuf = args.get_crate_path().join(args.get_www_dir());
450    let out_dir_absolute: PathBuf = resolve_out_dir(args);
451    let serving_root: PathBuf = if out_dir_absolute.strip_prefix(&www_absolute).is_ok() {
452        www_absolute
453    } else {
454        out_dir_absolute
455            .parent()
456            .map(|p: &Path| p.to_path_buf())
457            .unwrap_or_else(|| www_absolute)
458    };
459    serving_root
460        .strip_prefix(args.get_crate_path())
461        .map(|rel: &Path| {
462            rel.to_string_lossy()
463                .replace(CHAR_SLASH_BACK, STR_SLASH_FORWARD)
464        })
465        .unwrap_or_else(|_| {
466            serving_root
467                .file_name()
468                .and_then(|name: &ffi::OsStr| name.to_str())
469                .unwrap_or_default()
470                .to_string()
471        })
472}
473
474/// Resolves the JS import path for HTML generation.
475///
476/// Computes the relative path from the serving root to the output directory,
477/// then appends the JS filename (from `resolve_out_name`, which includes `.js`)
478/// to form the full import path (e.g. `./pkg/euv.js` or `./pksg/cc.js`).
479///
480/// # Arguments
481///
482/// - `&ModeArgs` - The CLI arguments containing crate_path, www_dir, wasm_pack_args.
483///
484/// # Returns
485///
486/// - `String` - The resolved JS import path relative to the serving root.
487pub fn resolve_import_path(args: &ModeArgs) -> String {
488    let out_name: String = resolve_out_name(args);
489    let www_absolute: PathBuf = args.get_crate_path().join(args.get_www_dir());
490    let out_dir_absolute: PathBuf = resolve_out_dir(args);
491    let serving_root: PathBuf = if out_dir_absolute.strip_prefix(&www_absolute).is_ok() {
492        www_absolute
493    } else {
494        out_dir_absolute
495            .parent()
496            .map(|p: &Path| p.to_path_buf())
497            .unwrap_or_else(|| www_absolute)
498    };
499    let relative: PathBuf = compute_relative_path(&serving_root, &out_dir_absolute);
500    let mut components: Vec<String> = relative
501        .components()
502        .filter_map(|component: Component| match component {
503            Component::Normal(os_str) => os_str.to_str().map(|text: &str| text.to_string()),
504            Component::ParentDir => Some(PARENT_DIR.to_string()),
505            _ => None,
506        })
507        .collect();
508    components.push(out_name);
509    format!("{RELATIVE_PATH_PREFIX}{}", components.join(PATH_SEPARATOR))
510}
511
512/// Resolves the output directory for wasm-pack artifacts.
513///
514/// Uses `--out-dir` from wasm-pack args if specified,
515/// otherwise defaults to `{www_dir}/pkg` so that build artifacts
516/// are placed directly inside the www directory served
517/// by the development server.
518///
519/// # Arguments
520///
521/// - `&ModeArgs` - The CLI arguments containing crate_path, www_dir, and wasm_pack_args.
522///
523/// # Returns
524///
525/// - `PathBuf` - The resolved output directory (absolute if crate_path is joined).
526pub fn resolve_out_dir(args: &ModeArgs) -> PathBuf {
527    let out_dir_path: PathBuf = PathBuf::from(
528        extract_out_dir(args.get_wasm_pack_args())
529            .unwrap_or_else(|| format!("{}/{PKG_DIR_NAME}", args.get_www_dir())),
530    );
531    if out_dir_path.is_absolute() {
532        out_dir_path
533    } else {
534        args.get_crate_path().join(&out_dir_path)
535    }
536}
537
538/// Formats euv macros, builds WASM, writes HTML, then removes generated glue.
539///
540/// The generated `.js`, `.d.ts`, `.js.map` and `snippets/` files are removed
541/// only after the HTML carrying their inlined bootstrap has been written, so a
542/// failed build leaves its artifacts on disk for diagnosis rather than deleting
543/// the evidence and reporting success.
544///
545/// # Arguments
546///
547/// - `&ModeArgs` - The CLI arguments.
548///
549/// # Returns
550///
551/// - `Result<(), EuvError>` - Indicates success or failure of the build.
552pub async fn run_build_only_pipeline(args: &ModeArgs) -> Result<(), EuvError> {
553    let src_path: PathBuf = args.get_crate_path().join(SRC_DIR_NAME);
554    if let Err(error) = format_dir(&src_path, FmtMode::Write).await {
555        log::warn!("euv fmt error: {error}");
556    }
557    build_wasm(args).await?;
558    log::info!("WASM build completed successfully");
559    finalize_html_output(args, false).await?;
560    Ok(())
561}
562
563/// Writes the page and removes the JavaScript it inlined, in that order.
564///
565/// Every failure propagates: a build that cannot inline its bridge, cannot
566/// write its page, or cannot delete the JavaScript it just inlined reports the
567/// failure rather than shipping a page that imports a deleted file.
568///
569/// # Arguments
570///
571/// - `&ModeArgs` - The CLI arguments.
572/// - `bool` - Whether the page is being generated for the dev server, which
573///   injects a `<base href>` tag.
574///
575/// # Returns
576///
577/// - `Result<String, EuvError>` - The generated HTML.
578pub(crate) async fn finalize_html_output(
579    args: &ModeArgs,
580    is_dev_server: bool,
581) -> Result<String, EuvError> {
582    let html_config: HtmlConfig = HtmlConfig::new(
583        resolve_serving_root(args).await,
584        resolve_import_path(args),
585        resolve_build_mode(args) == BuildMode::Release,
586        args.try_get_index_html().clone(),
587        is_dev_server.then(|| resolve_serving_route_prefix(args)),
588    );
589    let html: String = generate_html(&html_config).await?;
590    let pkg_dir: PathBuf = resolve_out_dir(args);
591    let removed: Vec<PathBuf> = remove_generated_js(&pkg_dir).await?;
592    if !removed.is_empty() {
593        log::info!(
594            "Inlined {} generated JavaScript file(s) into {} and removed them from {}",
595            removed.len(),
596            INDEX_HTML_FILE_NAME,
597            pkg_dir.display()
598        );
599    }
600    assert_no_js_artifacts(&pkg_dir).await?;
601    Ok(html)
602}
603
604/// Fails when the wasm-pack output directory still holds a JavaScript file
605/// this build is responsible for.
606///
607/// Catches the case where a delete silently missed a file: the page would
608/// still boot, but the deployed tree would carry the glue the build just
609/// claimed to have removed.
610///
611/// # Arguments
612///
613/// - `&Path` - The wasm-pack output directory.
614///
615/// # Returns
616///
617/// - `Result<(), EuvError>` - `Ok` when no generated JavaScript remains.
618async fn assert_no_js_artifacts(pkg_dir: &Path) -> Result<(), EuvError> {
619    let mut pending: Vec<PathBuf> = vec![pkg_dir.to_path_buf()];
620    while let Some(dir) = pending.pop() {
621        let mut entries: ReadDir =
622            read_dir(&dir)
623                .await
624                .map_err(|error: io::Error| EuvError::IoPath {
625                    message: String::from("Failed to inspect finalized WASM output"),
626                    path: dir.clone(),
627                    error,
628                })?;
629        while let Some(entry) =
630            entries
631                .next_entry()
632                .await
633                .map_err(|error: io::Error| EuvError::IoPath {
634                    message: String::from("Failed to inspect an entry of finalized WASM output"),
635                    path: dir.clone(),
636                    error,
637                })?
638        {
639            let path: PathBuf = entry.path();
640            let file_type: FileType =
641                entry
642                    .file_type()
643                    .await
644                    .map_err(|error: io::Error| EuvError::IoPath {
645                        message: String::from("Failed to inspect a finalized WASM output file"),
646                        path: path.clone(),
647                        error,
648                    })?;
649            if file_type.is_dir() {
650                pending.push(path);
651                continue;
652            }
653            if is_generated_js_artifact(&path) {
654                return Err(EuvError::Message(format!(
655                    "{} survived the cleanup, so this build would deploy JavaScript; \
656                     the page no longer imports it, and it cannot be served",
657                    path.display()
658                )));
659            }
660        }
661    }
662    Ok(())
663}
664
665/// Cleans the output directory before a fresh build.
666///
667/// Removes all files and subdirectories within the output directory
668/// so that stale artifacts from previous builds do not remain.
669/// The directory itself is preserved (recreated if missing).
670///
671/// # Arguments
672///
673/// - `&Path` - The output directory to clean.
674pub async fn clean_out_dir(out_dir: &Path) {
675    let mut entries: ReadDir = match read_dir(out_dir).await {
676        Ok(dir) => dir,
677        Err(_) => return,
678    };
679    while let Ok(Some(entry)) = entries.next_entry().await {
680        let path: PathBuf = entry.path();
681        if path.is_dir() {
682            if let Err(error) = remove_dir_all(&path).await {
683                log::warn!("Failed to remove directory '{}': {error}", path.display());
684            }
685        } else if let Err(error) = remove_file(&path).await {
686            log::warn!("Failed to remove file '{}': {error}", path.display());
687        }
688    }
689}
690
691/// Executes a full build pipeline: euv fmt, build wasm, generate HTML, then
692/// remove the JavaScript that was inlined into it.
693///
694/// Only a pipeline whose wasm build, page write and JavaScript cleanup all
695/// succeeded broadcasts a reload. A failure at any phase notifies the client
696/// of the error and leaves the previous page in memory, so a browser is never
697/// pointed at a page whose inlined bootstrap references a deleted file.
698///
699/// # Arguments
700///
701/// - `&ModeArgs` - The CLI arguments.
702/// - `Option<&broadcast::Sender<ReloadEvent>>` - Optional reload channel for notifying clients.
703///
704/// # Returns
705///
706/// - `Result<String, EuvError>` - The generated HTML with reload script injected on success.
707pub async fn run_build_pipeline(
708    args: &ModeArgs,
709    reload_tx: Option<&broadcast::Sender<ReloadEvent>>,
710) -> Result<String, EuvError> {
711    let src_path: PathBuf = args.get_crate_path().join(SRC_DIR_NAME);
712    if let Err(error) = format_dir(&src_path, FmtMode::Write).await {
713        log::warn!("euv fmt error: {error}");
714    }
715    if let Err(error) = build_wasm(args).await {
716        log::error!("WASM build failed: {error}");
717        notify_reload(reload_tx, Err(error.to_string()));
718        return Err(error);
719    }
720    log::info!("WASM build completed successfully");
721    let html: String = match finalize_html_output(args, true).await {
722        Ok(html) => html,
723        Err(error) => {
724            log::error!("Page generation failed: {error}");
725            notify_reload(reload_tx, Err(error.to_string()));
726            return Err(error);
727        }
728    };
729    notify_reload(reload_tx, Ok(()));
730    Ok(html)
731}
732
733/// Sends one reload event to the dev server's clients.
734///
735/// # Arguments
736///
737/// - `Option<&broadcast::Sender<ReloadEvent>>` - The channel, when the caller has one.
738/// - `Result<(), String>` - `Ok` to ask clients to reload, `Err` to tell them
739///   why the rebuild failed.
740fn notify_reload(reload_tx: Option<&broadcast::Sender<ReloadEvent>>, outcome: Result<(), String>) {
741    let Some(sender) = reload_tx else {
742        return;
743    };
744    let event: ReloadEvent = match outcome {
745        Ok(()) => ReloadEvent::Reload,
746        Err(message) => ReloadEvent::Error(message),
747    };
748    let _: Result<usize, broadcast::error::SendError<ReloadEvent>> = sender.send(event);
749}
750
751/// Watches source files and triggers WASM builds.
752///
753/// # Arguments
754///
755/// - `Arc<AppState>` - The shared application state.
756///
757/// # Returns
758///
759/// - `Result<(), EuvError>` - Indicates success or failure of the file watcher.
760pub(crate) async fn watch_and_build(state: Arc<AppState>) -> Result<(), EuvError> {
761    let crate_path: PathBuf = state.get_args().get_crate_path().clone();
762    let src_path: PathBuf = crate_path.join(SRC_DIR_NAME);
763    let gitignore: Gitignore = build_gitignore(&crate_path).await;
764    let (tx, mut rx): (Sender<Event>, Receiver<Event>) = channel(32);
765    let mut watcher: RecommendedWatcher = RecommendedWatcher::new(
766        move |result: Result<Event, notify::Error>| {
767            if let Ok(event) = result {
768                let _: Result<(), mpsc::error::SendError<Event>> = tx.blocking_send(event);
769            }
770        },
771        Config::default(),
772    )?;
773    watcher.watch(&src_path, RecursiveMode::Recursive)?;
774    log::info!("Watching {} for changes...", src_path.display());
775    let mut debounce: Interval = interval(Duration::from_millis(500));
776    debounce.tick().await;
777    while let Some(event) = rx.recv().await {
778        let filtered_paths: Vec<String> = event
779            .paths
780            .iter()
781            .filter(|path: &&PathBuf| !gitignore.matched(*path, path.is_dir()).is_ignore())
782            .map(|path: &PathBuf| path.display().to_string())
783            .collect();
784        if filtered_paths.is_empty() {
785            continue;
786        }
787        log::warn!("File change detected: {}", filtered_paths.join(", "));
788        debounce.reset();
789        sleep(Duration::from_millis(300)).await;
790        let mut building: RwLockWriteGuard<bool> = state.get_is_building().write().await;
791        if *building {
792            continue;
793        }
794        *building = true;
795        drop(building);
796        let state_for_build: Arc<AppState> = Arc::clone(&state);
797        spawn(async move {
798            let args: ModeArgs = state_for_build.get_args().clone();
799            let reload_tx: broadcast::Sender<ReloadEvent> = state_for_build.get_reload_tx().clone();
800            match run_build_pipeline(&args, Some(&reload_tx)).await {
801                Ok(html) => {
802                    let mut content: RwLockWriteGuard<String> =
803                        state_for_build.get_html_content().write().await;
804                    *content = html;
805                }
806                Err(error) => {
807                    log::error!("Build pipeline error: {error}");
808                }
809            }
810            let mut building: RwLockWriteGuard<bool> =
811                state_for_build.get_is_building().write().await;
812            *building = false;
813        });
814    }
815    Ok(())
816}
817
818/// Constructs the wasm-pack command with generated options before Cargo passthrough.
819///
820/// # Arguments
821///
822/// - `&ModeArgs` - The CLI arguments containing the crate path and forwarded arguments.
823///
824/// # Returns
825///
826/// - `Command` - The configured command preserving the forwarded argument order.
827pub(crate) fn wasm_pack_build_command(args: &ModeArgs) -> Command {
828    let build_mode: BuildMode = resolve_build_mode(args);
829    let build_mode_flag: &str = build_mode_to_flag(build_mode);
830    let filtered_args: Vec<String> = filter_euv_args(args.get_wasm_pack_args());
831    let has_existing_build_mode: bool = has_build_mode_flag(&filtered_args);
832    let default_out_dir: String = format!("{}/{PKG_DIR_NAME}", args.get_www_dir());
833    let mut command: Command = Command::new(WASM_PACK_COMMAND);
834    command.arg(WASM_PACK_BUILD_SUBCOMMAND);
835    command.args(once(build_mode_flag).filter(|_: &&str| !has_existing_build_mode));
836    command.env(RUST_MIN_STACK_ENV, RUST_MIN_STACK_VALUE);
837    let has_out_dir: bool = extract_out_dir(&filtered_args).is_some();
838    if !has_out_dir {
839        command.arg(OUT_DIR_ARG).arg(&default_out_dir);
840    }
841    let has_target: bool = filtered_args
842        .iter()
843        .any(|arg: &String| arg == TARGET_ARG || arg.starts_with(&format!("{TARGET_ARG}=")));
844    if !has_target {
845        command.arg(TARGET_ARG).arg(TARGET_WEB);
846    }
847    command.args(&filtered_args);
848    command.current_dir(args.get_crate_path());
849    command.stdout(Stdio::piped()).stderr(Stdio::piped());
850    command
851}
852
853/// Runs wasm-pack build for the target crate.
854///
855/// All arguments in `args.wasm_pack_args` are transparently forwarded
856/// to `wasm-pack build`. If `--out-dir` is not specified by the user,
857/// `--out-dir {www_dir}/pkg` is automatically injected so that build artifacts
858/// are placed inside the www directory served by the development server.
859///
860/// # Arguments
861///
862/// - `&ModeArgs` - The CLI arguments containing crate_path, www_dir, and wasm_pack_args.
863///
864/// # Returns
865///
866/// - `Result<(), EuvError>` - Indicates success or failure of the wasm-pack build.
867pub async fn build_wasm(args: &ModeArgs) -> Result<(), EuvError> {
868    let mut command: Command = wasm_pack_build_command(args);
869    let display_args: Vec<String> = command
870        .as_std()
871        .get_args()
872        .skip(1)
873        .map(|arg: &OsStr| arg.to_string_lossy().into_owned())
874        .collect();
875    let out_dir_absolute: PathBuf = resolve_out_dir(args);
876    create_dir_all(&out_dir_absolute)
877        .await
878        .map_err(|error: io::Error| EuvError::IoPath {
879            message: String::from("Failed to create output directory"),
880            path: out_dir_absolute.clone(),
881            error,
882        })?;
883    log::info!(
884        "Running: {WASM_PACK_COMMAND} {WASM_PACK_BUILD_SUBCOMMAND} {} ...",
885        display_args.join(" ")
886    );
887    let output: Output = command
888        .output()
889        .await
890        .map_err(|error: io::Error| EuvError::Io {
891            message: String::from("Failed to execute wasm-pack"),
892            error,
893        })?;
894    let stdout: String = String::from_utf8_lossy(&output.stdout).to_string();
895    let stderr: String = String::from_utf8_lossy(&output.stderr).to_string();
896    if args.get_no_gitignore() {
897        let gitignore_path: PathBuf = out_dir_absolute.join(GITIGNORE_FILE_NAME);
898        if gitignore_path.exists()
899            && let Err(error) = remove_file(&gitignore_path).await
900        {
901            log::warn!("Failed to remove '{}': {error}", gitignore_path.display());
902        }
903    }
904    for line in stdout.lines().filter(|line: &&str| !line.is_empty()) {
905        log::info!("{line}");
906    }
907    if output.status.success() {
908        for line in stderr.lines().filter(|line: &&str| !line.is_empty()) {
909            log::info!("{line}");
910        }
911    } else {
912        for line in stderr.lines().filter(|line: &&str| !line.is_empty()) {
913            log::error!("{line}");
914        }
915        return Err(EuvError::Message(String::from("wasm-pack build failed")));
916    }
917    Ok(())
918}
919
920/// Prints the startup banner and command information.
921///
922/// # Arguments
923///
924/// - `Action` - The action to perform (run or build).
925pub fn print_banner(action: Action) {
926    let version: &str = env!("CARGO_PKG_VERSION");
927    if version.is_empty() {
928        log::warn!("Failed to parse version from root Cargo.toml");
929    } else {
930        log::info!("euv v{version}");
931    }
932    let action_name: &str = match action {
933        Action::Run => ACTION_RUN,
934        Action::Build => ACTION_BUILD,
935    };
936    log::info!("Mode: {action_name}");
937    log::info!(
938        "Use .gitignore to filter file change events; pass --no-gitignore to remove .gitignore from output"
939    );
940}
941
942/// Enumerates all network interface IP addresses and prints each server URL
943/// along with its corresponding QR code to the console.
944///
945/// Includes both loopback (127.0.0.1) and all private/public IPv4 addresses
946/// bound to the host's network interfaces. Each address produces one URL line
947/// followed by a Unicode QR code rendered with half-block characters,
948/// where every line carries the standard log prefix (timestamp + level).
949///
950/// # Arguments
951///
952/// - `&ServerUrlConfig` - The server URL configuration.
953pub(crate) fn print_server_urls(config: &ServerUrlConfig) {
954    let port: u16 = config.get_port();
955    let route_prefix: &str = config.get_route_prefix();
956    let index_html_file_name: &str = config.get_index_html_file_name();
957    let mut addresses: Vec<IpAddr> = Vec::new();
958    match if_addrs::get_if_addrs() {
959        Ok(interfaces) => {
960            for interface in interfaces {
961                let ip: IpAddr = interface.addr.ip();
962                if !addresses.contains(&ip) {
963                    addresses.push(ip);
964                }
965            }
966        }
967        Err(error) => {
968            log::warn!("Failed to enumerate network interfaces: {error}");
969        }
970    }
971    if addresses.is_empty() {
972        addresses.push(IpAddr::V4(Ipv4Addr::LOCALHOST));
973    }
974    for ip in addresses {
975        let host: String = match ip {
976            IpAddr::V6(_) => format!("[{ip}]"),
977            IpAddr::V4(_) => format!("{ip}"),
978        };
979        let url: String =
980            format!("{HTTP_SCHEME}://{host}:{port}/{route_prefix}/{index_html_file_name}");
981        log::info!("Server: {url}");
982        match QrCode::new(url.as_str()) {
983            Ok(code) => {
984                let string: String = code.render::<Dense1x2>().quiet_zone(false).build();
985                for line in string.lines() {
986                    log::info!("{line}");
987                }
988            }
989            Err(error) => {
990                log::warn!("Failed to generate QR code: {error}");
991            }
992        }
993    }
994}
995
996/// Reads the wasm-bindgen JS bridge produced by `wasm-pack build
997/// --target web` and returns a self-contained IIFE that inlines the
998/// bridge and every module it imports, fetches the wasm module from
999/// `wasm_url`, then calls `main()` once the instance is ready.
1000///
1001/// The bridge's own top-level `import` lines (the snippet helpers under
1002/// `./snippets/`) are stripped and their bodies inlined, so the result
1003/// makes zero HTTP requests for JavaScript: the page carries the whole
1004/// module graph in one `<script>`.
1005///
1006/// Fails closed. A bridge whose bootstrap this cannot reproduce — one
1007/// whose `__wbg_init` uses `import.meta.url` on a line that carries
1008/// other statements, one that imports a non-relative or named-bound
1009/// module — returns an error naming the construct, never a bootstrap
1010/// that silently fails in the browser.
1011///
1012/// # Arguments
1013///
1014/// - `&Path` - Directory holding the wasm-pack output.
1015/// - `&str` - File name of the generated JS bridge inside it.
1016///
1017/// # Returns
1018///
1019/// - `Result<String, EuvError>` - The IIFE source, or an error naming the
1020///   exact unsupported construct when the bridge cannot be inlined.
1021pub(crate) async fn build_inline_bridge(
1022    pkg_dir: &Path,
1023    js_name: &str,
1024    wasm_url: &str,
1025) -> Result<String, EuvError> {
1026    let js_path: PathBuf = pkg_dir.join(js_name);
1027    let bridge_source: String =
1028        read_to_string(&js_path)
1029            .await
1030            .map_err(|error: io::Error| EuvError::IoPath {
1031                message: String::from("Failed to read wasm-bindgen JS bridge"),
1032                path: js_path.clone(),
1033                error,
1034            })?;
1035    let inlined: String = inline_module_graph(&bridge_source, pkg_dir).await?;
1036    let js_only: String = strip_trailing_module_exports(&inlined);
1037    if !js_only.contains("function main(") {
1038        return Err(EuvError::Message(format!(
1039            "wasm-bindgen bridge '{js_name}' declares no main() for the bootstrap to call"
1040        )));
1041    }
1042    if !js_only.contains("__wbg_get_imports") {
1043        return Err(EuvError::Message(format!(
1044            "wasm-bindgen bridge '{js_name}' declares no __wbg_get_imports() \
1045             for the bootstrap to instantiate the module with"
1046        )));
1047    }
1048    let wasm_url_json: String = encode_js_string(wasm_url);
1049    Ok(format!(
1050        "(function() {{\n\
1051         {js_only}\n\
1052         var __euv_wasm_url = {wasm_url_json};\n\
1053         var __euv_base = (document.querySelector('base[href]') && document.baseURI) || location.href;\n\
1054         var __euv_url = new URL(__euv_wasm_url, __euv_base).toString();\n\
1055         function __euv_main() {{ if (typeof main === 'function') {{ main(); }} }}\n\
1056         if (typeof __wbg_init === 'function') {{\n\
1057         __wbg_init(__euv_url).then(__euv_main).catch(function(e) {{\n\
1058         console.error('[euv] inline bridge init failed:', e);\n\
1059         }});\n\
1060         }} else if (typeof initSync === 'function') {{\n\
1061         fetch(__euv_url).then(function(response) {{ return response.arrayBuffer(); }})\n\
1062         .then(function(bytes) {{ initSync({{ module: bytes }}); __euv_main(); }})\n\
1063         .catch(function(e) {{ console.error('[euv] inline bridge init failed:', e); }});\n\
1064         }} else {{\n\
1065         console.error('[euv] inline bridge: no __wbg_init or initSync to instantiate the module');\n\
1066         }}\n\
1067         }})();\n"
1068    ))
1069}
1070
1071/// Walks the bridge and every module it imports, returning their bodies
1072/// concatenated in dependency order with the bridge's own `import` lines
1073/// and namespace aliases materialised as plain `var` objects.
1074///
1075/// Fails closed: an import clause shape this inliner does not model, a
1076/// specifier that is not relative, a specifier that escapes the package
1077/// directory, a snippet that cannot be read, or a snippet that exports
1078/// nothing a namespace import can bind all produce an error instead of a
1079/// silently truncated bootstrap.
1080///
1081/// # Arguments
1082///
1083/// - `&str` - The bridge source.
1084/// - `&Path` - Directory holding the wasm-pack output.
1085///
1086/// # Returns
1087///
1088/// - `Result<String, EuvError>` - The concatenated module bodies.
1089async fn inline_module_graph(bridge_source: &str, pkg_dir: &Path) -> Result<String, EuvError> {
1090    let mut snippets: Vec<(PathBuf, String)> = Vec::new();
1091    let mut namespace_clauses: Vec<NamespaceImport> = Vec::new();
1092    for line in bridge_source.lines() {
1093        let trimmed: &str = line.trim();
1094        if !trimmed.starts_with("import ") {
1095            continue;
1096        }
1097        let rest: &str = trimmed.strip_prefix("import ").unwrap_or_default();
1098        let clause: ImportClause<'_> = parse_import_clause(rest)?;
1099        if clause.default_binding.is_some() || !clause.named.is_empty() {
1100            return Err(EuvError::Message(format!(
1101                "wasm-bindgen bridge imports a default or named binding from '{}', \
1102                 which a self-contained bootstrap cannot reproduce",
1103                clause.spec
1104            )));
1105        }
1106        if !(clause.spec.starts_with("./") || clause.spec.starts_with("../")) {
1107            return Err(EuvError::Message(format!(
1108                "wasm-bindgen bridge imports the bare module '{}', which a \
1109                 self-contained bootstrap cannot fetch",
1110                clause.spec
1111            )));
1112        }
1113        if let Some(alias) = clause.namespace {
1114            namespace_clauses.push(NamespaceImport {
1115                alias: alias.to_string(),
1116                spec: clause.spec.to_string(),
1117            });
1118        }
1119        let snippet_path: PathBuf = resolve_snippet_path(pkg_dir, clause.spec).await?;
1120        if snippets
1121            .iter()
1122            .any(|(path, _): &(PathBuf, String)| path == &snippet_path)
1123        {
1124            continue;
1125        }
1126        let raw: String = read_to_string(&snippet_path)
1127            .await
1128            .map_err(|error: io::Error| EuvError::IoPath {
1129                message: String::from("Failed to read wasm-pack snippet module"),
1130                path: snippet_path.clone(),
1131                error,
1132            })?;
1133        snippets.push((snippet_path, raw));
1134    }
1135    let mut out: String = String::new();
1136    for (snippet_path, raw) in &snippets {
1137        let body: String = strip_module_exports(raw).map_err(|error: EuvError| match error {
1138            EuvError::Message(message) => EuvError::Message(format!(
1139                "{} in snippet module '{}'",
1140                message,
1141                snippet_path.display()
1142            )),
1143            other => other,
1144        })?;
1145        if body.trim().is_empty() {
1146            return Err(EuvError::Message(format!(
1147                "snippet module '{}' has no inlinable body",
1148                snippet_path.display()
1149            )));
1150        }
1151        out.push_str(&body);
1152        out.push('\n');
1153    }
1154    for clause in &namespace_clauses {
1155        let snippet_path: PathBuf = resolve_snippet_path(pkg_dir, &clause.spec).await?;
1156        let raw: String = snippets
1157            .iter()
1158            .find(|(path, _): &&(PathBuf, String)| *path == snippet_path)
1159            .map(|(_, raw): &(PathBuf, String)| raw.clone())
1160            .unwrap_or_default();
1161        let names: Vec<String> = extract_exported_names(&raw);
1162        if names.is_empty() {
1163            return Err(EuvError::Message(format!(
1164                "snippet module '{}' exports nothing the namespace binding '{}' \
1165                 could reference",
1166                clause.spec, clause.alias
1167            )));
1168        }
1169        out.push_str(&render_namespace_object(&clause.alias, &names));
1170    }
1171    for line in bridge_source.lines() {
1172        let trimmed: &str = line.trim();
1173        if trimmed.starts_with("import ") {
1174            continue;
1175        }
1176        if trimmed.contains(IMPORT_META_URL_MARKER) {
1177            continue;
1178        }
1179        out.push_str(line);
1180        out.push('\n');
1181    }
1182    Ok(out)
1183}
1184
1185/// Parses one `import` clause, rejecting shapes the inliner cannot model.
1186///
1187/// # Arguments
1188///
1189/// - `&str` - The static import clause after the `import` keyword.
1190///
1191/// # Returns
1192///
1193/// - `Result<ImportClause<'_>, EuvError>` - Borrowed bindings and module specifier.
1194pub fn parse_import_clause(rest: &str) -> Result<ImportClause<'_>, EuvError> {
1195    let rest: &str = rest.trim().trim_end_matches(';').trim();
1196    let from_idx: usize = rest.find(" from ").ok_or_else(|| {
1197        EuvError::Message(format!(
1198            "bridge import '{rest}' is not a static `from` clause, which a \
1199             self-contained bootstrap cannot reproduce"
1200        ))
1201    })?;
1202    let head: &str = rest[..from_idx].trim();
1203    let quoted: &str = rest[from_idx + " from ".len()..].trim();
1204    let quote: char = match quoted.chars().next() {
1205        Some(quote @ ('\'' | '"')) => quote,
1206        _ => {
1207            return Err(EuvError::Message(format!(
1208                "bridge import specifier '{quoted}' is not a quoted string"
1209            )));
1210        }
1211    };
1212    let after: &str = &quoted[quote.len_utf8()..];
1213    let spec: &str = after.split(quote).next().unwrap_or_default();
1214    if spec.is_empty() {
1215        return Err(EuvError::Message(format!(
1216            "bridge import '{rest}' names an empty specifier"
1217        )));
1218    }
1219    if head.starts_with('*') {
1220        let alias: &str = head
1221            .strip_prefix('*')
1222            .map(|value: &str| value.trim())
1223            .and_then(|value: &str| value.strip_prefix("as "))
1224            .map(|value: &str| value.trim())
1225            .unwrap_or_default();
1226        if alias.is_empty() {
1227            return Err(EuvError::Message(format!(
1228                "bridge import '{rest}' is a namespace import without a binding"
1229            )));
1230        }
1231        return Ok(ImportClause {
1232            spec,
1233            namespace: Some(alias),
1234            default_binding: None,
1235            named: Vec::new(),
1236        });
1237    }
1238    if let Some(inner) = head.strip_prefix('{') {
1239        let inner: &str = inner.strip_suffix('}').ok_or_else(|| {
1240            EuvError::Message(format!(
1241                "bridge import '{rest}' has an unbalanced `{{` clause"
1242            ))
1243        })?;
1244        return Ok(ImportClause {
1245            spec,
1246            namespace: None,
1247            default_binding: None,
1248            named: inner
1249                .split(',')
1250                .map(|entry: &str| entry.trim())
1251                .filter(|entry: &&str| !entry.is_empty())
1252                .collect(),
1253        });
1254    }
1255    Ok(ImportClause {
1256        spec,
1257        namespace: None,
1258        default_binding: Some(head),
1259        named: Vec::new(),
1260    })
1261}
1262
1263/// Renders the `var <alias> = { a: a, ... };` statement a namespace import
1264/// becomes once the module graph is gone.
1265///
1266/// # Arguments
1267///
1268/// - `&str` - Local namespace binding.
1269/// - `&[String]` - Exported names to expose on the namespace object.
1270///
1271/// # Returns
1272///
1273/// - `String` - The JavaScript namespace declaration.
1274fn render_namespace_object(alias: &str, names: &[String]) -> String {
1275    let mut out: String = format!("var {alias} = {{");
1276    for (index, name) in names.iter().enumerate() {
1277        if index > 0 {
1278            out.push(',');
1279        }
1280        out.push_str(name);
1281        out.push(':');
1282        out.push_str(name);
1283    }
1284    out.push_str("};\n");
1285    out
1286}
1287
1288/// Strips the `export` keyword from a snippet module, turning it into bare
1289/// declarations, and rejects export forms a bare declaration cannot carry.
1290///
1291/// # Arguments
1292///
1293/// - `&str` - The snippet module source.
1294///
1295/// # Returns
1296///
1297/// - `Result<String, EuvError>` - The same source with its `export` keywords
1298///   removed, or an error naming the unsupported export form.
1299fn strip_module_exports(source: &str) -> Result<String, EuvError> {
1300    let mut out: String = String::with_capacity(source.len());
1301    for line in source.lines() {
1302        let trimmed: &str = line.trim();
1303        let Some(rest) = trimmed.strip_prefix("export ") else {
1304            out.push_str(line);
1305            out.push('\n');
1306            continue;
1307        };
1308        match classify_export(rest) {
1309            ExportForm::Aliases(clause) => {
1310                out.push_str(&render_export_aliases(clause)?);
1311            }
1312            ExportForm::Declaration(declaration) => {
1313                out.push_str(declaration);
1314                out.push('\n');
1315            }
1316            ExportForm::Unsupported => {
1317                return Err(EuvError::Message(format!(
1318                    "snippet exports '{rest}', a form a self-contained \
1319                     bootstrap cannot reproduce"
1320                )));
1321            }
1322        }
1323    }
1324    Ok(out)
1325}
1326
1327/// Classifies the text following an `export ` keyword.
1328///
1329/// # Arguments
1330///
1331/// - `&str` - Source immediately after the export keyword.
1332///
1333/// # Returns
1334///
1335/// - `ExportForm<'_>` - A declaration, alias list, or unsupported export.
1336fn classify_export(rest: &str) -> ExportForm<'_> {
1337    let trimmed: &str = rest.trim_end().trim_end_matches(';');
1338    if let Some(inner) = trimmed.strip_prefix('{')
1339        && inner.trim_end().ends_with('}')
1340    {
1341        return ExportForm::Aliases(inner.trim_end().trim_end_matches('}'));
1342    }
1343    if EXPORT_DECLARATION_KEYWORDS
1344        .iter()
1345        .any(|keyword: &&str| trimmed.starts_with(keyword))
1346    {
1347        return ExportForm::Declaration(trimmed);
1348    }
1349    ExportForm::Unsupported
1350}
1351
1352/// Renders an `{ a, b as c }` export clause as the assignments that keep
1353/// each local binding reachable under its exported name.
1354///
1355/// An export of `wasm`, or an alias whose two names match, is dropped:
1356/// the inlined bootstrap is a plain `<script>` with no module namespace
1357/// and no `wasm` binding in scope, and an identity alias needs no
1358/// assignment.
1359///
1360/// # Arguments
1361///
1362/// - `&str` - The clause body between the braces.
1363///
1364/// # Returns
1365///
1366/// - `Result<String, EuvError>` - The assignments, or an error naming a
1367///   non-identifier entry.
1368fn render_export_aliases(clause: &str) -> Result<String, EuvError> {
1369    let mut out: String = String::new();
1370    for entry in clause.split(',') {
1371        let entry: &str = entry.trim();
1372        if entry.is_empty() {
1373            continue;
1374        }
1375        let (original, exported): (&str, &str) = match entry.split_once(" as ") {
1376            Some((original, exported)) => (original.trim(), exported.trim()),
1377            None => (entry, entry),
1378        };
1379        if !is_identifier(original) || !is_identifier(exported) {
1380            return Err(EuvError::Message(format!(
1381                "snippet exports the non-identifier entry '{entry}'"
1382            )));
1383        }
1384        if original == exported || exported == "default" || original == "wasm" {
1385            continue;
1386        }
1387        out.push_str(exported);
1388        out.push_str(" = ");
1389        out.push_str(original);
1390        out.push_str(";\n");
1391    }
1392    Ok(out)
1393}
1394
1395/// Returns `true` when `value` is a bare JavaScript identifier.
1396///
1397/// # Arguments
1398///
1399/// - `&str` - Candidate binding name.
1400///
1401/// # Returns
1402///
1403/// - `bool` - Whether the value contains only supported identifier characters.
1404fn is_identifier(value: &str) -> bool {
1405    !value.is_empty()
1406        && !value.starts_with(|c: char| c.is_ascii_digit())
1407        && value
1408            .chars()
1409            .all(|c: char| c.is_ascii_alphanumeric() || c == '_' || c == '$')
1410}
1411
1412/// Scans a snippet module for every name it exports, so a namespace import
1413/// can be rebuilt as a plain object. `export function`, `export async
1414/// function`, `export class` and `export const|let|var` all count.
1415///
1416/// # Arguments
1417///
1418/// - `&str` - The snippet module source to scan.
1419///
1420/// # Returns
1421///
1422/// - `Vec<String>` - Every exported name, in source order.
1423pub fn extract_exported_names(source: &str) -> Vec<String> {
1424    let mut names: Vec<String> = Vec::new();
1425    for line in source.lines() {
1426        let trimmed: &str = line.trim();
1427        let Some(rest) = trimmed.strip_prefix("export ") else {
1428            continue;
1429        };
1430        let declaration: Option<&str> = EXPORT_DECLARATION_KEYWORDS
1431            .iter()
1432            .find_map(|keyword: &&str| rest.strip_prefix(keyword));
1433        if let Some(name) = declaration.and_then(leading_identifier)
1434            && !names.iter().any(|existing: &String| existing == name)
1435        {
1436            names.push(name.to_string());
1437        }
1438    }
1439    names
1440}
1441
1442/// Returns the leading identifier of `value`, or `None` when it starts with
1443/// something that cannot be one.
1444///
1445/// # Arguments
1446///
1447/// - `&str` - Declaration text starting with the exported name.
1448///
1449/// # Returns
1450///
1451/// - `Option<&str>` - The leading identifier, when present.
1452fn leading_identifier(value: &str) -> Option<&str> {
1453    let end: usize = value
1454        .find(|c: char| !c.is_alphanumeric() && c != '_' && c != '$')
1455        .unwrap_or(value.len());
1456    if end == 0 { None } else { Some(&value[..end]) }
1457}
1458
1459/// Resolves a relative specifier to a path inside `pkg_dir`.
1460///
1461/// # Arguments
1462///
1463/// - `&Path` - Directory holding the wasm-pack output.
1464/// - `&str` - Relative specifier taken from the bridge's import clause.
1465///
1466/// # Returns
1467///
1468/// - `Result<PathBuf, EuvError>` - The resolved path, or an error if the
1469///   specifier climbs above `pkg_dir`.
1470async fn resolve_snippet_path(pkg_dir: &Path, spec: &str) -> Result<PathBuf, EuvError> {
1471    let base: &str = spec.strip_prefix("./").unwrap_or(spec);
1472    let mut path: PathBuf = pkg_dir.to_path_buf();
1473    for segment in base.split('/') {
1474        if segment.is_empty() || segment == "." {
1475            continue;
1476        }
1477        if segment == ".." {
1478            return Err(EuvError::Message(String::from(
1479                "Snippet import spec escapes pkg directory",
1480            )));
1481        }
1482        path.push(segment);
1483    }
1484    let root: PathBuf =
1485        canonicalize(pkg_dir)
1486            .await
1487            .map_err(|error: io::Error| EuvError::IoPath {
1488                message: String::from("Failed to resolve the WASM output directory"),
1489                path: pkg_dir.to_path_buf(),
1490                error,
1491            })?;
1492    let resolved: PathBuf =
1493        canonicalize(&path)
1494            .await
1495            .map_err(|error: io::Error| EuvError::IoPath {
1496                message: String::from("Failed to resolve the imported snippet"),
1497                path: path.clone(),
1498                error,
1499            })?;
1500    if !resolved.starts_with(root) {
1501        return Err(EuvError::Message(format!(
1502            "Snippet import '{spec}' resolves outside the WASM output directory",
1503        )));
1504    }
1505    Ok(resolved)
1506}
1507
1508/// Removes the bridge's trailing `export { ... }` clauses, turning each
1509/// exported alias into the assignment that keeps the local function
1510/// reachable under its exported name, and its `export function` lines into
1511/// plain declarations.
1512///
1513/// # Arguments
1514///
1515/// - `&str` - The bridge source, after its `import` lines were removed.
1516///
1517/// # Returns
1518///
1519/// - `String` - The source with its module-level export syntax removed.
1520fn strip_trailing_module_exports(source: &str) -> String {
1521    let mut out: String = String::with_capacity(source.len());
1522    for line in source.lines() {
1523        let trimmed: &str = line.trim();
1524        let Some(rest) = trimmed.strip_prefix("export ") else {
1525            out.push_str(line);
1526            out.push('\n');
1527            continue;
1528        };
1529        match classify_export(rest) {
1530            ExportForm::Aliases(clause) => {
1531                if let Ok(aliases) = render_export_aliases(clause) {
1532                    out.push_str(&aliases);
1533                }
1534            }
1535            ExportForm::Declaration(declaration) => {
1536                out.push_str(declaration);
1537                out.push('\n');
1538            }
1539            ExportForm::Unsupported => {
1540                out.push_str(line);
1541                out.push('\n');
1542            }
1543        }
1544    }
1545    out
1546}
1547
1548/// Encodes a value as a JavaScript string literal, including the
1549/// surrounding quotes, escaping every character that would otherwise end
1550/// the literal, open a new line inside it, or close the enclosing
1551/// `<script>` element early.
1552///
1553/// # Arguments
1554///
1555/// - `&str` - The value to encode.
1556///
1557/// # Returns
1558///
1559/// - `String` - A quoted, escaped JavaScript string.
1560pub(crate) fn encode_js_string(value: &str) -> String {
1561    let mut out: String = String::with_capacity(value.len() + 2);
1562    out.push('"');
1563    for ch in value.chars() {
1564        match ch {
1565            '"' => out.push_str("\\\""),
1566            '\\' => out.push_str("\\\\"),
1567            '\n' => out.push_str("\\n"),
1568            '\r' => out.push_str("\\r"),
1569            '\t' => out.push_str("\\t"),
1570            '\u{08}' => out.push_str("\\b"),
1571            '\u{0C}' => out.push_str("\\f"),
1572            '<' => out.push_str("\\u003c"),
1573            '>' => out.push_str("\\u003e"),
1574            '&' => out.push_str("\\u0026"),
1575            '\u{2028}' => out.push_str("\\u2028"),
1576            '\u{2029}' => out.push_str("\\u2029"),
1577            c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
1578            c => out.push(c),
1579        }
1580    }
1581    out.push('"');
1582    out
1583}
1584
1585/// Deletes every JavaScript artifact wasm-pack emitted for this build:
1586/// the bridge itself, its `.d.ts` declarations, its source maps and the
1587/// `snippets/` modules that were inlined into the HTML.
1588///
1589/// Runs only after the HTML carrying the inlined bridge has been written,
1590/// and only inside the wasm-pack output directory. The walk classifies each
1591/// entry with `symlink_metadata`, so a directory symlink is never followed:
1592/// a link pointing outside the output, or into a cycle, is left in place
1593/// and named, rather than extending the walk without bound. Every file
1594/// that is deleted is first confirmed to resolve inside the output.
1595///
1596/// A directory wasm-pack itself created is removed only once it is
1597/// genuinely empty — `remove_dir`, never `remove_dir_all` — so a
1598/// non-JavaScript asset an author left inside `snippets/` survives
1599/// together with its directory. Unreadable directories and failed
1600/// enumerations are errors, not silent skips: reporting success while
1601/// JavaScript remains is exactly the failure this guards against.
1602///
1603/// # Arguments
1604///
1605/// - `&Path` - The wasm-pack output directory.
1606///
1607/// # Returns
1608///
1609/// - `Result<Vec<PathBuf>, EuvError>` - The files removed, or an error naming
1610///   what could not be read or deleted.
1611pub(crate) async fn remove_generated_js(pkg_dir: &Path) -> Result<Vec<PathBuf>, EuvError> {
1612    let root: PathBuf = match canonicalize(pkg_dir).await {
1613        Ok(root) => root,
1614        Err(error) if error.kind() == io::ErrorKind::NotFound => {
1615            return Ok(Vec::new());
1616        }
1617        Err(error) => {
1618            return Err(EuvError::IoPath {
1619                message: String::from("Failed to resolve the wasm-pack output directory"),
1620                path: pkg_dir.to_path_buf(),
1621                error,
1622            });
1623        }
1624    };
1625    let mut removed: Vec<PathBuf> = Vec::new();
1626    let mut generated_dirs: Vec<PathBuf> = Vec::new();
1627    let mut pending: Vec<PathBuf> = vec![root.clone()];
1628    while let Some(dir) = pending.pop() {
1629        let mut entries: ReadDir = read_dir(&dir).await.map_err(|error: io::Error| {
1630            EuvError::IoPath {
1631                message: String::from(
1632                    "Failed to list the wasm-pack output directory while removing inlined JavaScript",
1633                ),
1634                path: dir.clone(),
1635                error,
1636            }
1637        })?;
1638        loop {
1639            let entry: DirEntry = match entries.next_entry().await {
1640                Ok(Some(entry)) => entry,
1641                Ok(None) => break,
1642                Err(error) => {
1643                    return Err(EuvError::IoPath {
1644                        message: String::from(
1645                            "Failed to read an entry of the wasm-pack output directory while \
1646                             removing inlined JavaScript",
1647                        ),
1648                        path: dir.clone(),
1649                        error,
1650                    });
1651                }
1652            };
1653            let path: PathBuf = entry.path();
1654            let file_type: FileType =
1655                entry
1656                    .file_type()
1657                    .await
1658                    .map_err(|error: io::Error| EuvError::IoPath {
1659                        message: String::from(
1660                            "Failed to stat an entry of the wasm-pack output directory while \
1661                         removing inlined JavaScript",
1662                        ),
1663                        path: path.clone(),
1664                        error,
1665                    })?;
1666            if file_type.is_symlink() {
1667                // Never followed: a link may leave the package or close a
1668                // cycle, and neither is this walk's to resolve.
1669                log::warn!(
1670                    "Leaving '{}' in place: it is a symlink, and the cleanup never follows one",
1671                    path.display()
1672                );
1673                continue;
1674            }
1675            if file_type.is_dir() {
1676                if path.starts_with(root.join(SNIPPET_DIR_NAME)) {
1677                    generated_dirs.push(path.clone());
1678                }
1679                pending.push(path);
1680                continue;
1681            }
1682            let canonical: PathBuf =
1683                canonicalize(&path)
1684                    .await
1685                    .map_err(|error: io::Error| EuvError::IoPath {
1686                        message: String::from(
1687                            "Failed to resolve an entry of the wasm-pack output directory before \
1688                         deleting it",
1689                        ),
1690                        path: path.clone(),
1691                        error,
1692                    })?;
1693            if !canonical.starts_with(&root) {
1694                log::warn!(
1695                    "Leaving '{}' in place: it resolves outside the wasm-pack output",
1696                    path.display()
1697                );
1698                continue;
1699            }
1700            if !is_generated_js_artifact(&path) {
1701                continue;
1702            }
1703            remove_file(&path)
1704                .await
1705                .map_err(|error: io::Error| EuvError::IoPath {
1706                    message: String::from(
1707                        "Failed to remove a generated JavaScript file after inlining it",
1708                    ),
1709                    path: path.clone(),
1710                    error,
1711                })?;
1712            removed.push(path);
1713        }
1714    }
1715    for dir in generated_dirs.iter().rev() {
1716        match remove_dir(dir).await {
1717            Ok(()) => {}
1718            Err(error) if error.kind() == io::ErrorKind::DirectoryNotEmpty => {}
1719            Err(error) => {
1720                return Err(EuvError::IoPath {
1721                    message: String::from("Failed to remove an emptied snippet directory"),
1722                    path: dir.clone(),
1723                    error,
1724                });
1725            }
1726        }
1727    }
1728    log::debug!(
1729        "Removed {} generated JavaScript file(s) and {} empty generated directory(ies)",
1730        removed.len(),
1731        generated_dirs.len()
1732    );
1733    Ok(removed)
1734}
1735
1736/// Returns `true` for the JavaScript-adjacent files wasm-pack generates:
1737/// `.js`, `.mjs`, `.cjs`, their source maps and their `.d.ts` declarations.
1738///
1739/// # Arguments
1740///
1741/// - `&Path` - Output file path to classify.
1742///
1743/// # Returns
1744///
1745/// - `bool` - Whether the file belongs to the generated JavaScript artifacts.
1746fn is_generated_js_artifact(path: &Path) -> bool {
1747    let name: String = path
1748        .file_name()
1749        .and_then(|name: &ffi::OsStr| name.to_str())
1750        .unwrap_or_default()
1751        .to_ascii_lowercase();
1752    GENERATED_JS_SUFFIXES
1753        .iter()
1754        .any(|suffix: &&str| name.ends_with(suffix))
1755}