ic-wire 0.32.0

Bounded Serde/Postcard encoding with schema and TypeScript generation
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
//! One typed authority for supported JSON metadata.
//!
//! This imports explicit metadata; it does not infer arbitrary Serde layouts.
//! Manual projections remain trusted and require independent byte vectors.
//! Named Rust type collection and a matching subset runtime share this contract.

mod advice;
mod advice_policy;
mod native;
mod render;

pub use advice::{BulkLintReport, BulkWarning};
pub use advice_policy::{BulkAdvisory, BulkPolicy, BulkSite};
use alloc::{
    collections::{BTreeMap, BTreeSet},
    string::{String, ToString},
    vec,
    vec::Vec,
};
#[cfg(feature = "derive")]
pub use ic_wire_derive::Wire;
#[doc(hidden)]
pub use native::{PackedField, SerdeBytesField};
pub use native::{SchemaContext, SchemaRegistry, Wire};
use serde_json::{Number, Value};

const MAX_SAFE_INTEGER: u64 = (1_u64 << 53) - 1;

/// Macro support for generated metadata; not a second schema API.
#[doc(hidden)]
pub mod __private {
    pub use serde_json::{Value, json};
}

/// Generated client modules require this metadata/runtime interface marker.
/// This labels tooling artifacts, never Wire payload bytes.
pub const RUNTIME_SCHEMA_FORMAT: &str = "ic-wire-json";

/// TypeScript interpreter for the admitted schema subset. Write this beside
/// generated client modules at their selected runtime import path.
/// Contains no transport, SDK, endpoint execution or deployment implementation.
pub const RUNTIME: &str = include_str!("runtime.ts");

/// Explicit browser payload allowances, owned by the consuming application.
///
/// Node/depth accounting follows the selected browser runtime, not Rust Serde
/// traversal. No native allocation allowance is translated into a JS heap limit.
#[derive(Clone, Copy, Debug)]
pub struct PayloadLimits {
    /// Maximum payload bytes, excluding any frame or transport envelope.
    /// A sparse root requires at least one byte for its extension block.
    pub bytes: u64,
    /// Maximum runtime value visits; must be nonzero.
    pub nodes: u64,
    /// Maximum runtime value depth; must be nonzero.
    pub depth: u64,
}

/// One typed request/response contract for generated framed clients.
///
/// Both byte allowances are payload-only; generation adds the existing 11-byte
/// header. Node/depth allowances retain browser runtime accounting.
#[derive(Clone, Copy, Debug)]
pub struct Method<'a> {
    /// Exported codec identifier. Does not implicitly determine the method ID.
    pub export: &'a str,
    /// Exact routing identity; use crate::method_id explicitly for named IDs.
    pub id: u64,
    /// Admitted request type name.
    pub request: &'a str,
    /// Admitted response type name.
    pub response: &'a str,
    /// Request payload allowances.
    pub request_limits: PayloadLimits,
    /// Response payload allowances.
    pub response_limits: PayloadLimits,
}

/// One mounted endpoint and its existing TypeScript method codec.
#[cfg(feature = "service-client")]
#[derive(Clone, Copy, Debug)]
pub struct ServiceMethod<'a> {
    /// Public property name on the generated service client.
    pub binding: &'a str,
    /// Identifier imported from the method's codec module.
    pub codec_export: &'a str,
    /// Deployed name passed verbatim to the transport.
    pub endpoint: &'a str,
    /// Module specifier exporting the codec generated by `method_module`.
    pub codec_module: &'a str,
    /// Mounted call mode: `query`, `composite_query` or `update`.
    pub mode: &'a str,
}

/// Invalid metadata or exhausted schema generation allowance.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum GenerationError {
    /// Unsupported shape, invalid field, unresolved name or alias-only cycle.
    Schema,
    /// Metadata or output exceeds its schema allowance.
    Complexity,
}

