mcproto-types 0.3.0

Minecraft protocol types.
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
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
//! Data model for Minecraft text components.
//!
//! The types in this module represent the component schema shared by JSON and
//! NBT text component encodings.

use std::{collections::BTreeMap, fmt, num::NonZeroI32};

use fastnbt::Value as NbtValue;
use serde::{
    Deserialize, Deserializer, Serialize, Serializer,
    de::{Error as _, MapAccess, SeqAccess, Visitor, value::MapAccessDeserializer},
    ser::{SerializeMap, SerializeSeq},
};

/// Java Edition release whose text component schema is represented here.
pub const TEXT_COMPONENT_FORMAT_VERSION: &str = "26.1";

/// The Java Edition text component schema documented for the current protocol.
///
/// `V` is the wire format's deliberately dynamic value type. Use
/// [`NbtComponent`] for NBT and [`JsonComponent`] for JSON.
#[derive(Debug, Clone, PartialEq)]
pub enum Component<V> {
    /// The string shorthand for a plain-text component.
    Text(String),
    /// The non-empty list shorthand.
    Sequence(ComponentSequence<V>),
    /// A full component object.
    Object(Box<ComponentObject<V>>),
}

/// A text component whose dynamic payloads use NBT values.
pub type NbtComponent = Component<NbtValue>;
/// A text component whose dynamic payloads use JSON values.
pub type JsonComponent = Component<serde_json::Value>;

impl<V> Component<V> {
    /// Creates the string shorthand for a plain-text component.
    pub fn text(value: impl Into<String>) -> Self {
        Self::Text(value.into())
    }

    /// Creates a full component object with the supplied content.
    ///
    /// The new object has an empty [`Style`] and no extra components.
    pub fn object(content: Content<V>) -> Self {
        Self::Object(Box::new(ComponentObject::new(content)))
    }

    /// Creates a non-empty component sequence from its first element and the
    /// remaining elements.
    pub fn sequence(first: Component<V>, rest: impl IntoIterator<Item = Component<V>>) -> Self {
        Self::Sequence(ComponentSequence::new(first, rest))
    }

    pub(crate) fn validate_depth(&self, max_depth: usize) -> Result<(), ComponentDepthError> {
        let mut pending = vec![(self, 1_usize)];
        while let Some((component, depth)) = pending.pop() {
            if depth > max_depth {
                return Err(ComponentDepthError { max_depth });
            }
            let next = depth + 1;
            match component {
                Self::Text(_) => {}
                Self::Sequence(sequence) => {
                    pending.extend(sequence.iter().map(|child| (child, next)));
                }
                Self::Object(object) => {
                    pending.extend(object.extra.iter().map(|child| (child, next)));
                    match &object.content {
                        Content::Translatable { with, .. } => {
                            pending.extend(with.iter().map(|child| (child, next)));
                        }
                        Content::Selector { separator, .. } | Content::Nbt { separator, .. } => {
                            if let Some(separator) = separator {
                                pending.push((separator, next));
                            }
                        }
                        _ => {}
                    }
                    if let Some(hover) = &object.style.hover_event {
                        match hover {
                            HoverEvent::ShowText { value } => pending.push((value, next)),
                            HoverEvent::ShowEntity { name, .. } => {
                                if let Some(name) = name {
                                    pending.push((name, next));
                                }
                            }
                            HoverEvent::ShowItem { .. } => {}
                        }
                    }
                }
            }
        }
        Ok(())
    }
}

impl Component<serde_json::Value> {
    pub(crate) fn validate_dynamic_depth(
        &self,
        max_depth: usize,
    ) -> Result<(), ComponentDepthError> {
        validate_dynamic_values(self, |root| {
            let mut pending = vec![(root, 1_usize)];
            while let Some((value, depth)) = pending.pop() {
                if depth > max_depth {
                    return Err(ComponentDepthError { max_depth });
                }
                let next = depth + 1;
                match value {
                    serde_json::Value::Array(values) => {
                        pending.extend(values.iter().map(|value| (value, next)));
                    }
                    serde_json::Value::Object(values) => {
                        pending.extend(values.values().map(|value| (value, next)));
                    }
                    _ => {}
                }
            }
            Ok(())
        })
    }
}

impl Component<NbtValue> {
    pub(crate) fn validate_dynamic_depth(
        &self,
        max_depth: usize,
    ) -> Result<(), ComponentDepthError> {
        validate_dynamic_values(self, |root| {
            let mut pending = vec![(root, 1_usize)];
            while let Some((value, depth)) = pending.pop() {
                if depth > max_depth {
                    return Err(ComponentDepthError { max_depth });
                }
                let next = depth + 1;
                match value {
                    NbtValue::List(values) => {
                        pending.extend(values.iter().map(|value| (value, next)));
                    }
                    NbtValue::Compound(values) => {
                        pending.extend(values.values().map(|value| (value, next)));
                    }
                    _ => {}
                }
            }
            Ok(())
        })
    }
}

fn validate_dynamic_values<V, E>(
    root: &Component<V>,
    mut validate: impl FnMut(&V) -> Result<(), E>,
) -> Result<(), E> {
    let mut pending = vec![root];
    while let Some(component) = pending.pop() {
        match component {
            Component::Text(_) => {}
            Component::Sequence(sequence) => pending.extend(sequence.iter()),
            Component::Object(object) => {
                pending.extend(&object.extra);
                match &object.content {
                    Content::Translatable { with, .. } => pending.extend(with),
                    Content::Selector { separator, .. } | Content::Nbt { separator, .. } => {
                        if let Some(separator) = separator {
                            pending.push(separator);
                        }
                    }
                    _ => {}
                }
                if let Some(click) = &object.style.click_event {
                    match click {
                        ClickEvent::ShowDialog {
                            dialog: DialogReference::Inline(values),
                        } => {
                            for value in values.values() {
                                validate(value)?;
                            }
                        }
                        ClickEvent::Custom {
                            payload: Some(value),
                            ..
                        } => validate(value)?,
                        _ => {}
                    }
                }
                if let Some(hover) = &object.style.hover_event {
                    match hover {
                        HoverEvent::ShowText { value } => pending.push(value),
                        HoverEvent::ShowItem { components, .. } => {
                            for value in components.values() {
                                validate(value)?;
                            }
                        }
                        HoverEvent::ShowEntity { name, .. } => {
                            if let Some(name) = name {
                                pending.push(name);
                            }
                        }
                    }
                }
            }
        }
    }
    Ok(())
}

impl<V> Default for Component<V> {
    fn default() -> Self {
        Self::text("")
    }
}

