Skip to main content

rust_anything/
codegen_tswire.rs

1//! The binary wire for TypeScript/JavaScript: generated JS encoders write arguments into a
2//! buffer registered once with the Rust module, the Rust side reads them in place, and the
3//! result comes back the same way. No JSON text, no per-property napi calls.
4//!
5//! When an argument does not have the declared shape at run time, that call falls back to the
6//! JSON bridge, so behavior on unexpected inputs stays exactly as before.
7
8use std::fmt::Write as _;
9
10use crate::bridge::Manifest;
11use crate::codegen::{PortApi, PortFn, Wire, wire};
12use crate::ts::exports::{ExportedFn, LocalType};
13use crate::ts::shape::{self, Shape};
14use crate::wire::{Ty, rust_read_args, rust_write, schema_expr};
15
16/// The wire type of a TS shape. Shapes the wire does not model travel as tagged values.
17fn shape_ty(s: &Shape, types: &[LocalType], depth: usize) -> Ty {
18    if depth > 6 {
19        return Ty::Dyn;
20    }
21    let str_like = |s: &Shape| matches!(s, Shape::Str | Shape::LitStr(_));
22    let num_like = |s: &Shape| matches!(s, Shape::Num | Shape::Int | Shape::LitNum(_));
23    let bool_like = |s: &Shape| matches!(s, Shape::Bool | Shape::LitBool(_));
24    match s {
25        Shape::Str | Shape::LitStr(_) => Ty::Str16,
26        Shape::Num | Shape::Int | Shape::LitNum(_) => Ty::Num,
27        Shape::Bool | Shape::LitBool(_) => Ty::Bool,
28        Shape::Null | Shape::Undefined | Shape::Any | Shape::Tuple(_) => Ty::Dyn,
29        Shape::Array(item) => Ty::List {
30            item: Box::new(shape_ty(item, types, depth + 1)),
31            native: "ts".into(),
32            array: false,
33        },
34        Shape::Object(props, None) => Ty::Obj(
35            props
36                .iter()
37                .map(|(name, optional, s)| {
38                    let t = shape_ty(s, types, depth + 1);
39                    let t = match t {
40                        Ty::OptJs {
41                            inner, nullable, ..
42                        } if *optional => Ty::OptJs {
43                            inner,
44                            nullable,
45                            undefinable: true,
46                        },
47                        t if *optional && t != Ty::Dyn => Ty::OptJs {
48                            inner: Box::new(t),
49                            nullable: false,
50                            undefinable: true,
51                        },
52                        t => t,
53                    };
54                    (name.clone(), t)
55                })
56                .collect(),
57        ),
58        Shape::Object(props, Some(value)) if props.is_empty() => {
59            Ty::Map16(Box::new(shape_ty(value, types, depth + 1)))
60        }
61        Shape::Object(..) => Ty::Dyn,
62        Shape::Union(members) => {
63            let nullable = members.iter().any(|m| matches!(m, Shape::Null));
64            let undefinable = members.iter().any(|m| matches!(m, Shape::Undefined));
65            let rest: Vec<&Shape> = members
66                .iter()
67                .filter(|m| !matches!(m, Shape::Null | Shape::Undefined))
68                .collect();
69            let base = if rest.is_empty() {
70                Ty::Dyn
71            } else if rest.iter().all(|m| str_like(m)) {
72                Ty::Str16
73            } else if rest.iter().all(|m| num_like(m)) {
74                Ty::Num
75            } else if rest.iter().all(|m| bool_like(m)) {
76                Ty::Bool
77            } else if rest.len() == 1 {
78                shape_ty(rest[0], types, depth + 1)
79            } else {
80                Ty::Dyn
81            };
82            if (nullable || undefinable) && base != Ty::Dyn {
83                Ty::OptJs {
84                    inner: Box::new(base),
85                    nullable,
86                    undefinable,
87                }
88            } else {
89                base
90            }
91        }
92        Shape::Ref(name, args) => {
93            let resolved = shape::resolve(name, args, types);
94            if matches!(resolved, Shape::Ref(..)) {
95                Ty::Dyn
96            } else {
97                shape_ty(&resolved, types, depth + 1)
98            }
99        }
100    }
101}
102
103fn js_key(k: &str) -> String {
104    serde_json::to_string(k).unwrap_or_else(|_| "\"\"".into())
105}
106
107/// JS statements writing `x` as `t`; `return false` when `x` does not have the shape.
108fn js_enc(x: &str, t: &Ty, d: usize) -> String {
109    match t {
110        Ty::Num => format!("if (typeof {x} !== 'number') return false\nwF64({x})\n"),
111        Ty::Bool => format!("if (typeof {x} !== 'boolean') return false\nwU8({x} ? 1 : 0)\n"),
112        Ty::Str16 => format!("if (typeof {x} !== 'string') return false\nwStr({x})\n"),
113        Ty::Dyn => format!("if (!wDyn({x})) return false\n"),
114        Ty::OptJs {
115            inner,
116            nullable,
117            undefinable,
118        } => format!(
119            "if ({x} === undefined) {{\n{}wU8(0)\n}} else if ({x} === null) {{\n{}wU8(2)\n}} else {{\nwU8(1)\n{}}}\n",
120            if *undefinable { "" } else { "return false\n" },
121            if *nullable { "" } else { "return false\n" },
122            js_enc(x, inner, d)
123        ),
124        Ty::List { item, .. } => format!(
125            "if (!Array.isArray({x})) return false\nwU8(1)\nwU32({x}.length)\nfor (let i{d} = 0; i{d} < {x}.length; i{d}++) {{\nconst v{d} = {x}[i{d}]\n{}}}\n",
126            js_enc(&format!("v{d}"), item, d + 1)
127        ),
128        Ty::Map16(value) => format!(
129            "if ({x} === null || typeof {x} !== 'object' || Array.isArray({x})) return false\n{{\nconst k{d} = Object.keys({x})\nwU8(1)\nwU32(k{d}.length)\nfor (const key{d} of k{d}) {{\nwStr(key{d})\nconst v{d} = {x}[key{d}]\n{}}}\n}}\n",
130            js_enc(&format!("v{d}"), value, d + 1)
131        ),
132        Ty::Obj(fields) => {
133            // Keys in the object's own order (a port may pass the object through); a key the
134            // type does not list sends the call through JSON.
135            let required = fields
136                .iter()
137                .filter(|(_, ft)| {
138                    !(matches!(
139                        ft,
140                        Ty::OptJs {
141                            undefinable: true,
142                            ..
143                        }
144                    ) || *ft == Ty::Dyn)
145                })
146                .count();
147            let mut cases = String::new();
148            for (i, (key, ft)) in fields.iter().enumerate() {
149                let optional = matches!(
150                    ft,
151                    Ty::OptJs {
152                        undefinable: true,
153                        ..
154                    }
155                ) || *ft == Ty::Dyn;
156                let _ = write!(
157                    cases,
158                    "case {}: {{\nwU8({i})\n{}const f{d} = {x}[k{d}]\n{}break\n}}\n",
159                    js_key(key),
160                    if optional {
161                        String::new()
162                    } else {
163                        format!("r{d}++\n")
164                    },
165                    js_enc(&format!("f{d}"), ft, d + 1)
166                );
167            }
168            format!(
169                "if ({x} === null || typeof {x} !== 'object' || Array.isArray({x})) return false\n{{\n\
170                 const at{d} = at\nwU8(0)\nlet n{d} = 0, r{d} = 0\nfor (const k{d} in {x}) {{\nswitch (k{d}) {{\n{cases}default: return false\n}}\n\
171                 if (++n{d} > 255) return false\n}}\nif (r{d} !== {required}) return false\niv.setUint8(at{d}, n{d})\n}}\n"
172            )
173        }
174        _ => "return false\n".into(),
175    }
176}
177
178/// JS statements decoding a value of `t` into the variable `target`.
179fn js_dec(target: &str, t: &Ty, d: usize) -> String {
180    match t {
181        Ty::Num => format!("{target} = rF64()\n"),
182        Ty::Bool => format!("{target} = rU8() === 1\n"),
183        Ty::Str16 => format!("{target} = rStr()\n"),
184        Ty::Dyn => format!("{target} = rDyn()\n"),
185        Ty::OptJs { inner, .. } => format!(
186            "{{\nconst g{d} = rU8()\nif (g{d} === 0) {target} = undefined\nelse if (g{d} === 2) {target} = null\nelse {{\n{}}}\n}}\n",
187            js_dec(target, inner, d + 1)
188        ),
189        Ty::List { item, .. } => format!(
190            "if (rU8() === 0) {target} = null\nelse {{\nconst n{d} = rU32()\nconst a{d} = new Array(n{d})\nfor (let i{d} = 0; i{d} < n{d}; i{d}++) {{\nlet v{d}\n{}a{d}[i{d}] = v{d}\n}}\n{target} = a{d}\n}}\n",
191            js_dec(&format!("v{d}"), item, d + 1)
192        ),
193        Ty::Map16(value) => format!(
194            "if (rU8() === 0) {target} = null\nelse {{\nconst n{d} = rU32()\nconst o{d} = {{}}\nfor (let i{d} = 0; i{d} < n{d}; i{d}++) {{\nconst k{d} = rStr()\nlet v{d}\n{}o{d}[k{d}] = v{d}\n}}\n{target} = o{d}\n}}\n",
195            js_dec(&format!("v{d}"), value, d + 1)
196        ),
197        Ty::Obj(fields) => {
198            let mut cases = String::new();
199            for (i, (key, ft)) in fields.iter().enumerate() {
200                let _ = write!(
201                    cases,
202                    "case {i}: {{\nlet v{d}\n{}o{d}[{}] = v{d}\nbreak\n}}\n",
203                    js_dec(&format!("v{d}"), ft, d + 1),
204                    js_key(key)
205                );
206            }
207            format!(
208                "{{\nconst o{d} = {{}}\nconst n{d} = rU8()\nfor (let j{d} = 0; j{d} < n{d}; j{d}++) {{\nswitch (rU8()) {{\n{cases}default: {{\nconst k{d} = rStr()\no{d}[k{d}] = rDyn()\n}}\n}}\n}}\n{target} = o{d}\n}}\n"
209            )
210        }
211        _ => format!("{target} = undefined\n"),
212    }
213}
214
215/// The JS runtime: registered buffers, writers, readers, tagged values.
216const WIRE_NAPI_CJS: &str = r#"
217// The binary wire (see rust-anything's `wire.rs`): arguments are written into `wIn`, results read
218// from `wOut`; both are registered with the native module once.
219let wIn = new Uint8Array(1 << 16), wOut = new Uint8Array(1 << 16)
220let iv = new DataView(wIn.buffer), ov = new DataView(wOut.buffer), at = 0, p = 0
221native.rustAnythingWireInit(wIn, wOut)
222const regrow = () => native.rustAnythingWireInit(wIn, wOut)
223// Runs a wire function; a result larger than `wOut` is fetched once `wOut` has grown.
224const wireCall = fn => {
225  const n = fn(at)
226  if (Number.isNaN(n)) return false
227  if (n < 0) {
228    wOut = new Uint8Array(Math.max(wOut.length * 2, -n))
229    ov = new DataView(wOut.buffer)
230    native.rustAnythingWireInit(wIn, wOut)
231    native.rustAnythingWireFlush()
232  }
233  p = 0
234  return true
235}
236"#;
237
238const WIRE_WASM_CJS: &str = r#"
239// The binary wire (see rust-anything's `wire.rs`): arguments are written into `wIn` and copied into
240// wasm memory in one step; results are read where the Rust side left them.
241let wIn = new Uint8Array(1 << 16), iv = new DataView(wIn.buffer), at = 0, p = 0
242const mem = native.rustAnythingWireMemory()
243let wOut = new Uint8Array(mem.buffer), ov = new DataView(mem.buffer)
244const regrow = () => {}
245// Growing wasm memory replaces its buffer: views are made again when that happened.
246const views = () => {
247  if (wOut.buffer !== mem.buffer) {
248    wOut = new Uint8Array(mem.buffer)
249    ov = new DataView(mem.buffer)
250  }
251}
252const wireCall = fn => {
253  const ptr = native.rustAnythingWireIn(at)
254  views()
255  wOut.set(wIn.subarray(0, at), ptr)
256  if (fn(at) === 0xFFFFFFFF) return false
257  views()
258  p = native.rustAnythingWireOut()
259  return true
260}
261"#;
262
263const WIRE_CJS: &str = r#"
264const need = n => {
265  if (at + n <= wIn.length) return
266  const grown = new Uint8Array(Math.max(wIn.length * 2, at + n))
267  grown.set(wIn)
268  wIn = grown
269  iv = new DataView(wIn.buffer)
270  regrow()
271}
272const wU8 = v => { need(1); iv.setUint8(at++, v) }
273const wU32 = v => { need(4); iv.setUint32(at, v, true); at += 4 }
274const wF64 = v => { need(8); iv.setFloat64(at, v, true); at += 8 }
275const wUnits = s => {
276  need(4 + 2 * s.length)
277  iv.setUint32(at, s.length, true)
278  at += 4
279  for (let i = 0; i < s.length; i++) { iv.setUint16(at, s.charCodeAt(i), true); at += 2 }
280}
281const wStr = s => { wU8(4); wUnits(s) }
282const wDyn = v => {
283  switch (typeof v) {
284    case 'undefined': wU8(0); return true
285    case 'boolean': wU8(v ? 3 : 2); return true
286    case 'number': wU8(4); wF64(v); return true
287    case 'string': wU8(5); wUnits(v); return true
288    case 'object':
289      if (v === null) { wU8(1); return true }
290      if (Array.isArray(v)) {
291        wU8(6); wU32(v.length)
292        for (let i = 0; i < v.length; i++) if (!wDyn(v[i])) return false
293        return true
294      }
295      if (Object.getPrototypeOf(v) !== Object.prototype && Object.getPrototypeOf(v) !== null) return false
296      {
297        const keys = Object.keys(v)
298        wU8(7); wU32(keys.length)
299        for (const k of keys) { wUnits(k); if (!wDyn(v[k])) return false }
300        return true
301      }
302  }
303  return false
304}
305const rU8 = () => ov.getUint8(p++)
306const rU32 = () => { const v = ov.getUint32(p, true); p += 4; return v }
307const rF64 = () => { const v = ov.getFloat64(p, true); p += 8; return v }
308// ignoreBOM: a leading U+FEFF is part of the string, not a byte-order mark.
309const utf16 = new TextDecoder('utf-16le', { ignoreBOM: true })
310const rUnits = (wellFormed) => {
311  const n = rU32()
312  let s
313  if (n > 24 && wellFormed) s = utf16.decode(wOut.subarray(p, p + 2 * n))
314  else {
315    s = ''
316    for (let i = 0; i < n; i++) s += String.fromCharCode(ov.getUint16(p + 2 * i, true))
317  }
318  p += 2 * n
319  return s
320}
321// Tag 1: a string from Rust (well-formed); 4: raw code units, lone surrogates included.
322const rStr = () => rUnits(rU8() === 1)
323const rDyn = () => {
324  switch (rU8()) {
325    case 0: return undefined
326    case 1: return null
327    case 2: return false
328    case 3: return true
329    case 4: return rF64()
330    case 5: return rUnits(false)
331    case 6: { const n = rU32(); const a = new Array(n); for (let i = 0; i < n; i++) a[i] = rDyn(); return a }
332    case 7: { const n = rU32(); const o = {}; for (let i = 0; i < n; i++) { const k = rUnits(false); o[k] = rDyn() } return o }
333  }
334}
335"#;
336
337/// The napi side: buffer registration and the call helper.
338const WIRE_NAPI_RS: &str = r#"
339// ---- the binary wire ------------------------------------------------------------------------
340
341thread_local! {
342    static WIRE: std::cell::RefCell<Option<(napi::bindgen_prelude::Uint8Array, napi::bindgen_prelude::Uint8Array)>> =
343        const { std::cell::RefCell::new(None) };
344    static PENDING: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
345}
346
347/// Registers the argument and result buffers `index.cjs` writes to and reads from.
348#[napi(js_name = "rustAnythingWireInit")]
349pub fn rust_anything_wire_init(input: napi::bindgen_prelude::Uint8Array, output: napi::bindgen_prelude::Uint8Array) {
350    WIRE.with(|w| *w.borrow_mut() = Some((input, output)));
351}
352
353/// Copies a result that did not fit into the (now larger) result buffer.
354#[napi(js_name = "rustAnythingWireFlush")]
355pub fn rust_anything_wire_flush() -> f64 {
356    let bytes = PENDING.with(|p| std::mem::take(&mut *p.borrow_mut()));
357    WIRE.with(|w| {
358        let mut w = w.borrow_mut();
359        let Some((_, output)) = w.as_mut() else {
360            return -1.0;
361        };
362        // SAFETY: the call is synchronous; JS does not touch `output` until it returns.
363        let out = unsafe { output.as_mut() };
364        let n = bytes.len().min(out.len());
365        out[..n].copy_from_slice(&bytes[..n]);
366        n as f64
367    })
368}
369
370/// Reads `len` argument bytes, runs `f`, and writes its result; a negative return is the size
371/// of a result that did not fit, kept for `rustAnythingWireFlush`.
372fn wire_io(len: u32, f: impl FnOnce(&mut wire::Reader, &mut wire::Writer) -> Result<(), String>) -> napi::Result<f64> {
373    WIRE.with(|cell| {
374        let mut guard = cell.borrow_mut();
375        let Some((input, output)) = guard.as_mut() else {
376            return Err(napi::Error::from_reason("rust-anything: the wire buffers are not registered"));
377        };
378        let len = (len as usize).min(input.len());
379        let mut w = wire::Writer::default();
380        match run(|| f(&mut wire::Reader::new(&input[..len]), &mut w)) {
381            // A result of another shape than the TS type: JS runs the call through JSON.
382            Err(e) if e.reason.starts_with(wire::MISMATCH) => return Ok(f64::NAN),
383            other => other?,
384        }
385        // SAFETY: the call is synchronous; JS does not touch `output` until it returns.
386        let out = unsafe { output.as_mut() };
387        let n = w.0.len();
388        if n > out.len() {
389            PENDING.with(|p| *p.borrow_mut() = w.0);
390            return Ok(-(n as f64));
391        }
392        out[..n].copy_from_slice(&w.0);
393        Ok(n as f64)
394    })
395}
396"#;
397
398/// The wasm side: buffers in wasm memory, and the call helper.
399const WIRE_WASM_RS: &str = r#"
400// ---- the binary wire ------------------------------------------------------------------------
401
402thread_local! {
403    static WIRE_IN: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
404    static WIRE_OUT: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
405}
406
407/// This module's memory, where `index.cjs` reads and writes the wire buffers.
408#[wasm_bindgen(js_name = "rustAnythingWireMemory")]
409pub fn rust_anything_wire_memory() -> JsValue {
410    wasm_bindgen::memory()
411}
412
413/// The address of an argument buffer of `len` bytes.
414#[wasm_bindgen(js_name = "rustAnythingWireIn")]
415pub fn rust_anything_wire_in(len: u32) -> u32 {
416    WIRE_IN.with(|b| {
417        let mut b = b.borrow_mut();
418        b.resize(len as usize, 0);
419        b.as_mut_ptr() as usize as u32
420    })
421}
422
423/// The address of the last result.
424#[wasm_bindgen(js_name = "rustAnythingWireOut")]
425pub fn rust_anything_wire_out() -> u32 {
426    WIRE_OUT.with(|b| b.borrow().as_ptr() as usize as u32)
427}
428
429/// Reads `len` argument bytes, runs `f`, and keeps its result for `rustAnythingWireOut`.
430fn wire_io(len: u32, f: impl FnOnce(&mut wire::Reader, &mut wire::Writer) -> Result<(), String>) -> Result<u32, JsError> {
431    let input = WIRE_IN.with(|b| std::mem::take(&mut *b.borrow_mut()));
432    let mut w = wire::Writer::default();
433    let result = f(&mut wire::Reader::new(&input[..(len as usize).min(input.len())]), &mut w);
434    WIRE_IN.with(|b| *b.borrow_mut() = input);
435    match result {
436        // A result of another shape than the TS type: JS runs the call through JSON.
437        Err(e) if e.starts_with(wire::MISMATCH) => return Ok(u32::MAX),
438        other => other.map_err(|e| JsError::new(&e))?,
439    }
440    let n = w.0.len();
441    WIRE_OUT.with(|b| *b.borrow_mut() = w.0);
442    Ok(u32::try_from(n).unwrap_or(u32::MAX))
443}
444"#;
445
446/// One wire function: its export, parameter and result types, and the generated code.
447struct WireFn<'m> {
448    export: &'m ExportedFn,
449    port: &'m PortFn,
450    params: Vec<Ty>,
451    result: Option<Ty>,
452    rust: String,
453}
454
455fn types_for(m: &Manifest, file: &str) -> Vec<LocalType> {
456    let text = std::fs::read_to_string(m.root.join(file)).unwrap_or_default();
457    crate::bridge::types_in_scope(&m.root, file, &text)
458}
459
460/// The functions that cross the wire: synchronous, with a structured parameter or result, and
461/// port types that fit the wire types.
462fn wire_fns<'m>(m: &'m Manifest, api: &'m PortApi) -> Vec<WireFn<'m>> {
463    let mut out = Vec::new();
464    let mut scopes: std::collections::HashMap<&str, Vec<LocalType>> =
465        std::collections::HashMap::new();
466    for f in &api.functions {
467        if f.is_async {
468            continue;
469        }
470        let structured =
471            f.params.iter().any(|(_, t)| wire(t) == Wire::Json) || wire(&f.ret) == Wire::Json;
472        if !structured {
473            continue;
474        }
475        let Some(e) = m.exports.iter().find(|e| e.name == f.js_name) else {
476            continue;
477        };
478        if e.params.len() != f.params.len() || e.params.iter().any(|p| p.rest) {
479            continue;
480        }
481        let types = scopes
482            .entry(e.file.as_str())
483            .or_insert_with(|| types_for(m, &e.file));
484        let params: Vec<Ty> = e
485            .params
486            .iter()
487            .map(|p| {
488                let t = shape_ty(&shape::parse(&p.ts_type), types, 0);
489                if p.optional || p.default.is_some() {
490                    match t {
491                        Ty::OptJs {
492                            inner, nullable, ..
493                        } => Ty::OptJs {
494                            inner,
495                            nullable,
496                            undefinable: true,
497                        },
498                        Ty::Dyn => Ty::Dyn,
499                        t => Ty::OptJs {
500                            inner: Box::new(t),
501                            nullable: false,
502                            undefinable: true,
503                        },
504                    }
505                } else {
506                    t
507                }
508            })
509            .collect();
510        let result = (f.ret != "()").then(|| shape_ty(&shape::parse(&e.returns), types, 0));
511        let named: Vec<(String, Ty)> = f
512            .params
513            .iter()
514            .map(|(n, _)| n.clone())
515            .zip(params.iter().cloned())
516            .collect();
517        let mut statics = String::new();
518        let prefix = format!("S_{}", crate::bridge::snake_case(&f.js_name).to_uppercase());
519        let Some(reads) = rust_read_args(&named, &f.params, &prefix, &mut statics) else {
520            continue;
521        };
522        let args: Vec<&str> = f.params.iter().map(|(n, _)| n.as_str()).collect();
523        let call = format!("port::{}({})", f.rust_name, args.join(", "));
524        let call = if f.fallible { format!("{call}?") } else { call };
525        let write = match &result {
526            None => format!("        let () = {call};\n"),
527            Some(t) => {
528                let schema = format!("{prefix}_OUT");
529                let Some(w) = rust_write(t, &f.ret, "out", &schema, 0) else {
530                    continue;
531                };
532                if w.contains(&schema) {
533                    let _ = writeln!(
534                        statics,
535                        "static {schema}: wire::Schema = {};",
536                        schema_expr(t)
537                    );
538                }
539                format!("        let out = &{call};\n        {w}\n")
540            }
541        };
542        let (attr, ret) = if m.kind == crate::bridge::Kind::Wasm {
543            ("wasm_bindgen", "Result<u32, JsError>")
544        } else {
545            ("napi", "napi::Result<f64>")
546        };
547        let rust = format!(
548            "\n{statics}\n/// `{js}` over the binary wire.\n#[{attr}(js_name = \"{js}Wire\")]\npub fn {name}_wire(len: u32) -> {ret} {{\n    \
549             wire_io(len, |r, w| {{\n{reads}{write}        Ok(())\n    }})\n}}\n",
550            js = f.js_name,
551            name = f.rust_name.trim_start_matches("r#"),
552        );
553        out.push(WireFn {
554            export: e,
555            port: f,
556            params,
557            result,
558            rust,
559        });
560    }
561    out
562}
563
564/// Rust code for `lib.rs` (napi): the wire runtime and one function per wire export; empty
565/// when no function uses the wire.
566pub fn napi_rs(m: &Manifest, api: &PortApi) -> String {
567    let fns = wire_fns(m, api);
568    if fns.is_empty() {
569        return String::new();
570    }
571    let mut out = String::from(if m.kind == crate::bridge::Kind::Wasm {
572        WIRE_WASM_RS
573    } else {
574        WIRE_NAPI_RS
575    });
576    for f in fns {
577        out.push_str(&f.rust);
578    }
579    out
580}
581
582/// Whether the crate has wire functions (and needs `src/wire.rs`).
583pub fn uses_wire(m: &Manifest, api: &PortApi) -> bool {
584    matches!(
585        m.kind,
586        crate::bridge::Kind::Napi | crate::bridge::Kind::Wasm
587    ) && !wire_fns(m, api).is_empty()
588}
589
590/// JS for `index.cjs`, after the exports are set: the runtime, and each wire function in front
591/// of its JSON version.
592pub fn index_cjs(m: &Manifest, api: &PortApi) -> String {
593    let fns = wire_fns(m, api);
594    if fns.is_empty() {
595        return String::new();
596    }
597    let mut out = String::from(if m.kind == crate::bridge::Kind::Wasm {
598        WIRE_WASM_CJS
599    } else {
600        WIRE_NAPI_CJS
601    });
602    out.push_str(WIRE_CJS);
603    for f in &fns {
604        let n = f.params.len();
605        let names: Vec<String> = (0..n).map(|i| format!("a{i}")).collect();
606        let mut enc = String::new();
607        for (i, t) in f.params.iter().enumerate() {
608            enc.push_str(&js_enc(&format!("a{i}"), t, 0));
609        }
610        let dec = f
611            .result
612            .as_ref()
613            .map_or_else(String::new, |t| js_dec("t", t, 0));
614        let js = &f.port.js_name;
615        let _ = write!(
616            out,
617            "\n// `{js}`: binary wire; the JSON version handles inputs of other shapes.\n{{\n\
618             const json = module.exports.{js}\nconst call = native.{js}Wire\n\
619             const encode = ({args}) => {{\nat = 0\n{enc}return true\n}}\n\
620             const decode = () => {{\nlet t\n{dec}return t\n}}\n\
621             module.exports.{js} = function {js} (...a) {{\n  if (a.length <= {n} && encode({spread}) && wireCall(call)) {{\n    return decode()\n  }}\n  return json(...a)\n}}\n}}\n",
622            args = names.join(", "),
623            spread = (0..n)
624                .map(|i| format!("a[{i}]"))
625                .collect::<Vec<_>>()
626                .join(", "),
627        );
628        let _ = f.export;
629    }
630    out
631}
632
633#[cfg(test)]
634mod tests {
635    use super::*;
636
637    #[test]
638    fn maps_ts_shapes() {
639        let none: Vec<LocalType> = Vec::new();
640        let t = shape_ty(
641            &shape::parse("{ start: number; end: number; label?: string | null }"),
642            &none,
643            0,
644        );
645        let Ty::Obj(fields) = &t else { panic!("{t:?}") };
646        assert_eq!(fields[0], ("start".into(), Ty::Num));
647        assert_eq!(
648            fields[2].1,
649            Ty::OptJs {
650                inner: Box::new(Ty::Str16),
651                nullable: true,
652                undefinable: true
653            }
654        );
655        assert_eq!(shape_ty(&shape::parse("'a' | 'b'"), &none, 0), Ty::Str16);
656        assert_eq!(shape_ty(&shape::parse("unknown"), &none, 0), Ty::Dyn);
657        assert!(matches!(
658            shape_ty(&shape::parse("Record<string, number>"), &none, 0),
659            Ty::Map16(_)
660        ));
661    }
662}