/// Schema limits, independent of codec runtime allowances.
#[derive(Clone, Copy, Debug)]
pub struct SchemaLimits {
    /// Maximum number of named definitions plus inline nodes.
    pub nodes: usize,
    /// Maximum nested inline JSON depth; references are not expanded.
    pub depth: usize,
    /// Maximum total bytes of names, field/variant labels and check names retained.
    pub names_bytes: usize,
    /// Maximum bytes per emitted declaration or metadata artifact.
    pub output_bytes: usize,
}

impl Default for SchemaLimits {
    fn default() -> Self {
        Self {
            nodes: 65_536,
            depth: 64,
            names_bytes: 1_048_576,
            output_bytes: 1_048_576,
        }
    }
}

#[derive(Debug)]
struct ScalarBounds {
    min: Option<Number>,
    max: Option<Number>,
}

#[derive(Debug)]
struct Annotations {
    check: Option<String>,
    bounds: Option<ScalarBounds>,
    fixed: bool,
    projected: bool,
}

#[derive(Debug)]
struct ExtensionField {
    id: u32,
    name: String,
    child: usize,
    required: bool,
}

#[derive(Debug)]
enum Node {
    Unit,
    Bool,
    Integer {
        bits: u8,
        signed: bool,
    },
    Float {
        bits: u8,
    },
    Text {
        max: Option<u64>,
    },
    Bytes {
        min: Option<u64>,
        max: Option<u64>,
    },
    Packed {
        word: &'static str,
        nonzero: bool,
        max: Option<u64>,
    },
    List {
        item: usize,
        max: Option<u64>,
    },
    Array {
        item: usize,
        len: u64,
    },
    Tuple(Vec<usize>),
    Result {
        ok: usize,
        err: usize,
    },
    Option(usize),
    Recover(usize),
    Alias(usize),
    Ref(usize),
    Record(Vec<(String, usize)>),
    Enum(Vec<(String, u32, usize)>),
    ExtensionRecord {
        fields: Vec<(String, usize)>,
        extensions: Vec<ExtensionField>,
    },
    ExtensionTuple {
        items: Vec<usize>,
        extensions: Vec<ExtensionField>,
    },
    OpenVariant {
        variants: Vec<(String, u32, usize)>,
        required: bool,
    },
}

/// Immutable admitted registry with private node indices.
///
/// Supplied definition names are preserved.
/// Input metadata can be mutated or dropped after construction without changing
/// the graph. All rendering consumes this graph, never the original JSON.
#[derive(Debug)]
pub struct ValidatedRegistry {
    names: Vec<String>,
    roots: Vec<usize>,
    nodes: Vec<Node>,
    annotations: BTreeMap<usize, Annotations>,
    output_bytes: usize,
}

impl ValidatedRegistry {
    /// Import explicit definitions in the Wire metadata grammar.
    ///
    /// Supported kinds: unit, bool, u/i, float, text, bytes, packed, list,
    /// array, tuple, result, option, recover, newtype, ref, record, enum,
    /// extension-record, extension-tuple and open-variant. Unknown keys reject;
    /// manual metadata must match the consumer's actual Serde representation.
    /// Records and tuples may declare `"fixed":true` for typed method admission.
    /// `"projected":true` identifies a generated extension layout that the
    /// typed Rust codec projects recursively.
    ///
    /// # Errors
    /// Returns Schema for invalid metadata and Complexity for exceeded bounds.
    /// Failure returns no partially usable registry. Input JSON allocation is
    /// caller-owned; limits apply to graph import, not parsing external JSON text.
    pub fn from_metadata(
        types: &BTreeMap<String, Value>,
        limits: SchemaLimits,
    ) -> Result<Self, GenerationError> {
        if limits.depth > 64 || types.len() > limits.nodes {
            return Err(GenerationError::Complexity);
        }
        let mut importer = Importer {
            nodes: Vec::new(),
            annotations: BTreeMap::new(),
            names: BTreeMap::new(),
            remaining: limits.nodes - types.len(),
            name_bytes: limits.names_bytes,
            depth: limits.depth,
        };
        let mut names = Vec::new();
        for (index, name) in types.keys().enumerate() {
            identifier(name)?;
            let name = importer.name(name)?;
            importer.names.insert(name.clone(), index);
            names.push(name);
        }
        let mut roots = Vec::new();
        for value in types.values() {
            roots.push(importer.parse(value, 0)?);
        }
        let graph = Self {
            names,
            roots,
            nodes: importer.nodes,
            annotations: importer.annotations,
            output_bytes: limits.output_bytes,
        };
        graph.validate_aliases()?;
        Ok(graph)
    }