impl<V> From<String> for Component<V> {
    fn from(value: String) -> Self {
        Self::text(value)
    }
}

impl<V> From<&str> for Component<V> {
    fn from(value: &str) -> Self {
        Self::text(value)
    }
}

impl<V: Serialize> Serialize for Component<V> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match self {
            Self::Text(text) => serializer.serialize_str(text),
            Self::Sequence(sequence) => sequence.serialize(serializer),
            Self::Object(object) => object.serialize(serializer),
        }
    }
}

impl<'de, V> Deserialize<'de> for Component<V>
where
    V: Deserialize<'de>,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct ComponentVisitor<V>(std::marker::PhantomData<V>);

        impl<'de, V> Visitor<'de> for ComponentVisitor<V>
        where
            V: Deserialize<'de>,
        {
            type Value = Component<V>;

            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
                formatter.write_str("a text component string, non-empty list, or object")
            }

            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                Ok(Component::Text(value.to_owned()))
            }

            fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                Ok(Component::Text(value))
            }

            fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
            where
                A: SeqAccess<'de>,
            {
                let mut components =
                    Vec::with_capacity(sequence.size_hint().unwrap_or(0).min(1024));
                while let Some(component) = sequence.next_element()? {
                    components.push(component);
                }
                ComponentSequence::try_from(components)
                    .map(Component::Sequence)
                    .map_err(A::Error::custom)
            }

            fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
            where
                A: MapAccess<'de>,
            {
                ComponentObject::deserialize(MapAccessDeserializer::new(map))
                    .map(Box::new)
                    .map(Component::Object)
            }
        }

        deserializer.deserialize_any(ComponentVisitor(std::marker::PhantomData))
    }
}

/// A non-empty list shorthand for a sequence of text components.
#[derive(Debug, Clone, PartialEq)]
pub struct ComponentSequence<V> {
    first: Box<Component<V>>,
    rest: Vec<Component<V>>,
}

impl<V> ComponentSequence<V> {
    /// Creates a sequence from its required first component and any remaining
    /// components.
    pub fn new(first: Component<V>, rest: impl IntoIterator<Item = Component<V>>) -> Self {
        Self {
            first: Box::new(first),
            rest: rest.into_iter().collect(),
        }
    }

    /// Returns the first component in the sequence.
    pub fn first(&self) -> &Component<V> {
        &self.first
    }

    /// Returns all components after the first one.
    pub fn rest(&self) -> &[Component<V>] {
        &self.rest
    }

    /// Iterates over every component in order, including the first one.
    pub fn iter(&self) -> impl Iterator<Item = &Component<V>> {
        std::iter::once(self.first.as_ref()).chain(&self.rest)
    }
}

impl<V> TryFrom<Vec<Component<V>>> for ComponentSequence<V> {
    type Error = EmptyComponentSequence;

    fn try_from(mut value: Vec<Component<V>>) -> Result<Self, Self::Error> {
        if value.is_empty() {
            return Err(EmptyComponentSequence);
        }
        let rest = value.split_off(1);
        let first = value.pop().ok_or(EmptyComponentSequence)?;
        Ok(Self::new(first, rest))
    }
}

impl<V: Serialize> Serialize for ComponentSequence<V> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut sequence = serializer.serialize_seq(Some(1 + self.rest.len()))?;
        for component in self.iter() {
            sequence.serialize_element(component)?;
        }
        sequence.end()
    }
}

/// Error returned when an empty list is converted into a [`ComponentSequence`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EmptyComponentSequence;

impl fmt::Display for EmptyComponentSequence {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("a text component sequence cannot be empty")
    }
}

impl std::error::Error for EmptyComponentSequence {}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct ComponentDepthError {
    pub max_depth: usize,
}

impl fmt::Display for ComponentDepthError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            formatter,
            "text component nesting exceeds {} levels",
            self.max_depth
        )
    }
}

impl std::error::Error for ComponentDepthError {}

/// A full text component object with content, style, and appended components.
#[derive(Debug, Clone, PartialEq)]
pub struct ComponentObject<V> {
    /// The content rendered by this component.
    pub content: Content<V>,
    /// Optional formatting and interaction behavior.
    pub style: Style<V>,
    /// Components appended after this component.
    pub extra: Vec<Component<V>>,
}

impl<V> ComponentObject<V> {
    /// Creates an object with the supplied content, an empty style, and no
    /// extra components.
    pub fn new(content: Content<V>) -> Self {
        Self {
            content,
            style: Style::default(),
            extra: Vec::new(),
        }
    }

    /// Creates an object containing literal text.
    pub fn text(value: impl Into<String>) -> Self {
        Self::new(Content::Text { text: value.into() })
    }
}

/// The mutually exclusive content payload of a [`ComponentObject`].
#[derive(Debug, Clone, PartialEq)]
pub enum Content<V> {
    /// Literal text.
    Text {
        /// The text to display.
        text: String,
    },
    /// Text looked up from a translation key.
    Translatable {
        /// The translation key.
        translate: String,
        /// Text used when the translation key is unavailable.
        fallback: Option<String>,
        /// Components substituted into the translated text.
        with: Vec<Component<V>>,
    },
    /// A value from a scoreboard objective.
    Score {
        /// The scoreboard holder and objective to query.
        score: Score,
    },
    /// The names selected by an entity selector.
    Selector {
        /// The entity selector expression.
        selector: String,
        /// Component placed between selected names.
        separator: Option<Box<Component<V>>>,
    },
    /// The localized name of a client key binding.
    Keybind {
        /// The key-binding identifier.
        keybind: String,
    },
    /// Values read from an NBT path.
    Nbt {
        /// The NBT path to evaluate.
        nbt: String,
        /// The entity, block, or storage source to query.
        target: NbtTarget,
        /// How extracted values are rendered.
        display: NbtDisplay,
        /// Component placed between multiple extracted values.
        separator: Option<Box<Component<V>>>,
    },
    /// A rendered object such as an atlas sprite or player head.
    Object {
        /// The object-specific rendering data.
        object: ObjectContent,
        /// Fallback text used when the object cannot be rendered.
        ///
        /// Added by Java Edition 26.1.
        fallback: Option<String>,
    },
}

/// A scoreboard holder and objective referenced by score content.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Score {
    /// The score holder name or selector.
    pub name: String,
    /// The scoreboard objective name.
    pub objective: String,
}

/// The source queried by an NBT component.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum NbtTarget {
    /// An entity selected by the contained selector.
    Entity(String),
    /// A block at the contained position expression.
    Block(String),
    /// A command storage entry identified by its resource location.
    Storage(ResourceLocation),
}

