euv-cli 0.51.0

Cross-platform CLI tool for the euv native UI framework supporting run, build, check, fmt, doctor, new, and Hyperlane SSE dynamic updates across all supported platforms.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
use super::*;

/// Converts a semantic version string (e.g. `"0.49.4"` or `"1.2.3-rc.1"`) into a deterministic positive numeric Android `versionCode`.
///
/// # Arguments
///
/// - `&str` - Semantic version string.
///
/// # Returns
///
/// - `u32` - Deterministic positive integer (`major * 10000 + minor * 100 + patch`, minimum `1`).
#[must_use]
pub fn semver_to_version_code(version: &str) -> u32 {
    let core: &str = version.trim().split(['-', '+']).next().unwrap_or("");
    let mut parts: Vec<u32> = Vec::with_capacity(3);
    for segment in core.split('.') {
        if let Ok(num) = segment.trim().parse::<u32>() {
            parts.push(num);
        } else {
            parts.push(0);
        }
    }
    let major: u32 = parts.first().copied().unwrap_or(0);
    let minor: u32 = parts.get(1).copied().unwrap_or(0);
    let patch: u32 = parts.get(2).copied().unwrap_or(0);
    let code: u32 = major
        .saturating_mul(10_000)
        .saturating_add(minor.saturating_mul(100))
        .saturating_add(patch);
    code.max(1)
}

/// Walks up from `start_dir` searching for the nearest `euv.toml` project configuration file.
///
/// # Arguments
///
/// - `&Path` - Starting directory or file path.
///
/// # Returns
///
/// - `Option<PathBuf>` - Path to the nearest `euv.toml`, if found.
#[must_use]
pub fn find_euv_config_path(start_dir: &Path) -> Option<PathBuf> {
    let anchor: &Path = if start_dir.is_file() {
        start_dir.parent().unwrap_or(start_dir)
    } else {
        start_dir
    };
    let mut current: Option<&Path> = Some(anchor);
    while let Some(dir) = current {
        let candidate: PathBuf = dir.join(EUV_TOML_NAME);
        if candidate.is_file() {
            return Some(candidate);
        }
        current = dir.parent();
    }
    None
}

/// Loads and parses the nearest `euv.toml` from `start_dir` (returns `Ok(None)` in zero-config projects).
///
/// # Arguments
///
/// - `&Path` - Starting directory or file path.
///
/// # Returns
///
/// - `io::Result<Option<LoadedEuvConfig>>` - Loaded config, `None` when absent, or parse/I/O error.
pub fn load_euv_config(start_dir: &Path) -> io::Result<Option<LoadedEuvConfig>> {
    let Some(config_path) = find_euv_config_path(start_dir) else {
        return Ok(None);
    };
    let raw: String = fs::read_to_string(&config_path)?;
    let parsed: EuvProjectConfig = parse_euv_toml(&raw)?;
    let project_root: PathBuf = config_path
        .parent()
        .map(Path::to_path_buf)
        .unwrap_or_else(|| start_dir.to_path_buf());
    Ok(Some(LoadedEuvConfig::new(
        config_path,
        project_root,
        parsed,
    )))
}

/// Parses an `euv.toml` text payload into an `EuvProjectConfig` without external TOML crate dependencies.
///
/// # Arguments
///
/// - `&str` - Raw UTF-8 `euv.toml` content.
///
/// # Returns
///
/// - `io::Result<EuvProjectConfig>` - Parsed project configuration or `InvalidData` syntax error.
pub fn parse_euv_toml(raw: &str) -> io::Result<EuvProjectConfig> {
    let entries: Vec<(String, String, String)> = collect_toml_entries(raw)?;
    let mut config: EuvProjectConfig = EuvProjectConfig::default();
    for (section, key, value) in entries.into_iter() {
        apply_euv_toml_entry(&mut config, &section, &key, &value)?;
    }
    Ok(config)
}

