1#![forbid(unsafe_code)]
2
3use std::collections::BTreeSet;
4use std::ffi::OsStr;
5use std::fs;
6use std::path::{Path, PathBuf};
7use std::process::Command;
8
9use anyhow::{Context, Result, anyhow};
10use clap::{ArgAction, Parser, ValueEnum};
11use regex::Regex;
12use semver::Version;
13use serde::Serialize;
14use serde_json::json;
15use tempfile::TempDir;
16use tracing::info;
17use walkdir::WalkDir;
18
19use crate::build;
20
21#[derive(Debug, Clone, ValueEnum)]
22pub enum GuiPackKind {
23 Layout,
24 Auth,
25 Feature,
26 Skin,
27 Telemetry,
28}
29
30#[derive(Debug, Clone, Parser)]
31pub struct Args {
32 #[arg(long = "pack-kind", value_enum)]
34 pub pack_kind: GuiPackKind,
35
36 #[arg(long = "id")]
38 pub pack_id: String,
39
40 #[arg(long = "version")]
42 pub version: String,
43
44 #[arg(long = "pack-manifest-kind", default_value = "application")]
46 pub pack_manifest_kind: String,
47
48 #[arg(long = "publisher", default_value = "greentic.gui")]
50 pub publisher: String,
51
52 #[arg(long)]
54 pub name: Option<String>,
55
56 #[arg(long = "repo-url", conflicts_with_all = ["dir", "assets_dir"])]
58 pub repo_url: Option<String>,
59
60 #[arg(long, requires = "repo_url", default_value = "main")]
62 pub branch: String,
63
64 #[arg(long, conflicts_with_all = ["repo_url", "assets_dir"])]
66 pub dir: Option<PathBuf>,
67
68 #[arg(long = "assets-dir", conflicts_with_all = ["repo_url", "dir"])]
70 pub assets_dir: Option<PathBuf>,
71
72 #[arg(long = "package-dir")]
74 pub package_dir: Option<PathBuf>,
75
76 #[arg(long = "install-cmd")]
78 pub install_cmd: Option<String>,
79
80 #[arg(long = "build-cmd")]
82 pub build_cmd: Option<String>,
83
84 #[arg(long = "build-dir")]
86 pub build_dir: Option<PathBuf>,
87
88 #[arg(long = "spa")]
90 pub spa: Option<bool>,
91
92 #[arg(long = "route", action = ArgAction::Append)]
94 pub routes: Vec<String>,
95
96 #[arg(long = "routes", value_name = "ROUTES")]
98 pub routes_flat: Option<String>,
99
100 #[arg(long = "out", alias = "output", value_name = "FILE")]
102 pub out: PathBuf,
103}
104
105struct ConvertOptions {
106 pack_kind: GuiPackKind,
107 pack_id: String,
108 version: Version,
109 pack_manifest_kind: String,
110 publisher: String,
111 name: Option<String>,
112 source: Source,
113 package_dir: Option<PathBuf>,
114 install_cmd: Option<String>,
115 build_cmd: Option<String>,
116 build_dir: Option<PathBuf>,
117 spa: Option<bool>,
118 routes: Vec<RouteOverride>,
119 out: PathBuf,
120}
121
122#[derive(Debug, Clone)]
123enum Source {
124 Repo { url: String, branch: String },
125 Dir(PathBuf),
126 AssetsDir(PathBuf),
127}
128
129#[derive(Debug, Clone)]
130struct RouteOverride {
131 path: String,
132 html: PathBuf,
133}
134
135#[derive(Debug, Serialize)]
136struct Summary {
137 pack_id: String,
138 version: String,
139 pack_kind: String,
140 gui_kind: String,
141 out: String,
142 routes: Vec<String>,
143 assets_copied: usize,
144}
145
146pub async fn handle(
147 args: Args,
148 json_out: bool,
149 runtime: &crate::runtime::RuntimeContext,
150) -> Result<()> {
151 let opts = ConvertOptions::try_from(args)?;
152 let staging = TempDir::new().context("failed to create staging dir")?;
153 let staging_root = staging.path();
154 let pack_root = staging_root
155 .canonicalize()
156 .context("failed to canonicalize staging dir")?;
157
158 let mut _clone_guard: Option<TempDir> = None;
159 let source_root = match &opts.source {
160 Source::Repo { url, branch } => {
161 runtime.require_online("git clone (packc gui loveable-convert --repo-url)")?;
162 let (temp, repo_dir) = clone_repo(url, branch)?;
163 let path = repo_dir
164 .canonicalize()
165 .context("failed to canonicalize cloned repo")?;
166 _clone_guard = Some(temp);
167 path
168 }
169 Source::Dir(p) => p.canonicalize().context("failed to canonicalize --dir")?,
170 Source::AssetsDir(p) => p
171 .canonicalize()
172 .context("failed to canonicalize --assets-dir")?,
173 };
174
175 let build_root = opts
176 .package_dir
177 .as_ref()
178 .map(|p| source_root.join(p))
179 .unwrap_or_else(|| source_root.clone());
180
181 let assets_dir = match opts.source {
182 Source::AssetsDir(_) => build_root,
183 _ => {
184 runtime.require_online("install/build GUI assets")?;
185 build_assets(&build_root, &opts)?
186 }
187 };
188
189 let assets_dir = assets_dir
190 .canonicalize()
191 .with_context(|| format!("failed to canonicalize assets dir {}", assets_dir.display()))?;
192
193 let staging_assets = staging_root.join("gui").join("assets");
194 let copied = copy_assets(&assets_dir, &staging_assets)?;
195
196 let gui_manifest = build_gui_manifest(&opts, &staging_assets)?;
197 write_gui_manifest(&pack_root.join("gui").join("manifest.json"), &gui_manifest)?;
198
199 write_pack_manifest(&opts, &pack_root, copied)?;
200
201 let build_opts = build::BuildOptions {
202 pack_dir: pack_root.clone(),
203 component_out: None,
204 manifest_out: pack_root.join("dist").join("manifest.cbor"),
205 sbom_out: None,
206 gtpack_out: Some(opts.out.clone()),
207 lock_path: pack_root.join("pack.lock.json"),
208 bundle: build::BundleMode::Cache,
209 dry_run: false,
210 secrets_req: None,
211 default_secret_scope: None,
212 allow_oci_tags: false,
213 runtime: runtime.clone(),
214 skip_update: false,
215 };
216 build::run(&build_opts).await?;
217
218 if json_out {
219 let summary = Summary {
220 pack_id: opts.pack_id.clone(),
221 version: opts.version.to_string(),
222 pack_kind: opts.pack_manifest_kind.clone(),
223 gui_kind: gui_kind_string(&opts.pack_kind),
224 out: opts.out.display().to_string(),
225 routes: extract_route_strings(&gui_manifest),
226 assets_copied: copied,
227 };
228 println!("{}", serde_json::to_string_pretty(&summary)?);
229 } else {
230 info!(
231 pack_id = %opts.pack_id,
232 version = %opts.version,
233 gui_kind = gui_kind_string(&opts.pack_kind),
234 out = %opts.out.display(),
235 assets = copied,
236 "gui pack conversion complete"
237 );
238 }
239
240 Ok(())
241}
242
243impl TryFrom<Args> for ConvertOptions {
244 type Error = anyhow::Error;
245
246 fn try_from(args: Args) -> Result<Self> {
247 if args.assets_dir.is_some() && args.package_dir.is_some() {
248 return Err(anyhow!(
249 "--package-dir cannot be combined with --assets-dir (assets are already built)"
250 ));
251 }
252
253 let source = if let Some(url) = args.repo_url {
254 Source::Repo {
255 url,
256 branch: args.branch,
257 }
258 } else if let Some(dir) = args.dir {
259 Source::Dir(dir)
260 } else if let Some(assets) = args.assets_dir {
261 Source::AssetsDir(assets)
262 } else {
263 return Err(anyhow!(
264 "one of --repo-url, --dir, or --assets-dir must be provided"
265 ));
266 };
267
268 let routes = parse_routes(&args.routes, args.routes_flat.as_deref())?;
269 let version =
270 Version::parse(&args.version).context("invalid --version (expected semver)")?;
271 let out = if args.out.is_absolute() {
272 args.out
273 } else {
274 std::env::current_dir()
275 .context("failed to resolve current dir")?
276 .join(args.out)
277 };
278
279 Ok(Self {
280 pack_kind: args.pack_kind,
281 pack_id: args.pack_id,
282 version,
283 pack_manifest_kind: args.pack_manifest_kind.to_ascii_lowercase(),
284 publisher: args.publisher,
285 name: args.name,
286 source,
287 package_dir: args.package_dir,
288 install_cmd: args.install_cmd,
289 build_cmd: args.build_cmd,
290 build_dir: args.build_dir,
291 spa: args.spa,
292 routes,
293 out,
294 })
295 }
296}
297
298fn parse_routes(explicit: &[String], flat: Option<&str>) -> Result<Vec<RouteOverride>> {
299 let mut entries = Vec::new();
300
301 for raw in explicit {
302 entries.push(parse_route_entry(raw)?);
303 }
304
305 if let Some(flat_raw) = flat {
306 for part in flat_raw.split(',') {
307 if part.trim().is_empty() {
308 continue;
309 }
310 entries.push(parse_route_entry(part.trim())?);
311 }
312 }
313
314 Ok(entries)
315}
316
317fn parse_route_entry(raw: &str) -> Result<RouteOverride> {
318 let mut parts = raw.splitn(2, ':');
319 let path = parts
320 .next()
321 .ok_or_else(|| anyhow!("invalid route entry: {}", raw))?;
322 let html = parts
323 .next()
324 .ok_or_else(|| anyhow!("route entry must be path:html => {}", raw))?;
325
326 let path = path.trim().to_string();
327 if !path.starts_with('/') {
328 return Err(anyhow!("route path must start with '/': {}", path));
329 }
330
331 let html_path = PathBuf::from(html.trim());
332 if html_path.is_absolute() {
333 return Err(anyhow!(
334 "route html path must be relative to gui/assets: {}",
335 html
336 ));
337 }
338
339 Ok(RouteOverride {
340 path,
341 html: html_path,
342 })
343}
344
345fn clone_repo(url: &str, branch: &str) -> Result<(TempDir, PathBuf)> {
346 let temp = TempDir::new().context("failed to create temp dir for clone")?;
347 let target = temp.path().join("repo");
348
349 let status = Command::new("git")
350 .arg("clone")
351 .arg("--branch")
352 .arg(branch)
353 .arg("--depth")
354 .arg("1")
355 .arg(url)
356 .arg(&target)
357 .status()
358 .with_context(|| format!("failed to execute git clone for {}", url))?;
359
360 if !status.success() {
361 return Err(anyhow!("git clone failed with status {}", status));
362 }
363
364 Ok((temp, target))
365}
366
367fn build_assets(build_root: &Path, opts: &ConvertOptions) -> Result<PathBuf> {
368 let install_cmd = opts
369 .install_cmd
370 .clone()
371 .unwrap_or_else(|| default_install_command(build_root));
372 let build_cmd = opts
373 .build_cmd
374 .clone()
375 .unwrap_or_else(|| "npm run build".to_string());
376
377 run_shell(&install_cmd, build_root, "install dependencies")?;
378 run_shell(&build_cmd, build_root, "build GUI assets")?;
379
380 if let Some(dir) = &opts.build_dir {
381 return Ok(build_root.join(dir));
382 }
383
384 let dist = build_root.join("dist");
385 if dist.is_dir() {
386 return Ok(dist);
387 }
388
389 let build = build_root.join("build");
390 if build.is_dir() {
391 return Ok(build);
392 }
393
394 Err(anyhow!(
395 "unable to detect build output; specify --build-dir"
396 ))
397}
398
399fn default_install_command(root: &Path) -> String {
400 if root.join("pnpm-lock.yaml").exists() {
401 "pnpm install".to_string()
402 } else if root.join("yarn.lock").exists() {
403 "yarn install".to_string()
404 } else {
405 "npm install".to_string()
406 }
407}
408
409fn run_shell(cmd: &str, cwd: &Path, why: &str) -> Result<()> {
410 info!(command = %cmd, cwd = %cwd.display(), "running {}", why);
411 let status = Command::new("sh")
412 .arg("-c")
413 .arg(cmd)
414 .current_dir(cwd)
415 .status()
416 .with_context(|| format!("failed to run command: {}", cmd))?;
417
418 if !status.success() {
419 return Err(anyhow!("command failed ({}) with status {}", why, status));
420 }
421
422 Ok(())
423}
424
425fn copy_assets(src: &Path, dest: &Path) -> Result<usize> {
426 let mut count = 0usize;
427 for entry in WalkDir::new(src)
428 .into_iter()
429 .filter_map(Result::ok)
430 .filter(|e| e.file_type().is_file())
431 {
432 let rel = entry
433 .path()
434 .strip_prefix(src)
435 .expect("walkdir provided prefix");
436 let target = dest.join(rel);
437 if let Some(parent) = target.parent() {
438 fs::create_dir_all(parent)
439 .with_context(|| format!("failed to create {}", parent.display()))?;
440 }
441 fs::copy(entry.path(), &target).with_context(|| {
442 format!(
443 "failed to copy {} to {}",
444 entry.path().display(),
445 target.display()
446 )
447 })?;
448 count += 1;
449 }
450
451 Ok(count)
452}
453
454fn build_gui_manifest(opts: &ConvertOptions, assets_root: &Path) -> Result<serde_json::Value> {
455 let html_files = discover_html_files(assets_root);
456 if html_files.is_empty()
457 && !matches!(opts.pack_kind, GuiPackKind::Skin | GuiPackKind::Telemetry)
458 {
459 return Err(anyhow!(
460 "no HTML files found in assets dir {}",
461 assets_root.display()
462 ));
463 }
464
465 match opts.pack_kind {
466 GuiPackKind::Layout => {
467 let entry = select_entrypoint(&html_files);
468 let spa = opts.spa.unwrap_or_else(|| infer_spa(&html_files, &entry));
469 Ok(json!({
470 "kind": "gui-layout",
471 "layout": {
472 "slots": ["header","menu","main","footer"],
473 "entrypoint_html": format!("gui/assets/{}", to_unix_path(&entry)),
474 "spa": spa,
475 "slot_selectors": {
476 "header": "#app-header",
477 "menu": "#app-menu",
478 "main": "#app-main",
479 "footer": "#app-footer"
480 }
481 }
482 }))
483 }
484 GuiPackKind::Auth => {
485 let routes = build_auth_routes(&html_files);
486 Ok(json!({
487 "kind": "gui-auth",
488 "routes": routes,
489 "ui_bindings": {
490 "login_form_selector": "#login-form",
491 "login_buttons": [
492 { "provider": "microsoft", "selector": "#login-ms" },
493 { "provider": "google", "selector": "#login-google" }
494 ]
495 }
496 }))
497 }
498 GuiPackKind::Feature => {
499 let routes = build_feature_routes(opts, &html_files);
500 let workers = detect_workers(assets_root, &html_files)?;
501 Ok(json!({
502 "kind": "gui-feature",
503 "routes": routes,
504 "digital_workers": workers,
505 "fragments": []
506 }))
507 }
508 GuiPackKind::Skin => {
509 let theme_css_path = find_theme_css(assets_root);
510 let theme_css = theme_css_path.map(|p| format!("gui/assets/{}", to_unix_path(&p)));
511 Ok(json!({
512 "kind": "gui-skin",
513 "skin": {
514 "theme_css": theme_css
515 }
516 }))
517 }
518 GuiPackKind::Telemetry => Ok(json!({
519 "kind": "gui-telemetry",
520 "telemetry": {}
521 })),
522 }
523}
524
525fn write_gui_manifest(path: &Path, value: &serde_json::Value) -> Result<()> {
526 if let Some(parent) = path.parent() {
527 fs::create_dir_all(parent)
528 .with_context(|| format!("failed to create {}", parent.display()))?;
529 }
530 let data = serde_json::to_vec_pretty(value)?;
531 fs::write(path, data).with_context(|| format!("failed to write {}", path.display()))
532}
533
534#[derive(Debug, Serialize)]
535struct PackManifestYaml<'a> {
536 pack_id: &'a str,
537 version: &'a str,
538 kind: &'a str,
539 publisher: &'a str,
540 #[serde(skip_serializing_if = "Vec::is_empty")]
541 components: Vec<()>,
542 #[serde(skip_serializing_if = "Vec::is_empty")]
543 dependencies: Vec<()>,
544 #[serde(skip_serializing_if = "Vec::is_empty")]
545 flows: Vec<()>,
546 assets: Vec<AssetEntry>,
547 #[serde(skip_serializing_if = "Option::is_none")]
548 name: Option<&'a str>,
549}
550
551#[derive(Debug, Serialize)]
552struct AssetEntry {
553 path: String,
554}
555
556fn write_pack_manifest(opts: &ConvertOptions, root: &Path, assets_copied: usize) -> Result<()> {
557 if assets_copied == 0 {
558 return Err(anyhow!("no assets copied; cannot build GUI pack"));
559 }
560
561 let mut assets = Vec::new();
562 assets.push(AssetEntry {
563 path: "gui/manifest.json".to_string(),
564 });
565
566 let assets_root = root.join("gui").join("assets");
567 for entry in WalkDir::new(&assets_root)
568 .into_iter()
569 .filter_map(Result::ok)
570 .filter(|e| e.file_type().is_file())
571 {
572 let rel = entry.path().strip_prefix(root).expect("walkdir prefix");
573 assets.push(AssetEntry {
574 path: to_unix_path(rel),
575 });
576 }
577
578 assets.sort_by(|a, b| a.path.cmp(&b.path));
579
580 let yaml = PackManifestYaml {
581 pack_id: &opts.pack_id,
582 version: &opts.version.to_string(),
583 kind: &opts.pack_manifest_kind,
584 publisher: &opts.publisher,
585 components: Vec::new(),
586 dependencies: Vec::new(),
587 flows: Vec::new(),
588 assets,
589 name: opts.name.as_deref(),
590 };
591
592 let manifest_path = root.join("pack.yaml");
593 let contents = serde_yaml_bw::to_string(&yaml)?;
594 fs::write(&manifest_path, contents)
595 .with_context(|| format!("failed to write {}", manifest_path.display()))?;
596
597 Ok(())
598}
599
600fn discover_html_files(assets_root: &Path) -> Vec<PathBuf> {
601 WalkDir::new(assets_root)
602 .into_iter()
603 .filter_map(Result::ok)
604 .filter(|e| e.file_type().is_file())
605 .filter(|e| {
606 e.path()
607 .extension()
608 .map(|ext| ext == "html")
609 .unwrap_or(false)
610 })
611 .map(|e| {
612 e.path()
613 .strip_prefix(assets_root)
614 .unwrap_or(e.path())
615 .to_path_buf()
616 })
617 .collect()
618}
619
620fn select_entrypoint(html_files: &[PathBuf]) -> PathBuf {
621 html_files
622 .iter()
623 .find(|p| p.file_name().map(|n| n == "index.html").unwrap_or(false))
624 .cloned()
625 .unwrap_or_else(|| html_files[0].clone())
626}
627
628fn infer_spa(html_files: &[PathBuf], entry: &Path) -> bool {
629 let real_pages = html_files.iter().filter(|p| is_real_page(p)).count();
630 real_pages <= 1
631 && entry
632 .file_name()
633 .map(|n| n == "index.html")
634 .unwrap_or(false)
635}
636
637fn is_real_page(path: &Path) -> bool {
638 let ignore = ["404", "robots"];
639 path.extension().map(|ext| ext == "html").unwrap_or(false)
640 && !ignore
641 .iter()
642 .any(|ig| path.file_stem().and_then(OsStr::to_str) == Some(ig))
643}
644
645fn build_auth_routes(html_files: &[PathBuf]) -> Vec<serde_json::Value> {
646 let mut routes = Vec::new();
647 let login = html_files
648 .iter()
649 .find(|p| p.file_name().and_then(OsStr::to_str) == Some("login.html"))
650 .or_else(|| html_files.first());
651
652 if let Some(login) = login {
653 routes.push(json!({
654 "path": "/login",
655 "html": format!("gui/assets/{}", to_unix_path(login)),
656 "public": true
657 }));
658 }
659
660 routes
661}
662
663fn build_feature_routes(opts: &ConvertOptions, html_files: &[PathBuf]) -> Vec<serde_json::Value> {
664 if !opts.routes.is_empty() {
665 return opts
666 .routes
667 .iter()
668 .map(|r| {
669 json!({
670 "path": r.path,
671 "html": format!("gui/assets/{}", to_unix_path(&r.html)),
672 "authenticated": true
673 })
674 })
675 .collect();
676 }
677
678 let entry = select_entrypoint(html_files);
679 let spa = opts.spa.unwrap_or_else(|| infer_spa(html_files, &entry));
680
681 let mut routes = Vec::new();
682 if spa {
683 routes.push(json!({
684 "path": "/",
685 "html": format!("gui/assets/{}", to_unix_path(&entry)),
686 "authenticated": true
687 }));
688 return routes;
689 }
690
691 for page in html_files.iter().filter(|p| is_real_page(p)) {
692 let route = route_from_path(page);
693 routes.push(json!({
694 "path": route,
695 "html": format!("gui/assets/{}", to_unix_path(page)),
696 "authenticated": true
697 }));
698 }
699
700 routes
701}
702
703fn route_from_path(path: &Path) -> String {
704 let mut parts = Vec::new();
705 if let Some(parent) = path.parent()
706 && parent != Path::new("")
707 {
708 parts.push(to_unix_path(parent));
709 }
710 if path.file_stem().and_then(OsStr::to_str) != Some("index") {
711 parts.push(
712 path.file_stem()
713 .and_then(OsStr::to_str)
714 .unwrap_or_default()
715 .to_string(),
716 );
717 }
718
719 let combined = parts.join("/");
720 if combined.is_empty() {
721 "/".to_string()
722 } else if combined.starts_with('/') {
723 combined
724 } else {
725 format!("/{}", combined)
726 }
727}
728
729fn detect_workers(assets_root: &Path, html_files: &[PathBuf]) -> Result<Vec<serde_json::Value>> {
730 let worker_re = Regex::new(r#"data-greentic-worker\s*=\s*"([^"]+)""#)?;
731 let slot_re = Regex::new(r#"data-greentic-worker-slot\s*=\s*"([^"]+)""#)?;
732 let mut seen = BTreeSet::new();
733 let mut workers = Vec::new();
734
735 for rel in html_files {
736 let abs = assets_root.join(rel);
737 let contents = fs::read_to_string(&abs).with_context(|| {
738 format!(
739 "failed to read HTML for worker detection: {}",
740 abs.display()
741 )
742 })?;
743
744 for caps in worker_re.captures_iter(&contents) {
745 let worker_id = caps
746 .get(1)
747 .map(|m| m.as_str().to_string())
748 .unwrap_or_default();
749 if worker_id.is_empty() || !seen.insert(worker_id.clone()) {
750 continue;
751 }
752
753 let slot = slot_re
754 .captures(&contents)
755 .and_then(|c| c.get(1))
756 .map(|m| m.as_str().to_string());
757
758 let selector = slot
759 .as_ref()
760 .map(|s| format!("#{}", s))
761 .unwrap_or_else(|| format!(r#"[data-greentic-worker="{}"]"#, worker_id));
762
763 workers.push(json!({
764 "id": worker_id.split('.').next_back().unwrap_or(&worker_id),
765 "worker_id": worker_id,
766 "attach": { "mode": "selector", "selector": selector },
767 "routes": ["/*"]
768 }));
769 }
770 }
771
772 Ok(workers)
773}
774
775fn extract_route_strings(manifest: &serde_json::Value) -> Vec<String> {
776 manifest
777 .get("routes")
778 .and_then(|r| r.as_array())
779 .map(|arr| {
780 arr.iter()
781 .filter_map(|r| {
782 r.get("path")
783 .and_then(|p| p.as_str())
784 .map(|s| s.to_string())
785 })
786 .collect()
787 })
788 .unwrap_or_default()
789}
790
791fn to_unix_path(path: &Path) -> String {
792 path.iter()
793 .map(|p| p.to_string_lossy())
794 .collect::<Vec<_>>()
795 .join("/")
796}
797
798fn gui_kind_string(kind: &GuiPackKind) -> String {
799 match kind {
800 GuiPackKind::Layout => "gui-layout",
801 GuiPackKind::Auth => "gui-auth",
802 GuiPackKind::Feature => "gui-feature",
803 GuiPackKind::Skin => "gui-skin",
804 GuiPackKind::Telemetry => "gui-telemetry",
805 }
806 .to_string()
807}
808
809fn find_theme_css(assets_root: &Path) -> Option<PathBuf> {
810 let candidates = ["theme.css", "styles.css"];
811 for candidate in candidates {
812 let path = assets_root.join(candidate);
813 if path.exists() {
814 return Some(PathBuf::from(candidate));
815 }
816 }
817 None
818}