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
use super::*;

/// Queries a live `DevAutomationBridge` HTTP server for health, AI Schema snapshot, and 9-rule layout anomalies.
///
/// # Arguments
///
/// - `&str` - Base HTTP URL (e.g. `http://127.0.0.1:17890` or `http://127.0.0.1:4174`).
///
/// # Returns
///
/// - `io::Result<LiveInspectReport>` - Structured live inspection result or URL validation error.
pub fn inspect_live_bridge(base_url: &str) -> io::Result<LiveInspectReport> {
    let (host_port, base_prefix): (String, String) = parse_http_base_url(base_url)?;
    let health_path: String = format!("{base_prefix}{PATH_AI_HEALTH}");
    let health_resp: Result<(u16, String), Error> = http_get_text(&host_port, &health_path);
    let (reachable, health_status, err_opt): (bool, String, Option<String>) = match health_resp {
        Ok((200, body)) => {
            let status_str: String = from_str::<Value>(&body)
                .ok()
                .and_then(|val: Value| {
                    val.get(JSON_KEY_STATUS)
                        .and_then(Value::as_str)
                        .map(str::to_string)
                })
                .unwrap_or_else(|| STATUS_OK.to_string());
            (true, status_str, None)
        }
        Ok((code, _)) => (true, format!("http-{code}"), None),
        Err(err) => (
            false,
            INSPECT_UNREACHABLE_STATUS.to_string(),
            Some(err.to_string()),
        ),
    };
    if !reachable {
        let mut unreachable_report: LiveInspectReport =
            LiveInspectReport::new(base_url.to_string(), false, health_status);
        let _: &mut LiveInspectReport = unreachable_report
            .set_active_route(INSPECT_UNKNOWN_ROUTE.to_string())
            .set_error(err_opt);
        return Ok(unreachable_report);
    }
    let candidate_paths: [&str; 3] = [PATH_AI_SNAPSHOT_V2, PATH_AI_SNAPSHOT, PATH_AI_SCHEMA];
    let mut snapshot_json: Option<Value> = None;
    for suffix in candidate_paths.iter() {
        let full_path: String = format!("{base_prefix}{suffix}");
        if let Ok((200, body)) = http_get_text(&host_port, &full_path)
            && let Ok(parsed) = from_str::<Value>(&body)
        {
            snapshot_json = Some(parsed);
            break;
        }
    }
    let mut protocol_version: String = String::new();
    let mut active_route: String = INSPECT_UNKNOWN_ROUTE.to_string();
    let mut node_count: usize = 0;
    let mut anomalies: Vec<String> = Vec::new();
    if let Some(root_val) = snapshot_json {
        if let Some(proto) = root_val
            .get(JSON_KEY_PROTOCOL)
            .or_else(|| root_val.get(JSON_KEY_SCHEMA))
            .or_else(|| root_val.get(JSON_KEY_VERSION))
            .and_then(Value::as_str)
        {
            protocol_version = proto.to_string();
        }
        if let Some(route) = root_val
            .get(JSON_KEY_ACTIVE_ROUTE)
            .or_else(|| root_val.get(JSON_KEY_ROUTE))
            .and_then(Value::as_str)
        {
            active_route = route.to_string();
        }
        if let Some(count) = root_val.get(JSON_KEY_NODE_COUNT).and_then(Value::as_u64) {
            node_count = count as usize;
        } else if let Some(nodes_arr) = root_val.get(JSON_KEY_NODES).and_then(Value::as_array) {
            node_count = nodes_arr.len();
        }
        let anomaly_array: Option<&Vec<Value>> = root_val
            .get(JSON_KEY_ANOMALIES)
            .or_else(|| root_val.get(JSON_KEY_LAYOUT_ANOMALIES))
            .and_then(Value::as_array);
        if let Some(items) = anomaly_array {
            for item in items.iter() {
                anomalies.push(describe_anomaly_value(item));
            }
        }
    }
    let anomaly_count: usize = anomalies.len();
    let mut report: LiveInspectReport =
        LiveInspectReport::new(base_url.to_string(), true, health_status);
    let _: &mut LiveInspectReport = report
        .set_protocol_version(protocol_version)
        .set_active_route(active_route)
        .set_node_count(node_count)
        .set_anomaly_count(anomaly_count)
        .set_anomalies(anomalies);
    Ok(report)
}

