Skip to main content

bynk_emit/emitter/
client.rs

1//! I4 (#1970): the typed TypeScript client for a context's foreign callers,
2//! `workers/<context>/bynk-client.ts` (`design/archive/retired-tracks.md`, interop track D3).
3//!
4//! A Bynk caller of another context gets a typed call: the compiler builds the
5//! path, stamps the contract hash, encodes the arguments and decodes the
6//! result. This module gives a Worker that is not Bynk the same, as a module it
7//! imports: one typed function per `on call` service a declared foreign caller
8//! may call, the boundary types as TypeScript types, and the contract hashes
9//! and wire version embedded as literals.
10//!
11//! # One codec, one caller
12//!
13//! Nothing here is a second implementation of the boundary. The codecs are the
14//! ones a Bynk *consumer* generates for a callee's types
15//! (`serialisation::emit_helpers_for_owner_qualified` under a non-empty
16//! qualifier, which inlines a transparent refinement and casts an opaque
17//! one), each call goes through the runtime's own `callService`, and the
18//! encode and decode references at each call site come from the same
19//! `serialisation::serialise_expr_via` / `serialisation::deserialise_ref_via`
20//! the Bynk call site uses (`emit.rs`'s cross-context call lowering). The
21//! runtime half ships as `@bynk/wire-client`, bundled from the runtime's own
22//! modules and versioned with the wire format (§11 Q7).
23//!
24//! # Signing as a foreign caller
25//!
26//! I3's hand-off gives the foreign Worker its secret under the name a Bynk
27//! caller holds its edge key by, `BYNK_CALL_TO_<CALLEE>`, and the callee's
28//! verifier checks a declared foreign caller's name against its own secret
29//! (`__FOREIGN_CALLERS`). So `callService` with the actor's name as the caller
30//! signs exactly the request the callee admits. The client asks for the
31//! foreign Worker's `env` (typed to require the secret) and its Service Binding.
32//!
33//! # When it is emitted
34//!
35//! Only for a context that declares at least one `Foreign` actor some `on call`
36//! handler admits, and only with the services such an actor may call. A
37//! context with no foreign caller has no one the client could sign as: an
38//! undeclared caller holds no secret (§8 D2, §11 Q5).
39
40use std::collections::{BTreeMap, BTreeSet, HashMap};
41use std::sync::Arc;
42
43use bynk_check::project_model::TypeDecl;
44use bynk_check::resolver::{CrossContextService, cross_context_service_for};
45use bynk_check::symbols::UnitTable;
46use bynk_check::wire::{TypeBody, TypeRef};
47use bynk_ts::{TsDecl, TsExpr, TsObjectEntry, TsParam, TsProgram, TsStmt, TsType, TsTypeMember};
48
49use super::runtime_use::RuntimeUse;
50use super::serialisation;
51use super::ts_ident;
52use crate::ts_build::{ident, str_lit};
53
54/// The file, beside the Worker's `bynk-contracts.json`. Hyphenated like the
55/// other compiler-written files there, so no Bynk unit can emit a module of
56/// the same name.
57pub const CLIENT_FILE: &str = "bynk-client.ts";
58
59/// The runtime package the client imports (§11 Q7).
60pub const CLIENT_PACKAGE: &str = "@bynk/wire-client";
61
62/// The type names the client's own surface declares. A boundary type of the
63/// same name is renamed in the client (`Client` → `Client_`), never the
64/// surface, so the surface reads the same for every context.
65const SURFACE_TYPES: &[&str] = &[
66    "Admits",
67    "Client",
68    "ConnectOptions",
69    "Env",
70    "ForeignCaller",
71    "Services",
72];
73
74/// The names `@bynk/wire-client` exports that generated code may use, each
75/// with the import specifier that brings it in. The import line carries those
76/// the module actually names ([`bynk_ts::unbound_names`]), so a caller whose
77/// `tsconfig` sets `noUnusedLocals` builds it too.
78const PACKAGE_NAMES: &[(&str, &str)] = &[
79    ("Err", "Err"),
80    ("None", "None"),
81    ("Ok", "Ok"),
82    ("Option", "type Option"),
83    ("Result", "type Result"),
84    ("Some", "Some"),
85    ("ValidationError", "type ValidationError"),
86    ("__BoundaryError", "type __BoundaryError"),
87    ("__BynkKeyMap", "__BynkKeyMap"),
88    ("__BynkKeySet", "__BynkKeySet"),
89    ("__JsonValue", "type __JsonValue"),
90    ("__ServiceBinding", "type __ServiceBinding"),
91    ("__WireVersion", "type WireVersion as __WireVersion"),
92    ("__boundaryError", "__boundaryError"),
93    ("__bynkBytesFromBase64", "__bynkBytesFromBase64"),
94    ("__bynkBytesToBase64", "__bynkBytesToBase64"),
95    ("__bynkDecimalParseWire", "__bynkDecimalParseWire"),
96    ("__bynkDecimalToString", "__bynkDecimalToString"),
97    ("__callService", "__callService"),
98];
99
100/// One service the client exposes.
101struct ClientService {
102    svc: CrossContextService,
103    /// The foreign actors its handler admits, sorted.
104    admits: Vec<String>,
105    hash: String,
106}
107
108/// The contract hash each declared foreign caller may call each service at:
109/// actor → service → hash. What a foreign caller's generated client embeds,
110/// so what `bynk deploy` compares a pin against. Empty when the context
111/// admits no foreign caller.
112pub fn foreign_contracts(
113    table: &UnitTable,
114    own_types: &HashMap<String, Arc<TypeDecl>>,
115) -> BTreeMap<String, BTreeMap<String, String>> {
116    let mut out: BTreeMap<String, BTreeMap<String, String>> = BTreeMap::new();
117    for s in client_services(table, own_types) {
118        for actor in &s.admits {
119            out.entry(actor.clone())
120                .or_default()
121                .insert(s.svc.name.clone(), s.hash.clone());
122        }
123    }
124    out
125}
126
127/// The `on call` services a foreign caller may call, sorted by name.
128fn client_services(
129    table: &UnitTable,
130    own_types: &HashMap<String, Arc<TypeDecl>>,
131) -> Vec<ClientService> {
132    let mut names: Vec<&String> = table.services.keys().collect();
133    names.sort();
134    let mut out = Vec::new();
135    for name in names {
136        let sdecl = &table.services[name];
137        let Some(svc) = cross_context_service_for(name, sdecl) else {
138            continue;
139        };
140        let mut admits: Vec<String> = sdecl
141            .handlers
142            .iter()
143            .find_map(|h| bynk_check::actors::call_admission_for(h, &table.actors))
144            .map(|a| a.foreign.into_iter().map(|f| f.actor).collect())
145            .unwrap_or_default();
146        if admits.is_empty() {
147            continue;
148        }
149        admits.sort();
150        admits.dedup();
151        let hash = bynk_check::contract::service_contract_hash(&svc, own_types);
152        out.push(ClientService { svc, admits, hash });
153    }
154    out
155}
156
157/// What [`surface_closure`] computes: the codec closure of a set of boundary
158/// roots with every type that would clash with a generated surface (or is filed
159/// under a qualified key) renamed to the plain name a reader sees.
160pub(super) struct SurfaceClosure {
161    /// The type table with the renames applied.
162    pub types: HashMap<String, Arc<TypeDecl>>,
163    /// Old name to new name, for the types that were renamed.
164    pub subst: HashMap<String, String>,
165    /// The named types the roots reach, renamed.
166    pub names: Vec<String>,
167    /// The generic instantiations the roots reach, renamed.
168    pub insts: Vec<serialisation::GenericInst>,
169    /// The generic declarations among them, renamed.
170    pub generic_bases: BTreeSet<String>,
171}
172
173/// The codec closure of `roots` over `own_types`, with a boundary type named
174/// like one of the generated `surface` names renamed (`Client` to `Client_`),
175/// never the surface, so the surface reads the same for every project. The
176/// foreign-caller client and the HTTP client (`bynk client`) share it.
177pub(super) fn surface_closure(
178    roots: &[TypeRef],
179    own_types: &HashMap<String, Arc<TypeDecl>>,
180    surface: &[&str],
181) -> SurfaceClosure {
182    let (closure, insts) = serialisation::collect_codec_closure(roots, own_types);
183    let mut generic_bases: BTreeSet<String> = BTreeSet::new();
184    for i in &insts {
185        if let serialisation::GenericInst::RecordInst { name, .. }
186        | serialisation::GenericInst::SumInst { name, .. } = i
187        {
188            generic_bases.insert(name.clone());
189        }
190    }
191    let mut declared: BTreeSet<String> = closure.iter().cloned().collect();
192    declared.extend(generic_bases.iter().cloned());
193    let mut subst: HashMap<String, String> = HashMap::new();
194    let mut taken: BTreeSet<String> = declared.clone();
195    for name in &declared {
196        // #2750: a consumed context's type is filed under a qualified key
197        // (`shop_order__Code`, #2087). The client is read by a person, so it
198        // declares the type under the plain name a user reads, adding a
199        // trailing `_` only when that name is already taken.
200        let plain = bynk_check::symbols::display_type_name(name);
201        let qualified = plain != name.as_str();
202        if qualified || surface.contains(&name.as_str()) {
203            let mut to = plain.to_string();
204            while surface.contains(&to.as_str()) || taken.contains(&to) {
205                to.push('_');
206            }
207            taken.insert(to.clone());
208            subst.insert(name.clone(), to);
209        }
210    }
211    let renamed = |t: &TypeRef| serialisation::rename_type_ref(t, &subst);
212    let types: HashMap<String, Arc<TypeDecl>> = if subst.is_empty() {
213        own_types.clone()
214    } else {
215        // Types the signatures never reach go in first, so a declared type
216        // renamed onto the same key (`Code`) wins; the closure never sees them.
217        let mut out: HashMap<String, Arc<TypeDecl>> = own_types
218            .iter()
219            .filter(|(k, _)| !declared.contains(*k))
220            .map(|(k, d)| (k.clone(), d.clone()))
221            .collect();
222        for (k, d) in own_types.iter().filter(|(k, _)| declared.contains(*k)) {
223            let decl = super::rename_in_decl(d, &subst);
224            out.insert(
225                subst.get(k).cloned().unwrap_or_else(|| k.clone()),
226                Arc::new(decl),
227            );
228        }
229        out
230    };
231    let roots: Vec<TypeRef> = roots.iter().map(renamed).collect();
232    let (names, insts) = serialisation::collect_codec_closure(&roots, &types);
233    let generic_bases: BTreeSet<String> = generic_bases
234        .into_iter()
235        .map(|n| subst.get(&n).cloned().unwrap_or(n))
236        .collect();
237    SurfaceClosure {
238        types,
239        subst,
240        names,
241        insts,
242        generic_bases,
243    }
244}
245
246/// The client for `ctx_name`, or `None` when no foreign caller may call any of
247/// its services. `own_types` is the context's own type namespace
248/// (`combined_types_for`), the table its contract hashes are computed in.
249pub fn emit_client(
250    ctx_name: &str,
251    table: &UnitTable,
252    own_types: &HashMap<String, Arc<TypeDecl>>,
253) -> Option<TsProgram> {
254    let services = client_services(table, own_types);
255    if services.is_empty() {
256        return None;
257    }
258    let actors: BTreeSet<&String> = services.iter().flat_map(|s| s.admits.iter()).collect();
259
260    // The codec closure of every exposed signature, in the callee's own
261    // namespace: the same roots a Bynk consumer collects for the services it
262    // calls (`emit_consumed_context_helpers`).
263    let mut roots: Vec<TypeRef> = Vec::new();
264    for s in &services {
265        roots.extend(s.svc.params.iter().map(|(_, t)| t.clone()));
266        roots.push(s.svc.return_type.clone());
267    }
268    // A boundary type named like the client's surface is renamed here, in a
269    // copy of the table, roots and closure; its contract hash was computed
270    // above from the original, as the callee computes it.
271    let SurfaceClosure {
272        types,
273        subst,
274        names,
275        insts,
276        generic_bases,
277    } = surface_closure(&roots, own_types, SURFACE_TYPES);
278    let renamed = |t: &TypeRef| serialisation::rename_type_ref(t, &subst);
279
280    // Every boundary type is declared in this module, under its own name, so
281    // a whole-name qualifier (#1846's form) names it bare while still
282    // selecting the consumer's codec: a transparent refinement re-checked
283    // inline, an opaque one cast, since the owner's `.of` is not here.
284    let mut qual: HashMap<String, String> = HashMap::new();
285    for n in names.iter().chain(generic_bases.iter()) {
286        qual.insert(n.clone(), n.clone());
287    }
288
289    let ru = RuntimeUse::default();
290    let mut body: Vec<TsStmt> = Vec::new();
291
292    // Constants.
293    body.extend(doc_const(
294        "The context this client calls.",
295        "CONTEXT",
296        None,
297        str_lit(ctx_name),
298    ));
299    body.extend(doc_const(
300        "The wire format version this client was generated for. Typed by the\n`@bynk/wire-client` package's own version, so a package that speaks another\nwire version fails `tsc` here.",
301        "WIRE_VERSION",
302        Some(TsType::named("__WireVersion")),
303        str_lit(bynk_check::wire_format::WIRE_VERSION.to_string()),
304    ));
305    let secret = bynk_check::wire_format::edge_key_to(ctx_name).unwrap_or_else(|| {
306        panic!("bynk internal error: `{ctx_name}` is not an edge name, so it has no call key")
307    });
308    body.extend(doc_const(
309        "The secret this Worker signs its calls with, as `bynk deploy` hands it over.",
310        "SECRET",
311        None,
312        str_lit(&secret),
313    ));
314    let contract_entries: Vec<(String, TsExpr)> = services
315        .iter()
316        .map(|s| (s.svc.name.clone(), str_lit(&s.hash)))
317        .collect();
318    body.extend(doc_const(
319        &contracts_doc(&services, ctx_name),
320        "CONTRACTS",
321        None,
322        TsExpr::AsConst(Box::new(TsExpr::multiline_object(contract_entries))),
323    ));
324
325    // The surface types.
326    body.extend(doc(
327        "The foreign callers the context declares, by actor name.",
328        TsDecl::TypeAlias {
329            name: "ForeignCaller".to_string(),
330            type_params: Vec::new(),
331            ty: TsType::union(actors.iter().map(|a| TsType::named(quoted(a))).collect()),
332        },
333    ));
334    body.extend(doc(
335        "What the calling Worker's `env` must hold.",
336        TsDecl::Interface {
337            name: "Env".to_string(),
338            type_params: Vec::new(),
339            members: vec![TsTypeMember::readonly_prop(
340                secret.clone(),
341                TsType::named("string"),
342            )],
343        },
344    ));
345    let mut service_members = Vec::new();
346    for s in &services {
347        service_members.push(TsTypeMember::method(
348            s.svc.name.clone(),
349            service_params(&s.svc, &renamed),
350            service_return(&s.svc, &renamed),
351        ));
352    }
353    body.extend(doc(
354        "Every service a foreign caller of the context may call.",
355        TsDecl::Interface {
356            name: "Services".to_string(),
357            type_params: Vec::new(),
358            members: service_members,
359        },
360    ));
361    body.extend(doc(
362        "The foreign callers each service admits.",
363        TsDecl::Interface {
364            name: "Admits".to_string(),
365            type_params: Vec::new(),
366            members: services
367                .iter()
368                .map(|s| {
369                    TsTypeMember::readonly_prop(
370                        s.svc.name.clone(),
371                        TsType::union(s.admits.iter().map(|a| TsType::named(quoted(a))).collect()),
372                    )
373                })
374                .collect(),
375        },
376    ));
377    body.extend(doc(
378        "The services `A` may call: calling one its handler does not admit is a\n`tsc` error rather than a `403`.",
379        TsDecl::TypeAlias {
380            name: "Client".to_string(),
381            type_params: vec!["A extends ForeignCaller".to_string()],
382            ty: TsType::named(
383                "{ readonly [S in keyof Services as [A] extends [Admits[S]] ? S : never]: Services[S] }",
384            ),
385        },
386    ));
387    body.extend(doc(
388        "How to reach the context: the actor this Worker is declared as, its Service\nBinding to the context's Worker, and its `env`, which holds `SECRET`.",
389        TsDecl::Interface {
390            name: "ConnectOptions".to_string(),
391            type_params: vec!["A extends ForeignCaller".to_string()],
392            members: vec![
393                TsTypeMember::readonly_prop("caller", TsType::named("A")),
394                TsTypeMember::readonly_prop("binding", TsType::named("__ServiceBinding")),
395                TsTypeMember::readonly_prop("env", TsType::named("Env")),
396            ],
397        },
398    ));
399
400    // `connect`.
401    let opt = |p: &str| TsExpr::Member {
402        object: Box::new(TsExpr::Ident("options".to_string())),
403        property: p.to_string(),
404    };
405    let mut methods = Vec::new();
406    for s in &services {
407        let encoded: Vec<TsExpr> = s
408            .svc
409            .params
410            .iter()
411            .map(|(name, t)| {
412                serialisation::serialise_expr_via(&renamed(t), &ident(ts_ident(name)), "", &ru)
413            })
414            .collect();
415        let args = match encoded.len() {
416            0 => TsExpr::object_entries(Vec::new()),
417            1 => encoded.into_iter().next().expect("one argument"),
418            _ => TsExpr::object_entries(
419                s.svc
420                    .params
421                    .iter()
422                    .zip(encoded)
423                    .map(|((name, _), e)| TsObjectEntry::prop(name.clone(), e))
424                    .collect(),
425            ),
426        };
427        let call = TsExpr::Call {
428            callee: Box::new(TsExpr::Ident("__callService".to_string())),
429            args: vec![
430                opt("binding"),
431                str_lit(&s.svc.name),
432                args,
433                serialisation::deserialise_ref_via(&renamed(&s.svc.return_type), "", &ru),
434                opt("caller"),
435                TsExpr::Member {
436                    object: Box::new(TsExpr::Ident("CONTRACTS".to_string())),
437                    property: s.svc.name.clone(),
438                },
439                opt("env"),
440                TsExpr::Ident("CONTEXT".to_string()),
441            ],
442        };
443        methods.push(TsObjectEntry::Method {
444            name: s.svc.name.clone(),
445            is_async: false,
446            generics: Vec::new(),
447            params: service_params(&s.svc, &renamed),
448            return_type: Some(service_return(&s.svc, &renamed)),
449            doc: None,
450            inline: false,
451            body: vec![TsStmt::return_stmt(Some(call), None)],
452            span: None,
453        });
454    }
455    body.extend(doc(
456        "A client calling the context as the foreign caller `options.caller`. Each\ncall is signed under `SECRET`, stamped with its service's contract hash,\nand decoded with the codec a Bynk caller uses. A refusal or transport failure\nis thrown; `callErrorOf` (from `@bynk/wire-client`) reads it.\n\n    const client = connect({ caller: \"<Actor>\", binding: env.<BINDING>, env });",
457        TsDecl::Function {
458            name: "connect".to_string(),
459            generics: vec!["A extends ForeignCaller".to_string()],
460            params: vec![TsParam::new("options".to_string(), Some(TsType::named_with_args(
461                    "ConnectOptions",
462                    vec![TsType::named("A")],
463                )))],
464            return_type: Some(TsType::named_with_args("Client", vec![TsType::named("A")])),
465            body: vec![
466                TsStmt::const_stmt(
467                    bynk_ts::TsBindingName::Ident("services".to_string()),
468                    Some(TsType::named("Services")),
469                    TsExpr::multiline_object_entries(methods),
470                    None,
471                ),
472                TsStmt::return_stmt(
473                    Some(TsExpr::As {
474                        expr: Box::new(TsExpr::As {
475                            expr: Box::new(TsExpr::Ident("services".to_string())),
476                            ty: TsType::named("unknown"),
477                        }),
478                        ty: TsType::named_with_args("Client", vec![TsType::named("A")]),
479                    }),
480                    None,
481                ),
482            ],
483            is_async: false,
484            inline: false,
485        },
486    ));
487
488    // The boundary types, then their codecs.
489    let mut type_names: Vec<String> = names
490        .iter()
491        .filter(|n| types.get(*n).is_some_and(|d| d.type_params.is_empty()))
492        .cloned()
493        .collect();
494    type_names.extend(generic_bases.iter().cloned());
495    type_names.sort();
496    type_names.dedup();
497    for name in &type_names {
498        if let Some(decl) = types.get(name) {
499            body.extend(boundary_type(name, decl));
500        }
501    }
502    body.extend(serialisation::decls_as_stmts(
503        serialisation::emit_helpers_for_owner_qualified(&names, &types, ctx_name, &qual, &ru),
504    ));
505    body.extend(serialisation::decls_as_stmts(
506        serialisation::emit_generic_helpers_qualified(&insts, &types, &qual, &ru),
507    ));
508
509    // The header and the import line, carrying the package names the module
510    // actually uses.
511    let unbound = bynk_ts::unbound_names(&TsProgram {
512        stmts: body.clone(),
513    });
514    let imports: Vec<String> = PACKAGE_NAMES
515        .iter()
516        .filter(|(name, _)| unbound.iter().any(|u| u == name))
517        .map(|(_, spec)| spec.to_string())
518        .collect();
519    let mut stmts = vec![
520        TsStmt::comment("Generated by bynk — do not edit by hand.", None),
521        TsStmt::comment(
522            [
523                "The typed client for context `",
524                ctx_name,
525                "`, for a Worker that is not Bynk.",
526            ]
527            .concat(),
528            None,
529        ),
530        TsStmt::comment(
531            "It imports `@bynk/wire-client`: https://bynk-lang.org/reference/typescript-client/",
532            None,
533        ),
534        TsStmt::decl(
535            TsDecl::Import {
536                type_only: false,
537                names: imports,
538                from: CLIENT_PACKAGE.to_string(),
539            },
540            None,
541        ),
542    ];
543    stmts.extend(body);
544    Some(TsProgram { stmts })
545}
546
547/// `CONTRACTS`' doc: what the hashes are, and the pin the callee's project
548/// records for each foreign caller (`bynk.foreign.toml`, §8 D3 layer 2), ready
549/// to paste.
550fn contracts_doc(services: &[ClientService], ctx_name: &str) -> String {
551    let mut lines = vec![
552        "The contract hash of each service, as the callee was built. A call stamps".to_string(),
553        "it, and the callee refuses a different one with `409 ContractMismatch`.".to_string(),
554        String::new(),
555        "The context's project pins them per foreign caller in `bynk.foreign.toml`,".to_string(),
556        "beside its `bynk.toml`, and `bynk deploy` refuses a contract change that".to_string(),
557        "breaks a pin. Regenerate this client, then update the pin:".to_string(),
558    ];
559    let mut by_actor: BTreeMap<&String, Vec<&ClientService>> = BTreeMap::new();
560    for s in services {
561        for a in &s.admits {
562            by_actor.entry(a).or_default().push(s);
563        }
564    }
565    for (actor, svcs) in by_actor {
566        lines.push(String::new());
567        lines.push(["    [\"", ctx_name, "\".", actor, "]"].concat());
568        for s in svcs {
569            lines.push(["    ", &s.svc.name, " = \"", &s.hash, "\""].concat());
570        }
571    }
572    lines.join("\n")
573}
574
575/// A service's parameters, typed for the client.
576fn service_params(
577    svc: &CrossContextService,
578    renamed: &dyn Fn(&TypeRef) -> TypeRef,
579) -> Vec<TsParam> {
580    svc.params
581        .iter()
582        .map(|(name, t)| TsParam::new(super::ts_ident(name), Some(ts_type(&renamed(t)))))
583        .collect()
584}
585
586/// A service's result, as the promise a client call returns.
587fn service_return(svc: &CrossContextService, renamed: &dyn Fn(&TypeRef) -> TypeRef) -> TsType {
588    let ret = renamed(&svc.return_type);
589    let ret = if let TypeRef::Effect(inner, _) = ret {
590        *inner
591    } else {
592        ret
593    };
594    TsType::named_with_args("globalThis.Promise", vec![ts_type(&ret)])
595}
596
597/// The TypeScript type of a boundary type reference, every name bare.
598fn ts_type(t: &TypeRef) -> TsType {
599    super::ts_types::ts_type_ref_qualified_multi_ts_type(t, &HashMap::new())
600}
601
602/// A boundary type's declaration in the client: its in-memory shape, which is
603/// what the codecs produce and consume. A record is an interface of readonly
604/// fields; a sum a union discriminated by `tag`; a transparent refined type
605/// its base type (the callee checks the predicate); an opaque type its base
606/// type branded, so a caller passes back a value it was given rather than
607/// making one.
608fn boundary_type(name: &str, decl: &TypeDecl) -> Vec<TsStmt> {
609    let params: Vec<String> = decl
610        .type_params
611        .iter()
612        .map(|p| p.name.name.clone())
613        .collect();
614    let d = match &decl.body {
615        TypeBody::Record(r) => TsDecl::Interface {
616            name: name.to_string(),
617            type_params: params,
618            members: r
619                .fields
620                .iter()
621                .map(|f| TsTypeMember::readonly_prop(f.name.name.clone(), ts_type(&f.type_ref)))
622                .collect(),
623        },
624        TypeBody::Sum(sum) => TsDecl::TypeAlias {
625            name: name.to_string(),
626            type_params: params,
627            ty: TsType::multiline_union(
628                sum.variants
629                    .iter()
630                    .map(|v| {
631                        let mut members = vec![TsTypeMember::readonly_prop(
632                            "tag",
633                            TsType::named(quoted(&v.name.name)),
634                        )];
635                        members.extend(v.payload.iter().map(|f| {
636                            TsTypeMember::readonly_prop(
637                                super::payload_prop(&f.name.name),
638                                ts_type(&f.type_ref),
639                            )
640                        }));
641                        TsType::Object(members)
642                    })
643                    .collect(),
644            ),
645        },
646        TypeBody::Refined {
647            base, base_span, ..
648        } => TsDecl::TypeAlias {
649            name: name.to_string(),
650            type_params: params,
651            ty: ts_type(&TypeRef::Base(*base, *base_span)),
652        },
653        TypeBody::Opaque {
654            base, base_span, ..
655        } => TsDecl::TypeAlias {
656            name: name.to_string(),
657            type_params: params,
658            ty: TsType::intersection(vec![
659                ts_type(&TypeRef::Base(*base, *base_span)),
660                TsType::Object(vec![TsTypeMember::readonly_prop(
661                    "__opaque",
662                    TsType::named(quoted(name)),
663                )]),
664            ]),
665        },
666    };
667    let mut out = Vec::new();
668    if let Some(text) = decl.documentation.as_deref() {
669        out.push(TsStmt::doc_comment(text, None));
670    }
671    let mut stmt = TsStmt::decl(TsDecl::Export(Box::new(d)), None);
672    stmt.no_blank_before = !out.is_empty();
673    out.push(stmt);
674    out
675}
676
677/// `"name"`, a string literal type. Actor, variant and type names are
678/// identifiers, so there is nothing to escape.
679fn quoted(name: &str) -> String {
680    ["\"", name, "\""].concat()
681}
682
683/// An exported declaration under a doc comment.
684fn doc(text: &str, decl: TsDecl) -> Vec<TsStmt> {
685    let mut stmt = TsStmt::decl(TsDecl::Export(Box::new(decl)), None);
686    stmt.no_blank_before = true;
687    vec![TsStmt::doc_comment(text, None), stmt]
688}
689
690fn doc_const(text: &str, name: &str, ty: Option<TsType>, init: TsExpr) -> Vec<TsStmt> {
691    doc(
692        text,
693        TsDecl::ConstDecl {
694            name: name.to_string(),
695            ty,
696            init,
697        },
698    )
699}