Skip to main content

bynk_emit/emitter/compose/
workers.rs

1//! The Cloudflare Workers composition root (v0.8 §4.5, v0.9 §5.1).
2//!
3//! Each Worker's `compose.ts` exports a `compose(env)` function that
4//! assembles the context's deps and returns the surface the entry point
5//! invokes — `on call` services for the internal Service Binding protocol
6//! plus `on http` route wrappers for the external HTTP router.
7//!
8//! Arc C slice 3 (#1321): `emit_worker_compose` and its private helpers build
9//! a real `bynk_ts::TsProgram` directly instead of `writeln!`-ing a `String`.
10//! Back-half paydown 1B.1a moved them here from `workers.rs`. Since 1B.1b the
11//! unit and its dependencies come from the [`ComposePlan`]; the order of the
12//! `deps` entries, the `const` per provider, the `__exec` condition, the
13//! cross-capability set, `env`, the session entry and the delivery through the
14//! fan-out are this renderer's own (divergences 1 to 7 of #3928).
15
16use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
17
18use crate::emitter::compose::{ComposePlan, empty_deps};
19
20use crate::emit_model::{ImportExt, LocaleNegotiationArgs};
21use crate::emitter::RuntimeUse;
22use crate::emitter::bindings::{BindingSource, WorkerBinding, events_fanout_binding};
23use crate::emitter::workers::*;
24use crate::emitter::wrangler::binding_ts_type;
25use crate::ts_build::{as_expr, call, const_, ident, member, method_call, return_, str_lit};
26use bynk_check::symbols::MessageBundleInfo;
27use bynk_check::symbols::UnitTable;
28use bynk_ts::{
29    TsArrowBody, TsDecl, TsExpr, TsObjectEntry, TsParam, TsProgram, TsStmt, TsType, TsTypeMember,
30};
31
32/// Where `compose.ts` imports the runtime from — it sits two levels below the
33/// out root (`<out>/workers/<worker>/compose.ts`).
34///
35/// The import is built from the finished tree (`derived_worker_runtime_names`)
36/// and inserted after the banner, so this is the one place the specifier is
37/// spelled. It is named so that it cannot drift from the layout the entry and
38/// the other per-Worker modules assume.
39const COMPOSE_RUNTIME_SPECIFIER: &str = "../../runtime.js";
40
41/// The events a publishing handler hands its fan-out. A group's one fan-out
42/// serves every publishing member, so a member names itself on each event
43/// (`publisher`), as two members may declare an event of one name (#3562, G3-1).
44/// A context on a Worker of its own sends them as they are.
45fn fanout_events(context: &str, layout: &bynk_project::worker_layout::WorkerLayout) -> TsExpr {
46    if !layout.is_member(context) {
47        return ident("events");
48    }
49    let tagged = TsExpr::Arrow {
50        params: vec![TsParam::new("e".to_string(), None)],
51        is_async: false,
52        generics: Vec::new(),
53        return_type: None,
54        // Parenthesised, or the braces read as the arrow's body.
55        body: Box::new(TsArrowBody::Expr(Box::new(TsExpr::Paren(Box::new(
56            as_expr(
57                TsExpr::object_entries(vec![
58                    TsObjectEntry::Spread(ident("e")),
59                    TsObjectEntry::prop("publisher".to_string(), str_lit(context.to_string())),
60                ]),
61                TsType::named(crate::emitter::EVENTS_WIRE_EVENT_TS_TYPE),
62            ),
63        ))))),
64    };
65    method_call(ident("events"), "map", vec![tagged])
66}
67
68/// Events track, slice 0 (spine #936, ADR 0284): a publishing handler's
69/// release-at-commit event batch is handed to this context's own fan-out DO
70/// (`env.<bind>` is typed by the `Env` interface, one instance per publishing
71/// context), as `deps.__eventsDispatch`.
72/// Divergence 7 of #3928, delivery: through the fan-out Durable Object (the
73/// Bundle dispatches in-process).
74fn events_dispatch_entry(
75    context: &str,
76    layout: &bynk_project::worker_layout::WorkerLayout,
77) -> TsObjectEntry {
78    let bind = events_fanout_binding().name;
79    let arrow = TsExpr::Arrow {
80        params: vec![TsParam::new(
81            "events".to_string(),
82            Some(TsType::named_with_args(
83                "globalThis.Array",
84                vec![TsType::named(crate::emitter::EVENTS_WIRE_EVENT_TS_TYPE)],
85            )),
86        )],
87        is_async: false,
88        generics: Vec::new(),
89        return_type: None,
90        body: Box::new(TsArrowBody::Expr(Box::new(call(
91            ident("__dispatchToEventsFanout"),
92            vec![member(ident("env"), bind), fanout_events(context, layout)],
93        )))),
94    };
95    TsObjectEntry::prop("__eventsDispatch".to_string(), arrow)
96}
97
98/// Divergence 1 of #3928, the Workers' entry order for the capability part of
99/// `deps`: a plain `String` sort, so `Db` comes before `Db2` (the Bundle sorts
100/// by `key + ":"`, which puts `Db2` first).
101fn deps_caps_in_order(mut caps: Vec<String>) -> Vec<String> {
102    caps.sort();
103    caps
104}
105
106#[allow(clippy::too_many_arguments)]
107pub fn emit_worker_compose(
108    context: &str,
109    plan: &ComposePlan,
110    layout: &bynk_project::worker_layout::WorkerLayout,
111    table: &UnitTable,
112    unit_tables: &HashMap<String, UnitTable>,
113    // v0.17: adapter unit name → its binding module path (relative to the out
114    // root, `.js`). An adapter's external provider class lives in this module,
115    // not in a `handlers.ts`.
116    binding_modules: &HashMap<String, String>,
117    // v0.18: the whole-project consume/alias/flattening maps, so external
118    // provider deps recurse across adapters (spec §4.5).
119    unit_consumes: &HashMap<String, Vec<String>>,
120    unit_consumes_aliases: &HashMap<String, HashMap<String, String>>,
121    unit_flattened: &HashMap<String, HashMap<String, String>>,
122    // Locale capability track, slice 2 (#882): this context's uniquely-
123    // detected message bundle, if any (`None` when zero or 2+ were found —
124    // the caller already resolved the cardinality, this function only acts).
125    locale_bundle: Option<&MessageBundleInfo>,
126    import_ext: ImportExt,
127    // #1944: every binding this Worker declares (`WorkerBindings`),
128    // the list its `wrangler.toml` is written from; `Env` types exactly it.
129    bindings: &[WorkerBinding],
130    // #2137: the test build of a context a `system` harness stands up — its
131    // first-party `Clock` reads the harness clock (`ProviderNamespaces::Workers`).
132    harness_clock: bool,
133    // #2967: the commons this context `uses`, whose public constants can key a
134    // WebSocket `on open`'s transfer (`bynk_check::consts::visible_consts`).
135    uses: &[String],
136    // #2969: used commons → the file declaring each of its functions and
137    // constants (`FileDeclIndex::fns`), for a commons split across files.
138    used_decl_paths: &HashMap<String, HashMap<String, std::path::PathBuf>>,
139) -> (TsProgram, bool) {
140    // #2967: the constants visible in this context, as the checker's
141    // `phase_workers_ws_open_key` classifies a transfer key against them.
142    let visible_consts = bynk_check::consts::visible_consts(table, uses, |u| unit_tables.get(u));
143    // #2967: a used commons' constant keying an `on open`'s transfer, imported
144    // into this module under an alias: alias → (owning commons, constant).
145    let mut const_imports: BTreeMap<String, (String, String)> = BTreeMap::new();
146    let unit = plan
147        .units
148        .get(context)
149        .unwrap_or_else(|| panic!("the compose plan has no unit `{context}`: every context with a checked table is planned in `build_output`"));
150    // v0.15: cross-context capabilities this Worker uses (in handlers or in a
151    // local provider's `given`) → `deps_key → consumed_context`. Their
152    // providers are instantiated locally (model A1). Divergence 3 of #3928,
153    // the cross-capability set: the Workers `compose` lifts the providers'
154    // cross-context `given`s to the top level too (the Bundle root, the
155    // handlers' only).
156    let cross_caps = unit.cross_caps();
157
158    // Locale capability track, slice 2 (#882, Decision C): only when this
159    // Worker both consumes `bynk`'s `Locale` and has a uniquely-detected
160    // message bundle do we import its declared-locale constants and pass
161    // `request` + them into `LocaleProvider`'s construction below.
162    let mut locale_import: Option<TsStmt> = None;
163    let mut locale_negotiation_args: Option<LocaleNegotiationArgs> = None;
164    if cross_caps
165        .get("Locale")
166        .is_some_and(|c| c == bynk_check::firstparty::BYNK_UNIT)
167        && let Some(bundle) = locale_bundle
168    {
169        let import = crate::emitter::cross_commons_import_specifier_for_path(
170            &layout.handlers_source_path(context),
171            &bundle.source_path,
172            import_ext,
173        );
174        // #1321: a renamed named import (`X as Y`) is one opaque `String`
175        // entry in `TsDecl::Import.names` — see that field's own doc.
176        locale_import = Some(TsStmt::decl(
177            TsDecl::Import {
178                type_only: false,
179                names: vec![
180                    "__messagesLocales as __locale_declaredLocales".to_string(),
181                    "__messagesReferenceLocale as __locale_referenceLocale".to_string(),
182                ],
183                from: import,
184            },
185            None,
186        ));
187        locale_negotiation_args = Some(LocaleNegotiationArgs {
188            request_expr: "request".to_string(),
189            declared_locales_expr: "__locale_declaredLocales".to_string(),
190            reference_locale_expr: "__locale_referenceLocale".to_string(),
191        });
192    }
193    let needs_request = locale_negotiation_args.is_some();
194
195    // v0.18: build each cross-cap provider expression up front, recording the
196    // units it references — an external provider's `given` may pull in another
197    // adapter's binding (the transitive given-closure), which must be imported.
198    let mut referenced_units: BTreeSet<String> = BTreeSet::new();
199    let mut cross_cap_exprs: Vec<(String, TsExpr)> = Vec::new();
200    for (key, cctx) in &cross_caps {
201        // #1321: the `TsExpr`-returning twin of `instantiate_provider_expr`
202        // (`project.rs`'s own Decision-B-style addition) — see its own doc
203        // for why the `String` version stays untouched.
204        let expr = crate::emit_model::instantiate_provider_ts_expr(
205            cctx,
206            key,
207            unit_tables,
208            unit_consumes,
209            unit_consumes_aliases,
210            unit_flattened,
211            crate::emit_model::ProviderNamespaces::Workers { harness_clock },
212            Some("env"),
213            locale_negotiation_args.as_ref(),
214            &mut referenced_units,
215        );
216        cross_cap_exprs.push((key.clone(), expr));
217    }
218    // S4a (#1966): each derived capability's instance, its base's platform
219    // provider bound to the instance's own Worker binding (which also imports
220    // the binding module).
221    for cap in &unit.derived {
222        let expr = crate::emit_model::instantiate_provider_ts_expr(
223            context,
224            cap,
225            unit_tables,
226            unit_consumes,
227            unit_consumes_aliases,
228            unit_flattened,
229            crate::emit_model::ProviderNamespaces::Workers { harness_clock },
230            Some("env"),
231            locale_negotiation_args.as_ref(),
232            &mut referenced_units,
233        );
234        cross_cap_exprs.push((cap.clone(), expr));
235    }
236
237    let runtime_use = RuntimeUse::default();
238    let binds = |kind: fn(&BindingSource) -> bool| bindings.iter().any(|b| kind(&b.source));
239
240    // Only consumed *contexts* become Service Bindings — a consumed adapter is
241    // not a Worker (its capability is provided in-process via the binding).
242    let consumes_a_context = unit
243        .consumes
244        .iter()
245        .any(|t| !binding_modules.contains_key(t));
246
247    // v0.79: if any handler in this context uses `detach`, `compose` also takes the
248    // request's execution context and threads its `waitUntil` into `deps.__exec`.
249
250    // -- Build the `compose` function's own body (Decision A/B: real nodes
251    // throughout) before assembling the header: the runtime import is read off the
252    // finished tree (below). --
253
254    let mut body: Vec<TsStmt> = Vec::new();
255
256    // v0.15: instantiate consumed-unit capability providers locally first, so
257    // local providers (and handlers) can depend on them by their deps key.
258    // v0.18: the expression recursively wires an external provider's `given`
259    // deps (built in the pre-pass above; cross_caps is a BTreeMap, so the
260    // pairs are already key-sorted).
261    let cross_keys: Vec<&String> = cross_caps.keys().collect();
262    for (key, expr) in cross_cap_exprs {
263        body.push(const_(key, expr));
264    }
265
266    // Capabilities: instantiate each capability's provider. v0.12: providers
267    // are emitted in dependency order (a composed provider's `given` deps must
268    // exist first) as local `const` bindings, injecting each provider's deps;
269    // then assembled into the `deps` object. v0.15: a provider's `given` may
270    // include cross-context capability keys (instantiated above).
271    // Divergence 2 of #3928, provider spelling: one `const` per provider, in the
272    // plan's dependency order (the Bundle root builds each inline).
273    let order = &unit.providers;
274    for cap in order {
275        let provider = table.providers.get(cap).unwrap();
276        let provider_ts = provider.provider_name.name.clone();
277        // #2355: a provider whose ops construct a local agent takes `env` in
278        // its deps, for the agent factory (`emit::emit_provider`).
279        let constructs_agent =
280            bynk_check::project_model::provider_constructs_agent(provider, |n| {
281                table.agents.contains_key(n)
282            });
283        let args = if provider.given.is_empty() && !constructs_agent {
284            vec![]
285        } else {
286            let mut entries: Vec<TsObjectEntry> = provider
287                .given
288                .iter()
289                .map(|c| TsObjectEntry::Shorthand(c.key().to_string()))
290                .collect();
291            if constructs_agent {
292                entries.push(TsObjectEntry::Shorthand("env".to_string()));
293            }
294            vec![TsExpr::object_entries(entries)]
295        };
296        let init = TsExpr::New {
297            callee: Box::new(member(ident("handlers"), provider_ts)),
298            args,
299        };
300        body.push(const_(cap.clone(), init));
301    }
302    // Divergence 1 of #3928, the entry order: capabilities by a plain sort,
303    // then `env`, the session, `__exec` and `__eventsDispatch` appended in that
304    // fixed order (the Bundle sorts every entry by `key + ":"`).
305    let mut deps_entries: Vec<TsObjectEntry> = {
306        let mut caps: Vec<String> = order.clone();
307        caps.extend(cross_keys.iter().map(|k| (*k).clone()));
308        caps.extend(unit.derived.iter().cloned());
309        deps_caps_in_order(caps)
310            .into_iter()
311            .map(TsObjectEntry::Shorthand)
312            .collect()
313    };
314    // Divergence 5 of #3928, `env`: it passes through for cross-context calls
315    // (Service Bindings) and agent instantiations (DOs); the Bundle threads it
316    // as a `composeApp` parameter into providers instead.
317    if consumes_a_context || unit.has_agents {
318        deps_entries.push(TsObjectEntry::Shorthand("env".to_string()));
319    }
320    // Divergence 6 of #3928: the session entry is the Workers' alone.
321    deps_entries.extend(session_deps_entry(table));
322    // v0.79: the execution context rides in `deps.__exec` for `detach` sends.
323    // Divergence 4 of #3928, the `__exec` gate and value: any handler that
324    // needs it, and the request's own `exec` (the Bundle: `call` handlers only,
325    // and `__bynkProcessExec()`).
326    let ctx_uses_send = unit.exec.any_handler;
327    if ctx_uses_send {
328        deps_entries.push(TsObjectEntry::prop("__exec".to_string(), ident("exec")));
329    }
330    if unit.publishes {
331        deps_entries.push(events_dispatch_entry(context, layout));
332    }
333    // `{  }` for no entries: see `compose::empty_deps`.
334    let deps_init = if deps_entries.is_empty() {
335        empty_deps()
336    } else {
337        TsExpr::object_entries(deps_entries)
338    };
339    body.push(const_("deps", deps_init));
340
341    // Local-surface object: one async wrapper per service operation plus
342    // one wrapper per `on http` handler.
343    let mut service_names: Vec<&String> = table.services.keys().collect();
344    service_names.sort();
345    let mut return_entries: Vec<TsObjectEntry> = Vec::new();
346    for sname in &service_names {
347        let service = table.services.get(*sname).unwrap();
348        let mut cron_idx = 0usize;
349        let mut queue_idx = 0usize;
350        for h in &service.handlers {
351            // P6.30 (design/tracks/the-ir.md §6a): dispatches on the checker-
352            // classified `IrHandlerKind` (P6.24a's own pure, unconditional
353            // mirror) rather than the raw AST `HandlerKind` directly. Slice 1
354            // of `#1542` (the IR cutover, `design/archive/retired-tracks.md`): the `Http`
355            // arm now reads `method`/`path` straight off that same
356            // `IrHandlerKind::Http` payload instead of re-deriving them from
357            // `h.kind` — un-deferred from Q7's original "wrapper signatures
358            // stay AST-typed until phase 7's printer" (phase 7 shipped; see
359            // the front-loading ADR).
360            match bynk_model::lower_handler_kind_ir(&h.kind) {
361                bynk_model::IrHandlerKind::Call => {
362                    return_entries.push(emit_call_wrapper(sname, h, &table.actors));
363                }
364                bynk_model::IrHandlerKind::Http { method, path } => {
365                    // v0.151: a single-actor `Oidc` handler gets the JWKS
366                    // verification wrapper. v0.52: a multi-actor sum handler gets
367                    // the first-wins resolution wrapper; otherwise the
368                    // single-actor Bearer/plain path. Review of #1209: this site
369                    // used to check `oidc` ahead of `sum`; `lower_actor_seam_ir`
370                    // checks `sum` ahead of `oidc` (matching `ActorSeamIr`'s own
371                    // canonical order). That swap is licensed by
372                    // `oidc_seam_for`'s own `by.is_sum()` early return
373                    // (`bynk-check/src/actors.rs`) — Oidc and a sum can never
374                    // both resolve for one handler, so which is tried first is a
375                    // no-op, unlike the sum-vs-Bearer order `ActorSeamIr`'s own
376                    // doc comment is about (Bearer was already checked last at
377                    // this site, so that pair's order didn't change here).
378                    // `Caller` never arises here — `caller_binder_for` only ever
379                    // resolves for `HandlerKind::Call` — so it shares the plain
380                    // path with `None`, exactly like the old fallthrough
381                    // (`bearer_seam_for` also misses on a `Caller` handler, since
382                    // `Caller` is a prelude actor, not a key of `table.actors`).
383                    match bynk_model::lower_actor_seam_ir(h, &table.actors) {
384                        bynk_model::ActorSeamIr::Oidc(oidc) => {
385                            return_entries
386                                .push(emit_http_oidc_wrapper(sname, h, method, &path, &oidc));
387                        }
388                        bynk_model::ActorSeamIr::SignedCookie(seam) => return_entries
389                            .push(signed_cookie_entry(service, sname, h, method, &path, &seam)),
390                        bynk_model::ActorSeamIr::Sum(members) => {
391                            return_entries.push(emit_http_sum_wrapper(
392                                sname,
393                                h,
394                                method,
395                                &path,
396                                &members,
397                                service.limits.as_ref().and_then(|p| p.max_body()),
398                                &runtime_use,
399                            ));
400                        }
401                        bynk_model::ActorSeamIr::Bearer(seam) => {
402                            return_entries.push(emit_http_wrapper(
403                                sname,
404                                h,
405                                method,
406                                &path,
407                                Some(&seam),
408                            ));
409                        }
410                        bynk_model::ActorSeamIr::Caller(_)
411                        | bynk_model::ActorSeamIr::Sender(_)
412                        | bynk_model::ActorSeamIr::CallSum(_)
413                        | bynk_model::ActorSeamIr::None => {
414                            return_entries.push(emit_http_wrapper(sname, h, method, &path, None));
415                        }
416                    }
417                }
418                bynk_model::IrHandlerKind::Cron { .. } => {
419                    return_entries.push(emit_cron_wrapper(sname, cron_idx, h));
420                    cron_idx += 1;
421                }
422                bynk_model::IrHandlerKind::Message => {
423                    let Some(entry) = message_wrapper(service, sname, queue_idx, h, &table.actors)
424                    else {
425                        continue;
426                    };
427                    return_entries.push(entry);
428                    queue_idx += 1;
429                }
430                bynk_model::IrHandlerKind::Open => {
431                    // An actor sum (`by who: A | B`) resolves member by member at the
432                    // edge; `bearer_seam_for` would see only its first member.
433                    let sum = bynk_check::actors::sum_members_for(h, &table.actors);
434                    let seam = if sum.is_some() {
435                        None
436                    } else {
437                        bynk_check::actors::bearer_seam_for(h, &table.actors)
438                    };
439                    let local_agents: HashSet<String> = table.agents.keys().cloned().collect();
440                    // #1818: hosting agents that read their key are forwarded it.
441                    let key_readers: HashSet<String> = table
442                        .agents
443                        .iter()
444                        .filter(|(_, a)| crate::emitter::emit::agent_reads_key(a))
445                        .map(|(n, _)| n.clone())
446                        .collect();
447                    return_entries.push(emit_websocket_upgrade(
448                        sname,
449                        h,
450                        seam.as_ref(),
451                        sum.as_deref(),
452                        &local_agents,
453                        &key_readers,
454                        &visible_consts,
455                        &mut const_imports,
456                    ));
457                }
458                // v0.106 (slice 3b-iii): `on close` runs in the DO (`webSocketClose`),
459                // not at the edge — no compose wrapper.
460                bynk_model::IrHandlerKind::Close => {}
461                // Events track, slice 0 (spine #936): unlike the WS
462                // lifecycle handlers above, an `on event` handler's body
463                // *does* need a compose-surface wrapper — it is reached from
464                // `/_bynk/event/<sname>` (`emit_worker_entry`), the route a
465                // *subscriber* Worker's own fan-out delivery lands on (not
466                // this context's edge traffic, and not HTTP-routable, hence
467                // no route table entry — just a plain wrapper like `on
468                // call`'s).
469                bynk_model::IrHandlerKind::Event => {
470                    return_entries.push(emit_event_wrapper(
471                        sname,
472                        unit.hosted_wants_envelope(context, sname),
473                    ));
474                }
475                // #2341 (decision C): the router calls `rejected_<svc>(why)`
476                // to render a rejection of one of this service's requests.
477                bynk_model::IrHandlerKind::Rejected => {
478                    return_entries.push(emit_rejected_wrapper(sname));
479                }
480            }
481        }
482    }
483    body.push(return_(Some(TsExpr::multiline_object_entries(
484        return_entries,
485    ))));
486
487    let mut compose_params = vec![TsParam::new("env".to_string(), Some(TsType::named("Env")))];
488    // Locale capability track, slice 2 (#882): `request` is threaded
489    // independently of `exec` — the two-way independence matters because
490    // `scheduled`/`queue` (which never have a `request`) may still use
491    // `detach` (`exec`), and a `fetch`-only Worker with no message bundle needs
492    // neither.
493    if needs_request {
494        compose_params.push(TsParam::optional(
495            "request".to_string(),
496            Some(TsType::named("globalThis.Request")),
497        ));
498    }
499    // L7 (#2414, Decision E): an `EdgeCache` instance is built from the
500    // entry's `ctx` (`new WorkersEdgeCache(exec)`), so compose takes it even
501    // when nothing sends; optional then, as the entry's own `ctx` is.
502    let edge_cache = table.derived.values().any(|d| d.is_edge_cache());
503    if edge_cache && !ctx_uses_send {
504        compose_params.push(TsParam::optional(
505            "exec".to_string(),
506            Some(TsType::named("unknown")),
507        ));
508    }
509    if ctx_uses_send {
510        compose_params.push(TsParam {
511            name: "exec".to_string(),
512            // #1321: a fixed, non-generative type-literal-with-a-method
513            // constant — no per-call variation, so it's carried as opaque
514            // `Named` text rather than a general method-signature-in-a-
515            // type-literal shape, the same "opaque `Named` for one real,
516            // unvarying shape" precedent `ts_type_ref_to_ts_type`'s own
517            // `TypeRef::Query` arm already established (`emitter.rs`).
518            ty: Some(TsType::named(
519                "{ waitUntil(promise: globalThis.Promise<unknown>): void }",
520            )),
521            optional: false,
522            rest: false,
523            array_pattern: None,
524            default: None,
525        });
526    }
527
528    // -- Assemble the whole document in its real, final order. --
529    let mut program = TsProgram::new();
530    program.push(TsStmt::comment(
531        "Generated by bynk — do not edit by hand.",
532        None,
533    ));
534    program.push(TsStmt::comment(
535        format!("composition root for `{context}` Worker."),
536        None,
537    ));
538    // The runtime import goes here, once the rest of the module is built (below).
539    let runtime_import_at = program.stmts.len();
540    program.push(TsStmt::decl(
541        TsDecl::ImportNamespace {
542            type_only: false,
543            alias: "handlers".to_string(),
544            from: layout.own_handlers_specifier(context),
545        },
546        None,
547    ));
548    // Import each referenced unit's provider classes. A *context*'s providers
549    // live in its Worker's `handlers.js`; an *adapter*'s external provider
550    // classes live in its binding module at the out root.
551    for cctx in &referenced_units {
552        let ns = cctx.replace('.', "_");
553        if let Some(module) = binding_modules.get(cctx) {
554            program.push(TsStmt::decl(
555                TsDecl::ImportNamespace {
556                    type_only: false,
557                    alias: format!("{ns}__binding"),
558                    from: format!("../../{module}"),
559                },
560                None,
561            ));
562        } else {
563            program.push(TsStmt::decl(
564                TsDecl::ImportNamespace {
565                    type_only: false,
566                    alias: format!("handlers_{ns}"),
567                    from: layout.handlers_specifier(context, cctx),
568                },
569                None,
570            ));
571        }
572    }
573    if let Some(li) = locale_import {
574        program.push(li);
575    }
576    // #2967: `compose.ts` imports a used commons' constant from the commons
577    // itself, as the context's own modules do: `handlers.ts` imports it without
578    // re-exporting it. Aliased, so a constant named like a binding of this
579    // module (`Env`, `handlers`) cannot shadow it.
580    // #2969: grouped by the module that declares each constant, which for a
581    // commons split across files is one of its files, not the commons path.
582    let mut by_module: BTreeMap<std::path::PathBuf, Vec<String>> = BTreeMap::new();
583    for (alias, (owner, name)) in &const_imports {
584        let module = used_decl_paths
585            .get(owner)
586            .and_then(|paths| paths.get(name))
587            .cloned()
588            .unwrap_or_else(|| crate::emit_model::EmitProjectCtx::commons_path(owner));
589        by_module.entry(module).or_default().push(format!(
590            "{} as {alias}",
591            bynk_check::emitted_names::ts_ident(name)
592        ));
593    }
594    for (module, names) in by_module {
595        program.push(TsStmt::decl(
596            TsDecl::Import {
597                type_only: false,
598                names,
599                from: crate::emitter::cross_commons_import_specifier_for_path(
600                    &layout.handlers_source_path(context),
601                    &module,
602                    import_ext,
603                ),
604            },
605            None,
606        ));
607    }
608
609    // Env shape: one member per binding the Worker's `wrangler.toml`
610    // declares, from the same list (#1944), so the two cannot drift.
611    let env_members: Vec<TsTypeMember> = bindings
612        .iter()
613        .map(|b| TsTypeMember::prop(b.name.clone(), TsType::named(binding_ts_type(&b.source))))
614        .collect();
615    program.push(TsStmt::decl(
616        TsDecl::Export(Box::new(TsDecl::Interface {
617            name: "Env".to_string(),
618            type_params: Vec::new(),
619            members: env_members,
620        })),
621        None,
622    ));
623
624    if binds(|s| {
625        matches!(
626            s,
627            BindingSource::Agent { .. }
628                | BindingSource::EventsFanout { .. }
629                | BindingSource::ContainerInstance { .. }
630        )
631    }) {
632        // P7.2: deferred, not narrowed — this settling attempt broke real
633        // `tsc --strict` fixtures. A real, differently-shaped imported
634        // `DurableObjectNamespace` (from `./runtime`, `fetch(input: string,
635        // init?: unknown)`) can be in scope in the same file as this local
636        // fallback (used with `fetch(new Request(...))` at this file's own
637        // `__stub.fetch` call site) — the two share a name but not a shape, and
638        // reconciling them needs more than a same-line fix (a real import/alias,
639        // or renaming the local fallback), not a guessed structural type.
640        program.push(TsStmt::decl(
641            TsDecl::TypeAlias {
642                name: "__DurableObjectNamespace".to_string(),
643                type_params: Vec::new(),
644                ty: TsType::named(
645                    "{ idFromName(name: string): { toString(): string }; idFromString(id: string): { toString(): string }; get(id: any): any }",
646                ),
647            },
648            None,
649        ));
650    }
651
652    program.push(TsStmt::decl(
653        TsDecl::Export(Box::new(TsDecl::Function {
654            name: "compose".to_string(),
655            generics: Vec::new(),
656            params: compose_params,
657            return_type: None,
658            body,
659            is_async: false,
660            inline: false,
661        })),
662        None,
663    ));
664
665    // 1A.36b-2: the runtime import is what the module's tree uses (`derived_worker_runtime_names`);
666    // its position is after the banner, before the other imports.
667    let names = crate::emitter::runtime_header::derived_worker_runtime_names(
668        &program.stmts[runtime_import_at..],
669    );
670    for (i, stmt) in crate::emitter::runtime_files::runtime_import_stmts(
671        false,
672        &names,
673        COMPOSE_RUNTIME_SPECIFIER,
674    )
675    .into_iter()
676    .enumerate()
677    {
678        program.stmts.insert(runtime_import_at + i, stmt);
679    }
680    // Each fixed import (`handlers`, a provider's namespace) is kept only if the tree uses it.
681    program.prune_unused_imports();
682
683    (program, needs_request)
684}
685
686#[cfg(test)]
687mod tests {
688    use super::*;
689
690    /// Divergence 1 of #3928: the Workers sort capabilities plainly. A `Db`/`Db2`
691    /// pair therefore orders the other way round from the Bundle's
692    /// `deps_entry_sort_key` order, and unifying the two would change output.
693    #[test]
694    fn workers_order_capabilities_by_a_plain_sort() {
695        assert_eq!(
696            deps_caps_in_order(vec!["Db2".to_string(), "Db".to_string()]),
697            ["Db", "Db2"]
698        );
699    }
700}