Skip to main content

bynk_emit/emitter/
wrangler.rs

1//! `wrangler.toml` generation per Worker (v0.8 §4.4 / §4.5).
2//!
3//! Each context becomes a Cloudflare Worker with its own wrangler config.
4//! Service Bindings are declared for every consumed context. Durable
5//! Object bindings + `exports` entries are declared for every agent.
6
7pub mod environment;
8
9use crate::emitter::bindings::{BindingSource, WorkerBinding};
10use crate::emitter::toml_doc::{TomlBlock, TomlDocument, TomlEntry, TomlValue};
11use bynk_project::env_protocol;
12use bynk_project::worker_layout::WorkerLayout;
13use bynk_project::wrangler_keys::WranglerKey;
14
15/// Compile-time pinned compatibility date. Cloudflare uses this to lock
16/// Workers runtime behaviour. When to bump it, and the gate a bump must pass,
17/// is the policy in `design/bynk-release-discipline.md` ("Part 3 — The Workers
18/// compatibility date", #1677): reviewed at each release, and moved only after
19/// the workerd smokes pass on the new date.
20pub const COMPATIBILITY_DATE: &str = "2026-08-11";
21
22/// #1890: the compatibility flags every emitted Worker carries, ahead of the
23/// project's own (`bynk.toml`'s `[workers] compatibility_flags`).
24///
25/// `global_fetch_strictly_public` makes `fetch()` to a URL go out over the
26/// public internet even when the URL is another Worker on the same account
27/// or zone. Without it Cloudflare refuses such a fetch (error 1042, or a
28/// fast `404` from a `workers.dev` sibling), so a Bynk `Fetch` to a sibling
29/// service's public URL failed where the same URL worked from outside. In
30/// Bynk, `Fetch` to a URL means over the public internet, which is exactly
31/// this flag's behaviour. Worker-to-Worker calls inside one project use
32/// Service Bindings, which the flag leaves alone.
33///
34/// Reviewed with [`COMPATIBILITY_DATE`] (`design/bynk-release-discipline.md`,
35/// Part 3): a date bump can turn a flag on by default, which makes it
36/// redundant here.
37pub const DEFAULT_COMPATIBILITY_FLAGS: &[&str] = &["global_fetch_strictly_public"];
38
39/// #1890: the flags a Worker's `wrangler.toml` carries, and the duplicates
40/// dropped on the way. [`DEFAULT_COMPATIBILITY_FLAGS`] come first, then
41/// `extra` (the manifest's list) in order. A name already present, whether a
42/// default or earlier in `extra`, is dropped and returned in the second list,
43/// once per extra occurrence, for the caller to warn about. Names are not
44/// otherwise checked.
45pub fn compatibility_flags(extra: &[String]) -> (Vec<String>, Vec<String>) {
46    let mut flags: Vec<String> = DEFAULT_COMPATIBILITY_FLAGS
47        .iter()
48        .map(|f| f.to_string())
49        .collect();
50    let mut duplicates = Vec::new();
51    for flag in extra {
52        if flags.contains(flag) {
53            duplicates.push(flag.clone());
54        } else {
55            flags.push(flag.clone());
56        }
57    }
58    (flags, duplicates)
59}
60
61/// #1732: the wrangler minimum. `bynk doctor` warns about a wrangler below it,
62/// and `bynk dev` prints the same warning before serving.
63///
64/// It was the oldest wrangler whose bundled `workerd` serves
65/// [`COMPATIBILITY_DATE`]: an older `workerd` refuses a newer date outright
66/// (`wrangler dev` exits: "This Worker requires compatibility date …"). Until
67/// v1.0.0 it instead tracks the newest wrangler at each release (the toolchain
68/// policy in `design/bynk-release-discipline.md` Part 3), which is never older
69/// than the one that serves the date. It is also past every feature a generated
70/// Worker needs, including the `durable_object` container policy (4.136.0), so
71/// no feature has a floor of its own. `bynk-emit/tests/compat_date_policy.rs`
72/// checks the policy doc names it.
73pub const WRANGLER_MIN: &str = "4.162.0";
74
75/// #3477 (slice C3): the `wrangler dev --var` that tells a generated container
76/// class its containers are off (`bynk dev` without Docker), so a call faults
77/// naming Docker. The runtime's own copy is `CONTAINERS_UNAVAILABLE_VAR`
78/// (`container.ts`); `xtask/tests/env_protocol.rs` keeps the two equal (#4003).
79pub use bynk_project::env_protocol::CONTAINERS_UNAVAILABLE as CONTAINERS_UNAVAILABLE_VAR;
80
81/// Events track, slice 0 (spine #936, ADR 0284): the class name of a
82/// publishing context's fan-out Durable Object (`emitter::events_fanout`).
83/// Shared with `emitter::workers` (the `Env` field name + `deps.
84/// __eventsDispatch` call it drives) and `emitter::events_fanout` (the class
85/// this name must actually export) so the three can never drift apart.
86///
87/// Double-underscore-prefixed, matching every other compiler-synthesised
88/// identifier in emitted output (`__events`, `__eventsDispatch`,
89/// `__makeLedger`, …) — a Bynk `agent` name can never start with `_` (a
90/// parse error, checked directly: `agent _Foo { … }` fails with
91/// `expected identifier after \`agent\`, found \`_\``), so an agent
92/// coincidentally named the same as this synthetic class is structurally
93/// impossible, not merely unlikely.
94pub const EVENTS_FANOUT_CLASS_NAME: &str = "__EventsFanout";
95
96/// Deploy-time sentinel in generated Worker configuration. The driver replaces
97/// this with the persistent Cloudflare KV namespace id immediately before a
98/// remote Wrangler command runs.
99pub const KV_NAMESPACE_ID_PLACEHOLDER: &str = "<KV_NAMESPACE_ID>";
100
101/// The bare `Kv`'s binding (`KV`), re-exported for `bynk deploy`, which reads
102/// generated configs and tells the bare namespace from derived instances by
103/// it (S4b, #1967).
104pub use bynk_check::firstparty::KV_BINDING_NAME;
105
106/// #1883, slice 1b: the `[assets]` block for a Worker that ships static files.
107/// `directory` is the Worker's own assets directory
108/// ([`crate::emit_model::WORKER_ASSETS_DIR`]), beside — never containing — its
109/// compiled code. The three routing settings are set explicitly rather than
110/// inherited (#1883 [DECISION C], checked against the wrangler reference):
111///
112/// - `run_worker_first = false`: a matching asset is served without running
113///   the Worker, which is what makes an asset public by construction.
114/// - `not_found_handling = "none"`: a request no asset matches falls through
115///   to the Worker, so every handler stays reachable.
116/// - `html_handling = "none"`: an asset is served only at its exact path (the
117///   default would also serve `foo.html` at `/foo`), so the route-conflict
118///   check can compare paths exactly.
119pub fn assets_block() -> TomlBlock {
120    TomlBlock::table(
121        WranglerKey::Assets,
122        vec![
123            TomlEntry::kv(
124                "directory",
125                TomlValue::str(format!("./{}", crate::emit_model::WORKER_ASSETS_DIR)),
126            ),
127            TomlEntry::kv("run_worker_first", TomlValue::Bool(false)),
128            TomlEntry::kv("not_found_handling", TomlValue::str("none")),
129            TomlEntry::kv("html_handling", TomlValue::str("none")),
130        ],
131    )
132}
133
134/// L7 (#2414): `[cache]` turning Workers Cache on for a Worker whose context
135/// declares an `EdgeCache` instance. Cloudflare then answers a `GET` or `HEAD`
136/// from its edge cache when it holds a fresh response, without running the
137/// Worker, and stores what the Worker sends as RFC 9111 allows: which is why
138/// such a Worker sends `no-store` on every response but a `@cache` route's
139/// `2xx` (`workers_entry`). A Worker without an instance gets no stanza.
140pub fn edge_cache_block() -> TomlBlock {
141    TomlBlock::table(
142        WranglerKey::Cache,
143        vec![TomlEntry::kv("enabled", TomlValue::Bool(true))],
144    )
145}
146
147/// #2321: the explicit module rule for a Worker whose adapter closure reaches
148/// an included WebAssembly module: `**/*.wasm` is compiled by Wrangler to a
149/// `WebAssembly.Module` (the shim's `import module from "./x.wasm"`). Wrangler's
150/// default rules already say this; stating it keeps the dependency visible and
151/// stops it changing under us. `fallthrough = true` leaves the other default
152/// rules in force.
153pub fn wasm_rule_block() -> TomlBlock {
154    TomlBlock::array_table(
155        WranglerKey::Rules,
156        vec![
157            TomlEntry::kv("type", TomlValue::str("CompiledWasm")),
158            TomlEntry::kv("globs", TomlValue::Array(vec![TomlValue::str("**/*.wasm")])),
159            TomlEntry::kv("fallthrough", TomlValue::Bool(true)),
160        ],
161    )
162}
163
164/// #1883, slice 1b: the `_headers` file written into a Worker's assets
165/// directory beside its files. Every served path carries its content hash, so
166/// a file under [`bynk_check::assets::SERVED_PREFIX`] never changes and may
167/// be cached for a year. Without it the platform's default is `max-age=0,
168/// must-revalidate`. The glob is built from the prefix, so the two cannot
169/// drift (review of #1904).
170pub fn asset_headers() -> String {
171    format!(
172        "{}*\n  Cache-Control: public, max-age=31536000, immutable\n",
173        bynk_check::assets::SERVED_PREFIX
174    )
175}
176
177/// State-migrations S3 (#2248): one context's agent class renames
178/// (`(old, new)`) and removals, as `exports` tombstones.
179#[derive(Debug, Default)]
180pub struct ClassTombstones {
181    pub renamed: Vec<(String, String)>,
182    pub deleted: Vec<String>,
183}
184
185impl ClassTombstones {
186    /// From the context's declarations: each agent's `replaces`, and each
187    /// `removed agent`, skipping an old name still declared live (the checker
188    /// already refuses that).
189    pub fn of(table: &bynk_check::symbols::UnitTable) -> Self {
190        let mut renamed: Vec<(String, String)> = table
191            .agents
192            .values()
193            .filter_map(|a| {
194                let old = a.replaces.as_ref()?;
195                (!table.agents.contains_key(&old.name))
196                    .then(|| (old.name.clone(), a.name.name.clone()))
197            })
198            .collect();
199        renamed.sort();
200        let mut deleted: Vec<String> = table
201            .removed_agents
202            .iter()
203            .filter(|r| !table.agents.contains_key(&r.name.name))
204            .map(|r| r.name.name.clone())
205            .collect();
206        deleted.sort();
207        deleted.dedup();
208        ClassTombstones { renamed, deleted }
209    }
210}
211
212/// #3328: wrangler's **top-level** `addresses` (it applies to every
213/// environment, so it is never copied into an `[env.*]` table). A Worker with no
214/// email service has none, and wrangler then manages no routing rule for it.
215fn addresses_entry(addresses: &[String]) -> Option<TomlEntry> {
216    (!addresses.is_empty()).then(|| {
217        TomlEntry::kv(
218            WranglerKey::Addresses.header(),
219            TomlValue::Array(addresses.iter().map(TomlValue::str).collect()),
220        )
221    })
222}
223
224/// P6.x cutover slice 2 (#1191, narrowed from #1187): `crons`/`queues` arrive
225/// pre-collected, sorted and deduped by the caller (`project.rs`'s own
226/// `emit_wrangler_toml` call site) rather than being walked here off
227/// `table.services`. Both used to match a handler's cron-schedule kind and a
228/// service's queue-binding protocol directly, straight off the syntax tree —
229/// this file's entire raw-syntax footprint, per #1191's own grounding.
230/// Relocating just these two matches removed `wrangler.rs` from the
231/// `ast_importers` probe outright — no `bynk_model` equivalent exists to route
232/// through instead: nothing builds a project-wide service IR at the call site
233/// (#1191's Framing), and after #1542's Slice D2 nothing builds one anywhere.
234///
235/// P7.3 (#1303): builds a [`TomlDocument`] rather than writing text directly
236/// — the caller (`project.rs`) prints it via `emitter::toml_doc::
237/// print_toml_document`. What gets built, in what order, under what gates,
238/// is unchanged; only the construction shape moved from direct `writeln!`
239/// into pushing typed blocks. String-escaping moved with it: every value
240/// below is escaped unconditionally by the printer now, not selectively by
241/// this function (`emitter/toml_doc.rs`'s own module doc has the reasoning).
242#[allow(clippy::too_many_arguments)]
243pub fn emit_wrangler_toml(
244    context: &str,
245    layout: &WorkerLayout,
246    // #1944: every binding this Worker declares, [`WorkerBindings`]' list —
247    // the same one its `Env` interface and the duplicate check read.
248    bindings: &[WorkerBinding],
249    // v0.10a: every `on cron "expr"` schedule in the context, sorted+deduped.
250    // Sorting is load-bearing, not cosmetic (review of #1192): the caller
251    // walks `table.services`, a `HashMap`, so unsorted input makes
252    // `wrangler.toml` non-reproducible across runs.
253    crons: &[String],
254    // v0.10b/v0.44: every `from queue("name")` service's bound queue name,
255    // sorted+deduped (same reproducibility requirement as `crons`).
256    queues: &[String],
257    addresses: &[String], // #3328: the `from email` addresses
258    // #1890: the merged flag list, [`compatibility_flags`]' first result.
259    // The same for every Worker in the project, so the caller merges (and
260    // warns about duplicates) once, not per Worker.
261    flags: &[String],
262    // `[workers] workers_dev`, the same for every Worker; `None` omits the key.
263    workers_dev: Option<bool>,
264    // State-migrations S3 (#2248): the context's declared class renames and
265    // removals, each emitted as an `exports` tombstone.
266    tombstones: &ClassTombstones,
267    // P4b (#2608): each `D1` database's migrations; one with any gets a
268    // `migrations_dir`.
269    d1_migrations: &bynk_check::d1_migrations::D1Migrations,
270) -> TomlDocument {
271    let name = layout.script_name(context);
272    let mut root = vec![
273        TomlEntry::kv(WranglerKey::Name.header(), TomlValue::str(name)),
274        TomlEntry::kv(WranglerKey::Main.header(), TomlValue::str("index.ts")),
275        TomlEntry::kv(
276            WranglerKey::CompatibilityDate.header(),
277            TomlValue::str(COMPATIBILITY_DATE),
278        ),
279        TomlEntry::kv(
280            WranglerKey::CompatibilityFlags.header(),
281            TomlValue::Array(flags.iter().map(TomlValue::str).collect()),
282        ),
283    ];
284    root.extend(addresses_entry(addresses));
285    if let Some(workers_dev) = workers_dev {
286        root.push(TomlEntry::kv(
287            WranglerKey::WorkersDev.header(),
288            TomlValue::Bool(workers_dev),
289        ));
290    }
291    let mut doc = TomlDocument::new("Generated by bynk — do not edit by hand.", root);
292
293    let mut class_names: Vec<&str> = Vec::new();
294    for binding in bindings {
295        let name = TomlValue::str(binding.name.clone());
296        let block = match &binding.source {
297            BindingSource::Service { context } => TomlBlock::array_table(
298                WranglerKey::Services,
299                vec![
300                    TomlEntry::kv("binding", name),
301                    TomlEntry::kv("service", TomlValue::str(layout.script_name(context))),
302                ],
303            ),
304            BindingSource::Kv => TomlBlock::array_table(
305                WranglerKey::KvNamespaces,
306                vec![
307                    TomlEntry::kv("binding", name),
308                    TomlEntry::with_comment(
309                        "id",
310                        TomlValue::str(KV_NAMESPACE_ID_PLACEHOLDER),
311                        "set at deploy time",
312                    ),
313                ],
314            ),
315            // S4a (#1966): an instance's own placeholder, named for its binding,
316            // so deploy (#1967) can mint and materialise each one apart.
317            BindingSource::KvInstance { .. } => TomlBlock::array_table(
318                WranglerKey::KvNamespaces,
319                vec![
320                    TomlEntry::kv("binding", name),
321                    TomlEntry::with_comment(
322                        "id",
323                        TomlValue::str(kv_instance_id_placeholder(&binding.name)),
324                        "set at deploy time",
325                    ),
326                ],
327            ),
328            // P5 (#2323): the bucket's derived name, which `bynk deploy`
329            // environment-qualifies; R2 bucket names are scoped to the
330            // account, so the name is a function of the Worker and the
331            // capability alone.
332            BindingSource::R2Instance { jurisdiction, .. } => {
333                let mut entries = vec![
334                    TomlEntry::kv("binding", name),
335                    TomlEntry::kv(
336                        "bucket_name",
337                        TomlValue::str(r2_bucket_name(&layout.dir(context), &binding.name)),
338                    ),
339                ];
340                if let Some(jurisdiction) = jurisdiction {
341                    entries.push(TomlEntry::kv(
342                        "jurisdiction",
343                        TomlValue::str(jurisdiction.clone()),
344                    ));
345                }
346                TomlBlock::array_table(WranglerKey::R2Buckets, entries)
347            }
348            // P3 (#2342): the limiter's own placeholder `namespace_id`, which
349            // `bynk deploy` allocates in the ledger and materialises; the
350            // limit and the window are configuration, not identity.
351            BindingSource::RateLimitInstance { limit, period, .. } => TomlBlock::array_table(
352                WranglerKey::RateLimits,
353                vec![
354                    TomlEntry::kv("name", name),
355                    TomlEntry::with_comment(
356                        "namespace_id",
357                        TomlValue::str(ratelimit_namespace_placeholder(&binding.name)),
358                        "set at deploy time",
359                    ),
360                    TomlEntry::kv(
361                        "simple",
362                        TomlValue::InlineTable(vec![
363                            ("limit", TomlValue::Int(*limit)),
364                            ("period", TomlValue::Int(*period)),
365                        ]),
366                    ),
367                ],
368            ),
369            // P2 (#2578): the queue as the declaration names it; `bynk
370            // deploy` environment-qualifies it, as it does a consumer's.
371            BindingSource::QueueProducer { queue, .. } => TomlBlock::array_table(
372                WranglerKey::QueueProducers,
373                vec![
374                    TomlEntry::kv("binding", name),
375                    TomlEntry::kv("queue", TomlValue::str(queue.clone())),
376                ],
377            ),
378            // P3b (#2582): the dataset's derived name, which `bynk deploy`
379            // environment-qualifies; the platform creates it on first write.
380            BindingSource::AnalyticsDataset { .. } => TomlBlock::array_table(
381                WranglerKey::AnalyticsEngineDatasets,
382                vec![
383                    TomlEntry::kv("binding", name),
384                    TomlEntry::kv(
385                        "dataset",
386                        TomlValue::str(analytics_dataset_name(&layout.dir(context), &binding.name)),
387                    ),
388                ],
389            ),
390            // P4a (#2602): the database's derived name, which `bynk deploy`
391            // environment-qualifies, and an id placeholder it fills from the
392            // ledger. Miniflare takes the placeholder as a local id, so
393            // `bynk dev` runs with it.
394            //
395            // P4b (#2608): a database with migrations names their copy beside
396            // this file, which `wrangler d1 migrations apply` reads.
397            BindingSource::D1Database { .. } => {
398                d1_block(context, layout, binding, name, d1_migrations)
399            }
400            BindingSource::StoredSecret { store, secret, .. } => {
401                stored_secret_block(name, store, secret)
402            }
403            BindingSource::Postgres { .. } | BindingSource::MySql { .. } => {
404                hyperdrive_block(name, &binding.name)
405            }
406            BindingSource::Email { .. } => email_block(name, &binding.source),
407            // #3479: the index's derived name, which `bynk deploy`
408            // environment-qualifies and creates (never recreates). The binding
409            // names the index; its dimensions, metric and metadata indexes are
410            // the deploy's, not this stanza's.
411            BindingSource::VectorizeIndex { .. } => vectorize_block(context, layout, binding, name),
412            // #3480: the account's instance, named as the declaration writes it
413            // (in every environment). `bynk deploy` checks it exists and never
414            // creates it.
415            BindingSource::AiSearchInstance { instance, .. } => ai_search_block(name, instance),
416            // #3513 A: the account's client certificate, named as the declaration writes it
417            // (in every environment). `bynk deploy` resolves its id and never uploads it.
418            BindingSource::MtlsCertificate { certificate, .. } => mtls_block(name, certificate),
419            // #3300: a one-per-Worker capability's plain table, holding only
420            // its fixed binding name (`[version_metadata]`).
421            BindingSource::Singleton { capability } => {
422                let table = bynk_check::firstparty::singleton(
423                    bynk_check::firstparty::CLOUDFLARE_UNIT,
424                    capability,
425                )
426                .expect("a `Singleton` binding names a registered singleton")
427                .wrangler_table;
428                TomlBlock::table(
429                    WranglerKey::Singleton(table),
430                    vec![TomlEntry::kv("binding", name)],
431                )
432            }
433            // Interop I5 (#1972): the Worker as the declaration names it,
434            // not a project context's `worker_dir_name`.
435            BindingSource::ForeignService { worker, .. } => TomlBlock::array_table(
436                WranglerKey::Services,
437                vec![
438                    TomlEntry::kv("binding", name),
439                    TomlEntry::kv("service", TomlValue::str(worker.clone())),
440                ],
441            ),
442            // #3477: a container's class is generated by the compiler, so it is
443            // a Durable Object binding and an `exports` entry like an agent's.
444            BindingSource::Agent { class_name }
445            | BindingSource::EventsFanout { class_name }
446            | BindingSource::ContainerInstance { class_name, .. } => {
447                class_names.push(class_name);
448                durable_object_binding_block(name, class_name)
449            }
450        };
451        doc.push_block(block);
452    }
453    // #1796: each class is declared in Cloudflare's declarative `exports`
454    // map, not a `[[migrations]]` list. Migrations are picked by tag: Wrangler
455    // uploads only the ones after the Worker's applied tag, so the single
456    // fixed `v1` this used to emit registered the classes of the *first*
457    // deploy and no class added after it (a new agent, or the fan-out class
458    // arriving with a context's first `emit`). `exports` has no tag. On every
459    // deploy Cloudflare compares the declared set with the Worker's
460    // namespaces and creates what's missing, so the config stays a pure
461    // function of the source and the ledger still records nothing (ADR 0194
462    // D1's principle). Wrangler reads `exports` from 4.107.0, so
463    // [`WRANGLER_MIN`] is past it, and `wrangler dev` takes each class's backend from
464    // it too.
465    //
466    // Every class is SQLite-backed (#1779, ADR 0438): the emitted agent uses
467    // only `storage.get`/`storage.put` on its single `"state"` key, which a
468    // SQLite-backed class supports unchanged, and the fan-out class uses no
469    // storage at all. A Worker whose classes an older Bynk created
470    // key-value-backed (`new_classes`, ≤ 0.309.10, Workers Paid only: the
471    // Free plan refuses that backend with code 10097) is refused
472    // (`storage_type_mismatch`, per Cloudflare's `exports` docs), because
473    // Cloudflare can't change a backend in place. That is a documented
474    // pre-1.0 break: such a Worker is torn down and redeployed. A Worker
475    // whose classes the `new_sqlite_classes` migration created takes them
476    // over into `exports` with their state (#1809, live).
477    //
478    // State-migrations S3 (#2248): a class leaves only through a declaration.
479    // `agent New replaces Old` emits a `renamed` tombstone (Cloudflare moves
480    // Old's stored data to New) and `removed agent Old` a `deleted` one (the
481    // data is destroyed, after a named confirmation at deploy). A class that
482    // simply disappears from source still fails the deploy with Cloudflare's
483    // `orphaned_provisioned_namespace` (confirmed live in #1809) — and, before
484    // that, `bynk check` with `bynk.agent.class_removed`. A tombstoned class
485    // gets no binding.
486    for class_name in class_names {
487        doc.push_block(TomlBlock::keyed_table(
488            WranglerKey::Exports,
489            class_name.to_string(),
490            vec![
491                TomlEntry::kv("type", TomlValue::str("durable-object")),
492                TomlEntry::kv("storage", TomlValue::str("sqlite")),
493            ],
494        ));
495    }
496    // #3477: each container's application, after the `exports` it names.
497    bindings
498        .iter()
499        .for_each(|b| container_blocks(&b.source, &mut doc));
500    push_tombstones(&mut doc, tombstones);
501
502    // #3513 B: `Analytics.dataset()` reads the dataset's name from `[vars]`.
503    if let Some(vars) = dataset_vars_block(context, layout, bindings) {
504        doc.push_block(vars);
505    }
506
507    // v0.10a: cron triggers. Cloudflare uses a single `[triggers]` table with a
508    // `crons` array aggregating every `on cron` schedule in the context.
509    // Already sorted+deduped by the caller (#1191).
510    if !crons.is_empty() {
511        let quoted = crons.iter().map(TomlValue::str).collect();
512        doc.push_block(TomlBlock::table(
513            WranglerKey::Triggers,
514            vec![TomlEntry::kv("crons", TomlValue::Array(quoted))],
515        ));
516    }
517
518    // v0.10b: queue consumers. Each `on queue "name"` becomes a
519    // `[[queues.consumers]]` binding. Already sorted+deduped by the caller
520    // (#1191).
521    for name in queues {
522        doc.push_block(TomlBlock::array_table(
523            WranglerKey::QueueConsumers,
524            vec![
525                TomlEntry::kv("queue", TomlValue::str(name.clone())),
526                TomlEntry::kv("max_batch_size", TomlValue::Int(10)),
527            ],
528        ));
529    }
530
531    doc
532}
533
534/// State-migrations S3 (#2248): each declared class rename and removal as an `exports` tombstone,
535/// in name order.
536fn push_tombstones(doc: &mut TomlDocument, tombstones: &ClassTombstones) {
537    let mut tombstones_sorted: Vec<(&str, Option<&str>)> = tombstones
538        .renamed
539        .iter()
540        .map(|(old, new)| (old.as_str(), Some(new.as_str())))
541        .chain(tombstones.deleted.iter().map(|old| (old.as_str(), None)))
542        .collect();
543    tombstones_sorted.sort();
544    for (old, renamed_to) in tombstones_sorted {
545        let mut entries = vec![TomlEntry::kv("type", TomlValue::str("durable-object"))];
546        match renamed_to {
547            Some(new) => {
548                entries.push(TomlEntry::kv("state", TomlValue::str("renamed")));
549                entries.push(TomlEntry::kv("renamed_to", TomlValue::str(new)));
550            }
551            None => entries.push(TomlEntry::kv("state", TomlValue::str("deleted"))),
552        }
553        doc.push_block(TomlBlock::keyed_table(
554            WranglerKey::Exports,
555            old.to_string(),
556            entries,
557        ));
558    }
559}
560
561/// P4a (#2602), P4b (#2608): a `D1` database's `[[d1_databases]]` entry: its
562/// derived name, the placeholder id `bynk deploy` fills, and the copy of its
563/// migrations beside the file when it has any (a project's own, or the
564/// compiler's for the implicit idempotency database, W30 #2840).
565fn d1_block(
566    context: &str,
567    layout: &WorkerLayout,
568    binding: &WorkerBinding,
569    name: TomlValue,
570    d1_migrations: &bynk_check::d1_migrations::D1Migrations,
571) -> TomlBlock {
572    let database = d1_database_name(&layout.dir(context), &binding.name);
573    let mut entries = vec![
574        TomlEntry::kv("binding", name),
575        TomlEntry::kv("database_name", TomlValue::str(database.clone())),
576        TomlEntry::with_comment(
577            "database_id",
578            TomlValue::str(d1_database_id_placeholder(&binding.name)),
579            "set at deploy time",
580        ),
581    ];
582    if !bynk_check::d1_migrations::migrations_of(d1_migrations, &database, binding).is_empty() {
583        entries.push(TomlEntry::kv(
584            "migrations_dir",
585            TomlValue::str(format!("{D1_MIGRATIONS_DIR}/{database}")),
586        ));
587    }
588    TomlBlock::array_table(WranglerKey::D1Databases, entries)
589}
590
591/// Every binding a Worker's `wrangler.toml` declares, in emission order:
592/// #3479: the `[[vectorize]]` entry of a `Vectorize` instance.
593fn vectorize_block(
594    context: &str,
595    layout: &WorkerLayout,
596    binding: &WorkerBinding,
597    name: TomlValue,
598) -> TomlBlock {
599    TomlBlock::array_table(
600        WranglerKey::Vectorize,
601        vec![
602            TomlEntry::kv("binding", name),
603            TomlEntry::kv(
604                "index_name",
605                TomlValue::str(vectorize_index_name(&layout.dir(context), &binding.name)),
606            ),
607        ],
608    )
609}
610
611/// #3513 A: the `[[mtls_certificates]]` entry of an `MtlsCertificate` instance. The
612/// certificate is written as its name, which `bynk deploy` replaces with the id it
613/// resolves (the same call as a `StoredSecret`'s store, ADR 0802).
614fn mtls_block(binding: TomlValue, certificate: &str) -> TomlBlock {
615    TomlBlock::array_table(
616        WranglerKey::MtlsCertificates,
617        vec![
618            TomlEntry::kv("binding", binding),
619            TomlEntry::with_comment(
620                "certificate_id",
621                TomlValue::str(certificate.to_string()),
622                "the certificate's name; `bynk deploy` replaces it with the id it resolves",
623            ),
624        ],
625    )
626}
627
628/// #3480: the `[[ai_search]]` entry of an `AiSearch` instance.
629fn ai_search_block(binding: TomlValue, instance: &str) -> TomlBlock {
630    TomlBlock::array_table(
631        WranglerKey::AiSearch,
632        vec![
633            TomlEntry::kv("binding", binding),
634            TomlEntry::kv("instance_name", TomlValue::str(instance.to_string())),
635        ],
636    )
637}
638
639/// #3301: the `[[secrets_store_secrets]]` entry of a `StoredSecret`: the secret
640/// in the store the declaration names. The store is written as its name, which
641/// doubles as its local id under `bynk dev`; `bynk deploy` links it (never
642/// creating it) and replaces the name with the id it resolves.
643fn stored_secret_block(binding: TomlValue, store: &str, secret: &str) -> TomlBlock {
644    TomlBlock::array_table(
645        WranglerKey::SecretsStoreSecrets,
646        vec![
647            TomlEntry::kv("binding", binding),
648            TomlEntry::with_comment(
649                "store_id",
650                TomlValue::str(store.to_string()),
651                "the store's name; its id is set at deploy time",
652            ),
653            TomlEntry::kv("secret_name", TomlValue::str(secret.to_string())),
654        ],
655    )
656}
657
658/// Hyperdrive H1 (#3318): the `[[hyperdrive]]` entry of a `Postgres` instance.
659/// The configuration is made by `bynk deploy` (or adopted: `bynk.toml`'s
660/// `[deploy.hyperdrive]`), so its `id` is a placeholder it replaces, as D1's
661/// is. `bynk dev` needs `[dev.hyperdrive]` in `bynk.toml`, or
662/// `CLOUDFLARE_HYPERDRIVE_LOCAL_CONNECTION_STRING_<BINDING>` in the
663/// environment.
664fn hyperdrive_block(name: TomlValue, binding: &str) -> TomlBlock {
665    TomlBlock::array_table(
666        WranglerKey::Hyperdrive,
667        vec![
668            TomlEntry::kv("binding", name),
669            TomlEntry::with_comment(
670                "id",
671                TomlValue::str(hyperdrive_id_placeholder(binding)),
672                "set at deploy time",
673            ),
674        ],
675    )
676}
677
678/// #3302: the `[[send_email]]` entry of an `Email` instance. Its key is `name`,
679/// not `binding` (as `[[ratelimits]]`'s is), and each restriction is written
680/// only when the declaration carries it: `destination_address` pins every
681/// message to one recipient, and the two lists limit recipients and senders.
682fn email_block(name: TomlValue, source: &BindingSource) -> TomlBlock {
683    let BindingSource::Email {
684        to,
685        allowed_recipients,
686        allowed_senders,
687        ..
688    } = source
689    else {
690        unreachable!("`email_block` takes an `Email` binding")
691    };
692    let to = to.as_deref();
693    let list = |items: &[String]| TomlValue::Array(items.iter().map(TomlValue::str).collect());
694    let mut entries = vec![TomlEntry::kv("name", name)];
695    if let Some(to) = to {
696        entries.push(TomlEntry::kv("destination_address", TomlValue::str(to)));
697    }
698    if !allowed_recipients.is_empty() {
699        entries.push(TomlEntry::kv(
700            "allowed_destination_addresses",
701            list(allowed_recipients),
702        ));
703    }
704    if !allowed_senders.is_empty() {
705        entries.push(TomlEntry::kv(
706            "allowed_sender_addresses",
707            list(allowed_senders),
708        ));
709    }
710    TomlBlock::array_table(WranglerKey::SendEmail, entries)
711}
712
713/// Whether `source` is the one-per-Worker binding of `capability` (#3300,
714/// #3478): the kind test for a singleton, whose runtime type and test double
715/// differ per capability.
716pub fn singleton_is(source: &BindingSource, capability: &str) -> bool {
717    matches!(source, BindingSource::Singleton { capability: c } if c == capability)
718}
719
720/// A test of a binding's kind (`|s| matches!(s, BindingSource::Kv)`), as
721/// the tables pairing each platform-resource kind with what it needs use.
722pub type BindingKind = fn(&BindingSource) -> bool;
723
724/// The TypeScript type a binding has on the Worker's `env`, for both its
725/// `Env` interface and a handler's `deps.env`.
726pub(crate) fn binding_ts_type(source: &BindingSource) -> &'static str {
727    match source {
728        BindingSource::Service { .. }
729        | BindingSource::ForeignService { .. }
730        | BindingSource::MtlsCertificate { .. } => "__ServiceBinding",
731        BindingSource::Kv | BindingSource::KvInstance { .. } => "__KVNamespace",
732        BindingSource::R2Instance { .. } => "__R2Bucket",
733        BindingSource::RateLimitInstance { .. } => "__RateLimiter",
734        BindingSource::QueueProducer { .. } => "__QueueProducer",
735        BindingSource::AnalyticsDataset { .. } => "__AnalyticsDataset",
736        BindingSource::D1Database { .. } => "__D1Database",
737        BindingSource::StoredSecret { .. } => "__SecretsStoreSecret",
738        BindingSource::Email { .. } => "__SendEmail",
739        BindingSource::VectorizeIndex { .. } => "__VectorizeIndex",
740        BindingSource::AiSearchInstance { .. } => "__AiSearchInstance",
741        BindingSource::Postgres { .. } | BindingSource::MySql { .. } => "__Hyperdrive",
742        BindingSource::Singleton { capability } => match capability.as_str() {
743            "Version" => "__WorkerVersionMetadata",
744            "Ai" => "__WorkerAiBinding",
745            "Images" => "__WorkerImagesBinding",
746            "AnalyticsSql" => "__AnalyticsSqlBinding",
747            other => unreachable!("singleton `{other}` has no `env` type"),
748        },
749        BindingSource::Agent { .. }
750        | BindingSource::EventsFanout { .. }
751        | BindingSource::ContainerInstance { .. } => "__DurableObjectNamespace",
752    }
753}
754
755/// Interop I5 (#1972): the status of the stand-in for a foreign Worker that
756/// `bynk dev` binds by default and the integration test harness binds always.
757/// 503, not a 2xx: the stand-in served nothing, and code that ignores the
758/// status should not mistake it for the Worker's answer.
759pub const FOREIGN_SERVICE_DOUBLE_STATUS: u16 = 503;
760
761/// Interop I5 (#1972): the body of that stand-in's every response, saying
762/// what it is. `bynk dev` adds how to reach the real Worker instead.
763pub fn foreign_service_double_body(binding: &str, worker: &str) -> String {
764    format!(
765        "bynk: `{binding}` is bound to a stand-in for Worker `{worker}`, which is not part of this project."
766    )
767}
768
769/// S4a (#1966): the deploy-time id placeholder of a derived KV instance's
770/// `[[kv_namespaces]]` entry: `KV_SESSIONS` → `<KV_SESSIONS_ID>`.
771pub fn kv_instance_id_placeholder(binding: &str) -> String {
772    format!("<{binding}_ID>")
773}
774
775/// P3 (#2342): the placeholder `namespace_id` of rate limiter `binding`,
776/// which `bynk deploy` replaces with the id the ledger allocates. Miniflare
777/// takes it as it is, so `bynk dev` runs with it.
778pub fn ratelimit_namespace_placeholder(binding: &str) -> String {
779    format!("<{binding}_NAMESPACE>")
780}
781
782// ---------------------------------------------------------------------------
783// P7.4 (#1305): structural post-emission patches — closes R7.6 ("downstream
784// consumers couple to nodes, never to emitted text") and R8.20 ("deploy-time
785// placeholders are typed, not textual"). `bynk deploy`/`bynk dev --remote`
786// and `--emit js` both need to rewrite one field of an *already-emitted*
787// `wrangler.toml` after compilation — not build one from scratch (that's
788// `emit_wrangler_toml`/`TomlDocument`, P7.3's own construction-side tree).
789//
790// This is the read-an-existing-document side, and needs a different tool
791// than `TomlDocument`'s own from-scratch builder or a plain `toml::Table`
792// parse: both discard everything they don't model (`toml::Table` round-trips
793// through a `BTreeMap` with no comment/order trivia at all — a first attempt
794// using it here silently dropped the "Generated by bynk" banner and every
795// inline comment, and re-sorted the whole document alphabetically, on every
796// patch). `toml_edit::DocumentMut` is format-preserving: parse, mutate the
797// one value that actually changed, re-serialise, and everything else survives
798// byte-for-byte. That's the real shape "immune to a reformat, scoped to the
799// actual field" needs — not just "found the right field," but "touched
800// nothing else."
801// ---------------------------------------------------------------------------
802
803/// Set `item`'s value to `s`, preserving whatever leading/trailing
804/// whitespace and comments already decorated it — e.g. the KV namespace
805/// id's own `# set at deploy time` note survives materialisation (stale
806/// once set, but that's the same text a caller would have seen under the
807/// old substring-replace behaviour too; not this slice's concern to change).
808fn set_string_preserving_decor(item: &mut toml_edit::Item, s: &str) {
809    let decor = item
810        .as_value()
811        .map(|v| v.decor().clone())
812        .unwrap_or_default();
813    let mut new_value = toml_edit::Value::from(s);
814    *new_value.decor_mut() = decor;
815    *item = toml_edit::Item::Value(new_value);
816}
817
818/// #3479: a Worker's generated `wrangler.toml` for `bynk dev`. A `Vectorize`
819/// has no local simulation, so each `[[vectorize]]` entry whose binding is in
820/// `dev` is pointed at that index of the developer's own with `remote = true`,
821/// and the entries not in it are removed: the instance is unbound, and a call
822/// to it faults saying how to bind it. `[vars]` gains one `<binding> =
823/// "<dimensions>:<metric>"` per bound index (`declared`), which the binding
824/// checks the index against on its first call. `dev` and `declared` are keyed
825/// by binding. The text is unchanged when there is no `[[vectorize]]`.
826pub fn bind_vectorize_for_dev(
827    text: &str,
828    dev: &std::collections::BTreeMap<String, String>,
829    declared: &std::collections::BTreeMap<String, String>,
830) -> Result<String, String> {
831    let mut doc: toml_edit::DocumentMut = text
832        .parse()
833        .map_err(|e| format!("invalid wrangler.toml: {e}"))?;
834    let Some(tables) = doc
835        .get_mut(WranglerKey::Vectorize.top_key())
836        .and_then(|i| i.as_array_of_tables_mut())
837    else {
838        return Ok(text.to_string());
839    };
840    tables.retain(|t| {
841        t.get("binding")
842            .and_then(|b| b.as_str())
843            .is_some_and(|b| dev.contains_key(b))
844    });
845    for table in tables.iter_mut() {
846        let Some(binding) = table.get("binding").and_then(|b| b.as_str()) else {
847            continue;
848        };
849        let Some(index) = dev.get(binding).cloned() else {
850            continue;
851        };
852        table["index_name"] = toml_edit::value(index);
853        table["remote"] = toml_edit::value(true);
854    }
855    if tables.is_empty() {
856        doc.remove(WranglerKey::Vectorize.top_key());
857    }
858    if !declared.is_empty() {
859        let vars = doc
860            .entry(WranglerKey::Vars.top_key())
861            .or_insert_with(|| toml_edit::Item::Table(toml_edit::Table::new()));
862        let Some(vars) = vars.as_table_like_mut() else {
863            return Err("`vars` in wrangler.toml is not a table".to_string());
864        };
865        for (binding, value) in declared {
866            vars.insert(
867                &format!("{}{binding}", env_protocol::DEV_INDEX_PREFIX),
868                toml_edit::value(value.as_str()),
869            );
870        }
871    }
872    Ok(doc.to_string())
873}
874
875/// The deploy-time placeholder a `[[kv_namespaces]]` entry for `binding`
876/// carries until `bynk deploy` materialises it: [`KV_NAMESPACE_ID_PLACEHOLDER`]
877/// for the bare `KV`, [`kv_instance_id_placeholder`] for a derived instance
878/// (S4b, #1967).
879pub fn kv_id_placeholder(binding: &str) -> String {
880    if binding == bynk_check::firstparty::KV_BINDING_NAME {
881        KV_NAMESPACE_ID_PLACEHOLDER.to_string()
882    } else {
883        kv_instance_id_placeholder(binding)
884    }
885}
886
887/// S4b (#1967): the account-facing title stem of a derived instance's KV
888/// namespace, `<worker>-<capability, kebab>`: `shop-cart` and `KV_SESSIONS`
889/// give `shop-cart-sessions`, `KV_PRICE_CACHE` gives `shop-cart-price-cache`.
890/// Read off the binding, which is a function of the capability's name, so a
891/// renamed capability is a new title. `bynk deploy` environment-qualifies it.
892pub fn kv_instance_title(worker: &str, binding: &str) -> String {
893    let prefix = format!("{}_", bynk_check::firstparty::KV_BINDING_NAME);
894    let stem = binding.strip_prefix(&prefix).unwrap_or(binding);
895    format!("{worker}-{}", stem.to_ascii_lowercase().replace('_', "-"))
896}
897
898/// P5 (#2323): the account-facing name of an `R2` instance's bucket,
899/// `<worker>-<capability, kebab>`: `shop-cart` and `R2_ARCHIVES` give
900/// `shop-cart-archives`. R2 bucket names are scoped to the account (not the
901/// Worker), so the Worker's name carries the uniqueness. `bynk deploy`
902/// environment-qualifies it.
903pub fn r2_bucket_name(worker: &str, binding: &str) -> String {
904    let prefix = format!("{}_", bynk_check::firstparty::R2_BINDING_PREFIX);
905    let stem = binding.strip_prefix(&prefix).unwrap_or(binding);
906    format!("{worker}-{}", stem.to_ascii_lowercase().replace('_', "-"))
907}
908
909/// #3477: a container's `[[containers]]` entry, with its image built from the
910/// Dockerfile of `@build`. `dockerfile` is the path of the file itself and
911/// `build_context` its directory, both from the Worker's output directory. The
912/// image's key is the capability's name, which the generated class reads as
913/// `ctx.container.images.<key>`.
914fn container_blocks(source: &BindingSource, doc: &mut TomlDocument) {
915    let BindingSource::ContainerInstance {
916        capability,
917        class_name,
918        build,
919        root_from_worker,
920        ..
921    } = source
922    else {
923        return;
924    };
925    let context = format!("{root_from_worker}/{build}");
926    doc.push_block(TomlBlock::array_table(
927        WranglerKey::Containers,
928        vec![
929            TomlEntry::kv("class_name", TomlValue::str(class_name.clone())),
930            TomlEntry::kv("scheduling_policy", TomlValue::str("durable_object")),
931        ],
932    ));
933    doc.push_block(TomlBlock::keyed_table(
934        WranglerKey::ContainerImages,
935        capability.clone(),
936        vec![
937            TomlEntry::kv(
938                "dockerfile",
939                TomlValue::str(format!("{context}/Dockerfile")),
940            ),
941            TomlEntry::kv("build_context", TomlValue::str(context)),
942        ],
943    ));
944}
945
946/// The `[[durable_objects.bindings]]` entry binding `name` to `class_name`.
947fn durable_object_binding_block(name: TomlValue, class_name: &str) -> TomlBlock {
948    TomlBlock::array_table(
949        WranglerKey::DurableObjectBindings,
950        vec![
951            TomlEntry::kv("name", name),
952            TomlEntry::kv("class_name", TomlValue::str(class_name.to_string())),
953        ],
954    )
955}
956
957/// Cloudflare's longest index name, in bytes.
958const VECTORIZE_INDEX_NAME_MAX: usize = 64;
959
960/// Bytes kept free for `bynk deploy`'s `-<environment>` suffix (a hyphen and up
961/// to 15 bytes of environment name), so the qualified name stays within the limit.
962const VECTORIZE_ENV_SUFFIX_ROOM: usize = 16;
963
964/// #3479: the account-facing name of a `Vectorize` instance's index,
965/// `<worker>-<capability>` in kebab case: `shop-cart` and `VECTORIZE_DOCS` give
966/// `shop-cart-docs`. Cloudflare takes a kebab-cased name of at most 64 bytes,
967/// so a name longer than that, less room for the environment suffix, keeps its head and ends in a hash of the whole name (the
968/// same inputs always give the same name). `bynk deploy` environment-qualifies
969/// it (`shop-cart-docs-staging`).
970pub fn vectorize_index_name(worker: &str, binding: &str) -> String {
971    let prefix = format!("{}_", bynk_check::firstparty::VECTORIZE_BINDING_PREFIX);
972    let stem = binding.strip_prefix(&prefix).unwrap_or(binding);
973    let full = format!("{worker}-{}", stem.to_ascii_lowercase().replace('_', "-"));
974    let budget = VECTORIZE_INDEX_NAME_MAX - VECTORIZE_ENV_SUFFIX_ROOM;
975    if full.len() <= budget {
976        return full;
977    }
978    // FNV-1a: stable across builds and platforms, unlike `DefaultHasher`.
979    let hash = full.bytes().fold(0xcbf2_9ce4_8422_2325_u64, |h, b| {
980        (h ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3)
981    });
982    let suffix = format!("-{:08x}", hash as u32);
983    let head = &full[..budget - suffix.len()];
984    format!("{}{suffix}", head.trim_end_matches('-'))
985}
986
987/// #3513 B: `Analytics.dataset()` reads the dataset's name, which only the deploy knows (it
988/// environment-qualifies it), from one `[vars]` entry per dataset binding. The variable is the
989/// binding's own, `BYNK_DATASET_<BINDING>`, in the reserved `BYNK_` namespace. `None` when the
990/// Worker has no dataset.
991fn dataset_vars_block(
992    context: &str,
993    layout: &WorkerLayout,
994    bindings: &[WorkerBinding],
995) -> Option<TomlBlock> {
996    let entries: Vec<TomlEntry> = bindings
997        .iter()
998        .filter(|b| matches!(b.source, BindingSource::AnalyticsDataset { .. }))
999        .map(|b| {
1000            TomlEntry::kv_owned(
1001                dataset_var_name(&b.name),
1002                TomlValue::str(analytics_dataset_name(&layout.dir(context), &b.name)),
1003            )
1004        })
1005        .collect();
1006    (!entries.is_empty()).then(|| TomlBlock::table(WranglerKey::Vars, entries))
1007}
1008
1009/// #3513 B: the `[vars]` entry that carries an `Analytics` binding's dataset name to the
1010/// Worker (`ANALYTICS_SIGNUPS` gives `BYNK_DATASET_ANALYTICS_SIGNUPS`).
1011pub fn dataset_var_name(binding: &str) -> String {
1012    format!("{}{binding}", env_protocol::DATASET_PREFIX)
1013}
1014
1015/// P3b (#2582): the account-facing name of an `Analytics` instance's dataset,
1016/// `<worker>_<capability>` in snake case: `shop-cart` and `ANALYTICS_SIGNUPS`
1017/// give `shop_cart_signups`. Underscores, not R2's hyphens, because the dataset
1018/// is the table name in the SQL API, where a hyphen would need quoting in
1019/// every query. `bynk deploy` environment-qualifies it
1020/// (`shop_cart_signups_staging`).
1021pub fn analytics_dataset_name(worker: &str, binding: &str) -> String {
1022    let prefix = format!("{}_", bynk_check::firstparty::ANALYTICS_BINDING_PREFIX);
1023    let stem = binding.strip_prefix(&prefix).unwrap_or(binding);
1024    format!("{worker}_{stem}")
1025        .to_ascii_lowercase()
1026        .replace('-', "_")
1027}
1028
1029/// #3479: the file beside a Worker's `wrangler.toml` that states each
1030/// `[[vectorize]]` binding's index configuration. `wrangler.toml`'s stanza
1031/// names only the index; its dimensions, metric and metadata indexes are what
1032/// `bynk deploy` creates it with and checks it against, and Cloudflare cannot
1033/// change them afterwards. Written only for a Worker with a `Vectorize`
1034/// instance, so any other project's output is unchanged.
1035pub const VECTORIZE_MANIFEST: &str = "bynk-vectorize.json";
1036
1037/// The manifest's version. A reader refuses one it does not know.
1038pub const VECTORIZE_MANIFEST_VERSION: u32 = 1;
1039
1040/// The `bynk-vectorize.json` of a Worker with `bindings`, or `None` when it
1041/// has no `Vectorize` instance.
1042pub fn emit_vectorize_manifest(bindings: &[WorkerBinding]) -> Option<String> {
1043    let entries: Vec<String> = bindings
1044        .iter()
1045        .filter_map(|b| {
1046            let BindingSource::VectorizeIndex {
1047                dimensions,
1048                metric,
1049                indexed,
1050                ..
1051            } = &b.source else {
1052                return None;
1053            };
1054            Some(format!(
1055                "    {{ \"binding\": {}, \"dimensions\": {dimensions}, \"metric\": {}, \"indexed\": [{}] }}",
1056                bynk_project::json_string(&b.name),
1057                bynk_project::json_string(metric),
1058                indexed
1059                    .iter()
1060                    .map(|i| bynk_project::json_string(i))
1061                    .collect::<Vec<_>>()
1062                    .join(", "),
1063            ))
1064        })
1065        .collect();
1066    if entries.is_empty() {
1067        return None;
1068    }
1069    Some(format!(
1070        "{{\n  \"version\": {VECTORIZE_MANIFEST_VERSION},\n  \"vectorize\": [\n{}\n  ]\n}}\n",
1071        entries.join(",\n")
1072    ))
1073}
1074
1075/// A generated `wrangler.toml`'s `[[vectorize]]` entries as `(binding,
1076/// index_name)`, in file order; an entry missing either is skipped.
1077pub fn vectorize_index_entries(text: &str) -> Result<Vec<(String, String)>, String> {
1078    let doc: toml_edit::DocumentMut = text
1079        .parse()
1080        .map_err(|e| format!("invalid wrangler.toml: {e}"))?;
1081    Ok(doc
1082        .get(WranglerKey::Vectorize.top_key())
1083        .and_then(|i| i.as_array_of_tables())
1084        .into_iter()
1085        .flatten()
1086        .filter_map(|t| {
1087            Some((
1088                t.get("binding")?.as_str()?.to_string(),
1089                t.get("index_name")?.as_str()?.to_string(),
1090            ))
1091        })
1092        .collect())
1093}
1094
1095/// The name of the manifest beside a Worker's `wrangler.toml` that states what
1096/// `[[containers]]` does not: each container's capability, `@build` directory and
1097/// `@instanceType`, which `bynk deploy` plans and checks from.
1098pub const CONTAINERS_MANIFEST: &str = "bynk-containers.json";
1099
1100/// The version of [`CONTAINERS_MANIFEST`]'s layout.
1101pub const CONTAINERS_MANIFEST_VERSION: u32 = 1;
1102
1103/// #3477 (slice C2): [`CONTAINERS_MANIFEST`] for a Worker's bindings, or `None`
1104/// when it has no container. `instance_type` is `null` when the declaration
1105/// gives none, which the platform runs as `lite`.
1106pub fn emit_containers_manifest(bindings: &[WorkerBinding]) -> Option<String> {
1107    let entries: Vec<String> = bindings
1108        .iter()
1109        .filter_map(|b| {
1110            let BindingSource::ContainerInstance {
1111                capability,
1112                class_name,
1113                build,
1114                instance_type,
1115                ..
1116            } = &b.source
1117            else {
1118                return None;
1119            };
1120            Some(format!(
1121                "    {{ \"capability\": {}, \"class\": {}, \"build\": {}, \"instance_type\": {} }}",
1122                bynk_project::json_string(capability),
1123                bynk_project::json_string(class_name),
1124                bynk_project::json_string(build),
1125                instance_type
1126                    .as_deref()
1127                    .map_or_else(|| "null".to_string(), bynk_project::json_string),
1128            ))
1129        })
1130        .collect();
1131    if entries.is_empty() {
1132        return None;
1133    }
1134    Some(format!(
1135        "{{\n  \"version\": {CONTAINERS_MANIFEST_VERSION},\n  \"containers\": [\n{}\n  ]\n}}\n",
1136        entries.join(",\n")
1137    ))
1138}
1139
1140/// #3477 (slice C2): `text` with each adopted container image named in the
1141/// `[containers.images.<capability>]` entry of `environment` (the top level for
1142/// `default`, else `[env.<name>]`): the entry's `dockerfile`, `build_context`
1143/// and `build_vars` go, and `image` takes the digest-pinned reference, so
1144/// `wrangler` builds nothing for it. `images` maps a capability to its
1145/// reference. An adopted capability with no entry to rewrite is an error: it
1146/// would be built after all.
1147pub fn materialise_adopted_container_images(
1148    text: &str,
1149    environment: &str,
1150    images: &std::collections::BTreeMap<String, String>,
1151) -> Result<String, String> {
1152    let mut doc: toml_edit::DocumentMut = text
1153        .parse()
1154        .map_err(|e| format!("invalid wrangler.toml: {e}"))?;
1155    let item = if environment == "default" {
1156        doc.get_mut(WranglerKey::Containers.top_key())
1157    } else {
1158        doc.get_mut("env")
1159            .and_then(|e| e.get_mut(environment))
1160            .and_then(|e| e.get_mut(WranglerKey::Containers.top_key()))
1161    };
1162    let mut found = std::collections::BTreeSet::new();
1163    if let Some(tables) = item.and_then(|i| i.as_array_of_tables_mut()) {
1164        for application in tables.iter_mut() {
1165            let Some(map) = application
1166                .get_mut("images")
1167                .and_then(|i| i.as_table_like_mut())
1168            else {
1169                continue;
1170            };
1171            for (capability, reference) in images {
1172                let Some(entry) = map.get_mut(capability).and_then(|e| e.as_table_like_mut())
1173                else {
1174                    continue;
1175                };
1176                found.insert(capability.clone());
1177                for key in ["dockerfile", "build_context", "build_vars"] {
1178                    entry.remove(key);
1179                }
1180                entry.insert("image", toml_edit::value(reference.as_str()));
1181            }
1182        }
1183    }
1184    if let Some(missing) = images.keys().find(|c| !found.contains(*c)) {
1185        return Err(format!(
1186            "no `containers.images.{missing}` entry in {}",
1187            if environment == "default" {
1188                "the configuration".to_string()
1189            } else {
1190                format!("`[env.{environment}]`")
1191            }
1192        ));
1193    }
1194    Ok(doc.to_string())
1195}
1196
1197/// #3479: point `[[vectorize]]` entries at the indexes `bynk.toml` adopts,
1198/// structurally, by binding. An adopted index keeps the name it has on the
1199/// account (never the derived, environment-qualified one), so it is written
1200/// into the top-level entries for the default environment and into
1201/// `[env.<environment>]`'s for a named one. Unchanged text when nothing
1202/// differs, as [`materialise_r2_bucket_names`].
1203pub fn materialise_vectorize_index_names(
1204    text: &str,
1205    environment: &str,
1206    names: &std::collections::BTreeMap<String, String>,
1207) -> Result<String, String> {
1208    let mut doc: toml_edit::DocumentMut = text
1209        .parse()
1210        .map_err(|e| format!("invalid wrangler.toml: {e}"))?;
1211    let mut changed = false;
1212    let mut found = std::collections::BTreeSet::new();
1213    let item = if environment == "default" {
1214        doc.get_mut(WranglerKey::Vectorize.top_key())
1215    } else {
1216        doc.get_mut("env")
1217            .and_then(|e| e.get_mut(environment))
1218            .and_then(|e| e.get_mut(WranglerKey::Vectorize.top_key()))
1219    };
1220    let mut set = |entry: &mut dyn toml_edit::TableLike| {
1221        let Some(binding) = entry.get("binding").and_then(|b| b.as_str()) else {
1222            return;
1223        };
1224        let Some(name) = names.get(binding).cloned() else {
1225            return;
1226        };
1227        found.insert(binding.to_string());
1228        if let Some(index) = entry.get_mut("index_name")
1229            && index.as_str() != Some(name.as_str())
1230        {
1231            set_string_preserving_decor(index, &name);
1232            changed = true;
1233        }
1234    };
1235    if let Some(item) = item {
1236        if let Some(tables) = item.as_array_of_tables_mut() {
1237            for table in tables.iter_mut() {
1238                set(table);
1239            }
1240        } else if let Some(array) = item.as_array_mut() {
1241            for value in array.iter_mut() {
1242                if let Some(table) = value.as_inline_table_mut() {
1243                    set(table);
1244                }
1245            }
1246        }
1247    }
1248    // An adopted binding with no stanza to name would bind the derived name.
1249    if let Some(missing) = names.keys().find(|b| !found.contains(*b)) {
1250        return Err(format!(
1251            "no `[[vectorize]]` entry for `{missing}` in {}",
1252            if environment == "default" {
1253                "the configuration".to_string()
1254            } else {
1255                format!("`[env.{environment}]`")
1256            }
1257        ));
1258    }
1259    Ok(if changed {
1260        doc.to_string()
1261    } else {
1262        text.to_string()
1263    })
1264}
1265
1266/// P4b (#2608): the directory beside a Worker's `wrangler.toml` holding its
1267/// `D1` databases' migrations, one subdirectory per database, as the
1268/// project's own `migrations/` folder does.
1269pub const D1_MIGRATIONS_DIR: &str = "migrations";
1270
1271/// Hyperdrive H5 (#3322): the file beside a Worker's `wrangler.toml` that says
1272/// which of its `[[hyperdrive]]` bindings are MySQL, and each one's `@tls`
1273/// mode. `wrangler.toml`'s stanza names neither (a Hyperdrive config's database
1274/// kind and TLS mode are the config's, not the binding's), and `bynk deploy`
1275/// needs both to make the config. It is written only for a Worker with a
1276/// `MySql` instance, so a `Postgres`-only project's output is unchanged, and it
1277/// holds names and modes, never a connection string.
1278pub const HYPERDRIVE_MANIFEST: &str = "bynk-hyperdrive.json";
1279
1280/// The manifest's version. A reader refuses one it does not know.
1281pub const HYPERDRIVE_MANIFEST_VERSION: u32 = 1;
1282
1283/// The `bynk-hyperdrive.json` of a Worker with `bindings`, or `None` when it
1284/// has no `MySql` instance. The `tls` field is the `@tls` mode as the source
1285/// wrote it (`required` when it wrote none).
1286pub fn emit_hyperdrive_manifest(bindings: &[WorkerBinding]) -> Option<String> {
1287    let entries: Vec<String> = bindings
1288        .iter()
1289        .filter_map(|b| {
1290            let BindingSource::MySql { tls, .. } = &b.source else {
1291                return None;
1292            };
1293            Some(format!(
1294                "    {{ \"binding\": {}, \"kind\": \"mysql\", \"tls\": {} }}",
1295                bynk_project::json_string(&b.name),
1296                bynk_project::json_string(tls.as_deref().unwrap_or("required")),
1297            ))
1298        })
1299        .collect();
1300    if entries.is_empty() {
1301        return None;
1302    }
1303    Some(format!(
1304        "{{\n  \"version\": {HYPERDRIVE_MANIFEST_VERSION},\n  \"hyperdrive\": [\n{}\n  ]\n}}\n",
1305        entries.join(",\n")
1306    ))
1307}
1308
1309/// P4a (#2602): the account-facing name of a `D1` instance's database. It
1310/// moved to the checker with P4b (#2608), which names each instance's
1311/// migrations directory by it.
1312pub use bynk_check::d1_migrations::d1_database_name;
1313
1314/// P4a (#2602): the placeholder `database_id` of D1 binding `binding`, which
1315/// `bynk deploy` replaces with the id it records in the ledger.
1316pub fn d1_database_id_placeholder(binding: &str) -> String {
1317    format!("<{binding}_ID>")
1318}
1319
1320/// Hyperdrive H1 (#3318): the placeholder `id` of Hyperdrive binding `binding`,
1321/// which `bynk deploy` replaces with the id of its Hyperdrive config.
1322pub fn hyperdrive_id_placeholder(binding: &str) -> String {
1323    format!("<{binding}_ID>")
1324}
1325
1326/// P4a (#2602): a generated `wrangler.toml`'s `[[d1_databases]]` entries as
1327/// `(binding, database_name)`, in file order; an entry missing either is
1328/// skipped.
1329pub fn d1_database_entries(text: &str) -> Result<Vec<(String, String)>, String> {
1330    let doc: toml_edit::DocumentMut = text
1331        .parse()
1332        .map_err(|e| format!("invalid wrangler.toml: {e}"))?;
1333    Ok(doc
1334        .get(WranglerKey::D1Databases.top_key())
1335        .and_then(|i| i.as_array_of_tables())
1336        .into_iter()
1337        .flatten()
1338        .filter_map(|t| {
1339            Some((
1340                t.get("binding")?.as_str()?.to_string(),
1341                t.get("database_name")?.as_str()?.to_string(),
1342            ))
1343        })
1344        .collect())
1345}
1346
1347/// P4a (#2602): point `[[d1_databases]]` entries at their deployed databases,
1348/// structurally, by binding: each entry whose binding `databases` lists gets
1349/// that `(database_name, database_id)`. Unchanged text when nothing differs,
1350/// as [`materialise_r2_bucket_names`].
1351pub fn materialise_d1_databases(
1352    text: &str,
1353    databases: &std::collections::BTreeMap<String, (String, String)>,
1354) -> Result<String, String> {
1355    let mut doc: toml_edit::DocumentMut = text
1356        .parse()
1357        .map_err(|e| format!("invalid wrangler.toml: {e}"))?;
1358    let mut changed = false;
1359    if let Some(entries) = doc
1360        .get_mut(WranglerKey::D1Databases.top_key())
1361        .and_then(|i| i.as_array_of_tables_mut())
1362    {
1363        for entry in entries.iter_mut() {
1364            let Some((name, id)) = entry
1365                .get("binding")
1366                .and_then(|b| b.as_str())
1367                .and_then(|b| databases.get(b))
1368                .cloned()
1369            else {
1370                continue;
1371            };
1372            for (key, value) in [("database_name", name), ("database_id", id)] {
1373                if let Some(item) = entry.get_mut(key)
1374                    && item.as_str() != Some(value.as_str())
1375                {
1376                    set_string_preserving_decor(item, &value);
1377                    changed = true;
1378                }
1379            }
1380        }
1381    }
1382    Ok(if changed {
1383        doc.to_string()
1384    } else {
1385        text.to_string()
1386    })
1387}
1388
1389/// Hyperdrive H2 (#3319): a generated `wrangler.toml`'s `[[hyperdrive]]`
1390/// entries as `(binding, id)`, in file order; an entry missing either is
1391/// skipped. In a freshly generated file `id` is the placeholder.
1392pub fn hyperdrive_entries(text: &str) -> Result<Vec<(String, String)>, String> {
1393    let doc: toml_edit::DocumentMut = text
1394        .parse()
1395        .map_err(|e| format!("invalid wrangler.toml: {e}"))?;
1396    Ok(doc
1397        .get(WranglerKey::Hyperdrive.top_key())
1398        .and_then(|i| i.as_array_of_tables())
1399        .into_iter()
1400        .flatten()
1401        .filter_map(|t| {
1402            Some((
1403                t.get("binding")?.as_str()?.to_string(),
1404                t.get("id")?.as_str()?.to_string(),
1405            ))
1406        })
1407        .collect())
1408}
1409
1410/// Hyperdrive H2 (#3319): point `[[hyperdrive]]` entries at their configs,
1411/// structurally, by binding: each entry whose binding `ids` lists gets that
1412/// id. Unchanged text when nothing differs, as [`materialise_d1_databases`].
1413/// Only an id is written: the connection string is never an input here.
1414pub fn materialise_hyperdrive_ids(
1415    text: &str,
1416    ids: &std::collections::BTreeMap<String, String>,
1417) -> Result<String, String> {
1418    let mut doc: toml_edit::DocumentMut = text
1419        .parse()
1420        .map_err(|e| format!("invalid wrangler.toml: {e}"))?;
1421    let mut changed = false;
1422    if let Some(entries) = doc
1423        .get_mut(WranglerKey::Hyperdrive.top_key())
1424        .and_then(|i| i.as_array_of_tables_mut())
1425    {
1426        for entry in entries.iter_mut() {
1427            let Some(id) = entry
1428                .get("binding")
1429                .and_then(|b| b.as_str())
1430                .and_then(|b| ids.get(b))
1431                .cloned()
1432            else {
1433                continue;
1434            };
1435            if let Some(item) = entry.get_mut("id")
1436                && item.as_str() != Some(id.as_str())
1437            {
1438                set_string_preserving_decor(item, &id);
1439                changed = true;
1440            }
1441        }
1442    }
1443    Ok(if changed {
1444        doc.to_string()
1445    } else {
1446        text.to_string()
1447    })
1448}
1449
1450/// #3301: a generated `wrangler.toml`'s `[[secrets_store_secrets]]` entries as
1451/// `(binding, store_id, secret_name)`, in file order; an entry missing any is
1452/// skipped. In a freshly generated file `store_id` is the store's *name*.
1453pub fn stored_secret_entries(text: &str) -> Result<Vec<(String, String, String)>, String> {
1454    let doc: toml_edit::DocumentMut = text
1455        .parse()
1456        .map_err(|e| format!("invalid wrangler.toml: {e}"))?;
1457    Ok(doc
1458        .get(WranglerKey::SecretsStoreSecrets.top_key())
1459        .and_then(|i| i.as_array_of_tables())
1460        .into_iter()
1461        .flatten()
1462        .filter_map(|t| {
1463            Some((
1464                t.get("binding")?.as_str()?.to_string(),
1465                t.get("store_id")?.as_str()?.to_string(),
1466                t.get("secret_name")?.as_str()?.to_string(),
1467            ))
1468        })
1469        .collect())
1470}
1471
1472/// #3301: point `[[secrets_store_secrets]]` entries at their stores' ids,
1473/// structurally, by binding. Unchanged text when nothing differs.
1474pub fn materialise_stored_secret_stores(
1475    text: &str,
1476    stores: &std::collections::BTreeMap<String, String>,
1477) -> Result<String, String> {
1478    let mut doc: toml_edit::DocumentMut = text
1479        .parse()
1480        .map_err(|e| format!("invalid wrangler.toml: {e}"))?;
1481    let mut changed = false;
1482    if let Some(entries) = doc
1483        .get_mut(WranglerKey::SecretsStoreSecrets.top_key())
1484        .and_then(|i| i.as_array_of_tables_mut())
1485    {
1486        for entry in entries.iter_mut() {
1487            let Some(id) = entry
1488                .get("binding")
1489                .and_then(|b| b.as_str())
1490                .and_then(|b| stores.get(b))
1491            else {
1492                continue;
1493            };
1494            if let Some(item) = entry.get_mut("store_id")
1495                && item.as_str() != Some(id.as_str())
1496            {
1497                set_string_preserving_decor(item, id);
1498                changed = true;
1499            }
1500        }
1501    }
1502    Ok(if changed {
1503        doc.to_string()
1504    } else {
1505        text.to_string()
1506    })
1507}
1508
1509/// #3513 A: point `[[mtls_certificates]]` entries at their certificates' ids, structurally, by
1510/// binding. Unchanged text when nothing differs.
1511pub fn materialise_mtls_certificates(
1512    text: &str,
1513    certificates: &std::collections::BTreeMap<String, String>,
1514) -> Result<String, String> {
1515    let mut doc: toml_edit::DocumentMut = text
1516        .parse()
1517        .map_err(|e| format!("invalid wrangler.toml: {e}"))?;
1518    let mut changed = false;
1519    if let Some(entries) = doc
1520        .get_mut(WranglerKey::MtlsCertificates.top_key())
1521        .and_then(|i| i.as_array_of_tables_mut())
1522    {
1523        for entry in entries.iter_mut() {
1524            let Some(id) = entry
1525                .get("binding")
1526                .and_then(|b| b.as_str())
1527                .and_then(|b| certificates.get(b))
1528            else {
1529                continue;
1530            };
1531            if let Some(item) = entry.get_mut("certificate_id")
1532                && item.as_str() != Some(id.as_str())
1533            {
1534                set_string_preserving_decor(item, id);
1535                changed = true;
1536            }
1537        }
1538    }
1539    Ok(if changed {
1540        doc.to_string()
1541    } else {
1542        text.to_string()
1543    })
1544}
1545
1546/// A generated `wrangler.toml`'s `[[r2_buckets]]` entries as `(binding,
1547/// bucket_name, jurisdiction)`, in file order; an entry missing a binding or
1548/// a name is skipped.
1549pub fn r2_bucket_entries(text: &str) -> Result<Vec<(String, String, Option<String>)>, String> {
1550    let doc: toml_edit::DocumentMut = text
1551        .parse()
1552        .map_err(|e| format!("invalid wrangler.toml: {e}"))?;
1553    Ok(doc
1554        .get(WranglerKey::R2Buckets.top_key())
1555        .and_then(|i| i.as_array_of_tables())
1556        .into_iter()
1557        .flatten()
1558        .filter_map(|t| {
1559            Some((
1560                t.get("binding")?.as_str()?.to_string(),
1561                t.get("bucket_name")?.as_str()?.to_string(),
1562                t.get("jurisdiction")
1563                    .and_then(|j| j.as_str())
1564                    .map(str::to_string),
1565            ))
1566        })
1567        .collect())
1568}
1569
1570/// P5 (#2323): point `[[r2_buckets]]` entries at their deploy-time bucket
1571/// names, structurally, by binding: each entry whose binding `names` lists gets
1572/// that `bucket_name`. The generated name is the unqualified derived one
1573/// ([`r2_bucket_name`]); an environment qualifies it. Unchanged text when
1574/// nothing differs, as [`materialise_kv_namespace_ids`].
1575pub fn materialise_r2_bucket_names(
1576    text: &str,
1577    names: &std::collections::BTreeMap<String, String>,
1578) -> Result<String, String> {
1579    let mut doc: toml_edit::DocumentMut = text
1580        .parse()
1581        .map_err(|e| format!("invalid wrangler.toml: {e}"))?;
1582    let mut changed = false;
1583    if let Some(entries) = doc
1584        .get_mut(WranglerKey::R2Buckets.top_key())
1585        .and_then(|i| i.as_array_of_tables_mut())
1586    {
1587        for entry in entries.iter_mut() {
1588            let Some(name) = entry
1589                .get("binding")
1590                .and_then(|b| b.as_str())
1591                .and_then(|b| names.get(b))
1592                .cloned()
1593            else {
1594                continue;
1595            };
1596            if let Some(item) = entry.get_mut("bucket_name")
1597                && item.as_str() != Some(name.as_str())
1598            {
1599                set_string_preserving_decor(item, &name);
1600                changed = true;
1601            }
1602        }
1603    }
1604    Ok(if changed {
1605        doc.to_string()
1606    } else {
1607        text.to_string()
1608    })
1609}
1610
1611/// The bindings of a generated `wrangler.toml`'s `[[kv_namespaces]]` entries
1612/// whose `id` is still that binding's deploy-time placeholder
1613/// ([`kv_id_placeholder`]), in file order: what [`materialise_kv_namespace_ids`]
1614/// would patch. Exposed so a caller can learn which ids it needs before doing
1615/// the (possibly fallible) work of finding them, as `bynk dev --remote` does
1616/// before it reads the ledger. Empty for a config with no KV, or one already
1617/// materialised.
1618pub fn kv_bindings_needing_ids(text: &str) -> Result<Vec<String>, String> {
1619    let doc: toml_edit::DocumentMut = text
1620        .parse()
1621        .map_err(|e| format!("invalid wrangler.toml: {e}"))?;
1622    Ok(kv_entries(&doc)
1623        .filter(|(binding, id)| *id == kv_id_placeholder(binding))
1624        .map(|(binding, _)| binding.to_string())
1625        .collect())
1626}
1627
1628/// Materialise deploy-time KV namespace ids in a generated `wrangler.toml`'s
1629/// text, structurally, by binding (S4b, #1967). Each `[[kv_namespaces]]` entry
1630/// whose binding has an id in `ids`, and whose `id` is currently *exactly* that
1631/// binding's placeholder ([`kv_id_placeholder`]), gets the id; the decor around
1632/// the value (the `# set at deploy time` note) is kept.
1633///
1634/// Any other state — no `[[kv_namespaces]]` section, an entry already
1635/// materialised, a binding `ids` doesn't name — is left alone, and when nothing
1636/// changes `text` is returned unchanged (byte-for-byte: the document is never
1637/// re-serialised in that case, so there's nothing for a caller to mistake for
1638/// a real write). It is not a general "overwrite with the given id" operation:
1639/// re-provisioning is a different feature (#1305's Decision B).
1640pub fn materialise_kv_namespace_ids(
1641    text: &str,
1642    ids: &std::collections::BTreeMap<String, String>,
1643) -> Result<String, String> {
1644    let mut doc: toml_edit::DocumentMut = text
1645        .parse()
1646        .map_err(|e| format!("invalid wrangler.toml: {e}"))?;
1647    let mut changed = false;
1648    if let Some(entries) = doc
1649        .get_mut(WranglerKey::KvNamespaces.top_key())
1650        .and_then(|i| i.as_array_of_tables_mut())
1651    {
1652        for entry in entries.iter_mut() {
1653            let Some(binding) = entry.get("binding").and_then(|b| b.as_str()) else {
1654                continue;
1655            };
1656            let Some(id) = ids.get(binding) else {
1657                continue;
1658            };
1659            let placeholder = kv_id_placeholder(binding);
1660            if let Some(item) = entry.get_mut("id")
1661                && item.as_str() == Some(placeholder.as_str())
1662            {
1663                set_string_preserving_decor(item, id);
1664                changed = true;
1665            }
1666        }
1667    }
1668    Ok(if changed {
1669        doc.to_string()
1670    } else {
1671        text.to_string()
1672    })
1673}
1674
1675/// P3 (#2342): the rate limiters whose `namespace_id` is still its
1676/// placeholder, by `name`, in file order.
1677pub fn ratelimits_needing_ids(text: &str) -> Result<Vec<String>, String> {
1678    let doc: toml_edit::DocumentMut = text
1679        .parse()
1680        .map_err(|e| format!("invalid wrangler.toml: {e}"))?;
1681    let mut out = Vec::new();
1682    if let Some(entries) = doc
1683        .get(WranglerKey::RateLimits.top_key())
1684        .and_then(|i| i.as_array_of_tables())
1685    {
1686        for entry in entries.iter() {
1687            let Some(name) = entry.get("name").and_then(|b| b.as_str()) else {
1688                continue;
1689            };
1690            if entry.get("namespace_id").and_then(|i| i.as_str())
1691                == Some(ratelimit_namespace_placeholder(name).as_str())
1692            {
1693                out.push(name.to_string());
1694            }
1695        }
1696    }
1697    Ok(out)
1698}
1699
1700/// P3 (#2342): write each rate limiter's allocated `namespace_id` over its
1701/// placeholder, structurally, by `name`, leaving its `simple = { … }` and
1702/// comment as they are. Unchanged text when nothing matches, as
1703/// [`materialise_kv_namespace_ids`].
1704pub fn materialise_ratelimit_namespace_ids(
1705    text: &str,
1706    ids: &std::collections::BTreeMap<String, String>,
1707) -> Result<String, String> {
1708    let mut doc: toml_edit::DocumentMut = text
1709        .parse()
1710        .map_err(|e| format!("invalid wrangler.toml: {e}"))?;
1711    let mut changed = false;
1712    if let Some(entries) = doc
1713        .get_mut(WranglerKey::RateLimits.top_key())
1714        .and_then(|i| i.as_array_of_tables_mut())
1715    {
1716        for entry in entries.iter_mut() {
1717            let Some(name) = entry.get("name").and_then(|b| b.as_str()) else {
1718                continue;
1719            };
1720            let Some(id) = ids.get(name) else {
1721                continue;
1722            };
1723            let placeholder = ratelimit_namespace_placeholder(name);
1724            if let Some(item) = entry.get_mut("namespace_id")
1725                && item.as_str() == Some(placeholder.as_str())
1726            {
1727                set_string_preserving_decor(item, id);
1728                changed = true;
1729            }
1730        }
1731    }
1732    Ok(if changed {
1733        doc.to_string()
1734    } else {
1735        text.to_string()
1736    })
1737}
1738
1739/// Interop I5 (#1972): point Service Bindings at other Workers, structurally,
1740/// by binding: each `[[services]]` entry whose binding `targets` names gets
1741/// that `service`. `bynk dev` uses it to bind a foreign Worker to its local
1742/// stand-in, which runs under a name of its own so that it never answers for
1743/// the real Worker in wrangler's shared dev registry. Unchanged text when
1744/// nothing matches, as [`materialise_kv_namespace_ids`].
1745pub fn retarget_services(
1746    text: &str,
1747    targets: &std::collections::BTreeMap<String, String>,
1748) -> Result<String, String> {
1749    let mut doc: toml_edit::DocumentMut = text
1750        .parse()
1751        .map_err(|e| format!("invalid wrangler.toml: {e}"))?;
1752    let mut changed = false;
1753    if let Some(entries) = doc
1754        .get_mut(WranglerKey::Services.top_key())
1755        .and_then(|i| i.as_array_of_tables_mut())
1756    {
1757        for entry in entries.iter_mut() {
1758            let Some(target) = entry
1759                .get("binding")
1760                .and_then(|b| b.as_str())
1761                .and_then(|b| targets.get(b))
1762                .cloned()
1763            else {
1764                continue;
1765            };
1766            if let Some(item) = entry.get_mut("service")
1767                && item.as_str() != Some(target.as_str())
1768            {
1769                set_string_preserving_decor(item, &target);
1770                changed = true;
1771            }
1772        }
1773    }
1774    Ok(if changed {
1775        doc.to_string()
1776    } else {
1777        text.to_string()
1778    })
1779}
1780
1781/// #3480: the config `bynk dev` serves, where each `[[ai_search]]` entry also
1782/// carries `remote = true`: AI Search has no local simulation, so wrangler
1783/// proxies the binding to the deployed instance. Only ever applied to the
1784/// development copy; the config `bynk deploy` reads never carries it. Unchanged
1785/// text when there is no such entry.
1786pub fn enable_remote_ai_search(text: &str) -> Result<String, String> {
1787    let mut doc: toml_edit::DocumentMut = text
1788        .parse()
1789        .map_err(|e| format!("invalid wrangler.toml: {e}"))?;
1790    let mut changed = false;
1791    if let Some(entries) = doc
1792        .get_mut(WranglerKey::AiSearch.top_key())
1793        .and_then(|i| i.as_array_of_tables_mut())
1794    {
1795        for entry in entries.iter_mut() {
1796            if entry.get("remote").and_then(|r| r.as_bool()) != Some(true) {
1797                entry.insert("remote", toml_edit::value(true));
1798                changed = true;
1799            }
1800        }
1801    }
1802    Ok(if changed {
1803        doc.to_string()
1804    } else {
1805        text.to_string()
1806    })
1807}
1808
1809/// #3513 A: the binding of each `[[mtls_certificates]]` entry, in file order.
1810pub fn mtls_certificate_bindings(text: &str) -> Result<Vec<String>, String> {
1811    let doc: toml_edit::DocumentMut = text
1812        .parse()
1813        .map_err(|e| format!("invalid wrangler.toml: {e}"))?;
1814    Ok(doc
1815        .get(WranglerKey::MtlsCertificates.top_key())
1816        .and_then(|i| i.as_array_of_tables())
1817        .into_iter()
1818        .flatten()
1819        .filter_map(|t| Some(t.get("binding")?.as_str()?.to_string()))
1820        .collect())
1821}
1822
1823/// #3513 A: `text` without the `[[mtls_certificates]]` entries bound as `bindings`. `bynk dev`
1824/// drops a certificate no deploy has linked from its development copy: marked `remote = true`
1825/// with a name where an id belongs, it could fail wrangler's whole startup, and unbound the Worker
1826/// serves and only a call through the binding fails. Unchanged text when none matches.
1827pub fn drop_mtls_certificates(text: &str, bindings: &[String]) -> Result<String, String> {
1828    let mut doc: toml_edit::DocumentMut = text
1829        .parse()
1830        .map_err(|e| format!("invalid wrangler.toml: {e}"))?;
1831    let mut changed = false;
1832    let mut now_empty = false;
1833    if let Some(entries) = doc
1834        .get_mut(WranglerKey::MtlsCertificates.top_key())
1835        .and_then(|i| i.as_array_of_tables_mut())
1836    {
1837        let before = entries.len();
1838        entries.retain(|e| {
1839            !e.get("binding")
1840                .and_then(|b| b.as_str())
1841                .is_some_and(|b| bindings.iter().any(|x| x == b))
1842        });
1843        changed = entries.len() != before;
1844        now_empty = entries.is_empty();
1845    }
1846    if now_empty {
1847        doc.remove(WranglerKey::MtlsCertificates.top_key());
1848    }
1849    Ok(if changed {
1850        doc.to_string()
1851    } else {
1852        text.to_string()
1853    })
1854}
1855
1856/// #3513 A: the config `bynk dev` serves, where each `[[mtls_certificates]]` entry also carries
1857/// `remote = true`: there is no local simulation of an mTLS binding, so wrangler runs it on
1858/// Cloudflare. Only ever applied to the development copy; the config `bynk deploy` reads never
1859/// carries it. Unchanged text when there is no such entry.
1860pub fn enable_remote_mtls(text: &str) -> Result<String, String> {
1861    let mut doc: toml_edit::DocumentMut = text
1862        .parse()
1863        .map_err(|e| format!("invalid wrangler.toml: {e}"))?;
1864    let mut changed = false;
1865    if let Some(entries) = doc
1866        .get_mut(WranglerKey::MtlsCertificates.top_key())
1867        .and_then(|i| i.as_array_of_tables_mut())
1868    {
1869        for entry in entries.iter_mut() {
1870            if entry.get("remote").and_then(|r| r.as_bool()) != Some(true) {
1871                entry.insert("remote", toml_edit::value(true));
1872                changed = true;
1873            }
1874        }
1875    }
1876    Ok(if changed {
1877        doc.to_string()
1878    } else {
1879        text.to_string()
1880    })
1881}
1882
1883/// #3581 (the dev agent-inspection track): the development copy of a Worker's
1884/// config binds the registry Durable Object its `index.ts` re-exports
1885/// (`BynkInspectRegistry`) as `__BYNK_INSPECT_REGISTRY`, and declares its class,
1886/// SQLite-backed like every other. Only ever applied to the development copy: the
1887/// config `bynk deploy` reads is a different build, which never carries it. A
1888/// Worker whose entry does not re-export the class (one that hosts no agent) is
1889/// returned unchanged, as is one that already has it.
1890pub fn enable_agent_inspection(text: &str, entry: &str) -> Result<String, String> {
1891    const CLASS: &str = "BynkInspectRegistry";
1892    if !entry.contains(CLASS) {
1893        return Ok(text.to_string());
1894    }
1895    let mut doc: toml_edit::DocumentMut = text
1896        .parse()
1897        .map_err(|e| format!("invalid wrangler.toml: {e}"))?;
1898    let bound = doc
1899        .get(WranglerKey::DurableObjectBindings.top_key())
1900        .and_then(|d| d.get("bindings"))
1901        .and_then(|b| b.as_array_of_tables())
1902        .is_some_and(|rows| {
1903            rows.iter()
1904                .any(|r| r.get("class_name").and_then(|c| c.as_str()) == Some(CLASS))
1905        });
1906    if bound {
1907        return Ok(text.to_string());
1908    }
1909    let mut binding = toml_edit::Table::new();
1910    binding.insert("name", toml_edit::value(env_protocol::INSPECT_REGISTRY));
1911    binding.insert("class_name", toml_edit::value(CLASS));
1912    let durable = doc
1913        .entry(WranglerKey::DurableObjectBindings.top_key())
1914        .or_insert_with(|| toml_edit::Item::Table(toml_edit::Table::new()))
1915        .as_table_mut()
1916        .ok_or("`durable_objects` is not a table")?;
1917    durable
1918        .entry("bindings")
1919        .or_insert_with(|| toml_edit::Item::ArrayOfTables(toml_edit::ArrayOfTables::new()))
1920        .as_array_of_tables_mut()
1921        .ok_or("`durable_objects.bindings` is not an array of tables")?
1922        .push(binding);
1923    let mut class = toml_edit::Table::new();
1924    class.insert("type", toml_edit::value("durable-object"));
1925    class.insert("storage", toml_edit::value("sqlite"));
1926    doc.entry(WranglerKey::Exports.top_key())
1927        .or_insert_with(|| {
1928            let mut t = toml_edit::Table::new();
1929            t.set_implicit(true);
1930            toml_edit::Item::Table(t)
1931        })
1932        .as_table_mut()
1933        .ok_or("`exports` is not a table")?
1934        .insert(CLASS, toml_edit::Item::Table(class));
1935    Ok(doc.to_string())
1936}
1937
1938/// #3513 B: the config `bynk dev` serves, where the `[analytics]` table (the Analytics SQL
1939/// binding) also carries `remote = true`: there is no local implementation of it, so wrangler
1940/// runs the query on Cloudflare. Only ever applied to the development copy. Unchanged text when
1941/// there is no such table.
1942pub fn enable_remote_analytics_sql(text: &str) -> Result<String, String> {
1943    let mut doc: toml_edit::DocumentMut = text
1944        .parse()
1945        .map_err(|e| format!("invalid wrangler.toml: {e}"))?;
1946    let mut changed = false;
1947    if let Some(table) = doc
1948        .get_mut("analytics")
1949        .and_then(|i| i.as_table_like_mut())
1950        .filter(|t| t.get("remote").and_then(|r| r.as_bool()) != Some(true))
1951    {
1952        table.insert("remote", toml_edit::value(true));
1953        changed = true;
1954    }
1955    Ok(if changed {
1956        doc.to_string()
1957    } else {
1958        text.to_string()
1959    })
1960}
1961
1962/// Each `[[kv_namespaces]]` entry's `(binding, id)`, in file order; an entry
1963/// missing either is skipped.
1964fn kv_entries(doc: &toml_edit::DocumentMut) -> impl Iterator<Item = (&str, &str)> {
1965    doc.get(WranglerKey::KvNamespaces.top_key())
1966        .and_then(|i| i.as_array_of_tables())
1967        .into_iter()
1968        .flatten()
1969        .filter_map(|t| Some((t.get("binding")?.as_str()?, t.get("id")?.as_str()?)))
1970}
1971
1972#[cfg(test)]
1973mod analytics_sql_dev_tests {
1974    use super::*;
1975
1976    const CONFIG: &str = "name = \"shop\"\n\n[[analytics_engine_datasets]]\nbinding = \"ANALYTICS_SIGNUPS\"\ndataset = \"shop_signups\"\n\n[analytics]\nbinding = \"CF_ANALYTICS_SQL\"\n";
1977
1978    #[test]
1979    fn the_analytics_sql_binding_runs_remotely_in_the_development_copy() {
1980        let out = enable_remote_analytics_sql(CONFIG).unwrap();
1981        let doc: toml::Table = out.parse().unwrap();
1982        assert_eq!(doc["analytics"]["remote"].as_bool(), Some(true));
1983        assert_eq!(
1984            doc["analytics"]["binding"].as_str(),
1985            Some("CF_ANALYTICS_SQL")
1986        );
1987        // The dataset the Worker writes to is a different table, and stays as it was.
1988        let dataset = &doc["analytics_engine_datasets"][0];
1989        assert_eq!(dataset["dataset"].as_str(), Some("shop_signups"));
1990        assert!(dataset.get("remote").is_none(), "{out}");
1991        // The config `bynk deploy` reads is the original, which never carries it.
1992        assert!(!CONFIG.contains("remote"));
1993    }
1994
1995    #[test]
1996    fn it_is_idempotent_and_leaves_a_config_without_the_binding_alone() {
1997        let once = enable_remote_analytics_sql(CONFIG).unwrap();
1998        assert_eq!(enable_remote_analytics_sql(&once).unwrap(), once);
1999        let plain = "name = \"shop\"\n";
2000        assert_eq!(enable_remote_analytics_sql(plain).unwrap(), plain);
2001        assert!(enable_remote_analytics_sql("not = [valid").is_err());
2002    }
2003}
2004
2005#[cfg(test)]
2006mod mtls_tests {
2007    use super::*;
2008
2009    const CONFIG: &str = "name = \"shop\"\n\n[[mtls_certificates]]\nbinding = \"MTLS_BACKEND\"\ncertificate_id = \"acme-client\" # the certificate's name\n\n[[mtls_certificates]]\nbinding = \"MTLS_OTHER\"\ncertificate_id = \"ops\"\n";
2010
2011    #[test]
2012    fn the_stanza_names_the_certificate_and_a_binding_lists_each_entry() {
2013        assert_eq!(
2014            mtls_certificate_bindings(CONFIG).unwrap(),
2015            ["MTLS_BACKEND", "MTLS_OTHER"]
2016        );
2017        assert!(
2018            mtls_certificate_bindings("name = \"shop\"\n")
2019                .unwrap()
2020                .is_empty()
2021        );
2022    }
2023
2024    #[test]
2025    fn materialising_replaces_only_the_linked_bindings_ids_and_keeps_the_comment() {
2026        let ids =
2027            std::collections::BTreeMap::from([("MTLS_BACKEND".to_string(), "c-123".to_string())]);
2028        let out = materialise_mtls_certificates(CONFIG, &ids).unwrap();
2029        assert!(
2030            out.contains("certificate_id = \"c-123\" # the certificate's name"),
2031            "{out}"
2032        );
2033        assert!(out.contains("certificate_id = \"ops\""), "{out}");
2034        // A repeat changes nothing.
2035        assert_eq!(materialise_mtls_certificates(&out, &ids).unwrap(), out);
2036        assert!(materialise_mtls_certificates("not = [valid", &ids).is_err());
2037    }
2038
2039    #[test]
2040    fn the_development_copy_runs_each_binding_on_the_account() {
2041        let out = enable_remote_mtls(CONFIG).unwrap();
2042        assert_eq!(out.matches("remote = true").count(), 2, "{out}");
2043        assert_eq!(enable_remote_mtls(&out).unwrap(), out);
2044        let plain = "name = \"shop\"\n";
2045        assert_eq!(enable_remote_mtls(plain).unwrap(), plain);
2046        assert!(enable_remote_mtls("not = [valid").is_err());
2047        // The config the deploy reads is the original, which never carries it.
2048        assert!(!CONFIG.contains("remote"));
2049    }
2050}
2051
2052#[cfg(test)]
2053mod inspect_dev_tests {
2054    use super::*;
2055
2056    const ENTRY: &str = "import { BynkInspectRegistry } from \"../../__bynk_runtime/inspect.js\";\nexport { BynkInspectRegistry };\n";
2057
2058    /// The development copy of a Worker that hosts agents binds the registry and
2059    /// declares its class; applying it again changes nothing.
2060    #[test]
2061    fn the_development_copy_binds_the_registry() {
2062        let text = "name = \"shop\"\n\n[[durable_objects.bindings]]\nname = \"CART\"\nclass_name = \"Cart\"\n\n[exports.Cart]\ntype = \"durable-object\"\nstorage = \"sqlite\"\n";
2063        let out = enable_agent_inspection(text, ENTRY).unwrap();
2064        assert!(out.contains("name = \"__BYNK_INSPECT_REGISTRY\""), "{out}");
2065        assert!(
2066            out.contains("class_name = \"BynkInspectRegistry\""),
2067            "{out}"
2068        );
2069        assert!(out.contains("[exports.BynkInspectRegistry]"), "{out}");
2070        assert!(out.contains("class_name = \"Cart\""), "{out}");
2071        assert_eq!(enable_agent_inspection(&out, ENTRY).unwrap(), out);
2072    }
2073
2074    /// A Worker whose entry does not re-export the class is left as it was.
2075    #[test]
2076    fn a_worker_without_the_registry_export_is_unchanged() {
2077        let text = "name = \"shop\"\n";
2078        assert_eq!(enable_agent_inspection(text, "export {};\n").unwrap(), text);
2079    }
2080
2081    /// A Worker with no durable-object bindings yet gets the first.
2082    #[test]
2083    fn a_worker_with_no_bindings_gets_the_first() {
2084        let out = enable_agent_inspection("name = \"shop\"\n", ENTRY).unwrap();
2085        assert!(out.contains("[[durable_objects.bindings]]"), "{out}");
2086    }
2087}
2088
2089#[cfg(test)]
2090mod ai_search_dev_tests {
2091    use super::*;
2092
2093    /// The development copy proxies each AI Search binding to the account;
2094    /// text with no such binding is returned unchanged.
2095    #[test]
2096    fn the_development_copy_proxies_each_ai_search_binding() {
2097        let text = "name = \"shop\"\n\n[[ai_search]]\nbinding = \"AI_SEARCH_KB\"\ninstance_name = \"support-docs\"\n\n[[ai_search]]\nbinding = \"AI_SEARCH_B\"\ninstance_name = \"b\"\n";
2098        let out = enable_remote_ai_search(text).unwrap();
2099        assert_eq!(out.matches("remote = true").count(), 2, "{out}");
2100        assert!(out.contains("instance_name = \"support-docs\""));
2101        assert_eq!(enable_remote_ai_search(&out).unwrap(), out);
2102        let plain = "name = \"shop\"\n";
2103        assert_eq!(enable_remote_ai_search(plain).unwrap(), plain);
2104        assert!(enable_remote_ai_search("not = [valid").is_err());
2105    }
2106}
2107
2108#[cfg(test)]
2109mod vectorize_name_tests {
2110    use super::*;
2111
2112    #[test]
2113    fn dev_binds_the_named_index_remotely_and_unbinds_the_rest() {
2114        let text = "name = \"w\"\n\n[[vectorize]]\nbinding = \"VECTORIZE_DOCS\"\nindex_name = \"w-docs\"\n\n[[vectorize]]\nbinding = \"VECTORIZE_OTHER\"\nindex_name = \"w-other\"\n";
2115        let dev = std::collections::BTreeMap::from([(
2116            "VECTORIZE_DOCS".to_string(),
2117            "docs-dev".to_string(),
2118        )]);
2119        let declared = std::collections::BTreeMap::from([(
2120            "VECTORIZE_DOCS".to_string(),
2121            "768:cosine".to_string(),
2122        )]);
2123        let out = bind_vectorize_for_dev(text, &dev, &declared).unwrap();
2124        assert!(
2125            out.contains("index_name = \"docs-dev\"") && out.contains("remote = true"),
2126            "{out}"
2127        );
2128        assert!(
2129            !out.contains("VECTORIZE_OTHER") && !out.contains("w-docs"),
2130            "{out}"
2131        );
2132        assert!(
2133            out.contains("BYNK_DEV_INDEX_VECTORIZE_DOCS = \"768:cosine\""),
2134            "{out}"
2135        );
2136        // Nothing bound leaves no stanza at all; no Vectorize leaves the text.
2137        let none = bind_vectorize_for_dev(text, &Default::default(), &Default::default()).unwrap();
2138        assert!(!none.contains("[[vectorize]]"), "{none}");
2139        assert_eq!(
2140            bind_vectorize_for_dev("name = \"w\"\n", &dev, &declared).unwrap(),
2141            "name = \"w\"\n"
2142        );
2143    }
2144
2145    #[test]
2146    fn an_adopted_binding_with_no_stanza_is_an_error_not_a_silent_derived_name() {
2147        let names = std::collections::BTreeMap::from([(
2148            "VECTORIZE_DOCS".to_string(),
2149            "docs-prod".to_string(),
2150        )]);
2151        let text = "name = \"w\"\n\n[env.production]\nname = \"w-production\"\n";
2152        let err = materialise_vectorize_index_names(text, "production", &names).unwrap_err();
2153        assert!(err.contains("VECTORIZE_DOCS"), "{err}");
2154    }
2155
2156    #[test]
2157    fn short_name_is_kebab_and_unhashed() {
2158        assert_eq!(
2159            vectorize_index_name("shop-cart", "VECTORIZE_DOCS"),
2160            "shop-cart-docs"
2161        );
2162    }
2163
2164    #[test]
2165    fn long_name_keeps_room_for_the_environment_suffix_and_is_stable() {
2166        let long = "w".repeat(70);
2167        let a = vectorize_index_name(&long, "VECTORIZE_DOCS");
2168        assert_eq!(a, vectorize_index_name(&long, "VECTORIZE_DOCS"));
2169        assert!(a.len() + VECTORIZE_ENV_SUFFIX_ROOM <= VECTORIZE_INDEX_NAME_MAX);
2170        // FNV-1a pin: the hashed form must not change between builds.
2171        assert!(a.ends_with("-46a118f1"), "{a}");
2172    }
2173
2174    #[test]
2175    fn head_does_not_end_in_a_doubled_hyphen() {
2176        // The cut lands on a hyphen: it is trimmed, not doubled.
2177        let worker = format!("{}-{}", "a".repeat(30), "b".repeat(30));
2178        let name = vectorize_index_name(&worker, "VECTORIZE_DOCS");
2179        assert!(!name.contains("--"), "{name}");
2180    }
2181}
2182
2183#[cfg(test)]
2184mod patch_tests {
2185    use super::*;
2186
2187    /// A full, realistic `wrangler.toml` — every stanza `emit_wrangler_toml`
2188    /// can produce, in its real order, with its real banner and inline
2189    /// comment (mirrors `bynk-tests/tests/fixtures/positive/
2190    /// 372_kv_agent_queue_workers/expected/workers/ops-hub/wrangler.toml`
2191    /// byte-for-byte). Review of #1305, finding 2: every test below asserts
2192    /// **exact** patched text against this fixture, not just "the changed
2193    /// field has the right value after a re-parse" — a re-parse is blind by
2194    /// construction to whatever the printer discarded, which is exactly how
2195    /// finding 1 (the whole-document alphabetical re-sort, dropped banner)
2196    /// survived a green suite the first time around.
2197    const REPRESENTATIVE: &str = "\
2198# Generated by bynk — do not edit by hand.
2199name = \"ops-hub\"
2200main = \"index.ts\"
2201compatibility_date = \"2026-08-11\"
2202compatibility_flags = [\"global_fetch_strictly_public\"]
2203
2204[[services]]
2205binding = \"PAYMENT\"
2206service = \"payment\"
2207
2208[[kv_namespaces]]
2209binding = \"KV\"
2210id = \"<KV_NAMESPACE_ID>\" # set at deploy time
2211
2212[[durable_objects.bindings]]
2213name = \"JOB_LEDGER\"
2214class_name = \"JobLedger\"
2215
2216[exports.JobLedger]
2217type = \"durable-object\"
2218storage = \"sqlite\"
2219
2220[[queues.consumers]]
2221queue = \"job-intake\"
2222max_batch_size = 10
2223";
2224
2225    fn ids(pairs: &[(&str, &str)]) -> std::collections::BTreeMap<String, String> {
2226        pairs
2227            .iter()
2228            .map(|(b, i)| (b.to_string(), i.to_string()))
2229            .collect()
2230    }
2231
2232    /// A Worker with the bare namespace and two derived instances (S4b,
2233    /// #1967), as the emitter writes it (fixture `1966_derived_kv_workers`
2234    /// plus the bare `KV`).
2235    const INSTANCES: &str = "\
2236[[kv_namespaces]]
2237binding = \"KV\"
2238id = \"<KV_NAMESPACE_ID>\" # set at deploy time
2239
2240[[kv_namespaces]]
2241binding = \"KV_PRICE_CACHE\"
2242id = \"<KV_PRICE_CACHE_ID>\" # set at deploy time
2243
2244[[kv_namespaces]]
2245binding = \"KV_SESSIONS\"
2246id = \"<KV_SESSIONS_ID>\" # set at deploy time
2247";
2248
2249    /// Interop I5 (#1972): only the named bindings move; the rest of the
2250    /// file, comments included, is untouched, and a no-op is byte-identical.
2251    #[test]
2252    fn retarget_services_moves_only_the_named_bindings() {
2253        let text = "name = \"shop-billing\"\n\n[[services]]\nbinding = \"SHOP_FRONT\"\nservice = \"shop-front\"\n\n[[services]]\nbinding = \"SERVICE_BILLING\"\nservice = \"legacy-billing\" # foreign\n";
2254        let targets = std::collections::BTreeMap::from([(
2255            "SERVICE_BILLING".to_string(),
2256            "bynk-stand-in-shop-billing-legacy-billing".to_string(),
2257        )]);
2258        let out = retarget_services(text, &targets).unwrap();
2259        assert_eq!(
2260            out,
2261            text.replace(
2262                "service = \"legacy-billing\"",
2263                "service = \"bynk-stand-in-shop-billing-legacy-billing\""
2264            )
2265        );
2266        assert_eq!(retarget_services(&out, &targets).unwrap(), out);
2267        assert_eq!(
2268            retarget_services(text, &std::collections::BTreeMap::new()).unwrap(),
2269            text
2270        );
2271        assert!(retarget_services("not [ toml", &targets).is_err());
2272    }
2273
2274    #[test]
2275    fn materialise_kv_namespace_ids_changes_only_the_bare_id() {
2276        let expected = REPRESENTATIVE.replacen("<KV_NAMESPACE_ID>", "abc123", 1);
2277        assert_eq!(
2278            materialise_kv_namespace_ids(REPRESENTATIVE, &ids(&[("KV", "abc123")])).unwrap(),
2279            expected
2280        );
2281        // The `# set at deploy time` note survives — the old text-replace
2282        // behaviour left it in place too (it only replaced the placeholder
2283        // substring, not the whole line), and this slice isn't the one
2284        // deciding whether that note should still be there post-materialisation.
2285        assert!(expected.contains("id = \"abc123\" # set at deploy time"));
2286    }
2287
2288    /// S4b (#1967): each instance's placeholder gets its own id, and only its
2289    /// own: an id for one binding never lands in another's entry.
2290    #[test]
2291    fn materialise_kv_namespace_ids_patches_each_binding_apart() {
2292        let all = materialise_kv_namespace_ids(
2293            INSTANCES,
2294            &ids(&[
2295                ("KV", "bare"),
2296                ("KV_SESSIONS", "sess"),
2297                ("KV_PRICE_CACHE", "price"),
2298            ]),
2299        )
2300        .unwrap();
2301        assert_eq!(
2302            all,
2303            INSTANCES
2304                .replacen("<KV_NAMESPACE_ID>", "bare", 1)
2305                .replacen("<KV_PRICE_CACHE_ID>", "price", 1)
2306                .replacen("<KV_SESSIONS_ID>", "sess", 1)
2307        );
2308        let one =
2309            materialise_kv_namespace_ids(INSTANCES, &ids(&[("KV_SESSIONS", "sess")])).unwrap();
2310        assert_eq!(one, INSTANCES.replacen("<KV_SESSIONS_ID>", "sess", 1));
2311        assert_eq!(
2312            kv_bindings_needing_ids(&one).unwrap(),
2313            ["KV", "KV_PRICE_CACHE"]
2314        );
2315    }
2316
2317    /// A placeholder belongs to its binding: the bare placeholder under an
2318    /// instance's binding is not that instance's to patch.
2319    #[test]
2320    fn materialise_kv_namespace_ids_matches_each_bindings_own_placeholder() {
2321        let text = "[[kv_namespaces]]\nbinding = \"KV_SESSIONS\"\nid = \"<KV_NAMESPACE_ID>\"\n";
2322        assert_eq!(
2323            materialise_kv_namespace_ids(text, &ids(&[("KV_SESSIONS", "sess")])).unwrap(),
2324            text
2325        );
2326        assert!(kv_bindings_needing_ids(text).unwrap().is_empty());
2327    }
2328
2329    #[test]
2330    fn materialise_kv_namespace_ids_is_immune_to_reformatting() {
2331        let text = "[[kv_namespaces]]\nbinding = \"KV\"\nid = \"<KV_NAMESPACE_ID>\" # set at deploy time\n";
2332        let patched = materialise_kv_namespace_ids(text, &ids(&[("KV", "abc123")])).unwrap();
2333        assert_eq!(
2334            patched,
2335            "[[kv_namespaces]]\nbinding = \"KV\"\nid = \"abc123\" # set at deploy time\n"
2336        );
2337    }
2338
2339    #[test]
2340    fn materialise_kv_namespace_ids_is_a_no_op_without_a_kv_namespaces_section() {
2341        let text = "name = \"api\"\nmain = \"index.ts\"\n";
2342        let patched = materialise_kv_namespace_ids(text, &ids(&[("KV", "abc123")])).unwrap();
2343        assert_eq!(patched, text);
2344    }
2345
2346    #[test]
2347    fn materialise_kv_namespace_ids_is_a_no_op_once_already_materialised() {
2348        let text = "[[kv_namespaces]]\nbinding = \"KV\"\nid = \"already-real\"\n";
2349        let patched = materialise_kv_namespace_ids(text, &ids(&[("KV", "abc123")])).unwrap();
2350        assert_eq!(patched, text);
2351    }
2352
2353    #[test]
2354    fn kv_bindings_needing_ids_matches_materialise_kv_namespace_ids_own_gate() {
2355        assert_eq!(
2356            kv_bindings_needing_ids(INSTANCES).unwrap(),
2357            ["KV", "KV_PRICE_CACHE", "KV_SESSIONS"]
2358        );
2359        assert!(
2360            kv_bindings_needing_ids("name = \"api\"\n")
2361                .unwrap()
2362                .is_empty()
2363        );
2364        let already_real = "[[kv_namespaces]]\nbinding = \"KV\"\nid = \"already-real\"\n";
2365        assert!(kv_bindings_needing_ids(already_real).unwrap().is_empty());
2366    }
2367
2368    #[test]
2369    fn kv_instance_title_is_the_worker_then_the_capability_in_kebab_case() {
2370        assert_eq!(
2371            kv_instance_title("shop-cart", "KV_SESSIONS"),
2372            "shop-cart-sessions"
2373        );
2374        assert_eq!(
2375            kv_instance_title("shop-cart", "KV_PRICE_CACHE"),
2376            "shop-cart-price-cache"
2377        );
2378    }
2379
2380    #[test]
2381    fn kv_bindings_needing_ids_rejects_invalid_toml() {
2382        assert!(kv_bindings_needing_ids("not = valid = toml = at = all").is_err());
2383    }
2384
2385    #[test]
2386    fn materialise_kv_namespace_ids_rejects_invalid_toml() {
2387        assert!(
2388            materialise_kv_namespace_ids("not = valid = toml = at = all", &ids(&[("KV", "x")]))
2389                .is_err()
2390        );
2391    }
2392}
2393
2394#[cfg(test)]
2395mod compatibility_flags_tests {
2396    use super::*;
2397
2398    fn strings(names: &[&str]) -> Vec<String> {
2399        names.iter().map(|s| s.to_string()).collect()
2400    }
2401
2402    /// #1890: the default set alone, when the manifest adds nothing.
2403    #[test]
2404    fn the_default_is_global_fetch_strictly_public() {
2405        assert_eq!(
2406            DEFAULT_COMPATIBILITY_FLAGS,
2407            ["global_fetch_strictly_public"]
2408        );
2409        let (flags, duplicates) = compatibility_flags(&[]);
2410        assert_eq!(flags, ["global_fetch_strictly_public"]);
2411        assert!(duplicates.is_empty());
2412    }
2413
2414    /// #1890: the manifest's flags follow the default, in manifest order;
2415    /// names are not checked.
2416    #[test]
2417    fn extra_flags_follow_the_default_in_order() {
2418        let (flags, duplicates) =
2419            compatibility_flags(&strings(&["nodejs_compat", "a_future_flag"]));
2420        assert_eq!(
2421            flags,
2422            [
2423                "global_fetch_strictly_public",
2424                "nodejs_compat",
2425                "a_future_flag"
2426            ]
2427        );
2428        assert!(duplicates.is_empty());
2429    }
2430
2431    /// #1890: a repeat, of a default or of an earlier extra, is dropped and
2432    /// reported once per repeat.
2433    #[test]
2434    fn duplicates_are_dropped_and_reported() {
2435        let (flags, duplicates) = compatibility_flags(&strings(&[
2436            "nodejs_compat",
2437            "global_fetch_strictly_public",
2438            "nodejs_compat",
2439            "nodejs_compat",
2440        ]));
2441        assert_eq!(flags, ["global_fetch_strictly_public", "nodejs_compat"]);
2442        assert_eq!(
2443            duplicates,
2444            [
2445                "global_fetch_strictly_public",
2446                "nodejs_compat",
2447                "nodejs_compat"
2448            ]
2449        );
2450    }
2451}
2452
2453#[cfg(test)]
2454mod vectorize_manifest_tests {
2455    use super::*;
2456
2457    fn index(name: &str, indexed: &[&str]) -> WorkerBinding {
2458        WorkerBinding {
2459            name: name.to_string(),
2460            source: BindingSource::VectorizeIndex {
2461                capability: "Docs".to_string(),
2462                dimensions: 768,
2463                metric: "cosine".to_string(),
2464                indexed: indexed.iter().map(|s| s.to_string()).collect(),
2465            },
2466        }
2467    }
2468
2469    /// #3479: the manifest states each index's configuration, and a Worker with
2470    /// no `Vectorize` instance gets no file.
2471    #[test]
2472    fn the_manifest_states_each_indexs_configuration() {
2473        assert_eq!(emit_vectorize_manifest(&[]), None);
2474        let text = emit_vectorize_manifest(&[
2475            index("VECTORIZE_DOCS", &["category:string", "year:number"]),
2476            index("VECTORIZE_PLAIN", &[]),
2477        ])
2478        .expect("two indexes");
2479        assert!(text.contains(
2480            "{ \"binding\": \"VECTORIZE_DOCS\", \"dimensions\": 768, \"metric\": \"cosine\", \"indexed\": [\"category:string\", \"year:number\"] }"
2481        ));
2482        assert!(text.contains("\"binding\": \"VECTORIZE_PLAIN\", \"dimensions\": 768, \"metric\": \"cosine\", \"indexed\": []"));
2483    }
2484
2485    /// The index entries are read back from a generated config by binding.
2486    #[test]
2487    fn index_entries_are_read_from_the_config() {
2488        let toml = "name = \"shop\"\n\n[[vectorize]]\nbinding = \"VECTORIZE_DOCS\"\nindex_name = \"shop-docs\"\n";
2489        assert_eq!(
2490            vectorize_index_entries(toml).unwrap(),
2491            [("VECTORIZE_DOCS".to_string(), "shop-docs".to_string())]
2492        );
2493    }
2494
2495    /// #3479: an adopted index's name replaces the derived one, in the top-level
2496    /// entries for the default environment and in the environment's block for a
2497    /// named one; a binding that is not adopted is left alone.
2498    #[test]
2499    fn adopted_index_names_are_written_where_the_environment_reads_them() {
2500        let top = "name = \"shop\"\n\n[[vectorize]]\nbinding = \"VECTORIZE_DOCS\"\nindex_name = \"shop-docs\"\n\n[[vectorize]]\nbinding = \"VECTORIZE_OTHER\"\nindex_name = \"shop-other\"\n";
2501        let names = std::collections::BTreeMap::from([(
2502            "VECTORIZE_DOCS".to_string(),
2503            "docs-prod".to_string(),
2504        )]);
2505        let patched = materialise_vectorize_index_names(top, "default", &names).unwrap();
2506        assert!(patched.contains("index_name = \"docs-prod\""), "{patched}");
2507        assert!(patched.contains("index_name = \"shop-other\""), "{patched}");
2508        assert_eq!(
2509            materialise_vectorize_index_names(top, "default", &Default::default()).unwrap(),
2510            top
2511        );
2512        let named = "name = \"shop\"\n\n[[env.staging.vectorize]]\nbinding = \"VECTORIZE_DOCS\"\nindex_name = \"shop-docs-staging\"\n";
2513        let patched = materialise_vectorize_index_names(named, "staging", &names).unwrap();
2514        assert!(patched.contains("index_name = \"docs-prod\""), "{patched}");
2515    }
2516
2517    /// A derived name longer than Cloudflare's 64 bytes keeps its head and ends
2518    /// in a stable hash; a short one is as derived.
2519    #[test]
2520    fn the_derived_name_respects_the_length_limit() {
2521        assert_eq!(
2522            vectorize_index_name("shop-cart", "VECTORIZE_DOCS"),
2523            "shop-cart-docs"
2524        );
2525        let long = vectorize_index_name(&"a".repeat(80), "VECTORIZE_DOCS");
2526        assert_eq!(
2527            long.len(),
2528            VECTORIZE_INDEX_NAME_MAX - VECTORIZE_ENV_SUFFIX_ROOM
2529        );
2530        assert_eq!(
2531            long,
2532            vectorize_index_name(&"a".repeat(80), "VECTORIZE_DOCS")
2533        );
2534        assert_ne!(
2535            long,
2536            vectorize_index_name(&"a".repeat(81), "VECTORIZE_DOCS")
2537        );
2538    }
2539}
2540
2541#[cfg(test)]
2542mod hyperdrive_manifest_tests {
2543    use super::*;
2544
2545    fn binding(name: &str, source: BindingSource) -> WorkerBinding {
2546        WorkerBinding {
2547            name: name.to_string(),
2548            source,
2549        }
2550    }
2551
2552    /// Hyperdrive H5 (#3322): the manifest lists the `MySql` bindings with their
2553    /// mode (`required` when none was written), and a Worker with only a
2554    /// `Postgres` one gets no file, so its output is unchanged.
2555    #[test]
2556    fn the_manifest_lists_mysql_bindings_only() {
2557        let postgres = binding(
2558            "HYPERDRIVE_MAIN",
2559            BindingSource::Postgres {
2560                capability: "Main".to_string(),
2561            },
2562        );
2563        assert_eq!(
2564            emit_hyperdrive_manifest(std::slice::from_ref(&postgres)),
2565            None
2566        );
2567        let bindings = [
2568            postgres,
2569            binding(
2570                "HYPERDRIVE_LEGACY",
2571                BindingSource::MySql {
2572                    capability: "Legacy".to_string(),
2573                    tls: Some("verify-identity".to_string()),
2574                },
2575            ),
2576            binding(
2577                "HYPERDRIVE_OTHER",
2578                BindingSource::MySql {
2579                    capability: "Other".to_string(),
2580                    tls: None,
2581                },
2582            ),
2583        ];
2584        let text = emit_hyperdrive_manifest(&bindings).expect("a MySql binding");
2585        assert!(
2586            text.contains(
2587                r#""binding": "HYPERDRIVE_LEGACY", "kind": "mysql", "tls": "verify-identity""#
2588            ),
2589            "{text}"
2590        );
2591        assert!(
2592            text.contains(r#""binding": "HYPERDRIVE_OTHER", "kind": "mysql", "tls": "required""#),
2593            "{text}"
2594        );
2595        assert!(!text.contains("HYPERDRIVE_MAIN"), "{text}");
2596        // Names and modes only: never a connection string or a URL.
2597        assert!(!text.contains("://") && !text.contains('@'), "{text}");
2598    }
2599}
2600
2601#[cfg(test)]
2602mod containers_tests {
2603    use super::*;
2604
2605    fn container(capability: &str, instance_type: Option<&str>) -> WorkerBinding {
2606        WorkerBinding {
2607            name: format!("CONTAINER_{}", capability.to_ascii_uppercase()),
2608            source: BindingSource::ContainerInstance {
2609                capability: capability.to_string(),
2610                class_name: format!("__Container_{capability}"),
2611                build: "containers/render".to_string(),
2612                root_from_worker: "../../..".to_string(),
2613                port: 8080,
2614                sleep_after: None,
2615                instance_type: instance_type.map(str::to_string),
2616                forward: Vec::new(),
2617            },
2618        }
2619    }
2620
2621    /// #3477: the manifest states each container's capability, build directory
2622    /// and instance type (`null` for the platform's default), and a Worker with
2623    /// no container gets none, so its output is unchanged.
2624    #[test]
2625    fn the_manifest_lists_each_container() {
2626        let text = emit_containers_manifest(&[
2627            container("Renderer", Some("standard-1")),
2628            container("Thumbs", None),
2629        ])
2630        .expect("a manifest");
2631        assert!(
2632            text.contains(&format!("\"version\": {CONTAINERS_MANIFEST_VERSION}")),
2633            "{text}"
2634        );
2635        assert!(text.contains(
2636            "{ \"capability\": \"Renderer\", \"class\": \"__Container_Renderer\", \"build\": \"containers/render\", \"instance_type\": \"standard-1\" }"
2637        ), "{text}");
2638        assert!(text.contains(
2639            "{ \"capability\": \"Thumbs\", \"class\": \"__Container_Thumbs\", \"build\": \"containers/render\", \"instance_type\": null }"
2640        ), "{text}");
2641        let kv = WorkerBinding {
2642            name: "KV".to_string(),
2643            source: BindingSource::Kv,
2644        };
2645        assert_eq!(emit_containers_manifest(&[kv]), None);
2646    }
2647
2648    const CONFIG: &str = r#"name = "shop-render"
2649
2650[[containers]]
2651class_name = "__Container_Renderer"
2652scheduling_policy = "durable_object"
2653
2654[containers.images.Renderer]
2655dockerfile = "../../../containers/render/Dockerfile"
2656build_context = "../../../containers/render"
2657
2658[env.staging]
2659name = "shop-render-staging"
2660
2661[[env.staging.containers]]
2662class_name = "__Container_Renderer"
2663scheduling_policy = "durable_object"
2664
2665[env.staging.containers.images.Renderer]
2666dockerfile = "../../../containers/render/Dockerfile"
2667build_context = "../../../containers/render"
2668"#;
2669
2670    const IMAGE: &str = "registry.cloudflare.com/abc123/renderer@sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
2671
2672    fn adopt() -> std::collections::BTreeMap<String, String> {
2673        [("Renderer".to_string(), IMAGE.to_string())]
2674            .into_iter()
2675            .collect()
2676    }
2677
2678    /// #3477: an adopted image replaces the Dockerfile in the environment's own
2679    /// block (the top level for `default`), and the other environment keeps
2680    /// building.
2681    #[test]
2682    fn an_adopted_image_replaces_the_dockerfile_in_its_environment_only() {
2683        let top = materialise_adopted_container_images(CONFIG, "default", &adopt()).unwrap();
2684        let doc: toml::Table = top.parse().unwrap();
2685        let images = &doc["containers"][0]["images"]["Renderer"];
2686        assert_eq!(images["image"].as_str(), Some(IMAGE));
2687        assert!(images.get("dockerfile").is_none() && images.get("build_context").is_none());
2688        assert!(
2689            doc["env"]["staging"]["containers"][0]["images"]["Renderer"]
2690                .get("dockerfile")
2691                .is_some(),
2692            "{top}"
2693        );
2694        let staging = materialise_adopted_container_images(CONFIG, "staging", &adopt()).unwrap();
2695        let doc: toml::Table = staging.parse().unwrap();
2696        assert_eq!(
2697            doc["env"]["staging"]["containers"][0]["images"]["Renderer"]["image"].as_str(),
2698            Some(IMAGE)
2699        );
2700        assert!(
2701            doc["containers"][0]["images"]["Renderer"]
2702                .get("dockerfile")
2703                .is_some()
2704        );
2705    }
2706
2707    /// An adopted capability with nothing to rewrite would be built after all,
2708    /// so it is an error rather than a silent no-op.
2709    #[test]
2710    fn an_adoption_with_no_entry_to_rewrite_is_refused() {
2711        let other: std::collections::BTreeMap<String, String> =
2712            [("Missing".to_string(), IMAGE.to_string())]
2713                .into_iter()
2714                .collect();
2715        let err = materialise_adopted_container_images(CONFIG, "default", &other).unwrap_err();
2716        assert!(err.contains("containers.images.Missing"), "{err}");
2717        let err = materialise_adopted_container_images(CONFIG, "qa", &adopt()).unwrap_err();
2718        assert!(err.contains("`[env.qa]`"), "{err}");
2719    }
2720}