golem-schema 1.6.1

Golem schema and value model
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
// Copyright 2024-2026 Golem Cloud
//
// Licensed under the Golem Source License v1.1 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://license.golem.cloud/LICENSE
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Concrete guest values converted directly to the canonical wire arena.
//!
//! These conversions check shape and affine ownership, not schema constraints.
//! The caller must validate the input against its declared schema at the host
//! boundary. No schema graph is needed to convert a statically known Rust type.

use super::wire::ValueNodeIndex;
use super::{GuestPermissionCardHandle, GuestQuotaTokenHandle, GuestSecretHandle, wire};
use crate::schema::SchemaValueStream;
use crate::schema::{Quantity, QuantityUnit, QuantityValue};
use std::collections::{BTreeMap, HashMap, HashSet};
use std::rc::Rc;

/// Builds the flat WIT schema arena used alongside directly encoded values.
/// Named definitions are reserved before their bodies are appended, allowing
/// derived recursive types to refer to themselves without constructing a
/// recursive schema model.
#[derive(Clone, Default)]
pub struct WireSchemaBuilder {
    type_nodes: Vec<wire::SchemaTypeNode>,
    defs: Vec<wire::SchemaTypeDef>,
    named: HashMap<String, wire::DefIndex>,
    claimants: HashMap<String, &'static str>,
    candidate_requests: HashMap<wire::DefIndex, &'static str>,
    active_candidates: HashMap<wire::DefIndex, &'static str>,
    validated_claimants: HashSet<(wire::DefIndex, &'static str)>,
}

pub enum WireSchemaReservation {
    Fresh,
    Recursive,
    Occupied,
}

impl WireSchemaBuilder {
    pub fn push(&mut self, body: wire::SchemaTypeBody) -> wire::TypeNodeIndex {
        self.push_with_metadata(body, empty_metadata())
    }

    pub fn push_with_metadata(
        &mut self,
        body: wire::SchemaTypeBody,
        metadata: wire::MetadataEnvelope,
    ) -> wire::TypeNodeIndex {
        let index = self.type_nodes.len() as wire::TypeNodeIndex;
        self.type_nodes
            .push(wire::SchemaTypeNode { body, metadata });
        index
    }

    pub fn reserve(&mut self, id: String, name: Option<String>) -> (wire::DefIndex, bool) {
        if let Some(index) = self.named.get(&id) {
            return (*index, false);
        }
        let index = self.defs.len() as wire::DefIndex;
        self.named.insert(id.clone(), index);
        self.defs.push(wire::SchemaTypeDef { id, name, body: -1 });
        (index, true)
    }

    pub fn reserve_nominal(
        &mut self,
        id: String,
        name: Option<String>,
        claimant: &'static str,
    ) -> (wire::DefIndex, WireSchemaReservation) {
        if let Some(&definition) = self.named.get(&id) {
            let owner = self
                .claimants
                .get(&id)
                .copied()
                .unwrap_or("<manual WireSchema implementation>");
            let pending = self.defs[definition as usize].body < 0;
            if pending && owner != claimant {
                panic!("wire schema id `{id}` is claimed by both `{owner}` and `{claimant}`");
            }
            if let Some(active_claimant) = self.active_candidates.get(&definition)
                && *active_claimant != claimant
            {
                panic!(
                    "wire schema id `{id}` is claimed by both `{active_claimant}` and `{claimant}`"
                );
            }
            let state = if pending
                || self.active_candidates.get(&definition) == Some(&claimant)
                || self.validated_claimants.contains(&(definition, claimant))
            {
                WireSchemaReservation::Recursive
            } else {
                self.candidate_requests.insert(definition, claimant);
                WireSchemaReservation::Occupied
            };
            return (definition, state);
        }
        let (definition, fresh) = self.reserve(id.clone(), name);
        debug_assert!(fresh);
        self.claimants.insert(id, claimant);
        (definition, WireSchemaReservation::Fresh)
    }

    pub fn begin_candidate(&mut self, definition: wire::DefIndex) -> Self {
        let claimant = self
            .candidate_requests
            .remove(&definition)
            .expect("occupied nominal reservation must precede candidate validation");
        let checkpoint = self.clone();
        self.active_candidates.insert(definition, claimant);
        checkpoint
    }

    pub fn verify_candidate(
        &mut self,
        checkpoint: Self,
        definition: wire::DefIndex,
        candidate_body: wire::TypeNodeIndex,
    ) {
        let existing_body = self.defs[definition as usize].body;
        let mut arena = self.clone();
        let placeholder = arena.push(wire::SchemaTypeBody::TupleType(Vec::new()));
        for definition in &mut arena.defs {
            if definition.body < 0 {
                definition.body = placeholder;
            }
        }
        let mut existing_wire = arena.clone().finish(existing_body);
        existing_wire.root = existing_body;
        let mut candidate_wire = arena.finish(candidate_body);
        candidate_wire.root = candidate_body;
        let existing = super::decode::decode_graph(&existing_wire)
            .expect("generated wire schema must form a valid flat arena");
        let candidate = super::decode::decode_graph(&candidate_wire)
            .expect("generated wire schema candidate must form a valid flat arena");
        if !crate::schema::validation::is_equivalent_cross_graph(
            &existing,
            &existing.root,
            &candidate,
            &candidate.root,
        ) {
            let id = &self.defs[definition as usize].id;
            let claimant = self
                .claimants
                .get(id)
                .copied()
                .unwrap_or("<manual WireSchema implementation>");
            panic!("wire schema id `{id}` has a divergent implementation in `{claimant}`");
        }
        let claimant = self
            .active_candidates
            .get(&definition)
            .copied()
            .expect("candidate must remain active until validation completes");
        *self = checkpoint;
        self.validated_claimants.insert((definition, claimant));
    }

    pub fn commit(&mut self, definition: wire::DefIndex, body: wire::TypeNodeIndex) {
        self.defs[definition as usize].body = body;
    }

    pub fn reference(&mut self, definition: wire::DefIndex) -> wire::TypeNodeIndex {
        self.push(wire::SchemaTypeBody::RefType(definition))
    }

    pub fn node(&self, index: wire::TypeNodeIndex) -> Option<&wire::SchemaTypeNode> {
        self.type_nodes.get(usize::try_from(index).ok()?)
    }

    pub fn resolve(&self, mut index: wire::TypeNodeIndex) -> Option<&wire::SchemaTypeNode> {
        for _ in 0..=self.defs.len() {
            let node = self.node(index)?;
            match node.body {
                wire::SchemaTypeBody::RefType(definition) => {
                    index = self.defs.get(usize::try_from(definition).ok()?)?.body;
                }
                _ => return Some(node),
            }
        }
        None
    }

    pub fn finish(self, root: wire::TypeNodeIndex) -> wire::SchemaGraph {
        wire::SchemaGraph {
            type_nodes: self.type_nodes,
            defs: self.defs,
            root,
        }
    }
}

pub fn empty_metadata() -> wire::MetadataEnvelope {
    wire::MetadataEnvelope {
        doc: None,
        aliases: Vec::new(),
        examples: Vec::new(),
        deprecated: None,
        role: None,
    }
}

/// Appends the concrete type's schema directly to a shared wire arena.
pub trait WireSchema {
    const IS_UNIT: bool = false;

    fn append_schema(builder: &mut WireSchemaBuilder) -> wire::TypeNodeIndex;

    fn contains_stream(seen: &mut HashSet<&'static str>) -> bool {
        let _ = seen;
        false
    }

