Skip to content
Playground(another site)

§7 Meaning by translation

Bynk has no operational semantics. A program’s dynamic meaning is defined by translation: it is the behaviour of the TypeScript the compiler emits for it, executed against the runtime library (§7.4). This chapter defines that translation per construct, and the two emission targets it varies over.

For every well-formed program (§5) the compiler emits TypeScript. The meaning of the program is the meaning of that TypeScript run against the runtime library. There is no second, independent definition of behaviour to reconcile against; where this chapter and the emitter disagree, that is a defect (§1.1). The emitted output is deterministic and each file is headed // Generated by bynk — do not edit by hand.

A program is emitted for one of two targets, selected by --target (§8). A commons emits the same plain TypeScript — types and functions — on either target; the targets differ in how a context, its agents, and cross-context calls are realised.

bundle (default)workers
Layouta flat .ts tree mirroring the sourceone Worker directory per context
Cross-context calla direct, in-process callJSON over a Cloudflare Service Binding, validated at the boundary
Agentbacked by an in-process StateRegistrya Cloudflare Durable Object keyed by the agent key
Consumed adapterin-process, via its bindingin-process, via its binding — no Service Binding, no Env entry

An adapter is not a deployment unit: consuming one is in-process on both targets (§7.3.6). Only consumed contexts become Service Bindings under workers.

On the workers target a context with handlers additionally emits a router and boundary plumbing (index.ts), the handler logic (handlers.ts), the composition root (compose.ts), and a wrangler.toml; records that cross a boundary gain __serialise_* / __deserialise_* helpers. Cross-context data MUST be structurally validated as it crosses (§6.5).

Float at boundaries (v0.21, ADR 0040). Boundary Float values are finite, even though in-language arithmetic is host-defined (§5.2):

  • __deserialise_ of a Float field requires typeof v === "number" && Number.isFinite(v), with no integer check (decimals are the point). JSON.parse("1e999") yields Infinity, which is rejected as a StructuralMismatch expecting a finite number — never admitted from the wire.
  • __serialise_ of a Float field throws on a non-finite value (a contract violation): JSON.stringify(NaN) would otherwise silently produce null and break the round-trip.
  • v0.22b (ADR 0049): a bare Int field additionally requires Number.isInteger — at record/nested fields and workers handler params. A previously-accepted {qty: 1.5} now fails with a StructuralMismatch expecting an integer; with Float in the language there is no excuse for fractional Ints, and codec and .of agree (as 0040 aligned them for Float).

