bynk_emit/emitter/emit/service.rs
1//! Services and contexts: `emit_service` and the context `deps` interface, the `make` surface,
2//! the cross-context capability namespaces, and the actor-sum types a service's `deps.who` uses.
3
4use super::{
5 append_deps_field, cron_handler_method_name, events_release_body, http_handler_method_name_ir,
6 queue_handler_method_name, return_undefined_unless, seam_identity_ts_type,
7};
8use crate::emit_model::EmitProjectCtx;
9use crate::emitter::ctx::{BodyMode, HandlerShared, ModuleCtx};
10use crate::emitter::lower_ctx::LowerCtx;
11use crate::emitter::lower_stmt::{Body, block_body_with_return};
12use crate::emitter::ts_types::{ts_ty_to_ts_type, ts_type_ref_to_ts_type};
13use crate::emitter::{BuildTarget, UnitFacts, UnitKind, event_pattern_guard_ir, ts_ident};
14use crate::ts_build::{binary, ident, member, num_lit};
15use bynk_check::actors::ActorDecl;
16use bynk_check::checker::TypedCommons;
17use bynk_check::firstparty::FirstPartyCap;
18use bynk_model::{
19 ActorSeamIr, HandlerSignatureIr, IrHandlerKind, ProtocolIr, SchemaVersionIr,
20 is_effectful_return, lower_actor_seam_ir, lower_handler_kind_ir,
21};
22use bynk_syntax::ast::{CommonsItem, Expr, ExprKind, Handler, ServiceDecl};
23use std::collections::{HashMap, HashSet};
24
25/// The runtime test a `via schema(...)` guard negates (events slice 4b, #990):
26/// `===` for a literal, `>=` and/or `<=` for a range, and none for `_`, which
27/// only forwards the envelope. Bounds are inclusive.
28fn schema_version_test(env_binder: &str, version: SchemaVersionIr) -> Option<bynk_ts::TsExpr> {
29 use crate::ts_build::{and_expr, strict_eq};
30 use bynk_ts::TsBinaryOp::{GreaterThanEq, LessThanEq};
31 let v = || member(ident(env_binder), "schemaVersion");
32 match version {
33 SchemaVersionIr::Exact(n) => Some(strict_eq(v(), num_lit(n))),
34 SchemaVersionIr::Range {
35 lo: Some(lo),
36 hi: Some(hi),
37 } => Some(and_expr(
38 binary(GreaterThanEq, v(), num_lit(lo)),
39 binary(LessThanEq, v(), num_lit(hi)),
40 )),
41 SchemaVersionIr::Range {
42 lo: Some(lo),
43 hi: None,
44 } => Some(binary(GreaterThanEq, v(), num_lit(lo))),
45 SchemaVersionIr::Range {
46 lo: None,
47 hi: Some(hi),
48 } => Some(binary(LessThanEq, v(), num_lit(hi))),
49 SchemaVersionIr::Range { lo: None, hi: None } | SchemaVersionIr::Any => None,
50 }
51}
52
53/// A service's declarations (1A.32a, Decision A of #3733): its doc comment, if any, then
54/// `export const {name} = { .. };` as a [`bynk_ts::TsDecl::ConstDecl`] over a multiline object
55/// with one [`bynk_ts::TsObjectEntry::Method`] per handler.
56///
57/// Source maps come from the printer alone: each handler's entry span anchors its header and
58/// prologue to its own `on call` line (#2280), and the object's `end_span` anchors the closing
59/// `};` to the service. The caller gives the first statement the service's span, as for every
60/// other item.
61pub(crate) fn emit_service(
62 s: &ServiceDecl,
63 protocol: &ProtocolIr,
64 signatures: &[HandlerSignatureIr],
65 commons: &TypedCommons,
66 ctx: &EmitProjectCtx,
67) -> Vec<bynk_ts::TsStmt> {
68 let tys = UnitFacts::of(ctx).render(commons);
69 let mut entries: Vec<bynk_ts::TsObjectEntry> = Vec::new();
70 let mut cron_idx = 0usize;
71 let mut queue_idx = 0usize;
72 let ws_proto = matches!(protocol, ProtocolIr::WebSocket { .. });
73 // #1187's slice 5: `s.handlers`/`signatures` are the same list in the
74 // same declaration order — `signatures` is built by mapping `s.handlers`
75 // 1:1 at the one call site (`emitter.rs`) — the same zip-by-index
76 // precedent `emit_capability`'s own `c.ops`/`ops` pairing already
77 // established (#1193).
78 for (handler, (ir_params, _ir_given, ir_ret, ir_effectful)) in s.handlers.iter().zip(signatures)
79 {
80 // v0.104/v0.106 (real-time track slice 3b): on Workers a `from websocket`
81 // lifecycle handler (`on open`/`on message`/`on close`) does not emit a
82 // service-surface method — its body runs inside the hosting Durable Object
83 // (`__wsOpen`/`__wsMessage`/`__wsClose`, DECISION A), driven by the edge
84 // upgrade / `webSocketMessage` / `webSocketClose`, not from here. (On bundle
85 // these are callable surface methods a `TestConnection` test drives.)
86 let handler_kind_ir = lower_handler_kind_ir(&handler.kind);
87 let is_ws_handler = matches!(handler_kind_ir, IrHandlerKind::Open | IrHandlerKind::Close)
88 || (ws_proto && matches!(handler_kind_ir, IrHandlerKind::Message));
89 // Events track, slice 0 (spine #936): unlike the WebSocket lifecycle
90 // handlers above, `on event` has no *other* place its body could go
91 // on Workers — a WS lifecycle handler's real body lives in the
92 // hosting agent's DO (`emit_ws_do_method`); a subscriber service has
93 // no such alternate home. So the method is still emitted here on
94 // every target — real delivery (the fan-out DO calling in) reaches
95 // it directly, not through `compose.ts`'s HTTP-routable surface,
96 // which never exposes it regardless (no HTTP method/route to route
97 // from).
98 if is_ws_handler && matches!(ctx.target, BuildTarget::Workers) {
99 continue;
100 }
101 // #1361: the doc block is no longer written directly here — it now
102 // lives on the real `TsObjectEntry::Method` built below (`doc:
103 // handler.documentation.clone()`), rendered by `render_multiline_
104 // object_entry`'s own `Method` arm at the right depth/position.
105 let kind_name = match &handler_kind_ir {
106 IrHandlerKind::Call => "call".to_string(),
107 IrHandlerKind::Http { method, path } => http_handler_method_name_ir(*method, path),
108 IrHandlerKind::Cron { .. } => {
109 let name = cron_handler_method_name(&s.name.name, cron_idx);
110 cron_idx += 1;
111 name
112 }
113 // v0.106: a `from websocket` `on message` is the inbound surface method.
114 IrHandlerKind::Message if ws_proto => "message".to_string(),
115 IrHandlerKind::Message => {
116 let name = queue_handler_method_name(&s.name.name, queue_idx);
117 queue_idx += 1;
118 name
119 }
120 // v0.103/v0.106: the WebSocket lifecycle surface methods.
121 IrHandlerKind::Open => "open".to_string(),
122 IrHandlerKind::Close => "close".to_string(),
123 // Events track, slice 0 (spine #936): exactly one `on event` per
124 // `from Events(E)` service.
125 IrHandlerKind::Event => "event".to_string(),
126 // #2341 (decision C): the router's rejection renderer.
127 IrHandlerKind::Rejected => "rejected".to_string(),
128 };
129 // For service handlers the operation name is the handler kind
130 // (e.g. `call`). v0.5 has only one handler kind, so the service is a
131 // single-operation object literal.
132 let mut params: Vec<bynk_ts::TsParam> = ir_params
133 .iter()
134 .map(|(name, ty)| {
135 bynk_ts::TsParam::new(ts_ident(name), Some(ts_ty_to_ts_type(*ty, tys)))
136 })
137 .collect();
138 // v0.103/v0.106: a `from websocket` lifecycle handler receives the
139 // `connection` as its first parameter (the synthetic binding the checker
140 // added — the fresh socket for `on open`, the firing socket for `on
141 // message`/`on close`); emit it so the lowered body's `connection` resolves.
142 if is_ws_handler && let ProtocolIr::WebSocket { out_ty, .. } = protocol {
143 params.insert(
144 0,
145 bynk_ts::TsParam::new(
146 "connection".to_string(),
147 Some(bynk_ts::TsType::named_with_args(
148 "Connection",
149 vec![ts_ty_to_ts_type(*out_ty, tys)],
150 )),
151 ),
152 );
153 }
154 // Events track, slice 4 (spine #936): a `via schema(N)` guard needs
155 // `env.schemaVersion` regardless of whether the subscriber declared
156 // the optional `env: EventEnvelope` parameter (slice 2) — a bare
157 // `on event(e: E)` handler has no envelope in scope otherwise. When
158 // missing, insert a synthetic parameter in the same position a real
159 // `env` would occupy, under a name distinct from anything a user
160 // could write, so it can never collide with a declared one. Every
161 // envelope-forwarding call site reads `wants_envelope`, so the value
162 // actually arrives here.
163 // 1B.1c (Decision F of #3928): whether the envelope arrives is the
164 // one rule every delivery site reads, `EventSubscriberShape::
165 // wants_envelope`; this callee is the side that must line up with it.
166 let envelope_shape = bynk_model::EventSubscriberShape {
167 two_param_handler: ir_params.len() == 2,
168 schema_dispatch: matches!(
169 protocol,
170 ProtocolIr::Events {
171 schema_dispatch: Some(_),
172 ..
173 }
174 ),
175 };
176 let schema_dispatch_env_binder =
177 if handler_kind_ir == IrHandlerKind::Event && envelope_shape.wants_envelope() {
178 match ir_params.get(1) {
179 Some((env_param_name, _)) => Some(ts_ident(env_param_name)),
180 None => {
181 params.insert(
182 1,
183 bynk_ts::TsParam::new(
184 "__bynkSchemaEnv".to_string(),
185 Some(bynk_ts::TsType::named("EventEnvelope")),
186 ),
187 );
188 Some("__bynkSchemaEnv".to_string())
189 }
190 }
191 } else {
192 None
193 };
194 // Lower the body first so we can detect cross-context usage and
195 // adjust the deps shape accordingly.
196 // v0.52: a multi-actor sum handler's resolved actor is threaded through
197 // `deps.who`; the binder ident lowers to it so the body can `match`. A
198 // sum supersedes the single-actor Bearer identity path (the per-arm
199 // identity comes from the match, not a single `deps.identity`).
200 // v0.47/v0.151/v0.52/v0.54: a handler's own actor-verification seam —
201 // Bearer/Oidc/Caller thread their identity through `deps.identity`,
202 // a sum threads the resolved-actor tagged union through `deps.who`
203 // (the body `match`es it). `lower_actor_seam_ir`'s own doc comment
204 // (`bynk_model::ActorSeamIr`) has the full grounding for why sum is
205 // tried first (it can otherwise collide with Bearer) and why the
206 // other three are mutually exclusive by construction.
207 let seam = lower_actor_seam_ir(handler, &ctx.actors);
208 let deps_identity_binder = match &seam {
209 ActorSeamIr::Caller(binder) | ActorSeamIr::Sender(binder) => Some(binder.clone()),
210 ActorSeamIr::Bearer(s) => s.binder.clone(),
211 ActorSeamIr::Oidc(s) => s.binder.clone(),
212 ActorSeamIr::SignedCookie(s) => s.binder.clone(),
213 ActorSeamIr::Sum(_) | ActorSeamIr::CallSum(_) | ActorSeamIr::None => None,
214 };
215 let actor_sum_binder = if matches!(seam, ActorSeamIr::Sum(_) | ActorSeamIr::CallSum(_)) {
216 handler
217 .by_clause
218 .as_ref()
219 .and_then(|by| by.binder.as_ref())
220 .map(|binder| binder.name.clone())
221 } else {
222 None
223 };
224 let mut module = ModuleCtx::for_unit(commons, ctx);
225 module.note_unit(ctx);
226 module.agent_method_givens = ctx.agent_method_givens.clone();
227 module.agent_called_contexts = ctx.agent_called_contexts.clone();
228 module.event_schema_versions = ctx.event_schema_versions.clone();
229 module.consumed_type_ns = consumed_type_ns(ctx);
230 module.consumed_type_declared = ctx.consumed_type_aliases.clone();
231 module.consumed_context_types = ctx.consumed_context_types();
232 module.target = ctx.target;
233 let mut cx = LowerCtx::new(
234 module,
235 BodyMode::ServiceHandler {
236 handler: HandlerShared {
237 capabilities: bynk_model::lower_handler_given_ir(handler)
238 .into_iter()
239 .map(|c| c.name)
240 .collect::<HashSet<_>>(),
241 // #934: the qualified handler name `Idempotency.dedup`/
242 // `remember` key scoping prefixes onto the developer-supplied
243 // key.
244 handler_scope: Some(format!(
245 "{}.{}.{}",
246 ctx.commons_name, s.name.name, kind_name
247 )),
248 owning_context: ctx.commons_name.clone(),
249 ..HandlerShared::default()
250 },
251 deps_identity_binder,
252 actor_sum_binder,
253 },
254 );
255 cx.local_agents = ctx.local_agents.clone();
256 // #1653: parameters are bindings of the body's own scope, so a `let` that
257 // re-binds one gets a fresh name instead of redeclaring it.
258 for p in &handler.params {
259 cx.declare_binder(&p.name.name);
260 }
261 let async_tail = *ir_effectful;
262 // 1A.15: the body is items, not text: the prologue guards, the lowered
263 // body and the events wrapper reach the printer as statements, which
264 // records their checkpoints.
265 let lowered_body = block_body_with_return(
266 &handler.body,
267 &mut cx,
268 async_tail,
269 Some(&handler.return_type),
270 );
271 let mut guards = Body::new();
272 // Events track, slice 1 (spine #936): a `from Events(E { ... })`
273 // subscription filter is deliver-and-filter (ADR 0286, unchanged by
274 // this slice) — the fan-out mechanism still delivers every emission
275 // of `E` to every subscriber; this subscriber's own generated
276 // handler evaluates the pattern as a guard and no-ops if it doesn't
277 // match. Prologue, not a wrapper edit, so it covers all three
278 // delivery paths (Cloudflare Workers, Bundle/node, Bundle/browser)
279 // in one place, since they all call into this same generated method.
280 // `handler.params[0]`'s type is guaranteed to equal the header's
281 // event type by `check_service_protocols`'s param-type-agreement
282 // check, so testing its own name (read off `ir_params`, the
283 // already-lowered signature `emit_service`'s own loop already
284 // holds — P6.54) here is sound.
285 if handler_kind_ir == IrHandlerKind::Event
286 && let ProtocolIr::Events {
287 pattern: Some(pattern),
288 ..
289 } = protocol
290 && let Some((param_name, _)) = ir_params.first()
291 && let Some(guard) = event_pattern_guard_ir(&ts_ident(param_name), Some(pattern))
292 {
293 guards.push(return_undefined_unless(guard));
294 }
295 // Events track, slice 4 (spine #936): a `via schema(N)` guard,
296 // independent of and in addition to the payload-pattern guard above
297 // — a service may carry either, both, or neither. Same
298 // prologue technique, same three-delivery-path coverage. The
299 // envelope binder is either the user's own declared `env` name or
300 // the synthetic one inserted above.
301 if let ProtocolIr::Events {
302 schema_dispatch: Some(version),
303 ..
304 } = protocol
305 && let Some(env_binder) = &schema_dispatch_env_binder
306 && let Some(test) = schema_version_test(env_binder, *version)
307 {
308 // Inserted ahead of the subscriber-filter guard, as it always was.
309 let mut schema_guard = Body::new();
310 schema_guard.push(return_undefined_unless(test));
311 schema_guard.append(std::mem::replace(&mut guards, Body::new()));
312 guards = schema_guard;
313 }
314 // Append the deps parameter (may include surface field if the body
315 // made cross-context calls). v0.47: a Bearer handler's deps also carries
316 // the seam-minted `identity` — but only when a binder captures it
317 // (v0.50: a binder-less Bearer handler verifies but mints no identity).
318 let mut deps_members = build_deps_object_ty_with_surface(
319 &effective_given(&bynk_model::lower_handler_given_ir(handler), &cx),
320 &cx,
321 &ctx.cross_context,
322 ctx.target,
323 );
324 // v0.47/v0.151/v0.52/v0.54: widen `deps` for whichever actor seam
325 // this handler resolved to — at most one arm ever fires, `seam`
326 // being an enum rather than four independent optionals (a stronger
327 // guarantee than the four-`if`-in-a-row shape this replaced, whose
328 // mutual exclusion depended on the resolver-priority `if`s above
329 // rather than the type system).
330 match &seam {
331 // #3386: a `SignedCookie` seam mints its identity from `sub` just the same.
332 ActorSeamIr::Bearer(_) | ActorSeamIr::SignedCookie(_) => {
333 if let Some(id) = seam.captured_identity_type() {
334 append_deps_field(&mut deps_members, "identity", bynk_ts::TsType::named(id));
335 }
336 }
337 // v0.151: an `Oidc`-binding handler threads its `sub`-minted
338 // identity into deps exactly like Bearer.
339 ActorSeamIr::Oidc(s) if s.binder.is_some() => {
340 append_deps_field(
341 &mut deps_members,
342 "identity",
343 bynk_ts::TsType::named(s.identity_type.clone()),
344 );
345 // #2380 (L5): and the verified token's claims.
346 append_deps_field(
347 &mut deps_members,
348 "claims",
349 crate::emitter::ts_types::token_claims_ts_type(),
350 );
351 }
352 // v0.54: a Caller-binding call handler's deps carries the
353 // caller's context name as its `CallerId` identity (a `string`).
354 // #3328: and a `Sender`-binding email handler's carries the minted
355 // `SenderIdentity` (see [`seam_identity_ts_type`]).
356 ActorSeamIr::Caller(_) | ActorSeamIr::Sender(_) => {
357 append_deps_field(&mut deps_members, "identity", seam_identity_ts_type(&seam));
358 }
359 // v0.52: a sum handler's deps carries the resolved-actor tagged
360 // union (`who`), which the body `match`es. A binder-less sum is
361 // rejected by the checker, so a sum handler always captures `who`.
362 //
363 // Arc F, slice 4 (#1463): review of #1463 found this can't build
364 // as a real `TsType::Object`/`TsType::union` — each member's own
365 // `{ tag: "Name", identity: T }` shape is comma-separated
366 // (matching the pre-existing hand-written text), but
367 // `TsType::Object`'s own printer always joins members with `"; "`
368 // (`bynk-ts/src/printer.rs`'s own hardcoded convention) —
369 // confirmed by a real fixture byte-diff, not assumed. Rebuilding
370 // it would silently change the punctuation, not just the
371 // construction. Stays the pre-rendered text it already was,
372 // wrapped as opaque `Named` — the same "an odd, one-off shape
373 // stays opaque text" precedent this track uses elsewhere, not a
374 // gap this slice leaves unclosed.
375 ActorSeamIr::Sum(members) => {
376 append_deps_field(&mut deps_members, "who", actor_sum_ts_union(members));
377 }
378 // I3 (#1971): a `call` sum. `Caller` carries the calling context's
379 // name; a foreign caller is its actor alone.
380 ActorSeamIr::CallSum(members) => {
381 append_deps_field(&mut deps_members, "who", call_sum_ts_type(members));
382 }
383 // A binder-less Bearer/Oidc, or no seam at all — nothing to widen.
384 ActorSeamIr::Oidc(_) | ActorSeamIr::None => {}
385 }
386 // v0.79: a handler whose body uses `detach` receives the execution context
387 // (`__exec`) in its deps, so the fire-and-forget send can hand its promise
388 // to `waitUntil`. Gated on the body so non-sending handlers are unchanged.
389 if commons.exec_plan.handler_needs(handler) {
390 append_deps_field(
391 &mut deps_members,
392 "__exec",
393 bynk_ts::TsType::Object(vec![bynk_ts::TsTypeMember::method(
394 "waitUntil",
395 vec![bynk_ts::TsParam::new(
396 "promise".to_string(),
397 Some(bynk_ts::TsType::named_with_args(
398 "globalThis.Promise",
399 vec![bynk_ts::TsType::named("unknown")],
400 )),
401 )],
402 bynk_ts::TsType::named("void"),
403 )]),
404 );
405 }
406 // Events track, slice 0 (spine #936): a handler whose body uses
407 // `Events.emit` receives a compose-supplied `__eventsDispatch`
408 // callback in its deps — the actual fanout delivery mechanism
409 // (a Cloudflare Durable Object per publishing context, or an
410 // in-process dispatch on Bundle/node) lives at the composition
411 // layer, which already knows how to build any capability's
412 // provider; the handler itself only needs to hand its buffered
413 // `__events` to whatever composed it. Mirrors `__exec`'s threading
414 // for `detach` exactly. Gated on more than this handler's own body: a
415 // handler with no direct `Events.emit` call but that invokes a
416 // *local agent* method which itself emits (`Ledger(id).bump(...)`)
417 // still needs `__eventsDispatch` threaded through, to hand onward —
418 // `cx.agent_given_caps_used` is exactly the existing mechanism that
419 // already propagates an invoked agent method's other `given`
420 // capabilities up to the caller (`effective_given`, just below);
421 // `Events` rides the same path since it's declared as an ordinary
422 // `given Events` on the agent handler.
423 let needs_events_dispatch = cx.is_first_party(FirstPartyCap::Events)
424 && (bynk_model::block_uses_emit(&handler.body, &commons.callees)
425 || cx
426 .agent_given_caps_used()
427 .is_some_and(|m| m.contains_key("Events")));
428 if needs_events_dispatch {
429 // Arc F, slice 4 (#1463): a bare function type has no way to name
430 // its own parameter (`TsType::Fn`'s params are anonymous,
431 // positional `a0`/`a1`/… — its own doc), the same real algebra
432 // gap `emit_context_deps_interface`'s own identical field already
433 // named (#1453) — stays opaque `Named` text, not a new pattern.
434 append_deps_field(
435 &mut deps_members,
436 "__eventsDispatch",
437 bynk_ts::TsType::named(format!(
438 "(events: globalThis.Array<{}>) => globalThis.Promise<void>",
439 crate::emitter::EVENTS_WIRE_EVENT_TS_TYPE
440 )),
441 );
442 }
443 // Arc F, slice 4 (#1463): `deps`'s own type is now the real
444 // `TsType::Object` `build_deps_object_ty_with_surface` builds,
445 // widened in place by every `append_deps_field` call above — closes
446 // #1361's own named residual ("deps's own type stays one opaque
447 // `TsType::named` string... real, separate, much larger work than
448 // this slice's own scope").
449 params.push(bynk_ts::TsParam::new(
450 "deps".to_string(),
451 Some(bynk_ts::TsType::Object(deps_members)),
452 ));
453 // Events track, slice 0 (spine #936): release-at-commit (the retired
454 // events track's §3.0, `design/archive/retired-tracks.md`) needs a
455 // completion boundary services never had before — the
456 // body runs inside an IIFE so its own `return`s resolve `__result`
457 // rather than the outer method, and only a handler that completes
458 // without throwing reaches past it, then flushes `__events` to
459 // whatever composed it (`deps.__eventsDispatch`, threaded above).
460 // Gated on `block_uses_emit` specifically (not the broader
461 // `needs_events_dispatch` above) — a handler that only *forwards*
462 // `__eventsDispatch` to an agent it calls has nothing of its own to
463 // buffer or flush, so it keeps byte-identical output, mirroring
464 // `__exec`'s gate on `block_uses_send`.
465 let body_emits_directly = bynk_model::block_uses_emit(&handler.body, &commons.callees);
466 // #1361: the events-IIFE wrapper (if any) surrounds the guards and the
467 // lowered body. The whole method body is statements, the wrapper an
468 // arrow whose body is the guards and the lowered body (1A.ws).
469 let mut body = guards;
470 body.append(lowered_body);
471 let body = if body_emits_directly {
472 events_release_body(body)
473 } else {
474 body
475 };
476 let body = body.into_stmts();
477
478 // #2280: anchor the method header and prologue to the handler's own
479 // `on call` line rather than the previous statement's.
480 entries.push(bynk_ts::TsObjectEntry::Method {
481 name: kind_name,
482 is_async: *ir_effectful,
483 generics: Vec::new(),
484 params,
485 return_type: Some(ts_ty_to_ts_type(*ir_ret, tys)),
486 doc: handler.documentation.as_deref().map(str::to_owned),
487 inline: false,
488 body,
489 span: Some(handler.span),
490 });
491 }
492 // #2280: what follows the last handler belongs to the service, not to that
493 // handler's final body line.
494 let mut stmts = Vec::new();
495 let has_doc = s.documentation.is_some();
496 if let Some(doc) = s.documentation.as_deref() {
497 stmts.push(bynk_ts::TsStmt::doc_comment(doc, None));
498 }
499 let mut object = bynk_ts::TsStmt::decl(
500 bynk_ts::TsDecl::Export(Box::new(bynk_ts::TsDecl::ConstDecl {
501 name: s.name.name.clone(),
502 ty: None,
503 init: bynk_ts::TsExpr::multiline_object_ending_at(entries, s.span),
504 })),
505 None,
506 );
507 // A leading doc comment sits directly above the declaration it documents.
508 object.no_blank_before = has_doc;
509 stmts.push(object);
510 stmts
511}
512
513/// v0.15: the TypeScript deps-field type for a `given` capability reference.
514/// A local capability uses its bare interface name; a cross-context one is
515/// qualified with the providing context's import namespace
516/// (`platform_time.Clock`).
517///
518/// Arc F, slice 4 (#1463): a qualified capability name (`ns.Cap`) has no
519/// dedicated `bynk_ts::TsType` shape (no member-access-on-a-type variant in
520/// the algebra) — `Named` carrying the whole dotted string is the same
521/// honest-opaque representation `workers_env_ty`'s own `ServiceBinding`/
522/// `DurableObjectNamespace` entries already use for library-provided names.
523pub(super) fn cap_ref_ty(
524 c: &bynk_model::CapRefIr,
525 info: &bynk_check::resolver::CrossContextInfo,
526) -> bynk_ts::TsType {
527 match c.context.as_deref().and_then(|p| info.resolve_prefix(p)) {
528 Some(consumed) => {
529 bynk_ts::TsType::named(format!("{}.{}", qualified_to_ns(&consumed), c.name))
530 }
531 // v0.17: a bare flattened capability (`consumes U { Cap }`) keeps its
532 // interface in the consumed unit's module — qualify the type there.
533 None => match info.flattened_caps.get(&c.name) {
534 Some(unit) => bynk_ts::TsType::named(format!("{}.{}", qualified_to_ns(unit), c.name)),
535 None => bynk_ts::TsType::named(c.name.clone()),
536 },
537 }
538}
539
540/// Events track, slice 0 (spine #936): does any service or agent handler in
541/// this commons emit — the same predicate `block_uses_emit` answers per
542/// handler body, rolled up to "does the context-level `__eventsDispatch`
543/// deps field need to exist at all." Syntactic, like its sibling: a false
544/// positive here just adds an unused interface field, not a miscompile.
545pub(crate) fn commons_uses_emit(commons: &TypedCommons) -> bool {
546 commons.commons.items.iter().any(|item| {
547 item.handlers()
548 .iter()
549 .any(|h| bynk_model::block_uses_emit(&h.body, &commons.callees))
550 })
551}
552
553/// v0.15: collect the cross-context capabilities a context's **handlers**
554/// (service + agent) reference via `given B.Cap`, as `(deps_key,
555/// consumed_context)` pairs, deduplicated by key and sorted. These become
556/// top-level deps fields (handlers access them as `deps.<key>`). Capabilities
557/// used only by a provider are injected into that provider's constructor
558/// instead, so they are excluded here.
559pub(crate) fn cross_context_caps_used(
560 commons: &TypedCommons,
561 ctx: &EmitProjectCtx,
562) -> Vec<(String, String)> {
563 let info = &ctx.cross_context;
564 let mut seen: std::collections::BTreeMap<String, String> = std::collections::BTreeMap::new();
565 let givens = commons
566 .commons
567 .items
568 .iter()
569 .flat_map(CommonsItem::handlers)
570 .map(bynk_model::lower_handler_given_ir)
571 .chain(std::iter::once(sibling_agent_givens(commons, ctx)));
572 for given in givens {
573 for c in given {
574 // Events track, slice 0 (spine #936): `Events.emit` is
575 // intercepted entirely at the call site (release-at-commit
576 // buffering) and never calls through a constructed provider
577 // — unlike every other capability, there is no
578 // `EventsProvider` for compose to build, so the first-party
579 // `Events` must not appear in any context's deps interface.
580 if bynk_check::firstparty::resolve(&c.name, &ctx.commons_name, &info.flattened_caps)
581 == Some(FirstPartyCap::Events)
582 {
583 continue;
584 }
585 if let Some(prefix) = &c.context {
586 if let Some(consumed) = info.resolve_prefix(prefix) {
587 seen.entry(c.name.clone()).or_insert(consumed);
588 }
589 } else if let Some(unit) = info.flattened_caps.get(&c.name) {
590 // v0.17: a bare flattened capability is a cross-unit dep too.
591 seen.entry(c.name.clone()).or_insert_with(|| unit.clone());
592 }
593 }
594 }
595 seen.into_iter().collect()
596}
597
598/// v0.15: the set of consumed contexts whose capabilities this context
599/// references anywhere (handlers *or* providers), so their namespaces are
600/// imported for the capability interface types.
601pub(crate) fn cross_context_cap_namespaces(
602 commons: &TypedCommons,
603 ctx: &EmitProjectCtx,
604) -> std::collections::BTreeSet<String> {
605 let info = &ctx.cross_context;
606 let mut out = std::collections::BTreeSet::new();
607 let mut collect = |given: Vec<bynk_model::CapRefIr>| {
608 for c in given {
609 if let Some(prefix) = &c.context
610 && let Some(consumed) = info.resolve_prefix(prefix)
611 {
612 out.insert(consumed);
613 } else if c.context.is_none()
614 // v0.17: a bare flattened capability imports its interface from
615 // the consumed unit's module.
616 && let Some(unit) = info.flattened_caps.get(&c.name)
617 {
618 out.insert(unit.clone());
619 }
620 }
621 };
622 for item in &commons.commons.items {
623 match item {
624 CommonsItem::Service(s) => s
625 .handlers
626 .iter()
627 .for_each(|h| collect(bynk_model::lower_handler_given_ir(h))),
628 CommonsItem::Agent(a) => a
629 .handlers
630 .iter()
631 .for_each(|h| collect(bynk_model::lower_handler_given_ir(h))),
632 CommonsItem::Provider(p) => collect(bynk_model::lower_provider_given_ir(p)),
633 // #2912: a function's `given` names its capability in `deps` too.
634 CommonsItem::Fn(f) => collect(bynk_model::lower_fn_given_ir(f)),
635 CommonsItem::Type(_)
636 | CommonsItem::Capability(_)
637 | CommonsItem::Actor(_)
638 | CommonsItem::Messages(_)
639 | CommonsItem::Event(_)
640 | CommonsItem::Asset(_)
641 | CommonsItem::Embed(_)
642 | CommonsItem::Const(_) => {}
643 }
644 }
645 collect(sibling_agent_givens(commons, ctx));
646 // S4a (#1966): a derived capability's alias names its base's interface in
647 // the base's module.
648 out.extend(
649 commons
650 .commons
651 .items
652 .iter()
653 .filter_map(CommonsItem::as_capability)
654 .filter_map(|c| c.derived.as_ref())
655 .filter_map(|d| info.flattened_caps.get(&d.base.name).cloned()),
656 );
657 out
658}
659
660/// #1820: the `given` capabilities of every agent this file constructs that
661/// a sibling file of its context declares. A handler here forwards its `deps`
662/// to that agent (`effective_given`), so its `deps` name them although no
663/// declaration in this file does. Empty unless the context is split across
664/// files: an agent this file declares is walked with the file's own items.
665fn sibling_agent_givens(commons: &TypedCommons, ctx: &EmitProjectCtx) -> Vec<bynk_model::CapRefIr> {
666 let declared_here: HashSet<&str> = commons
667 .commons
668 .items
669 .iter()
670 .filter_map(CommonsItem::as_agent)
671 .map(|a| a.name.name.as_str())
672 .collect();
673 let constructed: std::collections::BTreeSet<&str> = commons
674 .callees
675 .values()
676 .filter_map(|c| {
677 if let bynk_check::checker::Callee::AgentInit(a) = c
678 && !declared_here.contains(a.as_str())
679 {
680 Some(a.as_str())
681 } else {
682 None
683 }
684 })
685 .collect();
686 let mut out = Vec::new();
687 for agent in constructed {
688 let Some(methods) = ctx.agent_method_givens.get(agent) else {
689 continue;
690 };
691 let mut methods: Vec<_> = methods.iter().collect();
692 methods.sort_by_key(|(m, _)| *m);
693 for (_, caps) in methods {
694 out.extend(caps.iter().cloned());
695 }
696 }
697 out
698}
699
700/// #527: a handler's *effective* `given` list — its declared capabilities
701/// plus those required by the local-agent methods its body calls (recorded
702/// during lowering). Compose always instantiates the full capability union
703/// into the runtime deps value, so this widening only brings the deps *type*
704/// in line with the value; without it, forwarding `deps` to an agent method
705/// with `given` failed `tsc --strict` (and under-documented the dependency).
706pub(super) fn effective_given(
707 declared: &[bynk_model::CapRefIr],
708 cx: &LowerCtx<'_>,
709) -> Vec<bynk_model::CapRefIr> {
710 let mut out = declared.to_vec();
711 let have: HashSet<String> = declared.iter().map(|c| c.name.clone()).collect();
712 for (key, cap) in cx.agent_given_caps_used().into_iter().flatten() {
713 if !have.contains(key) {
714 out.push(cap.clone());
715 }
716 }
717 // Events track, slice 0 (spine #936): `Events.emit` is intercepted
718 // entirely at the call site (release-at-commit buffering; see the
719 // `Events`/`emit` special case in `lower.rs`) and never calls through a
720 // constructed provider — unlike every other capability, there is no
721 // `EventsProvider` for compose to build. So `Events` must not appear in
722 // `deps` at all, or compose would need to construct a provider that
723 // doesn't exist. Filtered the same way #934 distinguishes a genuine
724 // first-party `Events` from an unrelated same-named capability.
725 out.retain(|c| cx.first_party_cap(&c.name) != Some(FirstPartyCap::Events));
726 out
727}
728
729/// Review of #1469: returns the bare member list, not `TsType::Object(members)`
730/// — every real caller immediately widens it further (`append_deps_field`)
731/// before wrapping it as the `deps` parameter's own type, and threading
732/// `Vec<TsTypeMember>` end to end lets that widening take `&mut Vec<...>`
733/// directly, with no `TsType::Object` match arm (and no panic path for the
734/// "found something else" case that can't actually happen) in between.
735pub(super) fn build_deps_object_ty_with_surface(
736 given: &[bynk_model::CapRefIr],
737 cx: &LowerCtx<'_>,
738 cross_context: &bynk_check::resolver::CrossContextInfo,
739 target: BuildTarget,
740) -> Vec<bynk_ts::TsTypeMember> {
741 let mut members: Vec<bynk_ts::TsTypeMember> = given
742 .iter()
743 .map(|c| bynk_ts::TsTypeMember::prop(c.name.clone(), cap_ref_ty(c, cross_context)))
744 .collect();
745 match target {
746 BuildTarget::Bundle => {
747 // #1960: an agent method this body calls may itself call a
748 // consumed service, reading the `surface` this body hands it —
749 // the bundle counterpart of the whole `env` a Workers body
750 // threads whenever it constructs an agent.
751 if cx.cross_context_used()
752 || (cx.agents_instantiated() && has_consumed_service(cross_context))
753 {
754 members.push(bynk_ts::TsTypeMember::prop(
755 "surface",
756 surface_ty(cross_context),
757 ));
758 }
759 }
760 BuildTarget::Workers => {
761 // v0.9.2: in workers mode `env` carries both consumed-context
762 // Service Bindings and the local agents' Durable Object namespaces.
763 // It is threaded into deps whenever the handler makes a
764 // cross-context call or instantiates an agent.
765 if cx.cross_context_used() || cx.agents_instantiated() {
766 let agents = if cx.agents_instantiated() {
767 sorted_local_agents(cx)
768 } else {
769 Vec::new()
770 };
771 members.push(bynk_ts::TsTypeMember::prop(
772 "env",
773 workers_env_ty(&cx.cross_contexts_called(), &agents),
774 ));
775 }
776 }
777 }
778 members
779}
780
781/// Local agent names in this commons, sorted — the DO bindings `env` exposes
782/// in workers mode. #1820: every file's of the context (`cx.local_agents`),
783/// not only this file's: a handler constructing an agent declared in a
784/// sibling file passes the Worker's `env` to that agent's factory.
785fn sorted_local_agents(cx: &LowerCtx<'_>) -> Vec<String> {
786 let names: std::collections::BTreeSet<String> = cx
787 .commons()
788 .commons
789 .items
790 .iter()
791 .filter_map(CommonsItem::as_agent)
792 .map(|a| a.name.name.clone())
793 .chain(cx.local_agents.iter().cloned())
794 .collect();
795 names.into_iter().collect()
796}
797
798/// Workers-mode deps.env shape: the bindings handlers reach
799/// ([`crate::emitter::bindings::handler_bindings`], #1950) — one Service
800/// Binding per consumed context the handler calls and one Durable Object
801/// namespace per local agent.
802pub(super) fn workers_env_ty(called: &[String], agents: &[String]) -> bynk_ts::TsType {
803 // #1961: only a consumed context this handler **calls**
804 // (`lower_workers_cross_context_call`), the one thing a handler reaches
805 // through `env`. The Worker binds exactly the contexts some body of it
806 // calls (`WorkerBindings`), a superset of any one
807 // handler's, so `compose`'s `env` always satisfies this type. A unit
808 // consumed for capabilities, types or events only has no binding at all —
809 // an adapter is not a Worker, and a context whose services go uncalled
810 // need not be bound (binding it made an event subscriber and its
811 // publisher bind each other, which no deploy order satisfies).
812 let members = crate::emitter::bindings::handler_bindings(called, agents)
813 .into_iter()
814 .map(|b| {
815 let ty = crate::emitter::wrangler::binding_ts_type(&b.source);
816 bynk_ts::TsTypeMember::prop(b.name, bynk_ts::TsType::named(ty))
817 })
818 .collect();
819 bynk_ts::TsType::Object(members)
820}
821
822/// v0.15: true when at least one consumed context exposes services (and thus
823/// a `__makeSurface`). A context may now consume another purely for its
824/// capabilities, in which case there is no surface to thread.
825fn has_consumed_service(cross_context: &bynk_check::resolver::CrossContextInfo) -> bool {
826 cross_context
827 .consumed_services
828 .values()
829 .any(|svcs| !svcs.is_empty())
830}
831
832/// Build the TS type for the `surface` field in deps, naming each consumed
833/// context by its surface key plus the consumed context's __makeSurface type.
834/// Only service-bearing consumed contexts contribute (a capability-only
835/// consumed context has no `__makeSurface`).
836///
837/// Arc F, slice 4 (#1463): `ReturnType<T>` itself is representable generically
838/// (`TsType::named_with_args`, review of #1469) — the real gap is its own
839/// type argument here, `typeof {ns}.__makeSurface`, whose `typeof` operand
840/// isn't an ordinary type at all and has no algebra member of its own.
841/// `Named` carries only that opaque operand text now, one level narrower
842/// than the whole expression this used to wrap as one string.
843fn surface_ty(cross_context: &bynk_check::resolver::CrossContextInfo) -> bynk_ts::TsType {
844 let mut entries: Vec<(String, String)> = Vec::new();
845 // Use alias if present, else the last segment of the qualified name.
846 // Order: stable (sorted) so the diff is deterministic.
847 let mut consumed_sorted: Vec<String> = cross_context
848 .consumed_services
849 .iter()
850 .filter(|(_, svcs)| !svcs.is_empty())
851 .map(|(q, _)| q.clone())
852 .collect();
853 consumed_sorted.sort();
854 // Reverse lookup: consumed-context qualified name → alias.
855 let mut alias_for: HashMap<String, String> = HashMap::new();
856 for (alias, target) in &cross_context.aliases {
857 alias_for.insert(target.clone(), alias.clone());
858 }
859 for q in &consumed_sorted {
860 let key = alias_for
861 .get(q)
862 .cloned()
863 .unwrap_or_else(|| q.rsplit('.').next().unwrap_or(q.as_str()).to_string());
864 let ns = qualified_to_ns(q);
865 entries.push((key, format!("typeof {ns}.__makeSurface")));
866 }
867 bynk_ts::TsType::Object(
868 entries
869 .into_iter()
870 .map(|(k, v)| {
871 bynk_ts::TsTypeMember::prop(
872 k,
873 bynk_ts::TsType::named_with_args(
874 "globalThis.ReturnType",
875 vec![bynk_ts::TsType::named(v)],
876 ),
877 )
878 })
879 .collect(),
880 )
881}
882
883/// #2058: each type name this unit reaches from a consumed *context*, mapped
884/// to the namespace the module names that context's types under
885/// (`ev_store`). A literal admitted to such a refined type is cast to
886/// `ev_store.Code`, not a bare `Code` nothing imports.
887pub(crate) fn consumed_type_ns(ctx: &EmitProjectCtx) -> HashMap<String, String> {
888 ctx.imported_from_kind
889 .iter()
890 .filter(|(_, kind)| **kind == UnitKind::Context)
891 .filter_map(|(name, _)| {
892 let owner = ctx.imported_from.get(name)?;
893 Some((name.clone(), qualified_to_ns(owner)))
894 })
895 .collect()
896}
897
898/// Turn a qualified context name (e.g. `commerce.payment`) into the JS
899/// namespace ident used in `import * as <ns>` (`commerce_payment`).
900pub(crate) fn qualified_to_ns(q: &str) -> String {
901 q.replace('.', "_")
902}
903
904/// #1759: the identifier a generated **test** module imports a unit as
905/// (`import * as __ns_greet from …`). A test module destructures a unit's
906/// values out of this namespace (`const { greet } = __ns_greet;`), so the
907/// namespace can't take `qualified_to_ns`'s bare name: a context `greet`
908/// declaring `fn greet` would shadow its own import and read `greet` in its
909/// temporal dead zone. The reserved `__ns_` prefix can't be a user identifier.
910/// Every test-module namespace reference goes through this, in `tests_emit`
911/// and in lowering that runs `in_test_scaffold()`.
912pub fn test_scaffold_ns(q: &str) -> String {
913 format!("__ns_{}", qualified_to_ns(q))
914}
915
916/// The PascalCase name a context uses for its generated `Deps` interface:
917/// `shortener.links` → `ShortenerLinks`.
918pub fn context_pascal(name: &str) -> String {
919 name.split('.')
920 .map(|seg| {
921 let mut chars = seg.chars();
922 match chars.next() {
923 Some(c) => c.to_uppercase().collect::<String>() + chars.as_str(),
924 None => String::new(),
925 }
926 })
927 .collect()
928}
929
930/// Emit the per-context `<Ctx>Deps` interface (v0.9.2 §4): the providers the
931/// context contributes plus the surfaces of any consumed contexts. Replaces
932/// the fragile `Parameters<typeof svc.call>[1]` indexing, which only resolved
933/// correctly for single-argument service operations.
934/// Arc F slice 3 (#1453): builds a real `bynk_ts::TsDecl::Interface`, the
935/// same `readonly`-member shape `emit_agent`'s own state interface already
936/// establishes (`emit_agent.rs:4436-4444`) — return contract stays
937/// the interface's own name too (used as a plain `TsType::named(deps_name)`
938/// type reference by `emit_make_surface`, its one caller); since 1A.32c-1 it
939/// returns the declaration as a node, not printed text.
940///
941/// Two fields stay opaque `TsType::named(...)` text, deliberately, not
942/// guessed: `surface`'s type comes from `surface_ty`, itself still
943/// `String`-returning (#1449's own bucket-4 residual, out of this slice's
944/// scope) — wrapping its output opaquely is the established "carry an
945/// unconverted sibling's own text" pattern. `__eventsDispatch`'s function
946/// type needs a *named* parameter (`events`); `bynk_ts::TsType::Fn` only
947/// supports positional parameter names (`a0`, `a1`, …, confirmed against its
948/// own printer tests) — the same real, already-named algebra gap
949/// `ts_type_ref_to_ts_type`'s own `TypeRef::Query` arm (`emitter.rs`)
950/// resolved by pre-rendering and wrapping as opaque `Named` text rather than
951/// widening `TsType::Fn` for one call site.
952fn emit_context_deps_interface(
953 commons: &TypedCommons,
954 ctx: &EmitProjectCtx,
955) -> (bynk_ts::TsStmt, String) {
956 let deps_name = format!("__{}Deps", context_pascal(&commons.commons.name.joined()));
957 let mut members: Vec<bynk_ts::TsTypeMember> = commons
958 .commons
959 .items
960 .iter()
961 .filter_map(CommonsItem::as_capability)
962 .map(|c| {
963 bynk_ts::TsTypeMember::readonly_prop(
964 c.name.name.clone(),
965 bynk_ts::TsType::named(c.name.name.clone()),
966 )
967 })
968 .collect();
969 // #1820: and the capabilities a sibling file of a split context declares.
970 // A service here may call an agent there whose methods are `given` one,
971 // and its handler's `deps` then names it (`effective_given`).
972 let mut sibling_caps: Vec<&String> = ctx
973 .file_decl_index
974 .capabilities
975 .iter()
976 .filter(|(_, path)| **path != ctx.source_path)
977 .map(|(cap, _)| cap)
978 .collect();
979 sibling_caps.sort();
980 for cap in sibling_caps {
981 members.push(bynk_ts::TsTypeMember::readonly_prop(
982 cap.clone(),
983 bynk_ts::TsType::named(cap.clone()),
984 ));
985 }
986 // v0.15: cross-context capabilities the context consumes appear in deps,
987 // typed against the providing context's namespace.
988 for (key, consumed) in cross_context_caps_used(commons, ctx) {
989 let ty = bynk_ts::TsType::named(format!("{}.{key}", qualified_to_ns(&consumed)));
990 members.push(bynk_ts::TsTypeMember::readonly_prop(key, ty));
991 }
992 if !ctx.cross_context.consumed_contexts.is_empty() && has_consumed_service(&ctx.cross_context) {
993 // Arc F, slice 4 (#1463): `surface_ty` now returns a real `TsType`
994 // directly — closes the residual Arc F slice 3 (#1453) named here
995 // ("kept as opaque `TsType::named(...)` text... because its own
996 // source, `surface_ty`, is still `String`-returning").
997 members.push(bynk_ts::TsTypeMember::readonly_prop(
998 "surface",
999 surface_ty(&ctx.cross_context),
1000 ));
1001 }
1002 // Events track, slice 0 (spine #936): a context with any handler that
1003 // emits needs `__eventsDispatch` threaded all the way from `__makeSurface`
1004 // down to that handler's own `deps` param (`emit_service`/`emit_agent`'s
1005 // matching field) — otherwise `svc.call(args, deps)` inside `__makeSurface`
1006 // fails to typecheck, since `deps`'s static type there is this interface,
1007 // not whatever compose actually constructs.
1008 let is_first_party_events = bynk_check::firstparty::resolve(
1009 FirstPartyCap::Events.name(),
1010 &ctx.commons_name,
1011 &ctx.cross_context.flattened_caps,
1012 ) == Some(FirstPartyCap::Events);
1013 if is_first_party_events && commons_uses_emit(commons) {
1014 members.push(bynk_ts::TsTypeMember::readonly_prop(
1015 "__eventsDispatch",
1016 bynk_ts::TsType::named(format!(
1017 "(events: globalThis.Array<{}>) => globalThis.Promise<void>",
1018 crate::emitter::EVENTS_WIRE_EVENT_TS_TYPE
1019 )),
1020 ));
1021 }
1022 // #2683: a surface `on call` handler that calls `within` (or sends with
1023 // `detach`) forwards `deps` to a handler that requires `__exec`, so the
1024 // surface's `deps` carry it; the compose root supplies it.
1025 if commons.commons.items.iter().any(|i| {
1026 i.as_service().is_some_and(|s| {
1027 s.handlers
1028 .iter()
1029 .any(|h| crate::emitter::call_handler_needs_exec(&commons.exec_plan, h))
1030 })
1031 }) {
1032 members.push(bynk_ts::TsTypeMember::readonly_prop(
1033 "__exec",
1034 bynk_ts::TsType::Object(vec![bynk_ts::TsTypeMember::method(
1035 "waitUntil",
1036 vec![bynk_ts::TsParam::new(
1037 "promise".to_string(),
1038 Some(bynk_ts::TsType::named_with_args(
1039 "globalThis.Promise",
1040 vec![bynk_ts::TsType::named("unknown")],
1041 )),
1042 )],
1043 bynk_ts::TsType::named("void"),
1044 )]),
1045 ));
1046 }
1047 let interface_decl = bynk_ts::TsStmt::decl(
1048 bynk_ts::TsDecl::Export(Box::new(bynk_ts::TsDecl::Interface {
1049 name: deps_name.clone(),
1050 type_params: Vec::new(),
1051 members,
1052 })),
1053 None,
1054 );
1055 // #1486: no trailing blank baked in here — the printer's automatic
1056 // top-level spacing policy supplies the single blank before whatever
1057 // follows this interface.
1058 (interface_decl, deps_name)
1059}
1060
1061/// v0.54 (#655): whether any of `services` declares an `on call … by c: Caller`
1062/// handler, whose emitted `deps` carries the calling context's qualified name as
1063/// its `CallerId` identity (ADR 0092). This is the *single* predicate both
1064/// bundle caller-identity seams consult — `emit_make_surface` (which adds the
1065/// `__caller` parameter) and the compose root (which passes the name) — so the
1066/// two can never disagree on which providers thread a caller. `caller_binder_for`
1067/// self-guards `HandlerKind::Call`, so no kind filter is needed or wanted here.
1068pub fn any_service_binds_caller<'a>(
1069 services: impl IntoIterator<Item = &'a ServiceDecl>,
1070 actors: &HashMap<String, ActorDecl>,
1071) -> bool {
1072 // I3 (#1971): a `call` sum names its caller too (`who`), and in bundle
1073 // mode every caller is a context.
1074 services.into_iter().any(|s| {
1075 s.handlers.iter().any(|h| {
1076 bynk_check::actors::caller_binder_for(h, actors).is_some()
1077 || bynk_check::actors::call_admission_for(h, actors)
1078 .is_some_and(|a| a.sum.is_some())
1079 })
1080 })
1081}
1082
1083/// Emit the `__makeSurface(deps)` function for a context that exposes
1084/// services to other contexts (v0.6 §6.3 / §6.4).
1085///
1086/// Arc C, slice 18 (#1364): closes the `emit_make_surface` half of step (8)
1087/// of the design pass's own decomposition order (#1331) — the "cross-context
1088/// lowering cluster" the same step also names stays a separate, deferred
1089/// remainder (a genuinely different, harder shape: real cross-module codec
1090/// lowering, not top-level structure construction), the same "split when a
1091/// named remainder is harder" precedent steps (4)/(6) already established.
1092/// Converts fully — no opaque carve-out: every shape this function needs
1093/// (`bynk_ts::TsDecl::Function`, `TsObjectEntry::Method`/`Spread`,
1094/// `TsStmt::Return`, `TsExpr::Call`/`multiline_object_entries`) already
1095/// exists in `bynk_ts`, and this function never lowers an expression through
1096/// `LowerCtx` (no `source_map` parameter reaches it), so there is no
1097/// sub-builder/merge machinery to get right here. `emit_context_deps_interface`
1098/// converted later (Arc F slice 3, #1453) — it still returns `String` (just
1099/// the interface's own name, used below as a plain `TsType::named` type
1100/// reference), but the interface declaration itself is a real
1101/// `bynk_ts::TsDecl::Interface` now, not `writeln!`-built text.
1102/// #1478: returns real [`bynk_ts::TsStmt`]s (was `out: &mut String`).
1103/// `emit_context_deps_interface` returns the interface declaration as a node
1104/// (1A.32c-1), so it is the surface's first statement.
1105pub(crate) fn emit_make_surface(
1106 commons: &TypedCommons,
1107 ctx: &EmitProjectCtx,
1108) -> Vec<bynk_ts::TsStmt> {
1109 let services: Vec<&ServiceDecl> = commons
1110 .commons
1111 .items
1112 .iter()
1113 .filter_map(CommonsItem::as_service)
1114 .collect();
1115 if services.is_empty() {
1116 return Vec::new();
1117 }
1118 let (deps_decl, deps_name) = emit_context_deps_interface(commons, ctx);
1119 let mut stmts = vec![deps_decl];
1120 // v0.54 (#655): an `on call … by c: Caller` handler reads a live `CallerId`
1121 // (the calling context's qualified name) threaded through `deps.identity`.
1122 // In bundle mode the compose root supplies that name to `__makeSurface` as a
1123 // second `__caller` argument — the analogue of the `X-Bynk-Caller` header a
1124 // Worker reads at its entry (ADR 0092). Only a context with such a handler
1125 // takes the extra parameter, so a caller-free surface is byte-unchanged. The
1126 // shared `any_service_binds_caller` predicate is what keeps this seam and the
1127 // compose root in lockstep on which providers get the extra argument.
1128 let binds_caller =
1129 |h: &Handler| bynk_check::actors::caller_binder_for(h, &ctx.actors).is_some();
1130 let any_caller = any_service_binds_caller(services.iter().copied(), &ctx.actors);
1131 let mut params = vec![bynk_ts::TsParam::new(
1132 "deps".to_string(),
1133 Some(bynk_ts::TsType::named(deps_name)),
1134 )];
1135 if any_caller {
1136 params.push(bynk_ts::TsParam::new(
1137 "__caller".to_string(),
1138 Some(bynk_ts::TsType::named("string")),
1139 ));
1140 }
1141 let mut entries: Vec<bynk_ts::TsObjectEntry> = Vec::new();
1142 for s in &services {
1143 // For each handler kind currently only `call`. We bind it as a
1144 // method on the surface with the deps captured.
1145 let handler = s
1146 .handlers
1147 .iter()
1148 .find(|h| matches!(lower_handler_kind_ir(&h.kind), IrHandlerKind::Call));
1149 let Some(h) = handler else { continue };
1150 let is_async = is_effectful_return(&h.return_type);
1151 // #2696: the method body reads `<service>` after the parameters bind, so a
1152 // user parameter spelled like the service would shadow it. Rename the
1153 // user's binder (hygienically), never the generated name, so every other
1154 // surface stays byte-identical. `deps` needs no check here: `ts_ident`
1155 // already maps it to `__id_deps`. `__caller` needs none either: a
1156 // `__`-prefixed name can't be a user identifier.
1157 let surface_param = |name: &str| -> String {
1158 let id = ts_ident(name);
1159 if id == s.name.name {
1160 format!("__id_{id}")
1161 } else {
1162 id
1163 }
1164 };
1165 let method_params: Vec<bynk_ts::TsParam> = h
1166 .params
1167 .iter()
1168 .map(|p| {
1169 bynk_ts::TsParam::new(
1170 surface_param(&p.name.name),
1171 Some(ts_type_ref_to_ts_type(&p.type_ref, None)),
1172 )
1173 })
1174 .collect();
1175 let mut call_args: Vec<bynk_ts::TsExpr> = h
1176 .params
1177 .iter()
1178 .map(|p| bynk_ts::TsExpr::Ident(surface_param(&p.name.name)))
1179 .collect();
1180 // A Caller-binding handler's `deps.identity` is the caller name the
1181 // compose root threaded in; every other handler forwards `deps` verbatim.
1182 //
1183 // I3 (#1971): in bundle mode every caller is a context, never a
1184 // foreign caller, so a `call` sum resolves to `Caller` with that name,
1185 // and a handler that admits only foreign callers is never admitted.
1186 let admission = bynk_check::actors::call_admission_for(h, &ctx.actors);
1187 if admission.as_ref().is_some_and(|a| !a.contexts) {
1188 entries.push(bynk_ts::TsObjectEntry::Method {
1189 name: s.name.name.clone(),
1190 is_async,
1191 generics: Vec::new(),
1192 params: method_params,
1193 return_type: Some(ts_type_ref_to_ts_type(&h.return_type, None)),
1194 doc: None,
1195 inline: false,
1196 body: vec![bynk_ts::TsStmt::throw_stmt(
1197 bynk_ts::TsExpr::New {
1198 callee: Box::new(bynk_ts::TsExpr::Ident("globalThis.Error".to_string())),
1199 args: vec![bynk_ts::TsExpr::Lit(bynk_ts::TsLit::Str(format!(
1200 "`{}` admits only foreign callers, and a context is not one",
1201 s.name.name
1202 )))],
1203 },
1204 None,
1205 )],
1206 span: None,
1207 });
1208 continue;
1209 }
1210 let internal_tag = admission
1211 .as_ref()
1212 .map_or_else(|| "Caller".to_string(), |a| a.internal_tag().to_string());
1213 let deps_arg = if admission.is_some_and(|a| a.sum.is_some()) {
1214 bynk_ts::TsExpr::object_entries(vec![
1215 bynk_ts::TsObjectEntry::Spread(bynk_ts::TsExpr::Ident("deps".to_string())),
1216 bynk_ts::TsObjectEntry::prop(
1217 "who".to_string(),
1218 bynk_ts::TsExpr::object(vec![
1219 (
1220 "tag".to_string(),
1221 bynk_ts::TsExpr::Lit(bynk_ts::TsLit::Str(internal_tag)),
1222 ),
1223 (
1224 "identity".to_string(),
1225 bynk_ts::TsExpr::Ident("__caller".to_string()),
1226 ),
1227 ]),
1228 ),
1229 ])
1230 } else if binds_caller(h) {
1231 bynk_ts::TsExpr::object_entries(vec![
1232 bynk_ts::TsObjectEntry::Spread(bynk_ts::TsExpr::Ident("deps".to_string())),
1233 bynk_ts::TsObjectEntry::prop(
1234 "identity".to_string(),
1235 bynk_ts::TsExpr::Ident("__caller".to_string()),
1236 ),
1237 ])
1238 } else {
1239 bynk_ts::TsExpr::Ident("deps".to_string())
1240 };
1241 call_args.push(deps_arg);
1242 let call = bynk_ts::TsExpr::Call {
1243 callee: Box::new(bynk_ts::TsExpr::Member {
1244 object: Box::new(bynk_ts::TsExpr::Ident(s.name.name.clone())),
1245 property: "call".to_string(),
1246 }),
1247 args: call_args,
1248 };
1249 entries.push(bynk_ts::TsObjectEntry::Method {
1250 name: s.name.name.clone(),
1251 is_async,
1252 generics: Vec::new(),
1253 params: method_params,
1254 return_type: Some(ts_type_ref_to_ts_type(&h.return_type, None)),
1255 doc: None,
1256 inline: false,
1257 body: vec![bynk_ts::TsStmt::return_stmt(Some(call), None)],
1258 span: None,
1259 });
1260 }
1261 let func_decl = bynk_ts::TsStmt::decl(
1262 bynk_ts::TsDecl::Export(Box::new(bynk_ts::TsDecl::Function {
1263 name: "__makeSurface".to_string(),
1264 generics: Vec::new(),
1265 params,
1266 return_type: None,
1267 body: vec![bynk_ts::TsStmt::return_stmt(
1268 Some(bynk_ts::TsExpr::multiline_object_entries(entries)),
1269 None,
1270 )],
1271 is_async: false,
1272 inline: false,
1273 })),
1274 None,
1275 );
1276 stmts.push(func_decl);
1277 // #1486: no explicit trailing blank stmt here — the printer's automatic
1278 // top-level spacing policy supplies the single blank before whatever
1279 // follows (never import-kind at this function's own call site, so
1280 // never exempted from it).
1281 stmts
1282}
1283
1284pub(crate) fn flatten_emit_ident_chain(e: &Expr) -> Option<String> {
1285 match &e.kind {
1286 ExprKind::Ident(id) => Some(id.name.clone()),
1287 ExprKind::FieldAccess { receiver, field } => {
1288 let head = flatten_emit_ident_chain(receiver)?;
1289 Some(format!("{head}.{}", field.name))
1290 }
1291 ExprKind::IntLit { .. }
1292 | ExprKind::FloatLit { .. }
1293 | ExprKind::DecimalLit { .. }
1294 | ExprKind::DurationLit { .. }
1295 | ExprKind::StrLit(_)
1296 | ExprKind::InterpStr(_)
1297 | ExprKind::BoolLit(_)
1298 | ExprKind::Call { .. }
1299 | ExprKind::Lambda(_)
1300 | ExprKind::BinOp(..)
1301 | ExprKind::UnaryOp(..)
1302 | ExprKind::Paren(_)
1303 | ExprKind::Block(_)
1304 | ExprKind::If { .. }
1305 | ExprKind::Ok(_)
1306 | ExprKind::Err(_)
1307 | ExprKind::Question(_)
1308 | ExprKind::RecordConstruction { .. }
1309 | ExprKind::MethodCall { .. }
1310 | ExprKind::Match { .. }
1311 | ExprKind::Is { .. }
1312 | ExprKind::Some(_)
1313 | ExprKind::None
1314 | ExprKind::UnitLit
1315 | ExprKind::RecordSpread { .. }
1316 | ExprKind::EffectPure(_)
1317 | ExprKind::Expect(_)
1318 | ExprKind::Val { .. }
1319 | ExprKind::Wire(_)
1320 | ExprKind::ListLit(..)
1321 | ExprKind::Observation(_)
1322 | ExprKind::Faults(_)
1323 | ExprKind::Trace { .. } => None,
1324 }
1325}
1326
1327/// The TS type of a resolved actor sum (`deps.who`): each member's tagged
1328/// shape, `{ tag: "User", identity: UserId }` or `{ tag: "Visitor" }`, joined
1329/// as a union. The HTTP wrapper builds this value and the WebSocket Durable
1330/// Object rebuilds it, so both read the one shape.
1331pub(super) fn actor_sum_ts_union(members: &[bynk_check::actors::SumMember]) -> bynk_ts::TsType {
1332 bynk_ts::TsType::union(
1333 members
1334 .iter()
1335 .map(|m| match m.identity_type() {
1336 Some(id) => tag_member(&m.actor_name, Some(bynk_ts::TsType::named(id))),
1337 None => tag_member(&m.actor_name, None),
1338 })
1339 .collect(),
1340 )
1341}
1342
1343/// One member of an actor sum: `{ tag: "<name>"; identity: <ty> }`, or `{ tag: "<name>" }`.
1344fn tag_member(tag: &str, identity: Option<bynk_ts::TsType>) -> bynk_ts::TsType {
1345 let mut props = vec![bynk_ts::TsTypeMember::prop(
1346 "tag",
1347 bynk_ts::TsType::string_literal(tag),
1348 )];
1349 props.extend(identity.map(|id| bynk_ts::TsTypeMember::prop("identity", id)));
1350 bynk_ts::TsType::Object(props)
1351}
1352
1353/// I3 (#1971): the TypeScript type of a `call` handler's resolved actor sum
1354/// (`deps.who`): `Caller` carries the calling context's name, a foreign
1355/// caller is its actor alone. A `TsType` node, as the HTTP sum's union is.
1356pub(crate) fn call_sum_ts_type(members: &[bynk_check::actors::CallSumMember]) -> bynk_ts::TsType {
1357 bynk_ts::TsType::union(
1358 members
1359 .iter()
1360 .map(|m| match m {
1361 bynk_check::actors::CallSumMember::Caller => {
1362 tag_member("Caller", Some(bynk_ts::TsType::named("string")))
1363 }
1364 bynk_check::actors::CallSumMember::Foreign(f) => tag_member(&f.actor, None),
1365 bynk_check::actors::CallSumMember::Refined(name, _) => {
1366 tag_member(name, Some(bynk_ts::TsType::named("string")))
1367 }
1368 })
1369 .collect(),
1370 )
1371}