use super::*;
#[must_use]
pub fn normalize_web_asset_base(raw: &str) -> String {
let trimmed: &str = raw.trim();
if trimmed.is_empty() || trimmed == "." || trimmed == "./" {
return WEB_DEFAULT_ASSET_BASE.to_string();
}
if trimmed == "/" {
return "/".to_string();
}
let without_trailing: &str = trimmed.trim_end_matches('/');
if without_trailing.is_empty() {
return "/".to_string();
}
if without_trailing.starts_with('/') || without_trailing.starts_with("./") {
format!("{without_trailing}/")
} else {
format!("./{without_trailing}/")
}
}
#[must_use]
pub fn build_web_rustflags(existing: Option<&str>) -> String {
let mut parts: Vec<String> = Vec::new();
let base: &str = existing.map(str::trim).unwrap_or("");
if !base.is_empty() {
parts.push(base.to_string());
}
if !base.contains(WEB_RUSTFLAG_BULK_MEMORY_TOKEN) {
parts.push(WEB_RUSTFLAG_BULK_MEMORY.to_string());
}
if !base.contains(WEB_RUSTFLAG_GETRANDOM_TOKEN) {
parts.push(WEB_RUSTFLAG_GETRANDOM.to_string());
}
if !base.contains(WEB_RUSTFLAG_SIMD128_TOKEN) {
parts.push(WEB_RUSTFLAG_SIMD128.to_string());
}
parts.join(" ")
}
#[must_use]
pub fn transform_web_bindgen_glue(raw_js: &str, wasm_file: &str, asset_base: &str) -> String {
let normalized_base: String = normalize_web_asset_base(asset_base);
let wasm_href: String = format!("{normalized_base}{wasm_file}");
let single_url_expr: String = format!("new URL('{wasm_file}', import.meta.url)");
let double_url_expr: String = format!("new URL(\"{wasm_file}\", import.meta.url)");
let replacement: String = format!("'{wasm_href}'");
let rewritten: String = raw_js
.replace(&single_url_expr, &replacement)
.replace(&double_url_expr, &replacement);
let cleaned_lines: Vec<String> = rewritten
.lines()
.filter(|line: &&str| {
let trimmed: &str = line.trim_start();
!trimmed.starts_with(WEB_EXPORT_BRACE) && !trimmed.starts_with(WEB_EXPORT_DEFAULT)
})
.map(|line: &str| {
line.strip_prefix(WEB_EXPORT_PREFIX)
.unwrap_or(line)
.to_string()
})
.collect();
cleaned_lines.join("\n")
}
#[must_use]
pub fn render_zero_js_web_html(
title: &str,
asset_base: &str,
wasm_file: &str,
raw_js_glue: &str,
logo_data_uri: &str,
) -> String {
let normalized_base: String = normalize_web_asset_base(asset_base);
let wasm_href: String = format!("{normalized_base}{wasm_file}");
let cleaned_glue: String = transform_web_bindgen_glue(raw_js_glue, wasm_file, &normalized_base);
let safe_title: String = escape_web_html(title);
let mut html: String = String::with_capacity(
cleaned_glue.len() + safe_title.len() * 2 + logo_data_uri.len() * 3 + 4_096,
);
html.push_str(WEB_SHELL_HEAD_OPEN);
html.push_str(WEB_SHELL_PRELOAD_OPEN);
html.push_str(&wasm_href);
html.push_str(WEB_SHELL_PRELOAD_CLOSE);
html.push_str(WEB_SHELL_FAVICON_OPEN);
html.push_str(logo_data_uri);
html.push_str(WEB_SHELL_APPLE_ICON_MID);
html.push_str(logo_data_uri);
html.push_str(WEB_SHELL_TITLE_OPEN);
html.push_str(&safe_title);
html.push_str(WEB_SHELL_STYLE_AND_LOADER);
html.push_str(logo_data_uri);
html.push_str(WEB_SHELL_LOGO_END);
html.push_str(&safe_title);
html.push_str(WEB_SHELL_SCRIPT_OPEN);
html.push_str(&cleaned_glue);
html.push_str(WEB_SHELL_BOOT_OPEN);
html.push_str(&wasm_href);
html.push_str(WEB_SHELL_BOOT_BODY);
html
}
pub fn package_web_bundle_directory(
out_dir: &Path,
title: &str,
asset_base: &str,
version: &str,
custom_icon: Option<&Path>,
verify_release: bool,
) -> io::Result<ReleaseAssetManifest> {
let dir_meta: Metadata = fs::symlink_metadata(out_dir)?;
if dir_meta.file_type().is_symlink() || !dir_meta.is_dir() {
return Err(Error::new(
ErrorKind::InvalidInput,
format!("{ERR_WEB_SYMLINK_OUT}: {}", out_dir.display()),
));
}
let normalized_base: String = normalize_web_asset_base(asset_base);
let mut wasm_name: Option<String> = None;
let mut loader_path: Option<PathBuf> = None;
let mut removable: Vec<PathBuf> = Vec::new();
for entry_res in fs::read_dir(out_dir)? {
let entry: DirEntry = entry_res?;
let path: PathBuf = entry.path();
if !path.is_file() {
continue;
}
let name: String = entry.file_name().to_string_lossy().into_owned();
if name.ends_with(WEB_EXT_WASM) {
if name.ends_with(WEB_BG_WASM_SUFFIX) || wasm_name.is_none() {
wasm_name = Some(name);
}
} else if name.ends_with(WEB_EXT_JS) {
if loader_path.is_none() {
loader_path = Some(path.clone());
}
removable.push(path);
} else if name.ends_with(WEB_EXT_DTS) || name == WEB_PACKAGE_JSON || name == WEB_GITIGNORE {
removable.push(path);
}
}
let wasm_file: String =
wasm_name.ok_or_else(|| Error::new(ErrorKind::NotFound, ERR_WEB_DIR_WASM_MISSING))?;
let raw_js: String = match loader_path {
Some(js_path) => fs::read_to_string(&js_path)?,
None => WEB_FALLBACK_WBG_INIT.to_string(),
};
let _: Vec<PathBuf> = write_web_icons(out_dir, custom_icon)?;
let logo_data_uri: String = resolve_icon_data_uri(custom_icon)?;
let html: String =
render_zero_js_web_html(title, &normalized_base, &wasm_file, &raw_js, &logo_data_uri);
fs::write(out_dir.join(WEB_INDEX_HTML), html.as_bytes())?;
fs::write(out_dir.join(WEB_NOT_FOUND_HTML), html.as_bytes())?;
fs::write(out_dir.join(WEB_NOJEKYLL_NAME), [])?;
for path in removable.into_iter() {
let _: io::Result<()> = fs::remove_file(path);
}
let manifest: ReleaseAssetManifest = write_release_manifest(out_dir, version)?;
if verify_release {
verify_zero_js_web_bundle(out_dir, &normalized_base, &wasm_file, version)?;
}
Ok(manifest)
}
pub fn verify_zero_js_web_bundle(
out_dir: &Path,
asset_base: &str,
wasm_file: &str,
expected_version: &str,
) -> io::Result<ReleaseAssetManifest> {
for entry_res in fs::read_dir(out_dir)? {
let entry: DirEntry = entry_res?;
let path: PathBuf = entry.path();
if path.is_file()
&& path
.file_name()
.map(|name: &OsStr| name.to_string_lossy().ends_with(WEB_EXT_JS))
.unwrap_or(false)
{
return Err(Error::new(
ErrorKind::InvalidData,
format!("{ERR_WEB_EXTERNAL_JS_REMAIN}: {}", path.display()),
));
}
}
let _: AiSchemaScanReport = verify_no_ai_schema_leak(&out_dir.join(wasm_file))?;
let index_bytes: Vec<u8> = fs::read(out_dir.join(WEB_INDEX_HTML))?;
let fallback_bytes: Vec<u8> = fs::read(out_dir.join(WEB_NOT_FOUND_HTML))?;
if index_bytes != fallback_bytes {
return Err(Error::new(
ErrorKind::InvalidData,
ERR_WEB_FALLBACK_MISMATCH,
));
}
if !out_dir.join(WEB_NOJEKYLL_NAME).is_file() {
return Err(Error::new(ErrorKind::InvalidData, ERR_WEB_NOJEKYLL_MISSING));
}
let html: String = String::from_utf8(index_bytes)
.map_err(|err: FromUtf8Error| Error::new(ErrorKind::InvalidData, err.to_string()))?;
let normalized_base: String = normalize_web_asset_base(asset_base);
let expected_href: String = format!("{normalized_base}{wasm_file}");
let expected_js_lit: String = format!("'{expected_href}'");
let expected_preload: String =
format!("{WEB_SHELL_PRELOAD_OPEN}{expected_href}{WEB_SHELL_PRELOAD_CLOSE}");
let preload_trimmed: &str = expected_preload.trim_end();
if !html.contains(&expected_js_lit) || !html.contains(preload_trimmed) {
return Err(Error::new(ErrorKind::InvalidData, ERR_WEB_PRELOAD_OR_HREF));
}
if normalized_base == WEB_DEFAULT_ASSET_BASE {
let forbidden_single: String = format!("'/{wasm_file}'");
let forbidden_double: String = format!("\"/{wasm_file}\"");
if html.contains(&forbidden_single) || html.contains(&forbidden_double) {
return Err(Error::new(ErrorKind::InvalidData, ERR_WEB_ROOT_ABS_WASM));
}
}
let required: [&str; 5] = [
WEB_INDEX_HTML,
WEB_NOT_FOUND_HTML,
wasm_file,
WEB_FAVICON_PNG,
WEB_APPLE_TOUCH_PNG,
];
verify_release_manifest(out_dir, Some(expected_version), &required)
}
pub fn resolve_web_package_metadata(
repo_root: &Path,
package: &str,
) -> io::Result<WebPackageMetadata> {
let output: Output = Command::new(WEB_BIN_CARGO)
.current_dir(repo_root)
.args([
WEB_ARG_METADATA,
WEB_ARG_FORMAT_VERSION,
"1",
WEB_ARG_FILTER_PLATFORM,
WEB_RUST_TARGET,
])
.output()?;
if !output.status.success() {
let stderr: String = String::from_utf8_lossy(&output.stderr).into_owned();
return Err(Error::other(format!(
"{ERR_WEB_METADATA_PACKAGE}: {stderr}"
)));
}
let stdout: String = String::from_utf8_lossy(&output.stdout).into_owned();
let root_val: Value = from_str(&stdout)
.map_err(|err: serde_json::Error| Error::new(ErrorKind::InvalidData, err.to_string()))?;
let packages: &Vec<Value> = root_val
.get(META_KEY_PACKAGES)
.and_then(Value::as_array)
.ok_or_else(|| Error::new(ErrorKind::InvalidData, ERR_WEB_METADATA_PACKAGE))?;
let mut pkg_id_to_name_ver: BTreeMap<String, (String, String)> = BTreeMap::new();
let mut matched_pkg: Option<&Value> = None;
for pkg in packages.iter() {
let pkg_id: String = pkg
.get("id")
.and_then(Value::as_str)
.unwrap_or("")
.to_string();
let pkg_name: String = pkg
.get(META_KEY_NAME)
.and_then(Value::as_str)
.unwrap_or("")
.to_string();
let pkg_ver: String = pkg
.get(META_KEY_VERSION)
.and_then(Value::as_str)
.unwrap_or("")
.to_string();
if pkg_name == package {
matched_pkg = Some(pkg);
}
let _: Option<(String, String)> = pkg_id_to_name_ver.insert(pkg_id, (pkg_name, pkg_ver));
}
let pkg_val: &Value = matched_pkg.ok_or_else(|| {
Error::new(
ErrorKind::NotFound,
format!("{ERR_WEB_METADATA_PACKAGE}: {package}"),
)
})?;
let pkg_id: &str = pkg_val.get("id").and_then(Value::as_str).unwrap_or("");
let version: String = pkg_val
.get(META_KEY_VERSION)
.and_then(Value::as_str)
.unwrap_or(WEB_FALLBACK_VERSION)
.to_string();
let lib_name: String = resolve_lib_target_name(pkg_val, package);
let mut theme_features: Vec<String> = Vec::new();
if let Some(feat_map) = pkg_val.get(META_KEY_FEATURES).and_then(Value::as_object) {
for key in feat_map.keys() {
if key.starts_with(WEB_THEME_FEATURE_PREFIX) {
theme_features.push(key.clone());
}
}
}
theme_features.sort();
let target_dir: PathBuf = match env::var_os(ENV_CARGO_TARGET_DIR) {
Some(val) if !val.is_empty() => PathBuf::from(val),
_ => root_val
.get(META_KEY_TARGET_DIR)
.and_then(Value::as_str)
.map(PathBuf::from)
.unwrap_or_else(|| repo_root.join(WEB_TARGET_DIR_NAME)),
};
let mut wb_version: Option<String> = None;
if let Some(nodes) = root_val
.get(META_KEY_RESOLVE)
.and_then(|res: &Value| res.get(META_KEY_NODES))
.and_then(Value::as_array)
{
for node in nodes.iter() {
if node.get("id").and_then(Value::as_str) == Some(pkg_id)
&& let Some(deps) = node.get(META_KEY_DEPENDENCIES).and_then(Value::as_array)
{
for dep_id_val in deps.iter() {
if let Some(dep_id) = dep_id_val.as_str()
&& let Some((dep_name, dep_ver)) = pkg_id_to_name_ver.get(dep_id)
&& dep_name == DEP_NAME_WASM_BINDGEN
{
wb_version = Some(dep_ver.clone());
break;
}
}
}
}
}
Ok(WebPackageMetadata::new(
package.to_string(),
lib_name,
version,
target_dir,
wb_version,
theme_features,
))
}
pub fn build_web_bundle(config: &WebBuildConfig) -> io::Result<WebBuildReport> {
let started: SystemTime = SystemTime::now();
let repo_root: &Path = config.get_repo_root().as_path();
let out_dir: PathBuf = resolve_output_path(repo_root, config.get_out_dir());
if let Ok(meta) = fs::symlink_metadata(&out_dir)
&& meta.file_type().is_symlink()
{
return Err(Error::new(
ErrorKind::InvalidInput,
format!("{ERR_WEB_SYMLINK_OUT}: {}", out_dir.display()),
));
}
if out_dir.exists() {
fs::remove_dir_all(&out_dir)?;
}
fs::create_dir_all(&out_dir)?;
let metadata: WebPackageMetadata =
resolve_web_package_metadata(repo_root, config.get_package())?;
let version: String = match config.try_get_version() {
Some(explicit) if !explicit.trim().is_empty() => explicit.trim().to_string(),
_ => metadata.get_version().clone(),
};
let lib_name: &str = metadata.get_lib_name().as_str();
let base_url: String = normalize_web_asset_base(config.get_base_url());
let rustflags: String = build_web_rustflags(env::var(ENV_RUSTFLAGS).ok().as_deref());
let mut cargo_args: Vec<String> = vec![
WEB_ARG_BUILD.to_string(),
WEB_ARG_TARGET.to_string(),
WEB_RUST_TARGET.to_string(),
WEB_ARG_LIB.to_string(),
WEB_ARG_PACKAGE.to_string(),
config.get_package().clone(),
];
if config.get_release() {
cargo_args.push(WEB_ARG_RELEASE.to_string());
}
if config.get_no_default_features() {
cargo_args.push(WEB_ARG_NO_DEFAULT_FEATURES.to_string());
}
if !config.get_features().is_empty() {
cargo_args.push(WEB_ARG_FEATURES.to_string());
cargo_args.push(config.get_features().join(","));
}
let mut cargo_cmd: Command = Command::new(WEB_BIN_CARGO);
let _: &mut Command = cargo_cmd
.current_dir(repo_root)
.args(&cargo_args)
.env(ENV_RUSTFLAGS, &rustflags);
if config.get_release() {
let _: &mut Command = cargo_cmd.env(ENV_CARGO_RELEASE_PANIC, PANIC_ABORT_VALUE);
}
run_streaming_command(&mut cargo_cmd)?;
let profile_dir: &str = if config.get_release() {
WEB_PROFILE_RELEASE
} else {
WEB_PROFILE_DEBUG
};
let compiled_wasm: PathBuf = metadata
.get_target_dir()
.join(WEB_RUST_TARGET)
.join(profile_dir)
.join(format!("{lib_name}{WEB_EXT_WASM}"));
if !compiled_wasm.is_file() {
return Err(Error::new(
ErrorKind::NotFound,
format!(
"{ERR_WEB_COMPILED_WASM_MISSING}: {}",
compiled_wasm.display()
),
));
}
let custom_icon: Option<&Path> = config.try_get_icon_path().as_deref();
if config.get_raw_wasm() {
let wasm_file: String = format!("{lib_name}{WEB_EXT_WASM}");
let dest_wasm: PathBuf = out_dir.join(&wasm_file);
let wasm_bytes: u64 = fs::copy(&compiled_wasm, &dest_wasm)?;
if config.get_release() && config.get_verify() {
let _: AiSchemaScanReport = verify_no_ai_schema_leak(&dest_wasm)?;
}
let icon_paths: Vec<PathBuf> = write_web_raw_icons(&out_dir, custom_icon)?;
let plans: Vec<BuildPlan> =
resolve_build_plans(TargetArg::Web, RenderArg::Auto, config.get_release());
let plan_json: String = to_string_pretty(&plans)
.map_err(|err: serde_json::Error| Error::other(err.to_string()))?;
fs::write(out_dir.join(WEB_BUILD_PLAN_JSON), plan_json.as_bytes())?;
let archive_written: Option<PathBuf> = maybe_archive_web_dir(repo_root, &out_dir, config)?;
let elapsed_ms: u64 = elapsed_millis(started);
return Ok(WebBuildReport {
package: config.get_package().clone(),
version,
out_dir,
base_url,
wasm_file,
wasm_bytes,
wasm_opt_applied: false,
raw_wasm: true,
file_count: icon_paths.len() + 2,
elapsed_ms,
manifest_path: None,
archive_path: archive_written,
});
}
verify_wasm_bindgen_cli_version(metadata.try_get_wasm_bindgen_version().as_deref())?;
let mut wb_cmd: Command = Command::new(WEB_BIN_WASM_BINDGEN);
let _: &mut Command = wb_cmd.current_dir(repo_root).args([
WEB_ARG_TARGET,
WEB_TARGET_MODE,
WEB_ARG_NO_TS,
WEB_ARG_OUT_DIR,
&out_dir.to_string_lossy(),
WEB_ARG_OUT_NAME,
lib_name,
&compiled_wasm.to_string_lossy(),
]);
run_streaming_command(&mut wb_cmd)?;
let wasm_file: String = format!("{lib_name}{WEB_BG_WASM_SUFFIX}");
let bg_wasm_path: PathBuf = out_dir.join(&wasm_file);
let env_skip_opt: bool = env::var(ENV_SKIP_WASM_OPT)
.map(|val: String| val.trim() == "1")
.unwrap_or(false);
let wasm_opt_applied: bool =
if config.get_release() && !config.get_skip_wasm_opt() && !env_skip_opt {
run_optional_wasm_opt(
&bg_wasm_path,
&out_dir.join(format!("{lib_name}{WEB_OPT_WASM_SUFFIX}")),
)
} else {
false
};
let manifest: ReleaseAssetManifest = package_web_bundle_directory(
&out_dir,
config.get_title(),
&base_url,
&version,
custom_icon,
config.get_verify() && config.get_release(),
)?;
let wasm_bytes: u64 = fs::metadata(&bg_wasm_path)?.len();
let archive_written: Option<PathBuf> = maybe_archive_web_dir(repo_root, &out_dir, config)?;
let elapsed_ms: u64 = elapsed_millis(started);
Ok(WebBuildReport {
package: config.get_package().clone(),
version,
out_dir: out_dir.clone(),
base_url,
wasm_file,
wasm_bytes,
wasm_opt_applied,
raw_wasm: false,
file_count: manifest.get_files().len(),
elapsed_ms,
manifest_path: Some(out_dir.join(RELEASE_MANIFEST_NAME)),
archive_path: archive_written,
})
}
pub fn build_web_theme_variants(config: &WebBuildConfig) -> io::Result<ThemeVariantBuildReport> {
let started: SystemTime = SystemTime::now();
let repo_root: &Path = config.get_repo_root().as_path();
let out_dir: PathBuf = resolve_output_path(repo_root, config.get_out_dir());
let metadata: WebPackageMetadata =
resolve_web_package_metadata(repo_root, config.get_package())?;
let version: String = match config.try_get_version() {
Some(explicit) if !explicit.trim().is_empty() => explicit.trim().to_string(),
_ => metadata.get_version().clone(),
};
let fingerprint: String = compute_workspace_source_fingerprint(repo_root)?;
let cache_dir: PathBuf = out_dir.join(WEB_THEME_CACHE_SUBDIR);
let themes_dir: PathBuf = out_dir.join(WEB_THEMES_SUBDIR);
fs::create_dir_all(&cache_dir)?;
fs::create_dir_all(&themes_dir)?;
let mut variants: Vec<String> = vec![WEB_THEME_DEFAULT_NAME.to_string()];
for feature in metadata.get_theme_features().iter() {
variants.push(feature.clone());
}
let expected_wasm: String = format!("{}{WEB_BG_WASM_SUFFIX}", metadata.get_lib_name());
let mut built_variants: Vec<String> = Vec::new();
let mut cached_variants: Vec<String> = Vec::new();
for variant in variants.into_iter() {
let variant_dir: PathBuf = themes_dir.join(&variant);
let stamp_path: PathBuf = cache_dir.join(format!("{variant}.{WEB_THEME_STAMP_EXT}"));
let cached_stamp: String = fs::read_to_string(&stamp_path)
.map(|text: String| text.trim().to_string())
.unwrap_or_default();
let has_index: bool = variant_dir
.join(WEB_INDEX_HTML)
.metadata()
.map(|meta: Metadata| meta.len() > 0)
.unwrap_or(false);
let has_wasm: bool = variant_dir
.join(&expected_wasm)
.metadata()
.map(|meta: Metadata| meta.len() > 0)
.unwrap_or(false);
if cached_stamp == fingerprint && has_index && has_wasm {
cached_variants.push(variant);
continue;
}
let mut variant_cfg: WebBuildConfig = config.clone();
let variant_features: Vec<String> = if variant == WEB_THEME_DEFAULT_NAME {
Vec::new()
} else {
vec![variant.clone()]
};
variant_cfg
.set_out_dir(variant_dir)
.set_no_default_features(true)
.set_features(variant_features)
.set_archive_path(None)
.set_theme_variants(false);
let _: WebBuildReport = build_web_bundle(&variant_cfg)?;
fs::write(&stamp_path, format!("{fingerprint}\n").as_bytes())?;
built_variants.push(variant);
}
Ok(ThemeVariantBuildReport::new(
out_dir,
version,
built_variants,
cached_variants,
elapsed_millis(started),
))
}
pub fn compute_workspace_source_fingerprint(repo_root: &Path) -> io::Result<String> {
let mut files: Vec<PathBuf> = Vec::new();
for root_file in [WEB_CARGO_TOML, WEB_CARGO_LOCK] {
let candidate: PathBuf = repo_root.join(root_file);
if candidate.is_file() {
files.push(candidate);
}
}
collect_files_if_dir(&repo_root.join(WEB_SRC_DIR_NAME), &mut files)?;
for crate_name in WEB_FINGERPRINT_CRATES.iter() {
let crate_dir: PathBuf = repo_root.join(crate_name);
let manifest: PathBuf = crate_dir.join(WEB_CARGO_TOML);
if manifest.is_file() {
files.push(manifest);
}
collect_files_if_dir(&crate_dir.join(WEB_SRC_DIR_NAME), &mut files)?;
}
files.sort();
let mut combined: Vec<u8> = Vec::new();
for path in files.into_iter() {
if let Ok(rel) = path.strip_prefix(repo_root) {
combined.extend_from_slice(rel.to_string_lossy().as_bytes());
combined.push(0u8);
}
let content: Vec<u8> = fs::read(&path)?;
combined.extend_from_slice(sha256_hex(&content).as_bytes());
combined.push(b'\n');
}
Ok(sha256_hex(&combined))
}
fn collect_files_if_dir(dir: &Path, out: &mut Vec<PathBuf>) -> io::Result<()> {
if !dir.is_dir() {
return Ok(());
}
for entry_res in fs::read_dir(dir)? {
let entry: DirEntry = entry_res?;
let path: PathBuf = entry.path();
if path.is_dir() {
collect_files_if_dir(&path, out)?;
} else if path.is_file() {
out.push(path);
}
}
Ok(())
}
fn resolve_lib_target_name(pkg_val: &Value, fallback_pkg: &str) -> String {
if let Some(targets) = pkg_val.get(META_KEY_TARGETS).and_then(Value::as_array) {
for target in targets.iter() {
let is_lib: bool = target
.get(META_KEY_KIND)
.and_then(Value::as_array)
.map(|kinds: &Vec<Value>| {
kinds.iter().any(|kind_val: &Value| {
let kind_str: &str = kind_val.as_str().unwrap_or("");
kind_str == META_KIND_CDYLIB
|| kind_str == "lib"
|| kind_str == META_KIND_RLIB
})
})
.unwrap_or(false);
if is_lib && let Some(name) = target.get(META_KEY_NAME).and_then(Value::as_str) {
return name.replace('-', "_");
}
}
}
fallback_pkg.replace('-', "_")
}
fn verify_wasm_bindgen_cli_version(expected: Option<&str>) -> io::Result<()> {
let output: Output = Command::new(WEB_BIN_WASM_BINDGEN)
.arg(WEB_ARG_VERSION)
.output()
.map_err(|err: Error| {
Error::new(
ErrorKind::NotFound,
format!("{ERR_WEB_WASM_BINDGEN_MISMATCH}: {err}"),
)
})?;
if !output.status.success() {
return Err(Error::other(ERR_WEB_WASM_BINDGEN_MISMATCH));
}
let stdout: String = String::from_utf8_lossy(&output.stdout).into_owned();
let actual: &str = stdout.split_whitespace().nth(1).unwrap_or("").trim();
if let Some(req_ver) = expected
&& actual != req_ver
{
return Err(Error::new(
ErrorKind::InvalidData,
format!(
"{ERR_WEB_WASM_BINDGEN_MISMATCH}: installed {actual}, Cargo.lock requires {req_ver} (run: cargo install --locked wasm-bindgen-cli --version {req_ver})"
),
));
}
Ok(())
}
fn run_optional_wasm_opt(wasm_path: &Path, opt_tmp_path: &Path) -> bool {
let probe: io::Result<Output> = Command::new(WEB_BIN_WASM_OPT).arg(WEB_ARG_VERSION).output();
if !probe
.map(|out: Output| out.status.success())
.unwrap_or(false)
{
return false;
}
let status: io::Result<ExitStatus> = Command::new(WEB_BIN_WASM_OPT)
.args(WEB_WASM_OPT_FLAGS)
.arg(wasm_path)
.arg("-o")
.arg(opt_tmp_path)
.status();
if status
.map(|code: ExitStatus| code.success())
.unwrap_or(false)
&& fs::rename(opt_tmp_path, wasm_path).is_ok()
{
true
} else {
let _: io::Result<()> = fs::remove_file(opt_tmp_path);
false
}
}
fn maybe_archive_web_dir(
repo_root: &Path,
out_dir: &Path,
config: &WebBuildConfig,
) -> io::Result<Option<PathBuf>> {
if let Some(archive_rel) = config.try_get_archive_path() {
let dest: PathBuf = resolve_output_path(repo_root, archive_rel);
let _: u64 = archive_directory_auto(out_dir, &dest, None)?;
Ok(Some(dest))
} else {
Ok(None)
}
}
fn resolve_output_path(repo_root: &Path, candidate: &Path) -> PathBuf {
if candidate.is_absolute() {
candidate.to_path_buf()
} else {
repo_root.join(candidate)
}
}
fn run_streaming_command(cmd: &mut Command) -> io::Result<()> {
let status: ExitStatus = cmd
.stdout(Stdio::inherit())
.stderr(Stdio::inherit())
.status()?;
if status.success() {
Ok(())
} else {
Err(Error::other(format!("{ERR_WEB_CMD_FAILED}: {status}")))
}
}
fn elapsed_millis(started: SystemTime) -> u64 {
started
.elapsed()
.map(|dur: Duration| dur.as_millis() as u64)
.unwrap_or(0)
}
fn escape_web_html(input: &str) -> String {
let mut out: String = String::with_capacity(input.len());
for ch in input.chars() {
match ch {
'&' => out.push_str(WEB_HTML_AMP),
'<' => out.push_str(WEB_HTML_LT),
'>' => out.push_str(WEB_HTML_GT),
'"' => out.push_str(WEB_HTML_QUOT),
_ => out.push(ch),
}
}
out
}