/// Resolves dynamic Cargo workspace or package metadata by walking up from `start_dir`.
///
/// # Arguments
///
/// - `&Path` - Starting directory or file path.
///
/// # Returns
///
/// - `io::Result<WorkspaceMetadata>` - Resolved root, version, `versionCode`, packages, and locked `wasm-bindgen` version.
pub fn resolve_workspace_metadata(start_dir: &Path) -> io::Result<WorkspaceMetadata> {
    let anchor: &Path = if start_dir.is_file() {
        start_dir.parent().unwrap_or(start_dir)
    } else {
        start_dir
    };
    let manifest_path: PathBuf = find_workspace_cargo_toml(anchor)
        .ok_or_else(|| Error::new(ErrorKind::NotFound, ERR_CARGO_MANIFEST_NOT_FOUND))?;
    let workspace_root: PathBuf = manifest_path
        .parent()
        .map(Path::to_path_buf)
        .unwrap_or_else(|| anchor.to_path_buf());
    let root_raw: String = fs::read_to_string(&manifest_path)?;
    let root_entries: Vec<(String, String, String)> = collect_toml_entries(&root_raw)?;
    let ws_version: Option<String> =
        find_toml_string(&root_entries, SECTION_WORKSPACE_PACKAGE, KEY_VERSION)
            .or_else(|| find_toml_string(&root_entries, SECTION_PACKAGE, KEY_VERSION));
    let resolved_version: String = ws_version
        .clone()
        .unwrap_or_else(|| FALLBACK_CLI_VERSION.to_string());
    let version_code: u32 = semver_to_version_code(&resolved_version);
    let mut packages: Vec<WorkspacePackageInfo> = Vec::new();
    if let Some(root_pkg) = parse_package_info(
        &manifest_path,
        &workspace_root,
        &root_entries,
        &resolved_version,
    ) {
        packages.push(root_pkg);
    }
    let members: Vec<String> =
        find_toml_string_array(&root_entries, SECTION_WORKSPACE, KEY_MEMBERS);
    for member_rel in members.into_iter() {
        let member_dir: PathBuf = workspace_root.join(&member_rel);
        let member_manifest: PathBuf = member_dir.join(CARGO_TOML_NAME);
        if !member_manifest.is_file() {
            continue;
        }
        if let Ok(member_raw) = fs::read_to_string(&member_manifest)
            && let Ok(member_entries) = collect_toml_entries(&member_raw)
            && let Some(pkg_info) = parse_package_info(
                &member_manifest,
                &member_dir,
                &member_entries,
                &resolved_version,
            )
        {
            packages.push(pkg_info);
        }
    }
    let lock_path: PathBuf = workspace_root.join(CARGO_LOCK_NAME);
    let wasm_bindgen_version: Option<String> = if lock_path.is_file() {
        resolve_cargo_lock_package_version(&lock_path, CRATE_WASM_BINDGEN)
    } else {
        None
    };
    Ok(WorkspaceMetadata::new(
        workspace_root,
        manifest_path,
        resolved_version,
        version_code,
        packages,
        wasm_bindgen_version,
    ))
}

/// Resolves the locked version of `package_name` from a `Cargo.lock` file.
///
/// # Arguments
///
/// - `&Path` - Path to `Cargo.lock`.
/// - `&str` - Exact Cargo package name (e.g. `"wasm-bindgen"`).
///
/// # Returns
///
/// - `Option<String>` - Locked semantic version string if found.
#[must_use]
pub fn resolve_cargo_lock_package_version(lock_path: &Path, package_name: &str) -> Option<String> {
    let raw: String = fs::read_to_string(lock_path).ok()?;
    let mut in_package: bool = false;
    let mut matched_name: bool = false;
    for line in raw.lines() {
        let trimmed: &str = line.trim();
        if trimmed == TOML_PACKAGE_TABLE_HEADER {
            in_package = true;
            matched_name = false;
            continue;
        }
        if !in_package {
            continue;
        }
        if trimmed.starts_with('[') {
            in_package = false;
            matched_name = false;
            continue;
        }
        if let Some((raw_key, raw_val)) = trimmed.split_once('=') {
            let key: &str = raw_key.trim();
            if key == KEY_NAME {
                if let Ok(val) = parse_toml_string_value(raw_val.trim()) {
                    matched_name = val == package_name;
                }
            } else if key == KEY_VERSION
                && matched_name
                && let Ok(ver) = parse_toml_string_value(raw_val.trim())
            {
                return Some(ver);
            }
        }
    }
    None
}