/// Audits a local build distribution directory for bundle sizes, zero-JS compliance, and `euv-release.json` SHA-256 integrity.
///
/// # Arguments
///
/// - `&Path` - Local artifact output directory (e.g. `dist/web`).
///
/// # Returns
///
/// - `io::Result<DistInspectReport>` - Detailed artifact audit summary or I/O error.
pub fn inspect_dist_directory(dist_dir: &Path) -> io::Result<DistInspectReport> {
    if !dist_dir.is_dir() {
        return Err(Error::new(
            ErrorKind::NotFound,
            format!("{ERR_DIST_DIR_MISSING}: {}", dist_dir.display()),
        ));
    }
    let mut files: Vec<DistFileStat> = Vec::new();
    let mut js_files: Vec<String> = Vec::new();
    let mut total_bytes: u64 = 0;
    collect_dist_files(
        dist_dir,
        dist_dir,
        &mut files,
        &mut js_files,
        &mut total_bytes,
    )?;
    let file_count: usize = files.len();
    files.sort_by(|left: &DistFileStat, right: &DistFileStat| {
        right
            .get_size_bytes()
            .cmp(&left.get_size_bytes())
            .then_with(|| left.get_path().cmp(right.get_path()))
    });
    let largest_files: Vec<DistFileStat> =
        files.into_iter().take(INSPECT_MAX_LARGEST_FILES).collect();
    js_files.sort();
    let zero_js_compliant: bool = js_files.is_empty();
    let manifest_path: PathBuf = dist_dir.join(RELEASE_MANIFEST_NAME);
    let manifest_present: bool = manifest_path.is_file();
    let mut manifest_version: Option<String> = None;
    let mut manifest_errors: Vec<String> = Vec::new();
    if manifest_present {
        verify_release_manifest_file(
            dist_dir,
            &manifest_path,
            &mut manifest_version,
            &mut manifest_errors,
        );
    }
    let manifest_verified: bool = manifest_present && manifest_errors.is_empty();
    let mut report: DistInspectReport =
        DistInspectReport::new(dist_dir.display().to_string(), file_count, total_bytes);
    let _: &mut DistInspectReport = report
        .set_largest_files(largest_files)
        .set_js_files(js_files)
        .set_zero_js_compliant(zero_js_compliant)
        .set_manifest_present(manifest_present)
        .set_manifest_version(manifest_version)
        .set_manifest_verified(manifest_verified)
        .set_manifest_errors(manifest_errors);
    Ok(report)
}

/// Formats a `LiveInspectReport` for terminal display.
///
/// # Arguments
///
/// - `&LiveInspectReport` - Collected live bridge report.
/// - `bool` - When `true`, emphasizes layout anomaly findings.
///
/// # Returns
///
/// - `String` - Multi-line human-readable inspection report.
#[must_use]
pub fn format_live_inspect_report(report: &LiveInspectReport, anomalies_only: bool) -> String {
    let mut out: String = format!(
        "euv inspect — bridge: {} [{}]\n",
        report.get_url(),
        report.get_health_status()
    );
    if let Some(err) = report.try_get_error() {
        out.push_str(&format!("  error: {err}\n"));
        return out;
    }
    if !anomalies_only {
        out.push_str(&format!(
            "  protocol: {}\n  route: {}\n  nodes: {}\n",
            report.get_protocol_version(),
            report.get_active_route(),
            report.get_node_count()
        ));
    }
    out.push_str(&format!("  anomalies: {}\n", report.get_anomaly_count()));
    for item in report.get_anomalies().iter() {
        out.push_str(&format!("    - {item}\n"));
    }
    out
}

