1use super::*;
2
3fn escape_bundle_html(raw: &str) -> String {
13 let mut out: String = String::with_capacity(raw.len());
14 for ch in raw.chars() {
15 match ch {
16 '&' => out.push_str(BUNDLE_ESC_AMP),
17 '<' => out.push_str(BUNDLE_ESC_LT),
18 '>' => out.push_str(BUNDLE_ESC_GT),
19 '"' => out.push_str(BUNDLE_ESC_QUOT),
20 _ => out.push(ch),
21 }
22 }
23 out
24}
25
26fn toml_path_string(path: &Path) -> String {
36 path.display()
37 .to_string()
38 .replace('\\', "\\\\")
39 .replace('"', "\\\"")
40}
41
42fn render_wrapper_cargo_toml(manifest_dir: &Path) -> String {
52 let pkg_ver: &str = env!("CARGO_PKG_VERSION");
53 let has_local_crate: bool = manifest_dir.join(BUNDLE_CARGO_TOML).is_file();
54 let workspace_root: Option<&Path> = manifest_dir.parent().filter(|parent: &&Path| {
55 parent.join(BUNDLE_CARGO_TOML).is_file()
56 && parent
57 .join(BUNDLE_DIR_CORE)
58 .join(BUNDLE_CARGO_TOML)
59 .is_file()
60 && parent.join(BUNDLE_DIR_UI).join(BUNDLE_CARGO_TOML).is_file()
61 });
62 let mut toml: String = String::with_capacity(1024);
63 let _: fmt::Result = writeln!(toml, "[workspace]\n");
64 let _: fmt::Result = writeln!(toml, "[package]");
65 let _: fmt::Result = writeln!(toml, "name = \"{BUNDLE_CRATE_NAME}\"");
66 let _: fmt::Result = writeln!(toml, "version = \"{pkg_ver}\"");
67 let _: fmt::Result = writeln!(toml, "edition = \"2024\"\n");
68 let _: fmt::Result = writeln!(toml, "[lib]");
69 let _: fmt::Result = writeln!(toml, "crate-type = [\"cdylib\"]\n");
70 let _: fmt::Result = writeln!(toml, "[dependencies]");
71 if has_local_crate {
72 let docs_path: String = toml_path_string(manifest_dir);
73 let _: fmt::Result = writeln!(toml, "euv-docs = {{ path = \"{docs_path}\" }}");
74 } else {
75 let _: fmt::Result = writeln!(toml, "euv-docs = \"={pkg_ver}\"");
76 }
77 let _: fmt::Result = writeln!(toml, "wasm-bindgen = \"{BUNDLE_WASM_BINDGEN_VER}\"\n");
78 if let Some(ws_root) = workspace_root {
79 let root_p: String = toml_path_string(ws_root);
80 let core_p: String = toml_path_string(&ws_root.join(BUNDLE_DIR_CORE));
81 let macros_p: String = toml_path_string(&ws_root.join(BUNDLE_DIR_MACROS));
82 let ui_p: String = toml_path_string(&ws_root.join(BUNDLE_DIR_UI));
83 let docs_p: String = toml_path_string(manifest_dir);
84 let _: fmt::Result = writeln!(toml, "[patch.crates-io]");
85 let _: fmt::Result = writeln!(toml, "euv = {{ path = \"{root_p}\" }}");
86 let _: fmt::Result = writeln!(toml, "euv-core = {{ path = \"{core_p}\" }}");
87 let _: fmt::Result = writeln!(toml, "euv-macros = {{ path = \"{macros_p}\" }}");
88 let _: fmt::Result = writeln!(toml, "euv-ui = {{ path = \"{ui_p}\" }}");
89 let _: fmt::Result = writeln!(toml, "euv-docs = {{ path = \"{docs_p}\" }}\n");
90 }
91 let _: fmt::Result = writeln!(toml, "[profile.release]");
92 let _: fmt::Result = writeln!(toml, "opt-level = \"z\"");
93 let _: fmt::Result = writeln!(toml, "lto = true");
94 let _: fmt::Result = writeln!(toml, "codegen-units = 1");
95 let _: fmt::Result = writeln!(toml, "panic = \"abort\"");
96 let _: fmt::Result = writeln!(toml, "strip = \"debuginfo\"\n");
97 let _: fmt::Result = writeln!(toml, "[package.metadata.wasm-pack.profile.release]");
98 let _: fmt::Result = writeln!(toml, "wasm-opt = false");
99 toml
100}
101
102fn is_forbidden_asset_file(path: &Path) -> bool {
112 let lower: String = path
113 .file_name()
114 .map(|s: &OsStr| s.to_string_lossy().to_ascii_lowercase())
115 .unwrap_or_default();
116 lower.ends_with(BUNDLE_JS_EXT)
117 || lower.ends_with(BUNDLE_MJS_EXT)
118 || lower.ends_with(BUNDLE_CSS_EXT)
119 || BUNDLE_SKIP_FILES
120 .iter()
121 .any(|skip: &&str| lower.eq_ignore_ascii_case(skip))
122}
123
124fn copy_public_tree_real(src: &Path, dst: &Path, is_top_level: bool) -> io::Result<()> {
136 fs::create_dir_all(dst)?;
137 for entry_res in fs::read_dir(src)? {
138 let entry: DirEntry = entry_res?;
139 let file_name: OsString = entry.file_name();
140 let name_str: Cow<'_, str> = file_name.to_string_lossy();
141 if name_str.starts_with('.') {
142 continue;
143 }
144 let path: PathBuf = entry.path();
145 if path.is_dir() {
146 if is_top_level
147 && BUNDLE_FORBIDDEN_DIRS
148 .iter()
149 .any(|f: &&str| name_str.eq_ignore_ascii_case(f))
150 {
151 continue;
152 }
153 copy_public_tree_real(&path, &dst.join(&file_name), false)?;
154 } else if path.is_file() && !is_forbidden_asset_file(&path) {
155 let target: PathBuf = dst.join(&file_name);
156 let resolved_src: PathBuf = fs::canonicalize(&path).unwrap_or(path);
157 let _: u64 = fs::copy(&resolved_src, &target)?;
158 }
159 }
160 Ok(())
161}
162
163fn copy_site_public_assets(src_dir: &Path, out_dir: &Path) -> io::Result<()> {
174 let direct_public: PathBuf = src_dir.join(BUNDLE_PUBLIC_DIR);
175 if direct_public.is_dir() {
176 return copy_public_tree_real(&direct_public, out_dir, true);
177 }
178 if let Some(parent) = src_dir.parent() {
179 let parent_public: PathBuf = parent.join(BUNDLE_PUBLIC_DIR);
180 if parent_public.is_dir() {
181 return copy_public_tree_real(&parent_public, out_dir, true);
182 }
183 }
184 Ok(())
185}
186
187pub fn transform_wasm_glue_inline(raw_js: &str, wasm_file: &str) -> String {
198 let single_pat: String = format!("new URL('{wasm_file}', import.meta.url)");
199 let double_pat: String = format!("new URL(\"{wasm_file}\", import.meta.url)");
200 let target_ref: String = format!("'./pkg/{wasm_file}'");
201 let rewritten: String = raw_js
202 .replace(&single_pat, &target_ref)
203 .replace(&double_pat, &target_ref);
204 let mut out: String = String::with_capacity(rewritten.len());
205 for line in rewritten.lines() {
206 let trimmed: &str = line.trim_start();
207 if trimmed.starts_with(BUNDLE_EXPORT_BRACE) || trimmed.starts_with(BUNDLE_EXPORT_DEFAULT) {
208 continue;
209 }
210 if let Some(rest) = line.strip_prefix(BUNDLE_EXPORT_PREFIX) {
211 out.push_str(rest);
212 } else {
213 out.push_str(line);
214 }
215 out.push('\n');
216 }
217 out
218}
219
220#[must_use]
234pub fn render_wasm_locale_shell_html(
235 lang: &str,
236 title: &str,
237 description: &str,
238 inline_glue: &str,
239 wasm_file: &str,
240) -> String {
241 let safe_title: String = escape_bundle_html(title);
242 let mut html: String =
243 String::with_capacity(inline_glue.len() + safe_title.len() * 2 + description.len() + 4096);
244 html.push_str(BUNDLE_HTML_DOCTYPE_OPEN);
245 html.push_str(&escape_bundle_html(lang));
246 html.push_str(BUNDLE_HTML_HEAD_MID);
247 html.push_str(&escape_bundle_html(description));
248 html.push_str(BUNDLE_HTML_DESC_END);
249 html.push_str(&safe_title);
250 html.push_str(BUNDLE_HTML_STYLE_AND_BODY);
251 html.push_str(&safe_title);
252 html.push_str(BUNDLE_HTML_LOADER_END);
253 html.push_str(inline_glue);
254 html.push_str(BUNDLE_HTML_BOOT_PREFIX);
255 html.push_str(wasm_file);
256 html.push_str(BUNDLE_HTML_BOOT_SUFFIX);
257 html
258}
259
260fn select_locales(unique: &[DocLocaleConfig], filter: Option<&str>) -> Vec<DocLocaleConfig> {
271 let Some(raw_filter) = filter else {
272 return unique.to_vec();
273 };
274 let needle: String = raw_filter.trim().trim_matches('/').to_ascii_lowercase();
275 unique
276 .iter()
277 .filter(|loc: &&DocLocaleConfig| {
278 loc.get_dir().trim().eq_ignore_ascii_case(&needle)
279 || loc
280 .get_prefix()
281 .trim_matches('/')
282 .eq_ignore_ascii_case(&needle)
283 || loc.get_lang().trim().eq_ignore_ascii_case(&needle)
284 || loc
285 .get_label()
286 .trim()
287 .eq_ignore_ascii_case(raw_filter.trim())
288 })
289 .cloned()
290 .collect()
291}
292
293fn compile_locale_wasm_bundle(
308 site: &DocSite,
309 locale: &DocLocaleConfig,
310 locale_out: &Path,
311 builder_dir: &Path,
312 shared_target_dir: &Path,
313 release: bool,
314) -> io::Result<()> {
315 let src_dir: PathBuf = builder_dir.join(BUNDLE_SRC_DIR);
316 fs::create_dir_all(&src_dir)?;
317 let packed: PackedSiteBundle =
318 pack_site_bundle(site).map_err(|err: DocsCodecError| Error::other(err.to_string()))?;
319 fs::write(
320 src_dir.join(BUNDLE_SHELL_JSON_FILE),
321 packed.get_shell_json(),
322 )?;
323 fs::write(
324 src_dir.join(BUNDLE_BODIES_BIN_FILE),
325 packed.get_compressed_bodies(),
326 )?;
327 let safe_dir: String = slugify(locale.get_dir());
328 let suffix: &str = if safe_dir.is_empty() {
329 BUNDLE_DEFAULT_LOCALE_SUFFIX
330 } else {
331 safe_dir.as_str()
332 };
333 let bundle_name: String = format!("{BUNDLE_NAME_PREFIX}{suffix}");
334 let pkg_dir: PathBuf = locale_out.join(BUNDLE_PKG_DIR);
335 fs::create_dir_all(&pkg_dir)?;
336 let mut cmd: Command = Command::new(BUNDLE_WASM_PACK_BIN);
337 let _: &mut Command = cmd
338 .current_dir(builder_dir)
339 .env(BUNDLE_ENV_TARGET_DIR, shared_target_dir)
340 .env_remove(BUNDLE_ENV_RUSTC_WRAPPER)
341 .arg(BUNDLE_ARG_BUILD)
342 .arg(BUNDLE_ARG_TARGET)
343 .arg(BUNDLE_ARG_WEB)
344 .arg(BUNDLE_ARG_NO_TS)
345 .arg(if release {
346 DOCS_FLAG_RELEASE
347 } else {
348 BUNDLE_ARG_DEV
349 })
350 .arg(BUNDLE_ARG_OUT_DIR)
351 .arg(&pkg_dir)
352 .arg(BUNDLE_ARG_OUT_NAME)
353 .arg(&bundle_name);
354 let status: ExitStatus = cmd
355 .status()
356 .map_err(|err: Error| Error::other(format!("{BUNDLE_ERR_WASM_PACK}: {err}")))?;
357 if !status.success() {
358 return Err(Error::other(format!(
359 "{BUNDLE_ERR_WASM_PACK} (locale={} status={status})",
360 locale.get_dir()
361 )));
362 }
363 let wasm_file: String = format!("{bundle_name}{BUNDLE_BG_WASM_SUFFIX}");
364 let js_path: PathBuf = pkg_dir.join(format!("{bundle_name}{BUNDLE_JS_EXT}"));
365 let raw_js: String = fs::read_to_string(&js_path)?;
366 let inline_glue: String = transform_wasm_glue_inline(&raw_js, &wasm_file);
367 let html: String = render_wasm_locale_shell_html(
368 site.resolved_lang(),
369 site.get_title(),
370 site.get_tagline(),
371 &inline_glue,
372 &wasm_file,
373 );
374 fs::write(locale_out.join(BUNDLE_INDEX_HTML), &html)?;
375 fs::write(locale_out.join(BUNDLE_NOT_FOUND_HTML), &html)?;
376 for entry_res in fs::read_dir(&pkg_dir)? {
377 let entry: DirEntry = entry_res?;
378 let path: PathBuf = entry.path();
379 if path.is_file()
380 && path
381 .file_name()
382 .and_then(|s: &OsStr| s.to_str())
383 .is_none_or(|name: &str| name != wasm_file)
384 {
385 fs::remove_file(&path)?;
386 }
387 }
388 Ok(())
389}
390
391pub fn build_multilocale_wasm_site(
404 src_dir: &Path,
405 out_dir: &Path,
406 release: bool,
407 single_locale: Option<&str>,
408) -> io::Result<GeneratedSiteReport> {
409 let cfg: DocSiteConfig = load_site_config(src_dir)
410 .filter(|c: &DocSiteConfig| !c.get_locales().is_empty())
411 .ok_or_else(|| Error::new(ErrorKind::NotFound, BUNDLE_ERR_NO_LOCALES))?;
412 let unique: Vec<DocLocaleConfig> = unique_locales(cfg.get_locales());
413 let targets: Vec<DocLocaleConfig> = select_locales(&unique, single_locale);
414 if targets.is_empty() {
415 return Err(Error::new(
416 ErrorKind::InvalidInput,
417 BUNDLE_ERR_NO_MATCHING_LOCALE,
418 ));
419 }
420 fs::create_dir_all(out_dir)?;
421 copy_site_public_assets(src_dir, out_dir)?;
422 let abs_out: PathBuf = fs::canonicalize(out_dir).unwrap_or_else(|_| out_dir.to_path_buf());
423 let temp_root: PathBuf = env::temp_dir();
424 let builder_dir: PathBuf = temp_root.join(BUNDLE_BUILDER_DIR);
425 let shared_target_dir: PathBuf = temp_root.join(BUNDLE_TARGET_DIR);
426 fs::create_dir_all(builder_dir.join(BUNDLE_SRC_DIR))?;
427 let manifest_dir: PathBuf = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
428 let cargo_toml: String = render_wrapper_cargo_toml(&manifest_dir);
429 let cargo_toml_path: PathBuf = builder_dir.join(BUNDLE_CARGO_TOML);
430 if fs::read_to_string(&cargo_toml_path).ok().as_deref() != Some(cargo_toml.as_str()) {
431 fs::write(&cargo_toml_path, &cargo_toml)?;
432 }
433 let lib_rs_path: PathBuf = builder_dir.join(BUNDLE_SRC_DIR).join(BUNDLE_LIB_RS);
434 if fs::read_to_string(&lib_rs_path).ok().as_deref() != Some(BUNDLE_WRAPPER_LIB_RS) {
435 fs::write(&lib_rs_path, BUNDLE_WRAPPER_LIB_RS)?;
436 }
437 let mut total_pages: usize = 0;
438 for (idx, locale) in targets.iter().enumerate() {
439 let is_root_locale: bool =
440 locale.get_prefix().trim() == "/" || (single_locale.is_some() && idx == 0);
441 let locale_out: PathBuf = if is_root_locale {
442 abs_out.clone()
443 } else {
444 let sub: &str = locale.get_dir().trim().trim_matches('/');
445 abs_out.join(sub)
446 };
447 let site: DocSite = load_locale_site(src_dir, &cfg, locale, Some(&abs_out))?;
448 total_pages += site.get_pages().len();
449 compile_locale_wasm_bundle(
450 &site,
451 locale,
452 &locale_out,
453 &builder_dir,
454 &shared_target_dir,
455 release,
456 )?;
457 }
458 let generated_at: String = Utc::now().to_rfc3339();
459 Ok(GeneratedSiteReport::new(
460 total_pages,
461 generated_at,
462 out_dir.join(BUNDLE_INDEX_HTML).display().to_string(),
463 ))
464}