Recursive types at boundaries (#2656). The codecs of a type on a type cycle, and the container and generic-instantiation codecs the cycle passes through, take a trailing depth: number = 0 and are bounded at 256 levels (§6.5). A record’s or sum’s codec counts one level and passes depth + 1 on; a container’s passes depth through. __deserialise_ past the bound returns a StructuralMismatch expecting a value nested at most 256 levels deep; __serialise_ past it throws, as for a non-finite Float. The codecs of every other type, and every call from outside a cycle, are emitted without the parameter.

ConstructEmits
named type (type Id = Int)a branded base type with a .of brand cast returning the type (no predicate, so it cannot fail)
refined typea branded base with .of (a runtime predicate check returning Result)
opaque typea branded base with .of and .unsafe constructors; no structural access to the representation
recordan interface with readonly fields, constructed from an object literal
sum / enuma discriminated union over a tag field, plus a constructor namespace

Only an opaque type emits a public .unsafe constructor (ADR 0182) — its representation is hidden, so its defining commons needs one; a refined or named type emits none, so no host or adapter code can brand a value past the refinement predicate. A refined type is constructed through .of and compile-time literal admission (type-system §6.4); an admitted literal lowers to an inline brand cast (§7.3.2, below), not a constructor call.

A brand is a compile-time TypeScript intersection (a phantom field); it is erased after type-checking and has no runtime representation. A sum type lowers as:

export type Status =
{ readonly tag: "Pending" }
| { readonly tag: "Shipped"; readonly tracking: string };
export const Status = {
Pending: { tag: "Pending" } as Status,
Shipped: (tracking: string): Status => ({ tag: "Shipped", tracking }),
};

Decimal (#2622) lowers to a plain object { readonly coefficient: bigint; readonly scale: number }, written inline wherever the type appears (no import). A literal is the object literal (1.20d is { coefficient: 120n, scale: 2 }). +, -, *, unary -, == and the kernel methods call the runtime’s decimal module (__bynkDecimalAdd, __bynkDecimalEqual, __bynkDecimalRound, …); the ordering operators use __bynkCmpDecimal. A refined Decimal’s .of tests its predicates inline over the bigint coefficient. The bigint coefficient is what marks a value as a decimal to the runtime’s structural == and Key walkers.

The other base types lower to TypeScript primitives: Int and Float both emit number (v0.21 — the distinction is checker-side only and erased), String emits string, Bool emits boolean. A refined Int’s .of includes a Number.isInteger check; a refined Float’s .of includes Number.isFinite instead — validated Float values are finite (0040).

A Bynk name is emitted as written, so every name the emitter adds is chosen so that no Bynk name can collide with it. The emitted code MUST compile under tsc --strict whatever names the program declares:

  • Host globals are reached through globalThis (globalThis.JSON.stringify, new globalThis.Error(…), globalThis.Promise<T>), so a user type or function named Error, JSON, Record, Set or console cannot hide them. A parameter or local named globalThis is emitted as __id_globalThis, and a declaration of that name (a type, function, agent, provider, …) is rejected (bynk.resolve.reserved_host_name). String is the one global emitted bare: it is a Bynk keyword, so nothing can declare it. A capability’s injection token is therefore typed symbol, not unique symbol: TypeScript only gives a bare Symbol(…) call a unique type.
  • Runtime names are imported under a __ alias (__JsonValue, __BoundaryError, __matchPath), and the generated codec helpers are __serialise_<T> / __deserialise_<T>. A Bynk identifier cannot begin with _, so none of these can be spelled by a program.
  • Shadowing. A let, a parameter and a pattern binding (match arm or is) each get their own emitted identifier when they re-bind a name already in scope, so if o is Some(o) reads the outer o and let x = x + 1 after a parameter x does not redeclare it.
  • Sum payload fields. A variant object carries the in-memory discriminant tag, so a payload field named tag is emitted as the property $tag; its wire key is unchanged. The variant constructor binds each field as a parameter, so a field named like a reserved word (class, arguments) is renamed there and keeps its own property and wire name. On the wire a variant is a flat { "kind": "<Variant>", … } object, so a payload field named kind is rejected (bynk.resolve.reserved_payload_field).
  • Module format. The emitted files are ES modules. The output root always carries a generated package.json declaring "type": "module" (#2148), and the emitted tsconfig.json’s module: NodeNext follows it, so tsc checks and builds the output as ES modules under the rules Node runs it with. Down-levelled to CommonJS, tsc reserves the top-level names require, exports and (from TypeScript 7) Object, so a type named Object or a function named require would fail with TS2441. A hand-written binding is held to the same rules: relative imports name the .js file ("./runtime.js"; an extensionless one is TS2835), and CommonJS idioms (require, module.exports, __dirname) are not available. bynk test also marks its tsc output directory ES modules for Node (#2146). A user who runs the tsc-built JavaScript (out-js, inside the output root) with plain node gets the output root’s "type": "module" package.json; a copy moved elsewhere needs one above it.

A constant (const Name: T = e, §5.12b) emits as an exported, hoisted function of its declaring module that returns its value, typed by its annotation. The value is computed from e, lowered as an ordinary expression, on the first call and cached in a module-level var:

var __const_MaxRetries: { v: number } | undefined;
export function MaxRetries(): number { return (__const_MaxRetries ??= { v: 3 }).v; }
var __const_DefaultPage: { v: Page } | undefined;
export function DefaultPage(): Page { return (__const_DefaultPage ??= { v: { size: PageSize(), offset: 0 } }).v; }

Every reference to a constant is a call, Name(): in its own file, in a sibling file or a unit that uses it (which import it under the same name, as they import a function), in another constant’s initialiser and in a suite case. The { v } box keeps a value that is falsy or null cached, so e runs at most once.

A function declaration and a var are both hoisted, so a constant can be read before its module has evaluated. When the files of a unit import each other in a cycle, through a constant, a function or a type, the order in which ES modules evaluate cannot reach a constant before it is initialised. A module’s constants come after its types and before its functions, in declaration order. A module that declares no constant emits exactly as before.

ConstructEmits
if … else …a conditional / if
matcha switch on .tag, payload fields bound as const
match with a record pattern, a list pattern, a range pattern, a guard, or a nested refutable patterna sequence of if blocks, one per arm: each tests its refutable sub-patterns (a record pattern tests each refutable field against scrutinee.field; a list pattern tests scrutinee.length === n, or scrutinee.length >= n with a rest marker, then each refutable element against scrutinee[i]), binds names as const, then runs the guard and body; a range pattern tests scrutinee >= lo && scrutinee <= hi, or the one side an open range has; a record pattern adds no tag test, and [..] adds no test at all
a list pattern’s ..restconst rest = scrutinee.slice(n); after the n elements before it. Binding it copies the remaining elements, so it costs O(length − n) per match: a recursive [x, ..rest] => f(rest) is O(length²) overall, and the kernel folds are the way to iterate. [..rest] binds the scrutinee itself with no copy, which is unobservable because no list is ever mutated in place; a bare .. copies nothing
admitted literalan inline brand cast (literal as T) (§6.4; ADR 0182)
float literalthe source lexeme verbatim (1e10 does not normalise)
string literalthe decoded value as a double-quoted TypeScript string, whatever form it was written in (§3.2.2): \\, ", \n, \t and \r as those escapes, and any other control character, \0 included, and U+2028/U+2029 as \u{…}; every other character, non-BMP ones included, is written as itself
interpolated stringa template literal: chunks as escaped text (backslash, backtick, and $ escaped), each \(e) hole as ${String(<e>)} (ADR 0075)
Int / IntMath.trunc(a / b) — truncating, unchanged
Float / Floata / b — true division (v0.21, operand-typed)
numeric kerneli.toFloat() → the receiver (erased identity); f.round()/floor/ceil/truncate → Math.round(f) / Math.floor(f) / Math.ceil(f) / Math.trunc(f); x.toString() → String(x) (host number→string, ADR 0074)
?a check-and-early-return: on a Result, if (r.tag === "Err") return r; (or, when a declared embedding converts the error (v0.154), return Err(F.V(r.error));); on an Option in an HttpResult handler (v0.153), if (o.tag === "None") return HttpResult.NotFound; — then the expression is the Ok/Some payload
unreachable(m) / todo(m) (#2620)a call of the runtime’s never-returning __fault("Unreachable" | "Todo", m, "path:line:col") (§7.4): it throws, so it is an expression of any type, and inside an async body it rejects the effect
<-await
e.detach()__bynkDetach(<e>, deps.__exec, "path:line:col"[, "<ErrType>"]) — hands the running effect to waitUntil and reports a failure (§7.4.17); the type name is passed only when e is an Effect[Result[_, E]]
e.within(d)__bynkWithin(<e>, <ms>, deps.__exec) — races the effect against a timer and yields Ok(value) or Err({ after }); the handler receives __exec when its body calls within, as it does for detach (§7.4.14)
a.race(b)__bynkRace([<a>, <b>], deps.__exec) — resolves with the first effect to succeed and hands the others to waitUntil; a chain a.race(b).race(c) is one call over [a, b, c]; the handler receives __exec when its body calls race, as for within (§7.4.15)
par { let a <- e1 let b <- e2 }const [a, b] = await __bynkSettleAll([() => e1, () => e2]); — the join calls the thunks in source order, issuing each effect before either is awaited; a do binding takes a hole in the pattern (§7.4.13)

An Effect[T] is realised as a Promise<T>; it has no runtime constructor. Effect.pure(x) lowers to x directly where an async context absorbs it, and to Promise.resolve(x) in a synchronous or tail position. The <- bind is therefore await and needs no runtime support.

Recursion (§5.2) lowers to direct recursion in TypeScript: a recursive call is an ordinary call, except a direct self tail call, which an emitter MUST lower so that it consumes no stack in proportion to the number of calls (below). The depth a program can reach through any other recursion is host-defined, as Float arithmetic is (ADR 0042): it depends on the platform’s stack size and on how far the host has optimised the function, so it is not a fixed number, and this specification states no limit. Exceeding it raises the host’s stack-overflow error, which is a fault (§5.9e): a handler that faults this way commits no store writes, as any fault does (ADR 0109), and a test case that hits it fails.

A self tail call is a call whose callee is the enclosing function itself (a free function by name, a method by receiver or qualified name), at the function’s own type arguments, in tail position. Tail position is the function body’s final expression, propagated through the branches of an if, the arms of a match (guarded arms included) and the final expression of a block. A call is not in tail position when it is an argument or a receiver, operand of ?, inside a lambda or a par, within or race, bound by a let, or wrapped (Some(f(x)), Effect.pure(f(x))). Such a call is lowered as a loop: the body runs inside a labelled while (true), and the call evaluates all of its new arguments, then rebinds the parameters and continues the loop. The guarantee holds for Effect-returning functions too: the awaits ahead of the call are unchanged, the call does not extend a chain of promises, and the order of effects is that of the unrewritten program.

Three properties of the rewrite are normative. Bindings are per iteration: a lambda created in one iteration captures that iteration’s parameters, not the next’s. requires is checked on every iteration, against the arguments of the call that began it, so a contract violation is reported for the iteration whose arguments violate it. A function with an ensures clause is not rewritten, in any profile: a loop has one frame, so a postcondition could be checked only for the outermost call, and the function keeps direct recursion (host-defined depth).

Nothing else changes: mutual recursion, a call through a function value, a non-tail self call, and a self call at a different instantiation of a generic function are ordinary calls, with host-defined depth. The guarantee is on the shape of the emitted program, not on a depth, so it names no number.

An effectful function’s body is an async function, so the host’s stack is not the limit when each level awaits before it recurses, even where the recursive call is not a self tail call. In the repeat example of §5.2, do step(n) awaits and the call is a tail call, so it is a loop. A non-tail recursive call made before the body’s first await (for example let r <- repeat(n - 1, step) as its first statement) still descends on one stack and is limited as synchronous recursion is.

A par block (§4.8.7b) lowers to one await of the join over a thunk per binding. The join calls the thunks in source order, so each effect is issued before the next binding is evaluated and before any is awaited; a binding’s hoisted statements sit inside its thunk, so they run at its turn. A thunk that throws synchronously (a check that fails before a promise exists) becomes a rejected entry, so an earlier effect is never left unawaited. A binding with a type annotation types its thunk’s result ((): Promise<T> => …), so the destructured name has the type const x: T = await e gives it. A re-bound name takes a fresh identifier as for <-, and the names are bound only after every expression is lowered. The join is imported only by a module that has a par block, so every other module emits byte-for-byte as before. The parTraverse family imports it too, in a module with no par block.

A detached effect (e.detach()) lowers on the Workers target to __bynkDetach(<effect>, deps.__exec, <site>): the effect’s Promise is handed to the execution context’s waitUntil rather than awaited, so it settles after the handler returns its response instead of being cancelled with it. The execution context is threaded from the entry point (fetch/scheduled/queue’s third argument) through compose(env, ctx) into the handler’s deps.__exec — but only for contexts that contain a detach, so a context that never uses detach emits byte-for-byte as before. This is the immediate delivery tier; a buffered/at-commit tier is reserved for the events channel and is not yet emitted. waitUntil only keeps the effect alive past the response: nothing awaits or retries it, so the send is best-effort. A failure is never returned to the handler, but it is reported: __bynkDetach passes a fault on unchanged as a rejected promise into waitUntil, the mechanism of __bynkReportFault, and logs an Err of an Effect[Result[_, E]] as one structured console.error record carrying the site, the error’s type name and, for a sum, its variant tag, never its payload (§5.5, Delivery guarantee; ADR 0106, #3437).

A function, which has no deps, receives the execution context as a hidden trailing parameter (#2719). A function in the needs-context set (§4.8.5, The execution context in functions) is emitted with a final __exec parameter, after any comparator witnesses; detach, within and race lower through it (__exec.waitUntil(…)), every call to the function passes the caller’s context as the last argument (deps.__exec in a handler, its own __exec in another function, the harness’s double in a test case), and a function named as a value is wrapped in a closure that passes the context in scope. A service handler whose body uses a construct, or calls or names a function in the set, receives __exec in its deps (and on Workers its entry point and compose thread the request’s context). The parameter is not part of the function’s Bynk signature, and a function outside the set emits byte-for-byte as before.

A context function that declares given (#2868) likewise takes a hidden deps parameter, after any comparator witnesses and before __exec. Its type is an object of exactly the capabilities the function names, so a capability call in the body (a lambda included) lowers as in a handler (deps.Logger.error(…)). Every call passes the caller’s own deps on, which carries them because the caller must declare them (§5.3, Capabilities), and a function named as a value is wrapped in a closure over the deps in scope where it is named. A function with no given emits byte-for-byte as before.

An agent emits a state interface, a zero-value factory that realises the field zeros and initialisers of §5.4, and a class whose handlers read through loadState and write through commitState:

function __zeroOfCounterState(): CounterState { return { count: 0 }; }
// loadState(): return stored ?? __zeroOfCounterState();

A store Map, Set, Cache or Log field is held in the state as an insertion-ordered handle (StoreMap, StoreSet, StoreCache, StoreLog), not as a plain object: a JS object enumerates integer-like keys ("2", "10") ahead of every other key, by value, so it cannot keep the insertion order that §6.2.3 makes normative. A Map handle also holds the posting lists of its @indexed fields. The stored record is unchanged in form: each collection is written, and read back, in insertion order, on bundle and on workers alike. State written in the per-entry layout carries each entry’s insertion order; a record still in the earlier wholesale layout has none, so its integer-like keys are read in numeric order once, and the next commit stores that order.

On bundle an agent is constructed against a per-agent StateRegistry (a serialised-key-to-state map, reset between tests); on workers it is a Durable Object addressed by the agent key. A single makeAgent helper selects the path from whether a Durable Object binding is present, so call sites are identical across targets (§7.4).

The workers agent call is a boundary (#1678). On workers a call Agent(key).m(args) crosses the Durable Object’s fetch under /_bynk/agent/<m>, so its arguments and result are on a wire. They go through the boundary codec, the same __serialise_*/__deserialise_* helpers a cross-context call uses (§7.4.5). Each agent emits a wire table, const __<Agent>Wire: AgentWire, with a codec pair for each handler’s parameters and result, and __make<Agent> passes it to makeAgent. The proxy over the stub encodes the arguments and decodes the result, and the class’s fetch decodes the arguments (decodeAgentArgs) and encodes the result (encodeAgentResult). A decode failure on either side is an internal fault, not a 400: the caller is the program itself. A position whose type has no wire form (a held Connection, a function, a Stream, a Query) passes through unencoded (AGENT_WIRE_PASS). On bundle the call is in-process and no table is emitted.

Invariants (v0.80). When an agent declares invariants (§5.4.1), commitState(s) gates on each predicate (lowered as a pure expression over the proposed state s, with state fields read as s.<field> and implies as (!(P) || Q)) before storage.put. A failed predicate console.error-logs the agent type and invariant name — never the key value (ADR 0107) — and throws the dedicated invariantViolation(agent, invariant) fault, so the offending state is never written. The fault rides the existing uncaught-fault channel and surfaces to the caller as a 500-class fault, not an outcome:

private async commitState(s: OrderState): globalThis.Promise<void> {
if (!((!(__bynkEq(s.status, OrderStatus.Paid)) || (s.paymentRef.tag === "Some")))) {
console.error("InvariantViolation Order.paid_has_payment_ref",
{ agent: "Order", invariant: "paid_has_payment_ref" });
throw invariantViolation("Order", "paid_has_payment_ref");
}
await this.state.storage.put("state", __encodeOrderState(s));
}

Transitions (v0.116). When an agent declares transitions (§5.4.1-i), commitState(s) also gates on each step predicate, after the snapshot invariants and before storage.put. The old state is read from storage inside the gate — the method performs the write, so storage still holds the pre-commit value there; undefined is the genesis commit and the whole block is skipped. The bindings lower to __old/__new (new is a JS reserved word), and a failed predicate throws the same invariantViolation(agent, transition) fault:

const __prior = await this.state.storage.get<OrderState>("state");
if (__prior !== undefined) {
const __old = { ...__zeroOfOrderState(), ...__prior };
const __new = s;
if (!((!(__old.status.tag === "Paid") || __new.status.tag === "Paid"))) {
console.error("InvariantViolation Order.paid_is_terminal",
{ agent: "Order", invariant: "paid_is_terminal" });
throw invariantViolation("Order", "paid_is_terminal");
}
}

On the workers target, each context with HTTP handlers emits handlers.ts (the handler logic), index.ts (the router and boundary validation), compose.ts (the wiring), and a wrangler.toml. A handler’s HttpResult[T] (§5.7) determines the HTTP status and body of the Response; records crossing the boundary are serialised and deserialised through the generated __serialise_* / __deserialise_* helpers.

The router MUST answer the method contract derived from the declared routes. For each path, the allowed-method set is the union of the methods declared on it, plus HEAD when GET is declared, plus OPTIONS. A GET dispatch block also accepts HEAD: the GET handler runs and its Response is returned with the body stripped (headResponse — same status and headers, empty body, the source body never read). When no dispatch block matches, the router MUST test the request path against each known path: on a match, a plain OPTIONS (one that does not carry Access-Control-Request-Method) is a 204 and any other method is a 405, both carrying Allow = the path’s allowed-method set; on no match, the response is 404. The synthesised 405/OPTIONS answers are produced before the handler authentication seam (method discovery and rejection are credential-less, as with the CORS preflight); a HEAD runs GET’s seam unchanged. These are synthesised router responses and do not touch the HttpResult sum.

A route whose effective JSON mode is plain (§5.7.5) serialises its Ok, Created and Accepted body through withPlainJson(serialise_T). The one generated __serialise_Option_* encoder carries both forms: while withPlainJson has set the flag __bynkPlainJson (a globalThis property), it writes Some(v) as v and None as null; otherwise it writes the tagged object. The flag is set only for that one synchronous serialisation and restored afterwards, and the plain branch is emitted only in a project that has a plain route or a source file that mentions Json.encodePlain, so a project with neither is byte-for-byte unchanged.

Json.encodePlain(v) lowers to the same JSON.stringify(__serialise_<T>(v)) as Json.encode, inside an inline synchronous arrow that sets __bynkPlainJson, runs the serialisation, and restores the flag in a finally. It needs no runtime import. An argument whose text awaits is first bound to a temporary.

A service that declares a cors { } policy (§5.7.1) additionally emits, in index.ts, a synthesised CorsPolicy constant plus two behaviours. First, a preflight branch — an OPTIONS that carries Access-Control-Request-Method and matches any of that service’s route paths — returns corsPreflightResponse(policy, origin), a 204 carrying the Access-Control-* headers; this branch MUST precede the route dispatch, so a preflight is answered before the handler authentication seam (a preflight carries no credentials and MUST NOT be rejected by a by/Bearer check). A bare OPTIONS (without that header) is not a preflight and is answered by the generic method-contract fall-through above. Second, each of that service’s route responses — and its synthesised 405/OPTIONS — is wrapped in applyCors(response, policy, origin), which stamps Access-Control-Allow-Origin (reflecting a matched allowlist origin with Vary: Origin, or emitting * for a wildcard policy; omitting the header — fail closed — when the origin does not match). Allowed methods are derived from the service’s routes (the same derivation as the Allow header — so HEAD appears when GET is declared); allowed headers default to content-type (plus Authorization when the service has a Bearer route). A service without a cors { } policy emits neither CORS behaviour and, apart from the always-on method contract above, is otherwise unchanged.

§7.3.4a Actors & the verification seam (v0.45)

Section titled “§7.3.4a Actors & the verification seam (v0.45)”

An actor declaration emits no TypeScript — like a brand, it is a compile-time contract. The handler by clause (§5.7a) lowers through a per-scheme verification seam that mirrors the protocol descriptor: a scheme contributes its verification codegen, identity shape, and failure mapping behind one interface. The two zero-crypto schemes add no topology: None always admits, and Internal reuses the channel-trust assertion already implicit in the service-binding and platform-dispatch entry points — so a handler with a by clause emits byte-identically to one without. The bound identity (<binder>.identity) is minted at the seam; for the zero-crypto schemes it is the sealed unit value. Bearer (v0.47) extends the seam with real verification: the compose wrapper extracts Authorization: Bearer …, HS256-verifies the JWT (verifyBearerJwtHs256 in the runtime) against a secret sourced from env, enforces exp/nbf, and mints the identity by constructing the declared type from the sub claim — returning HttpResult.Unauthorized (401) fail-closed on any failure, before the body. The minted identity threads through the handler’s deps, so <binder>.identity reads the verified value. Signature (v0.51) verifies an HMAC over the request body for inbound webhooks. Because the signature is over the raw bytes, its seam sits in the entry dispatch (where the body is read): it reads the body once as text (await request.text()), sources the secret from env, recomputes HMAC-SHA256 and constant-time-compares (verifySignatureHmacSha256 in the runtime, via crypto.subtle.verify) against the configured signature header (accepting a bare hex digest or a sha256=<hex> prefix), optionally checks a signed timestamp is within tolerance of now (binding <timestamp>.<body> as the signed string), then hands the same text to body deserialisation — never a re-read or a re-serialisation. Any failure → HttpResult.Unauthorized (401), fail-closed, before the body. A Signature actor carries no identity.

Oidc (v0.151) extends the seam like Bearer, but verifies against a provider’s public key set instead of a shared secret. The compose wrapper extracts Authorization: Bearer …, calls verifyOidcJwt (in the runtime) with the declared issuer/audience/jwks literals, and mints the identity by constructing the declared type from the verified sub claim — returning HttpResult.Unauthorized (401) fail-closed on any failure, before the body. The verifier fetches the JWKS (cached, refetched on a kid miss for key rotation — rate-limited by a cooldown so an attacker-chosen kid cannot amplify into fetches), imports the matching RS256/ES256 public key, verifies the signature (crypto.subtle.verify), and enforces the trust contract — iss equals the declared issuer, aud contains the declared audience, exp is in the future, nbf (if present) has passed. Because no secret is named the wrapper sources nothing from env; the trust parameters are the actor declaration’s public literals. The minted identity threads through deps exactly as Bearer’s does.

A multi-actor sum (by who: A | B, v0.52) composes these seams under first-wins resolution in a single boundary wrapper, which owns the whole boundary so the request is read once. When any member verifies over the body (a Signature peer) or the handler takes a body, it reads the raw body once as text; it then tries each member’s scheme in declared order — a Bearer peer against the Authorization header, a Signature peer against those held bytes, a None peer accepting unconditionally — and binds the first success into a tagged { tag: "<Actor>", identity?: … } value threaded through deps.who, which the body matches. If no member verifies, the wrapper returns HttpResult.Unauthorized (401) fail-closed, before the body; otherwise it parses the body param from the same bytes and dispatches. No member re-reads the request — composing a header member with a body member never re-reads or re-serialises.

A refinement actor (actor Admin = User where <claim predicate>, v0.53) adds an authorisation check to its base’s seam. The Bearer base verifies as above (failure → 401); the seam then surfaces the verified claims (verifyBearerJwtHs256 now returns them alongside sub) and evaluates the lowered claim predicate against them — a failed invariant returns HttpResult.Forbidden (403, distinct from the 401 authentication channel), before the identity mints or the body runs. The claims are an authorisation-time input only: the body still sees just the sealed base identity (<binder>.identity), so claims are not threaded into deps.

The Caller actor (on call … by c: Caller, v0.54) mints a live CallerId over the cross-context Service Binding. The call site (callService) stamps the calling context’s qualified name — a compile-time constant — into a reserved X-Bynk-Caller header beside the (unchanged) args body. The callee’s /_bynk/call/<service> dispatch reads the header and threads the name into the handler’s deps as the CallerId identity, so <binder>.identity lowers to deps.identity (replacing the undefined placeholder). A binder-less on call reads no X-Bynk-Caller header. The name is proved, not claimed: the request’s signature (§7.3.4d) is checked under the key the callee holds for the edge from that caller, so a request whose caller is absent, or holds no key there, never reaches the dispatch.

§7.3.4b The cross-context boundary codec (v0.176)

Section titled “§7.3.4b The cross-context boundary codec (v0.176)”

Every value crossing a workers cross-context boundary is encoded and decoded by a generated codec — the same __serialise_* / __deserialise_* helpers §7.2 requires, monomorphised per instantiation. No wire position asserts a value with an as JsonValue cast, and no return type decodes through an unvalidated identity function.

The boundary is therefore symmetric by construction: the same dispatch names the serialiser and the deserialiser, so a type cannot be encoded one way and decoded another. This is what admits a bare Bytes in a cross-context signature — it base64-encodes outbound and base64-decodes (with validation) inbound. Before v0.176 the boundary carried its own codec dispatch, which cast a Bytes outbound while decoding it inbound; the resulting mis-encode was diagnosed rather than emitted (ADR 0142 D8). With one dispatch, the asymmetry — and so the restriction — is gone.

Each Worker is self-contained: a context generates its own codecs for the contracts it participates in and imports no sibling context’s module as a value (#661, discharging ADR 0199 Decision G). A caller reaches its callee’s codecs through local __serialise_* / __deserialise_* helpers it emits itself; the callee module is imported for types only (import type * as <ns>), which is erased outright, so the caller’s bundle never carries the callee’s provider implementation. Only the callee’s own exported types reachable from the services the caller actually calls are generated — commons types the caller already holds are left alone, and an uncalled service contributes nothing.

A caller-side codec for a callee-owned type cannot route through the owner’s .of constructor (it lives in the owner’s module), so validation follows the export visibility: an opaque type validates its base and casts — its refinement is the owner’s secret and is not re-checked, which is sound because the value came from the owner’s typed code (the only decode of one is the generated decode of the owner’s own service reply: Json.decode, a Codable witness and a handler input cannot name one, bynk.context.external_decode) and a skewed owner is caught by the §7.3.4c contract hash — while a transparent refined type inlines its predicate, since the consumer knows the shape by declaration. This applies to consumed contexts under workers only: a consumed adapter’s binding namespace is a real value import used by the composition root, and on bundle the contexts compile together.

One position remains deliberately not codec-checked, stated here rather than left to be discovered: the runtime-owned error types (ValidationError, DecodeError, HttpResult, QueueResult) pass through uncoded. They are declared by the runtime rather than by a type declaration the emitter can walk, so there is no helper to generate; their JSON shape is fixed by the runtime, so the pass-through is unchecked rather than wrong.

A recursive type’s codec is depth-bounded on both sides (#2656, §7.2): a callee refuses an argument nested past the bound with a 400 StructuralMismatch, and a caller or callee that would encode one faults instead of sending it, so a value one side rejects is never on the wire.

A cross-context call carries a contract hash beside the caller identity: a reserved X-Bynk-Contract header holding a compile-time constant, exactly as §7.3.4a’s X-Bynk-Caller does. The args body is unchanged.

The constant is the canonical normal form of the callee’s on call contract, hashed. The form is deterministic and order-insensitive where the wire is: refinement predicates canonicalise as a set, and record fields and sum variants sort by name — a JSON object is unordered and a sum carries a kind discriminant, so their order is not wire-observable and MUST NOT change the hash. Field presence, field types (an inline field refinement included, as a predicate set), parameter names, parameter order, and the return type all MUST change it. An opaque type contributes its representation but not its predicate: a consumer cannot observe that predicate, so it is not part of the contract between them. A field’s default (and whether it has one) is not part of the form either, so it MUST NOT change the hash. The stored structured form (the shape the compatibility classifier reads) does record whether a field has a default: a receiver’s field with one MAY be absent from the sender’s value, as an Option field may, because a body without the key decodes to the default (§5.2b).

Caller and callee canonicalise the callee’s contract in the callee’s own namespace, from the callee’s own type table. A caller MUST NOT canonicalise a consumed type in its own namespace, where rebranding would render the same type differently.

The callee compares the header against its own constant before parsing the request body — and so before the caller check — and on mismatch answers 409 with a ContractMismatch body naming the service, the expected hash, and what arrived. Once the contracts disagree the body’s interpretation is precisely what is in doubt, so validating it first would misreport the fault. An absent or empty header is a mismatch: a Bynk caller always stamps one.

ContractMismatch is not a BoundaryError — a codec cannot produce it — so the call surface is typed CallError = BoundaryError | ContractMismatch (§7.4).

Each Worker also emits bynk-contracts.json beside its wrangler.toml, carrying what the context provides per service and what it expects of each dependency, and the structure behind each hash (provides_shapes, expects_shapes) so the driver can classify a skew as compatible or breaking. When the project’s bynk.contracts.lock lists older contracts a service still accepts, the manifest records their hashes under accepts, and the Worker entry admits an X-Bynk-Contract that equals the service’s own hash or any of those. This is a driver artefact, not part of the wire. A context that declares a foreign caller also records, under foreign, the hash each such caller may call each service at, and gets a typed TypeScript client beside it, bynk-client.ts, for that caller’s build (TypeScript client). The client imports @bynk/wire-client and is excluded from the emitted tsconfig.json.

/_bynk/call/ and /_bynk/event/ are paths on the Worker’s single fetch entry, so they answer on every route the Worker serves, its workers.dev address included. The prefix does not prove that a Bynk Worker sent the request, so every internal request is signed, under a key one sender shares with one receiver: an edge.

An edge is a Service Binding between two of a project’s Workers: a caller to a context it calls, or a publisher to a subscriber its events fan out to. The receiver holds the edge’s key as BYNK_CALL_FROM_<SENDER> and the sender as BYNK_CALL_TO_<RECEIVER>, the qualified context name upper-cased with each dot written __. callService and the events fan-out’s deliverEvent sign each request with HMAC-SHA256 over the fields the wire format reference lists (the sender, the receiver, the method, the path, the contract and wire headers, a timestamp and the body’s SHA-256), and send the sender’s name, the timestamp and the signature in X-Bynk-Caller, X-Bynk-Timestamp and X-Bynk-Signature. They refuse to send without the edge’s key, naming it.

The receiving Worker verifies as the first step of each internal dispatch, after only the call dispatch’s method check. __verifyCall reads the body under a 1 MiB cap (else 413), picks the key it holds for the edge from the claimed sender, and checks the timestamp (within 300 seconds of its clock) and the signature, in constant time; any failure is 401 with the body Unauthorized and no detail. It runs before the service is looked up, before the §7.3.4c contract check and before the body is parsed, which then parses the verified text. It applies to every on call and every event subscriber, whether or not the handler binds a Caller. So a sender without a key cannot tell services apart (no 404 against 409), never has a contract hash echoed back, and cannot write the skew log line; and a key’s holder can claim only its own name. A captured request can be replayed until its timestamp leaves the window.

bynk deploy mints each edge’s key and sets it on both ends. bynk dev and the generated test harnesses give every edge a fixed local key, which is never written into a generated wrangler.toml; the harness calls its participants as integration.

Foreign callers (#1971). A context that declares Foreign actors admits callers that are not Bynk. Its entry holds a table of them, __FOREIGN_CALLERS (actor name → secret), and passes it to __verifyCall. A request naming one of them as its caller is verified under that actor’s secret rather than an edge key. An actor’s name starts with a capital letter, and an edge name cannot, so neither kind can pass for the other. Each service case then checks admission, after the service is found and before its contract: the caller must be one its handler’s by clause admits. A context is admitted by Caller (the default), a foreign caller only by its own actor. Anyone else gets 403 with the body Forbidden. For a call sum (by who: Caller | Legacy) the case builds the resolved actor, { tag: "Caller", identity: <name> } or { tag: "<Actor>" }, and passes it into the handler’s deps as who. A context with no Foreign actor emits neither the table nor the check.

The request a /_bynk/call/ dispatch accepts, the order of its checks with their statuses and error bodies, the JSON encoding of every boundary type and the contract hash’s normal form are a published surface with its own version, apart from the emitted TypeScript: the wire format reference, generated from the compiler and guarded against it. A caller states the version it speaks in X-Bynk-Wire (absent means 1); the callee accepts a range and refuses any other version with 400 UnsupportedWireVersion.

The dispatch makes its checks in the published order: the method (POST, else 405 with Allow: POST), the body’s size and the signature (§7.3.4d), the wire version, the service (404), the caller’s admission (403, §7.3.4d), the contract (§7.3.4c), the body’s JSON (the verified text, parsed, else 400 MalformedJson), then the arguments (§7.3.4b). A record field’s inline refinement is checked when the record is decoded, failing as a RefinementViolation at the field’s path, and a Duration or Instant must be a safe integer wherever it appears.

Each test unit emits a per-target test module; an aggregating runner (tests/main.ts) collects the module results. An assert (§5.9) lowers to a runtime check that throws on failure, which the runner records as a failing case. bynk test emits these modules, compiles them with tsc, and runs the aggregated runner on Node (§8.4).

ConstructEmits
function type A -> Bthe TS function type (a0: A) => B (an Effect return is Promise via the ordinary lowering)
lambdaa TS arrow — async exactly when its checked type is effectful; written annotations transcribe, omitted ones rely on TS contextual typing in argument position
lambda block bodythe same statement lowering as a function body
named function as a valuethe function’s TS identifier, unchanged
value applicationa TS call
generic functionan erased TS generic (function name<A, B>(…)) — no runtime type-argument dispatch

A contracted pure function (requires/ensures, §5.4.1a) emits behind a build-profile switch (ADR 0150). In the dev/test profile (bynk test, --inspect) the function is wrapped by a call-site guard: each requires is checked on entry and each ensures on exit (over the bound result), throwing a contract failure that names the clause and the offending arguments/result. The guard is emitted once around the definition (O(1) in code size), not at each call site. In the release profile (bynk compile) the guard is stripped entirely — the emitted function is identical to an uncontracted one, so contracts add no production cost or behaviour. The runner attack (§7.4.10) is emitted only alongside the guard.

A case that observes a capability (expect Cap.op called … or trace(Cap.op), §5.9b) emits behind the same build-profile switch as contracts (ADR 0150). In the test profile the case’s deps object is wrapped by a recording proxy — for each observed operation, the seam function is replaced by a wrapper that appends { args, order } to a per-op log (__obs) and then delegates to whatever stands behind the seam (a stub or the real provider), so the return value is unchanged. The sugar lowers to reads over that log (called → length checks; with <pred> → a filter over the recorded args using the lowered predicate; before → an order-index comparison); trace(Cap.op) lowers to the recorded list mapped to per-op records, with a synthetic type __Cap_op_Call = { … } alias emitted so the records type-check. The proxy, the log, and the alias are emitted only in the test build; a module with no observation emits byte-for-byte unchanged, and the deploy build calls the seam directly — observation adds no production cost or behaviour.

A case’s tier (§5.9c) resolves how each seam is provided, per build, behind the ADR-0147 build strip — a suite is a test-only declaration, so all of this machinery is test-build-only and never reaches the deploy build.

For each capability seam the unit under test consumes, the emitter resolves the provision in precedence order case provides > suite provides > the tier default (§5.9d):

  • The tier default. unit and integration emit in process with the real provider for any un-overridden seam (full unit auto-stubbing is a named follow-on); system stands the inferred participants up as Workers and wires them across the real serialise → JSON → deserialise boundary (§7.4.5), the participant set being the target’s transitive consumes closure.
  • A stub override lowers to a stub object behind the recording proxy (§7.3.5c), so a case can both stub a return and observe the call. The method’s clauses become an ordered match over the recorded arguments (the predicate surface lowered as in observation’s with), first match wins:
    • returns <value> lowers to a constant return of the lowered value;
    • fails lowers to a thrown capability fault (never an Err), which a case observes with expect <call> faults;
    • returns each [<outcome>, …] lowers to a per-call cursor over the lowered outcomes with last-outcome-repeat exhaustion (see §7.4.12).

Provision is resolved once per case; the stub, the cursor, and the match table are emitted only under bynk test. A module with no suite emits byte-for-byte unchanged.

A fault claim expect <call> faults lowers to an async IIFE inside the expectation check: it awaits the lowered call in a try, under the claim’s own call-site principal (#1812) supplied exactly as an effect-let’s is and never an enclosing one, yields false when the call returns, re-throws an ExpectationError, and yields true for any other thrown value (§7.4.12a). The check reports the call returned without faulting when it fails.

An adapter’s contract emits like a context’s: each capability becomes a TypeScript interface plus an injection token, and its types emit per §7.3.1 into the adapter’s module (<adapter>.ts). An external provider emits no class — its implementation is the class of the same name that the binding module MUST export, and implements <Interface> against the generated interface is the contract between the two halves, checked by the tsc --strict gate (§8.4).

A capability operation’s own type parameter (v0.235, ADR 0281) emits as a genuine generic interface method — dedup<T>(key: string): Promise<Option<T>> — not an erased/monomorphised one, since the implementing class is hand-authored TypeScript, not compiler-generated. Unlike a generic function (above) or Json.decode[T] (which specialises a runtime codec per call and needs no TS-level generic at all), a capability operation’s T is a pure type-level parameter with no runtime codec to specialise, so nothing at the call site lets tsc infer a return-position-only parameter — the call site therefore names the type argument explicitly too (deps.Cap.op<SomeType>(…)).

An operation with Codable parameters is emitted without them in the interface (ADR 0696): each parameter that mentions one is unknown, a JSON value in the boundary encoding, and a type parameter that then occurs nowhere else is dropped. A typed read (#3458) does the same to its return: the interface returns Promise<unknown>, the provider replying with plain JSON and never receiving a codec. The call site wraps the call in __bynkCapabilityReply(call, codec, { capability, operation, type }, policy) (__bynk_runtime/codec.ts), which decodes the reply as the instantiated Effect payload with that payload’s codec. policy is the operation’s declared "fault" (the promise rejects, with the capability, operation, type and $.path of the first mismatch) or "miss" (console.warn, then None). A provider that itself rejects rejects whichever the policy, and the value never appears in either message. A test double for such a capability keeps the JSON a write was given and returns it before the call-site decode.

The binding module is copied verbatim into the output beside the adapter’s emitted module, so its imports resolve and the gate checks it. It is checked as an ES module (see Module format in §7.3.1). Its declared requires dependencies are folded into the generated package.json.

The composition root instantiates an external provider from the binding module’s namespace. A provider with a given clause receives a by-name deps object: each key is the given name, each value the recursively instantiated provider of that capability — a bare name resolving through the provider’s own unit’s flattened consumes (§5.8), so an adapter’s dependency on another adapter pulls that adapter’s binding into the same compose, transitively:

const Jwt = new tokens__binding.JoseJwt({
Secrets: new bynk__binding.SecretsProvider(),
});

Provider selection is per build — a test-scoped stub overrides a local provides, which overrides the adapter default — but instances are per-compose: each consuming context constructs its own.

The first-party bynk adapter — the ambient surface: Clock, Random, Logger, Fetch, Secrets — is injected as a synthetic unit when any unit consumes it, and flows through this same pipeline. It has no binding clause; the toolchain supplies one per platform (bynk-<platform>.ts, selected by --platform, §8.5). Because the contract names canonical provider symbols, the emitted compose is platform-identical — only the imported binding module differs. On the workers target the compose passes the Worker env to the first-party providers that take it (Secrets); on bundle the binding falls back to a globalThis probe of process.env.

A platform adapter (v0.19: bynk.cloudflare, exporting Kv; v0.23 extends it — get/put/putTtl/delete/list) is injected the same way, with one toolchain-supplied binding copied to bynk/cloudflare.binding.ts. putTtl passes { expirationTtl } to the namespace (0051). list(prefix: Option[String]) -> Effect[List[String]] is a binding-side drain (0050): the cursor loops inside the host binding (env.KV.list({ prefix, cursor }) until list_complete, projecting keys[].name). The drain is eager and unbounded, normatively: a very large namespace loads every matching key. A program that needs to stop early pages explicitly with the experimental listPage (standard-library P1, #2590), one page per call; a loop over pages can be written in Bynk as a recursive function given the page-reading effect (§5.2, “Recursion”). (This paragraph previously said no Bynk routine could both recurse and hold a capability. That has never held for a function given an effectful function value, #2612.) The runtime KVNamespace interface (§7.4) carries the matching list page shape and put options parameter. Its resources exist only on the Worker env — there is no globalThis path — so its binding reads env.KV explicitly and throws a clear error when the binding is absent. The compiler’s work is derived, not injected: when a deployment unit’s closure reaches the adapter, the Worker’s Env gains a typed KV: KVNamespace field and its wrangler.toml a [[kv_namespaces]] stanza (one fixed KV binding name; the namespace id is a deploy-time placeholder). On the bundle target, composeApp gains an optional env?: unknown parameter — threaded to env-taking providers — only when a platform-native resource is consumed; native-free programs emit the parameterless signature unchanged. Consuming a platform adapter locks the deployment unit to its platform (§5.8).

(interop I5, #1972) A derived Service instance (capability Billing = Service @worker("legacy-billing")) emits a [[services]] entry with binding = "SERVICE_BILLING" and service = "legacy-billing", the Worker named as declared, and an Env member of the Service Binding type. Its provider, WorkersService, reads env.SERVICE_BILLING per call, sends through the binding’s fetch with Fetch.send’s header and response rules, and throws a clear error when the binding is absent. Neither instance kind adds the bare KV binding.

(v0.20b) The collection types lower to immutable TypeScript shapes:

ConstructEmits
List[T]readonly T[]
Map[K, V]ReadonlyMap<K, V>
Set[T]ReadonlySet<T>; Set.of(xs) → new Set<T>(xs); insert/remove copy, so the receiver is never mutated; on the wire a JSON array, and a repeated element fails the decode
[a, b, c]the array literal [a, b, c]
List.empty() / Map.empty()[] as readonly T[] / new Map<K, V>(), with the checked type arguments written out

Kernel operations emit inline — typed IIFEs and spreads, no runtime imports — so a module that never touches collections emits byte-identically to v0.20a. prepend is the spread [x, ...xs], evaluating the argument first; append is [...xs, x] and concat is [...xs, ...ys], each evaluating the receiver before the argument, as written; insert copies (new Map(m).set(k, v)) — the emitted value is never mutated in place. fold, foldEff, forEach, parForEach, parTraverse, traverseAll, and parTraverseAll emit as a single loop (an IIFE; async for the effectful ones) — iteration is the kernel’s, so no user-visible recursion or stack growth exists. forEach (v0.146) is the for…await analogue of the Query.forEach terminal, awaiting each step in sequence; parForEach (v0.147) is the await __bynkSettleAll(xs.map((x) => () => f(x))) analogue of Query.parTraverse (§7.4 settleAll; it was Promise.all until #2662), issuing every element’s effect concurrently, in input order, and waiting for all of them to settle before it raises the first fault in input order — both yield Promise<void>. The collect-all pair (v0.148) return the gathered Results: traverseAll awaits each into a typed Result<U, E>[] (const __out: Result<…>[] = []; … __out.push(await f(x))), parTraverseAll is the same await __bynkSettleAll(xs.map((x) => () => f(x))) keeping the resolved array (a Result Err is a value, so nothing rejects) — both yield Promise<Result<…>[]>. The short-circuit pair (v0.150) instead thread the Result: traverseTry awaits each and return Err(__r.error) on the first Err, else pushes __r.value, finally return Ok(__out); parTraverseTry settles all first (a fault anywhere is raised before any Err is looked at), then scans the resolved Results in input order for the first Err — both yield Promise<Result<U[], E>>. Local mutation inside these loops is permitted; it never escapes.

A do e statement emits as a bare await <e>; — the binder-free form of let _ <- e (which emits const <fresh> = await <e>;), dropping the throwaway binding. A block that ends with no explicit tail (or an if with no else) returns the unit value, which erases to undefined — the same output an explicit () / Effect.pure(()) tail already produced, so no existing emission changes.

At boundaries, a List[T] serialises element-wise as a JSON array; a Map[K, V] serialises as an entries array [[k, v], …] — uniform across String and Int keys (a JSON object could not carry Int keys), and insertion-ordered, normatively. Per-instantiation helpers (__serialise_List_<T>, __deserialise_Map_<K>_<V>) follow the existing Result/Option pattern: element and entry deserialisation validates structurally, re-validates refined types, and reports StructuralMismatch with an indexed path ($.orders[3].tags[0][1]). A Map entries array that repeats a key is refused the same way, at the repeated key’s path ($.orders[3][0], expected “a distinct map key”): duplicates are detected on the decoded key (for a Decimal key, its value, so "1.20" and "1.2" are one key), never on the wire text, and the last entry does not win.

The v0.22a kernel methods lower inline, like the collection kernel — no new runtime imports beyond the Some/None/Ok/Err constructors every module already has:

ConstructEmits
string opsthe TS string method (trim, split, includes, startsWith, …); s.length() → .length; toUpper/toLower → toUpperCase/toLowerCase
s.replace(a, b)replaceAll(a, () => b) — replace-all, normatively; the function replacer inserts b literally (#1650)
s.chars()[...s] — code points, normatively
s.slice(lo, hi)slice(Math.max(0, lo), Math.max(0, hi)) — negatives clamp, no wrap
s.indexOf(sub)a typed IIFE turning -1 into None, else Some(i)
s.percentEncode() / s.percentDecode()the runtime’s __bynkPercentEncode / __bynkPercentDecode (#2594), imported only when called
regex methods (#2600)new RegExp(pattern, flags) built from the checked literal, inline flags moved into flags (matchesRegex anchored with lookarounds, (?<![\s\S])(?:…)(?![\s\S]); g for findAllRegex/replaceRegex; a sticky scan for splitRegex); test/exec/matchAll/replace, captures mapped to Option
Option/Result combinatorstyped IIFEs branching on .tag; the miss branch returns the narrowed receiver or None
Effect[Result] combinators (v0.152)an async IIFE that awaits the receiver Promise<Result<…>> and rebuilds: mapOk/mapErr branch on .tag and re-wrap the mapped side (Ok(__f(__r.value)) / Err(__f(__r.error))), else return the narrowed receiver; flatMapOk/flatMapErr await __f(…) on the matching tag, else return the receiver — yielding Promise<Result<…>>. No runtime import
numeric abs/min/maxMath.*
x.clamp(lo, hi)Math.min(Math.max(x, lo), hi)
f.isNaN()/f.isFinite()Number.isNaN/Number.isFinite
a.div(b)/a.rem(b)/a.mod(b)/a.pow(n) on Int (#2598)the runtime’s __bynkIntDivFloor/__bynkIntRem/__bynkIntMod/__bynkIntPow, each faulting on a zero divisor or a result past the safe range
a.and(b)/or/xor/andNot/shl(n)/shr(n) on Int (#2621)the runtime’s __bynkIntAnd/__bynkIntOr/__bynkIntXor/__bynkIntAndNot/__bynkIntShl/__bynkIntShr, which split each operand into hi/lo halves (native operators only below 2^31) and fault on a negative operand, a shift count outside 0..52 or an shl past the safe range
Float functions (#2598)Math.sqrt/pow/exp/log (for ln)/log10/log2/sin/cos/tan/asin/acos/atan/atan2; Float.pi()/Float.e() are Math.PI/Math.E
Int.parse/Float.parsea typed IIFE over Number(s) (full-string), rejecting empty/whitespace input, non-safe-integers (Int) and non-finite values (Float)

Json.encode(v) lowers to globalThis.JSON.stringify(__serialise_<T>(v)) for the value’s checked type; Json.decode[T](s) to a typed IIFE that JSON.parses (a throw becomes a Malformed DecodeError), dispatches to __deserialise_<T>, and maps a BoundaryError into the uniform kind/path/message record (ADR 0047). The per-type __serialise_/__deserialise_ helpers and any generic instantiations (__deserialise_List_Order, …) are emitted module-locally into each module whose code calls the codec — the same closure machinery as the workers boundary path, deduped against helpers that path already emitted. The codec runtime types (DecodeError, __JsonValue, __BoundaryError) are imported only by modules that use the codec, so non-codec modules emit byte-identically to v0.22a.

Decimal on the wire (#2622). A Decimal is a JSON string of its canonical text ("1.20"), written by __bynkDecimalToString and read by __bynkDecimalParse, which accepts an optional -, digits, and optionally . and digits (at most 1000 characters and 100 fraction digits, and no leading zero: __bynkDecimalParseWire, where the in-language Decimal.parse is lenient about it). It rejects an exponent, a leading +, whitespace, .5 and 5.; a non-string, or a string that does not parse, is a StructuralMismatch (expected: "decimal string") at the field’s path. The scale is the number of fraction digits written and survives the round trip. A refined or opaque type over Decimal parses first and then applies its predicates to the decoded value, so a well-formed string that fails them is a RefinementViolation. A Decimal is never a JSON number, because a number is read as a float by most clients. The encoding is part of a persisted agent’s stored state and is frozen with the other stored shapes.

Option[U] on the wire (#1887). __serialise_Option_<U> writes the tagged form, { "kind": "Some", "value": … } or { "kind": "None" }. __deserialise_Option_<U> is lenient, and because it is the one Option codec, the rule holds at every boundary that decodes JSON: Json.decode, an HTTP request body, a cross-context call, agent-store rehydration and a WebSocket frame. It tries these forms in order:

  1. undefined (the key is absent from the enclosing record) or null is None.
  2. An object whose only key is kind, set to "None", is None.
  3. An object whose only keys are kind and value, with kind set to "Some", is Some of value decoded as U, with errors at <path>.value.
  4. Anything else is a bare value, Some of the value decoded and refinement-checked as U.

The tagged forms win when a value could be read both ways, so a value the encoder wrote always decodes back to itself. Recognition is exact, so a tagged object carrying any other key falls to rule 4 and is decoded as a bare U; the pre-#1887 decoder ignored such keys. U’s checks are emitted once, in a module-local __option_value_<U>(raw, at) that rules 3 and 4 share. A bare value that fails as a StructuralMismatch at the Option’s own path has its expected extended with every form the decoder accepts.

Yaml.decode[T](s) lowers to the typed IIFE of §7.3.9 with one change: the text is read by the runtime’s __bynkYamlParse in place of JSON.parse. The parser returns the value as the same JSON-shaped tree, or a DecodeError of its own; on success the tree goes to __deserialise_<T> and the same error mapping as Json.decode. The runtime module (yaml.ts) is imported, and emitted, only by a module that calls Yaml.decode.

Grammar read. YAML 1.2, one document, optionally opened by --- and closed by ...: block and flow mappings and sequences; plain, single-quoted and double-quoted scalars, which may span lines (a line break folds to one space, a blank line to a newline); literal | and folded > block scalars with a chomping indicator (-, +) and an indentation digit; comments; and scalar mapping keys. Indentation is spaces: a tab is content inside a scalar or a flow collection and is never block indentation.

Resolution. A plain scalar resolves by shape under the core schema: the empty scalar and ~, null, Null, NULL are null; true/True/TRUE and false/False/FALSE are booleans; [-+]?[0-9]+, 0o[0-7]+ and 0x[0-9a-fA-F]+ are integers; [-+]?(\.[0-9]+|[0-9]+(\.[0-9]*)?)([eE][-+]?[0-9]+)? is a float, read as Number would read it; every other plain scalar is a string. A quoted scalar and a block scalar are strings. A mapping key is the text of the key. No tag, anchor or other property affects resolution, because none is accepted.

Refusal. The parser MUST refuse, with a DecodeError and no value, each of: an anchor (UnsupportedAnchor), an alias (UnsupportedAlias), the unquoted key << (UnsupportedMergeKey), a tag (UnsupportedTag), a second document (MultipleDocuments), a directive, a complex key ? …, a collection used as a key (UnsupportedSyntax), .inf and .nan in any case (UnsupportedValue), a repeated key in one mapping (DuplicateKey), and any syntax error (Malformed). The error’s path is the path ($.a.b[2]) of the value being read when it was found, $ before any key, and its message ends (line L, column C), both counted from 1.

Limits. Input longer than 1,048,576 bytes of UTF-8 MUST be refused up front (LimitExceeded, path $), and a document with collections nested more than 256 levels deep (the bound of §6.5, counted over both block and flow collections) MUST be refused (LimitExceeded) while it is read. Json.decode has no size limit of its own.

§7.3.10 Streams and WebSockets (v0.100, v0.102+)

Section titled “§7.3.10 Streams and WebSockets (v0.100, v0.102+)”

A Stream[T] lowers to a host AsyncIterable<T>, emitted inline as async-generator IIFEs with no runtime import, so non-stream modules stay byte-identical: Stream.of(xs) becomes a generator over the list, map/take wrap it lazily, and the terminal collect() drains it into an array. A streamed HTTP response — Streaming(stream) — lowers to a Response whose body is the stream encoded as a Server-Sent-Events (SSE) byte stream consuming a Stream[String]; RawStreamed(body, contentType) (#2623) to one whose body is the Stream[Bytes]’s chunks, as they are pulled.

A stream is single-pass (#2623). Each inline op first claims its source: it marks the iterable under the registered symbol Symbol.for("bynk.stream.read"), throwing bynk: a stream can be read only once if the mark is already set. A builder claims when its generator is first pulled, collect when it runs, and a streamed response when it is built. The mark lives on the iterable, so it holds across modules. A stream-carrying record or sum has no serialise_* or deserialise_* helper, since the checker keeps it off every boundary.

A Connection[F] lowers against the runtime Connection<F> interface (§7.4.9): send JSON-encodes a frame, close ends the socket. The from websocket protocol lowers per target:

  • bundle — the on open/on message/on close handlers become callable surface methods (Service.open(conn, …)) taking a TestConnection — a capture-and-inspect channel recording every frame sent — so the service runs under Node with no Durable Object.
  • Workers — the Worker authenticates the upgrade at the edge (the same JWT verifier the HTTP seam uses, reading the Bearer token from the Sec-WebSocket-Protocol subprotocol) and forwards it to the addressed Durable Object, which accepts the socket via the hibernatable-WebSocket API (acceptWebSocket/serializeAttachment/getWebSockets). A held Map[K, Connection] cannot be JSON-persisted (a live socket), so it lives in an in-memory side-table split out of the durable record. parTraverse over the map lowers to await Promise.all(xs.map(f)). Only modules that use streams or WebSockets emit this machinery.

A held Map[K, Connection] closes the connections it stops holding, on both targets, so a held connection is never dropped with its socket open. remove closes the connection the key held and then deletes the entry, and put over a key that already holds a connection closes the displaced connection before storing the new one. A put of the connection the key already holds (on Workers, the same connection id; on the bundle, the same TestConnection) closes nothing. An absent key is a no-op for remove. The close happens while the handler runs, before its end-of-handler commit, so a handler that closes a connection and then faults has closed it although the entry is not committed as removed.

Every emitted project ships a single runtime module that the per-context and per-test modules import. It is the normative contract the emitted code depends on, defined in §7.4 The runtime library.