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
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
use super::*;

/// Computes the standard IEEE 802.3 CRC-32 checksum used by PNG, PKZIP, and GZIP.
///
/// # Arguments
///
/// - `&[u8]` - Input byte slice.
///
/// # Returns
///
/// - `u32` - Computed CRC-32 checksum.
#[must_use]
pub fn crc32_bytes(data: &[u8]) -> u32 {
    let mut crc: u32 = 0xFFFF_FFFF;
    for &byte_val in data.iter() {
        crc ^= u32::from(byte_val);
        let mut bit_idx: u8 = 0;
        while bit_idx < 8 {
            if (crc & 1) != 0 {
                crc = (crc >> 1) ^ CRC32_POLY;
            } else {
                crc >>= 1;
            }
            bit_idx += 1;
        }
    }
    !crc
}

/// Computes the RFC 1950 Adler-32 checksum used inside zlib streams and PNG `IDAT` chunks.
///
/// # Arguments
///
/// - `&[u8]` - Input byte slice.
///
/// # Returns
///
/// - `u32` - Computed Adler-32 checksum.
#[must_use]
pub fn adler32_bytes(data: &[u8]) -> u32 {
    let mut sum_low: u32 = 1;
    let mut sum_high: u32 = 0;
    for &byte_val in data.iter() {
        sum_low = (sum_low + u32::from(byte_val)) % ADLER32_MOD;
        sum_high = (sum_high + sum_low) % ADLER32_MOD;
    }
    (sum_high << 16) | sum_low
}

/// Compresses raw bytes into an RFC 1951 raw DEFLATE bitstream.
///
/// # Arguments
///
/// - `&[u8]` - Uncompressed input bytes.
///
/// # Returns
///
/// - `Vec<u8>` - Compressed RFC 1951 DEFLATE stream.
#[must_use]
pub fn deflate_compress(input: &[u8]) -> Vec<u8> {
    if input.is_empty() {
        return deflate_store_blocks(input);
    }
    let fixed: Vec<u8> = deflate_fixed_lz77(input);
    let stored_estimate: usize = input.len() + ((input.len() / DEFLATE_MAX_STORED_BLOCK) + 1) * 5;
    if fixed.len() <= stored_estimate {
        fixed
    } else {
        deflate_store_blocks(input)
    }
}

/// Decompresses an RFC 1951 raw DEFLATE bitstream (stored, fixed Huffman, and dynamic Huffman).
///
/// # Arguments
///
/// - `&[u8]` - Compressed RFC 1951 DEFLATE payload.
///
/// # Returns
///
/// - `io::Result<Vec<u8>>` - Decompressed bytes or error if malformed.
pub fn deflate_decompress(input: &[u8]) -> io::Result<Vec<u8>> {
    let mut reader: DeflateBitReader<'_> = DeflateBitReader::new(input);
    let mut out: Vec<u8> = Vec::new();
    loop {
        let is_final: u32 = reader.read_bits(1)?;
        let block_type: u32 = reader.read_bits(2)?;
        match block_type {
            0 => {
                reader.align_byte();
                let block_len: u16 = reader.read_aligned_u16()?;
                let inverted_len: u16 = reader.read_aligned_u16()?;
                if block_len != !inverted_len {
                    return Err(Error::new(ErrorKind::InvalidData, ERR_DEFLATE_INVALID));
                }
                reader.read_aligned_bytes(usize::from(block_len), &mut out)?;
            }
            1 => {
                let (lit_dec, dist_dec): (HuffmanDecoder, HuffmanDecoder) = build_fixed_decoders()?;
                decode_huffman_block(&mut reader, &lit_dec, &dist_dec, &mut out)?;
            }
            2 => {
                let (lit_dec, dist_dec): (HuffmanDecoder, HuffmanDecoder) =
                    read_dynamic_decoders(&mut reader)?;
                decode_huffman_block(&mut reader, &lit_dec, &dist_dec, &mut out)?;
            }
            _ => return Err(Error::new(ErrorKind::InvalidData, ERR_DEFLATE_INVALID)),
        }
        if is_final != 0 {
            break;
        }
    }
    Ok(out)
}

/// Compresses bytes into a standard RFC 1950 zlib stream with Adler-32 trailer.
///
/// # Arguments
///
/// - `&[u8]` - Uncompressed input bytes.
///
/// # Returns
///
/// - `Vec<u8>` - Complete RFC 1950 zlib byte stream.
#[must_use]
pub fn zlib_compress(input: &[u8]) -> Vec<u8> {
    let body: Vec<u8> = deflate_compress(input);
    let checksum: u32 = adler32_bytes(input);
    let mut out: Vec<u8> = Vec::with_capacity(body.len() + 6);
    out.push(ZLIB_HEADER_CMF);
    out.push(ZLIB_HEADER_FLG);
    out.extend_from_slice(&body);
    out.extend_from_slice(&checksum.to_be_bytes());
    out
}

/// Decompresses an RFC 1950 zlib stream and validates its header and Adler-32 checksum.
///
/// # Arguments
///
/// - `&[u8]` - Compressed zlib byte stream.
///
/// # Returns
///
/// - `io::Result<Vec<u8>>` - Verified decompressed bytes.
pub fn zlib_decompress(input: &[u8]) -> io::Result<Vec<u8>> {
    if input.len() < 6 {
        return Err(Error::new(ErrorKind::InvalidData, ERR_ZLIB_INVALID));
    }
    let cmf: u8 = input[0];
    let flg: u8 = input[1];
    let check_word: u16 = (u16::from(cmf) << 8) | u16::from(flg);
    if (cmf & 0x0F) != 8 || (flg & 0x20) != 0 || !check_word.is_multiple_of(31) {
        return Err(Error::new(ErrorKind::InvalidData, ERR_ZLIB_INVALID));
    }
    let body_end: usize = input.len() - 4;
    let decoded: Vec<u8> = deflate_decompress(&input[2..body_end])?;
    let expected: u32 = u32::from_be_bytes([
        input[body_end],
        input[body_end + 1],
        input[body_end + 2],
        input[body_end + 3],
    ]);
    let actual: u32 = adler32_bytes(&decoded);
    if actual != expected {
        return Err(Error::new(ErrorKind::InvalidData, ERR_ZLIB_INVALID));
    }
    Ok(decoded)
}

/// Compresses bytes into a standard RFC 1952 GZIP stream with CRC-32 and ISIZE trailers.
///
/// # Arguments
///
/// - `&[u8]` - Uncompressed input bytes.
///
/// # Returns
///
/// - `Vec<u8>` - Complete RFC 1952 GZIP byte stream.
#[must_use]
pub fn gzip_compress(input: &[u8]) -> Vec<u8> {
    let body: Vec<u8> = deflate_compress(input);
    let checksum: u32 = crc32_bytes(input);
    let isize_val: u32 = input.len() as u32;
    let mut out: Vec<u8> = Vec::with_capacity(GZIP_HEADER_BYTES.len() + body.len() + 8);
    out.extend_from_slice(&GZIP_HEADER_BYTES);
    out.extend_from_slice(&body);
    out.extend_from_slice(&checksum.to_le_bytes());
    out.extend_from_slice(&isize_val.to_le_bytes());
    out
}

