Skip to main content

bynk_std/
lib.rs

1//! The Bynk standard library's first-party sources, as data.
2//!
3//! The `bynk` conformance surface, the Bynk-written commons (`bynk.list`,
4//! `bynk.map`, `bynk.string`, `bynk.locale`, `bynk.locale.types`) and the
5//! `bynk.cloudflare` platform adapter ship with the compiler rather than being
6//! authored by the user. This crate holds their `.bynk` sources, their
7//! per-platform TypeScript bindings and the metadata the toolchain reads about
8//! them, embedded with `include_str!`. It holds no logic: `bynk-check` parses and
9//! injects these sources when a project `uses` or `consumes` them, and provides
10//! each binding for the selected [`Platform`]. The `bynk` root namespace is
11//! reserved (`bynk.namespace.reserved`) so user code can never collide with it.
12//!
13//! The sources live under `lib/`: the portable layers in `lib/core/` (with the
14//! `bynk` surface's bindings in `lib/core/bindings/`) and the platform adapter in
15//! `lib/cloudflare/`. Nothing in `lib/core/` depends on `lib/cloudflare/`, so the
16//! platform layer can be split out later without renaming a unit.
17
18// The README's `rust` examples are compiled (and, unless marked `no_run`, run)
19// as doctests, so they cannot rot (#1645). `cfg(doctest)` keeps this item out of
20// every build and out of the docs.rs front page, which the `//!` docs above own.
21#[cfg(doctest)]
22#[doc = include_str!("../README.md")]
23struct ReadmeDoctests;
24
25/// The deploy platform — a selection axis distinct from the `--target
26/// {bundle,workers}` emit mode (§6.2). It chooses which `bynk-<platform>.ts`
27/// binding is linked for the `bynk` surface. v0.17 shipped `cloudflare`;
28/// v0.18 adds `node`, making the axis observable (and giving v0.19's
29/// platform-lock enforcement a second platform to fire against).
30#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
31pub enum Platform {
32    #[default]
33    Cloudflare,
34    Node,
35    /// The browser (in-browser track, slice 1 — the REPL/playground host). A
36    /// Tier-3 binding exposing the `bynk` surface over Web APIs, composed with
37    /// `BuildTarget::Bundle` only (a browser cannot do the Workers wire model).
38    Browser,
39}
40
41impl Platform {
42    /// The output filename of this platform's `bynk` binding module.
43    pub fn bynk_binding_filename(self) -> &'static str {
44        match self {
45            Platform::Cloudflare => "bynk-cloudflare.ts",
46            Platform::Node => "bynk-node.ts",
47            Platform::Browser => "bynk-browser.ts",
48        }
49    }
50
51    /// The TypeScript source of this platform's `bynk` binding.
52    pub fn bynk_binding_source(self) -> &'static str {
53        match self {
54            Platform::Cloudflare => BYNK_CLOUDFLARE_BINDING,
55            Platform::Node => BYNK_NODE_BINDING,
56            Platform::Browser => BYNK_BROWSER_BINDING,
57        }
58    }
59
60    /// The platform's stable name (for the `--platform` flag and diagnostics).
61    pub fn as_str(self) -> &'static str {
62        match self {
63            Platform::Cloudflare => "cloudflare",
64            Platform::Node => "node",
65            Platform::Browser => "browser",
66        }
67    }
68}
69
70/// The unit name of the reserved first-party surface adapter.
71pub const BYNK_UNIT: &str = "bynk";
72
73/// The capabilities the env-free `bynk` surface exports (its `exports
74/// capability { … }` line in `bynk.bynk`). First-party symbols live on
75/// synthetic files and are excluded from the binding index, so the
76/// unknown-name quick-fix (#852) offering `consumes bynk { … }` needs this
77/// explicit list. Kept in sync with the adapter source by
78/// `bynk_surface_capabilities_match_the_adapter`.
79pub const BYNK_SURFACE_CAPABILITIES: &[&str] = &[
80    "Clock",
81    "Random",
82    "Logger",
83    "Fetch",
84    "Secrets",
85    "Locale",
86    "Idempotency",
87    "Events",
88];
89
90/// What reaches a first-party npm dependency (see [`FirstPartyNpm::reached_by`]),
91/// by the construct that needs it, never by text in a source file.
92#[derive(Debug, Clone, Copy, PartialEq, Eq)]
93pub enum Reach {
94    /// A context declares a service whose protocol is this one (`from email(…)`
95    /// is `"email"`).
96    ServiceProtocol(&'static str),
97    /// A context declares an instance of this `bynk.cloudflare` capability
98    /// (`capability Main = Postgres`, #3318), named by its base capability.
99    CapabilityInstance(&'static str),
100    /// The project's `bynk.toml` opts in to a test double that runs on it
101    /// (`[test] postgres = "pglite"`, #3321). Decided on the manifest, not on
102    /// any source: nothing in a program names a test double.
103    TestPostgresDouble,
104}
105
106/// A first-party npm dependency (ADR 0799 C, #3328): an npm package the
107/// toolchain itself emits into `out/package.json` for a built-in binding.
108///
109/// It is **pinned to an exact version** (no range), so a toolchain release, not
110/// an `npm install`, changes what runs. It needs no approval (ADR 0575
111/// approves fetched code; this ships inside the toolchain the user already
112/// trusts) and is never `approved` in `bynk.lock`, but it still appears in
113/// `out/package.json` and as a `first-party` `[[npm]]` row, so it is visible.
114/// An adapter in any other package that requires the same package stays under
115/// ADR 0575 and must agree on the version (`bynk.requires.conflicting_range`).
116///
117/// A package enters a build when a runtime module that imports it is emitted
118/// (`runtime_module`), not when a unit is consumed: an unrelated project never
119/// carries it. Each binding added here is held to R-12 (`tsc --strict` over the
120/// binding on its own) and R-16 (a security review) from the retired
121/// standard-library track.
122#[derive(Debug, Clone, Copy, PartialEq, Eq)]
123pub struct FirstPartyNpm {
124    pub package: &'static str,
125    /// An exact version: `MAJOR.MINOR.PATCH`, no range operator.
126    pub version: &'static str,
127    /// The `@bynk/runtime` module (`__bynk_runtime/<name>.ts`) importing it.
128    pub runtime_module: &'static str,
129    /// What, in a project's own checked model, brings the package into a build.
130    /// `bynk.lock`'s first-party row is written only for a project that reaches
131    /// it, so a lock records what the project *could* bring into its build and not
132    /// every pin the toolchain has. Data, so Hyperdrive H1 adds `postgres` with the
133    /// variant for the capability that needs it.
134    pub reached_by: Reach,
135}
136
137/// Every first-party npm dependency. Hyperdrive H1 (#3318) adds `postgres`
138/// here. `bynk-emit`'s `first_party_pins_match_the_runtime` test holds each
139/// pin to the version `@bynk/runtime`'s own `package.json` tests against.
140pub const FIRST_PARTY_NPM: &[FirstPartyNpm] = &[
141    // Inbound email (#3328): `email.ts` parses the raw message with it.
142    FirstPartyNpm {
143        package: "postal-mime",
144        version: "4.2.1",
145        runtime_module: "email",
146        reached_by: Reach::ServiceProtocol("email"),
147    },
148    // Hyperdrive H1 (#3318): `postgres.ts` is the driver seam of `Postgres`,
149    // handed to the binding by a Worker's compose, so only a Worker with a
150    // `Postgres` instance carries the package. 4.0.0, the newest 4.x that was
151    // 14 days old when #3529 moved it from 3.4.5 (the version ADR 0799 A measured).
152    FirstPartyNpm {
153        package: "postgres",
154        version: "4.0.0",
155        runtime_module: "postgres",
156        reached_by: Reach::CapabilityInstance("Postgres"),
157    },
158    // Hyperdrive H5 (#3322): `mysql.ts` is the driver seam of `MySql`, handed to
159    // the binding by a Worker's compose, so only a Worker with a `MySql`
160    // instance carries the package. Cloudflare's mysql2 guide needs 3.13.0 or
161    // later (with `disableEval: true`); this is the newest release that was
162    // more than a month old when H5 was cut.
163    FirstPartyNpm {
164        package: "mysql2",
165        version: "3.24.6",
166        runtime_module: "mysql",
167        reached_by: Reach::CapabilityInstance("MySql"),
168    },
169    // Hyperdrive H4 (#3321): `pglite.ts` is the opt-in `Postgres` test double
170    // (`[test] postgres = "pglite"`), so only a project that opts in carries
171    // the package, and only into a test build: the harness is the one place
172    // that references the module. Pinned at the version ADR 0799 I's
173    // measurements ran.
174    FirstPartyNpm {
175        package: "@electric-sql/pglite",
176        version: "0.5.16",
177        runtime_module: "testing/pglite",
178        reached_by: Reach::TestPostgresDouble,
179    },
180];
181
182/// The first-party npm dependencies a set of emitted runtime modules brings.
183pub fn first_party_npm_for<'a>(
184    modules: impl IntoIterator<Item = &'a str>,
185) -> Vec<&'static FirstPartyNpm> {
186    let modules: Vec<&str> = modules.into_iter().collect();
187    FIRST_PARTY_NPM
188        .iter()
189        .filter(|d| modules.contains(&d.runtime_module))
190        .collect()
191}
192
193/// Whether `version` is an exact `MAJOR.MINOR.PATCH` (with an optional
194/// pre-release or build suffix), which is all a first-party pin may be.
195pub fn is_exact_version(version: &str) -> bool {
196    let core = version.split(['-', '+']).next().unwrap_or_default();
197    let parts: Vec<&str> = core.split('.').collect();
198    parts.len() == 3
199        && parts
200            .iter()
201            .all(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit()))
202}
203
204/// The unit name of the first-party Cloudflare platform adapter (v0.19,
205/// decision 0026): inside the reserved `bynk.*` prefix, so no separate
206/// reservation rule is needed. The surface unit `bynk` stays the portability
207/// marker; `bynk.<platform>` units are the platform-locked ones.
208pub const CLOUDFLARE_UNIT: &str = "bynk.cloudflare";
209
210/// The fixed Worker binding name for the Kv namespace (decision C1, v0.19):
211/// one namespace, one `[[kv_namespaces]]` stanza, one `env.KV` field.
212pub const KV_BINDING_NAME: &str = "KV";
213
214/// v0.18 decision 0021 / v0.19 decision 0025: which first-party provider
215/// classes take the Worker `env` as a constructor argument, keyed by
216/// (unit, provider class). `SecretsProvider` accepts an optional env with a
217/// `globalThis` probe fallback; `WorkersKv` *requires* env on use — KV
218/// namespaces exist only on the Worker `env`, never on `globalThis`.
219///
220/// A view over [`UNITS`]: each entry's [`Unit::env_providers`].
221pub fn provider_takes_env(unit: &str, provider: &str) -> bool {
222    self::unit(unit).is_some_and(|u| u.env_providers.contains(&provider))
223}
224
225/// v0.19 decision 0024: which first-party units are **platform-native** —
226/// consuming one locks its deployment unit to the returned platform. This is
227/// the metadata that drives effective-platform computation, `env` resource
228/// typing, and `wrangler.toml` stanza derivation; no user-facing marker
229/// syntax exists (additive later, when third-party platform adapters become
230/// a goal).
231///
232/// A view over [`UNITS`]: each entry's [`Unit::platform`].
233pub fn platform_of(unit: &str) -> Option<Platform> {
234    self::unit(unit).and_then(|u| u.platform)
235}
236
237/// The unit names of the first-party collection commons (v0.20b): the
238/// Bynk-written combinator stdlib over the built-in `List`/`Map` kernel.
239/// Inside the reserved `bynk.*` prefix; injected when `uses`-imported.
240pub const LIST_UNIT: &str = "bynk.list";
241pub const MAP_UNIT: &str = "bynk.map";
242
243/// `bynk.list` — combinators over the `List` kernel (`fold`, `prepend`,
244/// `length`, `get`, `foldEff`), written in ordinary Bynk (decision 0034):
245/// the first real consumer of v0.20a generics, lambdas, and effectful
246/// traversal. Order-preserving combinators build with `fold` + `prepend`
247/// and a final `reverse` — O(n) builds, never `append` (which would be
248/// O(n²) over the array lowering).
249pub const BYNK_LIST_SRC: &str = include_str!("../lib/core/bynk.list.bynk");
250
251/// `bynk.map` — combinators over the `Map` kernel (`empty`, `insert`, `get`,
252/// `keys`, `length`). `fromList` is deliberately absent: Bynk has no pair
253/// type to spell a `List[(K, V)]` with, so map construction is `Map.empty()`
254/// + `insert` (revisit with tuples or generic records).
255pub const BYNK_MAP_SRC: &str = include_str!("../lib/core/bynk.map.bynk");
256
257/// Inside the reserved `bynk.*` prefix; injected when `uses`-imported.
258pub const STRING_UNIT: &str = "bynk.string";
259
260/// `bynk.string` — Bynk-written helpers over the v0.22a string kernel
261/// (`concat`, the `List` `fold`, and the `Option` kernel methods). The
262/// kernel itself is compiler built-in (ADR 0046); only derived helpers
263/// live here. `join` folds to `Option[String]` so empty-string *elements*
264/// are joined faithfully (a bare `""` accumulator could not tell "nothing
265/// yet" from "first element was empty").
266pub const BYNK_STRING_SRC: &str = include_str!("../lib/core/bynk.string.bynk");
267
268/// Inside the reserved `bynk.*` prefix; injected when `uses`-imported.
269pub const URL_UNIT: &str = "bynk.url";
270
271/// `bynk.url` (standard-library K2, #2594) — a `Url` record with RFC 3986
272/// `parse`/`format` and query-string helpers, written in Bynk over the
273/// `String` kernel. Only percent-encoding is kernel (`percentEncode`,
274/// `percentDecode`): it needs a string's UTF-8 bytes. `Url` is a record here,
275/// not a base type, because a base type's name is a lexer token, and `Url`
276/// as a keyword would break every user `type Url`.
277pub const BYNK_URL_SRC: &str = include_str!("../lib/core/bynk.url.bynk");
278
279pub const SET_UNIT: &str = "bynk.set";
280
281/// `bynk.set` (standard-library K6a, #2596) — Bynk-written combinators over
282/// the built-in `Set` kernel (`length`, `contains`, `insert`, `remove`,
283/// `toList`, `Set.of`): `union`, `intersect`, `difference`, `isSubsetOf`,
284/// `filter`, `map`.
285pub const BYNK_SET_SRC: &str = include_str!("../lib/core/bynk.set.bynk");
286
287/// Inside the reserved `bynk.*` prefix; injected when `uses`-imported by
288/// application code (a message-bundle commons, ADR 0272) — never directly by
289/// the `bynk` adapter itself any more (see [`LOCALE_TYPES_UNIT`]).
290pub const LOCALE_UNIT: &str = "bynk.locale";
291
292/// `bynk.locale` — the bundle-free `render`/`renderArg` helpers and the
293/// `message`/`withText`/`withWhole`/`withNum`/`withMoment` builder API
294/// (slice 1: `render` formats `code` plus a deterministic sorted-by-key
295/// rendering of `params`; no lookup, no locale-dependent behaviour). `uses
296/// bynk.locale.types` for the types its own signatures name.
297pub const BYNK_LOCALE_SRC: &str = include_str!("../lib/core/bynk.locale.bynk");
298
299/// Inside the reserved `bynk.*` prefix; injected when `uses`-imported. Also
300/// `uses`-imported by the `bynk` adapter itself, to give `capability Locale`'s
301/// `current() -> Effect[LocaleTag]` a type to name (an adapter may `uses` a
302/// commons; a commons cannot in turn reference an adapter). Split out of
303/// `bynk.locale` (locale-negotiation-slice-2 follow-up, #886) specifically so
304/// a context can reach `LocaleTag` without also pulling in `bynk.locale`'s
305/// own `render` — which previously collided with a message-bundle commons's
306/// own synthesised `render` (ADR 0272) the moment a context needed both.
307pub const LOCALE_TYPES_UNIT: &str = "bynk.locale.types";
308
309/// `bynk.locale.types` — `LocaleTag`, `MessageArg`, `Message`: a
310/// dependency-free leaf (no `uses` of its own) so any consumer, including
311/// the `bynk` adapter itself, can reach these types without also reaching
312/// `bynk.locale`'s value-level API.
313pub const BYNK_LOCALE_TYPES_SRC: &str = include_str!("../lib/core/bynk.locale.types.bynk");
314
315/// The reserved `bynk` conformance-surface adapter (env-free core). It has no
316/// `binding` clause — the toolchain supplies one per platform (see
317/// [`Platform::bynk_binding_source`]).
318pub const BYNK_ADAPTER_SRC: &str = include_str!("../lib/core/bynk.bynk");
319
320/// The Cloudflare binding for the `bynk` surface. Implements the canonical
321/// provider symbols against the platform host API. The refined `Uuid` is built
322/// through its emitted validating `.of` constructor (§4.4), treating the
323/// unreachable `Err` as a bug rather than trusting the value away.
324const BYNK_CLOUDFLARE_BINDING: &str = include_str!("../lib/core/bindings/bynk-cloudflare.ts");
325
326/// The Node (≥ the toolchain's `NODE_MAJOR_FLOOR`, in `bynk-emit`) binding for
327/// the `bynk` surface (v0.18). Deliberately
328/// near-identical to the cloudflare binding: `Date.now`, the global
329/// `crypto`/`fetch`, and `console` are the same host API on both runtimes —
330/// which is exactly the ambient-surface portability claim (spec §4.2). The
331/// `SecretsProvider` reads `process.env` through the same `globalThis` probe
332/// (never bare `process`, which would demand @types/node at the tsc gate).
333const BYNK_NODE_BINDING: &str = include_str!("../lib/core/bindings/bynk-node.ts");
334
335/// The Browser binding for the `bynk` surface (in-browser track, slice 1). Tier-3:
336/// the same capability surface over Web APIs. `Clock`/`Random`/`Logger` are
337/// byte-identical to the Node binding (`Date.now`, Web Crypto `crypto.randomUUID`,
338/// `console` — all Web standards); the two substitutions are the playground safety
339/// boundary — `Fetch` is **withheld** (throws; no outbound egress from the
340/// playground origin) and `Secrets` is **unavailable** (throws; a browser has no
341/// secret store), both failing loudly rather than silently degrading.
342const BYNK_BROWSER_BINDING: &str = include_str!("../lib/core/bindings/bynk-browser.ts");
343
344/// The first-party Cloudflare platform adapter (v0.19): the platform's real
345/// infrastructure capabilities, as they are — no portable intersection
346/// (decision 0016). The v0.19 surface was the minimal, collection-free `Kv`
347/// (decision 0023); v0.23 adds the `list` drain and `putTtl` (0050/0051);
348/// structured values are v0.22-codec composition, and `Queue` remains its
349/// own future increment. Like the `bynk` surface it has no `binding`
350/// clause — the toolchain supplies the binding.
351pub const CLOUDFLARE_ADAPTER_SRC: &str = include_str!("../lib/cloudflare/bynk.cloudflare.bynk");
352
353/// Every first-party `.bynk` source, paired with its unit name — the single
354/// list every consumer iterates: hover (`describe_firstparty_symbol`),
355/// completion (`EMBEDDED_UNITS`), and the parse guard
356/// (`every_first_party_source_parses`). Before this list each consumer kept its
357/// own hand-maintained copy, and `bynk.locale`/`bynk.locale.types` were added to
358/// none of them — so the whole locale surface hovered as nothing and was absent
359/// from completion (#901).
360///
361/// A view over [`UNITS`], in its order, which is observable: hover takes the
362/// first source declaring a name, and completion lists units in this order. The
363/// `firstparty_sources_cover_every_src_const` drift guard
364/// (`bynk-tests/tests/firstparty_sources.rs`) fails if a `*_SRC` const is left out of
365/// [`UNITS`].
366pub const FIRSTPARTY_SOURCES: &[(&str, &str)] = &SOURCES;
367
368/// [`FIRSTPARTY_SOURCES`]' backing array, built from [`UNITS`] at compile time.
369const SOURCES: [(&str, &str); UNITS.len()] = {
370    let mut out = [("", ""); UNITS.len()];
371    let mut i = 0;
372    while i < UNITS.len() {
373        out[i] = (UNITS[i].name, UNITS[i].source);
374        i += 1;
375    }
376    out
377};
378
379/// The output path of the Cloudflare platform adapter's binding module,
380/// beside the adapter's emitted `bynk/cloudflare.ts` (distinct from the
381/// `bynk` *surface*'s per-platform `bynk-cloudflare.ts`).
382pub const CLOUDFLARE_BINDING_FILENAME: &str = "bynk/cloudflare.binding.ts";
383
384/// The Cloudflare platform adapter's binding. `WorkersKv` reads the Worker
385/// `env` explicitly (decision 0025): KV namespaces exist only on `env` —
386/// there is no `globalThis` path — so a missing binding is a clear runtime
387/// error rather than a silent fallback.
388const CLOUDFLARE_BINDING: &str = include_str!("../lib/cloudflare/cloudflare.binding.ts");
389
390/// The toolchain-supplied binding for the Cloudflare platform adapter.
391pub fn cloudflare_binding_source() -> &'static str {
392    CLOUDFLARE_BINDING
393}
394
395/// The unit name of the first-party cryptography adapter (standard-library K4,
396/// D5/D6): a flat sibling of `bynk`, platform-free, with a binding per platform.
397pub const CRYPTO_UNIT: &str = "bynk.crypto";
398
399/// `bynk.crypto` — digests, HMAC, constant-time comparison, and signing and
400/// verification with imported keys, as `Effect`s over Web Crypto.
401pub const BYNK_CRYPTO_SRC: &str = include_str!("../lib/crypto/bynk.crypto.bynk");
402
403/// The Cloudflare Workers binding for `bynk.crypto`. The three differ only where
404/// the platforms do: the constant-time comparison primitive.
405const CRYPTO_CLOUDFLARE_BINDING: &str = include_str!("../lib/crypto/crypto-cloudflare.binding.ts");
406
407/// The Node binding for `bynk.crypto`.
408const CRYPTO_NODE_BINDING: &str = include_str!("../lib/crypto/crypto-node.binding.ts");
409
410/// The browser binding for `bynk.crypto`. Web Crypto exists only in a secure
411/// context (R14.5): outside one it throws, loudly, rather than degrade.
412const CRYPTO_BROWSER_BINDING: &str = include_str!("../lib/crypto/crypto-browser.binding.ts");
413
414/// The unit name of the toolchain's test-support adapter (#3458): an in-memory
415/// store whose reads are typed, which exercises the call-site decode of a
416/// first-party capability reply. Experimental and not part of the language.
417pub const TESTING_UNIT: &str = "bynk.testing";
418
419/// `bynk.testing`, the typed-read test support. Compiled in only with the
420/// `test-support` feature, which the toolchain's own test corpus enables: a
421/// released toolchain does not contain the unit.
422#[cfg(feature = "test-support")]
423pub const BYNK_TESTING_SRC: &str = include_str!("../lib/testing/bynk.testing.bynk");
424
425/// The output path of `bynk.testing`'s binding, beside its emitted `bynk/testing.ts`.
426pub const TESTING_BINDING_FILENAME: &str = "bynk/testing.binding.ts";
427
428/// The binding for `bynk.testing`: platform-free, an in-memory map.
429#[cfg(feature = "test-support")]
430const TESTING_BINDING: &str = include_str!("../lib/testing/testing.binding.ts");
431
432/// The opaque key types `bynk.crypto` exports. A value of one holds a
433/// non-extractable platform key, so it is never stored, persisted, logged or
434/// sent (`bynk.types.key_at_boundary`), as a `Stream` is not. The checker finds
435/// them by the unit's reserved span file, so a user type of the same name is not
436/// mistaken for one.
437pub const CRYPTO_KEY_TYPES: &[&str] = &["SigningKey", "VerifyKey"];
438
439/// What a first-party unit is, and so how a project brings it in: an adapter is
440/// injected when a unit `consumes` it, a commons when a unit `uses` it. Local to
441/// this crate, which has no dependencies; `bynk-check` maps it onto its own
442/// unit kind.
443#[derive(Debug, Clone, Copy, PartialEq, Eq)]
444pub enum UnitKind {
445    Adapter,
446    Commons,
447}
448
449/// The TypeScript binding the toolchain supplies for a first-party unit.
450#[derive(Debug, Clone, Copy, PartialEq, Eq)]
451pub enum Binding {
452    /// A commons: Bynk-written, so nothing to bind.
453    None,
454    /// One binding per [`Platform`] ([`Platform::bynk_binding_filename`] and
455    /// [`Platform::bynk_binding_source`]): the portable `bynk` surface.
456    PerPlatform,
457    /// A single binding, for a platform-native adapter that runs only on its own
458    /// platform (the platform lock rejects every other `--platform`).
459    Fixed {
460        filename: &'static str,
461        source: &'static str,
462    },
463    /// One binding file per [`Platform`], each with its own name and source, for a
464    /// platform-free unit whose binding differs where the platforms do
465    /// (`bynk.crypto`). [`Binding::PerPlatform`] stays the `bynk` surface's.
466    PerPlatformFiles {
467        cloudflare: (&'static str, &'static str),
468        node: (&'static str, &'static str),
469        browser: (&'static str, &'static str),
470    },
471}
472
473/// One first-party unit, as data (standard-library track, S1 #1945). Adding a
474/// unit to the standard library is an entry in [`UNITS`] plus its files; the
475/// checker's injection reads this table and needs no change.
476#[derive(Debug, Clone, Copy, PartialEq, Eq)]
477pub struct Unit {
478    /// The unit's dotted name, inside the reserved `bynk.*` prefix.
479    pub name: &'static str,
480    /// Whether a project `consumes` it (an adapter) or `uses` it (a commons).
481    pub kind: UnitKind,
482    /// The synthetic path the injected unit is parsed under. Diagnostics and
483    /// emission name the unit by it, so it never changes.
484    pub identity_path: &'static str,
485    /// The unit's `.bynk` source.
486    pub source: &'static str,
487    /// The binding the toolchain supplies for it.
488    pub binding: Binding,
489    /// Its permanent `ExprId` block: the checker parses it at
490    /// `FIRSTPARTY_ID_BASE + id_block * FIRSTPARTY_ID_BLOCK`, and injects units
491    /// in ascending `id_block` order. A block is never reused or moved, so ids
492    /// and injection order stay stable as units are added; a new unit takes the
493    /// next free block.
494    pub id_block: u32,
495    /// The platform that consuming it locks a deployment unit to (decision
496    /// 0024), if it is platform-native.
497    pub platform: Option<Platform>,
498    /// The provider classes whose constructor takes the Worker `env` (decisions
499    /// 0021/0025).
500    pub env_providers: &'static [&'static str],
501    /// The unit's stability (track D2, S3 #1963): a stable item is under the
502    /// 1.0 promise, an experimental one carries none and needs an explicit
503    /// `[unstable] allow` to use. Required, so no entry is added without a
504    /// choice.
505    pub stability: Stability,
506    /// Items inside a stable unit that are experimental, as paths relative to
507    /// the unit: an exported item (`"Kv"`) or a capability operation
508    /// (`"Kv.list"`). An experimental item makes its operations experimental.
509    pub experimental: &'static [&'static str],
510    /// The exported enums that may gain variants in a minor release, so a
511    /// `match` covering one needs a wildcard (track §11 Q5).
512    pub extensible: &'static [&'static str],
513    /// The capabilities a context may declare named instances of with
514    /// `capability Sessions = Kv` (S4a, #1966): each its own platform resource.
515    /// A capability not listed (Workers AI's single `[ai]` binding, say) has no
516    /// instances.
517    pub instantiable: &'static [Instantiable],
518    /// The capabilities bound once per Worker (#3300, track D3 rule 2): used
519    /// bare (`given Version`), never derived (`capability V = Version` is
520    /// `bynk.capability.base_not_instantiable`, as for any capability not in
521    /// [`Unit::instantiable`]), and bound only in a Worker whose closure
522    /// reaches one.
523    pub singletons: &'static [Singleton],
524}
525
526/// A platform capability with exactly one binding per Worker (#3300): Version
527/// metadata's `[version_metadata]` and Workers AI's `[ai]`.
528#[derive(Debug, Clone, Copy, PartialEq, Eq)]
529pub struct Singleton {
530    /// The capability's name in its unit (`Version`).
531    pub capability: &'static str,
532    /// Its fixed Worker binding name, the one `env` field its provider reads.
533    pub binding: &'static str,
534    /// The `wrangler.toml` table that declares it (`version_metadata`), a
535    /// plain table holding only `binding`.
536    pub wrangler_table: &'static str,
537}
538
539/// A capability a context may declare instances of (S4a, #1966, track D3).
540#[derive(Debug, Clone, Copy, PartialEq, Eq)]
541pub struct Instantiable {
542    /// The capability's name in its unit (`Kv`).
543    pub capability: &'static str,
544    /// The prefix of each instance's Worker binding name: `KV` makes
545    /// `capability Sessions = Kv` bind as `KV_SESSIONS`.
546    pub binding_prefix: &'static str,
547    /// The creation options (`@name(…)`) an instance may carry, each with the
548    /// one literal its value is (standard-library P3, #2342: `@worker("…")`
549    /// takes a string, `@limit(100)` an `Int`, `@period(60.seconds)` a
550    /// `Duration`); any other is refused. Empty when the kind takes none yet.
551    pub options: &'static [(&'static str, OptionKind)],
552    /// The options every instance must carry (interop I5, #1972): a
553    /// `Service` names the Worker it reaches, so it has no default. A subset
554    /// of [`Instantiable::options`].
555    pub required: &'static [&'static str],
556    /// Whether the base capability is usable bare, through `given Kv`, as
557    /// well as through instances. `false` for a kind whose every use needs an
558    /// option: a bare `Service` would name no Worker.
559    pub bare: bool,
560    /// Whether the resource behind an instance belongs to the account, not to
561    /// the build (#3301, track D3): `bynk deploy` *links* to it (finds it,
562    /// records what it found, and fails when it is missing) and never creates
563    /// it. `StoredSecret` is the first such kind; a foreign `Service` Worker
564    /// behaves the same by its own code until it moves onto this flag.
565    pub linked: bool,
566}
567
568impl Instantiable {
569    /// The kind of literal option `name` takes, or `None` when it is not one
570    /// of this kind's options.
571    pub fn option_kind(&self, name: &str) -> Option<OptionKind> {
572        self.options
573            .iter()
574            .find(|(o, _)| *o == name)
575            .map(|(_, k)| *k)
576    }
577
578    /// The names of this kind's options, in declaration order.
579    pub fn option_names(&self) -> impl Iterator<Item = &'static str> + '_ {
580        self.options.iter().map(|(o, _)| *o)
581    }
582}
583
584/// The literal an instance option takes (standard-library P3, #2342).
585#[derive(Debug, Clone, Copy, PartialEq, Eq)]
586pub enum OptionKind {
587    /// A string literal: `@worker("legacy-billing")`.
588    Str,
589    /// A positive `Int` literal: `@limit(100)`.
590    PositiveInt,
591    /// A `Duration` literal: `@period(60.seconds)`.
592    Duration,
593    /// A list literal of string literals: `@allowedSenders(["[email protected]"])`
594    /// (#3302).
595    StrList,
596}
597
598/// The Worker binding prefix of a `Service` instance (interop I5, #1972):
599/// `capability Billing = Service @worker("legacy-billing")` binds as
600/// `SERVICE_BILLING`, a `[[services]]` entry naming `legacy-billing`.
601pub const SERVICE_BINDING_PREFIX: &str = "SERVICE";
602
603/// The option of a `Service` instance that names the Worker it reaches.
604/// `worker`, not D4's `service`: `service` is a keyword, so `@service(…)`
605/// does not parse, and widening the annotation grammar is language work
606/// (ADR 0023).
607pub const SERVICE_WORKER_OPTION: &str = "worker";
608
609/// The Worker binding prefix of an `R2` instance (standard-library P5,
610/// #2323): `capability Archives = R2` binds as `R2_ARCHIVES`, an
611/// `[[r2_buckets]]` entry.
612pub const R2_BINDING_PREFIX: &str = "R2";
613
614/// The one creation option of an `R2` instance: the bucket's jurisdiction.
615pub const R2_JURISDICTION_OPTION: &str = "jurisdiction";
616
617/// The jurisdictions an `R2` bucket may be pinned to, as `@jurisdiction(…)`
618/// takes them and `wrangler r2 bucket create --jurisdiction` accepts them.
619pub const R2_JURISDICTIONS: &[&str] = &["eu", "fedramp"];
620
621/// The Worker binding prefix of a `RateLimit` instance (standard-library P3,
622/// #2342): `capability LoginLimit = RateLimit @limit(100) @period(60.seconds)`
623/// binds as `RATELIMIT_LOGIN_LIMIT`, a `[[ratelimits]]` entry.
624pub const RATELIMIT_BINDING_PREFIX: &str = "RATELIMIT";
625
626/// A `RateLimit` instance's count: the calls per key allowed in one period.
627pub const RATELIMIT_LIMIT_OPTION: &str = "limit";
628
629/// A `RateLimit` instance's window.
630pub const RATELIMIT_PERIOD_OPTION: &str = "period";
631
632/// The windows the Workers Rate Limiting binding offers, in seconds.
633pub const RATELIMIT_PERIODS: &[i64] = &[10, 60];
634
635/// The Worker binding prefix of a `Queue` instance (standard-library P2,
636/// #2578): `capability OrderEvents = Queue @name("order-events")` binds as
637/// `QUEUE_ORDER_EVENTS`, a `[[queues.producers]]` entry.
638pub const QUEUE_BINDING_PREFIX: &str = "QUEUE";
639
640/// The option of a `Queue` instance that names the queue it sends to.
641/// `name`, not the track's `queue`: `queue` is a keyword, so `@queue(…)` does
642/// not parse (as `Service`'s `@worker`, ADR 0023).
643pub const QUEUE_NAME_OPTION: &str = "name";
644
645/// The Worker binding prefix of an `Analytics` instance (standard-library
646/// P3b, #2582): `capability Signups = Analytics` binds as
647/// `ANALYTICS_SIGNUPS`, an `[[analytics_engine_datasets]]` entry. It takes no
648/// options: `bynk deploy` derives the dataset's name (track A12).
649pub const ANALYTICS_BINDING_PREFIX: &str = "ANALYTICS";
650
651/// The Worker binding prefix of a `D1` instance (standard-library P4a,
652/// #2602): `capability Orders = D1` binds as `D1_ORDERS`, a
653/// `[[d1_databases]]` entry whose `database_id` `bynk deploy` mints.
654pub const D1_BINDING_PREFIX: &str = "D1";
655
656/// The Worker binding prefix of a `StoredSecret` instance (#3301):
657/// `capability StripeKey = StoredSecret @store("payments") @secret("stripe-live")`
658/// binds as `SECRET_STRIPE_KEY`, a `[[secrets_store_secrets]]` entry.
659pub const STORED_SECRET_BINDING_PREFIX: &str = "SECRET";
660
661/// The option of a `StoredSecret` instance that names its Secrets Store, by
662/// the name the account gives it; `bynk deploy` resolves the id (#3301
663/// Decision C), so an id never appears in source.
664pub const STORED_SECRET_STORE_OPTION: &str = "store";
665
666/// The option of a `StoredSecret` instance that names the secret in its store.
667pub const STORED_SECRET_SECRET_OPTION: &str = "secret";
668
669/// The Worker binding prefix of an `AiSearch` instance (#3480):
670/// `capability Kb = AiSearch @instance("support-docs")` binds as
671/// `AI_SEARCH_KB`, an `[[ai_search]]` entry.
672pub const AI_SEARCH_BINDING_PREFIX: &str = "AI_SEARCH";
673
674/// The option of an `AiSearch` instance that names the instance, by the name
675/// the account gives it. It is used as written in every environment, and
676/// `bynk deploy` links to it and never creates it (#3480 Decisions A and B).
677pub const AI_SEARCH_INSTANCE_OPTION: &str = "instance";
678
679/// The Worker binding prefix of an `MtlsCertificate` instance (#3513 A):
680/// `capability Backend = MtlsCertificate @certificate("acme-client")` binds as
681/// `MTLS_BACKEND`, an `[[mtls_certificates]]` entry.
682pub const MTLS_BINDING_PREFIX: &str = "MTLS";
683
684/// The option of an `MtlsCertificate` instance that names the account's client
685/// certificate, by the name it was uploaded under. It is used as written in every
686/// environment, and `bynk deploy` links to it and never uploads it: a certificate's
687/// private key never passes through Bynk (#3513 A Decisions A1 and A2).
688pub const MTLS_CERTIFICATE_OPTION: &str = "certificate";
689
690/// The Worker binding prefix of an `Email` instance (#3302):
691/// `capability Mail = Email @allowedSenders(["[email protected]"])` binds as
692/// `EMAIL_MAIL`, a `[[send_email]]` entry (keyed by `name`).
693pub const EMAIL_BINDING_PREFIX: &str = "EMAIL";
694
695/// The Worker binding prefix of a `Postgres` instance (Hyperdrive H1, #3318,
696/// ADR 0799 D): `capability Main = Postgres` binds as `HYPERDRIVE_MAIN`, a
697/// `[[hyperdrive]]` entry whose `id` `bynk deploy` makes or adopts (#3319).
698pub const POSTGRES_BINDING_PREFIX: &str = "HYPERDRIVE";
699
700/// The Worker binding prefix of a `MySql` instance (Hyperdrive H5, #3322, ADR
701/// 0799 D): the same as `Postgres`'s, since both are a `[[hyperdrive]]` entry
702/// and the deploy path is one. `capability Legacy = MySql` binds as
703/// `HYPERDRIVE_LEGACY`.
704pub const MYSQL_BINDING_PREFIX: &str = POSTGRES_BINDING_PREFIX;
705
706/// The one option of a `MySql` instance: the TLS mode of the connection from
707/// Hyperdrive to the database (#3322, DECISION B).
708pub const MYSQL_TLS_OPTION: &str = "tls";
709
710/// The TLS modes `@tls("…")` takes, each with the `sslmode` Cloudflare's
711/// Hyperdrive API spells it as. `required` is the default and needs no CA
712/// certificate; the two `verify` modes check the server's certificate against a
713/// CA certificate the account holds.
714pub const MYSQL_TLS_MODES: &[(&str, &str)] = &[
715    ("required", "REQUIRED"),
716    ("verify-ca", "VERIFY_CA"),
717    ("verify-identity", "VERIFY_IDENTITY"),
718];
719
720/// The option of an `Email` instance that pins every message to one recipient
721/// (`destination_address`).
722pub const EMAIL_TO_OPTION: &str = "to";
723
724/// The option of an `Email` instance that lists the recipients it may send to
725/// (`allowed_destination_addresses`).
726pub const EMAIL_ALLOWED_RECIPIENTS_OPTION: &str = "allowedRecipients";
727
728/// The option of an `Email` instance that lists the senders it may send as
729/// (`allowed_sender_addresses`); `bynk deploy` checks each address's domain is
730/// verified for sending on the account (#3302 Decision D).
731pub const EMAIL_ALLOWED_SENDERS_OPTION: &str = "allowedSenders";
732
733/// The Worker binding prefix of a `Vectorize` instance (#3479): `capability
734/// Docs = Vectorize @dimensions(768) @metric("cosine")` binds as
735/// `VECTORIZE_DOCS`, a `[[vectorize]]` entry naming the index.
736pub const VECTORIZE_BINDING_PREFIX: &str = "VECTORIZE";
737
738/// A `Vectorize` instance's vector length. Fixed when the index is created
739/// and never changeable after, so the declaration states it (#3479 A).
740pub const VECTORIZE_DIMENSIONS_OPTION: &str = "dimensions";
741
742/// A `Vectorize` instance's distance metric, one of [`VECTORIZE_METRICS`].
743pub const VECTORIZE_METRIC_OPTION: &str = "metric";
744
745/// The metadata properties of a `Vectorize` instance a query may filter on,
746/// each written `name:type` (#3479 C).
747pub const VECTORIZE_INDEXED_OPTION: &str = "indexed";
748
749/// The distance metrics an index is created with.
750pub const VECTORIZE_METRICS: &[&str] = &["cosine", "euclidean", "dot-product"];
751
752/// The types a metadata index holds.
753pub const VECTORIZE_INDEXED_TYPES: &[&str] = &["string", "number", "boolean"];
754
755/// The most metadata indexes one index carries.
756pub const VECTORIZE_MAX_INDEXED: usize = 10;
757
758/// The fewest dimensions a Cloudflare Vectorize index accepts: creating one with
759/// fewer fails with `Dimensions must be in range: [32, 1536]`. `@dimensions`
760/// below it is refused at compile time, so the failure is not left for a deploy.
761pub const VECTORIZE_MIN_DIMENSIONS: i64 = 32;
762
763/// The most dimensions a Cloudflare Vectorize vector can have (its published
764/// limit); `@dimensions` above it is refused at compile time.
765pub const VECTORIZE_MAX_DIMENSIONS: i64 = 1536;
766
767/// The Worker binding prefix of a `Container` instance (#3477): `capability
768/// Renderer = Container @build("containers/renderer") @port(8080)` binds as
769/// `CONTAINER_RENDERER`, a Durable Object namespace whose class (derived from
770/// the capability's name) runs the container.
771pub const CONTAINER_BINDING_PREFIX: &str = "CONTAINER";
772
773/// A `Container` instance's build context: a project-relative directory that
774/// holds a `Dockerfile` (#3477 B).
775pub const CONTAINER_BUILD_OPTION: &str = "build";
776
777/// The one TCP port the container's HTTP server listens on (#3477 D).
778pub const CONTAINER_PORT_OPTION: &str = "port";
779
780/// How long an idle container runs before the platform stops it, applied with
781/// `setInactivityTimeout` on every start (#3477 E).
782pub const CONTAINER_SLEEP_AFTER_OPTION: &str = "sleepAfter";
783
784/// The instance type the container starts with, one of
785/// [`CONTAINER_INSTANCE_TYPES`], passed as `instance` to `start()` (#3477 E).
786pub const CONTAINER_INSTANCE_TYPE_OPTION: &str = "instanceType";
787
788/// The names of the Worker secrets passed to the container's process at start
789/// (#3477 J).
790pub const CONTAINER_FORWARD_OPTION: &str = "forward";
791
792/// The instance types a `Container` can start with under the `durable_object`
793/// scheduling policy. There is no `basic` under it.
794pub const CONTAINER_INSTANCE_TYPES: &[&str] = &[
795    "lite",
796    "standard-1",
797    "standard-2",
798    "standard-3",
799    "standard-4",
800];
801
802/// The longest inactivity timeout the platform accepts, in seconds (6 hours).
803pub const CONTAINER_MAX_SLEEP_AFTER_SECONDS: i64 = 6 * 60 * 60;
804
805/// The most Worker secrets one container forwards.
806pub const CONTAINER_MAX_FORWARD: usize = 32;
807
808/// The Worker binding of the `Version` capability (#3300): Cloudflare's
809/// Version metadata binding, `[version_metadata] binding = "CF_VERSION_METADATA"`,
810/// the name Cloudflare's own documentation uses.
811pub const VERSION_BINDING_NAME: &str = "CF_VERSION_METADATA";
812
813/// The Worker binding of the `Ai` capability (#3478): Workers AI's binding,
814/// `[ai] binding = "AI"`, the name Cloudflare's own documentation uses.
815pub const AI_BINDING_NAME: &str = "AI";
816
817/// The Worker binding of the `Images` capability (#3515): Cloudflare Images'
818/// binding, `[images] binding = "IMAGES"`, the name Cloudflare's own
819/// documentation uses.
820pub const IMAGES_BINDING_NAME: &str = "IMAGES";
821/// The Worker binding of the `AnalyticsSql` capability (#3513 B): Cloudflare's Analytics SQL
822/// binding, `[analytics] binding = "CF_ANALYTICS_SQL"`. Cloudflare's own documentation names it
823/// `ANALYTICS_SQL`; the `CF_` prefix keeps it clear of an `Analytics` instance's binding
824/// (`capability Sql = Analytics` would bind as `ANALYTICS_SQL`).
825pub const ANALYTICS_SQL_BINDING_NAME: &str = "CF_ANALYTICS_SQL";
826
827/// The prefix an `EdgeCache` instance's binding name would carry (first-party
828/// registry L7, #2414). Workers Cache is a Worker-wide `[cache]` setting with
829/// no `env` binding, so the name is never emitted: the instance is built from
830/// the entry's `ctx` instead.
831pub const EDGE_CACHE_BINDING_PREFIX: &str = "EDGE_CACHE";
832
833/// Whether a first-party item is under the 1.0 promise (track D2).
834#[derive(Debug, Clone, Copy, PartialEq, Eq)]
835pub enum Stability {
836    /// Under the promise: a stable L0/L1 item changes only at a major release; a
837    /// stable L2/L3 item may gain operations and, if extensible, variants.
838    Stable,
839    /// No promise: it may change or disappear in any release, and using it needs
840    /// an `[unstable] allow` entry in `bynk.toml`.
841    Experimental,
842}
843
844impl Unit {
845    /// The binding module to emit for this unit on `platform`, as
846    /// `(output path, source)`, or `None` for a commons.
847    pub fn binding_for(&self, platform: Platform) -> Option<(&'static str, &'static str)> {
848        match self.binding {
849            Binding::None => None,
850            Binding::PerPlatform => Some((
851                platform.bynk_binding_filename(),
852                platform.bynk_binding_source(),
853            )),
854            Binding::Fixed { filename, source } => Some((filename, source)),
855            Binding::PerPlatformFiles {
856                cloudflare,
857                node,
858                browser,
859            } => Some(match platform {
860                Platform::Cloudflare => cloudflare,
861                Platform::Node => node,
862                Platform::Browser => browser,
863            }),
864        }
865    }
866}
867
868/// The standard library's first-party units. Dependencies between them are not
869/// listed here: they are the `uses`/`consumes` lines of each unit's own source,
870/// which the checker follows when it injects. The table's order is
871/// [`FIRSTPARTY_SOURCES`]' order; injection follows [`Unit::id_block`].
872pub const UNITS: &[Unit] = &[
873    Unit {
874        name: BYNK_UNIT,
875        kind: UnitKind::Adapter,
876        identity_path: "bynk.bynk",
877        source: BYNK_ADAPTER_SRC,
878        binding: Binding::PerPlatform,
879        id_block: 0,
880        platform: None,
881        env_providers: &["SecretsProvider", "IdempotencyProvider"],
882        stability: Stability::Stable,
883        // K5a (#2586), K5b (#2604), K5c (#2627): the new operations, until a
884        // service has used them.
885        experimental: &[
886            "Fetch.sendWith",
887            "Fetch.receiveBytes",
888            "Fetch.sendBytes",
889            "Fetch.receiveStream",
890            "Fetch.sendStream",
891            "Logger.log",
892        ],
893        extensible: &["FetchError", "Method", "Redirect"],
894        instantiable: &[],
895        singletons: &[],
896    },
897    Unit {
898        name: CLOUDFLARE_UNIT,
899        kind: UnitKind::Adapter,
900        identity_path: "bynk/cloudflare.bynk",
901        source: CLOUDFLARE_ADAPTER_SRC,
902        binding: Binding::Fixed {
903            filename: CLOUDFLARE_BINDING_FILENAME,
904            source: CLOUDFLARE_BINDING,
905        },
906        id_block: 1,
907        platform: Some(Platform::Cloudflare),
908        env_providers: &[
909            "WorkersKv",
910            "WorkersService",
911            "WorkersR2",
912            "WorkersRateLimit",
913            "WorkersQueue",
914            "WorkersAnalytics",
915            "WorkersD1",
916            "WorkersVersion",
917            "WorkersAi",
918            "WorkersImages",
919            "WorkersStoredSecret",
920            "WorkersEmail",
921            "WorkersPostgres",
922            "WorkersMySql",
923            "WorkersVectorize",
924            "WorkersContainer",
925            "WorkersAiSearch",
926            "WorkersMtls",
927            "WorkersAnalyticsSql",
928        ],
929        stability: Stability::Stable,
930        // Interop I5 (#1972): a Service Binding to a non-Bynk Worker is new
931        // and its surface is untyped, so it lands outside the 1.0 promise.
932        // P5 (#2323): R2 ships experimental until the first-party registry has
933        // run on it (#2308 R6); its conditions are extensible meanwhile.
934        // P3 (#2342): RateLimit too, until the registry has run on it.
935        // L7 (#2414): EdgeCache likewise.
936        // P2 (#2578): Queue too, until a first-party service has sent on it.
937        // P3b (#2582): Analytics too, until a first-party service writes to it.
938        // Version metadata (#3300) too, until a first-party service reports it.
939        // Workers AI (#3478) too, until a first-party service has called a model.
940        // Cloudflare Images (#3515) too, until a first-party service has resized one.
941        // mTLS certificates (#3513 A) too, until a first-party service has called an mTLS origin.
942        // Secrets Store (#3301) too, until a first-party service reads one.
943        // Outbound email (#3302) too: Email Service carries no GA label.
944        // Hyperdrive H1 (#3318): `Postgres` too, until a first-party service
945        // has run on it; its records are stable and `PgError` is extensible.
946        // `request.cf` (#3513 C): `RequestCf` too, until a first-party service reads it.
947        // P1 (#2590): the new operations of the stable `Kv`, until a service
948        // has used them.
949        // D1 shipped experimental (P4a, #2602) and graduated in P4d (#2652)
950        // once its migrations and call-site shape were settled (P4b, P4c),
951        // by its own gate rather than the registry's.
952        experimental: &[
953            "Service",
954            "R2",
955            "RateLimit",
956            "EdgeCache",
957            "Queue",
958            "Analytics",
959            "Version",
960            "Ai",
961            "Images",
962            "StoredSecret",
963            "Email",
964            "Postgres",
965            "MySql",
966            "Vectorize",
967            "Container",
968            "AiSearch",
969            "MtlsCertificate",
970            "AnalyticsSql",
971            "RequestCf",
972            "Kv.getWith",
973            "Kv.putWith",
974            "Kv.getBytes",
975            "Kv.putBytes",
976            "Kv.listPage",
977        ],
978        extensible: &[
979            "R2Condition",
980            "KvExpiration",
981            "SqlError",
982            "EmailError",
983            "AiError",
984            "ImageFormat",
985            "ImageFit",
986            "ImagesError",
987            "AnalyticsSqlError",
988            "ChatRole",
989            "PgError",
990            "MySqlError",
991            "VectorError",
992            "ContainerError",
993            "SearchError",
994        ],
995        instantiable: &[
996            Instantiable {
997                capability: "Kv",
998                binding_prefix: KV_BINDING_NAME,
999                options: &[],
1000                required: &[],
1001                bare: true,
1002                linked: false,
1003            },
1004            Instantiable {
1005                capability: "Service",
1006                binding_prefix: SERVICE_BINDING_PREFIX,
1007                options: &[(SERVICE_WORKER_OPTION, OptionKind::Str)],
1008                required: &[SERVICE_WORKER_OPTION],
1009                bare: false,
1010                linked: false,
1011            },
1012            Instantiable {
1013                capability: "R2",
1014                binding_prefix: R2_BINDING_PREFIX,
1015                options: &[(R2_JURISDICTION_OPTION, OptionKind::Str)],
1016                required: &[],
1017                bare: false,
1018                linked: false,
1019            },
1020            Instantiable {
1021                capability: "RateLimit",
1022                binding_prefix: RATELIMIT_BINDING_PREFIX,
1023                options: &[
1024                    (RATELIMIT_LIMIT_OPTION, OptionKind::PositiveInt),
1025                    (RATELIMIT_PERIOD_OPTION, OptionKind::Duration),
1026                ],
1027                required: &[RATELIMIT_LIMIT_OPTION, RATELIMIT_PERIOD_OPTION],
1028                bare: false,
1029                linked: false,
1030            },
1031            Instantiable {
1032                capability: "Queue",
1033                binding_prefix: QUEUE_BINDING_PREFIX,
1034                options: &[(QUEUE_NAME_OPTION, OptionKind::Str)],
1035                required: &[QUEUE_NAME_OPTION],
1036                bare: false,
1037                linked: false,
1038            },
1039            Instantiable {
1040                capability: "Analytics",
1041                binding_prefix: ANALYTICS_BINDING_PREFIX,
1042                options: &[],
1043                required: &[],
1044                bare: false,
1045                linked: false,
1046            },
1047            Instantiable {
1048                capability: "D1",
1049                binding_prefix: D1_BINDING_PREFIX,
1050                options: &[],
1051                required: &[],
1052                bare: false,
1053                linked: false,
1054            },
1055            Instantiable {
1056                capability: "EdgeCache",
1057                binding_prefix: EDGE_CACHE_BINDING_PREFIX,
1058                options: &[],
1059                required: &[],
1060                bare: false,
1061                linked: false,
1062            },
1063            Instantiable {
1064                capability: "StoredSecret",
1065                binding_prefix: STORED_SECRET_BINDING_PREFIX,
1066                options: &[
1067                    (STORED_SECRET_STORE_OPTION, OptionKind::Str),
1068                    (STORED_SECRET_SECRET_OPTION, OptionKind::Str),
1069                ],
1070                required: &[STORED_SECRET_STORE_OPTION, STORED_SECRET_SECRET_OPTION],
1071                bare: false,
1072                linked: true,
1073            },
1074            // #3302: every option is optional, but each use is a named
1075            // instance (a bare `given Email` is refused, as for `Queue`), so a
1076            // Worker's mail binding is always one the source names. Nothing is
1077            // linked: the binding names no resource, and the deploy only
1078            // *checks* each allowed sender's domain.
1079            Instantiable {
1080                capability: "Email",
1081                binding_prefix: EMAIL_BINDING_PREFIX,
1082                options: &[
1083                    (EMAIL_TO_OPTION, OptionKind::Str),
1084                    (EMAIL_ALLOWED_RECIPIENTS_OPTION, OptionKind::StrList),
1085                    (EMAIL_ALLOWED_SENDERS_OPTION, OptionKind::StrList),
1086                ],
1087                required: &[],
1088                bare: false,
1089                linked: false,
1090            },
1091            // Hyperdrive H1 (#3318): no options (the connection string is
1092            // H2's `[deploy.hyperdrive.<Cap>]`), every use a named instance.
1093            Instantiable {
1094                capability: "Postgres",
1095                binding_prefix: POSTGRES_BINDING_PREFIX,
1096                options: &[],
1097                required: &[],
1098                bare: false,
1099                linked: false,
1100            },
1101            // Hyperdrive H5 (#3322): `@tls("…")` from a closed set, optional
1102            // (`required` when absent); every use a named instance.
1103            Instantiable {
1104                capability: "MySql",
1105                binding_prefix: MYSQL_BINDING_PREFIX,
1106                options: &[(MYSQL_TLS_OPTION, OptionKind::Str)],
1107                required: &[],
1108                bare: false,
1109                linked: false,
1110            },
1111            // #3479: the index is project-owned state, so `bynk deploy` creates
1112            // it from these (never linked); both fixed at creation, so required.
1113            Instantiable {
1114                capability: "Vectorize",
1115                binding_prefix: VECTORIZE_BINDING_PREFIX,
1116                options: &[
1117                    (VECTORIZE_DIMENSIONS_OPTION, OptionKind::PositiveInt),
1118                    (VECTORIZE_METRIC_OPTION, OptionKind::Str),
1119                    (VECTORIZE_INDEXED_OPTION, OptionKind::StrList),
1120                ],
1121                required: &[VECTORIZE_DIMENSIONS_OPTION, VECTORIZE_METRIC_OPTION],
1122                bare: false,
1123                linked: false,
1124            },
1125            // #3477: a container is a Durable Object class backed by an image
1126            // that `wrangler deploy` builds and pushes, so it is neither
1127            // linked nor provisioned by `bynk deploy`.
1128            Instantiable {
1129                capability: "Container",
1130                binding_prefix: CONTAINER_BINDING_PREFIX,
1131                options: &[
1132                    (CONTAINER_BUILD_OPTION, OptionKind::Str),
1133                    (CONTAINER_PORT_OPTION, OptionKind::PositiveInt),
1134                    (CONTAINER_SLEEP_AFTER_OPTION, OptionKind::Duration),
1135                    (CONTAINER_INSTANCE_TYPE_OPTION, OptionKind::Str),
1136                    (CONTAINER_FORWARD_OPTION, OptionKind::StrList),
1137                ],
1138                required: &[CONTAINER_BUILD_OPTION, CONTAINER_PORT_OPTION],
1139                bare: false,
1140                linked: false,
1141            },
1142            // #3480: an AI Search instance is configured and owned by someone
1143            // else (a data source, models, an indexing lifecycle), so the
1144            // deploy links to it by name and never creates it. The name is
1145            // required: a bare `given AiSearch` would name no instance.
1146            Instantiable {
1147                capability: "AiSearch",
1148                binding_prefix: AI_SEARCH_BINDING_PREFIX,
1149                options: &[(AI_SEARCH_INSTANCE_OPTION, OptionKind::Str)],
1150                required: &[AI_SEARCH_INSTANCE_OPTION],
1151                bare: false,
1152                linked: true,
1153            },
1154            // #3513 A: a client certificate is uploaded to the account by its owner, and
1155            // its private key never passes through Bynk, so the deploy links to it by name
1156            // and never uploads it. The name is required: a bare `given MtlsCertificate`
1157            // would name no certificate.
1158            Instantiable {
1159                capability: "MtlsCertificate",
1160                binding_prefix: MTLS_BINDING_PREFIX,
1161                options: &[(MTLS_CERTIFICATE_OPTION, OptionKind::Str)],
1162                required: &[MTLS_CERTIFICATE_OPTION],
1163                bare: false,
1164                linked: true,
1165            },
1166        ],
1167        // Version metadata (#3300): the running Worker version's id, tag and
1168        // creation time, one binding per Worker.
1169        singletons: &[
1170            Singleton {
1171                capability: "Version",
1172                binding: VERSION_BINDING_NAME,
1173                wrangler_table: "version_metadata",
1174            },
1175            // Workers AI (#3478): one `[ai]` binding per Worker, no instances.
1176            Singleton {
1177                capability: "Ai",
1178                binding: AI_BINDING_NAME,
1179                wrangler_table: "ai",
1180            },
1181            // Cloudflare Images (#3515): one `[images]` binding per Worker.
1182            Singleton {
1183                capability: "Images",
1184                binding: IMAGES_BINDING_NAME,
1185                wrangler_table: "images",
1186            },
1187            // Analytics SQL (#3513 B): one account-scoped `[analytics]` binding per Worker, the
1188            // read side of `Analytics`.
1189            Singleton {
1190                capability: "AnalyticsSql",
1191                binding: ANALYTICS_SQL_BINDING_NAME,
1192                wrangler_table: "analytics",
1193            },
1194        ],
1195    },
1196    Unit {
1197        name: LIST_UNIT,
1198        kind: UnitKind::Commons,
1199        identity_path: "bynk/list.bynk",
1200        source: BYNK_LIST_SRC,
1201        binding: Binding::None,
1202        id_block: 3,
1203        platform: None,
1204        env_providers: &[],
1205        stability: Stability::Stable,
1206        experimental: &[],
1207        extensible: &[],
1208        instantiable: &[],
1209        singletons: &[],
1210    },
1211    Unit {
1212        name: MAP_UNIT,
1213        kind: UnitKind::Commons,
1214        identity_path: "bynk/map.bynk",
1215        source: BYNK_MAP_SRC,
1216        binding: Binding::None,
1217        id_block: 2,
1218        platform: None,
1219        env_providers: &[],
1220        stability: Stability::Stable,
1221        experimental: &[],
1222        extensible: &[],
1223        instantiable: &[],
1224        singletons: &[],
1225    },
1226    Unit {
1227        name: STRING_UNIT,
1228        kind: UnitKind::Commons,
1229        identity_path: "bynk/string.bynk",
1230        source: BYNK_STRING_SRC,
1231        binding: Binding::None,
1232        id_block: 4,
1233        platform: None,
1234        env_providers: &[],
1235        stability: Stability::Stable,
1236        experimental: &[],
1237        extensible: &[],
1238        instantiable: &[],
1239        singletons: &[],
1240    },
1241    Unit {
1242        name: LOCALE_UNIT,
1243        kind: UnitKind::Commons,
1244        identity_path: "bynk/locale.bynk",
1245        source: BYNK_LOCALE_SRC,
1246        binding: Binding::None,
1247        id_block: 6,
1248        platform: None,
1249        env_providers: &[],
1250        stability: Stability::Stable,
1251        experimental: &[],
1252        extensible: &[],
1253        instantiable: &[],
1254        singletons: &[],
1255    },
1256    Unit {
1257        name: LOCALE_TYPES_UNIT,
1258        kind: UnitKind::Commons,
1259        identity_path: "bynk/locale/types.bynk",
1260        source: BYNK_LOCALE_TYPES_SRC,
1261        binding: Binding::None,
1262        id_block: 5,
1263        platform: None,
1264        env_providers: &[],
1265        stability: Stability::Stable,
1266        experimental: &[],
1267        extensible: &[],
1268        instantiable: &[],
1269        singletons: &[],
1270    },
1271    Unit {
1272        name: CRYPTO_UNIT,
1273        kind: UnitKind::Adapter,
1274        identity_path: "bynk/crypto.bynk",
1275        source: BYNK_CRYPTO_SRC,
1276        binding: Binding::PerPlatformFiles {
1277            cloudflare: (
1278                "bynk/crypto-cloudflare.binding.ts",
1279                CRYPTO_CLOUDFLARE_BINDING,
1280            ),
1281            node: ("bynk/crypto-node.binding.ts", CRYPTO_NODE_BINDING),
1282            browser: ("bynk/crypto-browser.binding.ts", CRYPTO_BROWSER_BINDING),
1283        },
1284        id_block: 7,
1285        platform: None,
1286        env_providers: &[],
1287        // Experimental until the first-party registry has signed with it in
1288        // production (#2308 R6), as P5's R2 does.
1289        stability: Stability::Experimental,
1290        experimental: &[],
1291        extensible: &["Digest", "Signature", "CryptoError"],
1292        instantiable: &[],
1293        singletons: &[],
1294    },
1295    Unit {
1296        name: URL_UNIT,
1297        kind: UnitKind::Commons,
1298        identity_path: "bynk/url.bynk",
1299        source: BYNK_URL_SRC,
1300        binding: Binding::None,
1301        id_block: 8,
1302        platform: None,
1303        env_providers: &[],
1304        stability: Stability::Stable,
1305        experimental: &[],
1306        extensible: &[],
1307        instantiable: &[],
1308        singletons: &[],
1309    },
1310    Unit {
1311        name: SET_UNIT,
1312        kind: UnitKind::Commons,
1313        identity_path: "bynk/set.bynk",
1314        source: BYNK_SET_SRC,
1315        binding: Binding::None,
1316        // 9, not 8: K2's `bynk.url` (#2594) takes 8 in parallel.
1317        id_block: 9,
1318        platform: None,
1319        env_providers: &[],
1320        stability: Stability::Stable,
1321        experimental: &[],
1322        extensible: &[],
1323        instantiable: &[],
1324        singletons: &[],
1325    },
1326    #[cfg(feature = "test-support")]
1327    Unit {
1328        name: TESTING_UNIT,
1329        kind: UnitKind::Adapter,
1330        identity_path: "bynk/testing.bynk",
1331        source: BYNK_TESTING_SRC,
1332        binding: Binding::Fixed {
1333            filename: TESTING_BINDING_FILENAME,
1334            source: TESTING_BINDING,
1335        },
1336        id_block: 10,
1337        platform: None,
1338        env_providers: &[],
1339        // The toolchain's own test support: no promise, and a project must opt in.
1340        stability: Stability::Experimental,
1341        experimental: &[],
1342        extensible: &[],
1343        instantiable: &[],
1344        singletons: &[],
1345    },
1346];
1347
1348/// The registry entry for `name`, if it is a first-party unit.
1349pub fn unit(name: &str) -> Option<&'static Unit> {
1350    UNITS.iter().find(|u| u.name == name)
1351}
1352
1353/// The unit a dotted item path lies in, and the rest of the path relative to it
1354/// (empty for the unit itself). Unit names contain dots, so the longest unit
1355/// name that is a whole-segment prefix wins: `bynk.cloudflare.Kv` is in
1356/// `bynk.cloudflare`, not in `bynk`.
1357pub fn split_item_path(path: &str) -> Option<(&'static Unit, &str)> {
1358    split_item_path_in(UNITS, path)
1359}
1360
1361/// [`split_item_path`] over a given table (tests pass a synthetic one).
1362pub fn split_item_path_in<'u, 'p>(units: &'u [Unit], path: &'p str) -> Option<(&'u Unit, &'p str)> {
1363    units
1364        .iter()
1365        .filter_map(|u| {
1366            if path == u.name {
1367                Some((u, ""))
1368            } else {
1369                path.strip_prefix(u.name)?
1370                    .strip_prefix('.')
1371                    .map(|rest| (u, rest))
1372            }
1373        })
1374        .max_by_key(|(u, _)| u.name.len())
1375}
1376
1377/// Whether `path` is `prefix` or lies under it, by whole dotted segments.
1378pub fn covers(prefix: &str, path: &str) -> bool {
1379    path == prefix
1380        || path
1381            .strip_prefix(prefix)
1382            .is_some_and(|rest| rest.starts_with('.'))
1383}
1384
1385/// The stability of a first-party item: a unit (`bynk.cloudflare`), an
1386/// exported item (`bynk.cloudflare.Kv`) or a capability operation
1387/// (`bynk.cloudflare.Kv.list`). An item in an experimental unit, or under an
1388/// experimental item, is experimental. `None` when no first-party unit holds
1389/// the path.
1390pub fn stability_of(path: &str) -> Option<Stability> {
1391    stability_of_in(UNITS, path)
1392}
1393
1394/// [`stability_of`] over a given table.
1395pub fn stability_of_in(units: &[Unit], path: &str) -> Option<Stability> {
1396    let (unit, rest) = split_item_path_in(units, path)?;
1397    if unit.stability == Stability::Experimental
1398        || unit.experimental.iter().any(|item| covers(item, rest))
1399    {
1400        Some(Stability::Experimental)
1401    } else {
1402        Some(Stability::Stable)
1403    }
1404}
1405
1406/// Every experimental item, as a full path: each experimental unit, and each
1407/// listed item of a stable one.
1408pub fn experimental_items() -> Vec<String> {
1409    experimental_items_in(UNITS)
1410}
1411
1412/// [`experimental_items`] over a given table.
1413pub fn experimental_items_in(units: &[Unit]) -> Vec<String> {
1414    let mut out = Vec::new();
1415    for u in units {
1416        if u.stability == Stability::Experimental {
1417            out.push(u.name.to_string());
1418        }
1419        out.extend(
1420            u.experimental
1421                .iter()
1422                .map(|item| format!("{}.{item}", u.name)),
1423        );
1424    }
1425    out
1426}
1427
1428/// Whether an `[unstable] allow` list covers `path`: an entry covers itself and
1429/// everything under it.
1430pub fn allows(allow: &[String], path: &str) -> bool {
1431    allow.iter().any(|entry| covers(entry, path))
1432}
1433
1434/// Whether `entry`, an `[unstable] allow` entry, reaches anything in
1435/// `experimental` (a list of experimental item paths, such as
1436/// [`experimental_items`]): it names an experimental item, lies under one, or
1437/// contains one. An entry that reaches nothing is stale.
1438pub fn allow_entry_is_live(experimental: &[String], entry: &str) -> bool {
1439    experimental
1440        .iter()
1441        .any(|item| covers(item, entry) || covers(entry, item))
1442}
1443
1444/// The instance kind `capability` of `unit` is, if a context may declare named
1445/// instances of it (S4a, #1966).
1446pub fn instantiable(unit: &str, capability: &str) -> Option<&'static Instantiable> {
1447    self::unit(unit)?
1448        .instantiable
1449        .iter()
1450        .find(|i| i.capability == capability)
1451}
1452
1453/// The one-per-Worker capability `capability` of first-party unit `unit`
1454/// (#3300), if it is one.
1455pub fn singleton(unit: &str, capability: &str) -> Option<&'static Singleton> {
1456    self::unit(unit)?
1457        .singletons
1458        .iter()
1459        .find(|s| s.capability == capability)
1460}
1461
1462/// Whether `name`, an enum exported by `unit`, is extensible.
1463pub fn is_extensible(unit: &str, name: &str) -> bool {
1464    is_extensible_in(UNITS, unit, name)
1465}
1466
1467/// [`is_extensible`] over a given table.
1468pub fn is_extensible_in(units: &[Unit], unit: &str, name: &str) -> bool {
1469    units
1470        .iter()
1471        .any(|u| u.name == unit && u.extensible.contains(&name))
1472}
1473
1474/// The names a first-party unit exports: those on its `exports … { … }` lines
1475/// (an adapter) and its own `fn`s and `type`s (a commons). Read from the
1476/// source, so the list cannot fall behind it.
1477pub fn exported_names(unit: &Unit) -> Vec<&'static str> {
1478    let mut out = Vec::new();
1479    let source = unit.source;
1480    let mut offset = 0;
1481    for line in source.lines() {
1482        let start = offset;
1483        offset += line.len() + 1;
1484        let trimmed = line.trim_start();
1485        // The list may run over several lines (`bynk-fmt` wraps a long one,
1486        // one name a line), so it is read from the source up to its `}`.
1487        if trimmed.starts_with("exports ")
1488            && let Some(open) = source[start..].find('{').map(|i| start + i)
1489            && let Some(close) = source[open..].find('}').map(|i| open + i)
1490        {
1491            out.extend(
1492                source[open + 1..close]
1493                    .split(',')
1494                    .map(str::trim)
1495                    .filter(|n| !n.is_empty()),
1496            );
1497        } else if unit.kind == UnitKind::Commons
1498            // A commons' own declarations: at column 0 in the flat form, one tab
1499            // in the braced `commons bynk.list { … }` form the first-party
1500            // sources use. Nothing deeper is a declaration.
1501            && (line == trimmed || line.strip_prefix('\t') == Some(trimmed))
1502        {
1503            for keyword in ["fn ", "type "] {
1504                if let Some(rest) = trimmed.strip_prefix(keyword) {
1505                    let end = rest
1506                        .find(|c: char| !(c.is_alphanumeric() || c == '_'))
1507                        .unwrap_or(rest.len());
1508                    if end > 0 {
1509                        out.push(&rest[..end]);
1510                    }
1511                }
1512            }
1513        }
1514    }
1515    out
1516}
1517
1518/// Whether `path` names a first-party unit or an item it exports. Operation
1519/// paths (`bynk.cloudflare.Kv.list`) are accepted when their item exists.
1520pub fn names_first_party_item(path: &str) -> bool {
1521    names_first_party_item_in(UNITS, path)
1522}
1523
1524/// [`names_first_party_item`] over a given table.
1525pub fn names_first_party_item_in(units: &[Unit], path: &str) -> bool {
1526    match split_item_path_in(units, path) {
1527        None => false,
1528        Some((_, "")) => true,
1529        Some((unit, rest)) => {
1530            let item = rest.split('.').next().unwrap_or(rest);
1531            exported_names(unit).contains(&item)
1532        }
1533    }
1534}
1535
1536#[cfg(test)]
1537mod tests {
1538    #[test]
1539    fn first_party_pins_are_exact() {
1540        for d in super::FIRST_PARTY_NPM {
1541            assert!(
1542                super::is_exact_version(d.version),
1543                "{} must be pinned exactly, not `{}`",
1544                d.package,
1545                d.version
1546            );
1547        }
1548        for range in [
1549            "^4.1.4", "~4.1.4", "4", "4.1", "*", "latest", ">=4.1.4", "4.x",
1550        ] {
1551            assert!(!super::is_exact_version(range), "{range}");
1552        }
1553        assert!(super::is_exact_version("4.1.4"));
1554    }
1555
1556    use super::*;
1557
1558    /// A synthetic registry with an experimental unit, an experimental item
1559    /// and an experimental operation inside stable units.
1560    const SYNTH: &[Unit] = &[
1561        Unit {
1562            name: "bynk",
1563            kind: UnitKind::Adapter,
1564            identity_path: "bynk.bynk",
1565            source: "adapter bynk {\n\texports capability { Clock, Fetch }\n\texports transparent { FetchError }\n}\n",
1566            binding: Binding::PerPlatform,
1567            id_block: 0,
1568            platform: None,
1569            env_providers: &[],
1570            stability: Stability::Stable,
1571            experimental: &["Fetch.stream"],
1572            extensible: &["FetchError"],
1573            instantiable: &[],
1574            singletons: &[],
1575        },
1576        Unit {
1577            name: "bynk.cloudflare",
1578            kind: UnitKind::Adapter,
1579            identity_path: "bynk/cloudflare.bynk",
1580            source: "adapter bynk.cloudflare {\n\texports capability { Kv, Ai }\n}\n",
1581            binding: Binding::None,
1582            id_block: 1,
1583            platform: Some(Platform::Cloudflare),
1584            env_providers: &[],
1585            stability: Stability::Stable,
1586            experimental: &["Ai"],
1587            extensible: &[],
1588            instantiable: &[],
1589            singletons: &[],
1590        },
1591        Unit {
1592            name: "bynk.cloudflare.d1",
1593            kind: UnitKind::Adapter,
1594            identity_path: "bynk/cloudflare/d1.bynk",
1595            source: "adapter bynk.cloudflare.d1 {\n\texports capability { D1 }\n}\n",
1596            binding: Binding::None,
1597            id_block: 2,
1598            platform: Some(Platform::Cloudflare),
1599            env_providers: &[],
1600            stability: Stability::Experimental,
1601            experimental: &[],
1602            extensible: &[],
1603            instantiable: &[],
1604            singletons: &[],
1605        },
1606        Unit {
1607            name: "bynk.text",
1608            kind: UnitKind::Commons,
1609            identity_path: "bynk/text.bynk",
1610            source: "commons bynk.text\n\ntype Slug = String\n\nfn shout(s: String) -> String {\n\ts\n}\n",
1611            binding: Binding::None,
1612            id_block: 3,
1613            platform: None,
1614            env_providers: &[],
1615            stability: Stability::Stable,
1616            experimental: &[],
1617            extensible: &[],
1618            instantiable: &[],
1619            singletons: &[],
1620        },
1621    ];
1622
1623    #[test]
1624    fn item_paths_resolve_to_the_longest_unit() {
1625        let unit_of = |p| split_item_path_in(SYNTH, p).map(|(u, rest)| (u.name, rest));
1626        assert_eq!(unit_of("bynk"), Some(("bynk", "")));
1627        assert_eq!(unit_of("bynk.Fetch.send"), Some(("bynk", "Fetch.send")));
1628        assert_eq!(
1629            unit_of("bynk.cloudflare.Kv"),
1630            Some(("bynk.cloudflare", "Kv"))
1631        );
1632        assert_eq!(
1633            unit_of("bynk.cloudflare.d1.D1"),
1634            Some(("bynk.cloudflare.d1", "D1"))
1635        );
1636        assert_eq!(unit_of("bynkx"), None, "a whole-segment prefix only");
1637        assert_eq!(unit_of("user.unit"), None);
1638    }
1639
1640    #[test]
1641    fn stability_follows_unit_item_and_operation() {
1642        let st = |p| stability_of_in(SYNTH, p);
1643        use Stability::*;
1644        assert_eq!(st("bynk.Clock"), Some(Stable));
1645        assert_eq!(st("bynk.Fetch.send"), Some(Stable));
1646        assert_eq!(
1647            st("bynk.Fetch.stream"),
1648            Some(Experimental),
1649            "an experimental operation"
1650        );
1651        assert_eq!(
1652            st("bynk.Fetch"),
1653            Some(Stable),
1654            "its capability stays stable"
1655        );
1656        assert_eq!(
1657            st("bynk.cloudflare.Ai"),
1658            Some(Experimental),
1659            "an experimental item"
1660        );
1661        assert_eq!(
1662            st("bynk.cloudflare.Ai.run"),
1663            Some(Experimental),
1664            "its operations too"
1665        );
1666        assert_eq!(st("bynk.cloudflare.Kv"), Some(Stable));
1667        assert_eq!(
1668            st("bynk.cloudflare.d1"),
1669            Some(Experimental),
1670            "an experimental unit"
1671        );
1672        assert_eq!(st("bynk.cloudflare.d1.D1.query"), Some(Experimental));
1673        assert_eq!(st("user.unit"), None);
1674    }
1675
1676    #[test]
1677    fn allow_entries_cover_by_whole_segment_prefix() {
1678        let allow = vec![
1679            "bynk.cloudflare.Ai".to_string(),
1680            "bynk.cloudflare.d1".to_string(),
1681        ];
1682        assert!(allows(&allow, "bynk.cloudflare.Ai"));
1683        assert!(allows(&allow, "bynk.cloudflare.Ai.run"));
1684        assert!(allows(&allow, "bynk.cloudflare.d1.D1.query"));
1685        assert!(
1686            !allows(&allow, "bynk.cloudflare.AiX"),
1687            "not a segment prefix"
1688        );
1689        assert!(!allows(&allow, "bynk.Fetch.stream"));
1690        assert!(!allows(&[], "bynk.cloudflare.Ai"));
1691    }
1692
1693    #[test]
1694    fn an_allow_entry_is_live_while_it_reaches_something_experimental() {
1695        let synth = experimental_items_in(SYNTH);
1696        let live = |e| allow_entry_is_live(&synth, e);
1697        assert!(live("bynk.cloudflare.Ai"));
1698        assert!(live("bynk.cloudflare.Ai.run"), "under an experimental item");
1699        assert!(live("bynk.cloudflare"), "contains an experimental item");
1700        assert!(live("bynk.Fetch.stream"));
1701        assert!(live("bynk"), "contains an experimental operation");
1702        assert!(!live("bynk.cloudflare.Kv"), "stable: a stale entry");
1703        assert!(!live("bynk.text"));
1704        assert_eq!(
1705            experimental_items_in(SYNTH),
1706            [
1707                "bynk.Fetch.stream",
1708                "bynk.cloudflare.Ai",
1709                "bynk.cloudflare.d1"
1710            ]
1711        );
1712    }
1713
1714    #[test]
1715    fn exported_names_and_item_existence_come_from_the_sources() {
1716        assert_eq!(exported_names(&SYNTH[0]), ["Clock", "Fetch", "FetchError"]);
1717        // K5a (#2586): a list `bynk-fmt` wrapped, one name a line.
1718        let wrapped = Unit {
1719            source: "adapter bynk {\n\texports transparent {\n\t\tMethod,\n\t\tRedirect,\n\t}\n\texports capability { Fetch }\n}\n",
1720            ..SYNTH[0]
1721        };
1722        assert_eq!(exported_names(&wrapped), ["Method", "Redirect", "Fetch"]);
1723        assert_eq!(exported_names(&SYNTH[3]), ["Slug", "shout"]);
1724        let names = |p| names_first_party_item_in(SYNTH, p);
1725        assert!(names("bynk.cloudflare"));
1726        assert!(names("bynk.cloudflare.Ai"));
1727        assert!(
1728            names("bynk.cloudflare.Ai.run"),
1729            "an operation of an existing item"
1730        );
1731        assert!(names("bynk.text.shout"));
1732        assert!(!names("bynk.cloudflare.Aii"), "a typo");
1733        assert!(!names("user.unit"));
1734    }
1735
1736    #[test]
1737    fn extensibility_is_by_unit_and_name() {
1738        assert!(is_extensible_in(SYNTH, "bynk", "FetchError"));
1739        assert!(
1740            !is_extensible_in(SYNTH, "user.app", "FetchError"),
1741            "a user's own FetchError"
1742        );
1743        assert!(!is_extensible_in(SYNTH, "bynk", "Method"));
1744    }
1745
1746    /// #3300: the shipped one-per-Worker capabilities: `bynk.cloudflare`'s
1747    /// `Version`, bound as `CF_VERSION_METADATA` under `[version_metadata]`.
1748    /// Each is a capability its unit exports, is not also instantiable, has a
1749    /// provider that takes `env`, and that provider's default binding in the
1750    /// TypeScript is the registry's name, so a bare construction reads it.
1751    #[test]
1752    fn the_shipped_singletons_are_pinned() {
1753        let shipped: Vec<(&str, &str, &str, &str)> = UNITS
1754            .iter()
1755            .flat_map(|u| {
1756                u.singletons
1757                    .iter()
1758                    .map(move |s| (u.name, s.capability, s.binding, s.wrangler_table))
1759            })
1760            .collect();
1761        assert_eq!(
1762            shipped,
1763            [
1764                (
1765                    "bynk.cloudflare",
1766                    "Version",
1767                    "CF_VERSION_METADATA",
1768                    "version_metadata"
1769                ),
1770                ("bynk.cloudflare", "Ai", "AI", "ai"),
1771                ("bynk.cloudflare", "Images", "IMAGES", "images"),
1772                (
1773                    "bynk.cloudflare",
1774                    "AnalyticsSql",
1775                    "CF_ANALYTICS_SQL",
1776                    "analytics"
1777                ),
1778            ]
1779        );
1780        for u in UNITS {
1781            for s in u.singletons {
1782                assert!(
1783                    instantiable(u.name, s.capability).is_none(),
1784                    "{}",
1785                    s.capability
1786                );
1787                assert!(
1788                    u.source
1789                        .contains(&format!("capability {} {{", s.capability)),
1790                    "{} declares `{}`",
1791                    u.name,
1792                    s.capability
1793                );
1794                assert!(
1795                    provider_takes_env(u.name, &format!("Workers{}", s.capability)),
1796                    "`Workers{}` takes `env`",
1797                    s.capability
1798                );
1799                let Binding::Fixed { source, .. } = u.binding else {
1800                    panic!("{} has a fixed binding", u.name);
1801                };
1802                assert!(
1803                    source.contains(&format!("binding: string = \"{}\"", s.binding)),
1804                    "`Workers{}` defaults to `{}`",
1805                    s.capability,
1806                    s.binding
1807                );
1808            }
1809        }
1810        assert!(singleton("bynk.cloudflare", "Version").is_some());
1811        assert!(singleton("bynk.cloudflare", "Kv").is_none());
1812    }
1813
1814    /// The shipped instantiable kinds: `bynk.cloudflare`'s `Kv` (S4a, #1966),
1815    /// binding as `KV_<NAME>` with no creation options, and its `Service`
1816    /// (interop I5, #1972), binding as `SERVICE_<NAME>` and naming its Worker
1817    /// with a required `@worker`, never usable bare. Each one is a capability
1818    /// its unit exports.
1819    #[test]
1820    fn the_shipped_instantiable_kinds_are_pinned() {
1821        let kinds: Vec<(&str, &str, &str)> = UNITS
1822            .iter()
1823            .flat_map(|u| {
1824                u.instantiable
1825                    .iter()
1826                    .map(move |i| (u.name, i.capability, i.binding_prefix))
1827            })
1828            .collect();
1829        assert_eq!(
1830            kinds,
1831            [
1832                ("bynk.cloudflare", "Kv", "KV"),
1833                ("bynk.cloudflare", "Service", "SERVICE"),
1834                ("bynk.cloudflare", "R2", "R2"),
1835                ("bynk.cloudflare", "RateLimit", "RATELIMIT"),
1836                ("bynk.cloudflare", "Queue", "QUEUE"),
1837                ("bynk.cloudflare", "Analytics", "ANALYTICS"),
1838                ("bynk.cloudflare", "D1", "D1"),
1839                ("bynk.cloudflare", "EdgeCache", "EDGE_CACHE"),
1840                ("bynk.cloudflare", "StoredSecret", "SECRET"),
1841                ("bynk.cloudflare", "Email", "EMAIL"),
1842                ("bynk.cloudflare", "Postgres", "HYPERDRIVE"),
1843                ("bynk.cloudflare", "MySql", "HYPERDRIVE"),
1844                ("bynk.cloudflare", "Vectorize", "VECTORIZE"),
1845                ("bynk.cloudflare", "Container", "CONTAINER"),
1846                ("bynk.cloudflare", "AiSearch", "AI_SEARCH"),
1847                ("bynk.cloudflare", "MtlsCertificate", "MTLS")
1848            ]
1849        );
1850        let kv = instantiable("bynk.cloudflare", "Kv").expect("Kv is instantiable");
1851        assert!(kv.options.is_empty() && kv.required.is_empty() && kv.bare);
1852        let service = instantiable("bynk.cloudflare", "Service").expect("Service is instantiable");
1853        assert_eq!(service.option_names().collect::<Vec<_>>(), ["worker"]);
1854        assert_eq!(service.required, ["worker"]);
1855        assert!(!service.bare);
1856        let r2 = instantiable("bynk.cloudflare", "R2").expect("R2 is instantiable");
1857        assert_eq!(r2.option_names().collect::<Vec<_>>(), ["jurisdiction"]);
1858        assert!(r2.required.is_empty() && !r2.bare);
1859        let rl = instantiable("bynk.cloudflare", "RateLimit").expect("RateLimit is instantiable");
1860        assert_eq!(rl.option_kind("limit"), Some(OptionKind::PositiveInt));
1861        assert_eq!(rl.option_kind("period"), Some(OptionKind::Duration));
1862        assert_eq!(rl.required, ["limit", "period"]);
1863        assert!(!rl.bare);
1864        let queue = instantiable("bynk.cloudflare", "Queue").expect("Queue is instantiable");
1865        assert_eq!(queue.option_kind("name"), Some(OptionKind::Str));
1866        assert_eq!(queue.required, ["name"]);
1867        assert!(!queue.bare);
1868        let analytics =
1869            instantiable("bynk.cloudflare", "Analytics").expect("Analytics is instantiable");
1870        assert!(analytics.options.is_empty() && !analytics.bare);
1871        let edge = instantiable("bynk.cloudflare", "EdgeCache").expect("EdgeCache is instantiable");
1872        assert!(edge.options.is_empty() && !edge.bare);
1873        // #3301: a stored secret names its store and its secret, both
1874        // required, and is the one kind the deploy links and never creates.
1875        let stored =
1876            instantiable("bynk.cloudflare", "StoredSecret").expect("StoredSecret is instantiable");
1877        assert_eq!(
1878            stored.option_names().collect::<Vec<_>>(),
1879            ["store", "secret"]
1880        );
1881        assert_eq!(stored.required, ["store", "secret"]);
1882        assert!(!stored.bare && stored.linked);
1883        let linked: Vec<&str> = UNITS
1884            .iter()
1885            .flat_map(|u| u.instantiable.iter().filter(|i| i.linked))
1886            .map(|i| i.capability)
1887            .collect();
1888        assert_eq!(linked, ["StoredSecret", "AiSearch", "MtlsCertificate"]);
1889        // #3480: an AI Search instance names the instance, required, and is
1890        // linked like a stored secret.
1891        let search = instantiable("bynk.cloudflare", "AiSearch").expect("AiSearch is instantiable");
1892        assert_eq!(search.option_names().collect::<Vec<_>>(), ["instance"]);
1893        assert_eq!(search.required, ["instance"]);
1894        assert!(!search.bare && search.linked);
1895        // #3513 A: an mTLS certificate names the certificate, required, and is linked like
1896        // a stored secret.
1897        let mtls = instantiable("bynk.cloudflare", "MtlsCertificate")
1898            .expect("MtlsCertificate is instantiable");
1899        assert_eq!(mtls.option_names().collect::<Vec<_>>(), ["certificate"]);
1900        assert_eq!(mtls.required, ["certificate"]);
1901        assert!(!mtls.bare && mtls.linked);
1902        // #3302: an email instance takes three optional options and is not
1903        // linked.
1904        let email = instantiable("bynk.cloudflare", "Email").expect("Email is instantiable");
1905        assert_eq!(
1906            email.option_names().collect::<Vec<_>>(),
1907            ["to", "allowedRecipients", "allowedSenders"]
1908        );
1909        assert_eq!(
1910            email.option_kind("allowedSenders"),
1911            Some(OptionKind::StrList)
1912        );
1913        assert!(email.required.is_empty() && !email.bare && !email.linked);
1914        // Hyperdrive H1 (#3318): a Postgres instance takes no option, is
1915        // never bare, and is not linked.
1916        // Hyperdrive H5 (#3322): a MySql instance takes only `@tls`, is never
1917        // bare, is not linked, and shares Postgres's binding prefix.
1918        let my = instantiable("bynk.cloudflare", "MySql").expect("MySql is instantiable");
1919        assert_eq!(my.option_names().collect::<Vec<_>>(), ["tls"]);
1920        assert!(my.required.is_empty() && !my.bare && !my.linked);
1921        assert_eq!(MYSQL_BINDING_PREFIX, POSTGRES_BINDING_PREFIX);
1922        assert_eq!(MYSQL_TLS_MODES[0], ("required", "REQUIRED"));
1923        // #3479: a Vectorize instance states the index's fixed configuration,
1924        // both required; the metadata indexes are optional. Never bare, and
1925        // created by the deploy, so not linked.
1926        let vec = instantiable("bynk.cloudflare", "Vectorize").expect("Vectorize is instantiable");
1927        assert_eq!(
1928            vec.option_names().collect::<Vec<_>>(),
1929            ["dimensions", "metric", "indexed"]
1930        );
1931        assert_eq!(vec.option_kind("dimensions"), Some(OptionKind::PositiveInt));
1932        assert_eq!(vec.option_kind("indexed"), Some(OptionKind::StrList));
1933        assert_eq!(vec.required, ["dimensions", "metric"]);
1934        assert!(!vec.bare && !vec.linked);
1935        // #3477: a Container names its build and port, and may set the rest.
1936        let container =
1937            instantiable("bynk.cloudflare", "Container").expect("Container is instantiable");
1938        assert_eq!(
1939            container.option_names().collect::<Vec<_>>(),
1940            ["build", "port", "sleepAfter", "instanceType", "forward"]
1941        );
1942        assert_eq!(
1943            container.option_kind("sleepAfter"),
1944            Some(OptionKind::Duration)
1945        );
1946        assert_eq!(container.required, ["build", "port"]);
1947        assert!(!container.bare && !container.linked);
1948        let pg = instantiable("bynk.cloudflare", "Postgres").expect("Postgres is instantiable");
1949        assert!(pg.options.is_empty() && pg.required.is_empty() && !pg.bare && !pg.linked);
1950        for u in UNITS {
1951            for i in u.instantiable {
1952                assert!(
1953                    i.required.iter().all(|r| i.option_kind(r).is_some()),
1954                    "{}.{}: a required option must be an option",
1955                    u.name,
1956                    i.capability
1957                );
1958            }
1959        }
1960        assert!(exported_names(unit("bynk.cloudflare").unwrap()).contains(&"Kv"));
1961        assert!(exported_names(unit("bynk.cloudflare").unwrap()).contains(&"Service"));
1962        assert_eq!(instantiable("bynk", "Clock"), None);
1963        assert_eq!(instantiable("bynk.cloudflare", "Nope"), None);
1964    }
1965
1966    /// The shipped registry: every unit is stable (S3 ships the mechanism,
1967    /// #1963 Decision C) but `bynk.crypto` (K4), which is experimental until the
1968    /// first-party registry has signed with it in production. The one
1969    /// experimental item inside a stable unit is `bynk.cloudflare`'s `Service`
1970    /// (interop I5, #1972), and the growing enums are extensible. A slice that
1971    /// marks an item experimental updates this test, so the change is visible
1972    /// in review.
1973    #[test]
1974    fn the_shipped_stability_is_pinned() {
1975        for u in UNITS {
1976            let expected = if u.name == CRYPTO_UNIT || u.name == TESTING_UNIT {
1977                Stability::Experimental
1978            } else {
1979                Stability::Stable
1980            };
1981            assert_eq!(u.stability, expected, "{}", u.name);
1982        }
1983        let mut shipped = experimental_items();
1984        shipped.retain(|i| i != TESTING_UNIT);
1985        assert_eq!(
1986            shipped,
1987            [
1988                "bynk.Fetch.sendWith",
1989                "bynk.Fetch.receiveBytes",
1990                "bynk.Fetch.sendBytes",
1991                "bynk.Fetch.receiveStream",
1992                "bynk.Fetch.sendStream",
1993                "bynk.Logger.log",
1994                "bynk.cloudflare.Service",
1995                "bynk.cloudflare.R2",
1996                "bynk.cloudflare.RateLimit",
1997                "bynk.cloudflare.EdgeCache",
1998                "bynk.cloudflare.Queue",
1999                "bynk.cloudflare.Analytics",
2000                "bynk.cloudflare.Version",
2001                "bynk.cloudflare.Ai",
2002                "bynk.cloudflare.Images",
2003                "bynk.cloudflare.StoredSecret",
2004                "bynk.cloudflare.Email",
2005                "bynk.cloudflare.Postgres",
2006                "bynk.cloudflare.MySql",
2007                "bynk.cloudflare.Vectorize",
2008                "bynk.cloudflare.Container",
2009                "bynk.cloudflare.AiSearch",
2010                "bynk.cloudflare.MtlsCertificate",
2011                "bynk.cloudflare.AnalyticsSql",
2012                "bynk.cloudflare.RequestCf",
2013                "bynk.cloudflare.Kv.getWith",
2014                "bynk.cloudflare.Kv.putWith",
2015                "bynk.cloudflare.Kv.getBytes",
2016                "bynk.cloudflare.Kv.putBytes",
2017                "bynk.cloudflare.Kv.listPage",
2018                "bynk.crypto"
2019            ]
2020        );
2021        let extensible: Vec<(&str, &str)> = UNITS
2022            .iter()
2023            .flat_map(|u| u.extensible.iter().map(move |e| (u.name, *e)))
2024            .collect();
2025        assert_eq!(
2026            extensible,
2027            [
2028                ("bynk", "FetchError"),
2029                ("bynk", "Method"),
2030                ("bynk", "Redirect"),
2031                ("bynk.cloudflare", "R2Condition"),
2032                ("bynk.cloudflare", "KvExpiration"),
2033                ("bynk.cloudflare", "SqlError"),
2034                ("bynk.cloudflare", "EmailError"),
2035                ("bynk.cloudflare", "AiError"),
2036                ("bynk.cloudflare", "ImageFormat"),
2037                ("bynk.cloudflare", "ImageFit"),
2038                ("bynk.cloudflare", "ImagesError"),
2039                ("bynk.cloudflare", "AnalyticsSqlError"),
2040                ("bynk.cloudflare", "ChatRole"),
2041                ("bynk.cloudflare", "PgError"),
2042                ("bynk.cloudflare", "MySqlError"),
2043                ("bynk.cloudflare", "VectorError"),
2044                ("bynk.cloudflare", "ContainerError"),
2045                ("bynk.cloudflare", "SearchError"),
2046                ("bynk.crypto", "Digest"),
2047                ("bynk.crypto", "Signature"),
2048                ("bynk.crypto", "CryptoError"),
2049            ]
2050        );
2051        for (unit, name) in extensible {
2052            assert!(
2053                exported_names(self::unit(unit).unwrap()).contains(&name),
2054                "{unit} lists {name} as extensible but does not export it"
2055            );
2056        }
2057        assert!(names_first_party_item("bynk.cloudflare.Kv.list"));
2058        assert!(names_first_party_item("bynk.list.reverse"));
2059        assert!(!names_first_party_item("bynk.cloudflare.Kvv"));
2060    }
2061
2062    /// #1958: `WorkersKv` reads the namespace at the name every generated
2063    /// Worker declares it under (`[[kv_namespaces]] binding`, its `Env`), the
2064    /// one TypeScript literal no Rust constructor can supply. Since S4a (#1966)
2065    /// the name is a constructor parameter, so a derived capability's instance
2066    /// can pass its own; the bare `Kv`'s is the parameter's default.
2067    ///
2068    /// Matched as a whole identifier, then by its neighbours, so the test
2069    /// ignores formatting but not a rename: `KVX` is not `KV` (review of
2070    /// #1962).
2071    #[test]
2072    fn the_cloudflare_binding_reads_kv_binding_name() {
2073        let ident = |c: char| c.is_ascii_alphanumeric() || c == '_' || c == '$';
2074        let src = CLOUDFLARE_BINDING;
2075        let uses: Vec<(&str, &str)> = src
2076            .match_indices(KV_BINDING_NAME)
2077            .map(|(at, name)| (&src[..at], &src[at + name.len()..]))
2078            .filter(|(before, after)| !before.ends_with(ident) && !after.starts_with(ident))
2079            .collect();
2080        assert!(
2081            uses.iter().any(|(b, a)| {
2082                b.trim_end().ends_with("binding: string = \"") && a.starts_with('"')
2083            }),
2084            "the constructor's `binding` no longer defaults to \"{KV_BINDING_NAME}\""
2085        );
2086        assert!(
2087            src.contains("?.[this.binding]"),
2088            "the namespace is no longer read at `env[binding]`"
2089        );
2090    }
2091
2092    /// #3458: `bynk.testing` is the toolchain's own test support, so a build
2093    /// without the `test-support` feature (every release) does not know it, and
2094    /// `[unstable] allow = ["bynk.testing"]` names no standard-library item.
2095    #[cfg(not(feature = "test-support"))]
2096    #[test]
2097    fn a_release_does_not_contain_the_test_support_unit() {
2098        assert!(unit(TESTING_UNIT).is_none());
2099        assert!(!UNITS.iter().any(|u| u.name == TESTING_UNIT));
2100        assert!(!names_first_party_item(TESTING_UNIT));
2101    }
2102
2103    /// Each unit's `ExprId` block is permanent: emitted output and the
2104    /// process-wide parse cache depend on it. These are the blocks the
2105    /// hand-written injection used before the registry (S1, #1945); a new
2106    /// unit takes a new block and never moves one of these.
2107    #[test]
2108    fn id_blocks_are_pinned_and_distinct() {
2109        // `bynk.testing` (#3458) exists only with the `test-support` feature.
2110        let blocks: Vec<(&str, u32)> = UNITS
2111            .iter()
2112            .filter(|u| u.name != TESTING_UNIT)
2113            .map(|u| (u.name, u.id_block))
2114            .collect();
2115        assert_eq!(
2116            blocks,
2117            [
2118                ("bynk", 0),
2119                ("bynk.cloudflare", 1),
2120                ("bynk.list", 3),
2121                ("bynk.map", 2),
2122                ("bynk.string", 4),
2123                ("bynk.locale", 6),
2124                ("bynk.locale.types", 5),
2125                ("bynk.crypto", 7),
2126                ("bynk.url", 8),
2127                ("bynk.set", 9),
2128            ]
2129        );
2130        let mut sorted: Vec<u32> = UNITS.iter().map(|u| u.id_block).collect();
2131        sorted.sort_unstable();
2132        sorted.dedup();
2133        assert_eq!(sorted.len(), UNITS.len(), "two units share an id block");
2134    }
2135
2136    /// Hover and completion read [`FIRSTPARTY_SOURCES`] in order, so it is
2137    /// pinned to the order the hand-written list had.
2138    #[test]
2139    fn firstparty_sources_keep_their_order() {
2140        // `bynk.testing` (#3458) exists only with the `test-support` feature.
2141        let names: Vec<&str> = FIRSTPARTY_SOURCES
2142            .iter()
2143            .map(|(n, _)| *n)
2144            .filter(|n| *n != TESTING_UNIT)
2145            .collect();
2146        assert_eq!(
2147            names,
2148            [
2149                "bynk",
2150                "bynk.cloudflare",
2151                "bynk.list",
2152                "bynk.map",
2153                "bynk.string",
2154                "bynk.locale",
2155                "bynk.locale.types",
2156                "bynk.crypto",
2157                "bynk.url",
2158                "bynk.set",
2159            ]
2160        );
2161        for (unit, (name, source)) in UNITS.iter().zip(FIRSTPARTY_SOURCES) {
2162            assert_eq!((unit.name, unit.source), (*name, *source));
2163        }
2164    }
2165
2166    /// The views over the table answer as the hand-written matches did.
2167    #[test]
2168    fn metadata_views_match_the_previous_answers() {
2169        assert_eq!(platform_of("bynk.cloudflare"), Some(Platform::Cloudflare));
2170        for name in [
2171            "bynk",
2172            "bynk.list",
2173            "bynk.map",
2174            "bynk.string",
2175            "bynk.locale",
2176            "user.unit",
2177        ] {
2178            assert_eq!(platform_of(name), None, "{name}");
2179        }
2180        assert!(provider_takes_env("bynk", "SecretsProvider"));
2181        assert!(provider_takes_env("bynk.cloudflare", "WorkersKv"));
2182        assert!(!provider_takes_env("bynk", "WorkersKv"));
2183        assert!(!provider_takes_env("bynk.cloudflare", "SecretsProvider"));
2184        assert!(!provider_takes_env("bynk", "ClockProvider"));
2185        assert!(!provider_takes_env("user.unit", "SecretsProvider"));
2186    }
2187
2188    /// An adapter carries a binding and a commons does not, and every name and
2189    /// identity path is unique, every name inside the reserved prefix.
2190    #[test]
2191    fn entries_are_well_formed() {
2192        for u in UNITS {
2193            assert!(
2194                u.name == "bynk" || u.name.starts_with("bynk."),
2195                "{}",
2196                u.name
2197            );
2198            assert_eq!(
2199                UNITS.iter().filter(|o| o.name == u.name).count(),
2200                1,
2201                "{}",
2202                u.name
2203            );
2204            // Two entries under one identity path would be two parsed units
2205            // that diagnostics and emission cannot tell apart.
2206            assert_eq!(
2207                UNITS
2208                    .iter()
2209                    .filter(|o| o.identity_path == u.identity_path)
2210                    .count(),
2211                1,
2212                "{}",
2213                u.identity_path
2214            );
2215            match u.kind {
2216                UnitKind::Adapter => assert_ne!(u.binding, Binding::None, "{}", u.name),
2217                UnitKind::Commons => {
2218                    assert_eq!(u.binding, Binding::None, "{}", u.name);
2219                    assert!(u.env_providers.is_empty(), "{}", u.name);
2220                }
2221            }
2222        }
2223        assert_eq!(
2224            unit("bynk.cloudflare").and_then(|u| u.binding_for(Platform::Node)),
2225            Some((CLOUDFLARE_BINDING_FILENAME, CLOUDFLARE_BINDING))
2226        );
2227        assert_eq!(
2228            unit("bynk").and_then(|u| u.binding_for(Platform::Browser)),
2229            Some(("bynk-browser.ts", BYNK_BROWSER_BINDING))
2230        );
2231        assert_eq!(
2232            unit("bynk.list").and_then(|u| u.binding_for(Platform::Node)),
2233            None
2234        );
2235    }
2236
2237    /// The three `bynk.crypto` bindings are one body with one marked region of
2238    /// platform difference (the constant-time comparison primitive). They are
2239    /// separate files because each ships alone, so this keeps them from drifting.
2240    #[test]
2241    fn the_crypto_bindings_differ_only_in_their_platform_region() {
2242        const START: &str = "// --- platform: constant-time comparison primitive";
2243        const END: &str = "// --- end platform";
2244        fn shared(src: &str) -> String {
2245            let (head, rest) = src.split_once(START).expect("platform region start");
2246            let (_, tail) = rest.split_once(END).expect("platform region end");
2247            // The second header line names the platform.
2248            let head = head.lines().skip(2).collect::<Vec<_>>().join("\n");
2249            format!("{head}\n{tail}")
2250        }
2251        let cloudflare = shared(CRYPTO_CLOUDFLARE_BINDING);
2252        assert_eq!(cloudflare, shared(CRYPTO_NODE_BINDING));
2253        assert_eq!(cloudflare, shared(CRYPTO_BROWSER_BINDING));
2254    }
2255
2256    /// The hardcoded [`BYNK_SURFACE_CAPABILITIES`] must match the adapter's
2257    /// `exports capability { … }` line — otherwise the unknown-name quick-fix
2258    /// (#852) would offer a stale `consumes bynk { … }` set.
2259    #[test]
2260    fn bynk_surface_capabilities_match_the_adapter() {
2261        let src = BYNK_ADAPTER_SRC;
2262        let line = src
2263            .lines()
2264            .find(|l| l.trim_start().starts_with("exports capability {"))
2265            .expect("adapter declares `exports capability`");
2266        let inner = line
2267            .split_once('{')
2268            .and_then(|(_, r)| r.split_once('}'))
2269            .map(|(names, _)| names)
2270            .expect("braced capability list");
2271        let declared: Vec<&str> = inner.split(',').map(|s| s.trim()).collect();
2272        assert_eq!(
2273            declared, BYNK_SURFACE_CAPABILITIES,
2274            "BYNK_SURFACE_CAPABILITIES is out of sync with bynk.bynk"
2275        );
2276    }
2277}