    fn message_root_nodes(
        &self,
        roots: &[usize],
        require_sparse: bool,
    ) -> Result<Vec<usize>, GenerationError> {
        if roots.is_empty() {
            return Ok(Vec::new());
        }
        let mut checked_roots = vec![false; self.nodes.len()];
        let mut terminals = Vec::new();
        for &root in roots {
            let mut id = self.roots[root];
            // Alias cycles have already been rejected. Share the walk across roots.
            while !core::mem::replace(&mut checked_roots[id], true) {
                match &self.nodes[id] {
                    Node::Alias(item) if !self.annotations.get(&id).is_some_and(|a| a.fixed) => {
                        id = *item
                    }
                    Node::Ref(root) => id = self.roots[*root],
                    _ if require_sparse && !self.sparse_node(id) => {
                        return Err(GenerationError::Schema);
                    }
                    _ => {
                        terminals.push(id);
                        break;
                    }
                }
            }
        }
        Ok(terminals)
    }

    fn validate_evolving_roots(&self, roots: &BTreeSet<String>) -> Result<(), GenerationError> {
        let indices = roots
            .iter()
            .map(|root| self.root_index(root))
            .collect::<Result<Vec<_>, _>>()?;
        self.validate_projection_layouts(self.message_root_nodes(&indices, true)?, Vec::new())
    }

    fn sparse_node(&self, id: usize) -> bool {
        matches!(
            self.nodes[id],
            Node::ExtensionRecord { .. } | Node::ExtensionTuple { .. }
        )
    }

    fn validate_message_roots(&self, roots: &[usize]) -> Result<(), GenerationError> {
        let mut sparse = Vec::new();
        let mut positional = Vec::new();
        for id in self.message_root_nodes(roots, false)? {
            if !self.sparse_node(id) {
                positional.push(id);
            } else if self.annotations.get(&id).is_some_and(|a| a.projected) {
                sparse.push(id);
            }
        }
        self.validate_projection_layouts(sparse, positional)
    }