/// Decompresses an RFC 1952 GZIP stream and verifies its CRC-32 and ISIZE trailers.
///
/// # Arguments
///
/// - `&[u8]` - Compressed GZIP byte stream.
///
/// # Returns
///
/// - `io::Result<Vec<u8>>` - Verified decompressed bytes.
pub fn gzip_decompress(input: &[u8]) -> io::Result<Vec<u8>> {
    if input.len() < 18 || input[0] != 0x1F || input[1] != 0x8B || input[2] != 0x08 {
        return Err(Error::new(ErrorKind::InvalidData, ERR_GZIP_INVALID));
    }
    let flags: u8 = input[3];
    let mut offset: usize = 10;
    if (flags & 0x04) != 0 {
        if offset + 2 > input.len() {
            return Err(Error::new(ErrorKind::InvalidData, ERR_GZIP_INVALID));
        }
        let extra_len: usize = usize::from(u16::from_le_bytes([input[offset], input[offset + 1]]));
        offset += 2 + extra_len;
    }
    if (flags & 0x08) != 0 {
        while offset < input.len() && input[offset] != 0 {
            offset += 1;
        }
        offset += 1;
    }
    if (flags & 0x10) != 0 {
        while offset < input.len() && input[offset] != 0 {
            offset += 1;
        }
        offset += 1;
    }
    if (flags & 0x02) != 0 {
        offset += 2;
    }
    if offset + 8 > input.len() {
        return Err(Error::new(ErrorKind::InvalidData, ERR_GZIP_INVALID));
    }
    let trailer_pos: usize = input.len() - 8;
    let decoded: Vec<u8> = deflate_decompress(&input[offset..trailer_pos])?;
    let expected_crc: u32 = u32::from_le_bytes([
        input[trailer_pos],
        input[trailer_pos + 1],
        input[trailer_pos + 2],
        input[trailer_pos + 3],
    ]);
    let expected_len: u32 = u32::from_le_bytes([
        input[trailer_pos + 4],
        input[trailer_pos + 5],
        input[trailer_pos + 6],
        input[trailer_pos + 7],
    ]);
    if crc32_bytes(&decoded) != expected_crc || (decoded.len() as u32) != expected_len {
        return Err(Error::new(ErrorKind::InvalidData, ERR_GZIP_INVALID));
    }
    Ok(decoded)
}

/// Validates whether `version` matches strict numeric semantic versioning `MAJOR.MINOR.PATCH`.
///
/// # Arguments
///
/// - `&str` - Candidate version string.
///
/// # Returns
///
/// - `bool` - `true` when strictly numeric `MAJOR.MINOR.PATCH` without leading zeroes.
#[must_use]
pub fn is_valid_numeric_semver(version: &str) -> bool {
    let parts: Vec<&str> = version.split('.').collect();
    if parts.len() != 3 {
        return false;
    }
    parts.iter().all(|part: &&str| {
        if part.is_empty() || !part.bytes().all(|byte_val: u8| byte_val.is_ascii_digit()) {
            return false;
        }
        part.len() == 1 || !part.starts_with('0')
    })
}

/// Validates that a forward-slash relative release path contains no traversal, control, or reserved segments.
///
/// # Arguments
///
/// - `&str` - POSIX-style relative file path inside a release directory.
///
/// # Returns
///
/// - `bool` - `true` when safe to emit into `euv-release.json`.
#[must_use]
pub fn is_safe_release_relative_path(relative: &str) -> bool {
    if relative.is_empty() {
        return false;
    }
    for byte_val in relative.bytes() {
        let forbidden: bool = RELEASE_FORBIDDEN_PATH_BYTES.contains(&byte_val);
        if byte_val < 32 || byte_val == 127 || forbidden {
            return false;
        }
    }
    for segment in relative.split('/') {
        if segment.is_empty()
            || segment == "."
            || segment == ".."
            || RELEASE_MANIFEST_RESERVED_NAMES.contains(&segment)
        {
            return false;
        }
    }
    true
}

/// Generates and writes the deterministic SHA-256 `euv-release.json` manifest for `dist_dir`.
///
/// # Arguments
///
/// - `&Path` - Distribution root directory containing `index.html` and release assets.
/// - `&str` - Numeric semantic version string (`MAJOR.MINOR.PATCH`).
///
/// # Returns
///
/// - `io::Result<ReleaseAssetManifest>` - Written manifest inventory or validation error.
pub fn write_release_manifest(dist_dir: &Path, version: &str) -> io::Result<ReleaseAssetManifest> {
    if !is_valid_numeric_semver(version) {
        return Err(Error::new(ErrorKind::InvalidInput, ERR_INVALID_SEMVER));
    }
    let root_meta: Metadata = fs::symlink_metadata(dist_dir)?;
    if root_meta.file_type().is_symlink() || !root_meta.is_dir() {
        return Err(Error::new(ErrorKind::InvalidInput, ERR_INVALID_DIST_DIR));
    }
    let mut collected_paths: Vec<(String, PathBuf)> = Vec::new();
    collect_release_files_recursive(dist_dir, dist_dir, &mut collected_paths)?;
    collected_paths
        .sort_by(|left: &(String, PathBuf), right: &(String, PathBuf)| left.0.cmp(&right.0));
    let mut entries: Vec<ReleaseManifestFileEntry> = Vec::with_capacity(collected_paths.len());
    let mut has_nonempty_index: bool = false;
    for (relative, full_path) in collected_paths.into_iter() {
        let data: Vec<u8> = fs::read(&full_path)?;
        let digest: String = sha256_hex(&data);
        let size: u64 = data.len() as u64;
        if relative == RELEASE_MANIFEST_INDEX_HTML && size > 0 {
            has_nonempty_index = true;
        }
        entries.push(ReleaseManifestFileEntry::new(relative, digest, size));
    }
    if !has_nonempty_index {
        return Err(Error::new(ErrorKind::InvalidInput, ERR_MISSING_INDEX_HTML));
    }
    let manifest: ReleaseAssetManifest =
        ReleaseAssetManifest::new(RELEASE_MANIFEST_FORMAT, version.to_string(), entries);
    let mut json_text: String = to_string_pretty(&manifest)
        .map_err(|err: serde_json::Error| Error::other(err.to_string()))?;
    json_text.push('\n');
    fs::write(dist_dir.join(RELEASE_MANIFEST_NAME), json_text.as_bytes())?;
    Ok(manifest)
}

/// Verifies `euv-release.json` schema, version, required assets, sizes, and SHA-256 digests on disk.
///
/// # Arguments
///
/// - `&Path` - Distribution root directory containing `euv-release.json`.
/// - `Option<&str>` - Optional expected release semantic version to enforce.
/// - `&[&str]` - Required relative asset paths that must exist and be non-empty.
///
/// # Returns
///
/// - `io::Result<ReleaseAssetManifest>` - Verified release manifest or integrity error.
pub fn verify_release_manifest(
    dist_dir: &Path,
    expected_version: Option<&str>,
    required_files: &[&str],
) -> io::Result<ReleaseAssetManifest> {
    let manifest_path: PathBuf = dist_dir.join(RELEASE_MANIFEST_NAME);
    let raw_json: String = fs::read_to_string(&manifest_path)?;
    let manifest: ReleaseAssetManifest = from_str(&raw_json)
        .map_err(|err: serde_json::Error| Error::new(ErrorKind::InvalidData, err.to_string()))?;
    if manifest.get_format() != RELEASE_MANIFEST_FORMAT {
        return Err(Error::new(ErrorKind::InvalidData, ERR_MANIFEST_FORMAT));
    }
    if !is_valid_numeric_semver(manifest.get_version()) {
        return Err(Error::new(ErrorKind::InvalidData, ERR_INVALID_SEMVER));
    }
    if let Some(expected) = expected_version
        && manifest.get_version() != expected
    {
        return Err(Error::new(
            ErrorKind::InvalidData,
            format!(
                "{ERR_MANIFEST_VERSION}: {} != {expected}",
                manifest.get_version()
            ),
        ));
    }
    let mut indexed: BTreeMap<&str, &ReleaseManifestFileEntry> = BTreeMap::new();
    for entry in manifest.get_files().iter() {
        let rel_path: &str = entry.get_path().as_str();
        if !is_safe_release_relative_path(rel_path) {
            return Err(Error::new(
                ErrorKind::InvalidData,
                format!("{ERR_UNSAFE_RELEASE_PATH}: {rel_path}"),
            ));
        }
        let disk_path: PathBuf = dist_dir.join(rel_path);
        let meta: Metadata = fs::symlink_metadata(&disk_path)?;
        if meta.file_type().is_symlink() {
            return Err(Error::new(
                ErrorKind::InvalidData,
                format!("{ERR_SYMLINK_FORBIDDEN}: {rel_path}"),
            ));
        }
        if !meta.is_file() {
            return Err(Error::new(
                ErrorKind::InvalidData,
                format!("{ERR_NOT_REGULAR_FILE}: {rel_path}"),
            ));
        }
        let raw_bytes: Vec<u8> = fs::read(&disk_path)?;
        if (raw_bytes.len() as u64) != entry.get_size() {
            return Err(Error::new(
                ErrorKind::InvalidData,
                format!("{ERR_MANIFEST_SIZE_MISMATCH}: {rel_path}"),
            ));
        }
        let actual_sha: String = sha256_hex(&raw_bytes);
        if actual_sha != *entry.get_sha256() {
            return Err(Error::new(
                ErrorKind::InvalidData,
                format!("{ERR_MANIFEST_SHA_MISMATCH}: {rel_path}"),
            ));
        }
        let _: Option<&ReleaseManifestFileEntry> = indexed.insert(rel_path, entry);
    }
    for &req_path in required_files.iter() {
        let found: Option<&&ReleaseManifestFileEntry> = indexed.get(req_path);
        if found.is_none_or(|entry: &&ReleaseManifestFileEntry| entry.get_size() == 0) {
            return Err(Error::new(
                ErrorKind::InvalidData,
                format!("{ERR_MANIFEST_REQUIRED_MISSING}: {req_path}"),
            ));
        }
    }
    Ok(manifest)
}

