1use super::*;
2
3pub 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
21pub 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 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 continue;
63 }
64 skip_next = true;
65 continue;
66 }
67 filtered.push(arg.clone());
68 }
69 filtered
70}
71
72pub 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
174pub 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
212pub 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
229async 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
261fn 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
285fn 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
309pub 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
341fn 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
373fn 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
410pub 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
436pub 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
474pub 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
512pub 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
538pub 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
563pub(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
604async 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
665pub 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
691pub 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
733fn 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
751pub(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
818pub async fn build_wasm(args: &ModeArgs) -> Result<(), EuvError> {
833 let build_mode: BuildMode = resolve_build_mode(args);
834 let build_mode_flag: &str = build_mode_to_flag(build_mode);
835 let filtered_args: Vec<String> = filter_euv_args(args.get_wasm_pack_args());
836 let has_existing_build_mode: bool = has_build_mode_flag(&filtered_args);
837 let default_out_dir: String = format!("{}/{PKG_DIR_NAME}", args.get_www_dir());
838 let mut command: Command = Command::new(WASM_PACK_COMMAND);
839 command.arg(WASM_PACK_BUILD_SUBCOMMAND);
840 if !has_existing_build_mode {
841 command.arg(build_mode_flag);
842 }
843 command
844 .args(&filtered_args)
845 .env(RUST_MIN_STACK_ENV, RUST_MIN_STACK_VALUE);
846 let has_out_dir: bool = extract_out_dir(&filtered_args).is_some();
847 if !has_out_dir {
848 command.arg(OUT_DIR_ARG).arg(&default_out_dir);
849 }
850 let has_target: bool = filtered_args
851 .iter()
852 .any(|arg: &String| arg == TARGET_ARG || arg.starts_with(&format!("{TARGET_ARG}=")));
853 if !has_target {
854 command.arg(TARGET_ARG).arg(TARGET_WEB);
855 }
856 command.current_dir(args.get_crate_path());
857 command.stdout(Stdio::piped()).stderr(Stdio::piped());
858 let display_args: Vec<String> = (if has_existing_build_mode {
859 filtered_args.to_vec()
860 } else {
861 once(build_mode_flag.to_string())
862 .chain(filtered_args.iter().cloned())
863 .collect::<Vec<String>>()
864 })
865 .into_iter()
866 .chain(if has_out_dir {
867 Vec::new()
868 } else {
869 vec![OUT_DIR_ARG.to_string(), default_out_dir.clone()]
870 })
871 .chain(if has_target {
872 Vec::new()
873 } else {
874 vec![TARGET_ARG.to_string(), TARGET_WEB.to_string()]
875 })
876 .collect();
877 let out_dir_absolute: PathBuf = resolve_out_dir(args);
878 create_dir_all(&out_dir_absolute)
879 .await
880 .map_err(|error: io::Error| EuvError::IoPath {
881 message: String::from("Failed to create output directory"),
882 path: out_dir_absolute.clone(),
883 error,
884 })?;
885 log::info!(
886 "Running: {WASM_PACK_COMMAND} {WASM_PACK_BUILD_SUBCOMMAND} {} ...",
887 display_args.join(" ")
888 );
889 let output: Output = command
890 .output()
891 .await
892 .map_err(|error: io::Error| EuvError::Io {
893 message: String::from("Failed to execute wasm-pack"),
894 error,
895 })?;
896 let stdout: String = String::from_utf8_lossy(&output.stdout).to_string();
897 let stderr: String = String::from_utf8_lossy(&output.stderr).to_string();
898 if args.get_no_gitignore() {
899 let gitignore_path: PathBuf = out_dir_absolute.join(GITIGNORE_FILE_NAME);
900 if gitignore_path.exists()
901 && let Err(error) = remove_file(&gitignore_path).await
902 {
903 log::warn!("Failed to remove '{}': {error}", gitignore_path.display());
904 }
905 }
906 for line in stdout.lines().filter(|line: &&str| !line.is_empty()) {
907 log::info!("{line}");
908 }
909 if output.status.success() {
910 for line in stderr.lines().filter(|line: &&str| !line.is_empty()) {
911 log::info!("{line}");
912 }
913 } else {
914 for line in stderr.lines().filter(|line: &&str| !line.is_empty()) {
915 log::error!("{line}");
916 }
917 return Err(EuvError::Message(String::from("wasm-pack build failed")));
918 }
919 Ok(())
920}
921
922pub fn print_banner(action: Action) {
928 let version: &str = env!("CARGO_PKG_VERSION");
929 if version.is_empty() {
930 log::warn!("Failed to parse version from root Cargo.toml");
931 } else {
932 log::info!("euv v{version}");
933 }
934 let action_name: &str = match action {
935 Action::Run => ACTION_RUN,
936 Action::Build => ACTION_BUILD,
937 };
938 log::info!("Mode: {action_name}");
939 log::info!(
940 "Use .gitignore to filter file change events; pass --no-gitignore to remove .gitignore from output"
941 );
942}
943
944pub(crate) fn print_server_urls(config: &ServerUrlConfig) {
956 let port: u16 = config.get_port();
957 let route_prefix: &str = config.get_route_prefix();
958 let index_html_file_name: &str = config.get_index_html_file_name();
959 let mut addresses: Vec<IpAddr> = Vec::new();
960 match if_addrs::get_if_addrs() {
961 Ok(interfaces) => {
962 for interface in interfaces {
963 let ip: IpAddr = interface.addr.ip();
964 if !addresses.contains(&ip) {
965 addresses.push(ip);
966 }
967 }
968 }
969 Err(error) => {
970 log::warn!("Failed to enumerate network interfaces: {error}");
971 }
972 }
973 if addresses.is_empty() {
974 addresses.push(IpAddr::V4(Ipv4Addr::LOCALHOST));
975 }
976 for ip in addresses {
977 let host: String = match ip {
978 IpAddr::V6(_) => format!("[{ip}]"),
979 IpAddr::V4(_) => format!("{ip}"),
980 };
981 let url: String =
982 format!("{HTTP_SCHEME}://{host}:{port}/{route_prefix}/{index_html_file_name}");
983 log::info!("Server: {url}");
984 match QrCode::new(url.as_str()) {
985 Ok(code) => {
986 let string: String = code.render::<Dense1x2>().quiet_zone(false).build();
987 for line in string.lines() {
988 log::info!("{line}");
989 }
990 }
991 Err(error) => {
992 log::warn!("Failed to generate QR code: {error}");
993 }
994 }
995 }
996}
997
998pub(crate) async fn build_inline_bridge(
1024 pkg_dir: &Path,
1025 js_name: &str,
1026 wasm_url: &str,
1027) -> Result<String, EuvError> {
1028 let js_path: PathBuf = pkg_dir.join(js_name);
1029 let bridge_source: String =
1030 read_to_string(&js_path)
1031 .await
1032 .map_err(|error: io::Error| EuvError::IoPath {
1033 message: String::from("Failed to read wasm-bindgen JS bridge"),
1034 path: js_path.clone(),
1035 error,
1036 })?;
1037 let inlined: String = inline_module_graph(&bridge_source, pkg_dir).await?;
1038 let js_only: String = strip_trailing_module_exports(&inlined);
1039 if !js_only.contains("function main(") {
1040 return Err(EuvError::Message(format!(
1041 "wasm-bindgen bridge '{js_name}' declares no main() for the bootstrap to call"
1042 )));
1043 }
1044 if !js_only.contains("__wbg_get_imports") {
1045 return Err(EuvError::Message(format!(
1046 "wasm-bindgen bridge '{js_name}' declares no __wbg_get_imports() \
1047 for the bootstrap to instantiate the module with"
1048 )));
1049 }
1050 let wasm_url_json: String = encode_js_string(wasm_url);
1051 Ok(format!(
1052 "(function() {{\n\
1053 {js_only}\n\
1054 var __euv_wasm_url = {wasm_url_json};\n\
1055 var __euv_base = (document.querySelector('base[href]') && document.baseURI) || location.href;\n\
1056 var __euv_url = new URL(__euv_wasm_url, __euv_base).toString();\n\
1057 function __euv_main() {{ if (typeof main === 'function') {{ main(); }} }}\n\
1058 if (typeof __wbg_init === 'function') {{\n\
1059 __wbg_init(__euv_url).then(__euv_main).catch(function(e) {{\n\
1060 console.error('[euv] inline bridge init failed:', e);\n\
1061 }});\n\
1062 }} else if (typeof initSync === 'function') {{\n\
1063 fetch(__euv_url).then(function(response) {{ return response.arrayBuffer(); }})\n\
1064 .then(function(bytes) {{ initSync({{ module: bytes }}); __euv_main(); }})\n\
1065 .catch(function(e) {{ console.error('[euv] inline bridge init failed:', e); }});\n\
1066 }} else {{\n\
1067 console.error('[euv] inline bridge: no __wbg_init or initSync to instantiate the module');\n\
1068 }}\n\
1069 }})();\n"
1070 ))
1071}
1072
1073async fn inline_module_graph(bridge_source: &str, pkg_dir: &Path) -> Result<String, EuvError> {
1092 let mut snippets: Vec<(PathBuf, String)> = Vec::new();
1093 let mut namespace_clauses: Vec<NamespaceImport> = Vec::new();
1094 for line in bridge_source.lines() {
1095 let trimmed: &str = line.trim();
1096 if !trimmed.starts_with("import ") {
1097 continue;
1098 }
1099 let rest: &str = trimmed.strip_prefix("import ").unwrap_or_default();
1100 let clause: ImportClause<'_> = parse_import_clause(rest)?;
1101 if clause.default_binding.is_some() || !clause.named.is_empty() {
1102 return Err(EuvError::Message(format!(
1103 "wasm-bindgen bridge imports a default or named binding from '{}', \
1104 which a self-contained bootstrap cannot reproduce",
1105 clause.spec
1106 )));
1107 }
1108 if !(clause.spec.starts_with("./") || clause.spec.starts_with("../")) {
1109 return Err(EuvError::Message(format!(
1110 "wasm-bindgen bridge imports the bare module '{}', which a \
1111 self-contained bootstrap cannot fetch",
1112 clause.spec
1113 )));
1114 }
1115 if let Some(alias) = clause.namespace {
1116 namespace_clauses.push(NamespaceImport {
1117 alias: alias.to_string(),
1118 spec: clause.spec.to_string(),
1119 });
1120 }
1121 let snippet_path: PathBuf = resolve_snippet_path(pkg_dir, clause.spec).await?;
1122 if snippets
1123 .iter()
1124 .any(|(path, _): &(PathBuf, String)| path == &snippet_path)
1125 {
1126 continue;
1127 }
1128 let raw: String = read_to_string(&snippet_path)
1129 .await
1130 .map_err(|error: io::Error| EuvError::IoPath {
1131 message: String::from("Failed to read wasm-pack snippet module"),
1132 path: snippet_path.clone(),
1133 error,
1134 })?;
1135 snippets.push((snippet_path, raw));
1136 }
1137 let mut out: String = String::new();
1138 for (snippet_path, raw) in &snippets {
1139 let body: String = strip_module_exports(raw).map_err(|error: EuvError| match error {
1140 EuvError::Message(message) => EuvError::Message(format!(
1141 "{} in snippet module '{}'",
1142 message,
1143 snippet_path.display()
1144 )),
1145 other => other,
1146 })?;
1147 if body.trim().is_empty() {
1148 return Err(EuvError::Message(format!(
1149 "snippet module '{}' has no inlinable body",
1150 snippet_path.display()
1151 )));
1152 }
1153 out.push_str(&body);
1154 out.push('\n');
1155 }
1156 for clause in &namespace_clauses {
1157 let snippet_path: PathBuf = resolve_snippet_path(pkg_dir, &clause.spec).await?;
1158 let raw: String = snippets
1159 .iter()
1160 .find(|(path, _): &&(PathBuf, String)| *path == snippet_path)
1161 .map(|(_, raw): &(PathBuf, String)| raw.clone())
1162 .unwrap_or_default();
1163 let names: Vec<String> = extract_exported_names(&raw);
1164 if names.is_empty() {
1165 return Err(EuvError::Message(format!(
1166 "snippet module '{}' exports nothing the namespace binding '{}' \
1167 could reference",
1168 clause.spec, clause.alias
1169 )));
1170 }
1171 out.push_str(&render_namespace_object(&clause.alias, &names));
1172 }
1173 for line in bridge_source.lines() {
1174 let trimmed: &str = line.trim();
1175 if trimmed.starts_with("import ") {
1176 continue;
1177 }
1178 if trimmed.contains(IMPORT_META_URL_MARKER) {
1179 continue;
1180 }
1181 out.push_str(line);
1182 out.push('\n');
1183 }
1184 Ok(out)
1185}
1186
1187pub fn parse_import_clause(rest: &str) -> Result<ImportClause<'_>, EuvError> {
1197 let rest: &str = rest.trim().trim_end_matches(';').trim();
1198 let from_idx: usize = rest.find(" from ").ok_or_else(|| {
1199 EuvError::Message(format!(
1200 "bridge import '{rest}' is not a static `from` clause, which a \
1201 self-contained bootstrap cannot reproduce"
1202 ))
1203 })?;
1204 let head: &str = rest[..from_idx].trim();
1205 let quoted: &str = rest[from_idx + " from ".len()..].trim();
1206 let quote: char = match quoted.chars().next() {
1207 Some(quote @ ('\'' | '"')) => quote,
1208 _ => {
1209 return Err(EuvError::Message(format!(
1210 "bridge import specifier '{quoted}' is not a quoted string"
1211 )));
1212 }
1213 };
1214 let after: &str = "ed[quote.len_utf8()..];
1215 let spec: &str = after.split(quote).next().unwrap_or_default();
1216 if spec.is_empty() {
1217 return Err(EuvError::Message(format!(
1218 "bridge import '{rest}' names an empty specifier"
1219 )));
1220 }
1221 if head.starts_with('*') {
1222 let alias: &str = head
1223 .strip_prefix('*')
1224 .map(|value: &str| value.trim())
1225 .and_then(|value: &str| value.strip_prefix("as "))
1226 .map(|value: &str| value.trim())
1227 .unwrap_or_default();
1228 if alias.is_empty() {
1229 return Err(EuvError::Message(format!(
1230 "bridge import '{rest}' is a namespace import without a binding"
1231 )));
1232 }
1233 return Ok(ImportClause {
1234 spec,
1235 namespace: Some(alias),
1236 default_binding: None,
1237 named: Vec::new(),
1238 });
1239 }
1240 if let Some(inner) = head.strip_prefix('{') {
1241 let inner: &str = inner.strip_suffix('}').ok_or_else(|| {
1242 EuvError::Message(format!(
1243 "bridge import '{rest}' has an unbalanced `{{` clause"
1244 ))
1245 })?;
1246 return Ok(ImportClause {
1247 spec,
1248 namespace: None,
1249 default_binding: None,
1250 named: inner
1251 .split(',')
1252 .map(|entry: &str| entry.trim())
1253 .filter(|entry: &&str| !entry.is_empty())
1254 .collect(),
1255 });
1256 }
1257 Ok(ImportClause {
1258 spec,
1259 namespace: None,
1260 default_binding: Some(head),
1261 named: Vec::new(),
1262 })
1263}
1264
1265fn render_namespace_object(alias: &str, names: &[String]) -> String {
1277 let mut out: String = format!("var {alias} = {{");
1278 for (index, name) in names.iter().enumerate() {
1279 if index > 0 {
1280 out.push(',');
1281 }
1282 out.push_str(name);
1283 out.push(':');
1284 out.push_str(name);
1285 }
1286 out.push_str("};\n");
1287 out
1288}
1289
1290fn strip_module_exports(source: &str) -> Result<String, EuvError> {
1302 let mut out: String = String::with_capacity(source.len());
1303 for line in source.lines() {
1304 let trimmed: &str = line.trim();
1305 let Some(rest) = trimmed.strip_prefix("export ") else {
1306 out.push_str(line);
1307 out.push('\n');
1308 continue;
1309 };
1310 match classify_export(rest) {
1311 ExportForm::Aliases(clause) => {
1312 out.push_str(&render_export_aliases(clause)?);
1313 }
1314 ExportForm::Declaration(declaration) => {
1315 out.push_str(declaration);
1316 out.push('\n');
1317 }
1318 ExportForm::Unsupported => {
1319 return Err(EuvError::Message(format!(
1320 "snippet exports '{rest}', a form a self-contained \
1321 bootstrap cannot reproduce"
1322 )));
1323 }
1324 }
1325 }
1326 Ok(out)
1327}
1328
1329fn classify_export(rest: &str) -> ExportForm<'_> {
1339 let trimmed: &str = rest.trim_end().trim_end_matches(';');
1340 if let Some(inner) = trimmed.strip_prefix('{')
1341 && inner.trim_end().ends_with('}')
1342 {
1343 return ExportForm::Aliases(inner.trim_end().trim_end_matches('}'));
1344 }
1345 if EXPORT_DECLARATION_KEYWORDS
1346 .iter()
1347 .any(|keyword: &&str| trimmed.starts_with(keyword))
1348 {
1349 return ExportForm::Declaration(trimmed);
1350 }
1351 ExportForm::Unsupported
1352}
1353
1354fn render_export_aliases(clause: &str) -> Result<String, EuvError> {
1371 let mut out: String = String::new();
1372 for entry in clause.split(',') {
1373 let entry: &str = entry.trim();
1374 if entry.is_empty() {
1375 continue;
1376 }
1377 let (original, exported): (&str, &str) = match entry.split_once(" as ") {
1378 Some((original, exported)) => (original.trim(), exported.trim()),
1379 None => (entry, entry),
1380 };
1381 if !is_identifier(original) || !is_identifier(exported) {
1382 return Err(EuvError::Message(format!(
1383 "snippet exports the non-identifier entry '{entry}'"
1384 )));
1385 }
1386 if original == exported || exported == "default" || original == "wasm" {
1387 continue;
1388 }
1389 out.push_str(exported);
1390 out.push_str(" = ");
1391 out.push_str(original);
1392 out.push_str(";\n");
1393 }
1394 Ok(out)
1395}
1396
1397fn is_identifier(value: &str) -> bool {
1407 !value.is_empty()
1408 && !value.starts_with(|c: char| c.is_ascii_digit())
1409 && value
1410 .chars()
1411 .all(|c: char| c.is_ascii_alphanumeric() || c == '_' || c == '$')
1412}
1413
1414pub fn extract_exported_names(source: &str) -> Vec<String> {
1426 let mut names: Vec<String> = Vec::new();
1427 for line in source.lines() {
1428 let trimmed: &str = line.trim();
1429 let Some(rest) = trimmed.strip_prefix("export ") else {
1430 continue;
1431 };
1432 let declaration: Option<&str> = EXPORT_DECLARATION_KEYWORDS
1433 .iter()
1434 .find_map(|keyword: &&str| rest.strip_prefix(keyword));
1435 if let Some(name) = declaration.and_then(leading_identifier)
1436 && !names.iter().any(|existing: &String| existing == name)
1437 {
1438 names.push(name.to_string());
1439 }
1440 }
1441 names
1442}
1443
1444fn leading_identifier(value: &str) -> Option<&str> {
1455 let end: usize = value
1456 .find(|c: char| !c.is_alphanumeric() && c != '_' && c != '$')
1457 .unwrap_or(value.len());
1458 if end == 0 { None } else { Some(&value[..end]) }
1459}
1460
1461async fn resolve_snippet_path(pkg_dir: &Path, spec: &str) -> Result<PathBuf, EuvError> {
1473 let base: &str = spec.strip_prefix("./").unwrap_or(spec);
1474 let mut path: PathBuf = pkg_dir.to_path_buf();
1475 for segment in base.split('/') {
1476 if segment.is_empty() || segment == "." {
1477 continue;
1478 }
1479 if segment == ".." {
1480 return Err(EuvError::Message(String::from(
1481 "Snippet import spec escapes pkg directory",
1482 )));
1483 }
1484 path.push(segment);
1485 }
1486 let root: PathBuf =
1487 canonicalize(pkg_dir)
1488 .await
1489 .map_err(|error: io::Error| EuvError::IoPath {
1490 message: String::from("Failed to resolve the WASM output directory"),
1491 path: pkg_dir.to_path_buf(),
1492 error,
1493 })?;
1494 let resolved: PathBuf =
1495 canonicalize(&path)
1496 .await
1497 .map_err(|error: io::Error| EuvError::IoPath {
1498 message: String::from("Failed to resolve the imported snippet"),
1499 path: path.clone(),
1500 error,
1501 })?;
1502 if !resolved.starts_with(root) {
1503 return Err(EuvError::Message(format!(
1504 "Snippet import '{spec}' resolves outside the WASM output directory",
1505 )));
1506 }
1507 Ok(resolved)
1508}
1509
1510fn strip_trailing_module_exports(source: &str) -> String {
1523 let mut out: String = String::with_capacity(source.len());
1524 for line in source.lines() {
1525 let trimmed: &str = line.trim();
1526 let Some(rest) = trimmed.strip_prefix("export ") else {
1527 out.push_str(line);
1528 out.push('\n');
1529 continue;
1530 };
1531 match classify_export(rest) {
1532 ExportForm::Aliases(clause) => {
1533 if let Ok(aliases) = render_export_aliases(clause) {
1534 out.push_str(&aliases);
1535 }
1536 }
1537 ExportForm::Declaration(declaration) => {
1538 out.push_str(declaration);
1539 out.push('\n');
1540 }
1541 ExportForm::Unsupported => {
1542 out.push_str(line);
1543 out.push('\n');
1544 }
1545 }
1546 }
1547 out
1548}
1549
1550pub(crate) fn encode_js_string(value: &str) -> String {
1563 let mut out: String = String::with_capacity(value.len() + 2);
1564 out.push('"');
1565 for ch in value.chars() {
1566 match ch {
1567 '"' => out.push_str("\\\""),
1568 '\\' => out.push_str("\\\\"),
1569 '\n' => out.push_str("\\n"),
1570 '\r' => out.push_str("\\r"),
1571 '\t' => out.push_str("\\t"),
1572 '\u{08}' => out.push_str("\\b"),
1573 '\u{0C}' => out.push_str("\\f"),
1574 '<' => out.push_str("\\u003c"),
1575 '>' => out.push_str("\\u003e"),
1576 '&' => out.push_str("\\u0026"),
1577 '\u{2028}' => out.push_str("\\u2028"),
1578 '\u{2029}' => out.push_str("\\u2029"),
1579 c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
1580 c => out.push(c),
1581 }
1582 }
1583 out.push('"');
1584 out
1585}
1586
1587pub(crate) async fn remove_generated_js(pkg_dir: &Path) -> Result<Vec<PathBuf>, EuvError> {
1614 let root: PathBuf = match canonicalize(pkg_dir).await {
1615 Ok(root) => root,
1616 Err(error) if error.kind() == io::ErrorKind::NotFound => {
1617 return Ok(Vec::new());
1618 }
1619 Err(error) => {
1620 return Err(EuvError::IoPath {
1621 message: String::from("Failed to resolve the wasm-pack output directory"),
1622 path: pkg_dir.to_path_buf(),
1623 error,
1624 });
1625 }
1626 };
1627 let mut removed: Vec<PathBuf> = Vec::new();
1628 let mut generated_dirs: Vec<PathBuf> = Vec::new();
1629 let mut pending: Vec<PathBuf> = vec![root.clone()];
1630 while let Some(dir) = pending.pop() {
1631 let mut entries: ReadDir = read_dir(&dir).await.map_err(|error: io::Error| {
1632 EuvError::IoPath {
1633 message: String::from(
1634 "Failed to list the wasm-pack output directory while removing inlined JavaScript",
1635 ),
1636 path: dir.clone(),
1637 error,
1638 }
1639 })?;
1640 loop {
1641 let entry: DirEntry = match entries.next_entry().await {
1642 Ok(Some(entry)) => entry,
1643 Ok(None) => break,
1644 Err(error) => {
1645 return Err(EuvError::IoPath {
1646 message: String::from(
1647 "Failed to read an entry of the wasm-pack output directory while \
1648 removing inlined JavaScript",
1649 ),
1650 path: dir.clone(),
1651 error,
1652 });
1653 }
1654 };
1655 let path: PathBuf = entry.path();
1656 let file_type: FileType =
1657 entry
1658 .file_type()
1659 .await
1660 .map_err(|error: io::Error| EuvError::IoPath {
1661 message: String::from(
1662 "Failed to stat an entry of the wasm-pack output directory while \
1663 removing inlined JavaScript",
1664 ),
1665 path: path.clone(),
1666 error,
1667 })?;
1668 if file_type.is_symlink() {
1669 log::warn!(
1672 "Leaving '{}' in place: it is a symlink, and the cleanup never follows one",
1673 path.display()
1674 );
1675 continue;
1676 }
1677 if file_type.is_dir() {
1678 if path.starts_with(root.join(SNIPPET_DIR_NAME)) {
1679 generated_dirs.push(path.clone());
1680 }
1681 pending.push(path);
1682 continue;
1683 }
1684 let canonical: PathBuf =
1685 canonicalize(&path)
1686 .await
1687 .map_err(|error: io::Error| EuvError::IoPath {
1688 message: String::from(
1689 "Failed to resolve an entry of the wasm-pack output directory before \
1690 deleting it",
1691 ),
1692 path: path.clone(),
1693 error,
1694 })?;
1695 if !canonical.starts_with(&root) {
1696 log::warn!(
1697 "Leaving '{}' in place: it resolves outside the wasm-pack output",
1698 path.display()
1699 );
1700 continue;
1701 }
1702 if !is_generated_js_artifact(&path) {
1703 continue;
1704 }
1705 remove_file(&path)
1706 .await
1707 .map_err(|error: io::Error| EuvError::IoPath {
1708 message: String::from(
1709 "Failed to remove a generated JavaScript file after inlining it",
1710 ),
1711 path: path.clone(),
1712 error,
1713 })?;
1714 removed.push(path);
1715 }
1716 }
1717 for dir in generated_dirs.iter().rev() {
1718 match remove_dir(dir).await {
1719 Ok(()) => {}
1720 Err(error) if error.kind() == io::ErrorKind::DirectoryNotEmpty => {}
1721 Err(error) => {
1722 return Err(EuvError::IoPath {
1723 message: String::from("Failed to remove an emptied snippet directory"),
1724 path: dir.clone(),
1725 error,
1726 });
1727 }
1728 }
1729 }
1730 log::debug!(
1731 "Removed {} generated JavaScript file(s) and {} empty generated directory(ies)",
1732 removed.len(),
1733 generated_dirs.len()
1734 );
1735 Ok(removed)
1736}
1737
1738fn is_generated_js_artifact(path: &Path) -> bool {
1749 let name: String = path
1750 .file_name()
1751 .and_then(|name: &ffi::OsStr| name.to_str())
1752 .unwrap_or_default()
1753 .to_ascii_lowercase();
1754 GENERATED_JS_SUFFIXES
1755 .iter()
1756 .any(|suffix: &&str| name.ends_with(suffix))
1757}