/// Resolves the effective application semantic version using precedence: CLI flag -> `euv.toml` -> workspace `Cargo.toml` -> CLI crate version.
///
/// # Arguments
///
/// - `&Path` - Working directory to probe for `Cargo.toml`.
/// - `Option<&str>` - Optional explicit `--version` CLI override.
/// - `Option<&EuvProjectConfig>` - Optional loaded `euv.toml` configuration.
///
/// # Returns
///
/// - `String` - Effective semantic version string.
#[must_use]
pub fn resolve_effective_version(
    start_dir: &Path,
    explicit: Option<&str>,
    config: Option<&EuvProjectConfig>,
) -> String {
    if let Some(ver) = explicit.map(str::trim).filter(|val: &&str| !val.is_empty()) {
        return ver.to_string();
    }
    if let Some(cfg) = config
        && let Some(ver) = cfg.get_app().try_get_version()
        && !ver.trim().is_empty()
    {
        return ver.trim().to_string();
    }
    if let Ok(meta) = resolve_workspace_metadata(start_dir) {
        return meta.get_version().clone();
    }
    FALLBACK_CLI_VERSION.to_string()
}

/// Resolves the effective Cargo package name using precedence: CLI `--package` -> `euv.toml` -> workspace showcase/binary package.
///
/// # Arguments
///
/// - `&WorkspaceMetadata` - Discovered workspace package inventory.
/// - `Option<&EuvProjectConfig>` - Optional loaded `euv.toml` configuration.
/// - `Option<&str>` - Optional explicit `--package` CLI flag.
///
/// # Returns
///
/// - `Option<String>` - Effective Cargo package name, if any.
#[must_use]
pub fn resolve_effective_package(
    workspace: &WorkspaceMetadata,
    config: Option<&EuvProjectConfig>,
    explicit: Option<&str>,
) -> Option<String> {
    if let Some(pkg) = explicit.map(str::trim).filter(|val: &&str| !val.is_empty()) {
        return Some(pkg.to_string());
    }
    if let Some(cfg) = config
        && let Some(pkg) = cfg.get_app().try_get_package()
        && !pkg.trim().is_empty()
    {
        return Some(pkg.trim().to_string());
    }
    if let Some(example) = workspace.find_package(EXAMPLE_PKG_HINT) {
        return Some(example.get_name().clone());
    }
    if let Some(bin_pkg) = workspace
        .get_packages()
        .iter()
        .find(|pkg: &&WorkspacePackageInfo| pkg.get_has_bin())
    {
        return Some(bin_pkg.get_name().clone());
    }
    workspace
        .get_packages()
        .first()
        .map(|pkg: &WorkspacePackageInfo| pkg.get_name().clone())
}

/// Walks up ancestor directories preferring the highest enclosing `[workspace]` `Cargo.toml` or nearest standalone `Cargo.toml`.
///
/// # Arguments
///
/// - `&Path` - Starting directory.
///
/// # Returns
///
/// - `Option<PathBuf>` - Resolved root `Cargo.toml` path.
fn find_workspace_cargo_toml(start_dir: &Path) -> Option<PathBuf> {
    let mut nearest: Option<PathBuf> = None;
    let mut current: Option<&Path> = Some(start_dir);
    while let Some(dir) = current {
        let candidate: PathBuf = dir.join(CARGO_TOML_NAME);
        if candidate.is_file() {
            if nearest.is_none() {
                nearest = Some(candidate.clone());
            }
            if let Ok(content) = fs::read_to_string(&candidate)
                && content
                    .lines()
                    .any(|line: &str| line.trim() == TOML_WORKSPACE_HEADER)
            {
                return Some(candidate);
            }
        }
        current = dir.parent();
    }
    nearest
}

