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