ic-wire 0.24.4

Bounded Serde/Postcard encoding with host 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
use super::{
    GenerationError, Method, Node, PayloadLimits, RUNTIME_SCHEMA_FORMAT, ValidatedRegistry,
    identifier,
};
use alloc::{
    collections::{BTreeMap, BTreeSet},
    format,
    string::String,
};
use core::fmt::{self, Write};

// Check before extending the output, including escaped field names. Syntax
// recursion is bounded at import; named references never expand during rendering.
struct Output {
    text: String,
    remaining: usize,
}

impl Write for Output {
    fn write_str(&mut self, value: &str) -> fmt::Result {
        self.remaining = self.remaining.checked_sub(value.len()).ok_or(fmt::Error)?;
        self.text.push_str(value);
        Ok(())
    }
}

impl Output {
    fn scalar_bounds(&mut self, bounds: &super::ScalarBounds, json: bool) -> fmt::Result {
        for (key, bound) in [("min", &bounds.min), ("max", &bounds.max)] {
            if let Some(bound) = bound {
                if json {
                    write!(self, ",\"{key}\":{bound}")?;
                } else {
                    write!(self, "/* {key} {bound} */ ")?;
                }
            }
        }
        Ok(())
    }
    fn quoted(&mut self, value: &str) -> fmt::Result {
        self.write_char('"')?;
        let mut start = 0;
        for (index, character) in value.char_indices() {
            if !matches!(
                character,
                '"' | '\\' | '\u{0000}'..='\u{001f}' | '\u{2028}' | '\u{2029}'
            ) {
                continue;
            }
            // Admit and append ordinary UTF-8 spans together. Only escape
            // boundaries need individual writes; byte accounting stays exact.
            self.write_str(&value[start..index])?;
            match character {
                '"' => self.write_str("\\\"")?,
                '\\' => self.write_str("\\\\")?,
                '\u{0000}'..='\u{001f}' | '\u{2028}' | '\u{2029}' => {
                    write!(self, "\\u{:04x}", u32::from(character))?;
                }
                _ => unreachable!(),
            }
            start = index + character.len_utf8();
        }
        self.write_str(&value[start..])?;
        self.write_char('"')
    }

    fn bounds(&mut self, min: Option<u64>, max: Option<u64>) -> fmt::Result {
        if let Some(min) = min {
            write!(self, "/* min {min} */ ")?;
        }
        if let Some(max) = max {
            write!(self, "/* max {max} */ ")?;
        }
        Ok(())
    }
}

impl ValidatedRegistry {
    /// Generate a typed payload client with privately owned metadata and policy.
    ///
    /// `root` names an admitted type. `export` names the exported codec object.
    /// The trusted runtime module must export `schemaFormat` matching
    /// [`RUNTIME_SCHEMA_FORMAT`] and `createPayloadCodec(metadata, registry)`.
    /// The factory returns `encode(unknown): Uint8Array` and `decode(Uint8Array):
    /// unknown`, using the exported JSON grammar. Qualification executes the bundled
    /// runtime against independent literal bytes and Rust decode results.
    /// Runtime code is not bundled, downloaded or selected by this function.
    /// Bulk advice always runs for `/types/ROOT`. The required handler runs once
    /// after successful rendering and linting, including a clean report. It should
    /// display diagnostics in the consumer's build output or enforce `is_clean()`.
    /// Acknowledgements never change generated source.
    ///
    /// # Errors
    /// Returns Schema for invalid names, missing roots, empty module specifiers
    /// or zero node/depth allowances; Complexity for unsafe JS integers or an
    /// artifact exceeding the registry's output allowance. Rooted advice can also
    /// return the errors documented by [`Self::lint_bulk_roots`].
    pub fn payload_module(
        &self,
        export: &str,
        root: &str,
        runtime_module: &str,
        limits: PayloadLimits,
        acknowledgements: &BTreeMap<String, String>,
        diagnostics: impl FnOnce(super::BulkLintReport),
    ) -> Result<String, GenerationError> {
        self.admit_client(export, root, runtime_module, limits)?;
        let mut output = Output {
            text: String::new(),
            remaining: self.output_bytes,
        };
        self.render_payload_module(&mut output, export, root, runtime_module, limits)
            .map_err(|_| GenerationError::Complexity)?;
        let report = self.lint_roots(
            [Ok((
                format!("/types/{}", super::advice::escape(root)),
                self.root_index(root)?,
            ))],
            acknowledgements,
        )?;
        diagnostics(report);
        Ok(output.text)
    }