/// Parses a single package `Cargo.toml`'s flattened entries into a `WorkspacePackageInfo`.
///
/// # Arguments
///
/// - `&Path` - Path to the package's `Cargo.toml`.
/// - `&Path` - Directory containing the package.
/// - `&[(String, String, String)]` - Flattened TOML `(section, key, raw_value)` records.
/// - `&str` - Workspace fallback semantic version.
///
/// # Returns
///
/// - `Option<WorkspacePackageInfo>` - Parsed package metadata when `[package].name` is present.
fn parse_package_info(
    manifest_path: &Path,
    crate_dir: &Path,
    entries: &[(String, String, String)],
    workspace_version: &str,
) -> Option<WorkspacePackageInfo> {
    let name: String = find_toml_string(entries, SECTION_PACKAGE, KEY_NAME)?;
    let lib_name: String =
        find_toml_string(entries, SECTION_LIB, KEY_NAME).unwrap_or_else(|| name.replace('-', "_"));
    let version: String =
        if find_toml_bool(entries, SECTION_PACKAGE, KEY_VERSION_WORKSPACE).unwrap_or(false) {
            workspace_version.to_string()
        } else {
            find_toml_string(entries, SECTION_PACKAGE, KEY_VERSION)
                .unwrap_or_else(|| workspace_version.to_string())
        };
    let crate_types: Vec<String> = find_toml_string_array(entries, SECTION_LIB, KEY_CRATE_TYPE);
    let has_cdylib: bool = crate_types.iter().any(|item: &String| item == TOKEN_CDYLIB);
    let has_bin_section: bool = entries
        .iter()
        .any(|(section, _, _): &(String, String, String)| section == SECTION_BIN_ARRAY);
    let has_main_file: bool = crate_dir.join(SRC_DIR_NAME).join(MAIN_RS_NAME).is_file();
    let has_bin: bool = has_bin_section || has_main_file;
    Some(WorkspacePackageInfo::new(
        name,
        lib_name,
        version,
        manifest_path.to_path_buf(),
        crate_dir.to_path_buf(),
        has_cdylib,
        has_bin,
    ))
}

/// Collects `(section, key, raw_value)` entries from a TOML document supporting multi-line arrays and `#` comments.
///
/// # Arguments
///
/// - `&str` - Raw TOML source text.
///
/// # Returns
///
/// - `io::Result<Vec<(String, String, String)>>` - Parsed entries or `InvalidData` error.
fn collect_toml_entries(raw: &str) -> io::Result<Vec<(String, String, String)>> {
    let mut entries: Vec<(String, String, String)> = Vec::new();
    let mut current_section: String = String::new();
    let mut pending_key: Option<String> = None;
    let mut pending_val: String = String::new();
    let mut pending_brackets: i32 = 0;
    for (line_idx, raw_line) in raw.lines().enumerate() {
        let stripped: String = strip_toml_comment(raw_line);
        let trimmed: &str = stripped.trim();
        if trimmed.is_empty() {
            continue;
        }
        if let Some(active_key) = pending_key.as_ref() {
            pending_val.push(' ');
            pending_val.push_str(trimmed);
            pending_brackets += bracket_balance(trimmed);
            if pending_brackets <= 0 {
                entries.push((
                    current_section.clone(),
                    active_key.clone(),
                    pending_val.trim().to_string(),
                ));
                pending_key = None;
                pending_val.clear();
                pending_brackets = 0;
            }
            continue;
        }
        if trimmed.starts_with('[') && trimmed.ends_with(']') {
            let inner: &str = trimmed[1..trimmed.len() - 1].trim();
            if inner.is_empty() {
                return Err(Error::new(
                    ErrorKind::InvalidData,
                    format!("{ERR_INVALID_EUV_TOML} at line {}", line_idx + 1),
                ));
            }
            current_section = inner.to_string();
            continue;
        }
        let Some((lhs, rhs)) = trimmed.split_once('=') else {
            continue;
        };
        let key: &str = lhs.trim();
        let val: &str = rhs.trim();
        if key.is_empty() {
            return Err(Error::new(
                ErrorKind::InvalidData,
                format!("{ERR_INVALID_EUV_TOML} at line {}", line_idx + 1),
            ));
        }
        let balance: i32 = bracket_balance(val);
        if balance > 0 {
            pending_key = Some(key.to_string());
            pending_val = val.to_string();
            pending_brackets = balance;
        } else {
            entries.push((current_section.clone(), key.to_string(), val.to_string()));
        }
    }
    if pending_key.is_some() {
        return Err(Error::new(
            ErrorKind::InvalidData,
            format!("{ERR_INVALID_EUV_TOML}: unclosed array"),
        ));
    }
    Ok(entries)
}