/// Controls how values extracted from NBT are rendered.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum NbtDisplay {
    /// Uses the default styled representation.
    #[default]
    Styled,
    /// Displays the extracted value as plain text.
    Plain,
    /// Interprets the extracted value as a serialized text component.
    Interpret,
}

/// The object rendered by object content.
#[derive(Debug, Clone, PartialEq)]
pub enum ObjectContent {
    /// A sprite from a texture atlas.
    Atlas {
        /// The atlas containing the sprite, or the protocol default.
        atlas: Option<ResourceLocation>,
        /// The sprite to render.
        sprite: ResourceLocation,
    },
    /// A player head derived from profile data.
    Player {
        /// The player name or complete profile.
        player: PlayerProfile,
        /// Whether to render the player's hat layer.
        hat: Option<bool>,
    },
}

/// The shorthand or full representation of a player profile.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum PlayerProfile {
    /// A profile resolved from a player name.
    Name(PlayerName),
    /// Explicit profile data.
    Profile(Profile),
}

/// Player profile data used to render a player object.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct Profile {
    /// The player's validated account name.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<PlayerName>,
    /// The player's UUID.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub id: Option<Uuid>,
    /// Signed or unsigned profile properties.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub properties: Vec<ProfileProperty>,
    /// The player's skin texture resource.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub texture: Option<ResourceLocation>,
    /// The player's cape texture resource.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cape: Option<ResourceLocation>,
    /// The player's elytra texture resource.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub elytra: Option<ResourceLocation>,
    /// The geometry model used for the player skin.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub model: Option<PlayerModel>,
}

/// A property attached to a player profile.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProfileProperty {
    /// The kind of profile property.
    pub name: ProfilePropertyName,
    /// The encoded property value.
    pub value: String,
    /// The optional signature authenticating the value.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub signature: Option<String>,
}

/// A supported player profile property name.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ProfilePropertyName {
    /// Player skin and related texture data.
    Textures,
}

/// The geometry used to render a player skin.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PlayerModel {
    /// The standard model with wide arms.
    Wide,
    /// The slim model with narrow arms.
    Slim,
}

/// Optional formatting and interaction properties for a component.
#[derive(Debug, Clone, PartialEq)]
pub struct Style<V> {
    /// The text color.
    pub color: Option<TextColor>,
    /// The font resource used to render text.
    pub font: Option<ResourceLocation>,
    /// Whether text is rendered in bold.
    pub bold: Option<bool>,
    /// Whether text is rendered in italics.
    pub italic: Option<bool>,
    /// Whether text is underlined.
    pub underlined: Option<bool>,
    /// Whether text has a strikethrough line.
    pub strikethrough: Option<bool>,
    /// Whether text characters are continuously obfuscated.
    pub obfuscated: Option<bool>,
    /// The text shadow color.
    pub shadow_color: Option<ShadowColor>,
    /// Text inserted into chat when the component is shift-clicked.
    pub insertion: Option<String>,
    /// The action performed when the component is clicked.
    pub click_event: Option<ClickEvent<V>>,
    /// The content shown when the component is hovered.
    pub hover_event: Option<HoverEvent<V>>,
}

impl<V> Default for Style<V> {
    fn default() -> Self {
        Self {
            color: None,
            font: None,
            bold: None,
            italic: None,
            underlined: None,
            strikethrough: None,
            obfuscated: None,
            shadow_color: None,
            insertion: None,
            click_event: None,
            hover_event: None,
        }
    }
}

impl<V> Style<V> {
    fn is_empty(&self) -> bool {
        self.color.is_none()
            && self.font.is_none()
            && self.bold.is_none()
            && self.italic.is_none()
            && self.underlined.is_none()
            && self.strikethrough.is_none()
            && self.obfuscated.is_none()
            && self.shadow_color.is_none()
            && self.insertion.is_none()
            && self.click_event.is_none()
            && self.hover_event.is_none()
    }
}

/// An action performed when a styled component is clicked.
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(
    tag = "action",
    rename_all = "snake_case",
    bound(serialize = "V: Serialize")
)]
pub enum ClickEvent<V> {
    /// Opens an HTTP or HTTPS URL.
    OpenUrl {
        /// The URL to open.
        url: HttpUrl,
    },
    /// Opens a local file path on the client.
    OpenFile {
        /// The file path to open.
        path: String,
    },
    /// Runs a command.
    RunCommand {
        /// The command to run.
        command: CommandString,
    },
    /// Places a command into the client's chat input.
    SuggestCommand {
        /// The command to suggest.
        command: CommandString,
    },
    /// Changes the current book page.
    ChangePage {
        /// The one-based page number.
        page: PositiveI32,
    },
    /// Copies text to the system clipboard.
    CopyToClipboard {
        /// The text to copy.
        value: String,
    },
    /// Opens a dialog.
    ShowDialog {
        /// The dialog identifier or inline definition.
        dialog: DialogReference<V>,
    },
    /// Performs a custom action identified by a resource location.
    Custom {
        /// The custom action identifier.
        id: ResourceLocation,
        /// An optional wire-format-specific action payload.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        payload: Option<V>,
    },
}

/// A reference to a registered dialog or an inline dialog definition.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(
    untagged,
    bound(serialize = "V: Serialize", deserialize = "V: Deserialize<'de>")
)]
pub enum DialogReference<V> {
    /// The resource location of a registered dialog.
    Id(ResourceLocation),
    /// An inline dialog represented by wire-format-specific values.
    Inline(BTreeMap<String, V>),
}

/// Content shown when a styled component is hovered.
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(
    tag = "action",
    rename_all = "snake_case",
    bound(serialize = "V: Serialize")
)]
pub enum HoverEvent<V> {
    /// Shows another text component.
    ShowText {
        /// The component displayed in the tooltip.
        value: Box<Component<V>>,
    },
    /// Shows an item stack.
    ShowItem {
        /// The item type.
        id: ResourceLocation,
        /// The optional stack size.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        count: Option<i32>,
        /// Item data components keyed by resource location.
        #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
        components: BTreeMap<ResourceLocation, V>,
    },
    /// Shows entity information.
    ShowEntity {
        /// The optional entity name displayed in the tooltip.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        name: Option<Box<Component<V>>>,
        /// The entity type.
        id: ResourceLocation,
        /// The entity UUID.
        uuid: Uuid,
    },
}

