1use super::*;
2
3#[must_use]
13pub fn normalize_web_asset_base(raw: &str) -> String {
14 let trimmed: &str = raw.trim();
15 if trimmed.is_empty() || trimmed == "." || trimmed == "./" {
16 return WEB_DEFAULT_ASSET_BASE.to_string();
17 }
18 if trimmed == "/" {
19 return "/".to_string();
20 }
21 let without_trailing: &str = trimmed.trim_end_matches('/');
22 if without_trailing.is_empty() {
23 return "/".to_string();
24 }
25 if without_trailing.starts_with('/') || without_trailing.starts_with("./") {
26 format!("{without_trailing}/")
27 } else {
28 format!("./{without_trailing}/")
29 }
30}
31
32#[must_use]
42pub fn build_web_rustflags(existing: Option<&str>) -> String {
43 let mut parts: Vec<String> = Vec::new();
44 let base: &str = existing.map(str::trim).unwrap_or("");
45 if !base.is_empty() {
46 parts.push(base.to_string());
47 }
48 if !base.contains(WEB_RUSTFLAG_BULK_MEMORY_TOKEN) {
49 parts.push(WEB_RUSTFLAG_BULK_MEMORY.to_string());
50 }
51 if !base.contains(WEB_RUSTFLAG_GETRANDOM_TOKEN) {
52 parts.push(WEB_RUSTFLAG_GETRANDOM.to_string());
53 }
54 if !base.contains(WEB_RUSTFLAG_SIMD128_TOKEN) {
55 parts.push(WEB_RUSTFLAG_SIMD128.to_string());
56 }
57 parts.join(" ")
58}
59
60#[must_use]
72pub fn transform_web_bindgen_glue(raw_js: &str, wasm_file: &str, asset_base: &str) -> String {
73 let normalized_base: String = normalize_web_asset_base(asset_base);
74 let wasm_href: String = format!("{normalized_base}{wasm_file}");
75 let single_url_expr: String = format!("new URL('{wasm_file}', import.meta.url)");
76 let double_url_expr: String = format!("new URL(\"{wasm_file}\", import.meta.url)");
77 let replacement: String = format!("'{wasm_href}'");
78 let rewritten: String = raw_js
79 .replace(&single_url_expr, &replacement)
80 .replace(&double_url_expr, &replacement);
81 let cleaned_lines: Vec<String> = rewritten
82 .lines()
83 .filter(|line: &&str| {
84 let trimmed: &str = line.trim_start();
85 !trimmed.starts_with(WEB_EXPORT_BRACE) && !trimmed.starts_with(WEB_EXPORT_DEFAULT)
86 })
87 .map(|line: &str| {
88 line.strip_prefix(WEB_EXPORT_PREFIX)
89 .unwrap_or(line)
90 .to_string()
91 })
92 .collect();
93 cleaned_lines.join("\n")
94}
95
96#[must_use]
110pub fn render_zero_js_web_html(
111 title: &str,
112 asset_base: &str,
113 wasm_file: &str,
114 raw_js_glue: &str,
115 logo_data_uri: &str,
116) -> String {
117 let normalized_base: String = normalize_web_asset_base(asset_base);
118 let wasm_href: String = format!("{normalized_base}{wasm_file}");
119 let cleaned_glue: String = transform_web_bindgen_glue(raw_js_glue, wasm_file, &normalized_base);
120 let safe_title: String = escape_web_html(title);
121 let mut html: String = String::with_capacity(
122 cleaned_glue.len() + safe_title.len() * 2 + logo_data_uri.len() * 3 + 4_096,
123 );
124 html.push_str(WEB_SHELL_HEAD_OPEN);
125 html.push_str(WEB_SHELL_PRELOAD_OPEN);
126 html.push_str(&wasm_href);
127 html.push_str(WEB_SHELL_PRELOAD_CLOSE);
128 html.push_str(WEB_SHELL_FAVICON_OPEN);
129 html.push_str(logo_data_uri);
130 html.push_str(WEB_SHELL_APPLE_ICON_MID);
131 html.push_str(logo_data_uri);
132 html.push_str(WEB_SHELL_TITLE_OPEN);
133 html.push_str(&safe_title);
134 html.push_str(WEB_SHELL_STYLE_AND_LOADER);
135 html.push_str(logo_data_uri);
136 html.push_str(WEB_SHELL_LOGO_END);
137 html.push_str(&safe_title);
138 html.push_str(WEB_SHELL_SCRIPT_OPEN);
139 html.push_str(&cleaned_glue);
140 html.push_str(WEB_SHELL_BOOT_OPEN);
141 html.push_str(&wasm_href);
142 html.push_str(WEB_SHELL_BOOT_BODY);
143 html
144}
145
146pub fn package_web_bundle_directory(
161 out_dir: &Path,
162 title: &str,
163 asset_base: &str,
164 version: &str,
165 custom_icon: Option<&Path>,
166 verify_release: bool,
167) -> io::Result<ReleaseAssetManifest> {
168 let dir_meta: Metadata = fs::symlink_metadata(out_dir)?;
169 if dir_meta.file_type().is_symlink() || !dir_meta.is_dir() {
170 return Err(Error::new(
171 ErrorKind::InvalidInput,
172 format!("{ERR_WEB_SYMLINK_OUT}: {}", out_dir.display()),
173 ));
174 }
175 let normalized_base: String = normalize_web_asset_base(asset_base);
176 let mut wasm_name: Option<String> = None;
177 let mut loader_path: Option<PathBuf> = None;
178 let mut removable: Vec<PathBuf> = Vec::new();
179 for entry_res in fs::read_dir(out_dir)? {
180 let entry: DirEntry = entry_res?;
181 let path: PathBuf = entry.path();
182 if !path.is_file() {
183 continue;
184 }
185 let name: String = entry.file_name().to_string_lossy().into_owned();
186 if name.ends_with(WEB_EXT_WASM) {
187 if name.ends_with(WEB_BG_WASM_SUFFIX) || wasm_name.is_none() {
188 wasm_name = Some(name);
189 }
190 } else if name.ends_with(WEB_EXT_JS) {
191 if loader_path.is_none() {
192 loader_path = Some(path.clone());
193 }
194 removable.push(path);
195 } else if name.ends_with(WEB_EXT_DTS) || name == WEB_PACKAGE_JSON || name == WEB_GITIGNORE {
196 removable.push(path);
197 }
198 }
199 let wasm_file: String =
200 wasm_name.ok_or_else(|| Error::new(ErrorKind::NotFound, ERR_WEB_DIR_WASM_MISSING))?;
201 let raw_js: String = match loader_path {
202 Some(js_path) => fs::read_to_string(&js_path)?,
203 None => WEB_FALLBACK_WBG_INIT.to_string(),
204 };
205 let _: Vec<PathBuf> = write_web_icons(out_dir, custom_icon)?;
206 let logo_data_uri: String = resolve_icon_data_uri(custom_icon)?;
207 let html: String =
208 render_zero_js_web_html(title, &normalized_base, &wasm_file, &raw_js, &logo_data_uri);
209 fs::write(out_dir.join(WEB_INDEX_HTML), html.as_bytes())?;
210 fs::write(out_dir.join(WEB_NOT_FOUND_HTML), html.as_bytes())?;
211 fs::write(out_dir.join(WEB_NOJEKYLL_NAME), [])?;
212 for path in removable.into_iter() {
213 let _: io::Result<()> = fs::remove_file(path);
214 }
215 let manifest: ReleaseAssetManifest = write_release_manifest(out_dir, version)?;
216 if verify_release {
217 verify_zero_js_web_bundle(out_dir, &normalized_base, &wasm_file, version)?;
218 }
219 Ok(manifest)
220}
221
222pub fn verify_zero_js_web_bundle(
235 out_dir: &Path,
236 asset_base: &str,
237 wasm_file: &str,
238 expected_version: &str,
239) -> io::Result<ReleaseAssetManifest> {
240 for entry_res in fs::read_dir(out_dir)? {
241 let entry: DirEntry = entry_res?;
242 let path: PathBuf = entry.path();
243 if path.is_file()
244 && path
245 .file_name()
246 .map(|name: &OsStr| name.to_string_lossy().ends_with(WEB_EXT_JS))
247 .unwrap_or(false)
248 {
249 return Err(Error::new(
250 ErrorKind::InvalidData,
251 format!("{ERR_WEB_EXTERNAL_JS_REMAIN}: {}", path.display()),
252 ));
253 }
254 }
255 let _: AiSchemaScanReport = verify_no_ai_schema_leak(&out_dir.join(wasm_file))?;
256 let index_bytes: Vec<u8> = fs::read(out_dir.join(WEB_INDEX_HTML))?;
257 let fallback_bytes: Vec<u8> = fs::read(out_dir.join(WEB_NOT_FOUND_HTML))?;
258 if index_bytes != fallback_bytes {
259 return Err(Error::new(
260 ErrorKind::InvalidData,
261 ERR_WEB_FALLBACK_MISMATCH,
262 ));
263 }
264 if !out_dir.join(WEB_NOJEKYLL_NAME).is_file() {
265 return Err(Error::new(ErrorKind::InvalidData, ERR_WEB_NOJEKYLL_MISSING));
266 }
267 let html: String = String::from_utf8(index_bytes)
268 .map_err(|err: FromUtf8Error| Error::new(ErrorKind::InvalidData, err.to_string()))?;
269 let normalized_base: String = normalize_web_asset_base(asset_base);
270 let expected_href: String = format!("{normalized_base}{wasm_file}");
271 let expected_js_lit: String = format!("'{expected_href}'");
272 let expected_preload: String =
273 format!("{WEB_SHELL_PRELOAD_OPEN}{expected_href}{WEB_SHELL_PRELOAD_CLOSE}");
274 let preload_trimmed: &str = expected_preload.trim_end();
275 if !html.contains(&expected_js_lit) || !html.contains(preload_trimmed) {
276 return Err(Error::new(ErrorKind::InvalidData, ERR_WEB_PRELOAD_OR_HREF));
277 }
278 if normalized_base == WEB_DEFAULT_ASSET_BASE {
279 let forbidden_single: String = format!("'/{wasm_file}'");
280 let forbidden_double: String = format!("\"/{wasm_file}\"");
281 if html.contains(&forbidden_single) || html.contains(&forbidden_double) {
282 return Err(Error::new(ErrorKind::InvalidData, ERR_WEB_ROOT_ABS_WASM));
283 }
284 }
285 let required: [&str; 5] = [
286 WEB_INDEX_HTML,
287 WEB_NOT_FOUND_HTML,
288 wasm_file,
289 WEB_FAVICON_PNG,
290 WEB_APPLE_TOUCH_PNG,
291 ];
292 verify_release_manifest(out_dir, Some(expected_version), &required)
293}
294
295pub fn resolve_web_package_metadata(
306 repo_root: &Path,
307 package: &str,
308) -> io::Result<WebPackageMetadata> {
309 let output: Output = Command::new(WEB_BIN_CARGO)
310 .current_dir(repo_root)
311 .args([
312 WEB_ARG_METADATA,
313 WEB_ARG_FORMAT_VERSION,
314 "1",
315 WEB_ARG_FILTER_PLATFORM,
316 WEB_RUST_TARGET,
317 ])
318 .output()?;
319 if !output.status.success() {
320 let stderr: String = String::from_utf8_lossy(&output.stderr).into_owned();
321 return Err(Error::other(format!(
322 "{ERR_WEB_METADATA_PACKAGE}: {stderr}"
323 )));
324 }
325 let stdout: String = String::from_utf8_lossy(&output.stdout).into_owned();
326 let root_val: Value = from_str(&stdout)
327 .map_err(|err: serde_json::Error| Error::new(ErrorKind::InvalidData, err.to_string()))?;
328 let packages: &Vec<Value> = root_val
329 .get(META_KEY_PACKAGES)
330 .and_then(Value::as_array)
331 .ok_or_else(|| Error::new(ErrorKind::InvalidData, ERR_WEB_METADATA_PACKAGE))?;
332 let mut pkg_id_to_name_ver: BTreeMap<String, (String, String)> = BTreeMap::new();
333 let mut matched_pkg: Option<&Value> = None;
334 for pkg in packages.iter() {
335 let pkg_id: String = pkg
336 .get("id")
337 .and_then(Value::as_str)
338 .unwrap_or("")
339 .to_string();
340 let pkg_name: String = pkg
341 .get(META_KEY_NAME)
342 .and_then(Value::as_str)
343 .unwrap_or("")
344 .to_string();
345 let pkg_ver: String = pkg
346 .get(META_KEY_VERSION)
347 .and_then(Value::as_str)
348 .unwrap_or("")
349 .to_string();
350 if pkg_name == package {
351 matched_pkg = Some(pkg);
352 }
353 let _: Option<(String, String)> = pkg_id_to_name_ver.insert(pkg_id, (pkg_name, pkg_ver));
354 }
355 let pkg_val: &Value = matched_pkg.ok_or_else(|| {
356 Error::new(
357 ErrorKind::NotFound,
358 format!("{ERR_WEB_METADATA_PACKAGE}: {package}"),
359 )
360 })?;
361 let pkg_id: &str = pkg_val.get("id").and_then(Value::as_str).unwrap_or("");
362 let version: String = pkg_val
363 .get(META_KEY_VERSION)
364 .and_then(Value::as_str)
365 .unwrap_or(WEB_FALLBACK_VERSION)
366 .to_string();
367 let lib_name: String = resolve_lib_target_name(pkg_val, package);
368 let mut theme_features: Vec<String> = Vec::new();
369 if let Some(feat_map) = pkg_val.get(META_KEY_FEATURES).and_then(Value::as_object) {
370 for key in feat_map.keys() {
371 if key.starts_with(WEB_THEME_FEATURE_PREFIX) {
372 theme_features.push(key.clone());
373 }
374 }
375 }
376 theme_features.sort();
377 let target_dir: PathBuf = match env::var_os(ENV_CARGO_TARGET_DIR) {
378 Some(val) if !val.is_empty() => PathBuf::from(val),
379 _ => root_val
380 .get(META_KEY_TARGET_DIR)
381 .and_then(Value::as_str)
382 .map(PathBuf::from)
383 .unwrap_or_else(|| repo_root.join(WEB_TARGET_DIR_NAME)),
384 };
385 let mut wb_version: Option<String> = None;
386 if let Some(nodes) = root_val
387 .get(META_KEY_RESOLVE)
388 .and_then(|res: &Value| res.get(META_KEY_NODES))
389 .and_then(Value::as_array)
390 {
391 for node in nodes.iter() {
392 if node.get("id").and_then(Value::as_str) == Some(pkg_id)
393 && let Some(deps) = node.get(META_KEY_DEPENDENCIES).and_then(Value::as_array)
394 {
395 for dep_id_val in deps.iter() {
396 if let Some(dep_id) = dep_id_val.as_str()
397 && let Some((dep_name, dep_ver)) = pkg_id_to_name_ver.get(dep_id)
398 && dep_name == DEP_NAME_WASM_BINDGEN
399 {
400 wb_version = Some(dep_ver.clone());
401 break;
402 }
403 }
404 }
405 }
406 }
407 Ok(WebPackageMetadata::new(
408 package.to_string(),
409 lib_name,
410 version,
411 target_dir,
412 wb_version,
413 theme_features,
414 ))
415}
416
417pub fn build_web_bundle(config: &WebBuildConfig) -> io::Result<WebBuildReport> {
427 let started: SystemTime = SystemTime::now();
428 let repo_root: &Path = config.get_repo_root().as_path();
429 let out_dir: PathBuf = resolve_output_path(repo_root, config.get_out_dir());
430 if let Ok(meta) = fs::symlink_metadata(&out_dir)
431 && meta.file_type().is_symlink()
432 {
433 return Err(Error::new(
434 ErrorKind::InvalidInput,
435 format!("{ERR_WEB_SYMLINK_OUT}: {}", out_dir.display()),
436 ));
437 }
438 if out_dir.exists() {
439 fs::remove_dir_all(&out_dir)?;
440 }
441 fs::create_dir_all(&out_dir)?;
442 let metadata: WebPackageMetadata =
443 resolve_web_package_metadata(repo_root, config.get_package())?;
444 let version: String = match config.try_get_version() {
445 Some(explicit) if !explicit.trim().is_empty() => explicit.trim().to_string(),
446 _ => metadata.get_version().clone(),
447 };
448 let lib_name: &str = metadata.get_lib_name().as_str();
449 let base_url: String = normalize_web_asset_base(config.get_base_url());
450 let rustflags: String = build_web_rustflags(env::var(ENV_RUSTFLAGS).ok().as_deref());
451 let mut cargo_args: Vec<String> = vec![
452 WEB_ARG_BUILD.to_string(),
453 WEB_ARG_TARGET.to_string(),
454 WEB_RUST_TARGET.to_string(),
455 WEB_ARG_LIB.to_string(),
456 WEB_ARG_PACKAGE.to_string(),
457 config.get_package().clone(),
458 ];
459 if config.get_release() {
460 cargo_args.push(WEB_ARG_RELEASE.to_string());
461 }
462 if config.get_no_default_features() {
463 cargo_args.push(WEB_ARG_NO_DEFAULT_FEATURES.to_string());
464 }
465 if !config.get_features().is_empty() {
466 cargo_args.push(WEB_ARG_FEATURES.to_string());
467 cargo_args.push(config.get_features().join(","));
468 }
469 let mut cargo_cmd: Command = Command::new(WEB_BIN_CARGO);
470 let _: &mut Command = cargo_cmd
471 .current_dir(repo_root)
472 .args(&cargo_args)
473 .env(ENV_RUSTFLAGS, &rustflags);
474 if config.get_release() {
475 let _: &mut Command = cargo_cmd.env(ENV_CARGO_RELEASE_PANIC, PANIC_ABORT_VALUE);
476 }
477 run_streaming_command(&mut cargo_cmd)?;
478 let profile_dir: &str = if config.get_release() {
479 WEB_PROFILE_RELEASE
480 } else {
481 WEB_PROFILE_DEBUG
482 };
483 let compiled_wasm: PathBuf = metadata
484 .get_target_dir()
485 .join(WEB_RUST_TARGET)
486 .join(profile_dir)
487 .join(format!("{lib_name}{WEB_EXT_WASM}"));
488 if !compiled_wasm.is_file() {
489 return Err(Error::new(
490 ErrorKind::NotFound,
491 format!(
492 "{ERR_WEB_COMPILED_WASM_MISSING}: {}",
493 compiled_wasm.display()
494 ),
495 ));
496 }
497 let custom_icon: Option<&Path> = config.try_get_icon_path().as_deref();
498 if config.get_raw_wasm() {
499 let wasm_file: String = format!("{lib_name}{WEB_EXT_WASM}");
500 let dest_wasm: PathBuf = out_dir.join(&wasm_file);
501 let wasm_bytes: u64 = fs::copy(&compiled_wasm, &dest_wasm)?;
502 if config.get_release() && config.get_verify() {
503 let _: AiSchemaScanReport = verify_no_ai_schema_leak(&dest_wasm)?;
504 }
505 let icon_paths: Vec<PathBuf> = write_web_raw_icons(&out_dir, custom_icon)?;
506 let plans: Vec<BuildPlan> =
507 resolve_build_plans(TargetArg::Web, RenderArg::Auto, config.get_release());
508 let plan_json: String = to_string_pretty(&plans)
509 .map_err(|err: serde_json::Error| Error::other(err.to_string()))?;
510 fs::write(out_dir.join(WEB_BUILD_PLAN_JSON), plan_json.as_bytes())?;
511 let archive_written: Option<PathBuf> = maybe_archive_web_dir(repo_root, &out_dir, config)?;
512 let elapsed_ms: u64 = elapsed_millis(started);
513 return Ok(WebBuildReport {
514 package: config.get_package().clone(),
515 version,
516 out_dir,
517 base_url,
518 wasm_file,
519 wasm_bytes,
520 wasm_opt_applied: false,
521 raw_wasm: true,
522 file_count: icon_paths.len() + 2,
523 elapsed_ms,
524 manifest_path: None,
525 archive_path: archive_written,
526 });
527 }
528 verify_wasm_bindgen_cli_version(metadata.try_get_wasm_bindgen_version().as_deref())?;
529 let mut wb_cmd: Command = Command::new(WEB_BIN_WASM_BINDGEN);
530 let _: &mut Command = wb_cmd.current_dir(repo_root).args([
531 WEB_ARG_TARGET,
532 WEB_TARGET_MODE,
533 WEB_ARG_NO_TS,
534 WEB_ARG_OUT_DIR,
535 &out_dir.to_string_lossy(),
536 WEB_ARG_OUT_NAME,
537 lib_name,
538 &compiled_wasm.to_string_lossy(),
539 ]);
540 run_streaming_command(&mut wb_cmd)?;
541 let wasm_file: String = format!("{lib_name}{WEB_BG_WASM_SUFFIX}");
542 let bg_wasm_path: PathBuf = out_dir.join(&wasm_file);
543 let env_skip_opt: bool = env::var(ENV_SKIP_WASM_OPT)
544 .map(|val: String| val.trim() == "1")
545 .unwrap_or(false);
546 let wasm_opt_applied: bool =
547 if config.get_release() && !config.get_skip_wasm_opt() && !env_skip_opt {
548 run_optional_wasm_opt(
549 &bg_wasm_path,
550 &out_dir.join(format!("{lib_name}{WEB_OPT_WASM_SUFFIX}")),
551 )
552 } else {
553 false
554 };
555 let manifest: ReleaseAssetManifest = package_web_bundle_directory(
556 &out_dir,
557 config.get_title(),
558 &base_url,
559 &version,
560 custom_icon,
561 config.get_verify() && config.get_release(),
562 )?;
563 let wasm_bytes: u64 = fs::metadata(&bg_wasm_path)?.len();
564 let archive_written: Option<PathBuf> = maybe_archive_web_dir(repo_root, &out_dir, config)?;
565 let elapsed_ms: u64 = elapsed_millis(started);
566 Ok(WebBuildReport {
567 package: config.get_package().clone(),
568 version,
569 out_dir: out_dir.clone(),
570 base_url,
571 wasm_file,
572 wasm_bytes,
573 wasm_opt_applied,
574 raw_wasm: false,
575 file_count: manifest.get_files().len(),
576 elapsed_ms,
577 manifest_path: Some(out_dir.join(RELEASE_MANIFEST_NAME)),
578 archive_path: archive_written,
579 })
580}
581
582pub fn build_web_theme_variants(config: &WebBuildConfig) -> io::Result<ThemeVariantBuildReport> {
592 let started: SystemTime = SystemTime::now();
593 let repo_root: &Path = config.get_repo_root().as_path();
594 let out_dir: PathBuf = resolve_output_path(repo_root, config.get_out_dir());
595 let metadata: WebPackageMetadata =
596 resolve_web_package_metadata(repo_root, config.get_package())?;
597 let version: String = match config.try_get_version() {
598 Some(explicit) if !explicit.trim().is_empty() => explicit.trim().to_string(),
599 _ => metadata.get_version().clone(),
600 };
601 let fingerprint: String = compute_workspace_source_fingerprint(repo_root)?;
602 let cache_dir: PathBuf = out_dir.join(WEB_THEME_CACHE_SUBDIR);
603 let themes_dir: PathBuf = out_dir.join(WEB_THEMES_SUBDIR);
604 fs::create_dir_all(&cache_dir)?;
605 fs::create_dir_all(&themes_dir)?;
606 let mut variants: Vec<String> = vec![WEB_THEME_DEFAULT_NAME.to_string()];
607 for feature in metadata.get_theme_features().iter() {
608 variants.push(feature.clone());
609 }
610 let expected_wasm: String = format!("{}{WEB_BG_WASM_SUFFIX}", metadata.get_lib_name());
611 let mut built_variants: Vec<String> = Vec::new();
612 let mut cached_variants: Vec<String> = Vec::new();
613 for variant in variants.into_iter() {
614 let variant_dir: PathBuf = themes_dir.join(&variant);
615 let stamp_path: PathBuf = cache_dir.join(format!("{variant}.{WEB_THEME_STAMP_EXT}"));
616 let cached_stamp: String = fs::read_to_string(&stamp_path)
617 .map(|text: String| text.trim().to_string())
618 .unwrap_or_default();
619 let has_index: bool = variant_dir
620 .join(WEB_INDEX_HTML)
621 .metadata()
622 .map(|meta: Metadata| meta.len() > 0)
623 .unwrap_or(false);
624 let has_wasm: bool = variant_dir
625 .join(&expected_wasm)
626 .metadata()
627 .map(|meta: Metadata| meta.len() > 0)
628 .unwrap_or(false);
629 if cached_stamp == fingerprint && has_index && has_wasm {
630 cached_variants.push(variant);
631 continue;
632 }
633 let mut variant_cfg: WebBuildConfig = config.clone();
634 let variant_features: Vec<String> = if variant == WEB_THEME_DEFAULT_NAME {
635 Vec::new()
636 } else {
637 vec![variant.clone()]
638 };
639 variant_cfg
640 .set_out_dir(variant_dir)
641 .set_no_default_features(true)
642 .set_features(variant_features)
643 .set_archive_path(None)
644 .set_theme_variants(false);
645 let _: WebBuildReport = build_web_bundle(&variant_cfg)?;
646 fs::write(&stamp_path, format!("{fingerprint}\n").as_bytes())?;
647 built_variants.push(variant);
648 }
649 Ok(ThemeVariantBuildReport::new(
650 out_dir,
651 version,
652 built_variants,
653 cached_variants,
654 elapsed_millis(started),
655 ))
656}
657
658pub fn compute_workspace_source_fingerprint(repo_root: &Path) -> io::Result<String> {
668 let mut files: Vec<PathBuf> = Vec::new();
669 for root_file in [WEB_CARGO_TOML, WEB_CARGO_LOCK] {
670 let candidate: PathBuf = repo_root.join(root_file);
671 if candidate.is_file() {
672 files.push(candidate);
673 }
674 }
675 collect_files_if_dir(&repo_root.join(WEB_SRC_DIR_NAME), &mut files)?;
676 for crate_name in WEB_FINGERPRINT_CRATES.iter() {
677 let crate_dir: PathBuf = repo_root.join(crate_name);
678 let manifest: PathBuf = crate_dir.join(WEB_CARGO_TOML);
679 if manifest.is_file() {
680 files.push(manifest);
681 }
682 collect_files_if_dir(&crate_dir.join(WEB_SRC_DIR_NAME), &mut files)?;
683 }
684 files.sort();
685 let mut combined: Vec<u8> = Vec::new();
686 for path in files.into_iter() {
687 if let Ok(rel) = path.strip_prefix(repo_root) {
688 combined.extend_from_slice(rel.to_string_lossy().as_bytes());
689 combined.push(0u8);
690 }
691 let content: Vec<u8> = fs::read(&path)?;
692 combined.extend_from_slice(sha256_hex(&content).as_bytes());
693 combined.push(b'\n');
694 }
695 Ok(sha256_hex(&combined))
696}
697
698fn collect_files_if_dir(dir: &Path, out: &mut Vec<PathBuf>) -> io::Result<()> {
709 if !dir.is_dir() {
710 return Ok(());
711 }
712 for entry_res in fs::read_dir(dir)? {
713 let entry: DirEntry = entry_res?;
714 let path: PathBuf = entry.path();
715 if path.is_dir() {
716 collect_files_if_dir(&path, out)?;
717 } else if path.is_file() {
718 out.push(path);
719 }
720 }
721 Ok(())
722}
723
724fn resolve_lib_target_name(pkg_val: &Value, fallback_pkg: &str) -> String {
735 if let Some(targets) = pkg_val.get(META_KEY_TARGETS).and_then(Value::as_array) {
736 for target in targets.iter() {
737 let is_lib: bool = target
738 .get(META_KEY_KIND)
739 .and_then(Value::as_array)
740 .map(|kinds: &Vec<Value>| {
741 kinds.iter().any(|kind_val: &Value| {
742 let kind_str: &str = kind_val.as_str().unwrap_or("");
743 kind_str == META_KIND_CDYLIB
744 || kind_str == "lib"
745 || kind_str == META_KIND_RLIB
746 })
747 })
748 .unwrap_or(false);
749 if is_lib && let Some(name) = target.get(META_KEY_NAME).and_then(Value::as_str) {
750 return name.replace('-', "_");
751 }
752 }
753 }
754 fallback_pkg.replace('-', "_")
755}
756
757fn verify_wasm_bindgen_cli_version(expected: Option<&str>) -> io::Result<()> {
767 let output: Output = Command::new(WEB_BIN_WASM_BINDGEN)
768 .arg(WEB_ARG_VERSION)
769 .output()
770 .map_err(|err: Error| {
771 Error::new(
772 ErrorKind::NotFound,
773 format!("{ERR_WEB_WASM_BINDGEN_MISMATCH}: {err}"),
774 )
775 })?;
776 if !output.status.success() {
777 return Err(Error::other(ERR_WEB_WASM_BINDGEN_MISMATCH));
778 }
779 let stdout: String = String::from_utf8_lossy(&output.stdout).into_owned();
780 let actual: &str = stdout.split_whitespace().nth(1).unwrap_or("").trim();
781 if let Some(req_ver) = expected
782 && actual != req_ver
783 {
784 return Err(Error::new(
785 ErrorKind::InvalidData,
786 format!(
787 "{ERR_WEB_WASM_BINDGEN_MISMATCH}: installed {actual}, Cargo.lock requires {req_ver} (run: cargo install --locked wasm-bindgen-cli --version {req_ver})"
788 ),
789 ));
790 }
791 Ok(())
792}
793
794fn run_optional_wasm_opt(wasm_path: &Path, opt_tmp_path: &Path) -> bool {
805 let probe: io::Result<Output> = Command::new(WEB_BIN_WASM_OPT).arg(WEB_ARG_VERSION).output();
806 if !probe
807 .map(|out: Output| out.status.success())
808 .unwrap_or(false)
809 {
810 return false;
811 }
812 let status: io::Result<ExitStatus> = Command::new(WEB_BIN_WASM_OPT)
813 .args(WEB_WASM_OPT_FLAGS)
814 .arg(wasm_path)
815 .arg("-o")
816 .arg(opt_tmp_path)
817 .status();
818 if status
819 .map(|code: ExitStatus| code.success())
820 .unwrap_or(false)
821 && fs::rename(opt_tmp_path, wasm_path).is_ok()
822 {
823 true
824 } else {
825 let _: io::Result<()> = fs::remove_file(opt_tmp_path);
826 false
827 }
828}
829
830fn maybe_archive_web_dir(
842 repo_root: &Path,
843 out_dir: &Path,
844 config: &WebBuildConfig,
845) -> io::Result<Option<PathBuf>> {
846 if let Some(archive_rel) = config.try_get_archive_path() {
847 let dest: PathBuf = resolve_output_path(repo_root, archive_rel);
848 let _: u64 = archive_directory_auto(out_dir, &dest, None)?;
849 Ok(Some(dest))
850 } else {
851 Ok(None)
852 }
853}
854
855fn resolve_output_path(repo_root: &Path, candidate: &Path) -> PathBuf {
866 if candidate.is_absolute() {
867 candidate.to_path_buf()
868 } else {
869 repo_root.join(candidate)
870 }
871}
872
873fn run_streaming_command(cmd: &mut Command) -> io::Result<()> {
883 let status: ExitStatus = cmd
884 .stdout(Stdio::inherit())
885 .stderr(Stdio::inherit())
886 .status()?;
887 if status.success() {
888 Ok(())
889 } else {
890 Err(Error::other(format!("{ERR_WEB_CMD_FAILED}: {status}")))
891 }
892}
893
894fn elapsed_millis(started: SystemTime) -> u64 {
904 started
905 .elapsed()
906 .map(|dur: Duration| dur.as_millis() as u64)
907 .unwrap_or(0)
908}
909
910fn escape_web_html(input: &str) -> String {
920 let mut out: String = String::with_capacity(input.len());
921 for ch in input.chars() {
922 match ch {
923 '&' => out.push_str(WEB_HTML_AMP),
924 '<' => out.push_str(WEB_HTML_LT),
925 '>' => out.push_str(WEB_HTML_GT),
926 '"' => out.push_str(WEB_HTML_QUOT),
927 _ => out.push(ch),
928 }
929 }
930 out
931}