/// Counts occurrences of `euv.ai.schema.v1` and `euv.ai.schema.v2` marker bytes in a slice.
///
/// # Arguments
///
/// - `&[u8]` - Raw binary bytes to scan.
///
/// # Returns
///
/// - `(usize, usize)` - Tuple of `(v1_matches, v2_matches)`.
#[must_use]
pub fn scan_bytes_for_ai_schema(bytes: &[u8]) -> (usize, usize) {
    let v1_hits: usize = count_subslice_occurrences(bytes, AI_SCHEMA_V1_MARKER);
    let v2_hits: usize = count_subslice_occurrences(bytes, AI_SCHEMA_V2_MARKER);
    (v1_hits, v2_hits)
}

/// Scans an artifact file on disk for dev-only AI schema markers.
///
/// # Arguments
///
/// - `&Path` - Path to `.wasm`, `.so`, or native executable binary.
///
/// # Returns
///
/// - `io::Result<AiSchemaScanReport>` - Match counts across v1 and v2 schema markers.
pub fn scan_file_for_ai_schema(path: &Path) -> io::Result<AiSchemaScanReport> {
    let raw: Vec<u8> = fs::read(path)?;
    let (v1_hits, v2_hits): (usize, usize) = scan_bytes_for_ai_schema(&raw);
    Ok(AiSchemaScanReport::new(
        path.to_path_buf(),
        v1_hits,
        v2_hits,
        v1_hits + v2_hits,
    ))
}

/// Verifies that a release artifact contains zero dev-only AI schema marker bytes.
///
/// # Arguments
///
/// - `&Path` - Path to the compiled release binary.
///
/// # Returns
///
/// - `io::Result<AiSchemaScanReport>` - Clean report on zero matches, or an error on any leak.
pub fn verify_no_ai_schema_leak(path: &Path) -> io::Result<AiSchemaScanReport> {
    let report: AiSchemaScanReport = scan_file_for_ai_schema(path)?;
    if report.get_total_matches() > 0 {
        return Err(Error::new(
            ErrorKind::InvalidData,
            format!(
                "{ERR_AI_SCHEMA_LEAK}: {} (v1={}, v2={})",
                path.display(),
                report.get_v1_matches(),
                report.get_v2_matches()
            ),
        ));
    }
    Ok(report)
}

/// Writes a pure-Rust PKZIP archive with per-entry stored (`-0`) or DEFLATE compression.
///
/// # Arguments
///
/// - `&Path` - Destination `.zip` file path.
/// - `&[ZipEntryInput]` - Ordered slice of entries to archive.
///
/// # Returns
///
/// - `io::Result<u64>` - Total byte length of the written `.zip` file.
pub fn write_zip_entries(output_path: &Path, entries: &[ZipEntryInput]) -> io::Result<u64> {
    if let Some(parent) = output_path.parent()
        && !parent.as_os_str().is_empty()
    {
        fs::create_dir_all(parent)?;
    }
    let mut out: Vec<u8> = Vec::new();
    let mut records: Vec<ZipCentralRecord> = Vec::with_capacity(entries.len());
    for entry in entries.iter() {
        let normalized_name: String = normalize_archive_entry_name(entry.get_archive_path());
        let name_bytes: Vec<u8> = normalized_name.into_bytes();
        let raw_data: &[u8] = entry.get_data();
        let crc: u32 = crc32_bytes(raw_data);
        let (method, payload): (u16, Vec<u8>) = if entry.get_stored() {
            (ZIP_METHOD_STORED, raw_data.to_vec())
        } else {
            let deflated: Vec<u8> = deflate_compress(raw_data);
            if deflated.len() < raw_data.len() {
                (ZIP_METHOD_DEFLATE, deflated)
            } else {
                (ZIP_METHOD_STORED, raw_data.to_vec())
            }
        };
        let local_offset: u32 = out.len() as u32;
        let comp_size: u32 = payload.len() as u32;
        let uncomp_size: u32 = raw_data.len() as u32;
        let external_attrs: u32 = (ZIP_UNIX_REGULAR_FILE | (entry.get_unix_mode() & 0o7777)) << 16;
        push_zip_local_header(
            &mut out,
            &name_bytes,
            method,
            ZIP_FLAG_UTF8,
            crc,
            comp_size,
            uncomp_size,
        );
        out.extend_from_slice(&payload);
        records.push(ZipCentralRecord {
            name_bytes,
            method,
            flags: ZIP_FLAG_UTF8,
            crc32: crc,
            compressed_size: comp_size,
            uncompressed_size: uncomp_size,
            local_offset,
            external_attrs,
        });
    }
    finalize_zip_central_directory(&mut out, &records);
    fs::write(output_path, &out)?;
    Ok(out.len() as u64)
}

/// Appends or replaces entries inside an existing ZIP archive (e.g. packing stored `.dex`/`.so` into an APK).
///
/// # Arguments
///
/// - `&Path` - Path to the existing `.zip` or `.apk` file to update in place.
/// - `&[ZipEntryInput]` - Entries to append or replace by archive path.
///
/// # Returns
///
/// - `io::Result<u64>` - Final archive byte size after rewrite.
pub fn append_entries_to_zip(
    existing_zip: &Path,
    extra_entries: &[ZipEntryInput],
) -> io::Result<u64> {
    let raw_zip: Vec<u8> = fs::read(existing_zip)?;
    let existing: Vec<ExistingZipRawEntry> = parse_existing_zip_entries(&raw_zip)?;
    let mut replace_names: BTreeSet<String> = BTreeSet::new();
    for item in extra_entries.iter() {
        let _: bool = replace_names.insert(normalize_archive_entry_name(item.get_archive_path()));
    }
    let mut out: Vec<u8> = Vec::with_capacity(raw_zip.len() + 65_536);
    let mut records: Vec<ZipCentralRecord> =
        Vec::with_capacity(existing.len() + extra_entries.len());
    for entry in existing.into_iter() {
        if replace_names.contains(&entry.name) {
            continue;
        }
        let name_bytes: Vec<u8> = entry.name.into_bytes();
        let local_offset: u32 = out.len() as u32;
        let comp_size: u32 = entry.compressed_data.len() as u32;
        push_zip_local_header(
            &mut out,
            &name_bytes,
            entry.method,
            entry.flags,
            entry.crc32,
            comp_size,
            entry.uncompressed_size,
        );
        out.extend_from_slice(&entry.compressed_data);
        records.push(ZipCentralRecord {
            name_bytes,
            method: entry.method,
            flags: entry.flags,
            crc32: entry.crc32,
            compressed_size: comp_size,
            uncompressed_size: entry.uncompressed_size,
            local_offset,
            external_attrs: entry.external_attrs,
        });
    }
    for entry in extra_entries.iter() {
        let name_bytes: Vec<u8> =
            normalize_archive_entry_name(entry.get_archive_path()).into_bytes();
        let raw_data: &[u8] = entry.get_data();
        let crc: u32 = crc32_bytes(raw_data);
        let (method, payload): (u16, Vec<u8>) = if entry.get_stored() {
            (ZIP_METHOD_STORED, raw_data.to_vec())
        } else {
            let deflated: Vec<u8> = deflate_compress(raw_data);
            if deflated.len() < raw_data.len() {
                (ZIP_METHOD_DEFLATE, deflated)
            } else {
                (ZIP_METHOD_STORED, raw_data.to_vec())
            }
        };
        let local_offset: u32 = out.len() as u32;
        let comp_size: u32 = payload.len() as u32;
        let uncomp_size: u32 = raw_data.len() as u32;
        let external_attrs: u32 = (ZIP_UNIX_REGULAR_FILE | (entry.get_unix_mode() & 0o7777)) << 16;
        push_zip_local_header(
            &mut out,
            &name_bytes,
            method,
            ZIP_FLAG_UTF8,
            crc,
            comp_size,
            uncomp_size,
        );
        out.extend_from_slice(&payload);
        records.push(ZipCentralRecord {
            name_bytes,
            method,
            flags: ZIP_FLAG_UTF8,
            crc32: crc,
            compressed_size: comp_size,
            uncompressed_size: uncomp_size,
            local_offset,
            external_attrs,
        });
    }
    finalize_zip_central_directory(&mut out, &records);
    fs::write(existing_zip, &out)?;
    Ok(out.len() as u64)
}

