1use 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
54pub const CLIENT_FILE: &str = "bynk-client.ts";
58
59pub const CLIENT_PACKAGE: &str = "@bynk/wire-client";
61
62const SURFACE_TYPES: &[&str] = &[
66 "Admits",
67 "Client",
68 "ConnectOptions",
69 "Env",
70 "ForeignCaller",
71 "Services",
72];
73
74const 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
100struct ClientService {
102 svc: CrossContextService,
103 admits: Vec<String>,
105 hash: String,
106}
107
108pub 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
127fn 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
157pub(super) struct SurfaceClosure {
161 pub types: HashMap<String, Arc<TypeDecl>>,
163 pub subst: HashMap<String, String>,
165 pub names: Vec<String>,
167 pub insts: Vec<serialisation::GenericInst>,
169 pub generic_bases: BTreeSet<String>,
171}
172
173pub(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 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 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
246pub 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 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 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 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 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 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 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 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 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
547fn 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
575fn 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
586fn 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
597fn ts_type(t: &TypeRef) -> TsType {
599 super::ts_types::ts_type_ref_qualified_multi_ts_type(t, &HashMap::new())
600}
601
602fn 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
677fn quoted(name: &str) -> String {
680 ["\"", name, "\""].concat()
681}
682
683fn 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}