    fn wire_type_id() -> String {
        std::any::type_name::<Self>().replace("::", ".")
    }
}

pub fn schema<T: WireSchema + ?Sized>() -> wire::SchemaGraph {
    let mut builder = WireSchemaBuilder::default();
    let root = T::append_schema(&mut builder);
    builder.finish(root)
}

macro_rules! wire_schema_scalar {
    ($($ty:ty => $body:expr),* $(,)?) => {$(
        impl WireSchema for $ty {
            fn wire_type_id() -> String {
                <Self as crate::schema::IntoSchema>::type_id().0
            }

            fn append_schema(builder: &mut WireSchemaBuilder) -> wire::TypeNodeIndex {
                builder.push($body)
            }
        }
    )*};
}

wire_schema_scalar! {
    bool => wire::SchemaTypeBody::BoolType,
    i8 => wire::SchemaTypeBody::S8Type(None), i16 => wire::SchemaTypeBody::S16Type(None),
    i32 => wire::SchemaTypeBody::S32Type(None), i64 => wire::SchemaTypeBody::S64Type(None),
    u8 => wire::SchemaTypeBody::U8Type(None), u16 => wire::SchemaTypeBody::U16Type(None),
    u32 => wire::SchemaTypeBody::U32Type(None), u64 => wire::SchemaTypeBody::U64Type(None),
    f32 => wire::SchemaTypeBody::F32Type(None), f64 => wire::SchemaTypeBody::F64Type(None),
    char => wire::SchemaTypeBody::CharType, String => wire::SchemaTypeBody::StringType,
    str => wire::SchemaTypeBody::StringType,
    chrono::DateTime<chrono::Utc> => wire::SchemaTypeBody::DatetimeType,
    std::time::Duration => wire::SchemaTypeBody::DurationType,
}

impl IntoWire for chrono::DateTime<chrono::Utc> {
    fn write_wire(&self, writer: &mut WireWriter) -> Result<ValueNodeIndex, WireError> {
        Ok(
            writer.push(wire::SchemaValueNode::DatetimeValue(wire::Datetime {
                seconds: self.timestamp(),
                nanoseconds: self.timestamp_subsec_nanos(),
            })),
        )
    }
}

impl FromWire for chrono::DateTime<chrono::Utc> {
    fn read_wire(reader: &mut WireReader, index: ValueNodeIndex) -> Result<Self, WireError> {
        let wire::SchemaValueNode::DatetimeValue(value) = reader.take(index)? else {
            return Err(WireError::Shape("datetime"));
        };
        super::datetime_from_wire(&value).ok_or(WireError::Shape("valid datetime"))
    }
}

impl IntoWire for std::time::Duration {
    fn write_wire(&self, writer: &mut WireWriter) -> Result<ValueNodeIndex, WireError> {
        Ok(writer.push(wire::SchemaValueNode::DurationValue(
            wire::DurationValuePayload {
                nanoseconds: self.as_nanos().min(i64::MAX as u128) as i64,
            },
        )))
    }
}

impl FromWire for std::time::Duration {
    fn read_wire(reader: &mut WireReader, index: ValueNodeIndex) -> Result<Self, WireError> {
        let wire::SchemaValueNode::DurationValue(value) = reader.take(index)? else {
            return Err(WireError::Shape("duration"));
        };
        let nanos = u64::try_from(value.nanoseconds)
            .map_err(|_| WireError::Shape("nonnegative duration"))?;
        Ok(Self::from_nanos(nanos))
    }
}

#[cfg(feature = "url")]
impl WireSchema for url::Url {
    fn append_schema(builder: &mut WireSchemaBuilder) -> wire::TypeNodeIndex {
        builder.push(wire::SchemaTypeBody::UrlType(wire::UrlRestrictions {
            allowed_schemes: None,
            allowed_hosts: None,
        }))
    }
}

#[cfg(feature = "url")]
impl IntoWire for url::Url {
    fn write_wire(&self, writer: &mut WireWriter) -> Result<ValueNodeIndex, WireError> {
        Ok(writer.push(wire::SchemaValueNode::UrlValue(self.to_string())))
    }
}

#[cfg(feature = "url")]
impl FromWire for url::Url {
    fn read_wire(reader: &mut WireReader, index: ValueNodeIndex) -> Result<Self, WireError> {
        let wire::SchemaValueNode::UrlValue(value) = reader.take(index)? else {
            return Err(WireError::Shape("url"));
        };
        Self::parse(&value).map_err(|_| WireError::Shape("valid url"))
    }
}

impl WireSchema for uuid::Uuid {
    fn append_schema(builder: &mut WireSchemaBuilder) -> wire::TypeNodeIndex {
        builder.push(wire::SchemaTypeBody::UuidType)
    }

    fn wire_type_id() -> String {
        "uuid.Uuid".into()
    }
}

impl IntoWire for uuid::Uuid {
    fn write_wire(&self, writer: &mut WireWriter) -> Result<ValueNodeIndex, WireError> {
        let (high_bits, low_bits) = self.as_u64_pair();
        Ok(writer.push(wire::SchemaValueNode::UuidValue(wire::Uuid {
            high_bits,
            low_bits,
        })))
    }
}

impl FromWire for uuid::Uuid {
    fn read_wire(reader: &mut WireReader, index: ValueNodeIndex) -> Result<Self, WireError> {
        let wire::SchemaValueNode::UuidValue(value) = reader.take(index)? else {
            return Err(WireError::Shape("uuid"));
        };
        Ok(Self::from_u64_pair(value.high_bits, value.low_bits))
    }
}

impl<U: QuantityUnit> WireSchema for Quantity<U> {
    fn wire_type_id() -> String {
        <Self as crate::schema::IntoSchema>::type_id().0
    }

    fn append_schema(builder: &mut WireSchemaBuilder) -> wire::TypeNodeIndex {
        builder.push(wire::SchemaTypeBody::QuantityType(wire::QuantitySpec {
            base_unit: U::base_unit().to_string(),
            allowed_suffixes: U::allowed_suffixes()
                .iter()
                .map(|value| (*value).to_string())
                .collect(),
            min: None,
            max: None,
        }))
    }
}

impl<U: QuantityUnit> IntoWire for Quantity<U> {
    fn write_wire(&self, writer: &mut WireWriter) -> Result<ValueNodeIndex, WireError> {
        let value = self.as_quantity_value();
        Ok(writer.push(wire::SchemaValueNode::QuantityValueNode(
            wire::QuantityValue {
                mantissa: value.mantissa,
                scale: value.scale,
                unit: value.unit.clone(),
            },
        )))
    }
}

impl<U: QuantityUnit> FromWire for Quantity<U> {
    fn read_wire(reader: &mut WireReader, index: ValueNodeIndex) -> Result<Self, WireError> {
        let wire::SchemaValueNode::QuantityValueNode(value) = reader.take(index)? else {
            return Err(WireError::Shape("quantity"));
        };
        Quantity::from_quantity_value(QuantityValue {
            mantissa: value.mantissa,
            scale: value.scale,
            unit: value.unit,
        })
        .map_err(|_| WireError::Shape("quantity unit"))
    }
}

impl WireSchema for std::path::PathBuf {
    fn append_schema(builder: &mut WireSchemaBuilder) -> wire::TypeNodeIndex {
        builder.push(wire::SchemaTypeBody::PathType(wire::PathSpec {
            direction: wire::PathDirection::InOut,
            kind: wire::PathKind::Any,
            allowed_mime_types: None,
            allowed_extensions: None,
        }))
    }
}

impl FromWire for std::path::PathBuf {
    fn read_wire(reader: &mut WireReader, index: ValueNodeIndex) -> Result<Self, WireError> {
        match reader.take(index)? {
            wire::SchemaValueNode::PathValue(path) => Ok(path.into()),
            _ => Err(WireError::Shape("path")),
        }
    }
}

impl IntoWire for std::path::PathBuf {
    fn write_wire(&self, writer: &mut WireWriter) -> Result<ValueNodeIndex, WireError> {
        Ok(writer.push(wire::SchemaValueNode::PathValue(
            self.to_string_lossy().into_owned(),
        )))
    }
}

macro_rules! wire_schema_pointer {
    ($pointer:ty) => {
        impl<T: WireSchema + ?Sized> WireSchema for $pointer {
            const IS_UNIT: bool = T::IS_UNIT;

            fn contains_stream(seen: &mut HashSet<&'static str>) -> bool {
                T::contains_stream(seen)
            }

            fn wire_type_id() -> String {
                T::wire_type_id()
            }

            fn append_schema(builder: &mut WireSchemaBuilder) -> wire::TypeNodeIndex {
                T::append_schema(builder)
            }
        }
    };
}
wire_schema_pointer!(Box<T>);
wire_schema_pointer!(Rc<T>);
wire_schema_pointer!(std::sync::Arc<T>);
wire_schema_pointer!(&T);

impl<T: WireSchema> WireSchema for Vec<T> {
    fn wire_type_id() -> String {
        format!("alloc.vec.Vec<{}>", T::wire_type_id())
    }