/// Formats a `DistInspectReport` into an aligned terminal summary.
///
/// # Arguments
///
/// - `&DistInspectReport` - Local artifact directory audit report.
///
/// # Returns
///
/// - `String` - Human-readable artifact audit summary.
#[must_use]
pub fn format_dist_inspect_report(report: &DistInspectReport) -> String {
    let zero_js_badge: &str = if report.get_zero_js_compliant() {
        StatusBadge::Pass.as_str()
    } else {
        StatusBadge::Fail.as_str()
    };
    let manifest_badge: &str = if !report.get_manifest_present() {
        StatusBadge::Skip.as_str()
    } else if report.get_manifest_verified() {
        StatusBadge::Pass.as_str()
    } else {
        StatusBadge::Fail.as_str()
    };
    let ver_label: &str = report
        .try_get_manifest_version()
        .as_deref()
        .unwrap_or(STATUS_MISSING);
    let mut out: String = format!(
        "euv inspect --dist {}\n  files: {} ({})\n  zero-js: [{}]\n  euv-release.json: [{}] (version={ver_label})\n\n",
        report.get_dist_dir(),
        report.get_file_count(),
        format_bytes_human(report.get_total_bytes()),
        zero_js_badge,
        manifest_badge
    );
    let mut table: TerminalTable = TerminalTable::with_headers(vec![
        INSPECT_HDR_FILE.to_string(),
        INSPECT_HDR_SIZE.to_string(),
    ]);
    for stat in report.get_largest_files().iter() {
        table.push_row(vec![
            stat.get_path().clone(),
            format_bytes_human(stat.get_size_bytes()),
        ]);
    }
    out.push_str(&table.render());
    for err in report.get_manifest_errors().iter() {
        out.push_str(&format!("  [{}] {err}\n", StatusBadge::Fail.as_str()));
    }
    out
}

/// Recursively collects regular files and flags forbidden `.js`/`.mjs`/`.d.ts` artifacts under `dir`.
///
/// # Arguments
///
/// - `&Path` - Root distribution directory.
/// - `&Path` - Current visited directory.
/// - `&mut Vec<DistFileStat>` - Collected file stat accumulator.
/// - `&mut Vec<String>` - Collected external JS/TS file paths.
/// - `&mut u64` - Aggregate byte counter.
///
/// # Returns
///
/// - `io::Result<()>` - Traversal outcome.
fn collect_dist_files(
    root: &Path,
    dir: &Path,
    files: &mut Vec<DistFileStat>,
    js_files: &mut Vec<String>,
    total_bytes: &mut u64,
) -> io::Result<()> {
    for entry_res in fs::read_dir(dir)? {
        let entry: DirEntry = entry_res?;
        let path: PathBuf = entry.path();
        let meta: Metadata = fs::symlink_metadata(&path)?;
        if meta.file_type().is_symlink() {
            continue;
        }
        if meta.is_dir() {
            collect_dist_files(root, &path, files, js_files, total_bytes)?;
            continue;
        }
        if !meta.is_file() {
            continue;
        }
        let rel_path: String = path
            .strip_prefix(root)
            .unwrap_or(&path)
            .to_string_lossy()
            .replace('\\', "/");
        let lower: String = rel_path.to_ascii_lowercase();
        if lower.ends_with(SUFFIX_JS) || lower.ends_with(SUFFIX_MJS) || lower.ends_with(SUFFIX_DTS)
        {
            js_files.push(rel_path.clone());
        }
        let size: u64 = meta.len();
        *total_bytes = total_bytes.saturating_add(size);
        files.push(DistFileStat::new(rel_path, size));
    }
    Ok(())
}