    fn validate_projection_layouts(
        &self,
        roots: Vec<usize>,
        positional: Vec<usize>,
    ) -> Result<(), GenerationError> {
        #[derive(Clone, Copy, PartialEq, Eq)]
        enum Layout {
            Positional,
            Projected,
            FixedChild,
        }
        use Layout::{FixedChild, Positional, Projected};

        let mut pending: Vec<_> = positional.into_iter().map(|id| (id, Positional)).collect();
        for id in roots {
            match &self.nodes[id] {
                Node::ExtensionRecord { fields, extensions } => {
                    pending.extend(fields.iter().map(|(_, child)| (*child, Projected)));
                    pending.extend(extensions.iter().map(|entry| (entry.child, Projected)));
                }
                Node::ExtensionTuple { items, extensions } => {
                    pending.extend(items.iter().map(|&item| (item, Projected)));
                    pending.extend(extensions.iter().map(|entry| (entry.child, Projected)));
                }
                _ => unreachable!("admitted evolving root"),
            }
        }
        if pending.is_empty() {
            return Ok(());
        }

        // Generated projection follows containers. A fixed Serde aggregate
        // decodes its descendants as ordinary Serde, so reachability from each
        // context must be checked separately even for the same named node.
        let mut visited = vec![[false; 3]; self.nodes.len()];
        while let Some((id, layout)) = pending.pop() {
            if core::mem::replace(&mut visited[id][layout as usize], true) {
                continue;
            }
            let flags = self.annotations.get(&id);
            let fixed = layout != Projected || flags.is_some_and(|a| a.fixed);
            let projected = layout == Projected && flags.is_some_and(|a| a.projected);
            // An ordinary Serde parent cannot emit a derived child's sparse projection.
            // Explicit carrier schemas own their custom Serde representation.
            if layout == Positional && flags.is_some_and(|a| a.projected) {
                return Err(GenerationError::Schema);
            }
            let child_layout = if layout == Positional {
                Positional
            } else {
                FixedChild
            };
            match &self.nodes[id] {
                Node::Record(fields) if fixed => {
                    pending.extend(fields.iter().map(|(_, child)| (*child, child_layout)));
                }
                Node::Tuple(items) if fixed => {
                    pending.extend(items.iter().map(|&item| (item, child_layout)));
                }
                Node::ExtensionRecord { fields, extensions } if projected => {
                    pending.extend(fields.iter().map(|(_, child)| (*child, Projected)));
                    pending.extend(extensions.iter().map(|entry| (entry.child, Projected)));
                }
                Node::ExtensionTuple { items, extensions } if projected => {
                    pending.extend(items.iter().map(|&item| (item, Projected)));
                    pending.extend(extensions.iter().map(|entry| (entry.child, Projected)));
                }
                Node::List { item, .. } | Node::Array { item, .. } | Node::Option(item) => {
                    pending.push((*item, layout))
                }
                Node::Alias(item) => pending.push((*item, child_layout)),
                Node::Ref(root) => pending.push((self.roots[*root], layout)),
                Node::Result { ok, err } => {
                    pending.extend([(*ok, layout), (*err, layout)]);
                }
                Node::Enum(variants) => {
                    pending.extend(variants.iter().map(|(_, _, child)| (*child, child_layout)));
                }
                Node::ExtensionRecord { .. }
                | Node::ExtensionTuple { .. }
                | Node::OpenVariant { .. }
                | Node::Recover(_)
                    if layout == Positional => {}
                Node::Record(_)
                | Node::Tuple(_)
                | Node::ExtensionRecord { .. }
                | Node::ExtensionTuple { .. }
                | Node::OpenVariant { .. }
                | Node::Recover(_) => return Err(GenerationError::Schema),
                Node::Unit
                | Node::Bool
                | Node::Integer { .. }
                | Node::Float { .. }
                | Node::Text { .. }
                | Node::Bytes { .. }
                | Node::Packed { .. } => {}
            }
        }
        Ok(())
    }

    // Linear worklist over transparent edges. Productive recursive records,
    // lists and options terminate an alias chain rather than expanding it.
    fn validate_aliases(&self) -> Result<(), GenerationError> {
        let mut state = vec![0_u8; self.nodes.len()];
        let mut path = Vec::new();
        for start in 0..self.nodes.len() {
            let mut current = start;
            path.clear();
            loop {
                match state[current] {
                    1 => return Err(GenerationError::Schema),
                    2 => break,
                    _ => {}
                }
                state[current] = 1;
                path.push(current);
                match self.nodes[current] {
                    Node::Alias(next) => current = next,
                    Node::Ref(root) => current = self.roots[root],
                    _ => break,
                }
            }
            for node in &path {
                state[*node] = 2;
            }
        }
        Ok(())
    }
}

struct Importer {
    nodes: Vec<Node>,
    annotations: BTreeMap<usize, Annotations>,
    names: BTreeMap<String, usize>,
    remaining: usize,
    name_bytes: usize,
    depth: usize,
}

impl Importer {
    fn name(&mut self, name: &str) -> Result<String, GenerationError> {
        self.name_bytes = self
            .name_bytes
            .checked_sub(name.len())
            .ok_or(GenerationError::Complexity)?;
        Ok(name.to_string())
    }