#[derive(Deserialize)]
#[serde(bound(deserialize = "V: Deserialize<'de>"))]
struct RawClickEvent<V> {
    action: ClickAction,
    #[serde(default)]
    url: Option<HttpUrl>,
    #[serde(default)]
    path: Option<String>,
    #[serde(default)]
    command: Option<CommandString>,
    #[serde(default)]
    page: Option<PositiveI32>,
    #[serde(default)]
    value: Option<String>,
    #[serde(default)]
    dialog: Option<DialogReference<V>>,
    #[serde(default)]
    id: Option<ResourceLocation>,
    #[serde(default)]
    payload: Option<V>,
}

#[derive(Deserialize)]
#[serde(rename_all = "snake_case")]
enum ClickAction {
    OpenUrl,
    OpenFile,
    RunCommand,
    SuggestCommand,
    ChangePage,
    CopyToClipboard,
    ShowDialog,
    Custom,
}

impl<'de, V> Deserialize<'de> for ClickEvent<V>
where
    V: Deserialize<'de>,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let raw = RawClickEvent::deserialize(deserializer)?;
        let missing = || D::Error::custom("click event is missing its action payload");
        match raw.action {
            ClickAction::OpenUrl => raw.url.map(|url| Self::OpenUrl { url }).ok_or_else(missing),
            ClickAction::OpenFile => raw
                .path
                .map(|path| Self::OpenFile { path })
                .ok_or_else(missing),
            ClickAction::RunCommand => raw
                .command
                .map(|command| Self::RunCommand { command })
                .ok_or_else(missing),
            ClickAction::SuggestCommand => raw
                .command
                .map(|command| Self::SuggestCommand { command })
                .ok_or_else(missing),
            ClickAction::ChangePage => raw
                .page
                .map(|page| Self::ChangePage { page })
                .ok_or_else(missing),
            ClickAction::CopyToClipboard => raw
                .value
                .map(|value| Self::CopyToClipboard { value })
                .ok_or_else(missing),
            ClickAction::ShowDialog => raw
                .dialog
                .map(|dialog| Self::ShowDialog { dialog })
                .ok_or_else(missing),
            ClickAction::Custom => raw
                .id
                .map(|id| Self::Custom {
                    id,
                    payload: raw.payload,
                })
                .ok_or_else(missing),
        }
    }
}

#[derive(Deserialize)]
#[serde(bound(deserialize = "V: Deserialize<'de>"))]
struct RawHoverEvent<V> {
    action: HoverAction,
    #[serde(default)]
    value: Option<Box<Component<V>>>,
    #[serde(default)]
    id: Option<ResourceLocation>,
    #[serde(default)]
    count: Option<i32>,
    #[serde(default)]
    components: BTreeMap<ResourceLocation, V>,
    #[serde(default)]
    name: Option<Box<Component<V>>>,
    #[serde(default)]
    uuid: Option<Uuid>,
}

#[derive(Deserialize)]
enum HoverAction {
    #[serde(rename = "show_text")]
    Text,
    #[serde(rename = "show_item")]
    Item,
    #[serde(rename = "show_entity")]
    Entity,
}

impl<'de, V> Deserialize<'de> for HoverEvent<V>
where
    V: Deserialize<'de>,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let raw = RawHoverEvent::deserialize(deserializer)?;
        let missing = || D::Error::custom("hover event is missing its action payload");
        match raw.action {
            HoverAction::Text => raw
                .value
                .map(|value| Self::ShowText { value })
                .ok_or_else(missing),
            HoverAction::Item => raw
                .id
                .map(|id| Self::ShowItem {
                    id,
                    count: raw.count,
                    components: raw.components,
                })
                .ok_or_else(missing),
            HoverAction::Entity => match (raw.id, raw.uuid) {
                (Some(id), Some(uuid)) => Ok(Self::ShowEntity {
                    name: raw.name,
                    id,
                    uuid,
                }),
                _ => Err(missing()),
            },
        }
    }
}

/// A validated Minecraft resource location.
///
/// Namespaces permit lowercase ASCII letters, digits, `_`, `.`, and `-`;
/// paths additionally permit `/`. The namespace may be omitted on input.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ResourceLocation(String);

impl ResourceLocation {
    /// Validates and stores a resource location.
    ///
    /// Returns [`InvalidResourceLocation`] when the namespace or path contains
    /// unsupported characters or is empty.
    pub fn new(value: impl Into<String>) -> Result<Self, InvalidResourceLocation> {
        let value = value.into();
        validate_resource_location(&value)?;
        Ok(Self(value))
    }

    /// Returns the resource location exactly as it was supplied.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for ResourceLocation {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(&self.0)
    }
}

impl Serialize for ResourceLocation {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&self.0)
    }
}

impl<'de> Deserialize<'de> for ResourceLocation {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        Self::new(String::deserialize(deserializer)?).map_err(D::Error::custom)
    }
}

/// Error returned when a string is not a valid [`ResourceLocation`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InvalidResourceLocation;

impl fmt::Display for InvalidResourceLocation {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("invalid Minecraft resource location")
    }
}

impl std::error::Error for InvalidResourceLocation {}

fn validate_resource_location(value: &str) -> Result<(), InvalidResourceLocation> {
    if crate::basic::is_valid_identifier(value) {
        Ok(())
    } else {
        Err(InvalidResourceLocation)
    }
}

/// A validated absolute HTTP or HTTPS URL used by an `open_url` click event.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct HttpUrl(String);

impl HttpUrl {
    /// Validates and stores an absolute HTTP or HTTPS URL with a host.
    pub fn new(value: impl Into<String>) -> Result<Self, InvalidHttpUrl> {
        let value = value.into();
        let parsed = url::Url::parse(&value).map_err(|_| InvalidHttpUrl)?;
        if matches!(parsed.scheme(), "http" | "https") && parsed.host().is_some() {
            Ok(Self(value))
        } else {
            Err(InvalidHttpUrl)
        }
    }

    /// Returns the original URL string.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl Serialize for HttpUrl {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&self.0)
    }
}

impl<'de> Deserialize<'de> for HttpUrl {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        Self::new(String::deserialize(deserializer)?).map_err(D::Error::custom)
    }
}

/// Error returned when an `open_url` value is not an absolute HTTP or HTTPS URL.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct InvalidHttpUrl;

impl fmt::Display for InvalidHttpUrl {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("open_url requires an absolute HTTP or HTTPS URL")
    }
}

impl std::error::Error for InvalidHttpUrl {}

/// A command string validated for use in a text component click event.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CommandString(String);