/// Recursively archives all files in `source_dir` into a deterministic pure-Rust PKZIP file.
///
/// # Arguments
///
/// - `&Path` - Source directory to archive.
/// - `&Path` - Destination `.zip` file path.
/// - `bool` - When `true`, stores all entries uncompressed (`-0`); otherwise applies DEFLATE.
///
/// # Returns
///
/// - `io::Result<u64>` - Written `.zip` file byte size.
pub fn archive_directory_to_zip(
    source_dir: &Path,
    output_zip: &Path,
    store_only: bool,
) -> io::Result<u64> {
    let mut files: Vec<(String, PathBuf, u32)> = Vec::new();
    collect_archive_files_recursive(source_dir, source_dir, None, &mut files)?;
    files.sort_by(
        |left: &(String, PathBuf, u32), right: &(String, PathBuf, u32)| left.0.cmp(&right.0),
    );
    let mut entries: Vec<ZipEntryInput> = Vec::with_capacity(files.len());
    for (rel_path, disk_path, mode) in files.into_iter() {
        let data: Vec<u8> = fs::read(&disk_path)?;
        entries.push(ZipEntryInput::new(rel_path, data, store_only, mode));
    }
    write_zip_entries(output_zip, &entries)
}

/// Writes a deterministic pure-Rust gzipped POSIX ustar `.tar.gz` archive from explicit entries.
///
/// # Arguments
///
/// - `&Path` - Destination `.tar.gz` file path.
/// - `&[TarEntryInput]` - Ordered slice of file and directory entries.
///
/// # Returns
///
/// - `io::Result<u64>` - Written `.tar.gz` file byte size.
pub fn write_tar_gz_entries(output_path: &Path, entries: &[TarEntryInput]) -> io::Result<u64> {
    if let Some(parent) = output_path.parent()
        && !parent.as_os_str().is_empty()
    {
        fs::create_dir_all(parent)?;
    }
    let mut tar_bytes: Vec<u8> = Vec::new();
    for entry in entries.iter() {
        let mut norm_path: String = normalize_archive_entry_name(entry.get_archive_path());
        if entry.get_is_dir() && !norm_path.ends_with('/') {
            norm_path.push('/');
        }
        let data_len: usize = if entry.get_is_dir() {
            0
        } else {
            entry.get_data().len()
        };
        let header: [u8; TAR_BLOCK_SIZE] = build_ustar_header(
            &norm_path,
            entry.get_unix_mode(),
            data_len as u64,
            entry.get_is_dir(),
        )?;
        tar_bytes.extend_from_slice(&header);
        if !entry.get_is_dir() && data_len > 0 {
            tar_bytes.extend_from_slice(entry.get_data());
            let rem: usize = data_len % TAR_BLOCK_SIZE;
            if rem > 0 {
                tar_bytes.resize(tar_bytes.len() + (TAR_BLOCK_SIZE - rem), 0u8);
            }
        }
    }
    tar_bytes.resize(tar_bytes.len() + TAR_BLOCK_SIZE * 2, 0u8);
    let gz_bytes: Vec<u8> = gzip_compress(&tar_bytes);
    fs::write(output_path, &gz_bytes)?;
    Ok(gz_bytes.len() as u64)
}

/// Recursively archives `source_dir` into a deterministic pure-Rust `.tar.gz` archive.
///
/// # Arguments
///
/// - `&Path` - Source directory to archive.
/// - `&Path` - Destination `.tar.gz` file path.
/// - `Option<&str>` - Optional top-level path prefix (e.g. `Some("EuvShowcase.app")`).
///
/// # Returns
///
/// - `io::Result<u64>` - Written `.tar.gz` file byte size.
pub fn archive_directory_to_tar_gz(
    source_dir: &Path,
    output_tar_gz: &Path,
    root_prefix: Option<&str>,
) -> io::Result<u64> {
    let mut files: Vec<(String, PathBuf, u32)> = Vec::new();
    collect_archive_files_recursive(source_dir, source_dir, root_prefix, &mut files)?;
    files.sort_by(
        |left: &(String, PathBuf, u32), right: &(String, PathBuf, u32)| left.0.cmp(&right.0),
    );
    let mut entries: Vec<TarEntryInput> = Vec::with_capacity(files.len());
    for (rel_path, disk_path, mode) in files.into_iter() {
        let data: Vec<u8> = fs::read(&disk_path)?;
        entries.push(TarEntryInput::new(rel_path, data, mode, false));
    }
    write_tar_gz_entries(output_tar_gz, &entries)
}

/// Archives `source_dir` into either `.zip` or `.tar.gz` automatically based on `output_archive` extension.
///
/// # Arguments
///
/// - `&Path` - Source directory to archive.
/// - `&Path` - Destination archive path ending in `.zip`, `.tar.gz`, or `.tgz`.
/// - `Option<&str>` - Optional top-level archive prefix for `.tar.gz` bundles.
///
/// # Returns
///
/// - `io::Result<u64>` - Written archive byte size.
pub fn archive_directory_auto(
    source_dir: &Path,
    output_archive: &Path,
    root_prefix: Option<&str>,
) -> io::Result<u64> {
    let name_lower: String = output_archive
        .file_name()
        .map(|name: &OsStr| name.to_string_lossy().to_ascii_lowercase())
        .unwrap_or_default();
    if name_lower.ends_with(ARCHIVE_EXT_ZIP) {
        archive_directory_to_zip(source_dir, output_archive, false)
    } else if name_lower.ends_with(ARCHIVE_EXT_TAR_GZ) || name_lower.ends_with(ARCHIVE_EXT_TGZ) {
        archive_directory_to_tar_gz(source_dir, output_archive, root_prefix)
    } else {
        Err(Error::new(
            ErrorKind::InvalidInput,
            format!(
                "{ERR_UNSUPPORTED_ARCHIVE_EXT}: {}",
                output_archive.display()
            ),
        ))
    }
}

/// Emits uncompressed RFC 1951 stored DEFLATE blocks covering `input`.
///
/// # Arguments
///
/// - `&[u8]` - Raw bytes to wrap in stored DEFLATE blocks.
///
/// # Returns
///
/// - `Vec<u8>` - Stored DEFLATE stream.
fn deflate_store_blocks(input: &[u8]) -> Vec<u8> {
    let mut out: Vec<u8> = Vec::with_capacity(input.len() + 16);
    if input.is_empty() {
        out.push(0x01);
        out.extend_from_slice(&0u16.to_le_bytes());
        out.extend_from_slice(&0xFFFFu16.to_le_bytes());
        return out;
    }
    let mut offset: usize = 0;
    while offset < input.len() {
        let remaining: usize = input.len() - offset;
        let chunk_len: usize = cmp::min(remaining, DEFLATE_MAX_STORED_BLOCK);
        let is_final: u8 = if offset + chunk_len >= input.len() {
            1
        } else {
            0
        };
        out.push(is_final);
        let len_u16: u16 = chunk_len as u16;
        out.extend_from_slice(&len_u16.to_le_bytes());
        out.extend_from_slice(&(!len_u16).to_le_bytes());
        out.extend_from_slice(&input[offset..offset + chunk_len]);
        offset += chunk_len;
    }
    out
}