    fn parse_extensions<'a>(
        &mut self,
        value: &'a Value,
        depth: usize,
        names: &mut BTreeSet<&'a str>,
        tuple_core_slots: Option<u32>,
    ) -> Result<Vec<ExtensionField>, GenerationError> {
        let entries = value.as_array().ok_or(GenerationError::Schema)?;
        if entries.len() > self.remaining {
            return Err(GenerationError::Complexity);
        }
        let mut extensions = Vec::new();
        let mut previous = tuple_core_slots.unwrap_or(0);
        for entry in entries {
            keys(entry, &["name", "id", "value", "required"])?;
            let name = text(entry, "name")?;
            let id = entry["id"]
                .as_u64()
                .and_then(|n| u32::try_from(n).ok())
                .ok_or(GenerationError::Schema)?;
            let required = entry["required"].as_bool().ok_or(GenerationError::Schema)?;
            if id <= previous
                || (tuple_core_slots.is_some() && (required || previous.checked_add(1) != Some(id)))
                || !names.insert(name)
            {
                return Err(GenerationError::Schema);
            }
            previous = id;
            extensions.push(ExtensionField {
                id,
                name: self.name(name)?,
                child: self.parse(&entry["value"], depth + 1)?,
                required,
            });
        }

        Ok(extensions)
    }

    fn parse(&mut self, value: &Value, depth: usize) -> Result<usize, GenerationError> {
        if depth > self.depth {
            return Err(GenerationError::Complexity);
        }
        self.remaining = self
            .remaining
            .checked_sub(1)
            .ok_or(GenerationError::Complexity)?;
        let kind = text(value, "k")?;
        let allowed: &[&str] = match kind {
            "unit" | "bool" => &["k", "check"],
            "u" | "i" | "float" => &["k", "check", "bits", "min", "max"],
            "text" => &["k", "check", "max"],
            "packed" => &["k", "check", "word", "nonzero", "max"],
            "bytes" => &["k", "check", "min", "max"],
            "list" | "array" => &["k", "check", "item", "max"],
            "tuple" => &["k", "check", "items", "fixed"],
            "result" => &["k", "check", "ok", "err"],
            "option" | "recover" => &["k", "check", "item"],
            "newtype" => &["k", "check", "item", "fixed"],
            "ref" => &["k", "check", "name"],
            "record" => &["k", "check", "fields", "fixed"],
            "enum" => &["k", "check", "variants"],
            "extension-record" => &["k", "check", "fields", "extensions", "projected"],
            "extension-tuple" => &["k", "check", "items", "extensions", "projected"],
            "open-variant" => &["k", "check", "variants", "required"],
            _ => return Err(GenerationError::Schema),
        };
        keys(value, allowed)?;
        let node = match kind {
            "unit" => Node::Unit,
            "bool" => Node::Bool,
            "float" => {
                let bits = value["bits"].as_u64().ok_or(GenerationError::Schema)?;
                if ![32, 64].contains(&bits) {
                    return Err(GenerationError::Schema);
                }
                Node::Float { bits: bits as u8 }
            }
            "u" | "i" => {
                let bits = value["bits"].as_u64().ok_or(GenerationError::Schema)?;
                if ![8, 16, 32, 64, 128].contains(&bits) {
                    return Err(GenerationError::Schema);
                }
                Node::Integer {
                    bits: bits as u8,
                    signed: kind == "i",
                }
            }
            "text" => Node::Text {
                max: bound(value, "max")?,
            },
            "bytes" => {
                let min = bound(value, "min")?;
                let max = bound(value, "max")?;
                if min.zip(max).is_some_and(|(min, max)| min > max) {
                    return Err(GenerationError::Schema);
                }
                Node::Bytes { min, max }
            }
            "packed" => {
                let word = text(value, "word")?;
                let word = [
                    "i8",
                    "i16",
                    "u16",
                    "i32",
                    "u32",
                    "i64",
                    "u64",
                    "hash16",
                    "hash32",
                    "bool",
                    "finite-f32",
                    "finite-f64",
                ]
                .into_iter()
                .find(|candidate| *candidate == word)
                .ok_or(GenerationError::Schema)?;
                let nonzero = match value.get("nonzero") {
                    None => false,
                    Some(Value::Bool(true)) if word == "i64" => true,
                    _ => return Err(GenerationError::Schema),
                };
                let max = bound(value, "max")?;
                let width = match word {
                    "bool" | "i8" => 1,
                    "i16" | "u16" => 2,
                    "i32" | "u32" | "finite-f32" => 4,
                    "i64" | "u64" | "finite-f64" => 8,
                    "hash16" => 16,
                    _ => 32,
                };
                if max.is_some_and(|n| n > MAX_SAFE_INTEGER / width) {
                    return Err(GenerationError::Complexity);
                }
                Node::Packed { word, nonzero, max }
            }
            "list" => Node::List {
                max: bound(value, "max")?,
                item: self.parse(&value["item"], depth + 1)?,
            },
            "array" => Node::Array {
                len: bound(value, "max")?.ok_or(GenerationError::Schema)?,
                item: self.parse(&value["item"], depth + 1)?,
            },
            "tuple" | "extension-tuple" => {
                let items = value["items"].as_array().ok_or(GenerationError::Schema)?;
                if items.len() > self.remaining {
                    return Err(GenerationError::Complexity);
                }
                let items = items
                    .iter()
                    .map(|item| self.parse(item, depth + 1))
                    .collect::<Result<Vec<_>, _>>()?;
                if kind == "extension-tuple" {
                    let slots =
                        u32::try_from(items.len()).map_err(|_| GenerationError::Complexity)?;
                    Node::ExtensionTuple {
                        items,
                        extensions: self.parse_extensions(
                            &value["extensions"],
                            depth,
                            &mut BTreeSet::new(),
                            Some(slots),
                        )?,
                    }
                } else {
                    Node::Tuple(items)
                }
            }
            "result" => Node::Result {
                ok: self.parse(&value["ok"], depth + 1)?,
                err: self.parse(&value["err"], depth + 1)?,
            },
            "option" => Node::Option(self.parse(&value["item"], depth + 1)?),
            "recover" => Node::Recover(self.parse(&value["item"], depth + 1)?),
            "newtype" => Node::Alias(self.parse(&value["item"], depth + 1)?),
            "ref" => Node::Ref(
                *self
                    .names
                    .get(text(value, "name")?)
                    .ok_or(GenerationError::Schema)?,
            ),
            "record" | "enum" | "extension-record" | "open-variant" => {
                let is_open = kind == "open-variant";
                let is_enum = kind == "enum" || is_open;
                let fields = value[if is_enum { "variants" } else { "fields" }]
                    .as_array()
                    .ok_or(GenerationError::Schema)?;
                if kind == "enum" && fields.is_empty() {
                    return Err(GenerationError::Schema);
                }
                if fields.len() > self.remaining {
                    return Err(GenerationError::Complexity);
                }
                let mut seen = BTreeSet::new();
                let mut ids = BTreeSet::new();
                let mut record = Vec::new();
                let mut variants = Vec::new();
                for field in fields {
                    keys(
                        field,
                        if is_enum {
                            &["name", "id", "value"]
                        } else {
                            &["name", "value"]
                        },
                    )?;
                    let name = text(field, "name")?;
                    if !seen.insert(name) {
                        return Err(GenerationError::Schema);
                    }
                    let name = self.name(name)?;
                    let child = self.parse(&field["value"], depth + 1)?;
                    if is_enum {
                        let id = field["id"]
                            .as_u64()
                            .and_then(|id| u32::try_from(id).ok())
                            .ok_or(GenerationError::Schema)?;
                        if (is_open && !(1..=u32::MAX >> 1).contains(&id)) || !ids.insert(id) {
                            return Err(GenerationError::Schema);
                        }
                        variants.push((name, id, child));
                    } else {
                        record.push((name, child));
                    }
                }
                match kind {
                    "enum" => Node::Enum(variants),
                    "open-variant" => Node::OpenVariant {
                        variants,
                        required: match value.get("required") {
                            Some(required) => required.as_bool().ok_or(GenerationError::Schema)?,
                            None => false,
                        },
                    },
                    "extension-record" => Node::ExtensionRecord {
                        fields: record,
                        extensions: self.parse_extensions(
                            &value["extensions"],
                            depth,
                            &mut seen,
                            None,
                        )?,
                    },
                    _ => Node::Record(record),
                }
            }
            _ => return Err(GenerationError::Schema),
        };
        let id = self.nodes.len();
        let check = value
            .get("check")
            .map(|check| self.name(check.as_str().ok_or(GenerationError::Schema)?))
            .transpose()?;
        let bounds = if matches!(kind, "u" | "i" | "float")
            && (value.get("min").is_some() || value.get("max").is_some())
        {
            Some(scalar_bounds(value, kind != "float")?)
        } else {
            None
        };
        let fixed = match value.get("fixed") {
            None => false,
            Some(Value::Bool(true)) => true,
            Some(_) => return Err(GenerationError::Schema),
        };
        let projected = match value.get("projected") {
            None => false,
            Some(Value::Bool(true)) => true,
            Some(_) => return Err(GenerationError::Schema),
        };
        if check.is_some() || bounds.is_some() || fixed || projected {
            self.annotations.insert(
                id,
                Annotations {
                    check,
                    bounds,
                    fixed,
                    projected,
                },
            );
        }
        self.nodes.push(node);
        Ok(id)
    }
}

