Skip to main content

bynk_emit/
emit_model.rs

1//! The model the code generator shares with the orchestration layer: the
2//! output documents (`Artefacts`, `Document`, `ProjectOutput`), the import
3//! extension, the per-unit emission context (`EmitProjectCtx`) and the
4//! provider-instantiation expressions the emitter splices into generated code.
5//!
6//! Crate-hygiene D1 (#2982, PR 1): these lived in `project.rs`, which made the
7//! emitter import its own orchestrator. They move here so `project` can leave
8//! this crate for `bynk-driver` without the emitter depending on it. `project`
9//! re-exports everything below at its old path until then.
10
11use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
12use std::path::{Path, PathBuf};
13
14use crate::emitter;
15use bynk_check::actors::ActorDecl;
16use bynk_check::checker::ExprId;
17use bynk_check::firstparty::FirstPartyCap;
18use bynk_check::project_model::BuildTarget;
19use bynk_check::project_model::{AdapterBinding, Visibility, resolve_consume_prefix};
20use bynk_check::resolver::{self};
21use bynk_check::symbols::*;
22use bynk_model::CapRefIr;
23use bynk_model::FnSig;
24use bynk_model::lower_provider_given_ir;
25use bynk_project::discovery::*;
26use bynk_project::paths::*;
27use bynk_project::{AttributedError, UnitKind};
28/// A project's output, as a keyed set of typed documents (R7.8, #1309) —
29/// replaces the old `ProjectOutput.files: Vec<CompiledFile>` outright, not
30/// alongside it ("Done when": `CompiledFile`/`ProjectOutput::files` are
31/// gone, not aliased). Keyed by output path (project-root-relative), so the
32/// sibling-path lookup `bynk-driver::output` needs for `.map`/
33/// `.bynkdbg.json` files is a direct map operation instead of a linear scan,
34/// and so a `wrangler.toml` document carries its real [`crate::emitter::
35/// toml_doc::TomlDocument`] all the way to the write boundary instead of
36/// being stringified at construction (Decision E).
37pub struct Artefacts {
38    pub docs: BTreeMap<PathBuf, Document>,
39    /// #1883, slice 0 (the binary-safe emission path the 2026-10-10 comment
40    /// names as a prerequisite): static-asset files, as raw bytes, keyed the
41    /// same way as `docs` (output-root-relative). Every key lies under a
42    /// Worker's [`WORKER_ASSETS_DIR`] ([`is_worker_asset_path`]).
43    ///
44    /// A sibling map rather than a `Document::Bytes` variant: every
45    /// `Document` has a text rendering ([`Document::text`], which golden
46    /// fixtures, `bynk-strip` and `bynk-wasm` all call), and an asset such as
47    /// a PNG has none. Keeping bytes out of `Document` means no caller of
48    /// `text()` has to decide what a binary file's text is. `bynk-strip`
49    /// passes this map through untouched; `bynk-driver::output::write_output`
50    /// writes and reconciles it alongside `docs`.
51    ///
52    /// Filled by a Workers build (slice 1b, `build_output`) with each Worker's
53    /// files and `_headers`; always empty for a Bundle build.
54    pub assets: BTreeMap<PathBuf, Vec<u8>>,
55    /// #2321: the WebAssembly modules adapter bindings include
56    /// (`binding "…" includes ["./x.wasm"]`), as raw bytes keyed by
57    /// output-root-relative path, beside the binding that loads them. Module
58    /// files are code, not assets: never served, and not under a Worker's
59    /// assets directory. Each has a generated loader shim at
60    /// [`wasm_shim_path`] in `docs` (the Workers form); a host that runs the
61    /// output on Node writes [`node_wasm_shim`] over it.
62    pub modules: BTreeMap<PathBuf, Vec<u8>>,
63}
64
65/// #2321: the generated loader beside an included module, whose default export
66/// is the compiled `WebAssembly.Module`. `adapters/x.wasm` → `adapters/x.wasm.ts`.
67pub fn wasm_shim_path(module: &Path) -> PathBuf {
68    let mut name = module.as_os_str().to_os_string();
69    name.push(".ts");
70    PathBuf::from(name)
71}
72
73/// The Workers form of the loader: Wrangler compiles `./x.wasm` to a
74/// `WebAssembly.Module` at deploy (`CompiledWasm` rule in `wrangler.toml`).
75pub fn workers_wasm_shim(module: &Path) -> String {
76    let file = module
77        .file_name()
78        .map(|n| n.to_string_lossy().into_owned())
79        .unwrap_or_default();
80    format!(
81        "// Generated by bynk — do not edit by hand.\nimport module from \"./{file}\";\n\nexport default module;\n"
82    )
83}
84
85/// The Node form of the loader (#2321, decision B): the module's bytes inlined
86/// and compiled at load, so it needs no file beside the compiled output (`tsc`
87/// copies only TypeScript and JSON) and no Node typings. `bynk test` writes
88/// this over the Workers form at [`wasm_shim_path`].
89pub fn node_wasm_shim(bytes: &[u8]) -> String {
90    format!(
91        "// Generated by bynk — do not edit by hand.\nconst bytes = Uint8Array.from(atob(\"{}\"), (c) => c.charCodeAt(0));\n\nexport default await WebAssembly.compile(bytes);\n",
92        base64_encode(bytes)
93    )
94}
95
96fn base64_encode(bytes: &[u8]) -> String {
97    const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
98    let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
99    for chunk in bytes.chunks(3) {
100        let n = (u32::from(chunk[0]) << 16)
101            | (u32::from(*chunk.get(1).unwrap_or(&0)) << 8)
102            | u32::from(*chunk.get(2).unwrap_or(&0));
103        out.push(TABLE[(n >> 18) as usize & 63] as char);
104        out.push(TABLE[(n >> 12) as usize & 63] as char);
105        out.push(if chunk.len() > 1 {
106            TABLE[(n >> 6) as usize & 63] as char
107        } else {
108            '='
109        });
110        out.push(if chunk.len() > 2 {
111            TABLE[n as usize & 63] as char
112        } else {
113            '='
114        });
115    }
116    out
117}
118
119/// #2321: whether `ctx`'s `consumes` closure (through adapter-to-adapter
120/// `consumes` too) reaches an adapter whose binding includes a module.
121pub fn worker_reaches_wasm_module(
122    ctx: &str,
123    unit_consumes: &HashMap<String, Vec<String>>,
124    kinds: &BTreeMap<String, UnitKind>,
125    adapter_bindings: &HashMap<String, AdapterBinding>,
126) -> bool {
127    let mut seen: HashSet<&str> = HashSet::new();
128    let mut stack: Vec<&str> = vec![ctx];
129    while let Some(unit) = stack.pop() {
130        if !seen.insert(unit) {
131            continue;
132        }
133        if adapter_bindings
134            .get(unit)
135            .is_some_and(|b| !b.includes.is_empty())
136        {
137            return true;
138        }
139        // Another context is a Service Binding away, not in this Worker.
140        if unit != ctx && kinds.get(unit) == Some(&UnitKind::Context) {
141            continue;
142        }
143        stack.extend(
144            unit_consumes
145                .get(unit)
146                .into_iter()
147                .flatten()
148                .map(String::as_str),
149        );
150    }
151    false
152}
153
154/// Ambient type for the Workers loader's `import module from "./x.wasm"`.
155pub const WASM_MODULES_DTS: &str = "// Generated by bynk — do not edit by hand.\ndeclare module \"*.wasm\" {\n  const module: WebAssembly.Module;\n  export default module;\n}\n";
156
157/// #1883, slice 0: the name of the directory, inside a Worker's own
158/// `workers/<dashes>/` output directory, that holds its static assets — the
159/// directory the generated `wrangler.toml`'s `[assets] directory` names
160/// (`emitter::wrangler::assets_block`). Separate from the Worker's own output so the compiled Worker and
161/// its source maps are never served as public assets.
162///
163/// The compiler owns everything under it: `bynk-driver::output::write_output`
164/// prunes any file there that the current build did not produce, whatever
165/// its extension (an asset keeps its source's extension, and the platform's
166/// `_headers` file has none). Shared by the producer and the pruner through
167/// [`worker_assets_dir`] / [`is_worker_asset_path`] so the two can't drift.
168pub const WORKER_ASSETS_DIR: &str = "assets";
169
170/// #1883, slice 0: `workers/<dashes>/<WORKER_ASSETS_DIR>`, the output-root-
171/// relative directory holding one Worker's static assets.
172pub fn worker_assets_dir(dashes: &str) -> PathBuf {
173    PathBuf::from("workers")
174        .join(dashes)
175        .join(WORKER_ASSETS_DIR)
176}
177
178/// #1883, slice 0: whether `rel` (output-root-relative) names a file inside
179/// some Worker's assets directory — `workers/<dashes>/<WORKER_ASSETS_DIR>/…`,
180/// at any depth. The ownership rule `bynk-driver::output`'s reconciliation
181/// applies regardless of extension.
182///
183/// Every component after the assets directory must be a plain name
184/// (`Component::Normal`), not just present. Review of #1902: `components()`
185/// keeps `..`, so checking only that the tail was non-empty accepted
186/// `workers/x/assets/../../../../etc/x`, which the driver's `dir.join` would
187/// then write outside the output root, where reconciliation can never see
188/// it. Slice 1 derives these paths from source, so this is a security rule,
189/// not tidiness.
190pub fn is_worker_asset_path(rel: &Path) -> bool {
191    use std::path::Component;
192    let mut parts = rel.components();
193    let mut tail_len = 0usize;
194    matches!(parts.next(), Some(Component::Normal(w)) if w == "workers")
195        && matches!(parts.next(), Some(Component::Normal(_)))
196        && matches!(parts.next(), Some(Component::Normal(a)) if a == WORKER_ASSETS_DIR)
197        && parts.all(|c| {
198            tail_len += 1;
199            matches!(c, Component::Normal(_))
200        })
201        && tail_len > 0
202}
203
204/// P4b (#2608): whether `rel` (output-root-relative) names a file in some
205/// Worker's copied D1 migrations, `workers/<dashes>/migrations/…`, where
206/// `bynk-driver::output`'s reconciliation prunes a `.sql` the build no longer
207/// produces. Every component must be a plain name, as for
208/// [`is_worker_asset_path`].
209pub fn is_worker_migration_path(rel: &Path) -> bool {
210    use std::path::Component;
211    let mut parts = rel.components();
212    let mut tail_len = 0usize;
213    matches!(parts.next(), Some(Component::Normal(w)) if w == "workers")
214        && matches!(parts.next(), Some(Component::Normal(_)))
215        && matches!(parts.next(), Some(Component::Normal(m)) if m == emitter::wrangler::D1_MIGRATIONS_DIR)
216        && parts.all(|c| {
217            tail_len += 1;
218            matches!(c, Component::Normal(_))
219        })
220        && tail_len > 0
221}
222
223/// One typed output document. No `String` at construction for TypeScript or
224/// TOML content (R7.8) — `Json`/`Js`/`SourceMap`/`DebugSidecar` stay opaque
225/// payloads because `bynk-emit` never re-parses them itself, not because
226/// they're an escape hatch from the rule.
227pub enum Document {
228    /// A generated TypeScript module. Every `bynk-emit` construction site
229    /// builds this today by wrapping its still-`String`-producing content in
230    /// one `TsStmt::verbatim(VerbatimOrigin::NotYetConverted, ..)` — see that
231    /// variant's own doc comment for why each site does this literally,
232    /// rather than through one shared helper.
233    Ts(bynk_ts::TsProgram),
234    /// `wrangler.toml`, still as the real tree `emit_wrangler_toml` built —
235    /// printed only at the `bynk-driver` write boundary.
236    Toml(crate::emitter::toml_doc::TomlDocument),
237    /// Generated JSON with no tree this compiler tracks yet (`package.json`,
238    /// `tsconfig.json`, the contracts/secrets manifests).
239    Json(String),
240    /// Type-stripped JavaScript (`bynk-strip::strip_project_to_js`'s own
241    /// output) — never produced by `bynk-emit` itself, which only ever
242    /// builds `Ts`; kept distinct from `Ts` so a stripped artefact never
243    /// round-trips back through the TypeScript printer/lint.
244    Js(String),
245    /// A source-map v3 document, split out of its originating file's own
246    /// staged `source_map` at the sibling path `write_output` names it
247    /// (`<file>.map`).
248    SourceMap(String),
249    /// The handler-label debug sidecar, split out the same way at
250    /// `<file>.bynkdbg.json`.
251    DebugSidecar(String),
252    /// P4b (#2608): a `D1` migration, copied verbatim from the project's
253    /// `migrations/` folder beside the Worker's `wrangler.toml`.
254    Sql(String),
255}
256
257impl Document {
258    /// This document's own text, whichever kind it is — for read-side
259    /// callers that only need bytes (golden fixtures, `bynk-strip`'s own
260    /// need to feed `Ts` content through `strip_types`, `bynk-wasm`'s
261    /// JS-facing API, in-process test helpers). `Ts`/`Toml` print through
262    /// the same printer `bynk-driver::output::write_document` writes from
263    /// (R7.3/R7.6) — this is a rendering, not a second construction path;
264    /// nothing here builds a `Document` from a `String`.
265    pub fn text(&self) -> String {
266        match self {
267            Document::Ts(program) => bynk_ts::print(program, "", "", "").text,
268            Document::Toml(doc) => crate::emitter::print_toml_document(doc),
269            Document::Json(s)
270            | Document::Js(s)
271            | Document::SourceMap(s)
272            | Document::DebugSidecar(s)
273            | Document::Sql(s) => s.clone(),
274        }
275    }
276}
277
278/// One generated document, staged during `build_output`/`emit_unit` before
279/// the final split into [`Artefacts`] — see `build_output`'s own tail.
280pub struct StagedFile {
281    pub output_path: PathBuf,
282    pub source_map: Option<String>,
283    pub debug_metadata: Option<String>,
284    pub document: Document,
285}
286
287/// Result of compiling a project.
288pub struct ProjectOutput {
289    /// P7.6 (#1309): every generated document, typed (R7.8).
290    /// `bynk-driver::output::write_output` writes from this.
291    pub artefacts: Artefacts,
292    /// v0.89 (ADR 0117): non-failing warnings emitted on a successful build —
293    /// surfaced (the CLI prints them, the LSP shows them) but not gating.
294    pub warnings: Vec<AttributedError>,
295    /// Per-file source snapshots, keyed the same way `ProjectFailure::snapshots`
296    /// is — lets a warning render with real file/line/col context (ariadne or
297    /// `path:line:col:`) instead of the position-free `warning[category]: …`
298    /// fallback a successful build previously had no way to avoid.
299    pub snapshots: Vec<(PathBuf, String)>,
300    /// #1772: the project or tree root the build was given, as the caller
301    /// spelled it. `snapshots` and each error's `source_path` are keyed by
302    /// identity path, relative to this root; a renderer shows
303    /// `display_root.join(identity)`, the path as typed from the working
304    /// directory. Empty for an in-memory build.
305    pub display_root: PathBuf,
306    /// v0.67: the test manifest — every discovered suite and case, retained at
307    /// emit time so `bynk test --no-run --format json` can render a discovery
308    /// document without running the suite. bynk_ts::TsExpr from the same names + spans the
309    /// runner would emit at `suite-begin`/`case`, so a discovery document
310    /// reconciles cleanly against a later run's document (same suite name/kind,
311    /// same case names). Ordered to match the runner (`emit_test_main`).
312    pub discovered: Vec<DiscoveredSuite>,
313    /// #2842: the snapshot files (`snapshots/…snap.json`, project-relative) the
314    /// project's unit suites take a snapshot into. A `snapshots/` file not named
315    /// here belongs to no suite that still takes one: it is obsolete.
316    pub snapshot_files: BTreeSet<String>,
317    /// #1078: the reconciled `bynk.schema.lock` content, `Some` whenever
318    /// `CompileOptions::schema_registry` was `SchemaLock::On` for this build
319    /// — `bynk-emit` computes it but never writes it; a building caller
320    /// (`bynk compile`, `bynk dev`/`deploy`) persists it atomically, exactly
321    /// the discipline `schema_registry.rs` used to implement itself. `None`
322    /// when the registry was off, regardless of whether the content would
323    /// have changed — the unchanged-content no-op lives in the writer, not
324    /// here, so a caller that reconciles the same shape twice in a row still
325    /// gets `Some` both times.
326    pub schema_lock: Option<String>,
327    /// #2695: the `on call(...)` handler of each of the project's own
328    /// `service`s, described from the checker's resolved types, in unit then
329    /// service order. Empty for a project with none.
330    pub entry_handlers: Vec<bynk_model::entry::EntryHandler>,
331    /// 1C.3a (#4040): what a Workers build decided about its Workers'
332    /// bindings, for the commands that act on them to read instead of reading
333    /// them back out of the files the build wrote. `None` for a Bundle build,
334    /// which has no Workers.
335    pub workers: Option<WorkersBuild>,
336}
337
338/// 1C.3a (#4040): the binding model of a Workers build, with what the model
339/// is read against. `bindings` is the one [`WorkerBindings`] the build's
340/// `wrangler.toml` files were rendered from, so a reader of it sees exactly the
341/// bindings written.
342///
343/// [`WorkerBindings`]: crate::emitter::WorkerBindings
344#[derive(Debug, Clone)]
345pub struct WorkersBuild {
346    /// Every Worker's bindings.
347    pub bindings: crate::emitter::WorkerBindings,
348    /// Where each context's Worker is, and what it is called.
349    pub layout: bynk_project::worker_layout::WorkerLayout,
350}
351
352/// v0.67: a discovered test suite — one `test <target>` group (unit) or
353/// `test integration "<suite>"` (integration). `name` + `kind` mirror exactly
354/// what the NDJSON runner emits at `suite-begin` (kind `"unit"` carries the
355/// joined target name; `"integration"` carries the bare suite name), so the
356/// editor reconciles discovery and run documents to the same tree items.
357#[derive(Debug, Clone, PartialEq)]
358pub struct DiscoveredSuite {
359    pub name: String,
360    pub kind: &'static str,
361    pub cases: Vec<DiscoveredCase>,
362    /// #2138: the cases a remote build skipped (`--skip-unsupported`), and
363    /// why. Empty for every other build.
364    pub skipped: Vec<RemoteSkip>,
365    /// #2138: under `--against dev`, the distinct `env` maps this suite's
366    /// cases run with (`RemoteTests::dev`). Empty for every other build.
367    pub envs: Vec<BTreeMap<String, String>>,
368}
369
370/// One discovered `test "<name>"` case. `location` points at the case-name
371/// literal (a run *failure* instead points at the failing `assert`), giving the
372/// editor click-through to the declaration before any run.
373#[derive(Debug, Clone, PartialEq)]
374pub struct DiscoveredCase {
375    pub name: String,
376    pub location: Option<TestLocation>,
377    /// The case's effective tier (`"unit"`, `"integration"` or `"system"`: its own
378    /// `as <tier>`, else the suite default, else `unit`), when it has one. A
379    /// property or contract attack has none.
380    pub tier: Option<&'static str>,
381    /// `"property"` or `"history"` for a generative case (a `property`, a history
382    /// property or a contract attack), whose draws depend on the run's seed and on
383    /// its position among the module's generative cases. `None` for a `case`.
384    pub generative: Option<&'static str>,
385    /// A doc-comment example's case (#2461), set by the driver after a build that
386    /// compiled such examples in; `false` from emission. A document marks it
387    /// `"origin": "doc"`.
388    pub doc: bool,
389}
390
391/// A project-root-relative `path:line:col` source location, structured. Line and
392/// col are 1-indexed (the [`bynk_syntax::span::line_col`] convention).
393#[derive(Debug, Clone, PartialEq)]
394pub struct TestLocation {
395    pub path: String,
396    pub line: u32,
397    pub col: u32,
398}
399
400// P4.1 (#1115): `AdapterBinding` and `BuildTarget` relocated to
401// `bynk-check::project_model` alongside `phase_group`, which constructs
402// them — see that module's own doc comment. `BuildTarget` is re-exported
403// below at its old `crate::project::BuildTarget` path (part of this crate's
404// public surface); `AdapterBinding` was never public here, so a plain `use`
405// (above) is enough.
406
407/// The extension emitted import specifiers use (`import … from "./x.<ext>"`).
408///
409/// `Js` is the default and the only shape for normal builds: Node's ESM
410/// resolution and `tsc` require `.js` specifiers even though the sources are `.ts`. `Ts` is
411/// the **debug build** (slice 2, ADR 0104): `bynk test --inspect` runs the
412/// emitted `.ts` directly under Node's line-preserving strip-only type-stripping,
413/// where slice 1's source maps apply unchanged — but Node will not resolve a `.js`
414/// specifier to the `.ts` on disk, so the debug build emits `.ts` specifiers.
415#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
416pub enum ImportExt {
417    #[default]
418    Js,
419    Ts,
420}
421
422impl ImportExt {
423    /// The bare extension string (`"js"` / `"ts"`), for `Path::with_extension`
424    /// and specifier formatting.
425    pub fn as_str(self) -> &'static str {
426        match self {
427            ImportExt::Js => "js",
428            ImportExt::Ts => "ts",
429        }
430    }
431}
432
433/// v0.15: build the TypeScript expression instantiating the provider of
434/// capability `cap` declared in `provider_ctx`, recursively wiring its `given`
435/// dependencies — local sibling providers and cross-context capability
436/// providers alike. Stateless providers, so fresh instances per use are fine.
437///
438/// v0.18 (spec §4.5/§5.1): a *bare* `given` name resolves through the
439/// provider's own unit's flattened-capability map (`Fetch` → `bynk`), falling
440/// back to the unit itself; an *external* provider's deps are built the same
441/// way and passed to the binding class constructor by name. Every unit whose
442/// namespace the expression references is recorded in `referenced_units` so
443/// the caller can emit the matching imports (the transitive given-closure).
444///
445/// Locale capability track, slice 2 (#882, Decision C): the three extra
446/// constructor arguments `LocaleProvider` receives when its composing
447/// context has a uniquely-detected message bundle — the JS expressions
448/// themselves (an identifier for `request`, and the two cross-commons-
449/// imported bundle constants), not raw data, since they're spliced directly
450/// into the generated `new bynk__binding.LocaleProvider(...)` call.
451pub struct LocaleNegotiationArgs {
452    pub request_expr: String,
453    pub declared_locales_expr: String,
454    pub reference_locale_expr: String,
455}
456
457/// Where [`instantiate_provider_ts_expr`]'s expression finds each unit's
458/// provider classes: the module that constructs it imports each unit under a
459/// different namespace.
460#[derive(Clone, Copy)]
461pub enum ProviderNamespaces<'a> {
462    /// The bundle's `compose.ts`: `{ns}`.
463    Bundle,
464    /// No module: `native_platforms_of_context`'s walk for the *bare*
465    /// platform resources a context reaches (whether its Worker declares the
466    /// `KV` namespace). As `Bundle`, except that a derived capability's
467    /// instance (S4a, #1966) is not followed to its base: a named instance has
468    /// its own binding and does not imply the bare one.
469    BareResources,
470    /// A Worker's `compose.ts` or `handlers.ts`: `handlers_{ns}`.
471    ///
472    /// #2137: `harness_clock` is set in the test build of a context a
473    /// `system` harness stands up. Its first-party `Clock` then reads the
474    /// harness clock the test module puts on `env.__bynkClock`, falling back to
475    /// the real provider; a deployable build carries no suites, so it never
476    /// sets it.
477    Workers { harness_clock: bool },
478    /// A test module (#1863): `__ns_{ns}`, the test scaffold's own.
479    ///
480    /// `prebuilt` names, by `(unit, capability)`, the local that holds a
481    /// capability the test deps build at the top level: a provider's `given`
482    /// that resolves to one is that local, not a fresh construction, so a
483    /// `stub` overlaid on it reaches every provider built over it (#1864
484    /// review). Each one so used is recorded in `used`.
485    ///
486    /// #1975: `bindings` names, by adapter, the binding module a test module
487    /// imports as `{ns}__binding` when it builds that adapter's external
488    /// provider for real (an adapter suite, or an `integration` case); an
489    /// adapter absent from it is the placeholder. `double` answers a
490    /// capability that has a deterministic test double (`__bynkTest_<Cap>()`)
491    /// with that double, recording it, so a real binding's own `given` takes
492    /// the tier's double rather than the platform's real provider.
493    Test {
494        prebuilt: &'a HashMap<(String, String), String>,
495        used: &'a std::cell::RefCell<BTreeSet<(String, String)>>,
496        bindings: Option<&'a HashMap<String, String>>,
497        double: &'a dyn Fn(&str, &str) -> Option<bynk_ts::TsExpr>,
498    },
499}
500
501/// #3300: how [`ProviderNamespaces::BareResources`]' walk records reaching
502/// one-per-Worker capability `cap` of `unit` in its `referenced_units`:
503/// `bynk.cloudflare#Version`. No unit is named with a `#`, so the marker never
504/// resolves to a platform, and the bare `KV` namespace stays tied to reaching
505/// the unit through `Kv`.
506pub fn bare_singleton_marker(unit: &str, cap: &str) -> String {
507    format!("{unit}#{cap}")
508}
509
510/// The `(unit, capability)` a [`bare_singleton_marker`] names, or `None` for a
511/// plain unit name.
512pub fn parse_bare_singleton_marker(entry: &str) -> Option<(&str, &str)> {
513    entry.split_once('#')
514}
515
516/// `new {ns}.{class}({args})` as a real [`bynk_ts::TsExpr::New`] node.
517pub fn new_call_ts_expr(ns: &str, class: &str, args: Vec<bynk_ts::TsExpr>) -> bynk_ts::TsExpr {
518    bynk_ts::TsExpr::New {
519        callee: Box::new(bynk_ts::TsExpr::Member {
520            object: Box::new(bynk_ts::TsExpr::Ident(ns.to_string())),
521            property: class.to_string(),
522        }),
523        args,
524    }
525}
526
527/// `namespaces` selects the namespace convention ([`ProviderNamespaces`]): a
528/// bodied provider's class lives in `{ns}` under the bundle root,
529/// `handlers_{ns}` in a Worker compose and `__ns_{ns}` in a test module;
530/// external (binding) classes are `{ns}__binding` in the first two, and a
531/// test module has none. When `env_ident` is set (workers), env-taking
532/// first-party providers receive it as a constructor argument.
533///
534/// Locale capability track, slice 2 (#882): `locale_negotiation`, when
535/// `Some`, is threaded to exactly the `(bynk, LocaleProvider)` pair, the same
536/// way `env_ident` is threaded to `provider_takes_env`'s pairs — a small,
537/// closed set of first-party providers that need ambient, request-scoped
538/// construction data no ordinary `given` clause could express.
539///
540/// Originally a `TsExpr`-returning twin *alongside* a `String`-returning
541/// `instantiate_provider_expr` (the same "structural converter added
542/// alongside the `String` one" pattern Decision B already uses for
543/// `TypeRef -> TsType`) — #1321 (Arc C slice 3): `emitter::workers::
544/// emit_worker_compose` now builds a real `TsProgram` directly, and its own
545/// cross-context capability-provider `const {key} = {expr};` lines need a
546/// real `TsExpr`, not a `String` to splice. `workers.rs`'s own
547/// `emit_worker_compose` (Workers mode, `workers_ns: true`) and
548/// `emit_composition_root`'s own Bundle-mode `compose.ts` (#1327, Arc C
549/// slice 6, `workers_ns: false`) called this twin from the start. Originally
550/// hardcoded `workers_ns = true` (the only mode `emit_worker_compose`'s own
551/// call site used at the time) — #1327 restored the `workers_ns: bool`
552/// parameter its then-`String`-returning sibling always had, matching that
553/// signature exactly, once a second real caller needed `false`.
554/// Arc F slice 2 (#1452): `plan_agent_given_deps`/`native_platforms_of_context`
555/// (below in this file) repointed here too — `instantiate_provider_expr`
556/// itself had no callers left and is deleted; its parameter-contract prose
557/// and body rationale comments (below) moved here rather than being lost.
558#[allow(clippy::too_many_arguments)]
559pub fn instantiate_provider_ts_expr(
560    provider_ctx: &str,
561    cap: &str,
562    unit_tables: &HashMap<String, UnitTable>,
563    unit_consumes: &HashMap<String, Vec<String>>,
564    unit_consumes_aliases: &HashMap<String, HashMap<String, String>>,
565    unit_flattened: &HashMap<String, HashMap<String, String>>,
566    namespaces: ProviderNamespaces<'_>,
567    env_ident: Option<&str>,
568    locale_negotiation: Option<&LocaleNegotiationArgs>,
569    referenced_units: &mut BTreeSet<String>,
570) -> bynk_ts::TsExpr {
571    // S4a (#1966): a derived capability (`capability Sessions = Kv`) is its
572    // base's provider bound to the instance's own Worker binding: the base's
573    // expression (`new bynk_cloudflare__binding.WorkersKv(env)`) with the
574    // binding name as one more argument. Every composer (a Worker's compose,
575    // the bundle's `composeApp`, an agent's deps, a provider's `given`) builds
576    // an instance through here.
577    if let Some(inst) = unit_tables
578        .get(provider_ctx)
579        .and_then(|t| t.derived.get(cap))
580    {
581        if matches!(namespaces, ProviderNamespaces::BareResources) {
582            return bynk_ts::TsExpr::Ident("undefined".to_string());
583        }
584        let mut expr = instantiate_provider_ts_expr(
585            &inst.base_unit,
586            &inst.base_cap,
587            unit_tables,
588            unit_consumes,
589            unit_consumes_aliases,
590            unit_flattened,
591            namespaces,
592            env_ident,
593            locale_negotiation,
594            referenced_units,
595        );
596        // L7 (#2414): an `EdgeCache` instance has no binding: it purges
597        // through the entry's `ctx`, which a Worker's compose takes as `exec`.
598        // Anywhere else (the bundle) there is no edge cache, and the provider
599        // built without one purges nothing.
600        if inst.is_edge_cache() {
601            if let (ProviderNamespaces::Workers { .. }, bynk_ts::TsExpr::New { args, .. }) =
602                (namespaces, &mut expr)
603            {
604                args.push(bynk_ts::TsExpr::Ident("exec".to_string()));
605            }
606            return expr;
607        }
608        // Hyperdrive H1 (#3318): a Workers build hands a `Postgres` instance
609        // the runtime's driver as a third argument (the compose imports it).
610        // The binding never imports the package, so a project that does not
611        // declare an instance does not carry it. Anywhere else (the bundle)
612        // there is no driver, and the binding faults on use.
613        if inst.is_postgres()
614            && let (ProviderNamespaces::Workers { .. }, bynk_ts::TsExpr::New { args, .. }) =
615                (namespaces, &mut expr)
616        {
617            args.push(bynk_ts::TsExpr::Lit(bynk_ts::TsLit::Str(
618                inst.binding.clone(),
619            )));
620            args.push(bynk_ts::TsExpr::Ident("__pgExecute".to_string()));
621            return expr;
622        }
623        // Hyperdrive H5 (#3322): a `MySql` instance the same, with mysql2's.
624        if inst.is_mysql()
625            && let (ProviderNamespaces::Workers { .. }, bynk_ts::TsExpr::New { args, .. }) =
626                (namespaces, &mut expr)
627        {
628            args.push(bynk_ts::TsExpr::Lit(bynk_ts::TsLit::Str(
629                inst.binding.clone(),
630            )));
631            args.push(bynk_ts::TsExpr::Ident("__mysqlExecute".to_string()));
632            return expr;
633        }
634        // Review of #1968: anything but a construction to append the binding
635        // to would quietly read the default `KV`, so two instances would share
636        // a namespace. The one other shape is a test module's placeholder for
637        // a provider it cannot build, which has no binding to carry.
638        if let bynk_ts::TsExpr::New { args, .. } = &mut expr {
639            args.push(bynk_ts::TsExpr::Lit(bynk_ts::TsLit::Str(
640                inst.binding.clone(),
641            )));
642        } else if !(matches!(expr, bynk_ts::TsExpr::As { .. })
643            && matches!(namespaces, ProviderNamespaces::Test { .. }))
644        {
645            panic!(
646                "derived capability `{cap}`: base `{}.{}` is not built by a construction, so binding `{}` has nowhere to go",
647                inst.base_unit, inst.base_cap, inst.binding
648            );
649        }
650        return expr;
651    }
652    let ns = provider_ctx.replace('.', "_");
653    let bodied_ns = match namespaces {
654        ProviderNamespaces::Bundle | ProviderNamespaces::BareResources => ns.clone(),
655        ProviderNamespaces::Workers { .. } => format!("handlers_{ns}"),
656        ProviderNamespaces::Test { .. } => crate::emitter::emit::test_scaffold_ns(provider_ctx),
657    };
658    let provider = unit_tables
659        .get(provider_ctx)
660        .and_then(|t| t.providers.get(cap));
661    // #1863: an external provider is the same placeholder as a capability
662    // with no provider, unless (#1975) the test module builds this adapter's
663    // binding for real; a capability with a test double takes the double.
664    if let ProviderNamespaces::Test {
665        bindings, double, ..
666    } = namespaces
667        && provider.is_none_or(|p| p.external)
668        && !(provider.is_some() && bindings.is_some_and(|b| b.contains_key(provider_ctx)))
669    {
670        if let Some(d) = double(provider_ctx, cap) {
671            return d;
672        }
673        return bynk_ts::TsExpr::As {
674            expr: Box::new(bynk_ts::TsExpr::As {
675                expr: Box::new(bynk_ts::TsExpr::Ident("undefined".to_string())),
676                ty: bynk_ts::TsType::named("unknown"),
677            }),
678            ty: bynk_ts::TsType::named("never"),
679        };
680    }
681    // #3300: the bare-resources walk records a one-per-Worker capability by
682    // itself ([`bare_singleton_marker`]), not by its unit, so reaching
683    // `Version` declares `[version_metadata]` and never the bare `KV`
684    // namespace that reaching the unit would imply.
685    if matches!(namespaces, ProviderNamespaces::BareResources)
686        && bynk_check::firstparty::singleton(provider_ctx, cap).is_some()
687    {
688        referenced_units.insert(bare_singleton_marker(provider_ctx, cap));
689    } else {
690        referenced_units.insert(provider_ctx.to_string());
691    }
692    let Some(provider) = provider else {
693        return new_call_ts_expr(&bodied_ns, cap, vec![]);
694    };
695    // Build the by-name deps object from the provider's `given`, if any.
696    // #1187's Provider given/deps-wiring slice: reads bynk_model's own CapRefIr
697    // (lower_provider_given_ir — a standalone reader of the `given` clause,
698    // never a full provider IR; see that function's own doc comment) instead
699    // of walking the raw AST CapRef directly.
700    let given: Vec<CapRefIr> = lower_provider_given_ir(provider);
701    let deps_obj: Option<bynk_ts::TsExpr> = if given.is_empty() {
702        None
703    } else {
704        let consumed = unit_consumes.get(provider_ctx).cloned().unwrap_or_default();
705        let aliases = unit_consumes_aliases
706            .get(provider_ctx)
707            .cloned()
708            .unwrap_or_default();
709        let flattened = unit_flattened
710            .get(provider_ctx)
711            .cloned()
712            .unwrap_or_default();
713        let deps: Vec<(String, bynk_ts::TsExpr)> = given
714            .iter()
715            .map(|g| {
716                let target_ctx = match &g.context {
717                    Some(p) => resolve_consume_prefix(p, &consumed, &aliases)
718                        .unwrap_or_else(|| provider_ctx.to_string()),
719                    None => flattened
720                        .get(&g.name)
721                        .cloned()
722                        .unwrap_or_else(|| provider_ctx.to_string()),
723                };
724                if let ProviderNamespaces::Test { prebuilt, used, .. } = namespaces {
725                    let key = (target_ctx.clone(), g.name.clone());
726                    if let Some(local) = prebuilt.get(&key) {
727                        used.borrow_mut().insert(key);
728                        return (g.name.clone(), bynk_ts::TsExpr::Ident(local.clone()));
729                    }
730                }
731                let expr = instantiate_provider_ts_expr(
732                    &target_ctx,
733                    &g.name,
734                    unit_tables,
735                    unit_consumes,
736                    unit_consumes_aliases,
737                    unit_flattened,
738                    namespaces,
739                    env_ident,
740                    locale_negotiation,
741                    referenced_units,
742                );
743                (g.name.clone(), expr)
744            })
745            .collect();
746        Some(bynk_ts::TsExpr::object(deps))
747    };
748    // #2355: a bodied provider whose ops construct a local agent takes a
749    // `deps` even with no `given`, and on `workers` that `deps` carries the
750    // Worker's `env` for the agent factory (`emit::emit_provider`).
751    let deps_obj = if !provider.external
752        && bynk_check::project_model::provider_constructs_agent(provider, |n| {
753            unit_tables
754                .get(provider_ctx)
755                .is_some_and(|t| t.agents.contains_key(n))
756        }) {
757        let mut entries = match deps_obj {
758            Some(bynk_ts::TsExpr::Object { entries, .. }) => entries,
759            Some(other) => unreachable!("a provider's deps is an object literal: {other:?}"),
760            None => Vec::new(),
761        };
762        if matches!(namespaces, ProviderNamespaces::Workers { .. }) {
763            // Every Workers composer has the Worker's `env` in scope; leaving it
764            // out would fault at `this.deps.env` at runtime instead.
765            let env = env_ident.expect("a Workers composer passes its `env`");
766            entries.push(bynk_ts::TsObjectEntry::prop(
767                "env".to_string(),
768                bynk_ts::TsExpr::Ident(env.to_string()),
769            ));
770        }
771        Some(bynk_ts::TsExpr::object_entries(entries))
772    } else {
773        deps_obj
774    };
775    let mut args: Vec<bynk_ts::TsExpr> = deps_obj.into_iter().collect();
776    // v0.18/v0.19: env-taking first-party providers (the bynk surface's
777    // SecretsProvider; bynk.cloudflare's WorkersKv) receive the Worker `env`
778    // explicitly — decisions 0021/0025. Keyed by (unit, class).
779    if provider.external
780        && bynk_check::firstparty::provider_takes_env(provider_ctx, &provider.provider_name.name)
781        && let Some(env) = env_ident
782    {
783        args.push(bynk_ts::TsExpr::Ident(env.to_string()));
784    }
785    // Locale capability track, slice 2 (#882, Decision C): only an external
786    // provider of bynk's own `Locale` capability receives these. Since 1A.33
787    // the test is the capability's first-party identity, not the provider's
788    // name: today that is exactly `LocaleProvider`, the one `provides Locale`
789    // in `bynk.bynk`, and any later first-party `Locale` provider would need
790    // the same negotiation arguments. Every other provider's construction is
791    // unaffected, since every other call site passes `None`.
792    if provider.external
793        && first_party_of(cap, provider_ctx) == Some(FirstPartyCap::Locale)
794        && let Some(loc) = locale_negotiation
795    {
796        args.push(bynk_ts::TsExpr::Ident(loc.request_expr.clone()));
797        args.push(bynk_ts::TsExpr::Ident(loc.declared_locales_expr.clone()));
798        args.push(bynk_ts::TsExpr::Ident(loc.reference_locale_expr.clone()));
799    }
800    let class = &provider.provider_name.name;
801    // v0.17: an external (adapter) provider's class lives in the binding module,
802    // not the adapter's interface module — instantiate it from the binding
803    // namespace (`<adapter>__binding`, imported by the composition root).
804    if provider.external {
805        let built = new_call_ts_expr(&format!("{ns}__binding"), class, args);
806        // #2137: in the test build of a `system` participant, the first-party
807        // `Clock` reads the harness clock when the harness supplies one.
808        if let (
809            ProviderNamespaces::Workers {
810                harness_clock: true,
811            },
812            Some(env),
813        ) = (namespaces, env_ident)
814            && first_party_of(cap, provider_ctx) == Some(FirstPartyCap::Clock)
815        {
816            return harness_clock_or(env, &format!("{ns}__binding.{class}"), built);
817        }
818        built
819    } else {
820        new_call_ts_expr(&bodied_ns, class, args)
821    }
822}
823
824/// #2137: `(env as unknown as { __bynkClock?: <class> }).__bynkClock ?? <built>`
825/// — the harness clock a `system` test puts on a participant's `env`, else
826/// the real provider.
827pub fn harness_clock_or(env: &str, class: &str, built: bynk_ts::TsExpr) -> bynk_ts::TsExpr {
828    use bynk_ts::{TsBinaryOp, TsExpr, TsType, TsTypeMember};
829    let slot = TsExpr::As {
830        expr: Box::new(TsExpr::As {
831            expr: Box::new(TsExpr::Ident(env.to_string())),
832            ty: TsType::named("unknown"),
833        }),
834        ty: TsType::Object(vec![TsTypeMember::optional_prop(
835            "__bynkClock",
836            TsType::named(class),
837        )]),
838    };
839    TsExpr::Binary {
840        op: TsBinaryOp::NullishCoalescing,
841        left: Box::new(TsExpr::Member {
842            object: Box::new(slot),
843            property: "__bynkClock".to_string(),
844        }),
845        right: Box::new(built),
846    }
847}
848
849/// #2137: every context a `system` suite's harness stands up as a Worker (its
850/// participants and their event subscribers,
851/// `test_suites::infer_harness_participants`).
852pub fn harness_clock_contexts(
853    parsed: &[ParsedFile],
854    unit_tables: &HashMap<String, UnitTable>,
855    unit_consumes: &HashMap<String, Vec<String>>,
856    kinds: &BTreeMap<String, UnitKind>,
857) -> HashSet<String> {
858    let systems: Vec<String> = parsed
859        .iter()
860        .filter_map(ParsedFile::integration)
861        .map(|d| d.target.joined())
862        .collect();
863    if systems.is_empty() {
864        return HashSet::new();
865    }
866    let subscribers = bynk_check::symbols::discover_event_subscribers(unit_tables, unit_consumes);
867    systems
868        .iter()
869        .flat_map(|t| {
870            bynk_check::test_suites::infer_harness_participants(
871                t,
872                unit_consumes,
873                kinds,
874                &subscribers,
875            )
876        })
877        .collect()
878}
879
880/// Events track, slice 0 (spine #936): does any handler in this unit emit?
881/// The `UnitTable`-level analogue of `emitter::commons_uses_emit`, needed
882/// because compose works from the project-wide `UnitTable` map, not a single
883/// unit's `TypedCommons`. It is
884/// [`bynk_check::project_model::unit_table_uses_emit`], which decides the
885/// four emission gates here (the fan-out DO, the `dispatchToEventsFanout`
886/// import, the `EVENTS_FANOUT` binding and the `__eventsDispatch` field) and
887/// whether a bundle has a composition root for the
888/// `bynk.capability.not_provided` check, which the editor runs too. One
889/// predicate, so the check and the emitter cannot disagree.
890///
891/// `emitter::block_uses_emit` — the per-*handler* twin deciding
892/// `emit_service`/`emit_agent`'s own `deps.__eventsDispatch` *parameter*
893/// threading — reads the same resolved `Callee`
894/// (`1204_events_emit_shadowed_by_local_type`), so the two stay in
895/// agreement on every input.
896pub fn unit_table_uses_emit(
897    table: &UnitTable,
898    callees: Option<&HashMap<ExprId, bynk_check::checker::Callee>>,
899) -> bool {
900    bynk_check::project_model::unit_table_uses_emit(table, callees)
901}
902
903/// Whether `cap`, a capability declared by the unit `provider_ctx` (a provider's own unit),
904/// is bynk's own, and which one (1A.33: [`bynk_check::firstparty::resolve`]). A provider's
905/// capability is declared in its own unit, so nothing is flattened into it.
906fn first_party_of(cap: &str, provider_ctx: &str) -> Option<FirstPartyCap> {
907    bynk_check::firstparty::resolve(cap, provider_ctx, &HashMap::new())
908}
909
910/// W30 (#2840): does any body in this unit call the first-party `Idempotency`
911/// (`claim`, `dedup` or `remember`)? A Worker that does declares the implicit
912/// database that holds its claims and remembered values. The checker resolved each call's
913/// first-party identity (`consumes bynk { Idempotency }` makes `Idempotency` a local name for the
914/// `bynk` capability), so a same-named capability from another unit does not
915/// count, as for the key scoping in `scope_idempotency_key`.
916pub fn unit_table_uses_idempotency(
917    table: &UnitTable,
918    callees: Option<&HashMap<ExprId, bynk_check::checker::Callee>>,
919) -> bool {
920    let Some(callees) = callees else {
921        return false;
922    };
923    let mut found = false;
924    emitter::walk_unit_table_bodies(table, &mut |e| {
925        use bynk_check::checker::Callee;
926        if !found {
927            found = match callees.get(&e.id) {
928                Some(
929                    Callee::Capability {
930                        op,
931                        first_party: Some(FirstPartyCap::Idempotency),
932                        ..
933                    }
934                    | Callee::CrossCap {
935                        op,
936                        first_party: Some(FirstPartyCap::Idempotency),
937                        ..
938                    },
939                ) => matches!(op.as_str(), "claim" | "dedup" | "remember"),
940                _ => false,
941            };
942        }
943    });
944    found
945}
946
947/// Context passed to the emitter so it can resolve cross-file and
948/// cross-unit references into TypeScript import statements.
949/// The schema registry's reconciled versions, threaded from `run_checks` to
950/// each unit's emission: events keyed `<unit>.<Event>` (#980), agents keyed
951/// `<unit>.<Agent>` (state-migrations S1, #2211). Both empty when the build
952/// has no lock.
953#[derive(Debug, Default)]
954pub struct SchemaVersions {
955    pub events: HashMap<String, i64>,
956    pub agents: HashMap<String, bynk_check::schema_registry::AgentVersions>,
957}
958
959/// #3580: what a traced build needs to name a call site: the file's source text,
960/// to turn a byte offset into `line:col`, and its project-relative path.
961#[derive(Clone)]
962pub struct TraceLoc {
963    pub source: std::sync::Arc<str>,
964    pub rel_path: String,
965}
966
967/// #2620: the `.bynk` source of the unit being emitted and its project-relative
968/// identity path, so a `unreachable(…)` / `todo(…)` / `detach` lowering can name
969/// its own `path:line:col`. bynk_ts::TsExpr once per unit by the driver; `None` on
970/// [`EmitProjectCtx::unit_source`] is the single-file path, which has no identity.
971pub struct UnitSource {
972    text: String,
973    identity_path: String,
974}
975
976impl UnitSource {
977    pub fn new(text: &str, identity_path: &str) -> Self {
978        Self {
979            text: text.to_string(),
980            identity_path: identity_path.replace('\\', "/"),
981        }
982    }
983
984    /// The `path:line:col` of a byte offset in the unit's source.
985    pub fn location(&self, offset: usize) -> String {
986        let (line, col) = bynk_syntax::span::line_col(&self.text, offset);
987        format!("{}:{line}:{col}", self.identity_path)
988    }
989}
990
991/// One import `handlers.ts` needs beyond the ones the emitter derives (#527): the
992/// driver forms them from what it knows of the build (adapter-binding modules,
993/// other Workers' handlers, the locale `render`), and the emitter writes each as
994/// an import node. A small enum owned here, so the driver does not build
995/// `bynk_ts` nodes itself.
996#[derive(Debug, Clone, PartialEq, Eq)]
997pub enum ExtraImport {
998    /// `import * as <alias> from "<from>";`
999    Namespace { alias: String, from: String },
1000    /// `import { <names> } from "<from>";`, or `import type { .. }` when
1001    /// `type_only`. Each name is spelled as it appears between the braces
1002    /// (`render as __bynkLocaleRender`).
1003    Named {
1004        names: Vec<String>,
1005        from: String,
1006        type_only: bool,
1007    },
1008}
1009
1010pub struct EmitProjectCtx {
1011    /// Source path of the file being emitted (relative to project root).
1012    pub source_path: PathBuf,
1013    /// The file's project-relative identity path, as the test runner reports it in
1014    /// an `expect`'s location. A violated declaration's location is built from it (#2272).
1015    pub identity_path: String,
1016    /// Joined name of the commons or context this file belongs to.
1017    pub commons_name: String,
1018    /// Which file declares each name in the local unit.
1019    pub file_decl_index: FileDeclIndex,
1020    /// For each imported name, the joined name of the unit it came from.
1021    pub imported_from: HashMap<String, String>,
1022    /// For each imported name, the kind (commons vs context) of the source unit.
1023    pub imported_from_kind: HashMap<String, UnitKind>,
1024    /// For each imported unit, the file path that declares each name.
1025    pub imported_decl_paths: HashMap<String, HashMap<String, PathBuf>>,
1026    /// #2887: the types this unit renames with `consumes U { T as Alias }`,
1027    /// alias → the name the consumed module declares it under.
1028    pub consumed_type_aliases: HashMap<String, String>,
1029    /// What kind of unit this is.
1030    pub unit_kind: UnitKind,
1031    /// For contexts: this context's qualified name (used as the brand for
1032    /// rebranded mixed-in types and exported types).
1033    pub owning_context: Option<String>,
1034    /// For contexts: exports of each consumed context (so the emitter knows
1035    /// which names to import and how).
1036    pub exports_for_consumed: HashMap<String, HashMap<String, Visibility>>,
1037    /// For contexts: full cross-context information (consumed contexts,
1038    /// aliases, consumed services and types). Mirrors what the resolver
1039    /// and checker see (v0.6).
1040    pub cross_context: resolver::CrossContextInfo,
1041    /// v0.8 build target. Workers mode reroutes cross-context calls through
1042    /// Service Bindings and adds per-Worker entry/composition artefacts.
1043    pub target: BuildTarget,
1044    /// Agent names declared in this unit. The body lowering uses this set
1045    /// to recognise `Agent(key)` construction and `agent_instance.method(...)`
1046    /// dispatch.
1047    pub local_agents: HashSet<String>,
1048    /// #527: for each local agent with `given` capabilities, the TS
1049    /// expression building those deps DO-side (workers contexts only; the DO
1050    /// wire cannot carry providers). Consumed by `emit_agent`'s fetch branch.
1051    pub agent_given_deps: HashMap<String, String>,
1052    /// 1A.36b-2: for each agent in `agent_given_deps`, the namespaces its expression spells
1053    /// (`bynk__binding`, `handlers_shop_orders`), declared with the text so the module's imports
1054    /// follow its tree.
1055    pub agent_given_deps_names: HashMap<String, Vec<String>>,
1056    /// #527: extra imports `handlers.ts` needs for the expressions above.
1057    pub extra_imports: Vec<ExtraImport>,
1058    /// #527: for each local agent, each `on call` method's `given` capability
1059    /// list. The lowering records which agent methods a handler body calls so
1060    /// the handler's emitted deps *type* carries the callee's capabilities —
1061    /// the runtime deps value (built by compose) always did.
1062    pub agent_method_givens: HashMap<String, HashMap<String, Vec<CapRefIr>>>,
1063    /// #1961: the consumed contexts the context's agents call
1064    /// ([`emitter::agent_cross_context_targets`]), unit-wide. A handler that
1065    /// constructs an agent names them in its `deps.env` type.
1066    pub agent_called_contexts: Vec<String>,
1067    /// v0.47: the context's actor declarations (merged across files), keyed by
1068    /// name. Used to resolve a handler's Bearer verification seam in `emit.rs`
1069    /// regardless of which file declares the actor.
1070    pub actors: HashMap<String, ActorDecl>,
1071    /// Events slice 3b (#978): each locally-declared event's resolved
1072    /// `@schema(N)` version (or `1` if absent), merged across files the same
1073    /// way `actors` is above — `Events.emit[E]`'s lowering site only has
1074    /// `E`'s bare name (the turbofish type argument), never its declaration,
1075    /// so this is threaded down to `ModuleCtx`/`LowerCtx` rather than
1076    /// re-derived from the per-file synthetic `Commons` `lower.rs` otherwise
1077    /// sees (which would silently miss an event declared in a sibling file).
1078    pub event_schema_versions: HashMap<String, i64>,
1079    /// State-migrations S1 (#2211): each locally-declared agent's lock
1080    /// `version` and oldest readable stored version, keyed by agent name.
1081    /// Empty when the build has no lock (`SchemaLock::Off`), in which case the
1082    /// agent emits no version logic at all (Decision A).
1083    pub agent_schema_versions: HashMap<String, bynk_check::schema_registry::AgentVersions>,
1084    /// v0.17: consumed unit names that are adapters. An adapter is not a Worker,
1085    /// so in workers mode its capability types are imported from its root module
1086    /// (`<adapter>.ts`), not from a per-Worker `handlers.ts`.
1087    pub consumed_adapters: HashSet<String>,
1088    /// #2045: the types of consumed *contexts* (adapters aside) that carry
1089    /// attached methods. A call to one (`b.big()` lowers to `Batch.big(b)`) runs
1090    /// the callee's own code from its companion object, so that name is a real
1091    /// value import; every other consumed context type imports type-only.
1092    pub consumed_types_with_methods: HashSet<String>,
1093    /// Slice 2: the extension emitted import specifiers use (`.js` default; `.ts`
1094    /// for the `bynk test --inspect` debug build). Consulted by `runtime_import_for`
1095    /// and the sibling/cross-commons specifier helpers.
1096    pub import_ext: ImportExt,
1097    /// v0.115 (testing track slice 3): emit the function-contract call-site guard
1098    /// (dev/test profile). Stripped in the deploy build for zero runtime cost.
1099    pub contracts: bool,
1100    /// #3580: `Some` emits the per-request trace recording (`bynk dev
1101    /// --trace-events`): the cross-context, agent and capability sites wrapped in
1102    /// `__traceStep`, and the Worker's `fetch` in `__traceFetch`. Never set by a
1103    /// deploy build, whose output is byte-identical.
1104    pub trace: Option<TraceLoc>,
1105    /// #3581: emit the dev-only agent inspection (the instance recording in each
1106    /// agent factory and the `/_bynk/inspect` branch of each agent). `false` for
1107    /// every build but `bynk dev`, so a deploy build is byte-identical.
1108    pub inspect_agents: bool,
1109    /// v0.119 (testing track slice 7, ADR 0155): agent names a `for all run:
1110    /// History[Agent]` property in this project drives. Only these agents gain the
1111    /// exported `__bynkDriveHistory_<Agent>` test-support driver — every other
1112    /// agent's emission is byte-for-byte unchanged.
1113    pub history_target_agents: HashSet<String>,
1114    /// #1883, slice 1b: each declared asset's served URL path, keyed by its
1115    /// normalised source path (`assets::declared_served_paths`) — the value
1116    /// of the asset's `.url`.
1117    pub asset_served: BTreeMap<String, String>,
1118    /// #2387, slice 2: each declared embed's text, keyed by its normalised
1119    /// source path (`embeds::read_declared_embeds`) — the value of the
1120    /// embed's constant.
1121    pub embed_text: BTreeMap<String, String>,
1122    /// v0.132.1 (#481): for a context, the user-defined attached methods of each
1123    /// `uses`-imported refined/opaque type, keyed by the type's name and sorted
1124    /// by method name. The context's own `TypedCommons` merges the imported
1125    /// *types* but not their fn items, so `emit_context_rebrands` reads this to
1126    /// forward `Cents.fromInt(…)` and friends onto the rebranded const. Empty
1127    /// for commons units and for contexts with no such imports.
1128    ///
1129    /// P6.18: each entry is a resolved [`FnSig`] (the declaring unit's own
1130    /// `params`/`return_ty`, already `TyId`-typed), not a raw `FnDecl` —
1131    /// see `build_emit_unit_ctx`'s own doc comment for why.
1132    pub imported_methods: HashMap<String, Vec<FnSig>>,
1133    /// Which conditional `runtime.ts` helpers this file's emission referenced.
1134    ///
1135    /// Unlike every field above, this is an **output**, not an input: emission
1136    /// writes it (through `&self`, via interior mutability) and the header /
1137    /// import post-pass reads it back. It rides on the context because the
1138    /// producers — the `Bytes` kernel in `lower`, the boundary codecs in
1139    /// `serialisation`, the ICU formatters in `emit` — already receive `&ctx`,
1140    /// so no other signature has to change to carry the fact up.
1141    ///
1142    /// One `EmitProjectCtx` is built per emitted file, immediately before its
1143    /// `emit_project` call, so the flags cannot leak between files. Replaces a
1144    /// substring scan of the generated text; see `emitter::runtime_use`.
1145    pub runtime_use: crate::emitter::RuntimeUse,
1146    /// #3562: where each context's generated files go on Workers.
1147    pub worker_layout: bynk_project::worker_layout::WorkerLayout,
1148    /// #2620: the unit's source and identity path; `None` for single-file emission.
1149    pub unit_source: Option<UnitSource>,
1150    /// #1927: a `uses`-imported type this unit hides behind its own value (a
1151    /// function, asset, service, agent or provider of the same name), type name
1152    /// to the inline import type that names it, `import("<module>").Name`. Empty
1153    /// for a unit that hides none.
1154    pub type_spellings: HashMap<String, String>,
1155}
1156
1157impl EmitProjectCtx {
1158    /// #2045: on `workers`, the types this unit imports from a consumed
1159    /// *context* (not an adapter): each is another Worker's, so this module
1160    /// names it in type position only and builds its sum variants inline.
1161    pub fn consumed_context_types(&self) -> HashSet<String> {
1162        if self.target != BuildTarget::Workers || self.unit_kind != UnitKind::Context {
1163            return HashSet::new();
1164        }
1165        self.imported_from
1166            .iter()
1167            .filter(|(n, owner)| {
1168                self.imported_from_kind.get(n.as_str()) == Some(&UnitKind::Context)
1169                    && !self.consumed_adapters.contains(owner.as_str())
1170            })
1171            .map(|(n, _)| n.clone())
1172            .collect()
1173    }
1174
1175    pub fn commons_path(name: &str) -> PathBuf {
1176        commons_dir_for(name)
1177    }
1178}
1179
1180/// v0.177 (#643, review of #658): the cross-context services a context actually
1181/// **calls**, as `consumed context → service names`.
1182///
1183/// This is not the same as "every service the dependency provides", and the
1184/// difference is the difference between a gate that reports what it *knows* is
1185/// skewed and one that reports what merely *differs*. If `payment` provides
1186/// `authorise` and `refund`, `orders` calls only `authorise`, and `refund`'s
1187/// contract changed, then recording `refund` in `orders`'s `expects` would refuse
1188/// `deploy --context orders` over a service `orders` never touches and whose
1189/// runtime check could never fire. ADR 0200 Decision E rejects a per-*context*
1190/// hash for exactly this reason — that it becomes a deployment tax — and a
1191/// per-context *gate* over per-service hashes would reintroduce it one layer up.
1192///
1193/// So the manifest's `expects` mirrors the runtime check's granularity: one entry
1194/// per call site, discovered the same way the lowering discovers it — an ident
1195/// chain on the receiver that resolves to a consumed context.
1196pub fn called_cross_context_services(
1197    table: &UnitTable,
1198    consumed: &[String],
1199    // #1187's slice 6 plumbing: reads the checker's own already-resolved
1200    // `Callee::Cross { unit, service }` (`RunChecks::Checked::unit_callees`'s
1201    // own doc comment has the full grounding) instead of re-deriving
1202    // cross-context-ness by flattening a receiver's own ident chain and
1203    // string-matching it against `consumed`/`aliases` — the identical
1204    // resolution `CrossContextInfo::resolve_prefix` already did once, at
1205    // check time, per call site. `consumed` stays, purely as the cheap
1206    // early-out below: an empty `consumes` list means no `Callee::Cross`
1207    // could exist in this unit's own bodies regardless, so skip the walk.
1208    callees: Option<&HashMap<ExprId, bynk_check::checker::Callee>>,
1209) -> std::collections::BTreeMap<String, std::collections::BTreeSet<String>> {
1210    let mut out: std::collections::BTreeMap<String, std::collections::BTreeSet<String>> =
1211        std::collections::BTreeMap::new();
1212    if consumed.is_empty() {
1213        return out;
1214    }
1215    // See `unit_table_uses_emit`'s own matching `debug_assert` (review of
1216    // #1202) — `consumed` non-empty means this unit certified with a real
1217    // `consumes`, so `callees` missing here is the same "invariant broke a
1218    // thousand lines away" case, just silently thinning the contracts
1219    // manifest's `expects` instead of silently disabling emission.
1220    let Some(callees) = callees else {
1221        debug_assert!(
1222            false,
1223            "called_cross_context_services: no Callee map for a checked unit with a non-empty \
1224             consumes list"
1225        );
1226        return out;
1227    };
1228    emitter::walk_unit_table_bodies(table, &mut |e| {
1229        if let Some(bynk_check::checker::Callee::Cross { unit, service }) = callees.get(&e.id) {
1230            out.entry(unit.clone()).or_default().insert(service.clone());
1231        }
1232    });
1233    out
1234}
1235
1236/// #2138: a `system` case a remote test build skipped, and why.
1237#[derive(Clone, Debug, PartialEq, Eq)]
1238pub struct RemoteSkip {
1239    pub case: String,
1240    /// The `bynk.test.remote_unsupported_*` code.
1241    pub code: String,
1242    /// The reason, as the refusal would have worded it.
1243    pub reason: String,
1244}
1245
1246/// #2138: how a remote test build treats a `system` case it can't run
1247/// against a real runtime (`CompileOptions::remote_tests` in the driver).
1248#[derive(Clone, Debug, Default, PartialEq, Eq)]
1249pub struct RemoteTests {
1250    /// `--skip-unsupported`: skip such a case, recording why
1251    /// ([`DiscoveredSuite::skipped`]), instead of refusing it.
1252    pub skip_unsupported: bool,
1253    /// The named target's declared `vars`, which each case's `env` must agree
1254    /// with (`bynk_check::test_env::remote_env_disagreement`).
1255    pub vars: BTreeMap<String, String>,
1256    /// The names of the named target's secrets, which a case's `env` may not
1257    /// set.
1258    pub secrets: Vec<String>,
1259    /// `--against dev`: the runner starts the Workers itself and applies each
1260    /// case's `env` to them, so `env` is not checked against `vars`; each
1261    /// suite instead reports the distinct `env` maps its cases run with
1262    /// ([`DiscoveredSuite::envs`]), one `bynk dev` per map.
1263    pub dev: bool,
1264    /// Under `dev`, build only the cases whose `env` is exactly this map: the
1265    /// group one `bynk dev` serves.
1266    pub only_env: Option<BTreeMap<String, String>>,
1267}
1268
1269/// `<name>.<suffix>`, matching `bynk-driver::output.rs`'s own sibling-name
1270/// derivation for `.map`/`.bynkdbg.json` files exactly (P7.6, #1309).
1271pub fn sibling_path(output_path: &Path, suffix: &str) -> PathBuf {
1272    let name = output_path
1273        .file_name()
1274        .map(|n| n.to_string_lossy().into_owned())
1275        .unwrap_or_default();
1276    output_path.with_file_name(format!("{name}.{suffix}"))
1277}