Skip to main content

bynk_emit/emitter/
workers_emit.rs

1//! The per-Worker emission (1B.2d, #4028 Decision F): each context's `compose.ts`,
2//! entry point, events fan-out class, contract and secrets manifests, and its
3//! Worker's `wrangler.toml` and sidecars, rendered from the binding model the
4//! build derived once ([`WorkerBindings`](super::WorkerBindings)). The driver builds a [`WorkersEmit`]
5//! from the checked project and its options and calls [`WorkersEmit::emit_all`];
6//! it decides nothing about which bindings a Worker has, or where it is.
7
8use super::{self as emitter};
9use crate::emit_model::{Document, ImportExt, StagedFile};
10use crate::emit_model::{
11    called_cross_context_services, worker_assets_dir, worker_reaches_wasm_module,
12};
13use bynk_check::checker::ExprId;
14use bynk_check::firstparty;
15use bynk_check::project_model::AdapterBinding;
16use bynk_check::schema_registry::AgentVersions;
17use bynk_check::symbols::UnitTable;
18use bynk_project::AttributedError;
19use bynk_project::UnitKind;
20use bynk_project::discovery::ParsedFile;
21use bynk_project::worker_layout::WorkerLayout;
22use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
23use std::path::PathBuf;
24use std::sync::Arc;
25
26/// #3581: the agent classes a `bynk dev` build's Worker answers the inspect route
27/// for, sorted; empty unless the build asks for inspection.
28fn inspect_classes(on: bool, table: &UnitTable) -> Vec<String> {
29    let mut classes: Vec<String> = if on {
30        table.agents.keys().cloned().collect()
31    } else {
32        Vec::new()
33    };
34    classes.sort();
35    classes
36}
37
38/// Everything a context's Workers emit reads from the checked project and the
39/// build's options (#3562, G2b): the same inputs the driver's emit loop used as
40/// locals, gathered so [`WorkersEmit::emit_all`] produces every context's files
41/// and the driver only supplies them.
42#[derive(Clone, Copy)]
43pub struct WorkersEmit<'a> {
44    pub adapter_bindings: &'a HashMap<String, AdapterBinding>,
45    pub agent_versions: &'a HashMap<String, AgentVersions>,
46    pub asset_files: Option<&'a BTreeMap<String, Vec<u8>>>,
47    pub asset_served: &'a BTreeMap<String, String>,
48    pub bindings: &'a emitter::WorkerBindings,
49    pub compatibility_flags: &'a [String],
50    pub contracts_lock: &'a bynk_project::contracts_lock::ContractsLock,
51    pub d1_migrations: &'a BTreeMap<String, Vec<bynk_check::d1_migrations::MigrationFile>>,
52    pub compose_plan: &'a emitter::ComposePlan,
53    pub groups: &'a BTreeMap<String, Vec<usize>>,
54    pub harness_clock_contexts: &'a HashSet<String>,
55    pub import_ext: ImportExt,
56    pub inspect_agents: bool,
57    pub kinds: &'a BTreeMap<String, UnitKind>,
58    pub layout: &'a WorkerLayout,
59    pub parsed: &'a [ParsedFile],
60    pub trace_requests: bool,
61    pub unit_callees: &'a HashMap<String, HashMap<ExprId, bynk_check::checker::Callee>>,
62    pub unit_consumed_context_types: &'a HashMap<String, HashSet<String>>,
63    pub unit_consumes: &'a HashMap<String, Vec<String>>,
64    pub unit_consumes_aliases: &'a HashMap<String, HashMap<String, String>>,
65    pub unit_flattened: &'a HashMap<String, HashMap<String, String>>,
66    pub unit_tables: &'a HashMap<String, UnitTable>,
67    pub unit_uses: &'a HashMap<String, Vec<String>>,
68    pub workers_dev: Option<bool>,
69}
70
71impl WorkersEmit<'_> {
72    /// The files of one context (a Worker's, or one member's of a group's):
73    /// `compose.ts`, its entry, its fan-out class and its manifests, pushed
74    /// onto `compiled`; contract-lock warnings onto `lock_warnings`. What it
75    /// contributes to its Worker's `wrangler.toml` comes back as [`MemberParts`],
76    /// for [`Self::finish_worker`].
77    fn emit_member(
78        &self,
79        ctx_name: &String,
80        table: &UnitTable,
81        compiled: &mut Vec<StagedFile>,
82        lock_warnings: &mut Vec<AttributedError>,
83        inspect_lists: bool,
84    ) -> MemberParts {
85        let WorkersEmit {
86            adapter_bindings,
87            agent_versions,
88            bindings: model,
89            compose_plan,
90            contracts_lock,
91            groups,
92            harness_clock_contexts,
93            import_ext,
94            inspect_agents,
95            kinds,
96            layout,
97            parsed,
98            trace_requests,
99            unit_callees,
100            unit_consumed_context_types,
101            unit_consumes,
102            unit_consumes_aliases,
103            unit_flattened,
104            unit_tables,
105            unit_uses,
106            ..
107        } = *self;
108        let consumes_targets = unit_consumes.get(ctx_name).cloned().unwrap_or_default();
109        // v0.177 (#643): the callee's own view of each of its `on call`
110        // contracts, hashed from *its own* namespace — the same table
111        // (`contract_types_for`) a caller reaches through
112        // `consumed_types[ctx_name]`, so the two sides cannot disagree.
113        let own_types = bynk_check::symbols::contract_types_for(
114            ctx_name,
115            unit_tables,
116            unit_uses,
117            unit_consumes,
118        )
119        .0;
120        let own_contracts = bynk_check::contract::own_contract_hashes(table, &own_types);
121        // #2554: the older contracts this callee also accepts, each
122        // re-checked against the contract it has now.
123        let accepted = bynk_check::contract_compat::own_accepted(
124            table,
125            &own_types,
126            |service| contracts_lock.accepted(ctx_name, service),
127            bynk_project::contracts_lock::ACCEPTED_CAP,
128        );
129        for (service, why) in &accepted.stale {
130            lock_warnings.push(bynk_project::contracts_lock::stale_warning(
131                ctx_name, service, why,
132            ));
133        }
134        for (service, count) in &accepted.oversized {
135            lock_warnings.push(bynk_project::contracts_lock::oversized_warning(
136                ctx_name, service, *count,
137            ));
138        }
139        let binding_modules: HashMap<String, String> = adapter_bindings
140            .iter()
141            .map(|(n, b)| {
142                (
143                    n.clone(),
144                    emitter::ts_specifier(&b.output_path.with_extension("js")),
145                )
146            })
147            .collect();
148        // Locale capability track, slice 2 (#882, Decision A): real
149        // negotiation is Cloudflare-only — `BuildTarget::Workers`
150        // isn't itself restricted to `Platform::Cloudflare`, so a
151        // hypothetical `--target workers --platform node` project
152        // must not try to pass 3 args to Node's still-0-arg
153        // `LocaleProvider`.
154        let is_cloudflare_binding = adapter_bindings
155            .get(firstparty::BYNK_UNIT)
156            .is_some_and(|b| {
157                b.output_path.file_name()
158                    == Some(std::ffi::OsStr::new(
159                        firstparty::Platform::Cloudflare.bynk_binding_filename(),
160                    ))
161            });
162        let bundle = bynk_check::symbols::detect_context_message_bundle(
163            ctx_name, unit_uses, groups, kinds, parsed,
164        );
165        use bynk_check::symbols::ContextMessageBundle as Bundle;
166        let locale_bundle_info = match &bundle {
167            Bundle::One(info) if is_cloudflare_binding => Some(info),
168            Bundle::One(_) | Bundle::None | Bundle::Many(_) => None,
169        };
170        // #1187's slice 6 plumbing: computed once, reused by every
171        // Workers-target emitter below that needs it.
172        let ctx_uses_emit = planned_unit(compose_plan, ctx_name).publishes;
173        // #1944: every binding this Worker declares, once — its `Env`
174        // interface and its `wrangler.toml` are both built from it, and the
175        // duplicate check reads the same list (1C.1b).
176        let bindings = model.of(ctx_name);
177        // What this context calls on each dependency (#1961): its contracts
178        // manifest, below.
179        let called =
180            called_cross_context_services(table, &consumes_targets, unit_callees.get(ctx_name));
181        // #2719: the context's handlers that hand work to the execution
182        // context, from the checker's needs-context set.
183        let ctx_uses_exec = planned_unit(compose_plan, ctx_name).exec.any_handler;
184        // #2969: the file of each used commons that declares each of its
185        // functions and constants, so `compose.ts` imports a commons
186        // constant from its declaring module, as `handlers.ts` does,
187        // when the commons is split across files.
188        let used_decl_paths: HashMap<String, HashMap<String, PathBuf>> = unit_uses
189            .get(ctx_name)
190            .into_iter()
191            .flatten()
192            .filter_map(|u| {
193                let indices = groups.get(u)?;
194                let index = bynk_check::symbols::build_file_decl_index(indices, parsed);
195                Some((u.clone(), index.fns))
196            })
197            .collect();
198        let (compose_ts, needs_locale_request) = emitter::emit_worker_compose(
199            ctx_name,
200            compose_plan,
201            self.layout,
202            table,
203            unit_tables,
204            &binding_modules,
205            unit_consumes,
206            unit_consumes_aliases,
207            unit_flattened,
208            locale_bundle_info,
209            import_ext,
210            bindings,
211            harness_clock_contexts.contains(ctx_name),
212            unit_uses
213                .get(ctx_name)
214                .map(Vec::as_slice)
215                .unwrap_or_default(),
216            &used_decl_paths,
217        );
218        // #2136: a context a `system` suite targets gets the test
219        // build's scheduled-result hook. A deployable build strips
220        // suites (`tests` off), so it never does.
221        let system_driven = parsed
222            .iter()
223            .filter_map(ParsedFile::integration)
224            .any(|d| d.target.joined() == *ctx_name);
225        // #2252: the types this context takes from the contexts it
226        // consumes, recorded when its handlers were checked.
227        let no_consumed_types = HashSet::new();
228        let consumed_types = unit_consumed_context_types
229            .get(ctx_name)
230            .unwrap_or(&no_consumed_types);
231        let migratable = migratable_agents(ctx_name, table, agent_versions);
232        let inspect_classes = inspect_classes(inspect_agents, table);
233        let entry_ts = emitter::emit_worker_entry(
234            ctx_name,
235            self.layout,
236            table,
237            &own_contracts,
238            &accepted.hashes,
239            needs_locale_request,
240            ctx_uses_emit,
241            system_driven,
242            consumed_types,
243            &migratable,
244            ctx_uses_exec,
245            &bynk_check::symbols::combined_types_for(ctx_name, unit_tables, unit_uses),
246            trace_requests,
247            (&inspect_classes, inspect_lists),
248        );
249        // P6.x cutover slice 2 (#1191): collected here, not inside
250        // `emit_wrangler_toml` itself, so that function's own file
251        // needs no raw-AST match. P6.46 (#1137): the walk itself
252        // relocated to `bynk_check::symbols::cron_and_queue_triggers`
253        // — a pure function of `table`, `project.rs`'s own remaining
254        // AST contact here was incidental to where the loop happened
255        // to be written, not structural.
256        let (crons, queues) = bynk_check::symbols::cron_and_queue_triggers(table);
257        // Arc C slice 4 (#1323): `emit_worker_entry` returns a real
258        // `TsProgram` directly — the construction site's own
259        // `Verbatim`/`NotYetConverted` wrap is gone, matching the
260        // precedent `events_fanout.rs`'s and `workers.rs`'s own
261        // construction sites already set. A group member's entry is its own
262        // file, which the group's entry imports.
263        compiled.push(StagedFile {
264            output_path: layout.member_file(ctx_name, "index.ts"),
265            document: Document::Ts(entry_ts),
266            source_map: None,
267            debug_metadata: None,
268        });
269        let mut classes: Vec<String> = table.agents.keys().cloned().collect();
270        classes.sort();
271        // Events track, slice 0: this context's fan-out Durable
272        // Object — emitted only when it actually publishes (mirrors
273        // `emit_worker_compose`'s own `unit_table_uses_emit` gate on
274        // `deps.__eventsDispatch`, so the two never disagree about
275        // whether `env.EVENTS_FANOUT` is real).
276        // #3562 (G3-1): a group's members share one fan-out, which the group
277        // emits from every publishing member's routes (`group_entry`).
278        let in_group = layout.is_member(ctx_name);
279        if ctx_uses_emit && !in_group {
280            // Arc C's own first real conversion slice (#1317):
281            // `emit_events_fanout_do` returns a real `TsProgram`
282            // directly — the first `bynk-emit` construction site
283            // that reaches `Document::Ts` with no `Verbatim` wrap.
284            let fanout_program = emitter::emit_events_fanout_do(ctx_name, &compose_plan.events);
285            compiled.push(StagedFile {
286                output_path: layout.member_file(ctx_name, "events_fanout.ts"),
287                document: Document::Ts(fanout_program),
288                source_map: None,
289                debug_metadata: None,
290            });
291            classes.push(emitter::wrangler::EVENTS_FANOUT_CLASS_NAME.to_string());
292        }
293        // A `bynk dev` build's registry class is exported once for the Worker, by
294        // the member that answers the listing.
295        if inspect_lists {
296            classes.push("BynkInspectRegistry".to_string());
297        }
298        // Arc C slice 3 (#1321): `emit_worker_compose` returns a
299        // real `TsProgram` directly — the second `bynk-emit`
300        // construction site (after `events_fanout.ts`'s own,
301        // #1317) that reaches `Document::Ts` with no `Verbatim`
302        // wrap.
303        compiled.push(StagedFile {
304            output_path: layout.member_file(ctx_name, "compose.ts"),
305            document: Document::Ts(compose_ts),
306            source_map: None,
307            debug_metadata: None,
308        });
309        let (contracts, secrets) =
310            self.emit_contract_manifests(ctx_name, table, &called, &own_types, &accepted, compiled);
311        MemberParts {
312            context: ctx_name.clone(),
313            crons,
314            queues,
315            addresses: bynk_check::email::routed_addresses(table),
316            has_events: own_handles_events(table),
317            has_migrate: !migratable.is_empty(),
318            has_inspect: !inspect_classes.is_empty(),
319            inspect_classes,
320            classes,
321            contracts,
322            secrets,
323            publishes: ctx_uses_emit && in_group,
324        }
325    }
326
327    /// Whether `ctx_name`'s entry answers its Worker's `/_bynk/inspect/agents`
328    /// listing (`bynk dev` only): the first member of its group that hosts an
329    /// agent does, so the registry is listed once. False outside a group, where
330    /// the one entry answers everything.
331    fn lists_inspection(&self, ctx_name: &str) -> bool {
332        let WorkersEmit {
333            inspect_agents,
334            layout,
335            unit_tables,
336            ..
337        } = *self;
338        let Some(members) = layout
339            .is_member(ctx_name)
340            .then(|| layout.group_members(&layout.dir(ctx_name)))
341            .flatten()
342        else {
343            return false;
344        };
345        members
346            .iter()
347            .find(|m| {
348                unit_tables
349                    .get(m.as_str())
350                    .is_some_and(|t| !inspect_classes(inspect_agents, t).is_empty())
351            })
352            .is_some_and(|first| first == ctx_name)
353    }
354
355    /// Every context's files, then every Worker's: a Worker is a context's own,
356    /// or a group's members (in the order the manifest lists them).
357    pub fn emit_all(
358        &self,
359        compiled: &mut Vec<StagedFile>,
360        lock_warnings: &mut Vec<AttributedError>,
361        staged_assets: &mut BTreeMap<PathBuf, Vec<u8>>,
362    ) {
363        let WorkersEmit {
364            kinds,
365            layout,
366            unit_tables,
367            ..
368        } = *self;
369        let mut parts: BTreeMap<&String, (MemberParts, &UnitTable)> = BTreeMap::new();
370        for (ctx_name, kind) in kinds {
371            if *kind != UnitKind::Context {
372                continue;
373            }
374            let Some(table) = unit_tables.get(ctx_name) else {
375                continue;
376            };
377            let lists = self.lists_inspection(ctx_name);
378            let member = self.emit_member(ctx_name, table, compiled, lock_warnings, lists);
379            parts.insert(ctx_name, (member, table));
380        }
381        let mut done: HashSet<String> = HashSet::new();
382        for ctx_name in parts.keys() {
383            let dir = layout.dir(ctx_name);
384            if !done.insert(dir.clone()) {
385                continue;
386            }
387            let order = layout
388                .group_members(&dir)
389                .map_or_else(|| vec![(*ctx_name).clone()], <[String]>::to_vec);
390            let worker: Vec<(&MemberParts, &UnitTable)> = order
391                .iter()
392                .filter_map(|c| parts.get(c))
393                .map(|(member, table)| (member, *table))
394                .collect();
395            self.finish_worker(&worker, compiled, staged_assets);
396        }
397    }
398
399    /// One Worker's whole-Worker files, from its members' parts: `wrangler.toml`
400    /// (their bindings, crons, queues and addresses merged, an identical
401    /// capability one binding), the staged binding files, the assets it serves,
402    /// `containers.ts`, and, for a group, the entry that dispatches to its
403    /// members. A context's own Worker is a group of one, whose entry is the
404    /// member's own.
405    fn finish_worker(
406        &self,
407        members: &[(&MemberParts, &UnitTable)],
408        compiled: &mut Vec<StagedFile>,
409        staged_assets: &mut BTreeMap<PathBuf, Vec<u8>>,
410    ) {
411        let WorkersEmit {
412            compatibility_flags,
413            d1_migrations,
414            layout,
415            workers_dev,
416            ..
417        } = *self;
418        let first = members[0].0.context.as_str();
419        let bindings = self.bindings.of_worker(&layout.dir(first));
420        let union = |of: fn(&MemberParts) -> &Vec<String>| -> Vec<String> {
421            let mut all: Vec<String> = members.iter().flat_map(|(p, _)| of(p).clone()).collect();
422            all.sort();
423            all.dedup();
424            all
425        };
426        let mut tombstones = emitter::ClassTombstones::default();
427        for (_, table) in members {
428            let one = emitter::ClassTombstones::of(table);
429            tombstones.renamed.extend(one.renamed);
430            tombstones.deleted.extend(one.deleted);
431        }
432        tombstones.renamed.sort();
433        tombstones.deleted.sort();
434        tombstones.deleted.dedup();
435        let mut wrangler_doc = emitter::emit_wrangler_toml(
436            first,
437            layout,
438            bindings,
439            &union(|p| &p.crons),
440            &union(|p| &p.queues),
441            &union(|p| &p.addresses),
442            compatibility_flags,
443            workers_dev,
444            &tombstones,
445            d1_migrations,
446        );
447        stage_binding_files(bindings, layout, first, d1_migrations, compiled);
448        let tables: Vec<(&str, &UnitTable)> = members
449            .iter()
450            .map(|(parts, table)| (parts.context.as_str(), *table))
451            .collect();
452        self.stage_worker_extras(&tables, &mut wrangler_doc, staged_assets);
453        // #3477: the Durable Object classes of this Worker's containers.
454        if let Some(program) = emitter::emit_containers_ts(bindings) {
455            compiled.push(StagedFile {
456                output_path: layout.worker_file(first, "containers.ts"),
457                document: Document::Ts(program),
458                source_map: None,
459                debug_metadata: None,
460            });
461        }
462        compiled.push(StagedFile {
463            output_path: layout.worker_file(first, "wrangler.toml"),
464            document: Document::Toml(wrangler_doc),
465            source_map: None,
466            debug_metadata: None,
467        });
468        if layout.is_member(first) {
469            if let Some(text) = agents_manifest(members) {
470                compiled.push(StagedFile {
471                    output_path: layout.worker_file(first, crate::AGENTS_MANIFEST),
472                    document: Document::Json(text),
473                    source_map: None,
474                    debug_metadata: None,
475                });
476            }
477            self.stage_group_manifests(first, members, compiled);
478            // #3562 (G3-1): the group's one events fan-out, for every member that
479            // publishes, in declaration order.
480            let publishers: Vec<&str> = members
481                .iter()
482                .filter(|(parts, _)| parts.publishes)
483                .map(|(parts, _)| parts.context.as_str())
484                .collect();
485            if !publishers.is_empty() {
486                compiled.push(StagedFile {
487                    output_path: layout.worker_file(first, "events_fanout.ts"),
488                    document: Document::Ts(emitter::emit_group_events_fanout_do(
489                        &layout.dir(first),
490                        &publishers,
491                        &self.compose_plan.events,
492                    )),
493                    source_map: None,
494                    debug_metadata: None,
495                });
496            }
497            if let Some(text) = group_inspect_manifest(members) {
498                compiled.push(StagedFile {
499                    output_path: layout.worker_file(first, crate::INSPECT_MEMBERS_FILE),
500                    document: Document::Json(text),
501                    source_map: None,
502                    debug_metadata: None,
503                });
504            }
505            let entry = self.group_entry(first, members, bindings);
506            compiled.push(StagedFile {
507                output_path: layout.worker_file(first, "index.ts"),
508                document: Document::Ts(entry),
509                source_map: None,
510                debug_metadata: None,
511            });
512        }
513    }
514
515    /// A group's one `bynk-contracts.json` and `bynk-secrets.json`, which `deploy`
516    /// reads beside the Worker: the members' merged (#3562).
517    fn stage_group_manifests(
518        &self,
519        first: &str,
520        members: &[(&MemberParts, &UnitTable)],
521        compiled: &mut Vec<StagedFile>,
522    ) {
523        let names: Vec<String> = members.iter().map(|(p, _)| p.context.clone()).collect();
524        let contracts = emitter::contracts::ContractParts::merged(
525            members.iter().map(|(p, _)| p.contracts.clone()),
526            &names,
527        );
528        let secrets =
529            emitter::secrets::SecretsParts::merged(members.iter().map(|(p, _)| p.secrets.clone()));
530        for (file, text) in [
531            (emitter::contracts::CONTRACTS_MANIFEST, contracts.render()),
532            (emitter::secrets::SECRETS_MANIFEST, secrets.render()),
533        ] {
534            if let Some(text) = text {
535                compiled.push(StagedFile {
536                    output_path: self.layout.worker_file(first, file),
537                    document: Document::Json(text),
538                    source_map: None,
539                    debug_metadata: None,
540                });
541            }
542        }
543    }
544
545    /// A group's `index.ts` (see `emitter::workers_group`).
546    fn group_entry(
547        &self,
548        first: &str,
549        members: &[(&MemberParts, &UnitTable)],
550        bindings: &[emitter::bindings::WorkerBinding],
551    ) -> bynk_ts::TsProgram {
552        let layout = self.layout;
553        let facts: Vec<emitter::GroupMember> = members
554            .iter()
555            .map(|(parts, _)| emitter::GroupMember {
556                context: parts.context.clone(),
557                specifier: layout.own_module_specifier(&parts.context, "index.ts"),
558                crons: parts.crons.clone(),
559                queues: parts.queues.clone(),
560                addresses: parts.addresses.clone(),
561                classes: parts.classes.clone(),
562            })
563            .collect();
564        emitter::emit_group_entry(&emitter::GroupEntry {
565            key: &layout.dir(first),
566            members: &facts,
567            container_classes: &emitter::container_class_names(bindings),
568            has_fanout: members.iter().any(|(parts, _)| parts.publishes),
569            has_events: members.iter().any(|(parts, _)| parts.has_events),
570            has_migrate: members.iter().any(|(parts, _)| parts.has_migrate),
571            has_inspect: members.iter().any(|(parts, _)| parts.has_inspect),
572        })
573    }
574
575    /// The files `bynk deploy` reads beside a Worker: the contracts manifest
576    /// (the hashes its entry enforces and what it expects of each dependency),
577    /// the typed client a foreign caller imports, and the secrets manifest.
578    fn emit_contract_manifests(
579        &self,
580        ctx_name: &str,
581        table: &UnitTable,
582        called: &BTreeMap<String, BTreeSet<String>>,
583        own_types: &HashMap<String, Arc<bynk_check::project_model::TypeDecl>>,
584        accepted: &bynk_check::contract_compat::ContextAccepted,
585        compiled: &mut Vec<StagedFile>,
586    ) -> (
587        emitter::contracts::ContractParts,
588        emitter::secrets::SecretsParts,
589    ) {
590        let WorkersEmit {
591            layout,
592            unit_consumes,
593            unit_consumes_aliases,
594            unit_flattened,
595            unit_tables,
596            unit_uses,
597            ..
598        } = *self;
599        // v0.177 (#643): the contract hashes this context's entry
600        // enforces, written where `deploy` can read them — so a skew is
601        // refused at the push rather than discovered by live traffic.
602        // #2750: the SAME table the entry's hashes (`own_contracts`, in
603        // `emit_member`) and every caller's `expects` are computed from —
604        // `own_types`, bound once from `contract_types_for`. A second
605        // binding from `combined_types_for` here left a consumed
606        // context's exported type unresolved in `provides`.
607        // What this context expects of each dependency — the same hash
608        // it stamps at each call site, computed the same way: in the
609        // *dependency's* namespace, from the dependency's own table.
610        //
611        // Only the services this context actually **calls**. Recording
612        // everything the dependency provides would refuse a deploy over a
613        // service this caller never touches — a skew its runtime check
614        // could never fire on. See `called_cross_context_services`.
615        let mut expects: std::collections::BTreeMap<
616            String,
617            std::collections::BTreeMap<String, String>,
618        > = std::collections::BTreeMap::new();
619        let mut expects_shapes: std::collections::BTreeMap<
620            String,
621            std::collections::BTreeMap<String, String>,
622        > = std::collections::BTreeMap::new();
623        for (dep, services) in called {
624            let Some(dep_table) = unit_tables.get(dep) else {
625                continue;
626            };
627            let dep_types =
628                bynk_check::symbols::contract_types_for(dep, unit_tables, unit_uses, unit_consumes)
629                    .0;
630            let all = bynk_check::contract::own_contract_hashes(dep_table, &dep_types);
631            let hashes: std::collections::BTreeMap<String, String> = all
632                .into_iter()
633                .filter(|(svc, _)| services.contains(svc))
634                .collect();
635            if !hashes.is_empty() {
636                // #2485: the structure behind each hash, from the same
637                // dependency table.
638                let dep_shapes: std::collections::BTreeMap<String, String> =
639                    bynk_check::contract_compat::own_contract_shapes(dep_table, &dep_types)
640                        .into_iter()
641                        .filter(|(svc, _)| hashes.contains_key(svc))
642                        .collect();
643                expects_shapes.insert(dep.clone(), dep_shapes);
644                expects.insert(dep.clone(), hashes);
645            }
646        }
647        // I4 (#1970): what each declared foreign caller's generated
648        // client embeds, recorded beside `provides` so `deploy` can
649        // hold it against the caller's pin.
650        let foreign = emitter::client::foreign_contracts(table, own_types);
651        let contracts = emitter::contracts::ContractParts {
652            provides: bynk_check::contract::own_contract_hashes(table, own_types),
653            expects,
654            foreign,
655            provides_shapes: bynk_check::contract_compat::own_contract_shapes(table, own_types),
656            expects_shapes,
657            accepts: accepted.hashes.clone(),
658        };
659        // A group's members share one Worker and so one manifest, merged by
660        // `finish_worker` (#3562).
661        if !layout.is_member(ctx_name)
662            && let Some(manifest) = contracts.render()
663        {
664            compiled.push(StagedFile {
665                output_path: layout.member_file(ctx_name, emitter::contracts::CONTRACTS_MANIFEST),
666                document: Document::Json(manifest),
667                source_map: None,
668                debug_metadata: None,
669            });
670        }
671
672        // I4 (#1970): the typed TypeScript client a foreign caller
673        // imports, when the context declares one.
674        if let Some(client) = emitter::client::emit_client(ctx_name, table, own_types) {
675            compiled.push(StagedFile {
676                output_path: layout.member_file(ctx_name, emitter::client::CLIENT_FILE),
677                document: Document::Ts(client),
678                source_map: None,
679                debug_metadata: None,
680            });
681        }
682
683        // v0.172 (ADR 0195 D5): the secret names this Worker's handlers
684        // will read from `env`, for `deploy` to check before it pushes.
685        // Emitted from the same seams the entry lowers, so the two
686        // cannot describe different Workers.
687        //
688        // v0.173 (ADR 0196): plus the literal `bynk.Secrets` names it
689        // reads, and whether that list is everything. The walk is here
690        // rather than in the checker because it needs `unit_flattened`
691        // to answer *whose* `Secrets` this is (D4) and the warning sink
692        // to say when it cannot know a name — and `bynk-check` has
693        // neither. Absent when there is nothing at all to say (D5).
694        // The warnings half is dropped here: `run_checks` already raised
695        // it, on the analyse path the editor shares.
696        let reads = emitter::secrets::secret_reads(
697            ctx_name,
698            unit_tables,
699            unit_consumes,
700            unit_consumes_aliases,
701            unit_flattened,
702        );
703        let secrets = emitter::secrets::SecretsParts::of(table, &reads);
704        if !layout.is_member(ctx_name)
705            && let Some(manifest) = secrets.render()
706        {
707            compiled.push(StagedFile {
708                output_path: layout.member_file(ctx_name, emitter::secrets::SECRETS_MANIFEST),
709                document: Document::Json(manifest),
710                source_map: None,
711                debug_metadata: None,
712            });
713        }
714        (contracts, secrets)
715    }
716
717    /// What a Worker's `wrangler.toml` gains beyond its bindings: the static
718    /// files it serves under its assets directory (with `_headers` and the
719    /// `[assets]` block), the Workers Cache for an `EdgeCache` instance, and the
720    /// `CompiledWasm` rule for a WebAssembly module its adapter closure reaches.
721    /// A group's members share one Worker, so each is asked and each block is
722    /// added once.
723    fn stage_worker_extras(
724        &self,
725        members: &[(&str, &UnitTable)],
726        wrangler_doc: &mut crate::emitter::toml_doc::TomlDocument,
727        staged_assets: &mut BTreeMap<PathBuf, Vec<u8>>,
728    ) {
729        let WorkersEmit {
730            adapter_bindings,
731            asset_files,
732            asset_served,
733            kinds,
734            layout,
735            unit_consumes,
736            unit_tables,
737            unit_uses,
738            ..
739        } = *self;
740        // #1883, slice 1b: the static files this Worker serves — its
741        // own and those of every commons its `uses` closure reaches —
742        // under its assets directory, with `_headers` and the
743        // `[assets]` block. A Worker with none gets neither.
744        let mut deployed = BTreeMap::new();
745        for (ctx_name, _) in members {
746            deployed.extend(bynk_check::assets::deployed_assets(
747                ctx_name,
748                unit_uses,
749                unit_consumes,
750                unit_tables,
751                asset_served,
752            ));
753        }
754        if !deployed.is_empty() {
755            let dir = worker_assets_dir(&layout.dir(members[0].0));
756            for (served, source) in &deployed {
757                let bytes = asset_files
758                    .and_then(|files| files.get(source))
759                    .cloned()
760                    .unwrap_or_else(|| {
761                        panic!("bynk internal error: deployed asset `{source}` was never read")
762                    });
763                staged_assets.insert(dir.join(served.trim_start_matches('/')), bytes);
764            }
765            staged_assets.insert(
766                dir.join("_headers"),
767                emitter::wrangler::asset_headers().into_bytes(),
768            );
769            wrangler_doc.push_block(emitter::wrangler::assets_block());
770        }
771        // L7 (#2414): an `EdgeCache` instance turns Workers Cache on.
772        if members
773            .iter()
774            .any(|(_, table)| table.derived.values().any(|d| d.is_edge_cache()))
775        {
776            wrangler_doc.push_block(emitter::wrangler::edge_cache_block());
777        }
778        // #2321: a Worker whose adapter closure reaches an included
779        // WebAssembly module gets the explicit `CompiledWasm` rule.
780        if members.iter().any(|(ctx_name, _)| {
781            worker_reaches_wasm_module(ctx_name, unit_consumes, kinds, adapter_bindings)
782        }) {
783            wrangler_doc.push_block(emitter::wrangler::wasm_rule_block());
784        }
785    }
786}
787
788/// What one context contributes to its Worker's `wrangler.toml` and, in a
789/// group, to the group's entry ([`WorkersEmit::emit_member`]).
790pub(crate) struct MemberParts {
791    context: String,
792    crons: Vec<String>,
793    queues: Vec<String>,
794    addresses: Vec<String>,
795    /// Whether it subscribes to events (answers `/_bynk/event/`).
796    has_events: bool,
797    /// Whether it hosts a migratable agent (answers `/_bynk/migrate/`).
798    has_migrate: bool,
799    /// Whether it hosts an agent a `bynk dev` build can inspect.
800    has_inspect: bool,
801    /// The agent classes a `bynk dev` build can inspect.
802    inspect_classes: Vec<String>,
803    /// The Durable Object classes its entry exports.
804    classes: Vec<String>,
805    /// Its contract and secrets manifests, merged into the Worker's own when it is
806    /// in a group (#3562).
807    contracts: emitter::contracts::ContractParts,
808    secrets: emitter::secrets::SecretsParts,
809    /// Whether a group member publishes, so the group's one fan-out routes its
810    /// events (#3562).
811    publishes: bool,
812}
813
814/// #3562 (G6): which member owns which agent class in a `bynk dev` group, for
815/// `bynk dev inspect`, which signs each request for the member that answers it: the
816/// listing for the first member that hosts an agent, a read for the class's owner.
817/// `None` when no member hosts one (and in a deploy build, which has no inspect).
818///
819/// Written as `serde_json::to_string_pretty` would (sorted keys, two-space indent), by
820/// hand: the shape is two fields, and this crate takes no JSON dependency.
821fn group_inspect_manifest(members: &[(&MemberParts, &UnitTable)]) -> Option<String> {
822    // Every member is named, those hosting no agent with no classes, so that
823    // `bynk dev inspect --context <member>` finds the group for any of them.
824    members.iter().any(|(p, _)| p.has_inspect).then(|| {
825        let all: Vec<(&str, &[String])> = members
826            .iter()
827            .map(|(p, _)| (p.context.as_str(), p.inspect_classes.as_slice()))
828            .collect();
829        render_inspect_members(&all)
830    })
831}
832
833/// The listing of [`group_inspect_manifest`], from each member's context and classes.
834fn render_inspect_members(members: &[(&str, &[String])]) -> String {
835    let all: Vec<String> = members
836        .iter()
837        .map(|(context, classes)| {
838            format!(
839                "    {{\n      \"classes\": {},\n      \"context\": {}\n    }}",
840                json_string_array(classes, 6),
841                bynk_project::json_string(context),
842            )
843        })
844        .collect();
845    format!("{{\n  \"members\": [\n{}\n  ]\n}}\n", all.join(",\n"))
846}
847
848/// #3562 (G5): which context of a Worker owns which agent class, for `bynk deploy`: a
849/// class's state belongs to its Worker's script, so a context that hosts agents moving to
850/// another script must not be redeployed over empty state unannounced. Only a group has one
851/// (a Worker that is one context owns its own classes). `None` when no member hosts an agent.
852///
853/// Written as `serde_json::to_string_pretty` would (sorted keys, two-space indent).
854fn agents_manifest(members: &[(&MemberParts, &UnitTable)]) -> Option<String> {
855    let agents: BTreeMap<&str, Vec<String>> = members
856        .iter()
857        .filter_map(|(parts, table)| {
858            let mut classes: Vec<String> = table.agents.keys().cloned().collect();
859            classes.sort();
860            (!classes.is_empty()).then_some((parts.context.as_str(), classes))
861        })
862        .collect();
863    (!agents.is_empty()).then(|| render_agents(&agents))
864}
865
866/// The manifest of [`agents_manifest`], from each hosting context's classes.
867fn render_agents(agents: &BTreeMap<&str, Vec<String>>) -> String {
868    let entries: Vec<String> = agents
869        .iter()
870        .map(|(context, classes)| {
871            format!(
872                "    {}: {}",
873                bynk_project::json_string(context),
874                json_string_array(classes, 4)
875            )
876        })
877        .collect();
878    format!("{{\n  \"agents\": {{\n{}\n  }}\n}}\n", entries.join(",\n"))
879}
880
881/// A JSON array of strings, one item per line at `indent` + 2 spaces, as
882/// `serde_json::to_string_pretty` lays it out; `[]` when empty.
883fn json_string_array(items: &[String], indent: usize) -> String {
884    if items.is_empty() {
885        return "[]".to_string();
886    }
887    let pad = " ".repeat(indent);
888    let lines: Vec<String> = items
889        .iter()
890        .map(|item| format!("{pad}  {}", bynk_project::json_string(item)))
891        .collect();
892    format!("[\n{}\n{pad}]", lines.join(",\n"))
893}
894
895/// Whether any service of `table` has an `on event` handler.
896fn own_handles_events(table: &UnitTable) -> bool {
897    table.services.values().any(|s| {
898        s.handlers.iter().any(|h| {
899            matches!(
900                bynk_model::lower_handler_kind_ir(&h.kind),
901                bynk_model::IrHandlerKind::Event
902            )
903        })
904    })
905}
906
907/// The plan's unit for a context the driver is emitting. Every grouped context
908/// has a checked `UnitTable`, so the plan covers it.
909fn planned_unit<'a>(plan: &'a emitter::ComposePlan, context: &str) -> &'a emitter::ComposeUnit {
910    plan.units
911        .get(context)
912        .expect("the compose plan has a unit for every context with a checked table")
913}
914
915/// The files a Worker's bindings stage beside its `wrangler.toml`: P4b (#2608)
916/// each `D1` database's migrations, under the `migrations_dir` the config names,
917/// and Hyperdrive H5 (#3322) which Hyperdrive bindings are MySQL and their TLS
918/// modes, for `bynk deploy` (a Worker with no `MySql` instance gets no file).
919pub fn stage_binding_files(
920    bindings: &[emitter::bindings::WorkerBinding],
921    layout: &WorkerLayout,
922    context: &str,
923    d1_migrations: &bynk_check::d1_migrations::D1Migrations,
924    compiled: &mut Vec<StagedFile>,
925) {
926    // A D1 database is named from the Worker, as the migrations' check side
927    // (`d1_migrations`, `d1_sql`) and `wrangler.toml`'s `d1_block` name it, so
928    // all of them agree.
929    let dashes = layout.dir(context);
930    if let Some(manifest) = emitter::wrangler::emit_hyperdrive_manifest(bindings) {
931        compiled.push(StagedFile {
932            output_path: layout.worker_file(context, emitter::wrangler::HYPERDRIVE_MANIFEST),
933            document: Document::Json(manifest),
934            source_map: None,
935            debug_metadata: None,
936        });
937    }
938    // #3479: each `Vectorize` index's configuration, for `bynk deploy` to
939    // create the index with and check it against.
940    if let Some(manifest) = emitter::wrangler::emit_vectorize_manifest(bindings) {
941        compiled.push(StagedFile {
942            output_path: layout.worker_file(context, emitter::wrangler::VECTORIZE_MANIFEST),
943            document: Document::Json(manifest),
944            source_map: None,
945            debug_metadata: None,
946        });
947    }
948    // #3477: each container's capability, build directory and instance type,
949    // for `bynk deploy` to plan from and to adopt an image against.
950    if let Some(manifest) = emitter::wrangler::emit_containers_manifest(bindings) {
951        compiled.push(StagedFile {
952            output_path: layout.worker_file(context, emitter::wrangler::CONTAINERS_MANIFEST),
953            document: Document::Json(manifest),
954            source_map: None,
955            debug_metadata: None,
956        });
957    }
958    for binding in bindings {
959        if !matches!(
960            binding.source,
961            emitter::bindings::BindingSource::D1Database { .. }
962        ) {
963            continue;
964        }
965        let database = emitter::wrangler::d1_database_name(&dashes, &binding.name);
966        for file in bynk_check::d1_migrations::migrations_of(d1_migrations, &database, binding) {
967            compiled.push(StagedFile {
968                output_path: layout.worker_file(
969                    context,
970                    &format!(
971                        "{}/{database}/{}",
972                        emitter::wrangler::D1_MIGRATIONS_DIR,
973                        file.name
974                    ),
975                ),
976                document: Document::Sql(file.sql.clone()),
977                source_map: None,
978                debug_metadata: None,
979            });
980        }
981    }
982}
983
984/// State-migrations S4 (#2259 Decision D): the context's versioned agent classes,
985/// which its Worker's signed `/_bynk/migrate/` route can wake, with their lock
986/// versions, sorted.
987fn migratable_agents(
988    ctx_name: &str,
989    table: &UnitTable,
990    agent_versions: &std::collections::HashMap<String, bynk_check::schema_registry::AgentVersions>,
991) -> Vec<(String, i64)> {
992    let mut migratable: Vec<(String, i64)> = agent_versions
993        .iter()
994        .filter_map(|(class, v)| {
995            let (unit, agent) = class.rsplit_once('.')?;
996            (unit == ctx_name && table.agents.contains_key(agent))
997                .then(|| (agent.to_string(), v.version))
998        })
999        .collect();
1000    migratable.sort();
1001    migratable
1002}
1003
1004#[cfg(test)]
1005mod tests {
1006    use super::*;
1007    use serde_json::json;
1008
1009    /// Names that need escaping: a quote, a backslash, the three short control
1010    /// escapes both writers use (`\t`, `\n`, `\r`), control characters with only a
1011    /// `\u00xx` form, and non-ASCII (which `serde_json` writes as it is). U+0008
1012    /// and U+000C are left out: `serde_json` writes them `\b` and `\f`, while
1013    /// `json_string` writes `\u0008` and `\u000c`, the same value spelt
1014    /// differently, so the byte-for-byte comparisons below would not hold.
1015    const AWKWARD: &[&str] = &[
1016        "q\"uote",
1017        "back\\slash",
1018        "tab\tnl\ncr\r",
1019        "bell\u{7}\u{1f}",
1020        "caf\u{e9} \u{4e2d}\u{1f600}",
1021    ];
1022
1023    fn classes(names: &[&str]) -> Vec<String> {
1024        names.iter().map(|c| c.to_string()).collect()
1025    }
1026
1027    /// What `serde_json::to_string_pretty` printed for the group listing before
1028    /// the layout was written by hand: sorted keys, two-space indent, `[]` for
1029    /// no classes, and every awkward name escaped the same way (the writer
1030    /// reuses `bynk_project::json_string`).
1031    #[test]
1032    fn the_group_inspect_listing_is_laid_out_as_pretty_json() {
1033        let (orders, pay, odd) = (
1034            classes(&["Counter", "Ledger"]),
1035            classes(&[]),
1036            classes(AWKWARD),
1037        );
1038        let odd_context = AWKWARD.join("/");
1039        let ours = render_inspect_members(&[
1040            ("shop.orders", &orders),
1041            ("shop.pay", &pay),
1042            (&odd_context, &odd),
1043        ]);
1044        let theirs = serde_json::to_string_pretty(&json!({ "members": [
1045            { "context": "shop.orders", "classes": orders },
1046            { "context": "shop.pay", "classes": pay },
1047            { "context": odd_context, "classes": odd },
1048        ] }))
1049        .unwrap()
1050            + "\n";
1051        assert_eq!(ours, theirs);
1052        assert!(ours.contains("\"classes\": [],"), "{ours}");
1053    }
1054
1055    /// The agents manifest is what `serde_json` printed: contexts and classes in
1056    /// order, and every awkward name escaped.
1057    #[test]
1058    fn the_agents_manifest_is_laid_out_as_pretty_json() {
1059        let odd_context = AWKWARD.join("/");
1060        let agents = BTreeMap::from([
1061            ("shop.pay", classes(&["Counter", "Ledger"])),
1062            (odd_context.as_str(), classes(AWKWARD)),
1063            ("\u{e9}clair", classes(&["A"])),
1064        ]);
1065        let theirs = serde_json::to_string_pretty(&json!({ "agents": {
1066            "shop.pay": ["Counter", "Ledger"],
1067            odd_context.as_str(): AWKWARD,
1068            "\u{e9}clair": ["A"],
1069        } }))
1070        .unwrap()
1071            + "\n";
1072        assert_eq!(render_agents(&agents), theirs);
1073    }
1074}