/// Compresses `input` using a single RFC 1951 Fixed-Huffman LZ77 block.
///
/// # Arguments
///
/// - `&[u8]` - Raw input bytes.
///
/// # Returns
///
/// - `Vec<u8>` - Compressed RFC 1951 bitstream.
fn deflate_fixed_lz77(input: &[u8]) -> Vec<u8> {
    let mut writer: DeflateBitWriter = DeflateBitWriter::with_capacity(input.len());
    writer.write_bits(1, 1);
    writer.write_bits(1, 2);
    let mut head: Vec<usize> = vec![DEFLATE_HASH_EMPTY; DEFLATE_HASH_BUCKETS];
    let mut pos: usize = 0;
    let total_len: usize = input.len();
    while pos < total_len {
        let mut best_len: usize = 0;
        let mut best_dist: usize = 0;
        if pos + DEFLATE_MIN_MATCH <= total_len {
            let bucket: usize = lz77_hash3(input[pos], input[pos + 1], input[pos + 2]);
            let prev: usize = head[bucket];
            head[bucket] = pos;
            if prev != DEFLATE_HASH_EMPTY && pos > prev {
                let dist: usize = pos - prev;
                if dist <= DEFLATE_WINDOW_SIZE {
                    let max_len: usize = cmp::min(DEFLATE_MAX_MATCH, total_len - pos);
                    let mut matched: usize = 0;
                    while matched < max_len && input[prev + matched] == input[pos + matched] {
                        matched += 1;
                    }
                    if matched >= DEFLATE_MIN_MATCH {
                        best_len = matched;
                        best_dist = dist;
                    }
                }
            }
        }
        if best_len >= DEFLATE_MIN_MATCH {
            emit_fixed_match(&mut writer, best_len, best_dist);
            let limit: usize = cmp::min(pos + best_len, total_len.saturating_sub(2));
            let mut step: usize = pos + 1;
            while step < limit {
                let bucket: usize = lz77_hash3(input[step], input[step + 1], input[step + 2]);
                head[bucket] = step;
                step += 1;
            }
            pos += best_len;
        } else {
            emit_fixed_literal(&mut writer, u16::from(input[pos]));
            pos += 1;
        }
    }
    emit_fixed_literal(&mut writer, DEFLATE_EOB_SYMBOL as u16);
    writer.finish()
}

/// Computes a 12-bit hash bucket index for 3 consecutive input bytes.
///
/// # Arguments
///
/// - `u8` - First byte.
/// - `u8` - Second byte.
/// - `u8` - Third byte.
///
/// # Returns
///
/// - `usize` - Bucket index in `0..DEFLATE_HASH_BUCKETS`.
fn lz77_hash3(first: u8, second: u8, third: u8) -> usize {
    let packed: u32 = (u32::from(first) << 16) + (u32::from(second) << 8) + u32::from(third);
    let mixed: u32 = packed.wrapping_mul(2_654_435_761);
    ((mixed >> 20) as usize) & (DEFLATE_HASH_BUCKETS - 1)
}

/// Emits one literal or length symbol using RFC 1951 fixed Huffman codewords.
///
/// # Arguments
///
/// - `&mut DeflateBitWriter` - Active bit writer.
/// - `u16` - Symbol value in `0..=285`.
fn emit_fixed_literal(writer: &mut DeflateBitWriter, symbol: u16) {
    let sym: u32 = u32::from(symbol);
    if sym <= 143 {
        writer.write_huffman_bits(0b0011_0000 + sym, 8);
    } else if sym <= 255 {
        writer.write_huffman_bits(0b1_1001_0000 + (sym - 144), 9);
    } else if sym <= 279 {
        writer.write_huffman_bits(sym - 256, 7);
    } else {
        writer.write_huffman_bits(0b1100_0000 + (sym - 280), 8);
    }
}

/// Emits a fixed-Huffman LZ77 `(length, distance)` back-reference pair.
///
/// # Arguments
///
/// - `&mut DeflateBitWriter` - Active bit writer.
/// - `usize` - Match length in `3..=258`.
/// - `usize` - Backward match distance in `1..=32768`.
fn emit_fixed_match(writer: &mut DeflateBitWriter, match_len: usize, match_dist: usize) {
    let len_u16: u16 = match_len as u16;
    let mut len_code_idx: usize = DEFLATE_LEN_BASE.len() - 1;
    let mut idx: usize = 0;
    while idx < DEFLATE_LEN_BASE.len() {
        let max_for_code: u16 = DEFLATE_LEN_BASE[idx] + ((1u16 << DEFLATE_LEN_EXTRA[idx]) - 1);
        if len_u16 >= DEFLATE_LEN_BASE[idx] && len_u16 <= max_for_code {
            len_code_idx = idx;
            break;
        }
        idx += 1;
    }
    emit_fixed_literal(writer, (257 + len_code_idx) as u16);
    let len_extra: u32 = u32::from(DEFLATE_LEN_EXTRA[len_code_idx]);
    if len_extra > 0 {
        let extra_val: u32 = u32::from(len_u16 - DEFLATE_LEN_BASE[len_code_idx]);
        writer.write_bits(extra_val, len_extra);
    }
    let dist_u16: u16 = match_dist as u16;
    let mut dist_code_idx: usize = DEFLATE_DIST_BASE.len() - 1;
    let mut d_idx: usize = 0;
    while d_idx < DEFLATE_DIST_BASE.len() {
        let max_for_code: u16 =
            DEFLATE_DIST_BASE[d_idx] + ((1u16 << DEFLATE_DIST_EXTRA[d_idx]) - 1);
        if dist_u16 >= DEFLATE_DIST_BASE[d_idx] && dist_u16 <= max_for_code {
            dist_code_idx = d_idx;
            break;
        }
        d_idx += 1;
    }
    writer.write_huffman_bits(dist_code_idx as u32, 5);
    let dist_extra: u32 = u32::from(DEFLATE_DIST_EXTRA[dist_code_idx]);
    if dist_extra > 0 {
        let extra_val: u32 = u32::from(dist_u16 - DEFLATE_DIST_BASE[dist_code_idx]);
        writer.write_bits(extra_val, dist_extra);
    }
}

/// Builds the RFC 1951 fixed literal/length and distance Huffman decoders.
///
/// # Returns
///
/// - `io::Result<(HuffmanDecoder, HuffmanDecoder)>` - Fixed literal/length and distance decoders.
fn build_fixed_decoders() -> io::Result<(HuffmanDecoder, HuffmanDecoder)> {
    let mut lit_lengths: [u8; 288] = [0u8; 288];
    let mut idx: usize = 0;
    while idx <= 143 {
        lit_lengths[idx] = 8;
        idx += 1;
    }
    while idx <= 255 {
        lit_lengths[idx] = 9;
        idx += 1;
    }
    while idx <= 279 {
        lit_lengths[idx] = 7;
        idx += 1;
    }
    while idx <= 287 {
        lit_lengths[idx] = 8;
        idx += 1;
    }
    let dist_lengths: [u8; 32] = [5u8; 32];
    let lit_dec: HuffmanDecoder = HuffmanDecoder::from_lengths(&lit_lengths)?;
    let dist_dec: HuffmanDecoder = HuffmanDecoder::from_lengths(&dist_lengths)?;
    Ok((lit_dec, dist_dec))
}