/// Applies one parsed `(section, key, raw_value)` record onto `EuvProjectConfig`.
///
/// # Arguments
///
/// - `&mut EuvProjectConfig` - Mutable destination config.
/// - `&str` - Active TOML section name.
/// - `&str` - Key identifier.
/// - `&str` - Raw TOML value text.
///
/// # Returns
///
/// - `io::Result<()>` - Success or `InvalidData` on value type mismatch.
fn apply_euv_toml_entry(
    config: &mut EuvProjectConfig,
    section: &str,
    key: &str,
    raw_value: &str,
) -> io::Result<()> {
    if section == SECTION_APP {
        let app: &mut EuvAppConfig = config.get_mut_app();
        if key == KEY_NAME {
            let _: &mut EuvAppConfig = app.set_name(Some(parse_toml_string_value(raw_value)?));
        } else if key == KEY_VERSION {
            let _: &mut EuvAppConfig = app.set_version(Some(parse_toml_string_value(raw_value)?));
        } else if key == KEY_BUNDLE_ID {
            let _: &mut EuvAppConfig = app.set_bundle_id(Some(parse_toml_string_value(raw_value)?));
        } else if key == KEY_PACKAGE {
            let _: &mut EuvAppConfig = app.set_package(Some(parse_toml_string_value(raw_value)?));
        } else if key == KEY_ICON {
            let _: &mut EuvAppConfig =
                app.set_icon(Some(PathBuf::from(parse_toml_string_value(raw_value)?)));
        } else if key == KEY_DEFAULT_TARGETS {
            let _: &mut EuvAppConfig = app.set_default_targets(parse_toml_string_array(raw_value)?);
        } else if key == KEY_RENDER {
            let _: &mut EuvAppConfig = app.set_render(Some(parse_toml_string_value(raw_value)?));
        }
    } else if section == SECTION_BUILD {
        let build: &mut EuvBuildConfig = config.get_mut_build();
        if key == KEY_OUT_DIR {
            let _: &mut EuvBuildConfig =
                build.set_out_dir(Some(PathBuf::from(parse_toml_string_value(raw_value)?)));
        } else if key == KEY_BASE {
            let _: &mut EuvBuildConfig = build.set_base(Some(parse_toml_string_value(raw_value)?));
        } else if key == KEY_RAW_WASM {
            let _: &mut EuvBuildConfig = build.set_raw_wasm(parse_toml_bool_value(raw_value)?);
        } else if key == KEY_SKIP_WASM_OPT {
            let _: &mut EuvBuildConfig = build.set_skip_wasm_opt(parse_toml_bool_value(raw_value)?);
        } else if key == KEY_INCLUDE_CLI {
            let _: &mut EuvBuildConfig = build.set_include_cli(parse_toml_bool_value(raw_value)?);
        } else if key == KEY_PARALLEL {
            let _: &mut EuvBuildConfig = build.set_parallel(parse_toml_bool_value(raw_value)?);
        } else if key == KEY_ANDROID_API_LEVEL {
            let parsed_num: u32 = raw_value.trim().parse::<u32>().map_err(|_| {
                Error::new(
                    ErrorKind::InvalidData,
                    format!("{ERR_INVALID_EUV_TOML}: invalid integer `{raw_value}`"),
                )
            })?;
            let _: &mut EuvBuildConfig = build.set_android_api_level(Some(parsed_num));
        } else if key == KEY_ANDROID_BUILD_TOOLS {
            let _: &mut EuvBuildConfig =
                build.set_android_build_tools(Some(parse_toml_string_value(raw_value)?));
        } else if key == KEY_IOS_TEAM_ID {
            let _: &mut EuvBuildConfig =
                build.set_ios_team_id(Some(parse_toml_string_value(raw_value)?));
        }
    } else if section == SECTION_OTA {
        let ota: &mut EuvOtaConfig = config.get_mut_ota();
        if key == KEY_PROJECT {
            let _: &mut EuvOtaConfig = ota.set_project(Some(parse_toml_string_value(raw_value)?));
        } else if key == KEY_CHANNEL {
            let _: &mut EuvOtaConfig = ota.set_channel(Some(parse_toml_string_value(raw_value)?));
        } else if key == KEY_STORE {
            let _: &mut EuvOtaConfig =
                ota.set_store(Some(PathBuf::from(parse_toml_string_value(raw_value)?)));
        } else if key == KEY_SERVER_URL {
            let _: &mut EuvOtaConfig =
                ota.set_server_url(Some(parse_toml_string_value(raw_value)?));
        } else if key == KEY_PROXY_BASE {
            let _: &mut EuvOtaConfig =
                ota.set_proxy_base(Some(parse_toml_string_value(raw_value)?));
        }
    } else if section == SECTION_DOCS {
        let docs: &mut EuvDocsConfig = config.get_mut_docs();
        if key == KEY_SRC {
            let _: &mut EuvDocsConfig =
                docs.set_src(Some(PathBuf::from(parse_toml_string_value(raw_value)?)));
        } else if key == KEY_OUT {
            let _: &mut EuvDocsConfig =
                docs.set_out(Some(PathBuf::from(parse_toml_string_value(raw_value)?)));
        } else if key == KEY_TITLE {
            let _: &mut EuvDocsConfig = docs.set_title(Some(parse_toml_string_value(raw_value)?));
        } else if key == KEY_BASE {
            let _: &mut EuvDocsConfig = docs.set_base(Some(parse_toml_string_value(raw_value)?));
        } else if key == KEY_WASM {
            let _: &mut EuvDocsConfig = docs.set_wasm(parse_toml_bool_value(raw_value)?);
        }
    }
    Ok(())
}