    fn contains_stream(seen: &mut HashSet<&'static str>) -> bool {
        T::contains_stream(seen)
    }

    fn append_schema(builder: &mut WireSchemaBuilder) -> wire::TypeNodeIndex {
        let element = T::append_schema(builder);
        builder.push(wire::SchemaTypeBody::ListType(element))
    }
}
impl<T: WireSchema> WireSchema for HashSet<T> {
    fn wire_type_id() -> String {
        format!("std.collections.HashSet<{}>", T::wire_type_id())
    }

    fn contains_stream(seen: &mut HashSet<&'static str>) -> bool {
        T::contains_stream(seen)
    }

    fn append_schema(builder: &mut WireSchemaBuilder) -> wire::TypeNodeIndex {
        let element = T::append_schema(builder);
        builder.push(wire::SchemaTypeBody::ListType(element))
    }
}
impl<T: WireSchema> WireSchema for Option<T> {
    fn wire_type_id() -> String {
        format!("core.option.Option<{}>", T::wire_type_id())
    }

    fn contains_stream(seen: &mut HashSet<&'static str>) -> bool {
        T::contains_stream(seen)
    }

    fn append_schema(builder: &mut WireSchemaBuilder) -> wire::TypeNodeIndex {
        let inner = T::append_schema(builder);
        builder.push(wire::SchemaTypeBody::OptionType(inner))
    }
}
impl<T: WireSchema, E: WireSchema> WireSchema for Result<T, E> {
    fn wire_type_id() -> String {
        format!(
            "core.result.Result<{}, {}>",
            T::wire_type_id(),
            E::wire_type_id()
        )
    }

    fn contains_stream(seen: &mut HashSet<&'static str>) -> bool {
        T::contains_stream(seen) || E::contains_stream(seen)
    }

    fn append_schema(builder: &mut WireSchemaBuilder) -> wire::TypeNodeIndex {
        let ok = if T::IS_UNIT {
            None
        } else {
            Some(T::append_schema(builder))
        };
        let err = if E::IS_UNIT {
            None
        } else {
            Some(E::append_schema(builder))
        };
        builder.push(wire::SchemaTypeBody::ResultType(wire::ResultSpec {
            ok,
            err,
        }))
    }
}
impl WireSchema for () {
    const IS_UNIT: bool = true;

    fn wire_type_id() -> String {
        "core.tuple.Unit".into()
    }

    fn append_schema(builder: &mut WireSchemaBuilder) -> wire::TypeNodeIndex {
        builder.push(wire::SchemaTypeBody::TupleType(Vec::new()))
    }
}
impl<K: WireSchema, V: WireSchema> WireSchema for HashMap<K, V> {
    fn wire_type_id() -> String {
        format!(
            "std.collections.HashMap<{}, {}>",
            K::wire_type_id(),
            V::wire_type_id()
        )
    }

    fn contains_stream(seen: &mut HashSet<&'static str>) -> bool {
        K::contains_stream(seen) || V::contains_stream(seen)
    }

    fn append_schema(builder: &mut WireSchemaBuilder) -> wire::TypeNodeIndex {
        let key = K::append_schema(builder);
        let value = V::append_schema(builder);
        builder.push(wire::SchemaTypeBody::MapType(wire::MapSpec { key, value }))
    }
}
impl<K: WireSchema, V: WireSchema> WireSchema for BTreeMap<K, V> {
    fn wire_type_id() -> String {
        format!(
            "alloc.collections.BTreeMap<{}, {}>",
            K::wire_type_id(),
            V::wire_type_id()
        )
    }

    fn contains_stream(seen: &mut HashSet<&'static str>) -> bool {
        K::contains_stream(seen) || V::contains_stream(seen)
    }

    fn append_schema(builder: &mut WireSchemaBuilder) -> wire::TypeNodeIndex {
        let key = K::append_schema(builder);
        let value = V::append_schema(builder);
        builder.push(wire::SchemaTypeBody::MapType(wire::MapSpec { key, value }))
    }
}

macro_rules! wire_map {
    ($map:ident, $($key_bound:tt)+) => {
        impl<K: IntoWire, V: IntoWire> IntoWire for $map<K, V> {
            const NEEDS_PREPARATION: bool = K::NEEDS_PREPARATION || V::NEEDS_PREPARATION;

            fn preflight(&self, resources: &mut WirePreflight) -> Result<(), WireError> {
                for (key, value) in self {
                    key.preflight(resources)?;
                    value.preflight(resources)?;
                }
                Ok(())
            }
            async fn prepare_wire(&self) -> Result<(), WireError> {
                for (key, value) in self {
                    key.prepare_wire().await?;
                    value.prepare_wire().await?;
                }
                Ok(())
            }
            fn write_wire(&self, writer: &mut WireWriter) -> Result<ValueNodeIndex, WireError> {
                let entries = self
                    .iter()
                    .map(|(key, value)| {
                        Ok(wire::MapEntry {
                            key: key.write_wire(writer)?,
                            value: value.write_wire(writer)?,
                        })
                    })
                    .collect::<Result<_, WireError>>()?;
                Ok(writer.push(wire::SchemaValueNode::MapValue(entries)))
            }
        }
        impl<K: FromWire + $($key_bound)+, V: FromWire> FromWire for $map<K, V> {
            fn read_wire(
                reader: &mut WireReader,
                index: ValueNodeIndex,
            ) -> Result<Self, WireError> {
                let wire::SchemaValueNode::MapValue(entries) = reader.take(index)? else {
                    return Err(WireError::Shape("map"));
                };
                entries
                    .into_iter()
                    .map(|entry| {
                        Ok((
                            K::read_wire(reader, entry.key)?,
                            V::read_wire(reader, entry.value)?,
                        ))
                    })
                    .collect()
            }
        }
    };
}
wire_map!(BTreeMap, Ord);
wire_map!(HashMap, Eq + std::hash::Hash);

impl<T: WireSchema> WireSchema for std::ops::Bound<T> {
    fn wire_type_id() -> String {
        format!("core.ops.range.Bound<{}>", T::wire_type_id())
    }

    fn contains_stream(seen: &mut HashSet<&'static str>) -> bool {
        T::contains_stream(seen)
    }