/// Parses dynamic Huffman tree headers from an RFC 1951 type-2 DEFLATE block.
///
/// # Arguments
///
/// - `&mut DeflateBitReader<'_>` - Active input bit reader.
///
/// # Returns
///
/// - `io::Result<(HuffmanDecoder, HuffmanDecoder)>` - Dynamic literal/length and distance decoders.
fn read_dynamic_decoders(
    reader: &mut DeflateBitReader<'_>,
) -> io::Result<(HuffmanDecoder, HuffmanDecoder)> {
    let hlit: usize = (reader.read_bits(5)? as usize) + 257;
    let hdist: usize = (reader.read_bits(5)? as usize) + 1;
    let hclen: usize = (reader.read_bits(4)? as usize) + 4;
    let invalid_counts: bool = hlit > 286 || hdist > 30;
    if invalid_counts || hclen > 19 {
        return Err(Error::new(ErrorKind::InvalidData, ERR_DEFLATE_INVALID));
    }
    let mut clen_lengths: [u8; 19] = [0u8; 19];
    let mut idx: usize = 0;
    while idx < hclen {
        clen_lengths[DEFLATE_CLEN_ORDER[idx]] = reader.read_bits(3)? as u8;
        idx += 1;
    }
    let clen_decoder: HuffmanDecoder = HuffmanDecoder::from_lengths(&clen_lengths)?;
    let total_codes: usize = hlit + hdist;
    let mut combined: Vec<u8> = Vec::with_capacity(total_codes);
    while combined.len() < total_codes {
        let sym: u16 = clen_decoder.decode(reader)?;
        match sym {
            0..=15 => combined.push(sym as u8),
            16 => {
                let repeat_count: usize = (reader.read_bits(2)? as usize) + 3;
                let prev_len: u8 = *combined
                    .last()
                    .ok_or_else(|| Error::new(ErrorKind::InvalidData, ERR_DEFLATE_INVALID))?;
                if combined.len() + repeat_count > total_codes {
                    return Err(Error::new(ErrorKind::InvalidData, ERR_DEFLATE_INVALID));
                }
                combined.resize(combined.len() + repeat_count, prev_len);
            }
            17 => {
                let repeat_count: usize = (reader.read_bits(3)? as usize) + 3;
                if combined.len() + repeat_count > total_codes {
                    return Err(Error::new(ErrorKind::InvalidData, ERR_DEFLATE_INVALID));
                }
                combined.resize(combined.len() + repeat_count, 0u8);
            }
            18 => {
                let repeat_count: usize = (reader.read_bits(7)? as usize) + 11;
                if combined.len() + repeat_count > total_codes {
                    return Err(Error::new(ErrorKind::InvalidData, ERR_DEFLATE_INVALID));
                }
                combined.resize(combined.len() + repeat_count, 0u8);
            }
            _ => return Err(Error::new(ErrorKind::InvalidData, ERR_DEFLATE_INVALID)),
        }
    }
    let lit_dec: HuffmanDecoder = HuffmanDecoder::from_lengths(&combined[..hlit])?;
    let dist_dec: HuffmanDecoder = HuffmanDecoder::from_lengths(&combined[hlit..])?;
    Ok((lit_dec, dist_dec))
}

/// Decodes symbols from an RFC 1951 Huffman block until the End-of-Block symbol (`256`).
///
/// # Arguments
///
/// - `&mut DeflateBitReader<'_>` - Active input bit reader.
/// - `&HuffmanDecoder` - Literal/length Huffman decoder.
/// - `&HuffmanDecoder` - Distance Huffman decoder.
/// - `&mut Vec<u8>` - Destination decompressed output buffer.
///
/// # Returns
///
/// - `io::Result<()>` - Decoding completion status.
fn decode_huffman_block(
    reader: &mut DeflateBitReader<'_>,
    lit_dec: &HuffmanDecoder,
    dist_dec: &HuffmanDecoder,
    out: &mut Vec<u8>,
) -> io::Result<()> {
    loop {
        let sym: usize = usize::from(lit_dec.decode(reader)?);
        if sym < DEFLATE_EOB_SYMBOL {
            out.push(sym as u8);
        } else if sym == DEFLATE_EOB_SYMBOL {
            break;
        } else if sym <= 285 {
            let len_idx: usize = sym - 257;
            let len_extra: u32 = u32::from(DEFLATE_LEN_EXTRA[len_idx]);
            let copy_len: usize =
                usize::from(DEFLATE_LEN_BASE[len_idx]) + (reader.read_bits(len_extra)? as usize);
            let dist_sym: usize = usize::from(dist_dec.decode(reader)?);
            if dist_sym >= DEFLATE_DIST_BASE.len() {
                return Err(Error::new(ErrorKind::InvalidData, ERR_DEFLATE_INVALID));
            }
            let dist_extra: u32 = u32::from(DEFLATE_DIST_EXTRA[dist_sym]);
            let copy_dist: usize =
                usize::from(DEFLATE_DIST_BASE[dist_sym]) + (reader.read_bits(dist_extra)? as usize);
            if copy_dist == 0 || copy_dist > out.len() {
                return Err(Error::new(ErrorKind::InvalidData, ERR_DEFLATE_INVALID));
            }
            let mut copied: usize = 0;
            while copied < copy_len {
                let src_idx: usize = out.len() - copy_dist;
                let byte_val: u8 = out[src_idx];
                out.push(byte_val);
                copied += 1;
            }
        } else {
            return Err(Error::new(ErrorKind::InvalidData, ERR_DEFLATE_INVALID));
        }
    }
    Ok(())
}

/// Counts non-overlapping occurrences of `needle` inside `haystack`.
///
/// # Arguments
///
/// - `&[u8]` - Byte slice to search.
/// - `&[u8]` - Non-empty byte pattern to count.
///
/// # Returns
///
/// - `usize` - Number of matches found.
fn count_subslice_occurrences(haystack: &[u8], needle: &[u8]) -> usize {
    if needle.is_empty() || haystack.len() < needle.len() {
        return 0;
    }
    let mut hits: usize = 0;
    let mut offset: usize = 0;
    let limit: usize = haystack.len() - needle.len();
    while offset <= limit {
        if &haystack[offset..offset + needle.len()] == needle {
            hits += 1;
            offset += needle.len();
        } else {
            offset += 1;
        }
    }
    hits
}

/// Recursively collects regular non-reserved files under `dir` while rejecting symlinks and unsafe paths.
///
/// # Arguments
///
/// - `&Path` - Root distribution directory.
/// - `&Path` - Current directory being traversed.
/// - `&mut Vec<(String, PathBuf)>` - Accumulator of `(relative_posix_path, disk_path)`.
///
/// # Returns
///
/// - `io::Result<()>` - Traversal result.
fn collect_release_files_recursive(
    root: &Path,
    dir: &Path,
    out: &mut Vec<(String, PathBuf)>,
) -> io::Result<()> {
    let mut children: Vec<PathBuf> = Vec::new();
    for entry_res in fs::read_dir(dir)? {
        let entry: DirEntry = entry_res?;
        children.push(entry.path());
    }
    children.sort();
    for path in children.into_iter() {
        let rel_os: &Path = path
            .strip_prefix(root)
            .map_err(|err: StripPrefixError| Error::other(err.to_string()))?;
        let relative: String = path_to_posix_string(rel_os);
        let meta: Metadata = fs::symlink_metadata(&path)?;
        if meta.file_type().is_symlink() {
            return Err(Error::new(
                ErrorKind::InvalidInput,
                format!("{ERR_SYMLINK_FORBIDDEN}: {relative}"),
            ));
        }
        let file_name: String = path
            .file_name()
            .map(|name: &OsStr| name.to_string_lossy().into_owned())
            .unwrap_or_default();
        if RELEASE_MANIFEST_RESERVED_NAMES.contains(&file_name.as_str()) {
            continue;
        }
        if !is_safe_release_relative_path(&relative) {
            return Err(Error::new(
                ErrorKind::InvalidInput,
                format!("{ERR_UNSAFE_RELEASE_PATH}: {relative}"),
            ));
        }
        if meta.is_dir() {
            collect_release_files_recursive(root, &path, out)?;
        } else if meta.is_file() {
            out.push((relative, path));
        } else {
            return Err(Error::new(
                ErrorKind::InvalidInput,
                format!("{ERR_NOT_REGULAR_FILE}: {relative}"),
            ));
        }
    }
    Ok(())
}