/// Looks up a quoted string entry matching `(section, key)`.
///
/// # Arguments
///
/// - `&[(String, String, String)]` - Flattened TOML entries.
/// - `&str` - Section name.
/// - `&str` - Key name.
///
/// # Returns
///
/// - `Option<String>` - Unquoted string value if present and valid.
fn find_toml_string(
    entries: &[(String, String, String)],
    section: &str,
    key: &str,
) -> Option<String> {
    entries
        .iter()
        .find(|(sec, k, _): &&(String, String, String)| sec == section && k == key)
        .and_then(|(_, _, val): &(String, String, String)| parse_toml_string_value(val).ok())
}

/// Looks up a boolean entry matching `(section, key)`.
///
/// # Arguments
///
/// - `&[(String, String, String)]` - Flattened TOML entries.
/// - `&str` - Section name.
/// - `&str` - Key name.
///
/// # Returns
///
/// - `Option<bool>` - Parsed boolean value if present and valid.
fn find_toml_bool(entries: &[(String, String, String)], section: &str, key: &str) -> Option<bool> {
    entries
        .iter()
        .find(|(sec, k, _): &&(String, String, String)| sec == section && k == key)
        .and_then(|(_, _, val): &(String, String, String)| parse_toml_bool_value(val).ok())
}

/// Looks up a string array entry matching `(section, key)`.
///
/// # Arguments
///
/// - `&[(String, String, String)]` - Flattened TOML entries.
/// - `&str` - Section name.
/// - `&str` - Key name.
///
/// # Returns
///
/// - `Vec<String>` - Parsed string items or empty vector when absent.
fn find_toml_string_array(
    entries: &[(String, String, String)],
    section: &str,
    key: &str,
) -> Vec<String> {
    entries
        .iter()
        .find(|(sec, k, _): &&(String, String, String)| sec == section && k == key)
        .and_then(|(_, _, val): &(String, String, String)| parse_toml_string_array(val).ok())
        .unwrap_or_default()
}

/// Strips a trailing `#` TOML comment while respecting single- and double-quoted strings.
///
/// # Arguments
///
/// - `&str` - Raw TOML line.
///
/// # Returns
///
/// - `String` - Line with comments removed.
fn strip_toml_comment(line: &str) -> String {
    let mut out: String = String::with_capacity(line.len());
    let mut in_double: bool = false;
    let mut in_single: bool = false;
    let mut escaped: bool = false;
    for ch in line.chars() {
        if escaped {
            out.push(ch);
            escaped = false;
            continue;
        }
        if in_double && ch == '\\' {
            out.push(ch);
            escaped = true;
            continue;
        }
        if ch == '"' && !in_single {
            in_double = !in_double;
            out.push(ch);
            continue;
        }
        if ch == '\'' && !in_double {
            in_single = !in_single;
            out.push(ch);
            continue;
        }
        if ch == '#' && !in_double && !in_single {
            break;
        }
        out.push(ch);
    }
    out
}

/// Computes net `[` minus `]` bracket depth outside quoted strings in `text`.
///
/// # Arguments
///
/// - `&str` - Comment-stripped TOML text fragment.
///
/// # Returns
///
/// - `i32` - Net bracket balance delta.
fn bracket_balance(text: &str) -> i32 {
    let mut depth: i32 = 0;
    let mut in_double: bool = false;
    let mut in_single: bool = false;
    let mut escaped: bool = false;
    for ch in text.chars() {
        if escaped {
            escaped = false;
            continue;
        }
        if in_double && ch == '\\' {
            escaped = true;
            continue;
        }
        if ch == '"' && !in_single {
            in_double = !in_double;
            continue;
        }
        if ch == '\'' && !in_double {
            in_single = !in_single;
            continue;
        }
        if !in_double && !in_single {
            if ch == '[' {
                depth += 1;
            } else if ch == ']' {
                depth -= 1;
            }
        }
    }
    depth
}