    fn append_schema(builder: &mut WireSchemaBuilder) -> wire::TypeNodeIndex {
        let included = T::append_schema(builder);
        let excluded = T::append_schema(builder);
        builder.push(wire::SchemaTypeBody::VariantType(vec![
            wire::VariantCaseType {
                name: "included".to_string(),
                payload: Some(included),
                metadata: empty_metadata(),
            },
            wire::VariantCaseType {
                name: "excluded".to_string(),
                payload: Some(excluded),
                metadata: empty_metadata(),
            },
            wire::VariantCaseType {
                name: "unbounded".to_string(),
                payload: None,
                metadata: empty_metadata(),
            },
        ]))
    }
}

macro_rules! wire_schema_tuple {
    ($($ty:ident),+) => { impl<$($ty: WireSchema),+> WireSchema for ($($ty,)+) {
        fn wire_type_id() -> String {
            let args = [$($ty::wire_type_id()),+];
            format!("core.tuple.Tuple{}<{}>", args.len(), args.join(", "))
        }

        fn contains_stream(seen: &mut HashSet<&'static str>) -> bool {
            false $(|| $ty::contains_stream(seen))+
        }

        fn append_schema(builder: &mut WireSchemaBuilder) -> wire::TypeNodeIndex {
            let elements = vec![$($ty::append_schema(builder)),+];
            builder.push(wire::SchemaTypeBody::TupleType(elements))
        }
    }};
}
wire_schema_tuple!(A);
wire_schema_tuple!(A, B);
wire_schema_tuple!(A, B, C);
wire_schema_tuple!(A, B, C, D);
wire_schema_tuple!(A, B, C, D, E);
wire_schema_tuple!(A, B, C, D, E, F);
wire_schema_tuple!(A, B, C, D, E, F, G);
wire_schema_tuple!(A, B, C, D, E, F, G, H);

#[derive(Debug, PartialEq, Eq, thiserror::Error)]
pub enum WireError {
    #[error("expected wire {0}")]
    Shape(&'static str),
    #[error("wire value index {0} is out of bounds")]
    OutOfBounds(ValueNodeIndex),
    #[error("wire value index {0} is referenced more than once")]
    AliasedNode(ValueNodeIndex),
    #[error("wire resource at index {0} is not reachable from the root")]
    UnreachableResource(ValueNodeIndex),
    #[error("{0} resource appears more than once")]
    AliasedResource(&'static str),
    #[error("{0} resource has already been transferred")]
    ConsumedResource(&'static str),
    #[error("{0} resource is not allowed in this input")]
    ForbiddenResource(&'static str),
    #[error("native streams require asynchronous wire encoding")]
    AsyncStream,
}

/// Decode a concrete value, consuming every visited wire node exactly once.
pub trait FromWire: Sized {
    fn read_wire(reader: &mut WireReader, index: ValueNodeIndex) -> Result<Self, WireError>;

    fn read_result_payload(
        reader: &mut WireReader,
        index: Option<ValueNodeIndex>,
    ) -> Result<Self, WireError> {
        Self::read_wire(reader, index.ok_or(WireError::Shape("result payload"))?)
    }
}

/// Encode a concrete value without constructing an owned schema value.
///
/// Implementations must visit every resource in `preflight` before moving any
/// handles in `write_wire`. After a successful preflight, `write_wire` must not
/// fail except when a resource was concurrently transferred through an alias.
#[allow(async_fn_in_trait)]
pub trait IntoWire {
    /// False only when `prepare_wire` is a no-op for every value of this type.
    /// Resource preflight still runs regardless of this flag. Custom and derived
    /// implementations prepare by default, including those with no stream schema.
    const NEEDS_PREPARATION: bool = true;

    fn preflight(&self, _resources: &mut WirePreflight) -> Result<(), WireError> {
        Ok(())
    }

    fn write_wire(&self, writer: &mut WireWriter) -> Result<ValueNodeIndex, WireError>;

    /// Wrap native stream endpoints without reading from them. This is called
    /// only after the complete value has passed resource preflight.
    async fn prepare_wire(&self) -> Result<(), WireError> {
        Ok(())
    }

    fn write_result_payload(
        &self,
        writer: &mut WireWriter,
    ) -> Result<Option<ValueNodeIndex>, WireError> {
        self.write_wire(writer).map(Some)
    }
}

enum SnapshotNode {
    Value(wire::SchemaValueNode),
    Secret(GuestSecretHandle),
    QuotaToken(GuestQuotaTokenHandle),
    PermissionCard(GuestPermissionCardHandle),
    Stream(SchemaValueStream),
}

/// Reusable owned backing for independent direct decoders. Capability nodes
/// share their take-once cells; ordinary nodes are copied into each reader.
pub struct WireSnapshot {
    nodes: Vec<SnapshotNode>,
}

impl WireSnapshot {
    pub fn new(nodes: Vec<wire::SchemaValueNode>) -> Self {
        let nodes = nodes
            .into_iter()
            .map(|node| match node {
                wire::SchemaValueNode::SecretValue(value) => {
                    SnapshotNode::Secret(GuestSecretHandle::new(value))
                }
                wire::SchemaValueNode::QuotaTokenHandle(value) => {
                    SnapshotNode::QuotaToken(GuestQuotaTokenHandle::new(value))
                }
                wire::SchemaValueNode::PermissionCardHandle(value) => {
                    SnapshotNode::PermissionCard(GuestPermissionCardHandle::new(value))
                }
                wire::SchemaValueNode::StreamValue(value) => {
                    SnapshotNode::Stream(SchemaValueStream::from_wrapped(value))
                }
                value => SnapshotNode::Value(value),
            })
            .collect();
        Self { nodes }
    }

    pub fn reader(self: &Rc<Self>) -> WireReader {
        WireReader {
            visited: vec![false; self.nodes.len()],
            backing: ReaderBacking::Shared(Rc::clone(self)),
        }
    }
}

enum ReaderBacking {
    Owned(Vec<Option<SnapshotNode>>),
    Shared(Rc<WireSnapshot>),
}

/// Reads one independent view of a [`WireSnapshot`].
pub struct WireReader {
    backing: ReaderBacking,
    visited: Vec<bool>,
}

impl WireReader {
    pub fn new(nodes: Vec<wire::SchemaValueNode>) -> Self {
        Self {
            backing: ReaderBacking::Owned(
                WireSnapshot::new(nodes)
                    .nodes
                    .into_iter()
                    .map(Some)
                    .collect(),
            ),
            visited: Vec::new(),
        }
    }

    pub fn take(&mut self, index: ValueNodeIndex) -> Result<wire::SchemaValueNode, WireError> {
        let node = self.visit(index)?;
        match node {
            SnapshotNode::Value(value) => Ok(value),
            _ => Err(WireError::Shape("non-resource value")),
        }
    }

    pub fn push(&mut self, node: wire::SchemaValueNode) -> Result<ValueNodeIndex, WireError> {
        let ReaderBacking::Owned(nodes) = &mut self.backing else {
            return Err(WireError::Shape("cannot extend a shared wire reader"));
        };
        let index = nodes.len() as ValueNodeIndex;
        nodes.push(Some(SnapshotNode::Value(node)));
        Ok(index)
    }

    fn visit(&mut self, index: ValueNodeIndex) -> Result<SnapshotNode, WireError> {
        let snapshot = match &mut self.backing {
            ReaderBacking::Owned(nodes) => {
                return nodes
                    .get_mut(index as usize)
                    .ok_or(WireError::OutOfBounds(index))?
                    .take()
                    .ok_or(WireError::AliasedNode(index));
            }
            ReaderBacking::Shared(snapshot) => snapshot,
        };
        let visited = self
            .visited
            .get_mut(index as usize)
            .ok_or(WireError::OutOfBounds(index))?;
        if std::mem::replace(visited, true) {
            return Err(WireError::AliasedNode(index));
        }
        Ok(match &snapshot.nodes[index as usize] {
            SnapshotNode::Value(value) => SnapshotNode::Value(clone_value_node(value)),
            SnapshotNode::Secret(value) => SnapshotNode::Secret(value.clone()),
            SnapshotNode::QuotaToken(value) => SnapshotNode::QuotaToken(value.clone()),
            SnapshotNode::PermissionCard(value) => SnapshotNode::PermissionCard(value.clone()),
            SnapshotNode::Stream(value) => SnapshotNode::Stream(value.clone()),
        })
    }

    fn secret(&mut self, index: ValueNodeIndex) -> Result<GuestSecretHandle, WireError> {
        match self.visit(index)? {
            SnapshotNode::Secret(value) => Ok(value.clone()),
            _ => Err(WireError::Shape("secret")),
        }
    }

    fn quota_token(&mut self, index: ValueNodeIndex) -> Result<GuestQuotaTokenHandle, WireError> {
        match self.visit(index)? {
            SnapshotNode::QuotaToken(value) => Ok(value.clone()),
            _ => Err(WireError::Shape("quota-token")),
        }
    }

    fn permission_card(
        &mut self,
        index: ValueNodeIndex,
    ) -> Result<GuestPermissionCardHandle, WireError> {
        match self.visit(index)? {
            SnapshotNode::PermissionCard(value) => Ok(value.clone()),
            _ => Err(WireError::Shape("permission-card")),
        }
    }

    fn stream(&mut self, index: ValueNodeIndex) -> Result<SchemaValueStream, WireError> {
        match self.visit(index)? {
            SnapshotNode::Stream(value) => Ok(value.clone()),
            _ => Err(WireError::Shape("stream")),
        }
    }

    /// Consume an unbound field, releasing its resources and checking its edges
    /// without constructing a recursive value. The explicit stack also bounds
    /// stack usage for deeply nested fields not consumed by a typed decoder.
    pub fn discard(&mut self, index: ValueNodeIndex) -> Result<(), WireError> {
        let mut pending = vec![index];
        while let Some(index) = pending.pop() {
            let SnapshotNode::Value(node) = self.visit(index)? else {
                continue;
            };
            match node {
                wire::SchemaValueNode::RecordValue(children)
                | wire::SchemaValueNode::TupleValue(children)
                | wire::SchemaValueNode::ListValue(children)
                | wire::SchemaValueNode::FixedListValue(children) => pending.extend(children),
                wire::SchemaValueNode::MapValue(entries) => {
                    for entry in entries {
                        pending.extend([entry.key, entry.value]);
                    }
                }
                wire::SchemaValueNode::VariantValue(value) => pending.extend(value.payload),
                wire::SchemaValueNode::OptionValue(value) => pending.extend(value),
                wire::SchemaValueNode::ResultValue(value) => match value {
                    wire::ResultValuePayload::OkValue(value)
                    | wire::ResultValuePayload::ErrValue(value) => pending.extend(value),
                },
                wire::SchemaValueNode::UnionValue(value) => pending.push(value.body),
                _ => {}
            }
        }
        Ok(())
    }

    pub fn finish(self) -> Result<(), WireError> {
        match self.backing {
            ReaderBacking::Owned(nodes) => {
                for (index, node) in nodes.iter().enumerate() {
                    if node
                        .as_ref()
                        .is_some_and(|node| !matches!(node, SnapshotNode::Value(_)))
                    {
                        return Err(WireError::UnreachableResource(index as ValueNodeIndex));
                    }
                }
            }
            ReaderBacking::Shared(snapshot) => {
                for (index, (node, visited)) in
                    snapshot.nodes.iter().zip(self.visited.iter()).enumerate()
                {
                    if !visited && !matches!(node, SnapshotNode::Value(_)) {
                        return Err(WireError::UnreachableResource(index as ValueNodeIndex));
                    }
                }
            }
        }
        Ok(())
    }
}

fn clone_value_node(node: &wire::SchemaValueNode) -> wire::SchemaValueNode {
    match node {
        wire::SchemaValueNode::BoolValue(v) => wire::SchemaValueNode::BoolValue(*v),
        wire::SchemaValueNode::S8Value(v) => wire::SchemaValueNode::S8Value(*v),
        wire::SchemaValueNode::S16Value(v) => wire::SchemaValueNode::S16Value(*v),
        wire::SchemaValueNode::S32Value(v) => wire::SchemaValueNode::S32Value(*v),
        wire::SchemaValueNode::S64Value(v) => wire::SchemaValueNode::S64Value(*v),
        wire::SchemaValueNode::U8Value(v) => wire::SchemaValueNode::U8Value(*v),
        wire::SchemaValueNode::U16Value(v) => wire::SchemaValueNode::U16Value(*v),
        wire::SchemaValueNode::U32Value(v) => wire::SchemaValueNode::U32Value(*v),
        wire::SchemaValueNode::U64Value(v) => wire::SchemaValueNode::U64Value(*v),
        wire::SchemaValueNode::F32Value(v) => wire::SchemaValueNode::F32Value(*v),
        wire::SchemaValueNode::F64Value(v) => wire::SchemaValueNode::F64Value(*v),
        wire::SchemaValueNode::CharValue(v) => wire::SchemaValueNode::CharValue(*v),
        wire::SchemaValueNode::StringValue(v) => wire::SchemaValueNode::StringValue(v.clone()),
        wire::SchemaValueNode::RecordValue(v) => wire::SchemaValueNode::RecordValue(v.clone()),
        wire::SchemaValueNode::VariantValue(v) => wire::SchemaValueNode::VariantValue(*v),
        wire::SchemaValueNode::EnumValue(v) => wire::SchemaValueNode::EnumValue(*v),
        wire::SchemaValueNode::FlagsValue(v) => wire::SchemaValueNode::FlagsValue(v.clone()),
        wire::SchemaValueNode::TupleValue(v) => wire::SchemaValueNode::TupleValue(v.clone()),
        wire::SchemaValueNode::ListValue(v) => wire::SchemaValueNode::ListValue(v.clone()),
        wire::SchemaValueNode::FixedListValue(v) => {
            wire::SchemaValueNode::FixedListValue(v.clone())
        }
        wire::SchemaValueNode::MapValue(v) => wire::SchemaValueNode::MapValue(v.clone()),
        wire::SchemaValueNode::OptionValue(v) => wire::SchemaValueNode::OptionValue(*v),
        wire::SchemaValueNode::ResultValue(v) => wire::SchemaValueNode::ResultValue(*v),
        wire::SchemaValueNode::TextValue(v) => wire::SchemaValueNode::TextValue(v.clone()),
        wire::SchemaValueNode::BinaryValue(v) => wire::SchemaValueNode::BinaryValue(v.clone()),
        wire::SchemaValueNode::PathValue(v) => wire::SchemaValueNode::PathValue(v.clone()),
        wire::SchemaValueNode::UrlValue(v) => wire::SchemaValueNode::UrlValue(v.clone()),
        wire::SchemaValueNode::UuidValue(v) => wire::SchemaValueNode::UuidValue(*v),
        wire::SchemaValueNode::DatetimeValue(v) => wire::SchemaValueNode::DatetimeValue(*v),
        wire::SchemaValueNode::DurationValue(v) => wire::SchemaValueNode::DurationValue(*v),
        wire::SchemaValueNode::QuantityValueNode(v) => {
            wire::SchemaValueNode::QuantityValueNode(v.clone())
        }
        wire::SchemaValueNode::UnionValue(v) => wire::SchemaValueNode::UnionValue(v.clone()),
        wire::SchemaValueNode::SecretValue(_)
        | wire::SchemaValueNode::QuotaTokenHandle(_)
        | wire::SchemaValueNode::PermissionCardHandle(_)
        | wire::SchemaValueNode::StreamValue(_) => {
            unreachable!("resources are snapshot separately")
        }
    }
}

pub fn decode<T: FromWire>(tree: wire::SchemaValueTree) -> Result<T, WireError> {
    let mut reader = WireReader::new(tree.value_nodes);
    let value = T::read_wire(&mut reader, tree.root)?;
    reader.finish()?;
    Ok(value)
}

pub fn decode_result_payload<T: FromWire>(
    tree: Option<wire::SchemaValueTree>,
) -> Result<T, WireError> {
    let (nodes, root) = match tree {
        Some(tree) => (tree.value_nodes, Some(tree.root)),
        None => (Vec::new(), None),
    };
    let mut reader = WireReader::new(nodes);
    let value = T::read_result_payload(&mut reader, root)?;
    reader.finish()?;
    Ok(value)
}

#[derive(Default)]
pub struct WireWriter {
    nodes: Vec<wire::SchemaValueNode>,
}

impl WireWriter {
    pub fn push(&mut self, node: wire::SchemaValueNode) -> ValueNodeIndex {
        let index = self.nodes.len() as ValueNodeIndex;
        self.nodes.push(node);
        index
    }

    pub fn finish(self, root: ValueNodeIndex) -> wire::SchemaValueTree {
        wire::SchemaValueTree {
            value_nodes: self.nodes,
            root,
        }
    }
}

/// A resource-only preflight preserves live handles when aliasing or an
/// already-consumed handle would make an encode fail. It contains no value or
/// schema model and does not poll any stream.
#[derive(Default)]
pub struct WirePreflight {
    seen: HashSet<(&'static str, *const ())>,
    allow_native_streams: bool,
}

impl WirePreflight {
    pub fn asynchronous() -> Self {
        Self {
            allow_native_streams: true,
            ..Self::default()
        }
    }

    pub fn reject_quota_tokens(&self) -> Result<(), WireError> {
        if self.seen.iter().any(|(kind, _)| *kind == "quota-token") {
            Err(WireError::ForbiddenResource("quota-token"))
        } else {
            Ok(())
        }
    }

    fn resource(
        &mut self,
        kind: &'static str,
        id: *const (),
        present: bool,
    ) -> Result<(), WireError> {
        if !present {
            return Err(WireError::ConsumedResource(kind));
        }
        if !self.seen.insert((kind, id)) {
            return Err(WireError::AliasedResource(kind));
        }
        Ok(())
    }
}

pub fn encode<T: IntoWire + ?Sized>(value: &T) -> Result<wire::SchemaValueTree, WireError> {
    let mut preflight = WirePreflight::default();
    value.preflight(&mut preflight)?;
    write(value)
}

pub async fn encode_async<T: IntoWire + ?Sized>(
    value: &T,
) -> Result<wire::SchemaValueTree, WireError> {
    let mut preflight = WirePreflight::asynchronous();
    value.preflight(&mut preflight)?;
    if T::NEEDS_PREPARATION {
        value.prepare_wire().await?;
    }
    write(value)
}

fn write<T: IntoWire + ?Sized>(value: &T) -> Result<wire::SchemaValueTree, WireError> {
    let mut writer = WireWriter::default();
    let root = value.write_wire(&mut writer)?;
    Ok(writer.finish(root))
}

macro_rules! scalar {
    ($($ty:ty => $variant:ident),* $(,)?) => {$(
        impl FromWire for $ty {
            fn read_wire(reader: &mut WireReader, index: ValueNodeIndex) -> Result<Self, WireError> {
                match reader.take(index)? {
                    wire::SchemaValueNode::$variant(value) => Ok(value),
                    _ => Err(WireError::Shape(stringify!($variant))),
                }
            }
        }

        impl IntoWire for $ty {
            const NEEDS_PREPARATION: bool = false;

            fn write_wire(&self, writer: &mut WireWriter) -> Result<ValueNodeIndex, WireError> {
                Ok(writer.push(wire::SchemaValueNode::$variant(self.clone())))
            }
        }
    )*};
}

scalar! {
    bool => BoolValue, i8 => S8Value, i16 => S16Value, i32 => S32Value,
    i64 => S64Value, u8 => U8Value, u16 => U16Value, u32 => U32Value,
    u64 => U64Value, f32 => F32Value, f64 => F64Value, char => CharValue,
}

#[cfg(any(
    feature = "bigdecimal",
    feature = "rust_decimal",
    feature = "num_bigint",
    feature = "serde_json_types",
    feature = "chrono"
))]
macro_rules! wire_string {
    ($ty:ty, $encode:expr, $decode:expr) => {
        impl $crate::schema::wit::direct::WireSchema for $ty {
            fn wire_type_id() -> String {
                <Self as $crate::schema::IntoSchema>::type_id().0
            }

            fn append_schema(builder: &mut $crate::schema::wit::direct::WireSchemaBuilder) -> i32 {
                builder.push($crate::schema::wit::wire::SchemaTypeBody::StringType)
            }
        }

        impl $crate::schema::wit::direct::IntoWire for $ty {
            const NEEDS_PREPARATION: bool = false;

            fn write_wire(
                &self,
                writer: &mut $crate::schema::wit::direct::WireWriter,
            ) -> Result<i32, $crate::schema::wit::direct::WireError> {
                Ok(
                    writer.push($crate::schema::wit::wire::SchemaValueNode::StringValue(
                        ($encode)(self),
                    )),
                )
            }
        }

        impl $crate::schema::wit::direct::FromWire for $ty {
            fn read_wire(
                reader: &mut $crate::schema::wit::direct::WireReader,
                index: i32,
            ) -> Result<Self, $crate::schema::wit::direct::WireError> {
                let $crate::schema::wit::wire::SchemaValueNode::StringValue(value) =
                    reader.take(index)?
                else {
                    return Err($crate::schema::wit::direct::WireError::Shape("string"));
                };
                ($decode)(&value)
                    .map_err(|_| $crate::schema::wit::direct::WireError::Shape(stringify!($ty)))
            }
        }
    };
}
#[cfg(any(
    feature = "bigdecimal",
    feature = "rust_decimal",
    feature = "num_bigint",
    feature = "serde_json_types",
    feature = "chrono"
))]
pub(crate) use wire_string;