/// Recursively collects files and UNIX modes for `.zip` or `.tar.gz` archiving.
///
/// # Arguments
///
/// - `&Path` - Root directory being archived.
/// - `&Path` - Current directory being scanned.
/// - `Option<&str>` - Optional leading archive directory prefix.
/// - `&mut Vec<(String, PathBuf, u32)>` - Accumulator of `(archive_path, disk_path, unix_mode)`.
///
/// # Returns
///
/// - `io::Result<()>` - Traversal result.
fn collect_archive_files_recursive(
    root: &Path,
    dir: &Path,
    root_prefix: Option<&str>,
    out: &mut Vec<(String, PathBuf, u32)>,
) -> io::Result<()> {
    let mut children: Vec<PathBuf> = Vec::new();
    for entry_res in fs::read_dir(dir)? {
        let entry: DirEntry = entry_res?;
        children.push(entry.path());
    }
    children.sort();
    for path in children.into_iter() {
        let meta: Metadata = fs::symlink_metadata(&path)?;
        if meta.is_dir() {
            collect_archive_files_recursive(root, &path, root_prefix, out)?;
        } else if meta.is_file() {
            let rel_os: &Path = path
                .strip_prefix(root)
                .map_err(|err: StripPrefixError| Error::other(err.to_string()))?;
            let rel_posix: String = path_to_posix_string(rel_os);
            let archive_path: String = match root_prefix {
                Some(prefix) if !prefix.trim_matches('/').is_empty() => {
                    format!("{}/{}", prefix.trim_matches('/'), rel_posix)
                }
                _ => rel_posix,
            };
            let mode: u32 = file_unix_mode(&meta);
            out.push((archive_path, path, mode));
        }
    }
    Ok(())
}

/// Extracts UNIX file permission bits from filesystem metadata with cross-platform fallback.
///
/// # Arguments
///
/// - `&Metadata` - File metadata.
///
/// # Returns
///
/// - `u32` - Permission bits (e.g. `0o755` or `0o644`).
fn file_unix_mode(meta: &Metadata) -> u32 {
    #[cfg(unix)]
    {
        let raw_mode: u32 = meta.permissions().mode() & 0o7777;
        if raw_mode == 0 {
            ARCHIVE_DEFAULT_FILE_MODE
        } else {
            raw_mode
        }
    }
    #[cfg(not(unix))]
    {
        let _: &Metadata = meta;
        ARCHIVE_DEFAULT_FILE_MODE
    }
}