fn text<'a>(value: &'a Value, key: &str) -> Result<&'a str, GenerationError> {
    value[key].as_str().ok_or(GenerationError::Schema)
}

fn keys(value: &Value, allowed: &[&str]) -> Result<(), GenerationError> {
    if value
        .as_object()
        .ok_or(GenerationError::Schema)?
        .keys()
        .any(|key| !allowed.contains(&key.as_str()))
    {
        return Err(GenerationError::Schema);
    }
    Ok(())
}

fn bound(value: &Value, key: &str) -> Result<Option<u64>, GenerationError> {
    value
        .get(key)
        .map(|n| {
            let n = n.as_u64().ok_or(GenerationError::Schema)?;
            if n > MAX_SAFE_INTEGER {
                return Err(GenerationError::Complexity);
            }
            Ok(n)
        })
        .transpose()
}

fn identifier(name: &str) -> Result<(), GenerationError> {
    if name.is_empty()
        || !name
            .bytes()
            .enumerate()
            .all(|(i, b)| b.is_ascii_alphabetic() || b == b'_' || (i > 0 && b.is_ascii_digit()))
    {
        return Err(GenerationError::Schema);
    }
    if RESERVED.contains(&name) {
        return Err(GenerationError::Schema);
    }
    Ok(())
}