impl CommandString {
    /// Validates and stores a command string.
    ///
    /// Minecraft control characters, DEL, and the legacy section sign are
    /// rejected.
    pub fn new(value: impl Into<String>) -> Result<Self, InvalidCommandString> {
        let value = value.into();
        if value
            .chars()
            .all(|character| character >= ' ' && character != '\u{7f}' && character != '\u{a7}')
        {
            Ok(Self(value))
        } else {
            Err(InvalidCommandString)
        }
    }

    /// Returns the validated command string.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl Serialize for CommandString {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&self.0)
    }
}

impl<'de> Deserialize<'de> for CommandString {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        Self::new(String::deserialize(deserializer)?).map_err(D::Error::custom)
    }
}

/// Error returned when a command contains a character forbidden by Minecraft.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct InvalidCommandString;

impl fmt::Display for InvalidCommandString {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("command contains a character forbidden by Minecraft")
    }
}

impl std::error::Error for InvalidCommandString {}

/// A validated Java Edition player name.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct PlayerName(String);

impl PlayerName {
    /// Validates and stores a player name containing 1 to 16 ASCII letters,
    /// digits, or underscores.
    pub fn new(value: impl Into<String>) -> Result<Self, InvalidPlayerName> {
        let value = value.into();
        if !value.is_empty()
            && value.len() <= 16
            && value
                .bytes()
                .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
        {
            Ok(Self(value))
        } else {
            Err(InvalidPlayerName)
        }
    }

    /// Returns the validated player name.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl Serialize for PlayerName {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&self.0)
    }
}

impl<'de> Deserialize<'de> for PlayerName {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        Self::new(String::deserialize(deserializer)?).map_err(D::Error::custom)
    }
}

/// Error returned when a string is not a valid [`PlayerName`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct InvalidPlayerName;

impl fmt::Display for InvalidPlayerName {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("player name must contain 1-16 ASCII letters, digits, or underscores")
    }
}

impl std::error::Error for InvalidPlayerName {}

/// A strictly positive signed 32-bit integer.
///
/// Text components use this type for one-based book page numbers.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
#[serde(transparent)]
pub struct PositiveI32(NonZeroI32);

impl PositiveI32 {
    /// Creates a positive integer, returning `None` for zero or negative input.
    pub fn new(value: i32) -> Option<Self> {
        NonZeroI32::new(value)
            .filter(|value| value.get() > 0)
            .map(Self)
    }

    /// Returns the contained positive integer.
    pub fn get(self) -> i32 {
        self.0.get()
    }
}

impl<'de> Deserialize<'de> for PositiveI32 {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = i32::deserialize(deserializer)?;
        Self::new(value).ok_or_else(|| D::Error::custom("page must be a positive integer"))
    }
}

/// A 128-bit universally unique identifier used by component profile data.
///
/// Parsing and formatting are delegated to the [`uuid`] crate; the wrapper
/// exists to support the custom serde representations used by text components
/// (a string, a four-integer list, or an NBT int array).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Uuid(uuid::Uuid);

impl Uuid {
    /// Creates a UUID from its 16 bytes in network order.
    pub fn from_bytes(bytes: [u8; 16]) -> Self {
        Self(uuid::Uuid::from_bytes(bytes))
    }

    /// Returns the UUID as 16 bytes in network order.
    pub fn into_bytes(self) -> [u8; 16] {
        self.0.into_bytes()
    }

    /// Parses a compact or hyphenated hexadecimal UUID string.
    pub fn parse(value: &str) -> Result<Self, InvalidUuid> {
        uuid::Uuid::try_parse(value)
            .map(Self)
            .map_err(|_| InvalidUuid)
    }
}

impl fmt::Display for Uuid {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(formatter)
    }
}

impl Serialize for Uuid {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.collect_str(self)
    }
}

impl<'de> Deserialize<'de> for Uuid {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct UuidVisitor;

        impl<'de> Visitor<'de> for UuidVisitor {
            type Value = Uuid;

            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
                formatter.write_str("a UUID string, four-integer list, or NBT int array")
            }

            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                Uuid::parse(value).map_err(E::custom)
            }

            fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                self.visit_str(&value)
            }

            fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
            where
                A: SeqAccess<'de>,
            {
                let mut values = [0_i32; 4];
                for (index, value) in values.iter_mut().enumerate() {
                    *value = sequence
                        .next_element()?
                        .ok_or_else(|| A::Error::invalid_length(index, &self))?;
                }
                if sequence.next_element::<serde::de::IgnoredAny>()?.is_some() {
                    return Err(A::Error::invalid_length(5, &self));
                }
                uuid_from_ints(&values).map_err(A::Error::custom)
            }

            fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
            where
                A: MapAccess<'de>,
            {
                let value = fastnbt::IntArray::deserialize(MapAccessDeserializer::new(map))?;
                uuid_from_ints(value.as_ref()).map_err(A::Error::custom)
            }
        }

        deserializer.deserialize_any(UuidVisitor)
    }
}

fn uuid_from_ints(value: &[i32]) -> Result<Uuid, InvalidUuid> {
    let value: [i32; 4] = value.try_into().map_err(|_| InvalidUuid)?;
    let mut bytes = [0_u8; 16];
    for (chunk, integer) in bytes.chunks_exact_mut(4).zip(value) {
        chunk.copy_from_slice(&integer.to_be_bytes());
    }
    Ok(Uuid::from_bytes(bytes))
}

/// Error returned when a UUID representation is malformed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct InvalidUuid;

impl fmt::Display for InvalidUuid {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("invalid UUID")
    }
}

impl std::error::Error for InvalidUuid {}

/// A named Minecraft color or an explicit 24-bit RGB color.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum TextColor {
    /// One of Minecraft's predefined named colors.
    Named(NamedColor),
    /// An explicit red, green, and blue color.
    Rgb(RgbColor),
}

impl TextColor {
    /// Creates an RGB text color from a 24-bit integer.
    pub const fn rgb(value: u32) -> Result<Self, InvalidRgbColor> {
        match RgbColor::new(value) {
            Ok(value) => Ok(Self::Rgb(value)),
            Err(error) => Err(error),
        }
    }
}

/// A 24-bit red, green, and blue color.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct RgbColor(u32);

impl RgbColor {
    /// The largest value that fits in an RGB color.
    pub const MAX: u32 = 0x00ff_ffff;

    /// Creates a color from a 24-bit `0xRRGGBB` integer.
    pub const fn new(value: u32) -> Result<Self, InvalidRgbColor> {
        if value <= Self::MAX {
            Ok(Self(value))
        } else {
            Err(InvalidRgbColor)
        }
    }