/// Converts a relative filesystem path to forward-slash POSIX format.
///
/// # Arguments
///
/// - `&Path` - Relative path.
///
/// # Returns
///
/// - `String` - Slash-separated relative path string.
fn path_to_posix_string(path: &Path) -> String {
    let segments: Vec<String> = path
        .components()
        .map(|comp: Component<'_>| comp.as_os_str().to_string_lossy().into_owned())
        .collect();
    segments.join("/")
}

/// Normalizes an archive entry path to forward slashes without leading slashes.
///
/// # Arguments
///
/// - `&str` - Raw archive path string.
///
/// # Returns
///
/// - `String` - Normalized archive path.
fn normalize_archive_entry_name(raw: &str) -> String {
    raw.replace('\\', "/").trim_start_matches('/').to_string()
}

/// Appends a PKZIP Local File Header to `out`.
///
/// # Arguments
///
/// - `&mut Vec<u8>` - Destination archive buffer.
/// - `&[u8]` - UTF-8 filename bytes.
/// - `u16` - Compression method (`0` or `8`).
/// - `u16` - General-purpose bit flags.
/// - `u32` - Entry CRC-32 checksum.
/// - `u32` - Compressed payload length.
/// - `u32` - Uncompressed payload length.
fn push_zip_local_header(
    out: &mut Vec<u8>,
    name_bytes: &[u8],
    method: u16,
    flags: u16,
    crc: u32,
    comp_size: u32,
    uncomp_size: u32,
) {
    out.extend_from_slice(&ZIP_LOCAL_HEADER_SIG.to_le_bytes());
    out.extend_from_slice(&ZIP_VERSION_NEEDED.to_le_bytes());
    out.extend_from_slice(&flags.to_le_bytes());
    out.extend_from_slice(&method.to_le_bytes());
    out.extend_from_slice(&0u16.to_le_bytes());
    out.extend_from_slice(&0u16.to_le_bytes());
    out.extend_from_slice(&crc.to_le_bytes());
    out.extend_from_slice(&comp_size.to_le_bytes());
    out.extend_from_slice(&uncomp_size.to_le_bytes());
    out.extend_from_slice(&(name_bytes.len() as u16).to_le_bytes());
    out.extend_from_slice(&0u16.to_le_bytes());
    out.extend_from_slice(name_bytes);
}

/// Appends the PKZIP Central Directory and End of Central Directory record to `out`.
///
/// # Arguments
///
/// - `&mut Vec<u8>` - Destination archive buffer.
/// - `&[ZipCentralRecord]` - Accumulated central directory metadata records.
fn finalize_zip_central_directory(out: &mut Vec<u8>, records: &[ZipCentralRecord]) {
    let cd_offset: u32 = out.len() as u32;
    for rec in records.iter() {
        out.extend_from_slice(&ZIP_CENTRAL_HEADER_SIG.to_le_bytes());
        out.extend_from_slice(&ZIP_VERSION_MADE_BY.to_le_bytes());
        out.extend_from_slice(&ZIP_VERSION_NEEDED.to_le_bytes());
        out.extend_from_slice(&rec.flags.to_le_bytes());
        out.extend_from_slice(&rec.method.to_le_bytes());
        out.extend_from_slice(&0u16.to_le_bytes());
        out.extend_from_slice(&0u16.to_le_bytes());
        out.extend_from_slice(&rec.crc32.to_le_bytes());
        out.extend_from_slice(&rec.compressed_size.to_le_bytes());
        out.extend_from_slice(&rec.uncompressed_size.to_le_bytes());
        out.extend_from_slice(&(rec.name_bytes.len() as u16).to_le_bytes());
        out.extend_from_slice(&0u16.to_le_bytes());
        out.extend_from_slice(&0u16.to_le_bytes());
        out.extend_from_slice(&0u16.to_le_bytes());
        out.extend_from_slice(&0u16.to_le_bytes());
        out.extend_from_slice(&rec.external_attrs.to_le_bytes());
        out.extend_from_slice(&rec.local_offset.to_le_bytes());
        out.extend_from_slice(&rec.name_bytes);
    }
    let cd_size: u32 = (out.len() as u32) - cd_offset;
    let entry_count: u16 = records.len() as u16;
    out.extend_from_slice(&ZIP_EOCD_SIG.to_le_bytes());
    out.extend_from_slice(&0u16.to_le_bytes());
    out.extend_from_slice(&0u16.to_le_bytes());
    out.extend_from_slice(&entry_count.to_le_bytes());
    out.extend_from_slice(&entry_count.to_le_bytes());
    out.extend_from_slice(&cd_size.to_le_bytes());
    out.extend_from_slice(&cd_offset.to_le_bytes());
    out.extend_from_slice(&0u16.to_le_bytes());
}

/// Parses Central Directory records and raw compressed payloads from an existing ZIP byte slice.
///
/// # Arguments
///
/// - `&[u8]` - Complete bytes of an existing `.zip` or `.apk` file.
///
/// # Returns
///
/// - `io::Result<Vec<ExistingZipRawEntry>>` - Extracted raw entries preserving compression payloads.
fn parse_existing_zip_entries(raw: &[u8]) -> io::Result<Vec<ExistingZipRawEntry>> {
    if raw.len() < 22 {
        return Err(Error::new(ErrorKind::InvalidData, ERR_ZIP_INVALID));
    }
    let min_eocd: usize = raw.len().saturating_sub(65_557);
    let mut eocd_pos: Option<usize> = None;
    let mut cursor: usize = raw.len() - 22;
    loop {
        if read_le_u32(raw, cursor)? == ZIP_EOCD_SIG {
            eocd_pos = Some(cursor);
            break;
        }
        if cursor == min_eocd {
            break;
        }
        cursor -= 1;
    }
    let eocd: usize =
        eocd_pos.ok_or_else(|| Error::new(ErrorKind::InvalidData, ERR_ZIP_INVALID))?;
    let entry_count: usize = usize::from(read_le_u16(raw, eocd + 10)?);
    let cd_offset: usize = read_le_u32(raw, eocd + 16)? as usize;
    let mut cd_pos: usize = cd_offset;
    let mut entries: Vec<ExistingZipRawEntry> = Vec::with_capacity(entry_count);
    let mut idx: usize = 0;
    while idx < entry_count {
        if read_le_u32(raw, cd_pos)? != ZIP_CENTRAL_HEADER_SIG {
            return Err(Error::new(ErrorKind::InvalidData, ERR_ZIP_INVALID));
        }
        let flags: u16 = read_le_u16(raw, cd_pos + 8)?;
        let method: u16 = read_le_u16(raw, cd_pos + 10)?;
        let crc: u32 = read_le_u32(raw, cd_pos + 16)?;
        let comp_size: usize = read_le_u32(raw, cd_pos + 20)? as usize;
        let uncomp_size: u32 = read_le_u32(raw, cd_pos + 24)?;
        let name_len: usize = usize::from(read_le_u16(raw, cd_pos + 28)?);
        let extra_len: usize = usize::from(read_le_u16(raw, cd_pos + 30)?);
        let comment_len: usize = usize::from(read_le_u16(raw, cd_pos + 32)?);
        let external_attrs: u32 = read_le_u32(raw, cd_pos + 38)?;
        let local_offset: usize = read_le_u32(raw, cd_pos + 42)? as usize;
        let name_slice: &[u8] = raw
            .get(cd_pos + 46..cd_pos + 46 + name_len)
            .ok_or_else(|| Error::new(ErrorKind::InvalidData, ERR_ZIP_INVALID))?;
        let name: String = String::from_utf8_lossy(name_slice).into_owned();
        if read_le_u32(raw, local_offset)? != ZIP_LOCAL_HEADER_SIG {
            return Err(Error::new(ErrorKind::InvalidData, ERR_ZIP_INVALID));
        }
        let local_name_len: usize = usize::from(read_le_u16(raw, local_offset + 26)?);
        let local_extra_len: usize = usize::from(read_le_u16(raw, local_offset + 28)?);
        let data_start: usize = local_offset + 30 + local_name_len + local_extra_len;
        let data_end: usize = data_start
            .checked_add(comp_size)
            .ok_or_else(|| Error::new(ErrorKind::InvalidData, ERR_ZIP_INVALID))?;
        let payload: &[u8] = raw
            .get(data_start..data_end)
            .ok_or_else(|| Error::new(ErrorKind::InvalidData, ERR_ZIP_INVALID))?;
        entries.push(ExistingZipRawEntry {
            name,
            method,
            flags,
            crc32: crc,
            compressed_data: payload.to_vec(),
            uncompressed_size: uncomp_size,
            external_attrs,
        });
        cd_pos += 46 + name_len + extra_len + comment_len;
        idx += 1;
    }
    Ok(entries)
}

/// Reads a little-endian `u16` at `offset` with bounds validation.
///
/// # Arguments
///
/// - `&[u8]` - Source byte slice.
/// - `usize` - Starting byte offset.
///
/// # Returns
///
/// - `io::Result<u16>` - Decoded 16-bit integer.
fn read_le_u16(bytes: &[u8], offset: usize) -> io::Result<u16> {
    let slice: &[u8] = bytes
        .get(offset..offset + 2)
        .ok_or_else(|| Error::new(ErrorKind::InvalidData, ERR_ZIP_INVALID))?;
    Ok(u16::from_le_bytes([slice[0], slice[1]]))
}

/// Reads a little-endian `u32` at `offset` with bounds validation.
///
/// # Arguments
///
/// - `&[u8]` - Source byte slice.
/// - `usize` - Starting byte offset.
///
/// # Returns
///
/// - `io::Result<u32>` - Decoded 32-bit integer.
fn read_le_u32(bytes: &[u8], offset: usize) -> io::Result<u32> {
    let slice: &[u8] = bytes
        .get(offset..offset + 4)
        .ok_or_else(|| Error::new(ErrorKind::InvalidData, ERR_ZIP_INVALID))?;
    Ok(u32::from_le_bytes([slice[0], slice[1], slice[2], slice[3]]))
}

/// Constructs a 512-byte POSIX ustar tar header block.
///
/// # Arguments
///
/// - `&str` - Archive-relative POSIX entry path.
/// - `u32` - UNIX permission bits.
/// - `u64` - Entry payload byte length (`0` for directories).
/// - `bool` - `true` for directory entries, `false` for regular files.
///
/// # Returns
///
/// - `io::Result<[u8; TAR_BLOCK_SIZE]>` - Complete checksummed ustar header block.
fn build_ustar_header(
    archive_path: &str,
    unix_mode: u32,
    size: u64,
    is_dir: bool,
) -> io::Result<[u8; TAR_BLOCK_SIZE]> {
    let (prefix_bytes, name_bytes): (&[u8], &[u8]) = split_ustar_path(archive_path)?;
    let mut block: [u8; TAR_BLOCK_SIZE] = [0u8; TAR_BLOCK_SIZE];
    block[..name_bytes.len()].copy_from_slice(name_bytes);
    write_octal_field(&mut block[100..108], u64::from(unix_mode & 0o7777));
    write_octal_field(&mut block[108..116], 0);
    write_octal_field(&mut block[116..124], 0);
    write_octal_field(&mut block[124..136], size);
    write_octal_field(&mut block[136..148], 0);
    for slot in block[148..156].iter_mut() {
        *slot = b' ';
    }
    block[156] = if is_dir { b'5' } else { b'0' };
    block[257..263].copy_from_slice(TAR_USTAR_MAGIC);
    block[263..265].copy_from_slice(TAR_USTAR_VERSION);
    if !prefix_bytes.is_empty() {
        block[345..345 + prefix_bytes.len()].copy_from_slice(prefix_bytes);
    }
    let checksum: u32 = block.iter().map(|byte_val: &u8| u32::from(*byte_val)).sum();
    let cksum_str: String = format!("{checksum:06o}\0 ");
    block[148..156].copy_from_slice(cksum_str.as_bytes());
    Ok(block)
}

/// Splits a tar entry path into POSIX ustar `(prefix, name)` slices (`<=155` and `<=100` bytes).
///
/// # Arguments
///
/// - `&str` - Archive-relative path.
///
/// # Returns
///
/// - `io::Result<(&[u8], &[u8])>` - Pair of `(prefix, name)` byte slices.
fn split_ustar_path(path: &str) -> io::Result<(&[u8], &[u8])> {
    let raw: &[u8] = path.as_bytes();
    if raw.len() <= 100 {
        return Ok((&[], raw));
    }
    let mut split_at: Option<usize> = None;
    let max_prefix: usize = cmp::min(155, raw.len());
    let mut idx: usize = 0;
    while idx < max_prefix {
        if raw[idx] == b'/' && raw.len() - idx - 1 <= 100 {
            split_at = Some(idx);
        }
        idx += 1;
    }
    let cut: usize = split_at.ok_or_else(|| {
        Error::new(
            ErrorKind::InvalidInput,
            format!("{ERR_TAR_PATH_TOO_LONG}: {path}"),
        )
    })?;
    Ok((&raw[..cut], &raw[cut + 1..]))
}

/// Formats an unsigned integer as NUL-terminated zero-padded ASCII octal in a ustar field.
///
/// # Arguments
///
/// - `&mut [u8]` - Target header slice.
/// - `u64` - Numeric value to format.
fn write_octal_field(field: &mut [u8], value: u64) {
    let digits_len: usize = field.len() - 1;
    let formatted: String = format!("{value:0width$o}", width = digits_len);
    let raw: &[u8] = formatted.as_bytes();
    let copy_len: usize = cmp::min(digits_len, raw.len());
    field[..copy_len].copy_from_slice(&raw[raw.len() - copy_len..]);
    field[digits_len] = 0;
}