Skip to main content

packc/cli/gui/
loveable_convert.rs

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