    /// Creates a color from its red, green, and blue channels.
    pub const fn from_channels(red: u8, green: u8, blue: u8) -> Self {
        Self(((red as u32) << 16) | ((green as u32) << 8) | blue as u32)
    }

    /// Returns the color as a 24-bit `0xRRGGBB` integer.
    pub const fn value(self) -> u32 {
        self.0
    }

    /// Returns the red, green, and blue channels in that order.
    pub const fn channels(self) -> [u8; 3] {
        [(self.0 >> 16) as u8, (self.0 >> 8) as u8, self.0 as u8]
    }
}

impl From<RgbColor> for TextColor {
    fn from(value: RgbColor) -> Self {
        Self::Rgb(value)
    }
}

/// Error returned when an RGB value does not fit in 24 bits.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct InvalidRgbColor;

impl fmt::Display for InvalidRgbColor {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("RGB color must fit in 24 bits")
    }
}

impl std::error::Error for InvalidRgbColor {}

/// A predefined Minecraft text color.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum NamedColor {
    /// Black (`#000000`).
    Black,
    /// Dark blue (`#0000AA`).
    DarkBlue,
    /// Dark green (`#00AA00`).
    DarkGreen,
    /// Dark aqua (`#00AAAA`).
    DarkAqua,
    /// Dark red (`#AA0000`).
    DarkRed,
    /// Dark purple (`#AA00AA`).
    DarkPurple,
    /// Gold (`#FFAA00`).
    Gold,
    /// Gray (`#AAAAAA`).
    Gray,
    /// Dark gray (`#555555`).
    DarkGray,
    /// Blue (`#5555FF`).
    Blue,
    /// Green (`#55FF55`).
    Green,
    /// Aqua (`#55FFFF`).
    Aqua,
    /// Red (`#FF5555`).
    Red,
    /// Light purple (`#FF55FF`).
    LightPurple,
    /// Yellow (`#FFFF55`).
    Yellow,
    /// White (`#FFFFFF`).
    White,
}

impl Serialize for TextColor {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match self {
            Self::Named(color) => color.serialize(serializer),
            Self::Rgb(rgb) => serializer.serialize_str(&format!("#{:06x}", rgb.value())),
        }
    }
}

impl<'de> Deserialize<'de> for TextColor {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = String::deserialize(deserializer)?;
        if let Some(rgb) = value.strip_prefix('#')
            && rgb.len() == 6
        {
            return u32::from_str_radix(rgb, 16)
                .map_err(D::Error::custom)
                .and_then(|value| {
                    RgbColor::new(value)
                        .map(Self::Rgb)
                        .map_err(D::Error::custom)
                });
        }
        serde_json::from_value::<NamedColor>(serde_json::Value::String(value))
            .map(Self::Named)
            .map_err(D::Error::custom)
    }
}

/// A text shadow color stored as a packed 32-bit ARGB value.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
#[serde(transparent)]
pub struct ShadowColor(i32);

impl ShadowColor {
    /// Creates a shadow color from a packed ARGB value.
    pub fn from_argb(argb: i32) -> Self {
        Self(argb)
    }

    /// Returns the packed ARGB value.
    pub fn argb(self) -> i32 {
        self.0
    }
}

impl<'de> Deserialize<'de> for ShadowColor {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        #[derive(Deserialize)]
        #[serde(untagged)]
        enum Repr {
            Argb(i32),
            Rgba([f32; 4]),
        }

        match Repr::deserialize(deserializer)? {
            Repr::Argb(argb) => Ok(Self(argb)),
            Repr::Rgba(rgba) => {
                if rgba
                    .iter()
                    .any(|value| !value.is_finite() || !(0.0..=1.0).contains(value))
                {
                    return Err(D::Error::custom(
                        "shadow color channels must be between 0 and 1",
                    ));
                }
                let channel = |value: f32| (value * 255.0).round() as u32;
                let [red, green, blue, alpha] = rgba.map(channel);
                Ok(Self(
                    ((alpha << 24) | (red << 16) | (green << 8) | blue) as i32,
                ))
            }
        }
    }
}

impl<V: Serialize> Serialize for ComponentObject<V> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut map = serializer.serialize_map(None)?;
        serialize_content(&mut map, &self.content)?;
        serialize_style(&mut map, &self.style)?;
        if !self.extra.is_empty() {
            map.serialize_entry("extra", &self.extra)?;
        }
        map.end()
    }
}

fn serialize_content<M, V>(map: &mut M, content: &Content<V>) -> Result<(), M::Error>
where
    M: SerializeMap,
    V: Serialize,
{
    match content {
        Content::Text { text } => {
            map.serialize_entry("type", "text")?;
            map.serialize_entry("text", text)?;
        }
        Content::Translatable {
            translate,
            fallback,
            with,
        } => {
            map.serialize_entry("type", "translatable")?;
            map.serialize_entry("translate", translate)?;
            if let Some(fallback) = fallback {
                map.serialize_entry("fallback", fallback)?;
            }
            if !with.is_empty() {
                map.serialize_entry("with", with)?;
            }
        }
        Content::Score { score } => {
            map.serialize_entry("type", "score")?;
            map.serialize_entry("score", score)?;
        }
        Content::Selector {
            selector,
            separator,
        } => {
            map.serialize_entry("type", "selector")?;
            map.serialize_entry("selector", selector)?;
            if let Some(separator) = separator {
                map.serialize_entry("separator", separator)?;
            }
        }
        Content::Keybind { keybind } => {
            map.serialize_entry("type", "keybind")?;
            map.serialize_entry("keybind", keybind)?;
        }
        Content::Nbt {
            nbt,
            target,
            display,
            separator,
        } => {
            map.serialize_entry("type", "nbt")?;
            map.serialize_entry("nbt", nbt)?;
            match target {
                NbtTarget::Entity(entity) => {
                    map.serialize_entry("source", "entity")?;
                    map.serialize_entry("entity", entity)?;
                }
                NbtTarget::Block(block) => {
                    map.serialize_entry("source", "block")?;
                    map.serialize_entry("block", block)?;
                }
                NbtTarget::Storage(storage) => {
                    map.serialize_entry("source", "storage")?;
                    map.serialize_entry("storage", storage)?;
                }
            }
            match display {
                NbtDisplay::Styled => {}
                NbtDisplay::Plain => map.serialize_entry("plain", &true)?,
                NbtDisplay::Interpret => map.serialize_entry("interpret", &true)?,
            }
            if let Some(separator) = separator {
                map.serialize_entry("separator", separator)?;
            }
        }
        Content::Object { object, fallback } => {
            map.serialize_entry("type", "object")?;
            match object {
                ObjectContent::Atlas { atlas, sprite } => {
                    map.serialize_entry("object", "atlas")?;
                    if let Some(atlas) = atlas {
                        map.serialize_entry("atlas", atlas)?;
                    }
                    map.serialize_entry("sprite", sprite)?;
                }
                ObjectContent::Player { player, hat } => {
                    map.serialize_entry("object", "player")?;
                    map.serialize_entry("player", player)?;
                    if let Some(hat) = hat {
                        map.serialize_entry("hat", hat)?;
                    }
                }
            }
            if let Some(fallback) = fallback {
                map.serialize_entry("fallback", fallback)?;
            }
        }
    }
    Ok(())
}

