Skip to main content

bynk_emit/emitter/serialisation/
expr.rs

1//! A value at a boundary (back-half paydown 2.3a, #4088): `serialise_expr`, `deserialise_expr` and their
2//! `_via`, reference and witness forms, with their tests and the serialiser corpus. Moved out of
3//! `serialisation.rs` byte for byte.
4
5use bynk_syntax::ast::{BaseType, TypeRef};
6use bynk_ts::{TsArrowBody, TsBinaryOp, TsExpr, TsParam, TsType, TsUnaryOp};
7
8use crate::emitter::RuntimeUse;
9use crate::ts_build::{as_expr, call, ident, member, ret, str_lit};
10
11use super::field::{emit_field_deserialise, serialise_field_expr, serialise_field_expr_via};
12use super::inner_ts_name;
13
14/// v0.22b: an expression-form serialise for a codec target — the same
15/// dispatch as a record field's serialisation.
16pub(crate) fn serialise_expr(t: &TypeRef, value: &TsExpr, ru: &RuntimeUse) -> TsExpr {
17    serialise_field_expr(t, value, None, ru)
18}
19
20/// v0.176 (#642): the one serialise dispatch for the workers cross-context
21/// boundary, reaching helpers through `ns`. Replaces the two parallel
22/// dispatches this boundary used to carry — `emit.rs`'s `workers_serialise_expr`
23/// (which dropped `List`/`Map` to a bare `as JsonValue` cast) and
24/// `workers_entry.rs`'s `serialise_call` (which did the same to `Bytes`, the
25/// asymmetry that forced `bynk.types.bytes_at_workers_boundary`).
26pub fn serialise_expr_via(t: &TypeRef, value: &TsExpr, ns: &str, ru: &RuntimeUse) -> TsExpr {
27    serialise_field_expr_via(t, value, ns, ru)
28}
29
30/// v0.176 (#642): a deserialise **reference** for `ns`, shaped to
31/// `callService`'s `deserialiseResult` parameter. The inline arms become a
32/// lambda rather than the unvalidated `((j: any) => ({ tag: "Ok", value: j }))`
33/// identity the caller path used to fall back to.
34pub fn deserialise_ref_via(t: &TypeRef, ns: &str, ru: &RuntimeUse) -> TsExpr {
35    match strip_effect(t) {
36        TypeRef::Named(id) => ident(format!("{ns}__deserialise_{}", id.name)),
37        t @ (TypeRef::Result(..)
38        | TypeRef::Option(..)
39        | TypeRef::List(..)
40        | TypeRef::Set(..)
41        | TypeRef::Map(..)
42        | TypeRef::App { .. }) => ident(format!("{ns}__deserialise_{}", inner_ts_name(t))),
43        other @ TypeRef::Base(..)
44        | other @ TypeRef::Effect(..)
45        | other @ TypeRef::HttpResult(..)
46        | other @ TypeRef::QueueResult(_)
47        | other @ TypeRef::Asset(_)
48        | other @ TypeRef::RequestHeaders(_)
49        | other @ TypeRef::RequestQuery(_)
50        | other @ TypeRef::RequestCookies(_)
51        | other @ TypeRef::TokenClaims(_)
52        | other @ TypeRef::BoundaryRejection(_)
53        | other @ TypeRef::Query(..)
54        | other @ TypeRef::Stream(..)
55        | other @ TypeRef::Connection(..)
56        | other @ TypeRef::History(..)
57        | other @ TypeRef::ValidationError(_)
58        | other @ TypeRef::DecodeError(_)
59        | other @ TypeRef::Unit(_)
60        | other @ TypeRef::Fn(..) => TsExpr::Arrow {
61            params: vec![TsParam::new(
62                "__j".to_string(),
63                Some(TsType::named("__JsonValue")),
64            )],
65            is_async: false,
66            generics: Vec::new(),
67            return_type: None,
68            body: Box::new(TsArrowBody::Expr(Box::new(deserialise_expr_via(
69                other,
70                &ident("__j"),
71                "$",
72                ns,
73                ru,
74            )))),
75        },
76    }
77}
78
79/// v0.176 (#642) follow-up: a serialise **reference** for `ns`, shaped to
80/// `httpResultToResponse`'s serialiser parameter — the mirror image of
81/// `deserialise_ref_via` above. Replaces `workers_entry.rs`'s
82/// `http_value_serialiser`, a parallel dispatch that collapsed every base type
83/// to `(v: any) => v as JsonValue`, dropping the `Float` non-finite guard and
84/// `Bytes` base64 encoding that `serialise_field_expr_via` already carries.
85pub(crate) fn serialise_ref_via(t: &TypeRef, ns: &str, ru: &RuntimeUse) -> TsExpr {
86    match strip_effect(t) {
87        TypeRef::Named(id) => ident(format!("{ns}__serialise_{}", id.name)),
88        t @ (TypeRef::Result(..)
89        | TypeRef::Option(..)
90        | TypeRef::List(..)
91        | TypeRef::Set(..)
92        | TypeRef::Map(..)
93        | TypeRef::App { .. }) => ident(format!("{ns}__serialise_{}", inner_ts_name(t))),
94        other @ TypeRef::Base(..)
95        | other @ TypeRef::Effect(..)
96        | other @ TypeRef::HttpResult(..)
97        | other @ TypeRef::QueueResult(_)
98        | other @ TypeRef::Asset(_)
99        | other @ TypeRef::RequestHeaders(_)
100        | other @ TypeRef::RequestQuery(_)
101        | other @ TypeRef::RequestCookies(_)
102        | other @ TypeRef::TokenClaims(_)
103        | other @ TypeRef::BoundaryRejection(_)
104        | other @ TypeRef::Query(..)
105        | other @ TypeRef::Stream(..)
106        | other @ TypeRef::Connection(..)
107        | other @ TypeRef::History(..)
108        | other @ TypeRef::ValidationError(_)
109        | other @ TypeRef::DecodeError(_)
110        | other @ TypeRef::Unit(_)
111        | other @ TypeRef::Fn(..) => TsExpr::Arrow {
112            params: vec![TsParam::new(
113                "__v".to_string(),
114                Some(crate::emitter::ts_types::ts_type_of(other)),
115            )],
116            is_async: false,
117            generics: Vec::new(),
118            return_type: None,
119            body: Box::new(TsArrowBody::Expr(Box::new(serialise_field_expr_via(
120                other,
121                &ident("__v"),
122                ns,
123                ru,
124            )))),
125        },
126    }
127}
128
129/// Constrained generics slice 3: the `{ encode, decode }` witness for a
130/// variable-free type, from the generated codec for it. A named or container
131/// codec takes the path it is called with. A base type has no generated helper,
132/// so its decoder is the one a record field or container element uses
133/// ([`emit_field_deserialise`]), reporting at the path it is given: that is what
134/// every position nested in a container decodes with.
135pub(crate) fn witness_codec_expr(t: &TypeRef, ru: &RuntimeUse) -> TsExpr {
136    let encode = serialise_ref_via(t, "", ru);
137    let decode = match strip_effect(t) {
138        TypeRef::Named(_)
139        | TypeRef::Result(..)
140        | TypeRef::Option(..)
141        | TypeRef::List(..)
142        | TypeRef::Set(..)
143        | TypeRef::Map(..)
144        | TypeRef::App { .. } => deserialise_ref_via(t, "", ru),
145        other @ TypeRef::Base(..)
146        | other @ TypeRef::Effect(..)
147        | other @ TypeRef::HttpResult(..)
148        | other @ TypeRef::QueueResult(_)
149        | other @ TypeRef::Asset(_)
150        | other @ TypeRef::RequestHeaders(_)
151        | other @ TypeRef::RequestQuery(_)
152        | other @ TypeRef::RequestCookies(_)
153        | other @ TypeRef::TokenClaims(_)
154        | other @ TypeRef::BoundaryRejection(_)
155        | other @ TypeRef::Query(..)
156        | other @ TypeRef::Stream(..)
157        | other @ TypeRef::Connection(..)
158        | other @ TypeRef::History(..)
159        | other @ TypeRef::ValidationError(_)
160        | other @ TypeRef::DecodeError(_)
161        | other @ TypeRef::Unit(_)
162        | other @ TypeRef::Fn(..) => {
163            let mut body =
164                emit_field_deserialise("v", other, &ident("__j"), &ident("__p"), None, ru);
165            body.push(ret(call(
166                ident("Ok"),
167                vec![as_expr(
168                    ident("__v"),
169                    crate::emitter::ts_types::ts_type_of(other),
170                )],
171            )));
172            // A flat body: the printer's compact object literal takes no multi-line block, so each
173            // statement prints on the one line (1A.39a, Decision E). The tree is the arrow itself, so
174            // its parameters and locals bind and the names it uses are read from it.
175            TsExpr::Arrow {
176                params: vec![
177                    TsParam::new("__j".to_string(), Some(TsType::named("__JsonValue"))),
178                    TsParam::new("__p".to_string(), Some(TsType::named("string"))),
179                ],
180                is_async: false,
181                generics: Vec::new(),
182                return_type: None,
183                body: Box::new(TsArrowBody::Flat(body)),
184            }
185        }
186    };
187    TsExpr::object(vec![
188        ("encode".to_string(), encode),
189        ("decode".to_string(), decode),
190    ])
191}
192
193/// #1678: does an agent-call position carry a value with no wire form, so the
194/// workers Durable Object call passes it through unencoded, as it did before
195/// #1678? True when the type holds a `Connection`, a function, a `Stream`, a
196/// `Query` or a `History` anywhere in its structure (an `Effect` wrapper is
197/// peeled, as the codec peels it). Every other type has a codec, including a
198/// generic application (`Box[Bytes]`), whose helper the codec closure emits.
199pub(crate) fn agent_wire_passes_through(t: &TypeRef) -> bool {
200    match t {
201        TypeRef::Connection(..)
202        | TypeRef::Fn(..)
203        | TypeRef::Stream(..)
204        | TypeRef::Query(..)
205        | TypeRef::History(..) => true,
206        TypeRef::Effect(inner, _)
207        | TypeRef::Option(inner, _)
208        | TypeRef::List(inner, _)
209        | TypeRef::Set(inner, _)
210        | TypeRef::HttpResult(inner, _) => agent_wire_passes_through(inner),
211        TypeRef::Result(a, b, _) | TypeRef::Map(a, b, _) => {
212            agent_wire_passes_through(a) || agent_wire_passes_through(b)
213        }
214        TypeRef::App { args, .. } => args.iter().any(agent_wire_passes_through),
215        TypeRef::Base(..)
216        | TypeRef::Named(_)
217        | TypeRef::QueueResult(_)
218        | TypeRef::Asset(_)
219        | TypeRef::RequestHeaders(_)
220        | TypeRef::RequestQuery(_)
221        | TypeRef::RequestCookies(_)
222        | TypeRef::TokenClaims(_)
223        | TypeRef::BoundaryRejection(_)
224        | TypeRef::ValidationError(_)
225        | TypeRef::DecodeError(_)
226        | TypeRef::Unit(_) => false,
227    }
228}
229
230/// An `Effect[T]` in a handler signature wraps the *handler*, not the wire
231/// payload — the caller awaits the Promise, so the codec is `T`'s.
232fn strip_effect(t: &TypeRef) -> &TypeRef {
233    if let TypeRef::Effect(inner, _) = t {
234        strip_effect(inner)
235    } else {
236        t
237    }
238}
239
240/// A field's type with one `List` or `Option` wrapper peeled, and which wrapper it was:
241/// `(inner, is_list, is_option)`. Any other type is its own `inner` with neither flag.
242pub(crate) fn peel_list_option(t: &TypeRef) -> (&TypeRef, bool, bool) {
243    match t {
244        TypeRef::List(inner, _) => (inner.as_ref(), true, false),
245        TypeRef::Option(inner, _) => (inner.as_ref(), false, true),
246        TypeRef::Base(..)
247        | TypeRef::Named(_)
248        | TypeRef::Result(..)
249        | TypeRef::Effect(..)
250        | TypeRef::HttpResult(..)
251        | TypeRef::QueueResult(_)
252        | TypeRef::Asset(_)
253        | TypeRef::RequestHeaders(_)
254        | TypeRef::RequestQuery(_)
255        | TypeRef::RequestCookies(_)
256        | TypeRef::TokenClaims(_)
257        | TypeRef::BoundaryRejection(_)
258        | TypeRef::Map(..)
259        | TypeRef::Set(..)
260        | TypeRef::Query(..)
261        | TypeRef::Stream(..)
262        | TypeRef::Connection(..)
263        | TypeRef::History(..)
264        | TypeRef::ValidationError(_)
265        | TypeRef::DecodeError(_)
266        | TypeRef::Unit(_)
267        | TypeRef::Fn(..)
268        | TypeRef::App { .. } => (t, false, false),
269    }
270}
271
272/// `HttpResult<T>` over the type `inner` spells: generic with no default type argument, so a bare
273/// `HttpResult` in type position is `tsc`'s TS2314.
274fn http_result_ty(inner: &TypeRef) -> TsType {
275    TsType::named_with_args(
276        "HttpResult",
277        vec![crate::emitter::ts_types::ts_type_of(inner)],
278    )
279}
280
281/// v0.22b: an expression-form deserialise call for a codec target. Named
282/// types and generic instantiations go through their (module-local)
283/// helpers; bases inline the structural check.
284pub(crate) fn deserialise_expr(t: &TypeRef, json: &TsExpr, path: &str, ru: &RuntimeUse) -> TsExpr {
285    deserialise_expr_via(t, json, path, "", ru)
286}
287
288/// v0.176 (#642): the one deserialise dispatch for the workers cross-context
289/// boundary, reaching helpers through `ns`. Replaces `workers_entry.rs`'s
290/// `deserialise_call`; the `Json.decode` entry (`deserialise_expr`) is the same
291/// function with an empty prefix.
292///
293/// This carries two arms the `Json` codec path never needs, because the
294/// checker's codec-domain rule rejects them there but the cross-context
295/// boundary admits them: `Unit` (an `on call` may return `Effect[Result[(), E]]`)
296/// and the runtime-owned error types.
297pub(crate) fn deserialise_expr_via(
298    t: &TypeRef,
299    json: &TsExpr,
300    path: &str,
301    ns: &str,
302    ru: &RuntimeUse,
303) -> TsExpr {
304    // The runtime-owned-error-type arms below (`ValidationError`/`DecodeError`/
305    // `QueueResult`/`HttpResult`) all share this one shape: `Ok(json as
306    // unknown as {ty}) as Result<{ty}, BoundaryError>` — the deserialise-side
307    // mirror of `serialise_field_expr_wire`'s own `WireRef::Unchecked` arm
308    // (see that arm's own doc for why a nested `As`-under-`As` is safe here:
309    // this function's result is never rendered through `render_operand`).
310    let ok_unknown_cast = |ty: TsType| -> TsExpr {
311        as_expr(
312            call(
313                ident("Ok"),
314                vec![as_expr(
315                    as_expr(json.clone(), TsType::named("unknown")),
316                    ty.clone(),
317                )],
318            ),
319            TsType::named_with_args("Result", vec![ty, TsType::named("__BoundaryError")]),
320        )
321    };
322    // `Err({ kind: "StructuralMismatch", path, expected, actual } as
323    // BoundaryError)` — shared by the `Bytes` arm (below) and the plain
324    // `Base` arm further down, the one error shape both build.
325    let structural_mismatch = |expected: &str, actual: TsExpr| -> TsExpr {
326        call(
327            ident("Err"),
328            vec![as_expr(
329                TsExpr::object(vec![
330                    ("kind".to_string(), str_lit("StructuralMismatch")),
331                    ("path".to_string(), str_lit(path)),
332                    ("expected".to_string(), str_lit(expected)),
333                    ("actual".to_string(), actual),
334                ]),
335                TsType::named("__BoundaryError"),
336            )],
337        )
338    };
339    match t {
340        TypeRef::Named(id) => call(
341            ident(format!("{ns}__deserialise_{}", id.name)),
342            vec![json.clone(), str_lit(path)],
343        ),
344        TypeRef::Result(..)
345        | TypeRef::Option(..)
346        | TypeRef::List(..)
347        | TypeRef::Set(..)
348        | TypeRef::Map(..)
349        // v0.174 (#592): a generic-record instantiation decodes through its
350        // monomorphised codec (`deserialise_Paginated_User`).
351        | TypeRef::App { .. } => call(
352            ident(format!("{ns}__deserialise_{}", inner_ts_name(t))),
353            vec![json.clone(), str_lit(path)],
354        ),
355        TypeRef::Effect(inner, _) => deserialise_expr_via(inner, json, path, ns, ru),
356        // A `()` carries no wire content — the wire slot is `null` and the value
357        // is `undefined`. Nothing to validate, so `Ok` is the honest answer here
358        // rather than an erosion.
359        //
360        // Reached only by a **bare** `()` in a wire position. A `Result`-wrapped
361        // one — `on call () -> Effect[Result[(), E]]`, the common shape — strips
362        // its `Effect` and then goes through `deserialise_Result_Unit_E`, whose
363        // generated body handles the `Unit` payload itself (`emit_generic_helpers`),
364        // so it never lands here. No fixture currently exercises this arm; it is
365        // defensive, and saying so is more useful than implying coverage.
366        TypeRef::Unit(_) => as_expr(
367            call(ident("Ok"), vec![ident("undefined")]),
368            TsType::named("Result<void, __BoundaryError>"),
369        ),
370        // The runtime-owned error types: no generated codec to name, so the
371        // deserialised value casts through unchecked — same shape as
372        // `emit_field_deserialise_wire`'s `WireRef::Unchecked` arm.
373        //
374        // #1319: closes the `ts_any` residual — each arm now casts through
375        // its own real, exported runtime type instead of sharing one `any`
376        // arm, since `t` (the matched `TypeRef` itself) already tells this
377        // function precisely which of the four it is; no information is
378        // missing here the way it briefly was one layer down at the
379        // `WireRef::Unchecked`-with-a-`reason`-field call site. Bridged
380        // through `unknown` — the same fix, for the same TS2352 reason, as
381        // `emit_field_deserialise_wire`'s own `WireRef::Unchecked` arm (this
382        // function's `json` is not always statically a `JsonValue` the way
383        // that arm's is, but nothing about a real-vs-real interface cast
384        // gets *safer* when the source type is narrower, so the same
385        // defensive bridge applies uniformly). No fixture currently reaches
386        // this function for one of these four types directly (the field
387        // path above is what real code exercises today); named rather than
388        // silently assumed correct, the same "not exercised, defensive"
389        // precedent this file's own `TypeRef::Unit` arm above already sets.
390        TypeRef::ValidationError(_) => ok_unknown_cast(TsType::named("ValidationError")),
391        TypeRef::DecodeError(_) => ok_unknown_cast(TsType::named("DecodeError")),
392        // Review of #1319/#1320, finding 1: `HttpResult<T>` (`bynk-emit/
393        // runtime/src/http.ts:6`) is generic with no default type argument
394        // — a bare `HttpResult` in type position is `tsc`'s TS2314, not the
395        // `any`-compatible cast the other three residual types get. This
396        // arm already holds the element type (`TypeRef::HttpResult(Box<
397        // TypeRef>, Span)`, `bynk-syntax/src/ast.rs:2196`), so it builds
398        // `HttpResult<T>` through `http_result_ty` — the same type node every
399        // other `HttpResult<...>` position in this file already uses —
400        // instead of dropping the payload.
401        TypeRef::HttpResult(inner, _) => ok_unknown_cast(http_result_ty(inner)),
402        TypeRef::QueueResult(_) => ok_unknown_cast(TsType::named("QueueResult")),
403        // #1883, slice 1a: unreachable in a checked program
404        // (`bynk.types.asset_at_boundary`).
405        TypeRef::Asset(_) => ok_unknown_cast(TsType::named("{ readonly url: string }")),
406        // v0.110 (ADR 0142 D5): a `Bytes` wires as a base64 string; decode it
407        // (rejecting a non-string or invalid base64) to a `Uint8Array`.
408        TypeRef::Base(base @ (BaseType::Bytes | BaseType::Decimal), _) => {
409            let (parse, expected, invalid) = if *base == BaseType::Decimal {
410                ru.note_decimal("__bynkDecimalParseWire");
411                ("__bynkDecimalParseWire", "decimal string", "invalid decimal")
412            } else {
413                ru.note_bytes();
414                ("__bynkBytesFromBase64", "base64 string", "invalid base64")
415            };
416            call(
417                TsExpr::Arrow {
418                    params: vec![TsParam::new("__v".to_string(), None)],
419                    is_async: false,
420                    generics: Vec::new(),
421                    return_type: None,
422                    body: Box::new(TsArrowBody::Expr(Box::new(TsExpr::Conditional {
423                        test: Box::new(TsExpr::Binary {
424                            op: TsBinaryOp::StrictEq,
425                            left: Box::new(TsExpr::Unary {
426                                op: TsUnaryOp::Typeof,
427                                expr: Box::new(ident("__v")),
428                            }),
429                            right: Box::new(str_lit("string")),
430                        }),
431                        consequent: Box::new(call(
432                            TsExpr::Arrow {
433                                params: vec![TsParam::new("__b".to_string(), None)],
434                                is_async: false,
435                                generics: Vec::new(),
436                                return_type: None,
437                                body: Box::new(TsArrowBody::Expr(Box::new(
438                                    TsExpr::Conditional {
439                                        test: Box::new(TsExpr::Binary {
440                                            op: TsBinaryOp::StrictEq,
441                                            left: Box::new(member(ident("__b"), "tag")),
442                                            right: Box::new(str_lit("Some")),
443                                        }),
444                                        consequent: Box::new(call(
445                                            ident("Ok"),
446                                            vec![member(ident("__b"), "value")],
447                                        )),
448                                        alternate: Box::new(structural_mismatch(
449                                            expected,
450                                            str_lit(invalid),
451                                        )),
452                                    },
453                                ))),
454                            },
455                            vec![call(ident(parse), vec![ident("__v")])],
456                        )),
457                        alternate: Box::new(structural_mismatch(
458                            expected,
459                            TsExpr::Unary {
460                                op: TsUnaryOp::Typeof,
461                                expr: Box::new(ident("__v")),
462                            },
463                        )),
464                    }))),
465                },
466                vec![json.clone()],
467            )
468        }
469        TypeRef::Base(b, _) => {
470            let typeof_str = match b {
471                BaseType::Int => "number",
472                BaseType::String => "string",
473                BaseType::Bool => "boolean",
474                BaseType::Float => "number",
475                BaseType::Duration | BaseType::Instant => "number",
476                // Unreachable: handled by the dedicated `Bytes`/`Decimal` arm above.
477                BaseType::Bytes | BaseType::Decimal => "string",
478            };
479            // `Some(predicate)`: the arm needs a second, narrower runtime check
480            // beyond `typeof` — a real `TsExpr`, not text, now that `extra`'s
481            // only past job (interpolating into a hand-built `format!`) is
482            // gone.
483            let predicate: Option<TsExpr> = match b {
484                BaseType::Float => Some(call(
485                    member(ident("globalThis.Number"), "isFinite"),
486                    vec![ident("__v")],
487                )),
488                // v0.86 (ADR 0112 D6): a `Duration` is whole milliseconds —
489                // reject a non-integer from the wire, as a refined `Int` does.
490                // #1657: whole *and* within ±(2^53 − 1), the `Int` domain.
491                BaseType::Int | BaseType::Duration | BaseType::Instant => Some(call(
492                    member(ident("globalThis.Number"), "isSafeInteger"),
493                    vec![ident("__v")],
494                )),
495                BaseType::String | BaseType::Bool | BaseType::Bytes | BaseType::Decimal => None,
496            };
497            // v0.176 (#642): report what was *required*, not just the `typeof`
498            // that was tested. For the arms carrying a `predicate` the two
499            // differ, and reporting the bare `typeof` makes the error useless in
500            // exactly the case the predicate exists to catch: a `3.5` for an `Int`
501            // would read `expected: "number", actual: "number"`.
502            let expected = match b {
503                BaseType::Int | BaseType::Duration | BaseType::Instant => "safe integer",
504                BaseType::Float => "finite number",
505                BaseType::String | BaseType::Bool | BaseType::Bytes | BaseType::Decimal => {
506                    typeof_str
507                }
508            };
509            let typeof_v = || TsExpr::Unary {
510                op: TsUnaryOp::Typeof,
511                expr: Box::new(ident("__v")),
512            };
513            let Some(predicate) = predicate else {
514                return call(
515                    TsExpr::Arrow {
516                        params: vec![TsParam::new("__v".to_string(), None)],
517                        is_async: false,
518                        generics: Vec::new(),
519                        return_type: None,
520                        body: Box::new(TsArrowBody::Expr(Box::new(TsExpr::Conditional {
521                            test: Box::new(TsExpr::Binary {
522                                op: TsBinaryOp::StrictEq,
523                                left: Box::new(typeof_v()),
524                                right: Box::new(str_lit(typeof_str)),
525                            }),
526                            consequent: Box::new(call(ident("Ok"), vec![ident("__v")])),
527                            alternate: Box::new(structural_mismatch(expected, typeof_v())),
528                        }))),
529                    },
530                    vec![json.clone()],
531                );
532            };
533            // The two failure modes are **not** the same error, and collapsing
534            // them is what made both predecessors imprecise in opposite
535            // directions. The `Json` path reported `typeof` for both, losing the
536            // predicate failure's detail; the workers path reported
537            // `String(value)` for both, which echoes an arbitrary caller-supplied
538            // value into a 400 response body (an `Int` sent `"hunter2"` reported
539            // `actual: "hunter2"`) and violates the ADR 0107 discipline of never
540            // reporting the offending value.
541            //
542            // Split them and both problems go away. A wrong `typeof` reports the
543            // `typeof` — the value could be anything, so it is never echoed. A
544            // *failed predicate* means the `typeof` already matched, so the value
545            // is provably a **number**: `String(__v)` is `"3.5"` for a
546            // non-integer `Int`, and provably one of `"NaN"` / `"Infinity"` /
547            // `"-Infinity"` for a non-finite `Float` — a closed set. That is
548            // strictly more precise than either predecessor, with strictly less
549            // exposure.
550            call(
551                TsExpr::Arrow {
552                    params: vec![TsParam::new("__v".to_string(), None)],
553                    is_async: false,
554                    generics: Vec::new(),
555                    return_type: None,
556                    body: Box::new(TsArrowBody::Expr(Box::new(TsExpr::Conditional {
557                        test: Box::new(TsExpr::Binary {
558                            op: TsBinaryOp::StrictNotEq,
559                            left: Box::new(typeof_v()),
560                            right: Box::new(str_lit(typeof_str)),
561                        }),
562                        consequent: Box::new(structural_mismatch(expected, typeof_v())),
563                        alternate: Box::new(TsExpr::Conditional {
564                            test: Box::new(predicate),
565                            consequent: Box::new(call(ident("Ok"), vec![ident("__v")])),
566                            alternate: Box::new(structural_mismatch(
567                                expected,
568                                call(ident("String"), vec![ident("__v")]),
569                            )),
570                        }),
571                    }))),
572                },
573                vec![json.clone()],
574            )
575        }
576        // Everything else is rejected by the checker's codec-domain rule (the
577        // `Json` path) or by the boundary rules (the workers path). Shared by
578        // three callers, so the message names the type rather than one caller.
579        other @ (
580            TypeRef::RequestHeaders(_)
581            | TypeRef::RequestQuery(_)
582            | TypeRef::RequestCookies(_)
583            | TypeRef::TokenClaims(_)
584            | TypeRef::BoundaryRejection(_)
585            | TypeRef::Query(..)
586            | TypeRef::Stream(..)
587            | TypeRef::Connection(..)
588            | TypeRef::History(..)
589            | TypeRef::Fn(..)
590        ) => unreachable!("non-codable type reached a codec lowering: {other:?}"),
591    }
592}
593
594/// Review of #1319/#1320, finding 2: no unit test covered any of
595/// `deserialise_expr_via`'s own four runtime-owned-error-type arms — this
596/// path is not reached by any current fixture (see those arms' own doc),
597/// so a fixture-corpus regression would not have caught a text-level
598/// mistake here the way it caught the `HttpResult<unknown>` gap one layer
599/// down. Pins the exact generated text directly.
600#[cfg(test)]
601mod deserialise_expr_via_error_type_tests {
602    use super::*;
603    use bynk_syntax::span::Span;
604
605    fn sp() -> Span {
606        Span::new(0, 0)
607    }
608
609    #[test]
610    fn validation_error_casts_through_unknown() {
611        let ru = RuntimeUse::default();
612        let t = TypeRef::ValidationError(sp());
613        assert_eq!(
614            bynk_ts::print_expr(&deserialise_expr(&t, &ident("json"), "path", &ru)),
615            "Ok(json as unknown as ValidationError) as Result<ValidationError, __BoundaryError>"
616        );
617    }
618
619    #[test]
620    fn json_error_casts_through_unknown() {
621        let ru = RuntimeUse::default();
622        let t = TypeRef::DecodeError(sp());
623        assert_eq!(
624            bynk_ts::print_expr(&deserialise_expr(&t, &ident("json"), "path", &ru)),
625            "Ok(json as unknown as DecodeError) as Result<DecodeError, __BoundaryError>"
626        );
627    }
628
629    #[test]
630    fn http_result_names_its_real_element_type_and_casts_through_unknown() {
631        let ru = RuntimeUse::default();
632        let t = TypeRef::HttpResult(Box::new(TypeRef::Base(BaseType::Int, sp())), sp());
633        assert_eq!(
634            bynk_ts::print_expr(&deserialise_expr(&t, &ident("json"), "path", &ru)),
635            "Ok(json as unknown as HttpResult<number>) as Result<HttpResult<number>, __BoundaryError>"
636        );
637    }
638
639    #[test]
640    fn queue_result_casts_through_unknown() {
641        let ru = RuntimeUse::default();
642        let t = TypeRef::QueueResult(sp());
643        assert_eq!(
644            bynk_ts::print_expr(&deserialise_expr(&t, &ident("json"), "path", &ru)),
645            "Ok(json as unknown as QueueResult) as Result<QueueResult, __BoundaryError>"
646        );
647    }
648}
649
650#[cfg(test)]
651mod peel_tests {
652    use super::*;
653    use bynk_syntax::span::Span;
654
655    fn int() -> TypeRef {
656        TypeRef::Base(BaseType::Int, Span::default())
657    }
658
659    #[test]
660    fn a_list_or_option_peels_one_layer_and_says_which() {
661        let list = TypeRef::List(Box::new(int()), Span::default());
662        let (inner, is_list, is_option) = peel_list_option(&list);
663        assert!(matches!(inner, TypeRef::Base(BaseType::Int, _)) && is_list && !is_option);
664        let option = TypeRef::Option(Box::new(int()), Span::default());
665        let (inner, is_list, is_option) = peel_list_option(&option);
666        assert!(matches!(inner, TypeRef::Base(BaseType::Int, _)) && !is_list && is_option);
667    }
668
669    #[test]
670    fn any_other_type_is_its_own_inner_and_one_layer_only_is_peeled() {
671        let plain = int();
672        let (inner, is_list, is_option) = peel_list_option(&plain);
673        assert!(matches!(inner, TypeRef::Base(BaseType::Int, _)) && !is_list && !is_option);
674        let nested = TypeRef::List(
675            Box::new(TypeRef::Option(Box::new(int()), Span::default())),
676            Span::default(),
677        );
678        let (inner, is_list, is_option) = peel_list_option(&nested);
679        assert!(matches!(inner, TypeRef::Option(..)) && is_list && !is_option);
680        let set = TypeRef::Set(Box::new(int()), Span::default());
681        let (inner, is_list, is_option) = peel_list_option(&set);
682        assert!(matches!(inner, TypeRef::Set(..)) && !is_list && !is_option);
683    }
684}
685
686/// 1A.21 (#3722, Decision B): the serialiser entry points take their value as a node. This
687/// corpus is the old-versus-new equality check: `serialiser_corpus.txt` was printed by the
688/// text-valued entry points (`serialise_expr(t, "v", ..)`, `serialise_expr_via(t, "a.b", ns,
689/// ..)`) before they changed, over every base type and a spread of nested shapes, and the
690/// node-valued entries must print exactly the same.
691#[cfg(test)]
692mod serialiser_corpus_tests {
693    use super::*;
694    use bynk_syntax::ast::Ident;
695    use bynk_syntax::span::Span;
696
697    fn sp() -> Span {
698        Span::new(0, 0)
699    }
700
701    fn named(n: &str) -> TypeRef {
702        TypeRef::Named(Ident {
703            name: n.to_string(),
704            span: sp(),
705        })
706    }
707
708    fn b(t: TypeRef) -> Box<TypeRef> {
709        Box::new(t)
710    }
711
712    fn elements() -> Vec<(&'static str, TypeRef)> {
713        let base = |n, t| (n, TypeRef::Base(t, sp()));
714        vec![
715            base("Int", BaseType::Int),
716            base("String", BaseType::String),
717            base("Bool", BaseType::Bool),
718            base("Float", BaseType::Float),
719            base("Duration", BaseType::Duration),
720            base("Instant", BaseType::Instant),
721            base("Bytes", BaseType::Bytes),
722            base("Decimal", BaseType::Decimal),
723            ("Foo", named("Foo")),
724            ("ValidationError", TypeRef::ValidationError(sp())),
725            ("DecodeError", TypeRef::DecodeError(sp())),
726            ("QueueResult", TypeRef::QueueResult(sp())),
727        ]
728    }
729
730    fn shapes(e: &TypeRef) -> Vec<(&'static str, TypeRef)> {
731        let s = TypeRef::Base(BaseType::String, sp());
732        vec![
733            ("bare", e.clone()),
734            ("Option", TypeRef::Option(b(e.clone()), sp())),
735            ("List", TypeRef::List(b(e.clone()), sp())),
736            ("Set", TypeRef::Set(b(e.clone()), sp())),
737            ("Map", TypeRef::Map(b(s.clone()), b(e.clone()), sp())),
738            ("Result", TypeRef::Result(b(e.clone()), b(s), sp())),
739            ("Effect", TypeRef::Effect(b(e.clone()), sp())),
740            ("HttpResult", TypeRef::HttpResult(b(e.clone()), sp())),
741            (
742                "Option<List>",
743                TypeRef::Option(b(TypeRef::List(b(e.clone()), sp())), sp()),
744            ),
745            (
746                "List<Option>",
747                TypeRef::List(b(TypeRef::Option(b(e.clone()), sp())), sp()),
748            ),
749            (
750                "Map<Foo,List>",
751                TypeRef::Map(b(named("Foo")), b(TypeRef::List(b(e.clone()), sp())), sp()),
752            ),
753            (
754                "App",
755                TypeRef::App {
756                    name: Ident {
757                        name: "Pair".to_string(),
758                        span: sp(),
759                    },
760                    args: vec![e.clone(), named("Foo")],
761                    span: sp(),
762                },
763            ),
764        ]
765    }
766
767    /// Every case's printed text, one `label | entry | text` line each.
768    fn corpus() -> String {
769        let ru = RuntimeUse::default();
770        let mut out = String::new();
771        let mut cases = vec![("Unit", TypeRef::Unit(sp()))];
772        for (en, e) in elements() {
773            for (sn, t) in shapes(&e) {
774                cases.push((Box::leak(format!("{sn}[{en}]").into_boxed_str()) as &str, t));
775            }
776        }
777        for (label, t) in &cases {
778            for value in ["v", "value.items"] {
779                let node = serialise_expr(t, &ident(value), &ru);
780                out.push_str(&format!(
781                    "{label} | {value} | {}\n",
782                    bynk_ts::print_expr(&node)
783                ));
784            }
785            for ns in ["", "handlers."] {
786                let node = serialise_expr_via(t, &ident("a.b"), ns, &ru);
787                out.push_str(&format!(
788                    "{label} | via {ns:?} | {}\n",
789                    bynk_ts::print_expr(&node)
790                ));
791            }
792        }
793        out
794    }
795
796    #[test]
797    fn the_node_entry_prints_what_the_text_entry_printed() {
798        let want = include_str!("serialiser_corpus.txt");
799        let got = corpus();
800        if std::env::var_os("BYNK_WRITE_SERIALISER_CORPUS").is_some() {
801            std::fs::write(
802                concat!(
803                    env!("CARGO_MANIFEST_DIR"),
804                    "/src/emitter/serialisation/serialiser_corpus.txt"
805                ),
806                &got,
807            )
808            .unwrap();
809            return;
810        }
811        assert_eq!(got.lines().count(), want.lines().count(), "corpus size");
812        for (g, w) in got.lines().zip(want.lines()) {
813            assert_eq!(g, w);
814        }
815    }
816}