/// Validates `euv-release.json` schema, file existence, byte sizes, and SHA-256 digests.
///
/// # Arguments
///
/// - `&Path` - Distribution root directory.
/// - `&Path` - Path to `euv-release.json`.
/// - `&mut Option<String>` - Output slot populated with manifest version.
/// - `&mut Vec<String>` - Output list of integrity error messages.
fn verify_release_manifest_file(
    dist_dir: &Path,
    manifest_path: &Path,
    manifest_version: &mut Option<String>,
    errors: &mut Vec<String>,
) {
    let raw: String = match fs::read_to_string(manifest_path) {
        Ok(content) => content,
        Err(err) => {
            errors.push(format!("failed to read {RELEASE_MANIFEST_NAME}: {err}"));
            return;
        }
    };
    let parsed: Value = match from_str::<Value>(&raw) {
        Ok(val) => val,
        Err(err) => {
            errors.push(format!("invalid JSON in {RELEASE_MANIFEST_NAME}: {err}"));
            return;
        }
    };
    let format_ver: Option<u64> = parsed.get(JSON_KEY_FORMAT).and_then(Value::as_u64);
    if format_ver != Some(1) {
        errors.push(format!(
            "unsupported manifest format: expected 1, got {format_ver:?}"
        ));
    }
    *manifest_version = parsed
        .get(JSON_KEY_VERSION)
        .and_then(Value::as_str)
        .map(str::to_string);
    let Some(file_entries) = parsed.get(JSON_KEY_FILES).and_then(Value::as_array) else {
        errors.push(format!("missing files array in {RELEASE_MANIFEST_NAME}"));
        return;
    };
    for entry in file_entries.iter() {
        let Some(rel_path) = entry.get(JSON_KEY_PATH).and_then(Value::as_str) else {
            errors.push(format!(
                "manifest entry missing path in {RELEASE_MANIFEST_NAME}"
            ));
            continue;
        };
        let expected_sha: &str = entry
            .get(JSON_KEY_SHA256)
            .and_then(Value::as_str)
            .unwrap_or("");
        let expected_size: u64 = entry
            .get(JSON_KEY_SIZE)
            .and_then(Value::as_u64)
            .unwrap_or(0);
        let full_path: PathBuf = dist_dir.join(rel_path);
        match fs::read(&full_path) {
            Ok(bytes) => {
                if (bytes.len() as u64) != expected_size {
                    errors.push(format!(
                        "size mismatch for {rel_path}: expected {expected_size}, got {}",
                        bytes.len()
                    ));
                }
                let actual_sha: String = sha256_hex(&bytes);
                if actual_sha != expected_sha {
                    errors.push(format!(
                        "sha256 mismatch for {rel_path}: expected {expected_sha}, got {actual_sha}"
                    ));
                }
            }
            Err(_) => {
                errors.push(format!("manifest file missing on disk: {rel_path}"));
            }
        }
    }
}

/// Converts a raw anomaly JSON object or string into a readable single-line description.
///
/// # Arguments
///
/// - `&Value` - Anomaly JSON element.
///
/// # Returns
///
/// - `String` - Readable anomaly summary.
fn describe_anomaly_value(value: &Value) -> String {
    if let Some(text) = value.as_str() {
        return text.to_string();
    }
    let rule: &str = value
        .get(JSON_KEY_RULE)
        .or_else(|| value.get(JSON_KEY_KIND))
        .and_then(Value::as_str)
        .unwrap_or("");
    let msg: &str = value
        .get(JSON_KEY_MESSAGE)
        .and_then(Value::as_str)
        .unwrap_or("");
    if !rule.is_empty() && !msg.is_empty() {
        format!("[{rule}] {msg}")
    } else if !msg.is_empty() {
        msg.to_string()
    } else if !rule.is_empty() {
        rule.to_string()
    } else {
        value.to_string()
    }
}

/// Parses an `http://host[:port][/prefix]` base URL into `(host_port, normalized_prefix)`.
///
/// # Arguments
///
/// - `&str` - Raw HTTP URL string.
///
/// # Returns
///
/// - `io::Result<(String, String)>` - Socket address target and path prefix.
fn parse_http_base_url(base_url: &str) -> io::Result<(String, String)> {
    let trimmed: &str = base_url.trim().trim_end_matches('/');
    let Some(rest) = trimmed.strip_prefix(HTTP_SCHEME_PREFIX) else {
        return Err(Error::new(
            ErrorKind::InvalidInput,
            format!("{ERR_INVALID_INSPECT_URL}: `{base_url}`"),
        ));
    };
    let (authority, prefix): (&str, &str) = match rest.find('/') {
        Some(idx) => (&rest[..idx], &rest[idx..]),
        None => (rest, ""),
    };
    if authority.is_empty() {
        return Err(Error::new(
            ErrorKind::InvalidInput,
            format!("{ERR_INVALID_INSPECT_URL}: `{base_url}`"),
        ));
    }
    let host_port: String = if authority.contains(':') {
        authority.to_string()
    } else {
        format!("{authority}:80")
    };
    Ok((host_port, prefix.to_string()))
}