fn serialize_style<M, V>(map: &mut M, style: &Style<V>) -> Result<(), M::Error>
where
    M: SerializeMap,
    V: Serialize,
{
    macro_rules! optional {
        ($field:ident) => {
            if let Some(value) = &style.$field {
                map.serialize_entry(stringify!($field), value)?;
            }
        };
    }
    optional!(color);
    optional!(font);
    optional!(bold);
    optional!(italic);
    optional!(underlined);
    optional!(strikethrough);
    optional!(obfuscated);
    optional!(shadow_color);
    optional!(insertion);
    optional!(click_event);
    optional!(hover_event);
    Ok(())
}

#[derive(Deserialize)]
#[serde(bound(deserialize = "V: Deserialize<'de>"))]
struct RawComponent<V> {
    #[serde(rename = "type", default)]
    kind: Option<String>,
    #[serde(default)]
    text: Option<String>,
    #[serde(default)]
    translate: Option<String>,
    #[serde(default)]
    fallback: Option<String>,
    #[serde(default)]
    with: Vec<Component<V>>,
    #[serde(default)]
    score: Option<Score>,
    #[serde(default)]
    selector: Option<String>,
    #[serde(default)]
    separator: Option<Box<Component<V>>>,
    #[serde(default)]
    keybind: Option<String>,
    #[serde(default)]
    nbt: Option<String>,
    #[serde(default)]
    source: Option<NbtSource>,
    #[serde(default)]
    interpret: bool,
    #[serde(default)]
    plain: bool,
    #[serde(default)]
    entity: Option<String>,
    #[serde(default)]
    block: Option<String>,
    #[serde(default)]
    storage: Option<ResourceLocation>,
    #[serde(default)]
    object: Option<String>,
    #[serde(default)]
    atlas: Option<ResourceLocation>,
    #[serde(default)]
    sprite: Option<ResourceLocation>,
    #[serde(default)]
    player: Option<PlayerProfile>,
    #[serde(default)]
    hat: Option<bool>,
    #[serde(default)]
    extra: Vec<Component<V>>,
    #[serde(default)]
    color: Option<TextColor>,
    #[serde(default)]
    font: Option<ResourceLocation>,
    #[serde(default)]
    bold: Option<bool>,
    #[serde(default)]
    italic: Option<bool>,
    #[serde(default)]
    underlined: Option<bool>,
    #[serde(default)]
    strikethrough: Option<bool>,
    #[serde(default)]
    obfuscated: Option<bool>,
    #[serde(default)]
    shadow_color: Option<ShadowColor>,
    #[serde(default)]
    insertion: Option<String>,
    #[serde(default)]
    click_event: Option<ClickEvent<V>>,
    #[serde(default)]
    hover_event: Option<HoverEvent<V>>,
}

#[derive(Debug, Clone, Copy, Deserialize)]
#[serde(rename_all = "snake_case")]
enum NbtSource {
    Entity,
    Block,
    Storage,
}

impl<'de, V> Deserialize<'de> for ComponentObject<V>
where
    V: Deserialize<'de>,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let raw = RawComponent::deserialize(deserializer)?;
        raw.try_into().map_err(D::Error::custom)
    }
}

impl<V> TryFrom<RawComponent<V>> for ComponentObject<V> {
    type Error = InvalidComponentObject;

    fn try_from(raw: RawComponent<V>) -> Result<Self, Self::Error> {
        let selected = select_content(&raw).ok_or(InvalidComponentObject::MissingContent)?;
        let content = match selected {
            SelectedContent::Text => Content::Text {
                text: raw.text.ok_or(InvalidComponentObject::MissingContent)?,
            },
            SelectedContent::Translatable => Content::Translatable {
                translate: raw
                    .translate
                    .ok_or(InvalidComponentObject::MissingContent)?,
                fallback: raw.fallback,
                with: raw.with,
            },
            SelectedContent::Score => Content::Score {
                score: raw.score.ok_or(InvalidComponentObject::MissingContent)?,
            },
            SelectedContent::Selector => Content::Selector {
                selector: raw.selector.ok_or(InvalidComponentObject::MissingContent)?,
                separator: raw.separator,
            },
            SelectedContent::Keybind => Content::Keybind {
                keybind: raw.keybind.ok_or(InvalidComponentObject::MissingContent)?,
            },
            SelectedContent::Nbt => {
                if raw.interpret && raw.plain {
                    return Err(InvalidComponentObject::ConflictingNbtDisplay);
                }
                let target =
                    select_nbt_target(&raw).ok_or(InvalidComponentObject::MissingNbtTarget)?;
                let display = if raw.interpret {
                    NbtDisplay::Interpret
                } else if raw.plain {
                    NbtDisplay::Plain
                } else {
                    NbtDisplay::Styled
                };
                Content::Nbt {
                    nbt: raw.nbt.ok_or(InvalidComponentObject::MissingContent)?,
                    target,
                    display,
                    separator: raw.separator,
                }
            }
            SelectedContent::Object => {
                let object = match raw.object.as_deref() {
                    Some("player") => ObjectContent::Player {
                        player: raw
                            .player
                            .ok_or(InvalidComponentObject::MissingObjectField)?,
                        hat: raw.hat,
                    },
                    None | Some("atlas") => ObjectContent::Atlas {
                        atlas: raw.atlas,
                        sprite: raw
                            .sprite
                            .ok_or(InvalidComponentObject::MissingObjectField)?,
                    },
                    Some(_) => return Err(InvalidComponentObject::InvalidObjectType),
                };
                Content::Object {
                    object,
                    fallback: raw.fallback,
                }
            }
        };
        Ok(Self {
            content,
            style: Style {
                color: raw.color,
                font: raw.font,
                bold: raw.bold,
                italic: raw.italic,
                underlined: raw.underlined,
                strikethrough: raw.strikethrough,
                obfuscated: raw.obfuscated,
                shadow_color: raw.shadow_color,
                insertion: raw.insertion,
                click_event: raw.click_event,
                hover_event: raw.hover_event,
            },
            extra: raw.extra,
        })
    }
}