/// Parses a single- or double-quoted TOML string value with basic escape handling.
///
/// # Arguments
///
/// - `&str` - Trimmed TOML string literal.
///
/// # Returns
///
/// - `io::Result<String>` - Unescaped string value or `InvalidData`.
fn parse_toml_string_value(raw: &str) -> io::Result<String> {
    let trimmed: &str = raw.trim();
    if trimmed.len() >= 2 && trimmed.starts_with('\'') && trimmed.ends_with('\'') {
        return Ok(trimmed[1..trimmed.len() - 1].to_string());
    }
    if trimmed.len() >= 2 && trimmed.starts_with('"') && trimmed.ends_with('"') {
        let inner: &str = &trimmed[1..trimmed.len() - 1];
        let mut out: String = String::with_capacity(inner.len());
        let mut chars: Peekable<Chars<'_>> = inner.chars().peekable();
        while let Some(ch) = chars.next() {
            if ch == '\\'
                && let Some(next_ch) = chars.next()
            {
                match next_ch {
                    'n' => out.push('\n'),
                    'r' => out.push('\r'),
                    't' => out.push('\t'),
                    '\\' => out.push('\\'),
                    '"' => out.push('"'),
                    other => {
                        out.push('\\');
                        out.push(other);
                    }
                }
            } else {
                out.push(ch);
            }
        }
        return Ok(out);
    }
    Err(Error::new(
        ErrorKind::InvalidData,
        format!("{ERR_INVALID_EUV_TOML}: expected quoted string, got `{trimmed}`"),
    ))
}

/// Parses a TOML boolean literal (`true` or `false`).
///
/// # Arguments
///
/// - `&str` - Trimmed TOML boolean token.
///
/// # Returns
///
/// - `io::Result<bool>` - Parsed boolean value or `InvalidData`.
fn parse_toml_bool_value(raw: &str) -> io::Result<bool> {
    let trimmed: &str = raw.trim();
    if trimmed == TOKEN_TRUE {
        Ok(true)
    } else if trimmed == TOKEN_FALSE {
        Ok(false)
    } else {
        Err(Error::new(
            ErrorKind::InvalidData,
            format!("{ERR_INVALID_EUV_TOML}: expected boolean, got `{trimmed}`"),
        ))
    }
}

/// Parses a TOML string array literal (`["a", "b"]`).
///
/// # Arguments
///
/// - `&str` - Trimmed TOML array expression.
///
/// # Returns
///
/// - `io::Result<Vec<String>>` - Parsed string items or `InvalidData`.
fn parse_toml_string_array(raw: &str) -> io::Result<Vec<String>> {
    let trimmed: &str = raw.trim();
    if !trimmed.starts_with('[') || !trimmed.ends_with(']') {
        return Err(Error::new(
            ErrorKind::InvalidData,
            format!("{ERR_INVALID_EUV_TOML}: expected array, got `{trimmed}`"),
        ));
    }
    let inner: &str = trimmed[1..trimmed.len() - 1].trim();
    if inner.is_empty() {
        return Ok(Vec::new());
    }
    let mut items: Vec<String> = Vec::new();
    let mut current: String = String::new();
    let mut in_double: bool = false;
    let mut in_single: bool = false;
    let mut escaped: bool = false;
    for ch in inner.chars() {
        if escaped {
            current.push(ch);
            escaped = false;
            continue;
        }
        if in_double && ch == '\\' {
            current.push(ch);
            escaped = true;
            continue;
        }
        if ch == '"' && !in_single {
            in_double = !in_double;
            current.push(ch);
            continue;
        }
        if ch == '\'' && !in_double {
            in_single = !in_single;
            current.push(ch);
            continue;
        }
        if ch == ',' && !in_double && !in_single {
            let piece: &str = current.trim();
            if !piece.is_empty() {
                items.push(parse_toml_string_value(piece)?);
            }
            current.clear();
            continue;
        }
        current.push(ch);
    }
    let tail: &str = current.trim();
    if !tail.is_empty() {
        items.push(parse_toml_string_value(tail)?);
    }
    Ok(items)
}