/// Performs a pure-std HTTP/1.1 `GET` request and returns `(status_code, utf8_body)`.
///
/// # Arguments
///
/// - `&str` - Target `host:port` authority.
/// - `&str` - Request path (starting with `/`).
///
/// # Returns
///
/// - `io::Result<(u16, String)>` - HTTP status code and decoded UTF-8 body.
fn http_get_text(host_port: &str, path: &str) -> io::Result<(u16, String)> {
    let mut stream: TcpStream = TcpStream::connect(host_port)?;
    stream.set_read_timeout(Some(Duration::from_secs(3)))?;
    stream.set_write_timeout(Some(Duration::from_secs(3)))?;
    let request: String =
        format!("GET {path} HTTP/1.1\r\nHost: {host_port}\r\nConnection: close\r\n\r\n");
    stream.write_all(request.as_bytes())?;
    stream.flush()?;
    let mut raw: Vec<u8> = Vec::new();
    let _: usize = stream.read_to_end(&mut raw)?;
    let split_pos: usize = raw
        .windows(HTTP_HEADER_DELIM.len())
        .position(|window: &[u8]| window == HTTP_HEADER_DELIM)
        .ok_or_else(|| Error::new(ErrorKind::InvalidData, ERR_MALFORMED_HTTP_RESPONSE))?;
    let head_text: String = String::from_utf8_lossy(&raw[..split_pos]).into_owned();
    let body_bytes: &[u8] = &raw[split_pos + HTTP_HEADER_DELIM.len()..];
    let status_code: u16 = head_text
        .lines()
        .next()
        .and_then(|line: &str| line.split_whitespace().nth(1))
        .and_then(|code: &str| code.parse::<u16>().ok())
        .unwrap_or_else(|| {
            if head_text.contains(HTTP_STATUS_OK_TOKEN) {
                200
            } else {
                0
            }
        });
    let is_chunked: bool = head_text.lines().any(|line: &str| {
        let lower: String = line.to_ascii_lowercase();
        lower.starts_with(HTTP_HDR_TRANSFER_ENCODING) && lower.contains(HTTP_TOKEN_CHUNKED)
    });
    let decoded: Vec<u8> = if is_chunked {
        decode_chunked_body(body_bytes)
    } else {
        body_bytes.to_vec()
    };
    Ok((status_code, String::from_utf8_lossy(&decoded).into_owned()))
}

/// Decodes an HTTP/1.1 `Transfer-Encoding: chunked` body slice into contiguous bytes.
///
/// # Arguments
///
/// - `&[u8]` - Raw chunked HTTP response payload.
///
/// # Returns
///
/// - `Vec<u8>` - Decoded contiguous body bytes.
fn decode_chunked_body(raw: &[u8]) -> Vec<u8> {
    let mut out: Vec<u8> = Vec::new();
    let mut pos: usize = 0;
    while pos < raw.len() {
        let Some(rel_crlf) = raw[pos..]
            .windows(HTTP_CRLF_BYTES.len())
            .position(|pair: &[u8]| pair == HTTP_CRLF_BYTES)
        else {
            break;
        };
        let size_hex: &str = from_utf8(&raw[pos..pos + rel_crlf])
            .unwrap_or("")
            .split(';')
            .next()
            .unwrap_or("")
            .trim();
        let Ok(chunk_len) = usize::from_str_radix(size_hex, 16) else {
            break;
        };
        pos += rel_crlf + HTTP_CRLF_BYTES.len();
        if chunk_len == 0 || pos + chunk_len > raw.len() {
            break;
        }
        out.extend_from_slice(&raw[pos..pos + chunk_len]);
        pos += chunk_len;
        if pos + HTTP_CRLF_BYTES.len() <= raw.len()
            && &raw[pos..pos + HTTP_CRLF_BYTES.len()] == HTTP_CRLF_BYTES
        {
            pos += HTTP_CRLF_BYTES.len();
        }
    }
    out
}