impl FromWire for String {
    fn read_wire(reader: &mut WireReader, index: ValueNodeIndex) -> Result<Self, WireError> {
        match reader.take(index)? {
            wire::SchemaValueNode::StringValue(value) => Ok(value),
            // Text-refined tool arguments retain String as their Rust type.
            wire::SchemaValueNode::TextValue(value) => Ok(value.text),
            _ => Err(WireError::Shape("string or text")),
        }
    }
}

impl IntoWire for String {
    const NEEDS_PREPARATION: bool = false;

    fn write_wire(&self, writer: &mut WireWriter) -> Result<ValueNodeIndex, WireError> {
        self.as_str().write_wire(writer)
    }
}

impl WireSchema for usize {
    fn append_schema(builder: &mut WireSchemaBuilder) -> wire::TypeNodeIndex {
        <u64 as WireSchema>::append_schema(builder)
    }
}
impl IntoWire for usize {
    const NEEDS_PREPARATION: bool = false;

    fn write_wire(&self, writer: &mut WireWriter) -> Result<ValueNodeIndex, WireError> {
        (*self as u64).write_wire(writer)
    }
}
impl FromWire for usize {
    fn read_wire(reader: &mut WireReader, index: ValueNodeIndex) -> Result<Self, WireError> {
        usize::try_from(u64::read_wire(reader, index)?).map_err(|_| WireError::Shape("usize range"))
    }
}