const RESERVED: &[&str] = &[
    "as",
    "break",
    "case",
    "catch",
    "class",
    "const",
    "continue",
    "debugger",
    "default",
    "delete",
    "do",
    "else",
    "enum",
    "export",
    "extends",
    "false",
    "finally",
    "for",
    "function",
    "if",
    "import",
    "in",
    "instanceof",
    "new",
    "null",
    "return",
    "super",
    "switch",
    "this",
    "throw",
    "true",
    "try",
    "typeof",
    "var",
    "void",
    "while",
    "with",
    "implements",
    "interface",
    "let",
    "package",
    "private",
    "protected",
    "public",
    "static",
    "yield",
    "await",
    "any",
    "boolean",
    "bigint",
    "never",
    "number",
    "object",
    "string",
    "symbol",
    "undefined",
    "unknown",
    "eval",
    "arguments",
];

fn scalar_bounds(value: &Value, integer: bool) -> Result<ScalarBounds, GenerationError> {
    let read = |key| -> Result<Option<Number>, GenerationError> {
        value
            .get(key)
            .map(|value| {
                let number = value.as_number().ok_or(GenerationError::Schema)?;
                let n = number
                    .as_f64()
                    .filter(|n| n.is_finite())
                    .ok_or(GenerationError::Schema)?;
                if integer {
                    if n % 1.0 != 0.0 {
                        return Err(GenerationError::Schema);
                    }
                    if n.abs() > 9_007_199_254_740_991.0 {
                        return Err(GenerationError::Complexity);
                    }
                }
                Ok(number.clone())
            })
            .transpose()
    };
    let bounds = ScalarBounds {
        min: read("min")?,
        max: read("max")?,
    };
    if bounds
        .min
        .as_ref()
        .zip(bounds.max.as_ref())
        .is_some_and(|(min, max)| min.as_f64() > max.as_f64())
    {
        return Err(GenerationError::Schema);
    }
    Ok(bounds)
}