    fn admit_client(
        &self,
        export: &str,
        root: &str,
        runtime_module: &str,
        limits: PayloadLimits,
    ) -> Result<(), GenerationError> {
        identifier(export)?;
        if export == "globalThis"
            || self
                .names
                .binary_search_by(|name| name.as_str().cmp(root))
                .is_err()
            || self
                .names
                .binary_search_by(|name| name.as_str().cmp(export))
                .is_ok()
            || runtime_module.is_empty()
            || runtime_module.contains('\0')
            || limits.nodes == 0
            || limits.depth == 0
        {
            return Err(GenerationError::Schema);
        }
        if [limits.bytes, limits.nodes, limits.depth]
            .into_iter()
            .any(|n| n > (1_u64 << 53) - 1)
        {
            return Err(GenerationError::Complexity);
        }
        Ok(())
    }

    /// Generate typed framed codecs with independent request/response policy.
    ///
    /// The runtime must export `schemaFormat` and `createCodec` with the
    /// bundled framed-codec interface. IDs are emitted as decimal strings,
    /// preserving all u64 values without JavaScript Number rounding. Duplicate
    /// IDs or exports reject before rendering. This emits no routing/execution.
    /// Bulk advice always reviews each `/methods/EXPORT/request` and `/response`
    /// independently. The required handler runs once on success, even when clean.
    ///
    /// # Errors
    /// Returns Schema for invalid names, roots, policies or duplicate IDs;
    /// Complexity for unsafe header-inclusive byte allowances or excess output,
    /// and the rooted-advice errors documented by [`Self::lint_bulk_roots`].
    pub fn method_module(
        &self,
        methods: &[Method<'_>],
        runtime_module: &str,
        acknowledgements: &BTreeMap<String, String>,
        diagnostics: impl FnOnce(super::BulkLintReport),
    ) -> Result<String, GenerationError> {
        if methods.is_empty() {
            return Err(GenerationError::Schema);
        }
        // Each method necessarily emits at least one byte; bound admission work
        // before allocating duplicate-detection sets for caller-owned input.
        if methods.len() > self.output_bytes {
            return Err(GenerationError::Complexity);
        }
        let mut names = BTreeSet::new();
        let mut ids = BTreeSet::new();
        for method in methods {
            for (root, limits) in [
                (method.request, method.request_limits),
                (method.response, method.response_limits),
            ] {
                self.admit_client(method.export, root, runtime_module, limits)?;
                if limits.bytes > (1_u64 << 53) - 12 {
                    return Err(GenerationError::Complexity);
                }
            }
            if !names.insert(method.export) || !ids.insert(method.id) {
                return Err(GenerationError::Schema);
            }
        }
        let mut output = Output {
            text: String::new(),
            remaining: self.output_bytes,
        };
        self.render_methods(&mut output, methods, runtime_module)
            .map_err(|_| GenerationError::Complexity)?;
        let roots = methods.iter().flat_map(|method| {
            [("request", method.request), ("response", method.response)].map(|(direction, root)| {
                Ok((
                    format!(
                        "/methods/{}/{direction}",
                        super::advice::escape(method.export)
                    ),
                    self.root_index(root)?,
                ))
            })
        });
        let report = self.lint_roots(roots, acknowledgements)?;
        diagnostics(report);
        Ok(output.text)
    }

    fn render_methods(
        &self,
        output: &mut Output,
        methods: &[Method<'_>],
        runtime_module: &str,
    ) -> fmt::Result {
        self.module_prelude(output, runtime_module, "createCodec")?;
        for method in methods {
            writeln!(output, "export const {} = (() => {{", method.export)?;
            write!(
                output,
                "const $codec = $create({{id:'{}',request:{{k:'ref',name:",
                method.id
            )?;
            output.quoted(method.request)?;
            output.write_str("},response:{k:'ref',name:")?;
            output.quoted(method.response)?;
            for (prefix, limits) in [
                ("request", method.request_limits),
                ("response", method.response_limits),
            ] {
                write!(
                    output,
                    "{separator}{prefix}Bytes:{}, {prefix}Nodes:{}, {prefix}Depth:{}",
                    limits.bytes + 11,
                    limits.nodes,
                    limits.depth,
                    separator = if prefix == "request" { "}," } else { "," }
                )?;
            }
            output.write_str("}, $types);\nreturn globalThis.Object.freeze({\n")?;
            for (direction, root) in [("Request", method.request), ("Response", method.response)] {
                writeln!(
                    output,
                    "encode{direction}:(value: {root}): globalThis.Uint8Array => $codec.encode{direction}(value), decode{direction}:(bytes: globalThis.Uint8Array): {root} => $codec.decode{direction}(bytes) as {root},"
                )?;
            }
            output.write_str("});\n})();\n")?;
        }
        Ok(())
    }

    fn render_payload_module(
        &self,
        output: &mut Output,
        export: &str,
        root: &str,
        runtime_module: &str,
        limits: PayloadLimits,
    ) -> fmt::Result {
        self.module_prelude(output, runtime_module, "createPayloadCodec")?;
        writeln!(output, "export const {export} = (() => {{")?;
        output.write_str("const $codec = $create({schema:{k:'ref',name:")?;
        output.quoted(root)?;
        writeln!(
            output,
            "}},bytes:{},nodes:{},depth:{}}}, $types);",
            limits.bytes, limits.nodes, limits.depth
        )?;
        writeln!(
            output,
            "return globalThis.Object.freeze({{encode:(value: {root}): globalThis.Uint8Array => $codec.encode(value), decode:(bytes: globalThis.Uint8Array): {root} => $codec.decode(bytes) as {root}}});\n}})();"
        )
    }

    fn module_prelude(
        &self,
        output: &mut Output,
        runtime_module: &str,
        factory: &str,
    ) -> fmt::Result {
        write!(
            output,
            "// Generated IC Wire client; no transport or execution.\nimport {{ schemaFormat as $format, {factory} as $create }} from "
        )?;
        output.quoted(runtime_module)?;
        output.write_str(";\nif ($format !== ")?;
        output.quoted(RUNTIME_SCHEMA_FORMAT)?;
        output.write_str(") throw new globalThis.Error('IC Wire runtime format mismatch');\n")?;
        self.render(output)?;
        output.write_str("const $types = globalThis.JSON.parse(")?;
        // A bounded temporary JSON string permits correct JS string escaping,
        // including __proto__ keys, without another schema interpretation path.
        let metadata = self.metadata_json().map_err(|_| fmt::Error)?;
        output.quoted(&metadata)?;
        output.write_str(");\n")
    }

    /// Export the admitted subset in the JSON registry grammar.
    ///
    /// This is data for a trusted metadata consumer, not executable JavaScript.
    /// Parse it as JSON: embedding it as an object literal changes the meaning
    /// of `__proto__` keys. Supplied names and use-site constraints are preserved.
    /// No runtime version or payload policy is implied by this registry alone.
    ///
    /// # Errors
    /// Returns Complexity before extending output beyond its byte allowance.
    pub fn metadata_json(&self) -> Result<String, GenerationError> {
        let mut output = Output {
            text: String::new(),
            remaining: self.output_bytes,
        };
        self.render_metadata(&mut output)
            .map_err(|_| GenerationError::Complexity)?;
        Ok(output.text)
    }

    fn render_metadata(&self, output: &mut Output) -> fmt::Result {
        output.write_char('{')?;
        for (index, (name, root)) in self.names.iter().zip(&self.roots).enumerate() {
            if index != 0 {
                output.write_char(',')?;
            }
            output.quoted(name)?;
            output.write_char(':')?;
            self.metadata_node(*root, output)?;
        }
        output.write_char('}')
    }

    fn metadata_node(&self, id: usize, output: &mut Output) -> fmt::Result {
        output.write_str("{\"k\":")?;
        match &self.nodes[id] {
            Node::Unit => output.quoted("unit")?,
            Node::Bool => output.quoted("bool")?,
            Node::Float { bits } => {
                output.quoted("float")?;
                write!(output, ",\"bits\":{bits}")?;
            }
            Node::Integer { bits, signed } => {
                output.quoted(if *signed { "i" } else { "u" })?;
                write!(output, ",\"bits\":{bits}")?;
            }
            Node::Text { max } => {
                output.quoted("text")?;
                output.json_bound("max", *max)?;
            }
            Node::Bytes { min, max } => {
                output.quoted("bytes")?;
                output.json_bound("min", *min)?;
                output.json_bound("max", *max)?;
            }
            Node::Packed { word, nonzero, max } => {
                output.quoted("packed")?;
                output.json_bound("max", *max)?;
                output.write_str(",\"word\":")?;
                output.quoted(word)?;
                if *nonzero {
                    output.write_str(",\"nonzero\":true")?;
                }
            }
            Node::List { item, max } => {
                output.quoted("list")?;
                output.json_bound("max", *max)?;
                output.write_str(",\"item\":")?;
                self.metadata_node(*item, output)?;
            }
            Node::Array { item, len } => {
                output.quoted("array")?;
                output.json_bound("max", Some(*len))?;
                output.write_str(",\"item\":")?;
                self.metadata_node(*item, output)?;
            }
            Node::Tuple(items) => {
                output.write_str("\"tuple\",\"items\":[")?;
                for (index, item) in items.iter().enumerate() {
                    if index != 0 {
                        output.write_char(',')?;
                    }
                    self.metadata_node(*item, output)?;
                }
                output.write_char(']')?;
            }
            Node::Result { ok, err } => {
                output.write_str("\"result\",\"ok\":")?;
                self.metadata_node(*ok, output)?;
                output.write_str(",\"err\":")?;
                self.metadata_node(*err, output)?;
            }
            Node::Option(item) | Node::Alias(item) => {
                output.quoted(if matches!(self.nodes[id], Node::Option(_)) {
                    "option"
                } else {
                    "newtype"
                })?;
                output.write_str(",\"item\":")?;
                self.metadata_node(*item, output)?;
            }
            Node::Ref(root) => {
                output.write_str("\"ref\",\"name\":")?;
                output.quoted(&self.names[*root])?;
            }
            Node::Record(fields) => {
                output.write_str("\"record\",\"fields\":[")?;
                for (index, (name, child)) in fields.iter().enumerate() {
                    if index != 0 {
                        output.write_char(',')?;
                    }
                    output.write_str("{\"name\":")?;
                    output.quoted(name)?;
                    output.write_str(",\"value\":")?;
                    self.metadata_node(*child, output)?;
                    output.write_char('}')?;
                }
                output.write_char(']')?;
            }
            Node::Enum(variants) => {
                output.write_str("\"enum\",\"variants\":[")?;
                for (index, (name, tag, child)) in variants.iter().enumerate() {
                    if index != 0 {
                        output.write_char(',')?;
                    }
                    output.write_str("{\"name\":")?;
                    output.quoted(name)?;
                    write!(output, ",\"id\":{tag},\"value\":")?;
                    self.metadata_node(*child, output)?;
                    output.write_char('}')?;
                }
                output.write_char(']')?;
            }
        }
        if let Some(annotation) = self.annotations.get(&id) {
            if let Some(bounds) = &annotation.bounds {
                output.scalar_bounds(bounds, true)?;
            }
            if let Some(check) = &annotation.check {
                output.write_str(",\"check\":")?;
                output.quoted(check)?;
            }
        }
        output.write_char('}')
    }

    /// Render deterministic TypeScript type aliases from admitted nodes.
    ///
    /// Numeric widths, enum IDs and field bounds are informational comments;
    /// TypeScript types cannot enforce these runtime constraints. This produces
    /// declarations only, with no browser codec or executable metadata.
    ///
    /// # Errors
    /// Returns Complexity before extending output beyond its byte allowance.
    pub fn declarations(&self) -> Result<String, GenerationError> {
        let mut output = Output {
            text: String::new(),
            remaining: self.output_bytes,
        };
        self.render(&mut output)
            .map_err(|_| GenerationError::Complexity)?;
        Ok(output.text)
    }

    fn render(&self, output: &mut Output) -> fmt::Result {
        for (name, root) in self.names.iter().zip(&self.roots) {
            write!(output, "export type {name} = ")?;
            self.render_node(*root, output)?;
            output.write_str(";\n")?;
        }
        Ok(())
    }

    fn render_node(&self, id: usize, output: &mut Output) -> fmt::Result {
        if let Some(bounds) = self
            .annotations
            .get(&id)
            .and_then(|annotation| annotation.bounds.as_ref())
        {
            output.scalar_bounds(bounds, false)?;
        }
        match &self.nodes[id] {
            Node::Unit => output.write_str("null"),
            Node::Bool => output.write_str("boolean"),
            Node::Packed { word, max, .. } => {
                output.bounds(None, *max)?;
                output.write_str(match *word {
                    "bool" => "globalThis.ReadonlyArray<boolean>",
                    "finite-f32" => "globalThis.Float32Array",
                    "finite-f64" => "globalThis.Float64Array",
                    "i8" => "globalThis.Int8Array",
                    "i16" => "globalThis.Int16Array",
                    "u16" => "globalThis.Uint16Array",
                    "i32" => "globalThis.Int32Array",
                    "u32" => "globalThis.Uint32Array",
                    "i64" => "globalThis.BigInt64Array",
                    "u64" => "globalThis.BigUint64Array",
                    _ => "globalThis.Uint8Array",
                })
            }
            Node::Float { bits } => {
                write!(output, "/* f{bits} */ number")
            }
            Node::Integer { bits, signed } => {
                write!(
                    output,
                    "/* {}{bits} */ {}",
                    if *signed { "i" } else { "u" },
                    if *bits > 32 { "bigint" } else { "number" }
                )
            }
            Node::Text { max } => {
                output.bounds(None, *max)?;
                output.write_str("string")
            }
            Node::Bytes { min, max } => {
                output.bounds(*min, *max)?;
                output.write_str("globalThis.Uint8Array")
            }
            Node::List { item, max } => {
                output.bounds(None, *max)?;
                output.write_str("globalThis.ReadonlyArray<")?;
                self.render_node(*item, output)?;
                output.write_char('>')
            }
            Node::Option(item) => {
                output.write_str("null | { readonly some: ")?;
                self.render_node(*item, output)?;
                output.write_str(" }")
            }
            Node::Array { item, len } => {
                output.bounds(None, Some(*len))?;
                output.write_str("globalThis.ReadonlyArray<")?;
                self.render_node(*item, output)?;
                output.write_char('>')
            }
            Node::Tuple(items) => {
                output.write_str("readonly [")?;
                for (index, item) in items.iter().enumerate() {
                    if index != 0 {
                        output.write_str(", ")?;
                    }
                    self.render_node(*item, output)?;
                }
                output.write_char(']')
            }
            Node::Result { ok, err } => {
                output.write_str("{ readonly ok: ")?;
                self.render_node(*ok, output)?;
                output.write_str(" } | { readonly err: ")?;
                self.render_node(*err, output)?;
                output.write_str(" }")
            }
            Node::Alias(item) => self.render_node(*item, output),
            Node::Ref(root) => output.write_str(&self.names[*root]),
            Node::Record(fields) => {
                output.write_char('{')?;
                for (name, child) in fields {
                    output.write_str(" readonly ")?;
                    output.quoted(name)?;
                    output.write_str(": ")?;
                    self.render_node(*child, output)?;
                    output.write_char(';')?;
                }
                output.write_str(" }")
            }
            Node::Enum(variants) => {
                for (index, (name, tag, child)) in variants.iter().enumerate() {
                    if index != 0 {
                        output.write_str(" | ")?;
                    }
                    write!(output, "/* id {tag} */ {{ readonly tag: ")?;
                    output.quoted(name)?;
                    output.write_str("; readonly value: ")?;
                    self.render_node(*child, output)?;
                    output.write_str(" }")?;
                }
                Ok(())
            }
        }
    }
}

impl Output {
    fn json_bound(&mut self, name: &str, value: Option<u64>) -> fmt::Result {
        if let Some(value) = value {
            write!(self, ",\"{name}\":{value}")?;
        }
        Ok(())
    }
}