impl IntoWire for str {
    const NEEDS_PREPARATION: bool = false;

    fn write_wire(&self, writer: &mut WireWriter) -> Result<ValueNodeIndex, WireError> {
        Ok(writer.push(wire::SchemaValueNode::StringValue(self.to_string())))
    }
}

macro_rules! wire_pointer {
    ($pointer:ty) => {
        impl<T: IntoWire + ?Sized> IntoWire for $pointer {
            const NEEDS_PREPARATION: bool = T::NEEDS_PREPARATION;

            fn preflight(&self, resources: &mut WirePreflight) -> Result<(), WireError> {
                (**self).preflight(resources)
            }

            fn write_wire(&self, writer: &mut WireWriter) -> Result<ValueNodeIndex, WireError> {
                (**self).write_wire(writer)
            }

            async fn prepare_wire(&self) -> Result<(), WireError> {
                if T::NEEDS_PREPARATION {
                    Box::pin((**self).prepare_wire()).await?;
                }
                Ok(())
            }

            fn write_result_payload(
                &self,
                writer: &mut WireWriter,
            ) -> Result<Option<ValueNodeIndex>, WireError> {
                (**self).write_result_payload(writer)
            }
        }

        impl<T: FromWire> FromWire for $pointer {
            fn read_wire(
                reader: &mut WireReader,
                index: ValueNodeIndex,
            ) -> Result<Self, WireError> {
                T::read_wire(reader, index).map(Self::new)
            }

            fn read_result_payload(
                reader: &mut WireReader,
                index: Option<ValueNodeIndex>,
            ) -> Result<Self, WireError> {
                T::read_result_payload(reader, index).map(Self::new)
            }
        }
    };
}
wire_pointer!(Box<T>);
wire_pointer!(Rc<T>);
wire_pointer!(std::sync::Arc<T>);