#[derive(Debug, Clone, Copy)]
enum SelectedContent {
    Text,
    Translatable,
    Score,
    Selector,
    Keybind,
    Nbt,
    Object,
}

fn select_content<V>(raw: &RawComponent<V>) -> Option<SelectedContent> {
    let explicit = match raw.kind.as_deref() {
        Some("text") if raw.text.is_some() => Some(SelectedContent::Text),
        Some("translatable") if raw.translate.is_some() => Some(SelectedContent::Translatable),
        Some("score") if raw.score.is_some() => Some(SelectedContent::Score),
        Some("selector") if raw.selector.is_some() => Some(SelectedContent::Selector),
        Some("keybind") if raw.keybind.is_some() => Some(SelectedContent::Keybind),
        Some("nbt") if raw.nbt.is_some() && select_nbt_target(raw).is_some() => {
            Some(SelectedContent::Nbt)
        }
        Some("object") if object_fields_are_valid(raw) => Some(SelectedContent::Object),
        _ => None,
    };
    explicit.or_else(|| {
        if raw.text.is_some() {
            Some(SelectedContent::Text)
        } else if raw.translate.is_some() {
            Some(SelectedContent::Translatable)
        } else if raw.score.is_some() {
            Some(SelectedContent::Score)
        } else if raw.selector.is_some() {
            Some(SelectedContent::Selector)
        } else if raw.keybind.is_some() {
            Some(SelectedContent::Keybind)
        } else if raw.nbt.is_some() && select_nbt_target(raw).is_some() {
            Some(SelectedContent::Nbt)
        } else if object_fields_are_valid(raw) {
            Some(SelectedContent::Object)
        } else {
            None
        }
    })
}

fn object_fields_are_valid<V>(raw: &RawComponent<V>) -> bool {
    match raw.object.as_deref() {
        Some("player") => raw.player.is_some(),
        None | Some("atlas") => raw.sprite.is_some(),
        Some(_) => false,
    }
}

fn select_nbt_target<V>(raw: &RawComponent<V>) -> Option<NbtTarget> {
    match raw.source {
        Some(NbtSource::Entity) => raw.entity.clone().map(NbtTarget::Entity),
        Some(NbtSource::Block) => raw.block.clone().map(NbtTarget::Block),
        Some(NbtSource::Storage) => raw.storage.clone().map(NbtTarget::Storage),
        None => raw
            .entity
            .clone()
            .map(NbtTarget::Entity)
            .or_else(|| raw.block.clone().map(NbtTarget::Block))
            .or_else(|| raw.storage.clone().map(NbtTarget::Storage)),
    }
}

/// Describes why a serialized component object does not match the component
/// schema.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InvalidComponentObject {
    /// No recognized content field is present.
    MissingContent,
    /// NBT content does not identify an entity, block, or storage source.
    MissingNbtTarget,
    /// NBT content requests both plain and interpreted display modes.
    ConflictingNbtDisplay,
    /// Object content is missing a field required by its object type.
    MissingObjectField,
    /// The object type is not recognized.
    InvalidObjectType,
}

impl fmt::Display for InvalidComponentObject {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(match self {
            Self::MissingContent => "text component object has no valid content",
            Self::MissingNbtTarget => "NBT text component has no matching source",
            Self::ConflictingNbtDisplay => "NBT text component cannot be plain and interpreted",
            Self::MissingObjectField => "object text component is missing a required field",
            Self::InvalidObjectType => "unknown object text component type",
        })
    }
}

impl std::error::Error for InvalidComponentObject {}

impl Component<NbtValue> {
    pub(crate) fn normalized_root_for_nbt(&self) -> Self {
        let component = normalize_nbt(self.clone());
        match component {
            Component::Sequence(_) => Component::Object(Box::new(component_into_object(component))),
            Component::Object(object) => {
                let ComponentObject {
                    content,
                    style,
                    extra,
                } = *object;
                match content {
                    Content::Text { text } if style.is_empty() && extra.is_empty() => {
                        Component::Text(text)
                    }
                    content => Component::Object(Box::new(ComponentObject {
                        content,
                        style,
                        extra,
                    })),
                }
            }
            _ => component,
        }
    }
}

fn normalize_nbt(component: NbtComponent) -> NbtComponent {
    match component {
        Component::Text(_) => component,
        Component::Sequence(sequence) => {
            let ComponentSequence { first, rest } = sequence;
            let first = Component::Object(Box::new(component_into_object(normalize_nbt(*first))));
            let rest = rest
                .into_iter()
                .map(normalize_nbt)
                .map(component_into_object)
                .map(Box::new)
                .map(Component::Object);
            Component::Sequence(ComponentSequence::new(first, rest))
        }
        Component::Object(mut object) => {
            object.extra = object
                .extra
                .into_iter()
                .map(normalize_nbt)
                .map(component_into_object)
                .map(Box::new)
                .map(Component::Object)
                .collect();
            match &mut object.content {
                Content::Translatable { with, .. } => {
                    *with = std::mem::take(with)
                        .into_iter()
                        .map(normalize_nbt)
                        .map(component_into_object)
                        .map(Box::new)
                        .map(Component::Object)
                        .collect();
                }
                Content::Selector { separator, .. } | Content::Nbt { separator, .. } => {
                    if let Some(value) = separator.take() {
                        *separator = Some(Box::new(normalize_nbt(*value)));
                    }
                }
                _ => {}
            }
            if let Some(hover) = &mut object.style.hover_event {
                match hover {
                    HoverEvent::ShowText { value } => {
                        **value = normalize_nbt(std::mem::take(value.as_mut()));
                    }
                    HoverEvent::ShowEntity { name, .. } => {
                        if let Some(value) = name.take() {
                            *name = Some(Box::new(normalize_nbt(*value)));
                        }
                    }
                    HoverEvent::ShowItem { .. } => {}
                }
            }
            Component::Object(object)
        }
    }
}

fn component_into_object(component: NbtComponent) -> ComponentObject<NbtValue> {
    match component {
        Component::Text(text) => ComponentObject::text(text),
        Component::Object(object) => *object,
        Component::Sequence(sequence) => {
            let ComponentSequence { first, rest } = sequence;
            let mut first = component_into_object(*first);
            first.extra.extend(
                rest.into_iter()
                    .map(component_into_object)
                    .map(Box::new)
                    .map(Component::Object),
            );
            first
        }
    }
}