Skip to main content

bynk_emit/emitter/
ts_types.rs

1//! TypeScript type rendering: `ts_type_ref*`, `ts_ty`, and the `TsType` builders.
2
3use super::*;
4
5/// Unchecked construction of a branded value in emitted TypeScript.
6///
7/// ADR 0182: an **opaque** type exposes a runtime `.unsafe(value)` constructor
8/// (source-callable within its defining commons, and the target of its internal
9/// uses), so opaque construction stays `T.unsafe(value)`. A **refined** or
10/// **alias** type has **no** public `.unsafe`: exposing one let hand-written host
11/// or adapter code bypass the refinement predicate, the credibility hole #545
12/// closed. Its admitted / generated values are branded with an inline `as` cast
13/// — byte-for-byte the old `.unsafe` body (`return value as T`) at the call site,
14/// but not a callable API surface a consumer can reach.
15pub(crate) fn unchecked_construct(
16    name: &str,
17    value: bynk_ts::TsExpr,
18    is_opaque: bool,
19) -> bynk_ts::TsExpr {
20    if is_opaque {
21        bynk_ts::TsExpr::Call {
22            callee: Box::new(super::lower::member_node(name, "unsafe")),
23            args: vec![value],
24        }
25    } else {
26        bynk_ts::TsExpr::Paren(Box::new(bynk_ts::TsExpr::As {
27            expr: Box::new(value),
28            ty: bynk_ts::TsType::named(name),
29        }))
30    }
31}
32
33/// Unchecked construction inside GENERATED TEST scaffolding (`tests/*.test.ts`).
34///
35/// There a branded type is in scope only as an `any`-typed value binding
36/// (`const {{ T }} = ns as any`) — never as a type — so the production
37/// `(value as T)` form fails to resolve `T`. Opaque still constructs through its
38/// `.unsafe` value method (kept, ADR 0182); a refined/alias value brands to `any`,
39/// which is exactly the type the pre-0182 `T.unsafe(value)` already produced here
40/// (`T` being `any`) and erases to the raw value at runtime — without
41/// reintroducing a callable refined `.unsafe`.
42///
43/// `Name.unsafe(value)` for an opaque type, `(value as any)` otherwise (1A.17; the
44/// cast stays: `name` is not resolvable as a type at this call site, only as an
45/// `any`-typed value binding, so there is no real type to cast to).
46pub(crate) fn unchecked_construct_test_node(
47    name: &str,
48    value: bynk_ts::TsExpr,
49    is_opaque: bool,
50) -> bynk_ts::TsExpr {
51    if is_opaque {
52        bynk_ts::TsExpr::Call {
53            callee: Box::new(super::lower::member_node(name, "unsafe")),
54            args: vec![value],
55        }
56    } else {
57        bynk_ts::TsExpr::Paren(Box::new(bynk_ts::TsExpr::As {
58            expr: Box::new(value),
59            ty: bynk_ts::TsType::named("any"),
60        }))
61    }
62}
63
64pub(super) fn ts_base(b: BaseType) -> &'static str {
65    match b {
66        BaseType::Int => "number",
67        BaseType::String => "string",
68        BaseType::Bool => "boolean",
69        BaseType::Float => "number",
70        BaseType::Duration | BaseType::Instant => "number",
71        // v0.110 (ADR 0142): `Bytes` is the one base type that does NOT erase
72        // to `number` — it lowers to an immutable octet sequence, `Uint8Array`.
73        BaseType::Bytes => "globalThis.Uint8Array",
74        // #2622: a `Decimal` is a frozen `{ coefficient, scale }` over `bigint`,
75        // named structurally so no module needs a type import for it.
76        BaseType::Decimal => DECIMAL_TS_TYPE,
77    }
78}
79
80/// #2622: the TypeScript type of a `Decimal` (see `runtime/src/decimal.ts`).
81pub(crate) const DECIMAL_TS_TYPE: &str = "{ readonly coefficient: bigint; readonly scale: number }";
82
83/// The TypeScript type of a Bynk type reference, as a node (1A.39a, Decision G). A caller that
84/// needs text prints it itself: the driver's test harness does, at its own boundary.
85pub fn ts_type_of(r: &TypeRef) -> TsType {
86    ts_type_ref_to_ts_type(r, None)
87}
88
89/// [`TsType`]-returning sibling of `ts_type_ref`, qualifying named types that
90/// live in `scope` with the namespace `ns` (`Order` → `Ns.Order`). Used by
91/// `observation_call_record_types` (`project/tests_emit.rs`) for mock method
92/// signatures that sit outside the destructuring that brings a namespace's
93/// value-side names into local scope, so the types must be referenced fully
94/// qualified. Qualification recurses through generic arguments; base/unit
95/// types are unaffected.
96///
97/// Originally paired with a `String`-returning `ts_type_ref_qualified` (Decision
98/// B, #1321) — `workers.rs`'s own type-position needs (Arc C slice 3) wanted
99/// the structured `TsType` this function returns, added *alongside* rather
100/// than replacing, since `ts_type_ref_qualified` itself was still needed by a
101/// `String`-based caller. Arc C, slice 32 (`tests_emit.rs` slice B, #1399)
102/// converted that one remaining caller (`observation_call_record_types`) to
103/// call this function directly instead — `ts_type_ref_qualified` had no
104/// other production caller left, so it was deleted rather than kept as dead
105/// code (the same "close it, don't leave a substitute-around orphan" call
106/// slice 6's `ts_string_literal` deletion already made); its own direct unit
107/// tests below now pin this function's output through `bynk_ts::print_type`
108/// instead.
109///
110/// Not a new structural walk — `ts_type_ref_to_ts_type` (below) already
111/// builds a real `TsType` from every `TypeRef` variant; this function is
112/// that same build, just with the qualifying closure threaded through.
113pub fn ts_type_ref_qualified_ts_type(r: &TypeRef, scope: &HashSet<String>, ns: &str) -> TsType {
114    ts_type_ref_to_ts_type(
115        r,
116        Some(&|name| scope.contains(name).then(|| ns.to_string())),
117    )
118}
119
120/// [`TsType`]-returning sibling of `ts_type_ref`, like `ts_type_ref_qualified`
121/// but with each in-scope name carrying its *own* namespace via `type_ns`
122/// rather than one shared `ns` — needed when a signature mixes names owned
123/// by the target unit with names reached only through a `uses`d commons
124/// (e.g. a stub class implementing an adapter-sourced capability whose
125/// return type lives in a commons the capability's own unit `uses`, never
126/// in the target context itself — Locale capability track, slice 1, #844).
127/// Qualifying such a name under the target's own namespace would reference
128/// an export `emit_context_rebrands` never emits (it only rebrands names
129/// the target's *own* lowered body references), so each name is qualified
130/// under the namespace that actually exports it. Used by `emit_stub_class`
131/// (`project/tests_emit.rs`) for its own method params/return-type.
132///
133/// Originally paired with a `String`-returning `ts_type_ref_qualified_multi`
134/// — Arc C slice 33 (`tests_emit.rs` slice C, #1401) converted `emit_stub_
135/// class`'s own two real call sites (params/return-type) to call this
136/// function directly instead, the same cleanup Arc C slice 32/#1399 already
137/// made for `ts_type_ref_qualified`'s own identical pairing — `ts_type_ref_
138/// qualified_multi` had no other production caller left, so it was deleted
139/// rather than kept as dead code, with its own direct unit test rerouted
140/// through `bynk_ts::print_type` instead.
141pub fn ts_type_ref_qualified_multi_ts_type(
142    r: &TypeRef,
143    type_ns: &HashMap<String, String>,
144) -> TsType {
145    ts_type_ref_to_ts_type(r, Some(&|name| type_ns.get(name).cloned()))
146}
147
148/// A name → owning-namespace lookup for `ts_type_ref_with`'s `qualify` arm.
149pub(super) type QualifyFn<'a> = &'a dyn Fn(&str) -> Option<String>;
150
151/// Whether `ty` is a bare (no type arguments) `Named` type whose name is
152/// exactly `target` — used by the two arms below that special-case a
153/// `Promise`/function return of `void`, checking the *structure* of the
154/// already-built `TsType` instead of the pre-P7.9 code's own `inner == "()"
155/// || inner == "void"` text comparison. No arm in [`ts_type_ref_to_ts_type`]
156/// ever builds a literal `"()"`-named type, so that half of the check is
157/// dead in practice today, same as it was before this slice — inherited
158/// unchanged rather than dropped, since removing "impossible" defensive
159/// code isn't this slice's job.
160pub(super) fn is_bare_named(ty: &TsType, target: &str) -> bool {
161    matches!(ty, TsType::Named { name, type_args } if type_args.is_empty() && name == target)
162}
163
164/// #1883, slice 1a: the TypeScript shape of a Bynk `Asset` —
165/// `{ readonly url: string }`, structural, so a program that only *names* the
166/// type (`fn link(a: Asset) -> String`) compiles with no runtime support.
167/// Each declared asset is emitted as a constant of this shape (`emit_project`).
168/// #2341 (decision A): `RequestHeaders` as TypeScript — structural, so no
169/// module needs a new runtime import for it: `get`, `bearer` and `clientIp`,
170/// each answering an `Option<string>`. The runtime's `requestHeaders(request)`
171/// builds one.
172pub(crate) fn request_headers_ts_type() -> TsType {
173    // `Option<string>` spelled out: a composition root imports no `Option`,
174    // and the bare name there is the DOM's `Option` constructor.
175    let opt = || {
176        TsType::union(vec![
177            TsType::Object(vec![
178                bynk_ts::TsTypeMember::readonly_prop("tag", TsType::named("\"Some\"")),
179                bynk_ts::TsTypeMember::readonly_prop("value", TsType::named("string")),
180            ]),
181            TsType::Object(vec![bynk_ts::TsTypeMember::readonly_prop(
182                "tag",
183                TsType::named("\"None\""),
184            )]),
185        ])
186    };
187    let name = bynk_ts::TsParam::new("name".to_string(), Some(TsType::named("string")));
188    TsType::Object(vec![
189        bynk_ts::TsTypeMember::method("get", vec![name], opt()),
190        bynk_ts::TsTypeMember::method("bearer", vec![], opt()),
191        bynk_ts::TsTypeMember::method("clientIp", vec![], opt()),
192    ])
193}
194
195/// #2380 (L5): `TokenClaims` as TypeScript — structural, like
196/// `RequestHeaders`: `get(name)` for a string claim, `has(name)` for any.
197/// #2854 (decision B): `RequestQuery` as TypeScript — structural, like
198/// `RequestHeaders`: `get`, `all` and `params`. The runtime's
199/// `requestQuery(request)` builds one.
200pub(crate) fn request_query_ts_type() -> TsType {
201    let name = || bynk_ts::TsParam::new("name".to_string(), Some(TsType::named("string")));
202    let opt = TsType::union(vec![
203        TsType::Object(vec![
204            bynk_ts::TsTypeMember::readonly_prop("tag", TsType::named("\"Some\"")),
205            bynk_ts::TsTypeMember::readonly_prop("value", TsType::named("string")),
206        ]),
207        TsType::Object(vec![bynk_ts::TsTypeMember::readonly_prop(
208            "tag",
209            TsType::named("\"None\""),
210        )]),
211    ]);
212    TsType::Object(vec![
213        bynk_ts::TsTypeMember::method("get", vec![name()], opt),
214        bynk_ts::TsTypeMember::method("all", vec![name()], TsType::named("readonly string[]")),
215        bynk_ts::TsTypeMember::method(
216            "params",
217            vec![],
218            TsType::named("globalThis.ReadonlyMap<string, readonly string[]>"),
219        ),
220    ])
221}
222
223/// #3277: `RequestCookies` as TypeScript — structural, like `RequestQuery`:
224/// `get`, `all` and `names`. The runtime's `requestCookies(request)` builds one.
225pub(crate) fn request_cookies_ts_type() -> TsType {
226    let name = || bynk_ts::TsParam::new("name".to_string(), Some(TsType::named("string")));
227    let opt = TsType::union(vec![
228        TsType::Object(vec![
229            bynk_ts::TsTypeMember::readonly_prop("tag", TsType::named("\"Some\"")),
230            bynk_ts::TsTypeMember::readonly_prop("value", TsType::named("string")),
231        ]),
232        TsType::Object(vec![bynk_ts::TsTypeMember::readonly_prop(
233            "tag",
234            TsType::named("\"None\""),
235        )]),
236    ]);
237    TsType::Object(vec![
238        bynk_ts::TsTypeMember::method("get", vec![name()], opt),
239        bynk_ts::TsTypeMember::method("all", vec![name()], TsType::named("readonly string[]")),
240        bynk_ts::TsTypeMember::method("names", vec![], TsType::named("readonly string[]")),
241    ])
242}
243
244pub(crate) fn token_claims_ts_type() -> TsType {
245    let opt = TsType::union(vec![
246        TsType::Object(vec![
247            bynk_ts::TsTypeMember::readonly_prop("tag", TsType::named("\"Some\"")),
248            bynk_ts::TsTypeMember::readonly_prop("value", TsType::named("string")),
249        ]),
250        TsType::Object(vec![bynk_ts::TsTypeMember::readonly_prop(
251            "tag",
252            TsType::named("\"None\""),
253        )]),
254    ]);
255    let name = || bynk_ts::TsParam::new("name".to_string(), Some(TsType::named("string")));
256    TsType::Object(vec![
257        bynk_ts::TsTypeMember::method("get", vec![name()], opt),
258        bynk_ts::TsTypeMember::method("has", vec![name()], TsType::named("boolean")),
259    ])
260}
261
262pub(crate) fn asset_ts_type() -> TsType {
263    TsType::Object(vec![bynk_ts::TsTypeMember::readonly_prop(
264        "url",
265        TsType::named("string"),
266    )])
267}
268
269pub(super) fn ts_type_ref_to_ts_type(r: &TypeRef, qualify: Option<QualifyFn<'_>>) -> TsType {
270    match r {
271        TypeRef::Base(b, _) => TsType::named(ts_base(*b)),
272        TypeRef::Named(id) => {
273            let name = if let Some(f) = qualify
274                && let Some(ns) = f(&id.name)
275            {
276                format!("{ns}.{}", id.name)
277            } else {
278                id.name.clone()
279            };
280            TsType::named(name)
281        }
282        TypeRef::Result(t, e, _) => TsType::named_with_args(
283            "Result",
284            vec![
285                ts_type_ref_to_ts_type(t, qualify),
286                ts_type_ref_to_ts_type(e, qualify),
287            ],
288        ),
289        TypeRef::Option(t, _) => {
290            TsType::named_with_args("Option", vec![ts_type_ref_to_ts_type(t, qualify)])
291        }
292        TypeRef::Effect(t, _) => {
293            let inner = ts_type_ref_to_ts_type(t, qualify);
294            if is_bare_named(&inner, "()") || is_bare_named(&inner, "void") {
295                TsType::named_with_args("globalThis.Promise", vec![TsType::named("void")])
296            } else {
297                TsType::named_with_args("globalThis.Promise", vec![inner])
298            }
299        }
300        TypeRef::HttpResult(t, _) => {
301            TsType::named_with_args("HttpResult", vec![ts_type_ref_to_ts_type(t, qualify)])
302        }
303        // v0.20b: collections lower to immutable TS shapes.
304        TypeRef::List(t, _) => TsType::readonly_array(ts_type_ref_to_ts_type(t, qualify)),
305        // K6a (#2596): an immutable, insertion-ordered JS `Set`.
306        TypeRef::Set(t, _) => {
307            TsType::named_with_args("ReadonlySet", vec![ts_type_ref_to_ts_type(t, qualify)])
308        }
309        // A `Query[T]`'s own real shape is `(() => readonly T[])`: an outer paren pair around
310        // the whole function type, which every fixture's own Query annotation has (e.g.
311        // `bynk-tests/tests/fixtures/positive/302_query_annotated_let/expected/probe.ts:46`).
312        TypeRef::Query(t, _) => {
313            let fn_ty = TsType::Fn {
314                rest: false,
315                names: vec![],
316                params: vec![],
317                ret: Box::new(query_result_ty(ts_type_ref_to_ts_type(t, qualify))),
318            };
319            TsType::paren(fn_ty)
320        }
321        // v0.100: `Stream[T]` lowers to a host async iterable.
322        TypeRef::Stream(t, _) => {
323            TsType::named_with_args("AsyncIterable", vec![ts_type_ref_to_ts_type(t, qualify)])
324        }
325        // v0.102: a `Connection[F]` lowers to the runtime `Connection<F>`
326        // interface (the concrete implementation arrives with the protocol).
327        TypeRef::Connection(t, _) => {
328            TsType::named_with_args("Connection", vec![ts_type_ref_to_ts_type(t, qualify)])
329        }
330        // v0.119: `History[Agent]` is a test-only generator with no emitted TS
331        // type — it never reaches a signature/field position (the property runner
332        // binds the driven history as an ordinary array). Rendered defensively.
333        TypeRef::History(_, _) => TsType::named("never"),
334        TypeRef::Map(k, v, _) => TsType::named_with_args(
335            "ReadonlyMap",
336            vec![
337                ts_type_ref_to_ts_type(k, qualify),
338                ts_type_ref_to_ts_type(v, qualify),
339            ],
340        ),
341        TypeRef::QueueResult(_) => TsType::named("QueueResult"),
342        TypeRef::Asset(_) => asset_ts_type(),
343        TypeRef::RequestHeaders(_) => request_headers_ts_type(),
344        TypeRef::RequestQuery(_) => request_query_ts_type(),
345        TypeRef::RequestCookies(_) => request_cookies_ts_type(),
346        TypeRef::TokenClaims(_) => token_claims_ts_type(),
347        TypeRef::BoundaryRejection(_) => {
348            TsType::named("{ readonly tag: string; readonly detail: string }")
349        }
350        TypeRef::ValidationError(_) => TsType::named("ValidationError"),
351        TypeRef::DecodeError(_) => TsType::named("DecodeError"),
352        TypeRef::Unit(_) => TsType::named("void"),
353        // v0.157 (ADR 0183): `Name[Arg, …]` lowers to the erased TS generic
354        // `Name<Arg, …>` — the generic record's interface is emitted with the
355        // same type parameters (like a generic function's erased `<A, B>`).
356        TypeRef::App { name, args, .. } => {
357            // Review of #1315/#1316: pre-slice this arm interpolated `head`
358            // unconditionally, so a hypothetical empty-args `App` rendered
359            // `Head<>` — `TsType::named_with_args(head, vec![])` instead
360            // renders bare `Head` (`TsType::Named`'s own printer only opens
361            // `<...>` when `type_args` is non-empty), a real behaviour
362            // change *if* this arm is ever reached with empty `args`. It
363            // isn't today: `ty_to_type_ref` only ever builds `App` with a
364            // non-empty argument list (this file, `ty_to_type_ref`'s own
365            // `Ty::Named` arm), and the resolver arity-checks a
366            // `Name[Arg, …]` application before either side ever sees one.
367            // Asserted, not silently relied on, so a future caller that
368            // *can* reach here with no args fails loudly instead of
369            // silently changing bytes.
370            debug_assert!(
371                !args.is_empty(),
372                "TypeRef::App is only ever built with a non-empty argument list"
373            );
374            let head = if let Some(f) = qualify
375                && let Some(ns) = f(&name.name)
376            {
377                format!("{ns}.{}", name.name)
378            } else {
379                name.name.clone()
380            };
381            let rendered: Vec<TsType> = args
382                .iter()
383                .map(|a| ts_type_ref_to_ts_type(a, qualify))
384                .collect();
385            TsType::named_with_args(head, rendered)
386        }
387        // v0.20a: a function type lowers to a TS function type. Positional
388        // parameter names (`a0`, `a1`, …) are the printer's own job now
389        // (`bynk_ts::print_type`'s `TsType::Fn` rendering) — TS requires
390        // names in function type syntax; an Effect return is already
391        // Promise via recursion.
392        TypeRef::Fn(params, ret, _) => {
393            let params: Vec<TsType> = params
394                .iter()
395                .map(|p| ts_type_ref_to_ts_type(p, qualify))
396                .collect();
397            let ret = ts_type_ref_to_ts_type(ret, qualify);
398            let ret = if is_bare_named(&ret, "()") {
399                TsType::named("void")
400            } else {
401                ret
402            };
403            TsType::Fn {
404                rest: false,
405                names: vec![],
406                params,
407                ret: Box::new(ret),
408            }
409        }
410    }
411}
412
413/// P7.9 (#1315): pins `ts_type_ref`'s exact pre-slice text for a
414/// representative `TypeRef` from every real shape category, the same
415/// discipline this track's own history names for "prove the test would
416/// actually catch it" (P7.2's `brand_assertion` gap, P7.3's escaping gap —
417/// both invisible to the byte-golden fixture corpus alone). These pin the
418/// literal strings `ts_type_ref_with` built by hand before this slice
419/// rebuilt it to construct a real `bynk_ts::TsType` and print that instead
420/// — a regression here is a regression in every type-position string the
421/// compiler emits, not caught by any one fixture necessarily exercising
422/// this exact shape.
423#[cfg(test)]
424mod ts_type_ref_tests {
425    use super::*;
426
427    /// A type reference as the text of its `TsType` node.
428    fn ts_type_ref(r: &TypeRef) -> String {
429        bynk_ts::print_type(&ts_type_of(r))
430    }
431
432    fn sp() -> bynk_syntax::span::Span {
433        bynk_syntax::span::Span::new(0, 0)
434    }
435
436    fn base(b: BaseType) -> TypeRef {
437        TypeRef::Base(b, sp())
438    }
439
440    fn named(name: &str) -> TypeRef {
441        TypeRef::Named(Ident {
442            name: name.to_string(),
443            span: sp(),
444        })
445    }
446
447    #[test]
448    fn bare_named_type() {
449        assert_eq!(ts_type_ref(&named("Order")), "Order");
450    }
451
452    #[test]
453    fn result_type() {
454        let r = TypeRef::Result(
455            Box::new(base(BaseType::Int)),
456            Box::new(named("MyError")),
457            sp(),
458        );
459        assert_eq!(ts_type_ref(&r), "Result<number, MyError>");
460    }
461
462    #[test]
463    fn option_type() {
464        let r = TypeRef::Option(Box::new(base(BaseType::String)), sp());
465        assert_eq!(ts_type_ref(&r), "Option<string>");
466    }
467
468    #[test]
469    fn effect_of_a_non_unit_type_becomes_promise() {
470        let r = TypeRef::Effect(Box::new(base(BaseType::Int)), sp());
471        assert_eq!(ts_type_ref(&r), "globalThis.Promise<number>");
472    }
473
474    #[test]
475    fn effect_of_unit_becomes_promise_void() {
476        let r = TypeRef::Effect(Box::new(TypeRef::Unit(sp())), sp());
477        assert_eq!(ts_type_ref(&r), "globalThis.Promise<void>");
478    }
479
480    #[test]
481    fn http_result_type() {
482        let r = TypeRef::HttpResult(Box::new(named("Order")), sp());
483        assert_eq!(ts_type_ref(&r), "HttpResult<Order>");
484    }
485
486    #[test]
487    fn list_is_a_readonly_array() {
488        let r = TypeRef::List(Box::new(named("Order")), sp());
489        assert_eq!(ts_type_ref(&r), "readonly Order[]");
490    }
491
492    /// The one shape this slice's own gap analysis found: `Query`'s real
493    /// text wraps the whole function type in an *extra* outer paren pair
494    /// (`(() => readonly T[])`), distinct from a bare `Fn` type's own
495    /// convention (no outer wrap) — caught only by this zero-diff check
496    /// against `bynk-tests/tests/fixtures/positive/302_query_annotated_let/
497    /// expected/probe.ts`, not by reasoning about the algebra alone.
498    #[test]
499    fn query_wraps_the_whole_function_type_in_parens() {
500        let r = TypeRef::Query(Box::new(named("Order")), sp());
501        assert_eq!(
502            ts_type_ref(&r),
503            "(() => readonly Order[] | globalThis.Promise<readonly Order[]>)"
504        );
505    }
506
507    #[test]
508    fn stream_is_an_async_iterable() {
509        let r = TypeRef::Stream(Box::new(named("Order")), sp());
510        assert_eq!(ts_type_ref(&r), "AsyncIterable<Order>");
511    }
512
513    #[test]
514    fn connection_type() {
515        let r = TypeRef::Connection(Box::new(named("Frame")), sp());
516        assert_eq!(ts_type_ref(&r), "Connection<Frame>");
517    }
518
519    #[test]
520    fn history_renders_defensively_as_never() {
521        let r = TypeRef::History(Box::new(named("Agent")), sp());
522        assert_eq!(ts_type_ref(&r), "never");
523    }
524
525    #[test]
526    fn map_is_a_readonly_map() {
527        let r = TypeRef::Map(
528            Box::new(base(BaseType::String)),
529            Box::new(named("Order")),
530            sp(),
531        );
532        assert_eq!(ts_type_ref(&r), "ReadonlyMap<string, Order>");
533    }
534
535    #[test]
536    fn the_four_bare_named_types() {
537        assert_eq!(ts_type_ref(&TypeRef::QueueResult(sp())), "QueueResult");
538        assert_eq!(
539            ts_type_ref(&TypeRef::ValidationError(sp())),
540            "ValidationError"
541        );
542        assert_eq!(ts_type_ref(&TypeRef::DecodeError(sp())), "DecodeError");
543        assert_eq!(ts_type_ref(&TypeRef::Unit(sp())), "void");
544    }
545
546    #[test]
547    fn app_is_a_generic_instantiation() {
548        let r = TypeRef::App {
549            name: Ident {
550                name: "MyGeneric".to_string(),
551                span: sp(),
552            },
553            args: vec![base(BaseType::Int), named("Order")],
554            span: sp(),
555        };
556        assert_eq!(ts_type_ref(&r), "MyGeneric<number, Order>");
557    }
558
559    #[test]
560    fn real_function_type_uses_positional_parameter_names() {
561        let r = TypeRef::Fn(
562            vec![base(BaseType::String), base(BaseType::Int)],
563            Box::new(named("Order")),
564            sp(),
565        );
566        assert_eq!(ts_type_ref(&r), "(a0: string, a1: number) => Order");
567    }
568
569    #[test]
570    fn base_types() {
571        assert_eq!(ts_type_ref(&base(BaseType::Int)), "number");
572        assert_eq!(ts_type_ref(&base(BaseType::Float)), "number");
573        assert_eq!(ts_type_ref(&base(BaseType::Duration)), "number");
574        assert_eq!(ts_type_ref(&base(BaseType::Instant)), "number");
575        assert_eq!(ts_type_ref(&base(BaseType::String)), "string");
576        assert_eq!(ts_type_ref(&base(BaseType::Bool)), "boolean");
577        assert_eq!(ts_type_ref(&base(BaseType::Bytes)), "globalThis.Uint8Array");
578    }
579
580    /// Coverage gap named in review of #1315/#1316: every test above goes
581    /// through `ts_type_ref` (`qualify = None`) — the qualifying branches
582    /// this slice's own refactor most directly restructured (`App`'s `head`
583    /// now flows through `TsType::named_with_args` instead of being
584    /// interpolated) were unpinned. Asserts both that the head qualifies
585    /// *and* that qualification recurses into the type arguments.
586    #[test]
587    fn qualified_generic_instantiation_qualifies_head_and_recurses_into_args() {
588        let r = TypeRef::App {
589            name: Ident {
590                name: "MyGeneric".to_string(),
591                span: sp(),
592            },
593            args: vec![base(BaseType::Int), named("Order")],
594            span: sp(),
595        };
596        let mut scope = HashSet::new();
597        scope.insert("MyGeneric".to_string());
598        scope.insert("Order".to_string());
599        assert_eq!(
600            bynk_ts::print_type(&ts_type_ref_qualified_ts_type(&r, &scope, "Ns")),
601            "Ns.MyGeneric<number, Ns.Order>"
602        );
603    }
604
605    /// Same shape as above, through `ts_type_ref_qualified_multi_ts_type` —
606    /// no direct test existed for this function at all before this fix.
607    #[test]
608    fn qualified_multi_generic_instantiation_qualifies_head_and_recurses_into_args() {
609        let r = TypeRef::App {
610            name: Ident {
611                name: "MyGeneric".to_string(),
612                span: sp(),
613            },
614            args: vec![base(BaseType::Int), named("Order")],
615            span: sp(),
616        };
617        let mut type_ns = HashMap::new();
618        type_ns.insert("MyGeneric".to_string(), "A".to_string());
619        type_ns.insert("Order".to_string(), "B".to_string());
620        assert_eq!(
621            bynk_ts::print_type(&ts_type_ref_qualified_multi_ts_type(&r, &type_ns)),
622            "A.MyGeneric<number, B.Order>"
623        );
624    }
625}
626
627/// #1927: how the module being emitted spells a type it names. A unit's own
628/// value (a function, asset, service, agent or provider) can hide a
629/// `uses`-imported type of its name. The unit's source may not write that
630/// type, but the lowering still names the types of checked expressions (#1778:
631/// a kernel's `(__x: Name) => …`, an `if` slot, `List.empty`), and in this
632/// module `Name` is the local value: a `const`, or for an agent or provider a
633/// `class`, whose instance type would capture the annotation. So while such a
634/// module is emitted, each hidden type is spelled as an inline import type,
635/// `import("<module>").Name`, which needs no import statement and names the
636/// declaring module's type whatever this module declares. Agents are never
637/// `Ty::Named`, so within the unit a hidden name always means the imported
638/// type.
639///
640/// Scoped per module and carried by [`TyRender`]: the spellings are a field of
641/// the unit's [`EmitProjectCtx`] (`type_spellings`), built by the driver from
642/// `shadowed_imports`, and every renderer reaches them through the `TyRender`
643/// it is handed instead of a thread-local.
644#[derive(Clone, Copy)]
645pub(crate) struct TyRender<'a> {
646    tys: &'a Arc<Types>,
647    spellings: &'a HashMap<String, String>,
648}
649
650impl<'a> TyRender<'a> {
651    /// The checker's interner plus the unit's hidden-type spellings.
652    pub(crate) fn new(tys: &'a Arc<Types>, spellings: &'a HashMap<String, String>) -> Self {
653        Self { tys, spellings }
654    }
655
656    /// The interner, for a caller that wants `Ty` structure and not text.
657    pub(crate) fn types(&self) -> &'a Arc<Types> {
658        self.tys
659    }
660
661    /// How the unit spells the type `name`: its rename, if any.
662    pub(crate) fn spelling(&self, name: &str) -> String {
663        self.spellings
664            .get(name)
665            .cloned()
666            .unwrap_or_else(|| name.to_string())
667    }
668}
669
670/// The spellings of a unit that hides no imported type (and of a lowering with
671/// no unit behind it): every name is spelled as itself.
672pub(crate) fn no_spellings() -> &'static HashMap<String, String> {
673    static NONE: std::sync::LazyLock<HashMap<String, String>> =
674        std::sync::LazyLock::new(HashMap::new);
675    &NONE
676}
677
678impl std::ops::Deref for TyRender<'_> {
679    type Target = Arc<Types>;
680    fn deref(&self) -> &Arc<Types> {
681        self.tys
682    }
683}
684
685/// What a store `Query[T]`'s thunk produces: its elements, or a promise of them (#3189). A
686/// collection backed by storage reads asynchronously; one held in memory does not, and the
687/// query algebra chains through `__bynkThen` so it serves either.
688pub(super) fn query_result_ty(elem: TsType) -> TsType {
689    let items = TsType::readonly_array(elem);
690    TsType::union(vec![
691        items.clone(),
692        TsType::named_with_args("globalThis.Promise", vec![items]),
693    ])
694}
695
696pub(super) fn ts_ty_to_ts_type(t: TyId, tys: TyRender<'_>) -> TsType {
697    match &*tys.get(t) {
698        // bynk internal error (finding #28, R4.3): `Ty::Error` records a
699        // resolution failure, which per R4.3 is always accompanied by a
700        // pushed diagnostic — the check that produced it should have failed
701        // the whole program and never reached emission. A loud failure here
702        // beats silently emitting a type for a node the checker gave up on.
703        Ty::Error => panic!(
704            "bynk internal error (finding #28): emitter asked to render `Ty::Error` as a \
705             TypeScript type — a checked program should never contain one"
706        ),
707        // #2620: the bottom type renders as TypeScript's own `never`.
708        Ty::Never => TsType::named("never"),
709        Ty::Base(b) => TsType::named(ts_base(*b)),
710        // #1977: the compiler-known `MapEntry[K, V]` (ADR 0184) has no
711        // `TypeDecl`, so no module declares or imports a `MapEntry` type to
712        // name. It renders as its own shape, the `{ key, value }` record the
713        // `.entries` lowering builds. (A user type of the same name, which the
714        // checker prefers for field access, interns to the same `Ty` and so
715        // renders inline too; no program declares one today.)
716        Ty::Named {
717            name,
718            kind: NamedKind::Record,
719            args,
720        } if name == MAP_ENTRY && args.len() == 2 => TsType::Object(vec![
721            bynk_ts::TsTypeMember::readonly_prop("key", ts_ty_to_ts_type(args[0], tys)),
722            bynk_ts::TsTypeMember::readonly_prop("value", ts_ty_to_ts_type(args[1], tys)),
723        ]),
724        // v0.157 (ADR 0183): a generic record instantiation renders as the
725        // erased TS generic `Name<Arg, …>`; a non-generic named type is bare.
726        Ty::Named { name, args, .. } if args.is_empty() => TsType::named(tys.spelling(name)),
727        Ty::Named { name, args, .. } => TsType::named_with_args(
728            tys.spelling(name),
729            args.iter().map(|a| ts_ty_to_ts_type(*a, tys)).collect(),
730        ),
731        Ty::Result(t, e) => TsType::named_with_args(
732            "Result",
733            vec![ts_ty_to_ts_type(*t, tys), ts_ty_to_ts_type(*e, tys)],
734        ),
735        Ty::Option(t) => TsType::named_with_args("Option", vec![ts_ty_to_ts_type(*t, tys)]),
736        Ty::Effect(t) => {
737            if matches!(&*tys.get(*t), Ty::Unit) {
738                TsType::named_with_args("globalThis.Promise", vec![TsType::named("void")])
739            } else {
740                TsType::named_with_args("globalThis.Promise", vec![ts_ty_to_ts_type(*t, tys)])
741            }
742        }
743        Ty::HttpResult(t) => TsType::named_with_args("HttpResult", vec![ts_ty_to_ts_type(*t, tys)]),
744        Ty::List(t) => TsType::readonly_array(ts_ty_to_ts_type(*t, tys)),
745        Ty::Set(t) => TsType::named_with_args("ReadonlySet", vec![ts_ty_to_ts_type(*t, tys)]),
746        // v0.91 (ADR 0119): a `Query[T]` lowers to a deferred producer of its
747        // elements — a thunk run by the terminal. Same outer-paren shape as
748        // `TypeRef::Query` (`ts_type_ref_to_ts_type`'s own comment explains
749        // the opaque-`Named` wrap this reuses, unchanged reasoning).
750        Ty::Query(t) => {
751            let fn_ty = TsType::Fn {
752                rest: false,
753                names: vec![],
754                params: vec![],
755                ret: Box::new(query_result_ty(ts_ty_to_ts_type(*t, tys))),
756            };
757            TsType::paren(fn_ty)
758        }
759        // v0.100: a `Stream[T]` lowers to a host async iterable.
760        Ty::Stream(t) => TsType::named_with_args("AsyncIterable", vec![ts_ty_to_ts_type(*t, tys)]),
761        // v0.102: a `Connection[F]` lowers to the runtime `Connection<F>` interface.
762        Ty::Connection(t) => TsType::named_with_args("Connection", vec![ts_ty_to_ts_type(*t, tys)]),
763        Ty::TestConnection(t) => {
764            TsType::named_with_args("TestConnection", vec![ts_ty_to_ts_type(*t, tys)])
765        }
766        Ty::Map(k, v) => TsType::named_with_args(
767            "ReadonlyMap",
768            vec![ts_ty_to_ts_type(*k, tys), ts_ty_to_ts_type(*v, tys)],
769        ),
770        Ty::QueueResult => TsType::named("QueueResult"),
771        // #1934: produced only by a `system`-tier test-service address, so
772        // only a test module meets them: the runtime's `HttpOutcome<T>`, and
773        // the shape of its `Rejected` payload.
774        Ty::HttpOutcome(t) => {
775            TsType::named_with_args("HttpOutcome", vec![ts_ty_to_ts_type(*t, tys)])
776        }
777        Ty::BoundaryRejection => TsType::named("{ readonly tag: string; readonly detail: string }"),
778        Ty::Asset => asset_ts_type(),
779        Ty::RequestHeaders => request_headers_ts_type(),
780        Ty::RequestQuery => request_query_ts_type(),
781        Ty::RequestCookies => request_cookies_ts_type(),
782        Ty::TokenClaims => token_claims_ts_type(),
783        Ty::ValidationError => TsType::named("ValidationError"),
784        Ty::DecodeError => TsType::named("DecodeError"),
785        Ty::Unit => TsType::named("void"),
786        Ty::Fn { params, ret } => TsType::Fn {
787            rest: false,
788            names: vec![],
789            params: params.iter().map(|p| ts_ty_to_ts_type(*p, tys)).collect(),
790            ret: Box::new(ts_ty_to_ts_type(*ret, tys)),
791        },
792        Ty::Var(n) => TsType::named(n.clone()),
793        // The identity type the actor binding yields (`name.identity`).
794        Ty::Actor(id) => ts_ty_to_ts_type(*id, tys),
795        // v0.52: a resolved multi-actor sum lowers to a discriminated union
796        // tagged by actor name; non-unit members carry their identity. Each
797        // member is a type literal (1A.39a, Decision G), so it prints with the
798        // object-type separator, `{ tag: "x"; identity: T }`.
799        Ty::ActorSum(members) => TsType::union(
800            members
801                .iter()
802                .map(|(name, id)| {
803                    let mut props = vec![bynk_ts::TsTypeMember::prop(
804                        "tag",
805                        TsType::string_literal(name.clone()),
806                    )];
807                    if !matches!(&*tys.get(*id), Ty::Unit) {
808                        props.push(bynk_ts::TsTypeMember::prop(
809                            "identity",
810                            ts_ty_to_ts_type(*id, tys),
811                        ));
812                    }
813                    TsType::Object(props)
814                })
815                .collect(),
816        ),
817    }
818}
819
820/// P7.9 (#1315): pins `ts_ty`'s exact pre-slice text for a representative
821/// `Ty` from every real shape category — the same "prove the test would
822/// actually catch it" discipline `ts_type_ref_tests` above already applies
823/// to `ts_type_ref`, and doubly important here since `ts_ty` is where
824/// `TsType::Union`/`ActorSum` (added in review of this same PR, beyond the
825/// accepted proposal's own gap list) is the one real, exercised caller.
826#[cfg(test)]
827mod ts_ty_tests {
828    use super::*;
829    use bynk_check::checker::{NamedKind, Types};
830
831    /// A checker type as the text the printer gives its `TsType`.
832    fn ts_ty(t: TyId, tys: TyRender<'_>) -> String {
833        bynk_ts::print_type(&ts_ty_to_ts_type(t, tys))
834    }
835
836    #[test]
837    fn base_types() {
838        let tys = Arc::new(Types::new());
839        assert_eq!(
840            ts_ty(
841                tys.intern(Ty::Base(BaseType::Int)),
842                TyRender::new(&tys, no_spellings())
843            ),
844            "number"
845        );
846    }
847
848    #[test]
849    fn named_type_bare_and_generic() {
850        let tys = Arc::new(Types::new());
851        let bare = tys.intern(Ty::Named {
852            name: "Order".to_string(),
853            kind: NamedKind::Record,
854            args: vec![],
855        });
856        assert_eq!(ts_ty(bare, TyRender::new(&tys, no_spellings())), "Order");
857
858        let arg = tys.intern(Ty::Base(BaseType::String));
859        let generic = tys.intern(Ty::Named {
860            name: "Paginated".to_string(),
861            kind: NamedKind::Record,
862            args: vec![arg],
863        });
864        assert_eq!(
865            ts_ty(generic, TyRender::new(&tys, no_spellings())),
866            "Paginated<string>"
867        );
868    }
869
870    #[test]
871    fn map_entry_renders_its_own_shape() {
872        // #1977: no module declares `MapEntry`, so it is never named.
873        let tys = Arc::new(Types::new());
874        let k = tys.intern(Ty::Base(BaseType::String));
875        let v = tys.intern(Ty::Base(BaseType::Int));
876        let entry = bynk_check::checker::map_entry_ty(k, v, &tys);
877        assert_eq!(
878            ts_ty(entry, TyRender::new(&tys, no_spellings())),
879            "{ readonly key: string; readonly value: number }"
880        );
881        let list = tys.intern(Ty::List(entry));
882        assert_eq!(
883            ts_ty(list, TyRender::new(&tys, no_spellings())),
884            "readonly { readonly key: string; readonly value: number }[]"
885        );
886    }
887
888    #[test]
889    fn result_option_effect_http_result() {
890        let tys = Arc::new(Types::new());
891        let int = tys.intern(Ty::Base(BaseType::Int));
892        let err = tys.intern(Ty::Named {
893            name: "MyError".to_string(),
894            kind: NamedKind::Record,
895            args: vec![],
896        });
897        let result = tys.intern(Ty::Result(int, err));
898        assert_eq!(
899            ts_ty(result, TyRender::new(&tys, no_spellings())),
900            "Result<number, MyError>"
901        );
902
903        let option = tys.intern(Ty::Option(int));
904        assert_eq!(
905            ts_ty(option, TyRender::new(&tys, no_spellings())),
906            "Option<number>"
907        );
908
909        let effect = tys.intern(Ty::Effect(int));
910        assert_eq!(
911            ts_ty(effect, TyRender::new(&tys, no_spellings())),
912            "globalThis.Promise<number>"
913        );
914
915        let unit = tys.intern(Ty::Unit);
916        let effect_unit = tys.intern(Ty::Effect(unit));
917        assert_eq!(
918            ts_ty(effect_unit, TyRender::new(&tys, no_spellings())),
919            "globalThis.Promise<void>"
920        );
921
922        let http_result = tys.intern(Ty::HttpResult(int));
923        assert_eq!(
924            ts_ty(http_result, TyRender::new(&tys, no_spellings())),
925            "HttpResult<number>"
926        );
927    }
928
929    #[test]
930    fn list_map_stream_connection() {
931        let tys = Arc::new(Types::new());
932        let order = tys.intern(Ty::Named {
933            name: "Order".to_string(),
934            kind: NamedKind::Record,
935            args: vec![],
936        });
937        assert_eq!(
938            ts_ty(
939                tys.intern(Ty::List(order)),
940                TyRender::new(&tys, no_spellings())
941            ),
942            "readonly Order[]"
943        );
944        // A nested list's inner readonly array is parenthesised (TS1354).
945        let orders = tys.intern(Ty::List(order));
946        assert_eq!(
947            ts_ty(
948                tys.intern(Ty::List(orders)),
949                TyRender::new(&tys, no_spellings())
950            ),
951            "readonly (readonly Order[])[]"
952        );
953
954        let s = tys.intern(Ty::Base(BaseType::String));
955        assert_eq!(
956            ts_ty(
957                tys.intern(Ty::Map(s, order)),
958                TyRender::new(&tys, no_spellings())
959            ),
960            "ReadonlyMap<string, Order>"
961        );
962        assert_eq!(
963            ts_ty(
964                tys.intern(Ty::Stream(order)),
965                TyRender::new(&tys, no_spellings())
966            ),
967            "AsyncIterable<Order>"
968        );
969        assert_eq!(
970            ts_ty(
971                tys.intern(Ty::Connection(order)),
972                TyRender::new(&tys, no_spellings())
973            ),
974            "Connection<Order>"
975        );
976    }
977
978    /// The same shared shape as `TypeRef::Query` — pins that `ts_ty`'s own
979    /// `Query` arm reproduces the identical outer-paren wrap after
980    /// conversion, not just `ts_type_ref`'s.
981    #[test]
982    fn query_wraps_the_whole_function_type_in_parens() {
983        let tys = Arc::new(Types::new());
984        let order = tys.intern(Ty::Named {
985            name: "Order".to_string(),
986            kind: NamedKind::Record,
987            args: vec![],
988        });
989        assert_eq!(
990            ts_ty(
991                tys.intern(Ty::Query(order)),
992                TyRender::new(&tys, no_spellings())
993            ),
994            "(() => readonly Order[] | globalThis.Promise<readonly Order[]>)"
995        );
996    }
997
998    #[test]
999    fn bare_types_and_fn() {
1000        let tys = Arc::new(Types::new());
1001        assert_eq!(
1002            ts_ty(
1003                tys.intern(Ty::QueueResult),
1004                TyRender::new(&tys, no_spellings())
1005            ),
1006            "QueueResult"
1007        );
1008        assert_eq!(
1009            ts_ty(
1010                tys.intern(Ty::ValidationError),
1011                TyRender::new(&tys, no_spellings())
1012            ),
1013            "ValidationError"
1014        );
1015        assert_eq!(
1016            ts_ty(
1017                tys.intern(Ty::DecodeError),
1018                TyRender::new(&tys, no_spellings())
1019            ),
1020            "DecodeError"
1021        );
1022        assert_eq!(
1023            ts_ty(tys.intern(Ty::Unit), TyRender::new(&tys, no_spellings())),
1024            "void"
1025        );
1026
1027        let int = tys.intern(Ty::Base(BaseType::Int));
1028        let s = tys.intern(Ty::Base(BaseType::String));
1029        let f = tys.intern(Ty::Fn {
1030            params: vec![int, s],
1031            ret: int,
1032        });
1033        assert_eq!(
1034            ts_ty(f, TyRender::new(&tys, no_spellings())),
1035            "(a0: number, a1: string) => number"
1036        );
1037    }
1038
1039    /// The real gap found during implementation review: a resolved
1040    /// multi-actor sum lowers to a genuine type-position union, tagged by
1041    /// actor name, non-unit members carrying their identity — the shape
1042    /// that motivated adding `TsType::Union` beyond the accepted proposal's
1043    /// own `readonly`/`Fn` gap list.
1044    #[test]
1045    fn actor_sum_is_a_tagged_union() {
1046        let tys = Arc::new(Types::new());
1047        let unit = tys.intern(Ty::Unit);
1048        let identity = tys.intern(Ty::Named {
1049            name: "AdminIdentity".to_string(),
1050            kind: NamedKind::Record,
1051            args: vec![],
1052        });
1053        let sum = tys.intern(Ty::ActorSum(vec![
1054            ("Guest".to_string(), unit),
1055            ("Admin".to_string(), identity),
1056        ]));
1057        assert_eq!(
1058            ts_ty(sum, TyRender::new(&tys, no_spellings())),
1059            "{ tag: \"Guest\" } | { tag: \"Admin\"; identity: AdminIdentity }"
1060        );
1061    }
1062
1063    /// Coverage gap named in review of #1315/#1316: `Ty::Var` (a type
1064    /// variable's own bare name) and `Ty::Actor` (delegates to its
1065    /// identity type) were unpinned.
1066    #[test]
1067    fn var_and_actor() {
1068        let tys = Arc::new(Types::new());
1069        assert_eq!(
1070            ts_ty(
1071                tys.intern(Ty::Var("T".to_string())),
1072                TyRender::new(&tys, no_spellings())
1073            ),
1074            "T"
1075        );
1076
1077        let identity = tys.intern(Ty::Named {
1078            name: "AdminIdentity".to_string(),
1079            kind: NamedKind::Record,
1080            args: vec![],
1081        });
1082        let actor = tys.intern(Ty::Actor(identity));
1083        assert_eq!(
1084            ts_ty(actor, TyRender::new(&tys, no_spellings())),
1085            "AdminIdentity"
1086        );
1087    }
1088}