impl<T: IntoWire + ?Sized> IntoWire for &T {
    const NEEDS_PREPARATION: bool = T::NEEDS_PREPARATION;

    fn preflight(&self, resources: &mut WirePreflight) -> Result<(), WireError> {
        (**self).preflight(resources)
    }

    async fn prepare_wire(&self) -> Result<(), WireError> {
        (**self).prepare_wire().await
    }

    fn write_wire(&self, writer: &mut WireWriter) -> Result<ValueNodeIndex, WireError> {
        (**self).write_wire(writer)
    }

    fn write_result_payload(
        &self,
        writer: &mut WireWriter,
    ) -> Result<Option<ValueNodeIndex>, WireError> {
        (**self).write_result_payload(writer)
    }
}

impl<T: IntoWire> IntoWire for Vec<T> {
    const NEEDS_PREPARATION: bool = T::NEEDS_PREPARATION;

    fn preflight(&self, resources: &mut WirePreflight) -> Result<(), WireError> {
        for value in self {
            value.preflight(resources)?;
        }
        Ok(())
    }

    async fn prepare_wire(&self) -> Result<(), WireError> {
        if T::NEEDS_PREPARATION {
            for value in self {
                Box::pin(value.prepare_wire()).await?;
            }
        }
        Ok(())
    }

    fn write_wire(&self, writer: &mut WireWriter) -> Result<ValueNodeIndex, WireError> {
        let indices = self
            .iter()
            .map(|value| value.write_wire(writer))
            .collect::<Result<_, _>>()?;
        Ok(writer.push(wire::SchemaValueNode::ListValue(indices)))
    }
}

impl<T: FromWire> FromWire for Vec<T> {
    fn read_wire(reader: &mut WireReader, index: ValueNodeIndex) -> Result<Self, WireError> {
        match reader.take(index)? {
            wire::SchemaValueNode::ListValue(indices) => indices
                .into_iter()
                .map(|index| T::read_wire(reader, index))
                .collect(),
            _ => Err(WireError::Shape("list")),
        }
    }
}

impl<T: IntoWire> IntoWire for HashSet<T> {
    const NEEDS_PREPARATION: bool = T::NEEDS_PREPARATION;

    fn preflight(&self, resources: &mut WirePreflight) -> Result<(), WireError> {
        for value in self {
            value.preflight(resources)?;
        }
        Ok(())
    }

    async fn prepare_wire(&self) -> Result<(), WireError> {
        if T::NEEDS_PREPARATION {
            for value in self {
                Box::pin(value.prepare_wire()).await?;
            }
        }
        Ok(())
    }

    fn write_wire(&self, writer: &mut WireWriter) -> Result<ValueNodeIndex, WireError> {
        let indices = self
            .iter()
            .map(|value| value.write_wire(writer))
            .collect::<Result<_, _>>()?;
        Ok(writer.push(wire::SchemaValueNode::ListValue(indices)))
    }
}

impl<T: FromWire + Eq + std::hash::Hash> FromWire for HashSet<T> {
    fn read_wire(reader: &mut WireReader, index: ValueNodeIndex) -> Result<Self, WireError> {
        match reader.take(index)? {
            wire::SchemaValueNode::ListValue(indices) => indices
                .into_iter()
                .map(|index| T::read_wire(reader, index))
                .collect(),
            _ => Err(WireError::Shape("list")),
        }
    }
}

impl<T: IntoWire> IntoWire for Option<T> {
    const NEEDS_PREPARATION: bool = T::NEEDS_PREPARATION;

    fn preflight(&self, resources: &mut WirePreflight) -> Result<(), WireError> {
        if let Some(value) = self {
            value.preflight(resources)?;
        }
        Ok(())
    }

    async fn prepare_wire(&self) -> Result<(), WireError> {
        if let Some(value) = self {
            value.prepare_wire().await?;
        }
        Ok(())
    }

    fn write_wire(&self, writer: &mut WireWriter) -> Result<ValueNodeIndex, WireError> {
        let index = self
            .as_ref()
            .map(|value| value.write_wire(writer))
            .transpose()?;
        Ok(writer.push(wire::SchemaValueNode::OptionValue(index)))
    }
}

impl<T: FromWire> FromWire for Option<T> {
    fn read_wire(reader: &mut WireReader, index: ValueNodeIndex) -> Result<Self, WireError> {
        match reader.take(index)? {
            wire::SchemaValueNode::OptionValue(index) => {
                index.map(|index| T::read_wire(reader, index)).transpose()
            }
            _ => Err(WireError::Shape("option")),
        }
    }
}

impl<T: IntoWire, E: IntoWire> IntoWire for Result<T, E> {
    const NEEDS_PREPARATION: bool = T::NEEDS_PREPARATION || E::NEEDS_PREPARATION;

    fn preflight(&self, resources: &mut WirePreflight) -> Result<(), WireError> {
        match self {
            Ok(value) => value.preflight(resources),
            Err(value) => value.preflight(resources),
        }
    }

    async fn prepare_wire(&self) -> Result<(), WireError> {
        match self {
            Ok(value) => value.prepare_wire().await,
            Err(value) => value.prepare_wire().await,
        }
    }

    fn write_wire(&self, writer: &mut WireWriter) -> Result<ValueNodeIndex, WireError> {
        let payload = match self {
            Ok(value) => wire::ResultValuePayload::OkValue(value.write_result_payload(writer)?),
            Err(value) => wire::ResultValuePayload::ErrValue(value.write_result_payload(writer)?),
        };
        Ok(writer.push(wire::SchemaValueNode::ResultValue(payload)))
    }
}

impl<T: FromWire, E: FromWire> FromWire for Result<T, E> {
    fn read_wire(reader: &mut WireReader, index: ValueNodeIndex) -> Result<Self, WireError> {
        match reader.take(index)? {
            wire::SchemaValueNode::ResultValue(wire::ResultValuePayload::OkValue(index)) => {
                T::read_result_payload(reader, index).map(Ok)
            }
            wire::SchemaValueNode::ResultValue(wire::ResultValuePayload::ErrValue(index)) => {
                E::read_result_payload(reader, index).map(Err)
            }
            _ => Err(WireError::Shape("result")),
        }
    }
}

impl<T: IntoWire> IntoWire for std::ops::Bound<T> {
    const NEEDS_PREPARATION: bool = T::NEEDS_PREPARATION;

    fn preflight(&self, resources: &mut WirePreflight) -> Result<(), WireError> {
        match self {
            std::ops::Bound::Included(value) | std::ops::Bound::Excluded(value) => {
                value.preflight(resources)
            }
            std::ops::Bound::Unbounded => Ok(()),
        }
    }

    async fn prepare_wire(&self) -> Result<(), WireError> {
        match self {
            std::ops::Bound::Included(value) | std::ops::Bound::Excluded(value) => {
                value.prepare_wire().await
            }
            std::ops::Bound::Unbounded => Ok(()),
        }
    }

    fn write_wire(&self, writer: &mut WireWriter) -> Result<ValueNodeIndex, WireError> {
        let (case, payload) = match self {
            std::ops::Bound::Included(value) => (0, Some(value.write_wire(writer)?)),
            std::ops::Bound::Excluded(value) => (1, Some(value.write_wire(writer)?)),
            std::ops::Bound::Unbounded => (2, None),
        };
        Ok(writer.push(wire::SchemaValueNode::VariantValue(
            wire::VariantValuePayload { case, payload },
        )))
    }
}

impl<T: FromWire> FromWire for std::ops::Bound<T> {
    fn read_wire(reader: &mut WireReader, index: ValueNodeIndex) -> Result<Self, WireError> {
        let wire::SchemaValueNode::VariantValue(value) = reader.take(index)? else {
            return Err(WireError::Shape("bound variant"));
        };
        match (value.case, value.payload) {
            (0, Some(index)) => T::read_wire(reader, index).map(std::ops::Bound::Included),
            (1, Some(index)) => T::read_wire(reader, index).map(std::ops::Bound::Excluded),
            (2, None) => Ok(std::ops::Bound::Unbounded),
            _ => Err(WireError::Shape("bound case")),
        }
    }
}

impl IntoWire for () {
    const NEEDS_PREPARATION: bool = false;

    fn write_wire(&self, writer: &mut WireWriter) -> Result<ValueNodeIndex, WireError> {
        Ok(writer.push(wire::SchemaValueNode::TupleValue(Vec::new())))
    }

    fn write_result_payload(
        &self,
        _writer: &mut WireWriter,
    ) -> Result<Option<ValueNodeIndex>, WireError> {
        Ok(None)
    }
}

impl FromWire for () {
    fn read_wire(reader: &mut WireReader, index: ValueNodeIndex) -> Result<Self, WireError> {
        match reader.take(index)? {
            wire::SchemaValueNode::TupleValue(indices) if indices.is_empty() => Ok(()),
            _ => Err(WireError::Shape("unit tuple")),
        }
    }

    fn read_result_payload(
        _reader: &mut WireReader,
        index: Option<ValueNodeIndex>,
    ) -> Result<Self, WireError> {
        match index {
            Some(_) => Err(WireError::Shape("absent unit result payload")),
            None => Ok(()),
        }
    }
}

macro_rules! tuple {
    ($($index:tt : $ty:ident),+) => {
        impl<$($ty: IntoWire),+> IntoWire for ($($ty,)+) {
            const NEEDS_PREPARATION: bool = false $(|| $ty::NEEDS_PREPARATION)+;

            fn preflight(&self, resources: &mut WirePreflight) -> Result<(), WireError> {
                $(self.$index.preflight(resources)?;)+
                Ok(())
            }

            async fn prepare_wire(&self) -> Result<(), WireError> {
                $(self.$index.prepare_wire().await?;)+
                Ok(())
            }

            fn write_wire(&self, writer: &mut WireWriter) -> Result<ValueNodeIndex, WireError> {
                let indices = vec![$(self.$index.write_wire(writer)?),+];
                Ok(writer.push(wire::SchemaValueNode::TupleValue(indices)))
            }
        }

        impl<$($ty: FromWire),+> FromWire for ($($ty,)+) {
            #[allow(non_snake_case)]
            fn read_wire(reader: &mut WireReader, index: ValueNodeIndex) -> Result<Self, WireError> {
                match reader.take(index)? {
                    wire::SchemaValueNode::TupleValue(indices) => {
                        let [$($ty),+] = indices.as_slice() else {
                            return Err(WireError::Shape("tuple arity"));
                        };
                        Ok(($($ty::read_wire(reader, *$ty)?,)+))
                    }
                    _ => Err(WireError::Shape("tuple")),
                }
            }
        }
    };
}

tuple!(0: A);
tuple!(0: A, 1: B);
tuple!(0: A, 1: B, 2: C);
tuple!(0: A, 1: B, 2: C, 3: D);
tuple!(0: A, 1: B, 2: C, 3: D, 4: E);
tuple!(0: A, 1: B, 2: C, 3: D, 4: E, 5: F);
tuple!(0: A, 1: B, 2: C, 3: D, 4: E, 5: F, 6: G);
tuple!(0: A, 1: B, 2: C, 3: D, 4: E, 5: F, 6: G, 7: H);

macro_rules! resource {
    ($ty:ty, $method:ident, $variant:ident, $kind:literal) => {
        impl FromWire for $ty {
            fn read_wire(
                reader: &mut WireReader,
                index: ValueNodeIndex,
            ) -> Result<Self, WireError> {
                reader.$method(index)
            }
        }

        impl IntoWire for $ty {
            fn preflight(&self, resources: &mut WirePreflight) -> Result<(), WireError> {
                resources.resource($kind, self.cell_id(), self.is_present())
            }

            fn write_wire(&self, writer: &mut WireWriter) -> Result<ValueNodeIndex, WireError> {
                let handle = self.take().ok_or(WireError::ConsumedResource($kind))?;
                Ok(writer.push(wire::SchemaValueNode::$variant(handle)))
            }
        }
    };
}

resource!(GuestSecretHandle, secret, SecretValue, "secret");
resource!(
    GuestQuotaTokenHandle,
    quota_token,
    QuotaTokenHandle,
    "quota-token"
);
resource!(
    GuestPermissionCardHandle,
    permission_card,
    PermissionCardHandle,
    "permission-card"
);

impl WireSchema for GuestSecretHandle {
    fn append_schema(builder: &mut WireSchemaBuilder) -> wire::TypeNodeIndex {
        let inner = <String as WireSchema>::append_schema(builder);
        builder.push(wire::SchemaTypeBody::SecretType(wire::SecretSpec {
            inner,
            category: None,
        }))
    }
}

impl WireSchema for GuestQuotaTokenHandle {
    fn append_schema(builder: &mut WireSchemaBuilder) -> wire::TypeNodeIndex {
        builder.push(wire::SchemaTypeBody::QuotaTokenType(wire::QuotaTokenSpec {
            resource_name: None,
        }))
    }
}

impl WireSchema for GuestPermissionCardHandle {
    fn append_schema(builder: &mut WireSchemaBuilder) -> wire::TypeNodeIndex {
        builder.push(wire::SchemaTypeBody::PermissionCardType(
            wire::PermissionCardSpec { polymorphic: false },
        ))
    }
}

impl FromWire for SchemaValueStream {
    fn read_wire(reader: &mut WireReader, index: ValueNodeIndex) -> Result<Self, WireError> {
        reader.stream(index)
    }
}

impl IntoWire for SchemaValueStream {
    fn preflight(&self, resources: &mut WirePreflight) -> Result<(), WireError> {
        resources.resource("stream", self.cell_id(), self.is_present())?;
        if !resources.allow_native_streams && !self.is_wrapped() {
            return Err(WireError::AsyncStream);
        }
        Ok(())
    }

    async fn prepare_wire(&self) -> Result<(), WireError> {
        self.ensure_wrapped()
            .await
            .map_err(|_| WireError::ConsumedResource("stream"))
    }

    fn write_wire(&self, writer: &mut WireWriter) -> Result<ValueNodeIndex, WireError> {
        let stream = self.take_wrapped().ok_or(WireError::AsyncStream)?;
        Ok(writer.push(wire::SchemaValueNode::StreamValue(stream)))
    }
}

impl WireSchema for SchemaValueStream {
    fn contains_stream(_: &mut HashSet<&'static str>) -> bool {
        true
    }

    fn append_schema(builder: &mut WireSchemaBuilder) -> wire::TypeNodeIndex {
        builder.push(wire::SchemaTypeBody::StreamType(None))
    }
}

#[cfg(feature = "bytes")]
impl WireSchema for bytes::Bytes {
    fn wire_type_id() -> String {
        "bytes.Bytes".to_string()
    }

    fn append_schema(builder: &mut WireSchemaBuilder) -> wire::TypeNodeIndex {
        builder.push(wire::SchemaTypeBody::BinaryType(wire::BinaryRestrictions {
            mime_types: None,
            min_bytes: None,
            max_bytes: None,
        }))
    }
}

#[cfg(feature = "bytes")]
impl IntoWire for bytes::Bytes {
    fn write_wire(&self, writer: &mut WireWriter) -> Result<ValueNodeIndex, WireError> {
        Ok(writer.push(wire::SchemaValueNode::BinaryValue(
            wire::BinaryValuePayload {
                bytes: self.to_vec(),
                mime_type: None,
            },
        )))
    }
}

#[cfg(feature = "bytes")]
impl FromWire for bytes::Bytes {
    fn read_wire(reader: &mut WireReader, index: ValueNodeIndex) -> Result<Self, WireError> {
        match reader.take(index)? {
            wire::SchemaValueNode::BinaryValue(payload) => Ok(Self::from(payload.bytes)),
            _ => Err(WireError::Shape("binary")),
        }
    }
}