Skip to main content

bynk_emit/emitter/
http_client.rs

1//! `bynk client` (#3508, slice BC1): the typed TypeScript client for a project's
2//! `from http` services, one module a front end imports.
3//!
4//! The command in `bynk/src/http_client.rs` reads each route's facts from the
5//! checked project (the wire-contract peek `bynk openapi` reads) and hands them
6//! over as an [`HttpClientInput`]; this module turns them into the module's text.
7//!
8//! # One codec, one source of truth
9//!
10//! Nothing here is a second implementation of the boundary. The codecs are the
11//! ones a Bynk *consumer* generates for a callee's types
12//! (`serialisation::emit_helpers_for_owner_qualified` under a qualifier, which
13//! inlines a transparent refinement's check and casts an opaque one), and each
14//! call site names them through `serialise_expr_via` / `deserialise_ref_via`,
15//! exactly as the foreign-caller client (`client.rs`, #1970) does. What differs is
16//! the half the codec does not own:
17//!
18//! - **Optional values are `T | null`** in the generated types (the maintainer's
19//!   decision on #3508), not Bynk's tagged `Option`. The codecs still speak
20//!   `Option`, so each boundary type is declared twice: the *wire* type
21//!   (`__Wire_Order`, what a codec produces and consumes) and the *public* type
22//!   (`Order`, what a caller sees), with a generated function per type between
23//!   them. A type with no `Option` reachable has no conversion, and the two are
24//!   the same shape.
25//! - **Refinements are checked on the way out** by running the decoder over the
26//!   value just encoded, so the predicates are the server's own and a violation is
27//!   returned as `CallFailure` before anything is sent. On the way in the
28//!   response is decoded by the same codecs.
29//! - **A route's answer is a union keyed by status**, built from the response set
30//!   `bynk openapi` documents, and never thrown.
31//!
32//! The runtime half is `http_client_runtime.ts` (generated from `runtime/src/client/http_client.ts`
33//! by `bundle.mjs`), inlined: a browser-safe subset
34//! with no signing and no Workers types, plus the runtime's own `result`, `bytes`,
35//! `decimal` and `keys` modules for just the names the codecs use.
36
37use std::collections::{BTreeMap, BTreeSet, HashMap};
38use std::fmt;
39use std::sync::Arc;
40
41use bynk_check::contract;
42use bynk_check::project_model::TypeDecl;
43use bynk_check::wire::TypeBody;
44use bynk_check::wire::TypeRef;
45use bynk_ts::{
46    TsArrowBody, TsBinaryOp, TsDecl, TsExpr, TsLit, TsObjectEntry, TsParam, TsProgram, TsStmt,
47    TsType, TsTypeMember,
48};
49
50use super::client::{SurfaceClosure, surface_closure};
51use super::runtime_use::RuntimeUse;
52use super::serialisation;
53
54mod route;
55
56/// The generated module's own type names. A boundary type of the same name is
57/// renamed (`Client` to `Client_`), never the surface.
58const SURFACE_TYPES: &[&str] = &[
59    "BoundaryError",
60    "CallFailure",
61    "Client",
62    "ClientOptions",
63    "JsonValue",
64    "Option",
65    "Result",
66    "ValidationError",
67];
68
69/// The wire shape of the standard `File`, a `@multipart` file part.
70const FILE_TYPE: &str = "export interface __Wire_File {\n  readonly filename: Option<string>;\n  readonly contentType: string;\n  readonly bytes: globalThis.Uint8Array;\n}\n";
71
72/// A file part's codec, which only the stand-in a multipart check passes reaches.
73const FILE_CODEC: &str = "export function __serialise_File(value: __Wire_File): __JsonValue {\n  return {\n    filename: value.filename.tag === \"Some\" ? { kind: \"Some\", value: value.filename.value } : { kind: \"None\" },\n    contentType: value.contentType,\n    bytes: __bynkBytesToBase64(value.bytes),\n  };\n}\n\nexport function __deserialise_File(json: __JsonValue, path: string = \"$\"): Result<__Wire_File, __BoundaryError> {\n  if (typeof json !== \"object\" || json === null || globalThis.Array.isArray(json)) {\n    return Err({ kind: \"StructuralMismatch\", path, expected: \"object\", actual: typeof json });\n  }\n  return Ok(json as unknown as __Wire_File);\n}\n";
74
75/// The names [`FILE_TYPE`] uses without declaring (1A.36a, Decision D).
76const FILE_TYPE_USES: &[&str] = &["Option"];
77
78/// The names [`FILE_CODEC`] uses without declaring: the wire type [`FILE_TYPE`]
79/// declares, the codec runtime and the result vocabulary.
80const FILE_CODEC_USES: &[&str] = &[
81    "__Wire_File",
82    "__JsonValue",
83    "__bynkBytesToBase64",
84    "__BoundaryError",
85    "Result",
86    "Ok",
87    "Err",
88];
89
90/// The prefix of a boundary type's wire declaration, the shape its codec makes.
91const WIRE_PREFIX: &str = "__Wire_";
92
93/// The runtime modules the codecs may reach, in dependency order: `bytes`, `decimal`,
94/// `time` (`IsoDate`), `keys` (`Map` and `Set`, which reads `decimal`), `text`
95/// (the code-point length of a `String` predicate).
96const OPTIONAL_MODULES: [(&str, &str); 5] = [
97    ("bytes", BYTES_MODULE),
98    ("decimal", DECIMAL_MODULE),
99    ("time", TIME_MODULE),
100    ("keys", KEYS_MODULE),
101    ("text", TEXT_MODULE),
102];
103
104const RUNTIME: &str = include_str!("http_client_runtime.ts");
105const RESULT_MODULE: &str = include_str!("../../runtime/src/result.ts");
106const BYTES_MODULE: &str = include_str!("../../runtime/src/bytes.ts");
107const DECIMAL_MODULE: &str = include_str!("../../runtime/src/decimal.ts");
108const KEYS_MODULE: &str = include_str!("../../runtime/src/keys.ts");
109const TIME_MODULE: &str = include_str!("../../runtime/src/time.ts");
110const TEXT_MODULE: &str = include_str!("../../runtime/src/text.ts");
111
112/// The `bynk client` experimental notice, in the generated header.
113const EXPERIMENTAL: &str = "Experimental: member names and the shape of this module may change in a minor version until it is stabilised.";
114
115/// What the command hands the generator.
116#[derive(Debug, Clone)]
117pub struct HttpClientInput {
118    pub services: Vec<ServiceInput>,
119    /// The compiler's version, for the header.
120    pub compiler_version: String,
121}
122
123/// One `from http` service.
124#[derive(Debug, Clone)]
125pub struct ServiceInput {
126    pub unit: String,
127    pub name: String,
128    pub doc: Option<String>,
129    /// The type namespace the service's signatures are written in.
130    pub types: HashMap<String, Arc<TypeDecl>>,
131    pub routes: Vec<RouteInput>,
132}
133
134/// One route of a service.
135#[derive(Debug, Clone)]
136pub struct RouteInput {
137    /// `GET`, `POST`, ...
138    pub method: String,
139    /// `/orders/:id`.
140    pub path: String,
141    pub doc: Option<String>,
142    /// In handler order.
143    pub params: Vec<ParamInput>,
144    /// The declared success type; `None` when it carries no value.
145    pub success: Option<TypeRef>,
146    pub replies: Vec<ReplyInput>,
147}
148
149/// What a route takes.
150#[derive(Debug, Clone)]
151pub enum ParamInput {
152    /// A path segment, typed.
153    Path { name: String, ty: TypeRef },
154    /// The body, in the form its route reads it.
155    Body { ty: TypeRef, kind: BodyKind },
156    /// The typed `query` record, whose type is a named record.
157    Query { ty: TypeRef },
158    /// The typed `cookies` record, whose type is a named record.
159    Cookies { ty: TypeRef },
160}
161
162/// How a route reads its `body`.
163#[derive(Debug, Clone, PartialEq, Eq)]
164pub enum BodyKind {
165    /// JSON, the default.
166    Json,
167    /// `@form`: `application/x-www-form-urlencoded`.
168    Form,
169    /// `@multipart`: `multipart/form-data`.
170    Multipart,
171    /// `@raw`: the caller's bytes, sent as written under the author's content type
172    /// (`None` for the wildcard `*/*`, which names none).
173    Raw { content_type: Option<String> },
174}
175
176/// One answer a route can make, in `bynk openapi`'s terms.
177#[derive(Debug, Clone, PartialEq, Eq)]
178pub struct ReplyInput {
179    pub status: u16,
180    /// The `HttpResult` variant name, or the boundary's own (`StructuralMismatch`).
181    pub variant: String,
182    pub payload: ReplyPayload,
183}
184
185/// What an answer's body carries.
186#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
187pub enum ReplyPayload {
188    /// The route's success value.
189    Value,
190    /// `{ "error": string }`.
191    Message,
192    /// A `Location` header.
193    Location,
194    /// Nothing.
195    None,
196    /// The boundary's own `400` body: a `BoundaryError`.
197    BoundaryError,
198    /// The boundary's own `413`/`415` body: `{ kind, details }`.
199    BoundaryRefusal,
200    /// An author-owned body, untouched (`RawCreated`, `RawStreamed`, `RawError`).
201    Raw,
202    /// A `Raw`: untouched, and on a small `GET` carrying a weak `ETag` the server made.
203    RawEtag,
204    /// A `RawTagged`: untouched, with the `ETag` its handler chose.
205    RawTagged,
206    /// A `Streaming` answer: server-sent events, each a `string`.
207    Events,
208}
209
210/// What a raw member says of the `ETag`.
211#[derive(Clone, Copy)]
212enum RawEtag {
213    None,
214    Maybe,
215    Required,
216}
217
218impl ReplyPayload {
219    /// The payload's name in a contract hash: spelt out, so renaming a variant of this
220    /// enum does not move every route's hash.
221    fn name(self) -> &'static str {
222        match self {
223            Self::Value => "Value",
224            Self::Message => "Message",
225            Self::Location => "Location",
226            Self::None => "None",
227            Self::BoundaryError => "BoundaryError",
228            Self::BoundaryRefusal => "BoundaryRefusal",
229            Self::Raw => "Raw",
230            Self::RawEtag => "RawEtag",
231            Self::RawTagged => "RawTagged",
232            Self::Events => "Events",
233        }
234    }
235
236    /// Whether the body is the caller's to read, not the client's to decode.
237    fn is_raw(self) -> bool {
238        matches!(self, Self::Raw | Self::RawEtag | Self::RawTagged)
239    }
240}
241
242/// Why a client cannot be generated.
243#[derive(Debug, Clone)]
244pub struct ClientError(pub String);
245
246impl fmt::Display for ClientError {
247    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
248        f.write_str(&self.0)
249    }
250}
251
252impl std::error::Error for ClientError {}
253
254fn fail<T>(message: impl Into<String>) -> Result<T, ClientError> {
255    Err(ClientError(message.into()))
256}
257
258/// How the client is laid out.
259#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
260pub enum Layout {
261    /// One module.
262    #[default]
263    File,
264    /// `index.ts`, `types.ts`, `codecs.ts` and `runtime.ts`.
265    Dir,
266}
267
268/// The files of a directory layout, in the order they are written.
269pub const DIR_FILES: [&str; 4] = ["index.ts", "types.ts", "codecs.ts", "runtime.ts"];
270
271/// The file name a single-file client has in [`Emitted::files`]: the caller
272/// writes it wherever `--out` says.
273pub const SINGLE_FILE: &str = "client.ts";
274
275/// The client, and the routes it leaves out with why.
276#[derive(Debug, Clone)]
277pub struct Emitted {
278    /// `(file name, text)`: one file, or the four of [`DIR_FILES`].
279    pub files: Vec<(String, String)>,
280    /// `` `GET /x` of `service`: why ``, one per route left out.
281    pub skipped: Vec<String>,
282}
283
284/// The module for `input`. A route whose types have no `T | null` form (an `Option`
285/// inside a `Map`, `Set` or `Result`, or an `Option[Option[T]]`) is left out and
286/// named, never emitted wrong.
287pub fn emit_http_client(input: &HttpClientInput, layout: Layout) -> Result<Emitted, ClientError> {
288    let (kept, skipped) = viable_routes(input)?;
289    if kept.services.is_empty() {
290        return fail(format!(
291            "no route of the selected services is one this version of `bynk client` can represent{}",
292            skipped
293                .iter()
294                .map(|s| format!("\n  {s}"))
295                .collect::<String>()
296        ));
297    }
298    let mut gen_ = Gen::new(closure_of(&kept)?);
299    let plan = gen_.plan(&kept)?;
300    let parts = gen_.emit(&kept, &plan)?;
301    Ok(Emitted {
302        files: assemble(&kept, parts, layout),
303        skipped,
304    })
305}
306
307/// The codec closure of every route of `input`.
308fn closure_of(input: &HttpClientInput) -> Result<SurfaceClosure, ClientError> {
309    let own_types = merge_types(&input.services)?;
310    let mut roots: Vec<TypeRef> = Vec::new();
311    for s in &input.services {
312        for r in &s.routes {
313            for p in &r.params {
314                match p {
315                    ParamInput::Path { ty, .. }
316                    | ParamInput::Body { ty, .. }
317                    | ParamInput::Query { ty }
318                    | ParamInput::Cookies { ty } => roots.push(ty.clone()),
319                }
320            }
321            roots.extend(r.success.iter().cloned());
322        }
323    }
324    Ok(surface_closure(&roots, &own_types, SURFACE_TYPES))
325}
326
327/// `input` without the routes that cannot be generated, and a note for each of those.
328fn viable_routes(input: &HttpClientInput) -> Result<(HttpClientInput, Vec<String>), ClientError> {
329    let mut trial = Gen::new(closure_of(input)?);
330    let plan = trial.plan(input)?;
331    let mut kept = input.clone();
332    let mut skipped = Vec::new();
333    for ((s, sp), out) in input
334        .services
335        .iter()
336        .zip(&plan.services)
337        .zip(&mut kept.services)
338    {
339        out.routes.clear();
340        for (r, rp) in s.routes.iter().zip(&sp.routes) {
341            let (convs, holds) = (trial.convs.clone(), trial.holds.clone());
342            match trial.route(&sp.key, r, rp, &s.types) {
343                Ok(_) => out.routes.push(r.clone()),
344                Err(e) => {
345                    (trial.convs, trial.holds) = (convs, holds);
346                    skipped.push(format!("`{} {}` of `{}`: {e}", r.method, r.path, s.name));
347                }
348            }
349        }
350    }
351    kept.services.retain(|s| !s.routes.is_empty());
352    Ok((kept, skipped))
353}
354
355/// Every service's types in one table. Two services of different units may name
356/// a type alike; one file cannot hold both.
357fn merge_types(services: &[ServiceInput]) -> Result<HashMap<String, Arc<TypeDecl>>, ClientError> {
358    let mut out: HashMap<String, Arc<TypeDecl>> = HashMap::new();
359    let mut owner: HashMap<String, &str> = HashMap::new();
360    for s in services {
361        for (name, decl) in &s.types {
362            match out.get(name) {
363                None => {
364                    out.insert(name.clone(), decl.clone());
365                    owner.insert(name.clone(), &s.unit);
366                }
367                Some(prev) => {
368                    if !Arc::ptr_eq(prev, decl) && format!("{prev:?}") != format!("{decl:?}") {
369                        return fail(format!(
370                            "`{}` and `{}` declare different types named `{}`; one client module cannot hold both. Generate them one at a time with `--service`",
371                            owner[name],
372                            s.unit,
373                            bynk_check::symbols::display_type_name(name)
374                        ));
375                    }
376                }
377            }
378        }
379    }
380    Ok(out)
381}
382
383/// Everything decided about names before any text is written.
384struct Plan {
385    services: Vec<ServicePlan>,
386}
387
388struct ServicePlan {
389    /// The property of the client this service's functions hang from.
390    key: String,
391    routes: Vec<RoutePlan>,
392}
393
394struct RoutePlan {
395    /// The function name, `getOrderById`.
396    function: String,
397    /// The response union's type name.
398    response: String,
399    /// The query argument's type name, when the route takes one.
400    query: Option<String>,
401    /// The cookies argument's type name, when the route takes one.
402    cookies: Option<String>,
403}
404
405/// One declared boundary type, as the two declarations need it.
406struct Gen {
407    sc: SurfaceClosure,
408    /// The names a codec names a type by in its own signatures: the wire types.
409    qual: HashMap<String, String>,
410    ru: RuntimeUse,
411    /// Generated conversion functions, by name.
412    convs: BTreeMap<String, Option<TsDecl>>,
413    /// Types already found to hold an `Option`, or not.
414    holds: HashMap<String, bool>,
415}
416
417#[derive(Clone, Copy, PartialEq, Eq)]
418enum Dir {
419    /// A decoded wire value to the public shape.
420    ToPublic,
421    /// A public value to the shape the encoder takes.
422    ToWire,
423}
424
425impl Dir {
426    fn prefix(self) -> &'static str {
427        match self {
428            Dir::ToPublic => "__toPublic_",
429            Dir::ToWire => "__toWire_",
430        }
431    }
432}
433
434impl Gen {
435    fn new(sc: SurfaceClosure) -> Self {
436        let mut qual: HashMap<String, String> = HashMap::new();
437        for n in sc.names.iter().chain(sc.generic_bases.iter()) {
438            qual.insert(n.clone(), format!("{WIRE_PREFIX}{n}"));
439        }
440        Gen {
441            sc,
442            qual,
443            ru: RuntimeUse::default(),
444            convs: BTreeMap::new(),
445            holds: HashMap::new(),
446        }
447    }
448
449    fn renamed(&self, t: &TypeRef) -> TypeRef {
450        serialisation::rename_type_ref(t, &self.sc.subst)
451    }
452
453    // -----------------------------------------------------------------
454    // Names
455    // -----------------------------------------------------------------
456
457    fn plan(&self, input: &HttpClientInput) -> Result<Plan, ClientError> {
458        let mut taken: BTreeSet<String> = self.sc.names.iter().cloned().collect();
459        taken.extend(self.sc.generic_bases.iter().cloned());
460        taken.extend(SURFACE_TYPES.iter().map(|s| s.to_string()));
461        let mut keys: BTreeSet<String> = BTreeSet::new();
462        let mut services = Vec::new();
463        // A response type is named for the function; two services' functions of
464        // one name take their service's name too.
465        let mut seen: BTreeMap<String, usize> = BTreeMap::new();
466        for s in &input.services {
467            for r in &s.routes {
468                *seen.entry(function_name(&r.method, &r.path)).or_default() += 1;
469            }
470        }
471        for s in &input.services {
472            let mut key = s.name.clone();
473            if keys.contains(&key) {
474                key = format!("{}_{}", s.unit.replace('.', "_"), s.name);
475            }
476            keys.insert(key.clone());
477            let mut fns: BTreeMap<String, &RouteInput> = BTreeMap::new();
478            let mut routes = Vec::new();
479            for r in &s.routes {
480                let function = function_name(&r.method, &r.path);
481                if let Some(other) = fns.insert(function.clone(), r) {
482                    return fail(format!(
483                        "`{} {}` and `{} {}` of service `{}` both make the function `{function}`; the client cannot name them apart",
484                        other.method, other.path, r.method, r.path, s.name
485                    ));
486                }
487                let stem = if seen[&function] > 1 {
488                    format!("{}{}", pascal(&s.name), pascal(&function))
489                } else {
490                    pascal(&function)
491                };
492                let response = unique(format!("{stem}Response"), &mut taken);
493                let has_query = r
494                    .params
495                    .iter()
496                    .any(|p| matches!(p, ParamInput::Query { .. }));
497                let query = has_query.then(|| unique(format!("{stem}Query"), &mut taken));
498                let has_cookies = r
499                    .params
500                    .iter()
501                    .any(|p| matches!(p, ParamInput::Cookies { .. }));
502                let cookies = has_cookies.then(|| unique(format!("{stem}Cookies"), &mut taken));
503                routes.push(RoutePlan {
504                    function,
505                    response,
506                    query,
507                    cookies,
508                });
509            }
510            services.push(ServicePlan { key, routes });
511        }
512        Ok(Plan { services })
513    }
514
515    // -----------------------------------------------------------------
516    // Types
517    // -----------------------------------------------------------------
518
519    /// The type a caller sees: `Option[T]` is `T | null`.
520    fn public_type(&self, t: &TypeRef) -> Result<TsType, ClientError> {
521        Ok(match t {
522            TypeRef::Option(inner, _) => {
523                if matches!(inner.as_ref(), TypeRef::Option(..)) {
524                    return fail("an `Option[Option[T]]` has no `T | null` form");
525                }
526                TsType::union(vec![self.public_type(inner)?, TsType::named("null")])
527            }
528            TypeRef::List(inner, _) => TsType::readonly_array(self.public_type(inner)?),
529            TypeRef::Set(inner, _) => {
530                TsType::named_with_args("ReadonlySet", vec![self.public_type(inner)?])
531            }
532            TypeRef::Map(k, v, _) => TsType::named_with_args(
533                "ReadonlyMap",
534                vec![self.public_type(k)?, self.public_type(v)?],
535            ),
536            TypeRef::Result(a, b, _) => {
537                TsType::named_with_args("Result", vec![self.public_type(a)?, self.public_type(b)?])
538            }
539            TypeRef::App { name, args, .. } => {
540                let args: Result<Vec<TsType>, ClientError> =
541                    args.iter().map(|a| self.public_type(a)).collect();
542                TsType::named_with_args(name.name.clone(), args?)
543            }
544            // A `@multipart` file part: the standard `File` is a `Blob` here, which
545            // is what a `File` input yields, and what `fetch` appends.
546            TypeRef::Named(id) if self.is_file(&id.name) => TsType::named("globalThis.Blob"),
547            other @ TypeRef::Base(..)
548            | other @ TypeRef::Named(_)
549            | other @ TypeRef::Effect(..)
550            | other @ TypeRef::HttpResult(..)
551            | other @ TypeRef::QueueResult(_)
552            | other @ TypeRef::Asset(_)
553            | other @ TypeRef::RequestHeaders(_)
554            | other @ TypeRef::RequestQuery(_)
555            | other @ TypeRef::RequestCookies(_)
556            | other @ TypeRef::TokenClaims(_)
557            | other @ TypeRef::BoundaryRejection(_)
558            | other @ TypeRef::Query(..)
559            | other @ TypeRef::Stream(..)
560            | other @ TypeRef::Connection(..)
561            | other @ TypeRef::History(..)
562            | other @ TypeRef::ValidationError(_)
563            | other @ TypeRef::DecodeError(_)
564            | other @ TypeRef::Unit(_)
565            | other @ TypeRef::Fn(..) => {
566                super::ts_types::ts_type_ref_qualified_multi_ts_type(other, &HashMap::new())
567            }
568        })
569    }
570
571    /// Whether `name` is the standard library's `File`, the part of a `@multipart`
572    /// body that carries a file (`bynk.File`: `filename`, `contentType`, `bytes`).
573    fn is_file(&self, name: &str) -> bool {
574        if bynk_check::symbols::display_type_name(name) != "File" {
575            return false;
576        }
577        match self.sc.types.get(name).map(|d| &d.body) {
578            // The standard `File` is declared by the `bynk` unit, which a service's
579            // own type table does not hold.
580            None => name == "File" || name == "bynk__File",
581            Some(TypeBody::Record(r)) => {
582                let fields: Vec<&str> = r.fields.iter().map(|f| f.name.name.as_str()).collect();
583                fields == ["filename", "contentType", "bytes"]
584            }
585            Some(_) => false,
586        }
587    }
588
589    /// The type a codec makes and takes.
590    fn wire_type(&self, t: &TypeRef) -> TsType {
591        serialisation::qualified_ts_type(t, &self.qual)
592    }
593
594    /// One boundary type's declaration, in whichever of its two shapes `ty` renders.
595    fn declare(
596        &self,
597        name: &str,
598        decl: &TypeDecl,
599        public: bool,
600    ) -> Result<Vec<TsStmt>, ClientError> {
601        let ty = |t: &TypeRef| -> Result<TsType, ClientError> {
602            if public {
603                self.public_type(t)
604            } else {
605                Ok(self.wire_type(t))
606            }
607        };
608        let params: Vec<String> = decl
609            .type_params
610            .iter()
611            .map(|p| p.name.name.clone())
612            .collect();
613        let shown = if public {
614            name.to_string()
615        } else {
616            format!("{WIRE_PREFIX}{name}")
617        };
618        let d = match &decl.body {
619            TypeBody::Record(r) => {
620                let mut members = Vec::new();
621                for f in &r.fields {
622                    members.push(TsTypeMember::readonly_prop(
623                        f.name.name.clone(),
624                        ty(&f.type_ref)?,
625                    ));
626                }
627                TsDecl::Interface {
628                    name: shown,
629                    type_params: params,
630                    members,
631                }
632            }
633            TypeBody::Sum(sum) => {
634                let mut variants = Vec::new();
635                for v in &sum.variants {
636                    let mut members = vec![TsTypeMember::readonly_prop(
637                        "tag",
638                        TsType::named(format!("\"{}\"", v.name.name)),
639                    )];
640                    for f in &v.payload {
641                        members.push(TsTypeMember::readonly_prop(
642                            super::payload_prop(&f.name.name),
643                            ty(&f.type_ref)?,
644                        ));
645                    }
646                    variants.push(TsType::Object(members));
647                }
648                TsDecl::TypeAlias {
649                    name: shown,
650                    type_params: params,
651                    ty: TsType::multiline_union(variants),
652                }
653            }
654            TypeBody::Refined {
655                base, base_span, ..
656            } => TsDecl::TypeAlias {
657                name: shown,
658                type_params: params,
659                ty: ty(&TypeRef::Base(*base, *base_span))?,
660            },
661            TypeBody::Opaque {
662                base, base_span, ..
663            } => TsDecl::TypeAlias {
664                name: shown,
665                type_params: params,
666                ty: TsType::intersection(vec![
667                    ty(&TypeRef::Base(*base, *base_span))?,
668                    TsType::Object(vec![TsTypeMember::readonly_prop(
669                        "__opaque",
670                        TsType::named(format!("\"{name}\"")),
671                    )]),
672                ]),
673            },
674        };
675        let mut out = Vec::new();
676        if public && let Some(text) = decl.documentation.as_deref() {
677            out.push(TsStmt::doc_comment(text, None));
678        }
679        let mut stmt = TsStmt::decl(TsDecl::Export(Box::new(d)), None);
680        stmt.no_blank_before = !out.is_empty();
681        out.push(stmt);
682        Ok(out)
683    }
684
685    // -----------------------------------------------------------------
686    // Conversions between the wire shape and the public one
687    // -----------------------------------------------------------------
688
689    /// Whether a value of `t` holds an `Option` anywhere, so converts.
690    fn holds_option(&mut self, t: &TypeRef) -> bool {
691        match t {
692            TypeRef::Option(..) => true,
693            TypeRef::List(i, _) | TypeRef::Set(i, _) => self.holds_option(i),
694            TypeRef::Map(k, v, _) | TypeRef::Result(k, v, _) => {
695                self.holds_option(k) || self.holds_option(v)
696            }
697            TypeRef::Named(id) => {
698                let key = id.name.clone();
699                self.named_holds(&key, &key, &[])
700            }
701            TypeRef::App { name, args, .. } => {
702                let key = serialisation::app_ts_name(&name.name, args);
703                self.named_holds(&key, &name.name, args)
704            }
705            TypeRef::Base(..)
706            | TypeRef::Effect(..)
707            | TypeRef::HttpResult(..)
708            | TypeRef::QueueResult(_)
709            | TypeRef::Asset(_)
710            | TypeRef::RequestHeaders(_)
711            | TypeRef::RequestQuery(_)
712            | TypeRef::RequestCookies(_)
713            | TypeRef::TokenClaims(_)
714            | TypeRef::BoundaryRejection(_)
715            | TypeRef::Query(..)
716            | TypeRef::Stream(..)
717            | TypeRef::Connection(..)
718            | TypeRef::History(..)
719            | TypeRef::ValidationError(_)
720            | TypeRef::DecodeError(_)
721            | TypeRef::Unit(_)
722            | TypeRef::Fn(..) => false,
723        }
724    }
725
726    fn named_holds(&mut self, key: &str, decl: &str, args: &[TypeRef]) -> bool {
727        if let Some(h) = self.holds.get(key) {
728            return *h;
729        }
730        // A type met again while being decided is no new reason to convert.
731        self.holds.insert(key.to_string(), false);
732        let fields = self.fields_of(decl, args);
733        let found = fields.iter().any(|f| self.holds_option(&f.1));
734        self.holds.insert(key.to_string(), found);
735        found
736    }
737
738    /// The `(variant, [(field, type)])` list of a record or sum, with a generic
739    /// declaration's parameters replaced by `args`. A record is one unnamed variant.
740    fn variants_of(&self, decl: &str, args: &[TypeRef]) -> Option<(bool, Vec<Variant>)> {
741        let types = &self.sc.types;
742        let d = types.get(decl)?;
743        match &d.body {
744            TypeBody::Record(_) => {
745                let fields = if args.is_empty() {
746                    let TypeBody::Record(r) = &d.body else {
747                        return None;
748                    };
749                    r.fields
750                        .iter()
751                        .map(|f| (f.name.name.clone(), f.type_ref.clone()))
752                        .collect()
753                } else {
754                    bynk_check::wire::record_inst_fields(decl, args, types)?
755                };
756                Some((true, vec![(String::new(), fields)]))
757            }
758            TypeBody::Sum(_) => {
759                if args.is_empty() {
760                    let TypeBody::Sum(s) = &d.body else {
761                        return None;
762                    };
763                    Some((
764                        false,
765                        s.variants
766                            .iter()
767                            .map(|v| {
768                                (
769                                    v.name.name.clone(),
770                                    v.payload
771                                        .iter()
772                                        .map(|f| (f.name.name.clone(), f.type_ref.clone()))
773                                        .collect(),
774                                )
775                            })
776                            .collect(),
777                    ))
778                } else {
779                    Some((
780                        false,
781                        bynk_check::wire::sum_inst_variants(decl, args, types)?,
782                    ))
783                }
784            }
785            TypeBody::Refined { .. } | TypeBody::Opaque { .. } => None,
786        }
787    }
788
789    fn fields_of(&self, decl: &str, args: &[TypeRef]) -> Vec<(String, TypeRef)> {
790        self.variants_of(decl, args)
791            .map(|(_, vs)| vs.into_iter().flat_map(|v| v.1).collect())
792            .unwrap_or_default()
793    }
794
795    /// `expr`, a value of `t`, converted in direction `dir`. `depth` numbers the
796    /// lambda parameters.
797    fn convert(
798        &mut self,
799        t: &TypeRef,
800        dir: Dir,
801        expr: TsExpr,
802        depth: usize,
803    ) -> Result<TsExpr, ClientError> {
804        if !self.holds_option(t) {
805            return Ok(expr);
806        }
807        let x = format!("x{depth}");
808        let lambda = |body: TsExpr| TsExpr::Arrow {
809            params: vec![TsParam::new(x.clone(), None)],
810            is_async: false,
811            generics: Vec::new(),
812            return_type: None,
813            body: Box::new(TsArrowBody::Expr(Box::new(body))),
814        };
815        match t {
816            TypeRef::Option(inner, _) => {
817                if matches!(inner.as_ref(), TypeRef::Option(..)) {
818                    return fail("an `Option[Option[T]]` has no `T | null` form");
819                }
820                let body = self.convert(inner, dir, TsExpr::Ident(x.clone()), depth + 1)?;
821                let f = match dir {
822                    Dir::ToPublic => "__optToNull",
823                    Dir::ToWire => "__nullToOpt",
824                };
825                Ok(TsExpr::Call {
826                    callee: Box::new(TsExpr::Ident(f.to_string())),
827                    args: vec![expr, lambda(body)],
828                })
829            }
830            TypeRef::List(inner, _) => {
831                let body = self.convert(inner, dir, TsExpr::Ident(x.clone()), depth + 1)?;
832                Ok(TsExpr::Call {
833                    callee: Box::new(TsExpr::Member {
834                        object: Box::new(expr),
835                        property: "map".to_string(),
836                    }),
837                    args: vec![lambda(body)],
838                })
839            }
840            TypeRef::Set(..) | TypeRef::Map(..) | TypeRef::Result(..) => fail(
841                "an `Option` inside a `Map`, `Set` or `Result` has no `T | null` form in this version of `bynk client`",
842            ),
843            TypeRef::Named(id) => {
844                let key = id.name.clone();
845                self.named_conversion(&key, &key, &[], t, dir)?;
846                Ok(conversion_call(dir, &key, expr))
847            }
848            TypeRef::App { name, args, .. } => {
849                let key = serialisation::app_ts_name(&name.name, args);
850                self.named_conversion(&key, &name.name, args, t, dir)?;
851                Ok(conversion_call(dir, &key, expr))
852            }
853            TypeRef::Base(..)
854            | TypeRef::Effect(..)
855            | TypeRef::HttpResult(..)
856            | TypeRef::QueueResult(_)
857            | TypeRef::Asset(_)
858            | TypeRef::RequestHeaders(_)
859            | TypeRef::RequestQuery(_)
860            | TypeRef::RequestCookies(_)
861            | TypeRef::TokenClaims(_)
862            | TypeRef::BoundaryRejection(_)
863            | TypeRef::Query(..)
864            | TypeRef::Stream(..)
865            | TypeRef::Connection(..)
866            | TypeRef::History(..)
867            | TypeRef::ValidationError(_)
868            | TypeRef::DecodeError(_)
869            | TypeRef::Unit(_)
870            | TypeRef::Fn(..) => Ok(expr),
871        }
872    }
873
874    /// Build (once) the function converting values of the record or sum `t`.
875    fn named_conversion(
876        &mut self,
877        key: &str,
878        decl: &str,
879        args: &[TypeRef],
880        t: &TypeRef,
881        dir: Dir,
882    ) -> Result<(), ClientError> {
883        let name = format!("{}{key}", dir.prefix());
884        if self.convs.contains_key(&name) {
885            return Ok(());
886        }
887        // Reserve the name first, so a type that holds itself terminates.
888        self.convs.insert(name.clone(), None);
889        let Some((is_record, variants)) = self.variants_of(decl, args) else {
890            return Ok(());
891        };
892        let (wire, public) = (self.wire_type(t), self.public_type(t)?);
893        let (from, to) = match dir {
894            Dir::ToPublic => (wire, public),
895            Dir::ToWire => (public, wire),
896        };
897        let v = || TsExpr::Ident("v".to_string());
898        let mut body = Vec::new();
899        for (variant, fields) in &variants {
900            let mut entries = vec![TsObjectEntry::Spread(v())];
901            let mut converted = false;
902            for (field, ft) in fields {
903                if self.holds_option(ft) {
904                    let prop = if is_record {
905                        field.clone()
906                    } else {
907                        super::payload_prop(field)
908                    };
909                    let from_prop = TsExpr::Member {
910                        object: Box::new(v()),
911                        property: prop.clone(),
912                    };
913                    let conv = self.convert(ft, dir, from_prop, 0)?;
914                    entries.push(TsObjectEntry::prop(prop, conv));
915                    converted = true;
916                }
917            }
918            if !converted {
919                continue;
920            }
921            let object = cast_via_unknown(TsExpr::object_entries(entries), &to);
922            if is_record {
923                body.push(TsStmt::return_stmt(Some(object), None));
924            } else {
925                let is_variant = TsExpr::Binary {
926                    op: TsBinaryOp::StrictEq,
927                    left: Box::new(TsExpr::Member {
928                        object: Box::new(v()),
929                        property: "tag".to_string(),
930                    }),
931                    right: Box::new(TsExpr::Lit(TsLit::Str(variant.clone()))),
932                };
933                body.push(TsStmt::if_stmt(
934                    is_variant,
935                    TsStmt::return_stmt(Some(object), None),
936                    None,
937                ));
938            }
939        }
940        if !is_record {
941            body.push(TsStmt::return_stmt(Some(cast_via_unknown(v(), &to)), None));
942        }
943        self.convs.insert(
944            name.clone(),
945            Some(TsDecl::Function {
946                name,
947                generics: Vec::new(),
948                params: vec![TsParam::new("v", Some(from))],
949                return_type: Some(to),
950                body,
951                is_async: false,
952                inline: false,
953            }),
954        );
955        Ok(())
956    }
957
958    // -----------------------------------------------------------------
959    // The module
960    // -----------------------------------------------------------------
961
962    fn emit(&mut self, input: &HttpClientInput, plan: &Plan) -> Result<Parts, ClientError> {
963        let mut stmts: Vec<TsStmt> = Vec::new();
964
965        // The route glue is built first: it decides which conversions exist.
966        let mut glue: Vec<TsStmt> = Vec::new();
967        let mut unions: Vec<TsStmt> = Vec::new();
968        let mut services: Vec<TsObjectEntry> = Vec::new();
969        let mut contracts: Vec<TsObjectEntry> = Vec::new();
970        for (s, sp) in input.services.iter().zip(&plan.services) {
971            let mut methods: Vec<TsObjectEntry> = Vec::new();
972            let mut hashes: Vec<(String, String)> = Vec::new();
973            for (r, rp) in s.routes.iter().zip(&sp.routes) {
974                let route = self.route(&sp.key, r, rp, &s.types)?;
975                hashes.push((rp.function.clone(), route.hash.clone()));
976                glue.push(route.constant);
977                unions.extend(route.response_type.into_iter().flatten());
978                unions.extend(route.arg_types);
979                methods.push(route.method);
980            }
981            services.push(TsObjectEntry::prop(
982                property(&sp.key),
983                TsExpr::multiline_object_entries(methods),
984            ));
985            let all: Vec<String> = hashes.iter().map(|(_, h)| h.clone()).collect();
986            let routes = hashes
987                .iter()
988                .map(|(function, hash)| {
989                    TsObjectEntry::prop(property(function), TsExpr::Lit(TsLit::Str(hash.clone())))
990                })
991                .collect();
992            contracts.push(TsObjectEntry::prop(
993                property(&sp.key),
994                TsExpr::multiline_object_entries(vec![
995                    TsObjectEntry::prop(
996                        "service",
997                        TsExpr::Lit(TsLit::Str(contract::http_service_contract_hash(&all))),
998                    ),
999                    TsObjectEntry::prop("routes", TsExpr::multiline_object_entries(routes)),
1000                ]),
1001            ));
1002        }
1003
1004        // Boundary types, public then wire, then the codecs over the wire ones.
1005        let mut type_names: Vec<String> = self
1006            .sc
1007            .names
1008            .iter()
1009            .filter(|n| {
1010                self.sc
1011                    .types
1012                    .get(*n)
1013                    .is_some_and(|d| d.type_params.is_empty())
1014            })
1015            .cloned()
1016            .collect();
1017        type_names.extend(self.sc.generic_bases.iter().cloned());
1018        type_names.sort();
1019        type_names.dedup();
1020        for public in [true, false] {
1021            for name in &type_names {
1022                // A file part is a `Blob` to the caller: it has no public declaration.
1023                if public && self.is_file(name) {
1024                    continue;
1025                }
1026                if let Some(decl) = self.sc.types.get(name) {
1027                    stmts.extend(self.declare(name, decl, public)?);
1028                }
1029            }
1030        }
1031        stmts.extend(unions);
1032        let mut codecs: Vec<TsStmt> = Vec::new();
1033        // A file part has no codec in the project's own table: the caller's bytes
1034        // are not the client's to encode, so its wire form is a stand-in the decoder
1035        // accepts, and the part itself goes into the `FormData`.
1036        if self.sc.names.iter().any(|n| self.is_file(n)) {
1037            // 1A.38: fixed authored snippet, no interpolation
1038            stmts.push(TsStmt::raw_using(FILE_TYPE, FILE_TYPE_USES));
1039            // 1A.38: fixed authored snippet, no interpolation
1040            codecs.push(TsStmt::raw_using(FILE_CODEC, FILE_CODEC_USES));
1041        }
1042        let types = self.sc.types.clone();
1043        codecs.extend(serialisation::decls_as_stmts(
1044            serialisation::emit_helpers_for_owner_qualified(
1045                &self.sc.names,
1046                &types,
1047                "",
1048                &self.qual,
1049                &self.ru,
1050            ),
1051        ));
1052        codecs.extend(serialisation::decls_as_stmts(
1053            serialisation::emit_generic_helpers_qualified(
1054                &self.sc.insts,
1055                &types,
1056                &self.qual,
1057                &self.ru,
1058            ),
1059        ));
1060        for decl in self.convs.values().flatten() {
1061            codecs.push(TsStmt::decl(TsDecl::Export(Box::new(decl.clone())), None));
1062        }
1063        let mut index: Vec<TsStmt> = glue;
1064        index.extend(contracts_stmts(contracts));
1065        index.extend(client_stmts(services));
1066
1067        let print = |stmts: Vec<TsStmt>| {
1068            // A refinement's `field` names the type the codec was given: the
1069            // declared one, not its wire alias.
1070            bynk_ts::print(&TsProgram { stmts }, "", "", "client.ts")
1071                .text
1072                .replace(&format!("field: \"{WIRE_PREFIX}"), "field: \"")
1073        };
1074        Ok(Parts {
1075            types: print(stmts),
1076            codecs: print(codecs),
1077            index: print(index),
1078        })
1079    }
1080}
1081
1082type Variant = (String, Vec<(String, TypeRef)>);
1083
1084/// `__toPublic_Key(expr)`, the call of a generated conversion.
1085fn conversion_call(dir: Dir, key: &str, expr: TsExpr) -> TsExpr {
1086    let function = format!("{}{key}", dir.prefix());
1087    TsExpr::Call {
1088        callee: Box::new(TsExpr::Ident(function)),
1089        args: vec![expr],
1090    }
1091}
1092
1093/// A documented export that follows its own doc comment with no blank line between.
1094fn documented(doc: &str, decl: TsDecl) -> Vec<TsStmt> {
1095    let mut stmt = TsStmt::decl(TsDecl::Export(Box::new(decl)), None);
1096    stmt.no_blank_before = true;
1097    vec![TsStmt::doc_comment(doc, None), stmt]
1098}
1099
1100/// `export const API_CONTRACTS = { .. } as const;` under its doc block: the hash of
1101/// each service and route.
1102fn contracts_stmts(services: Vec<TsObjectEntry>) -> Vec<TsStmt> {
1103    documented(
1104        "The contract of each service and route this client was generated for: a hash of\nwhat a client acts on (the route's method and path, what it takes, what it can\nanswer). It moves when that does and not for a handler's body. Informational: log\nit, compare it with the server's, or send it with `sendContract`.",
1105        TsDecl::ConstDecl {
1106            name: "API_CONTRACTS".to_string(),
1107            ty: None,
1108            init: TsExpr::AsConst(Box::new(TsExpr::multiline_object_entries(services))),
1109        },
1110    )
1111}
1112
1113/// `createClient` and the `Client` type, each under its doc comment.
1114fn client_stmts(services: Vec<TsObjectEntry>) -> Vec<TsStmt> {
1115    let mut out = documented(
1116        "The client: one property per service, one function per route. Each returns\nthe route's own response, a union keyed by `status`, or a `CallFailure`.",
1117        TsDecl::Function {
1118            name: "createClient".to_string(),
1119            generics: Vec::new(),
1120            params: vec![
1121                TsParam::new("options", Some(TsType::named("ClientOptions")))
1122                    .with_default(TsExpr::object(Vec::new())),
1123            ],
1124            return_type: None,
1125            body: vec![TsStmt::return_stmt(
1126                Some(TsExpr::AsConst(Box::new(TsExpr::multiline_object_entries(
1127                    services,
1128                )))),
1129                None,
1130            )],
1131            is_async: false,
1132            inline: false,
1133        },
1134    );
1135    out.extend(documented(
1136        "The client `createClient` makes.",
1137        TsDecl::TypeAlias {
1138            name: "Client".to_string(),
1139            type_params: Vec::new(),
1140            ty: TsType::named_with_args(
1141                "ReturnType",
1142                vec![TsType::type_of(TsExpr::Ident("createClient".to_string()))],
1143            ),
1144        },
1145    ));
1146    out
1147}
1148
1149/// `expr as unknown as ty`.
1150fn cast_via_unknown(expr: TsExpr, ty: &TsType) -> TsExpr {
1151    TsExpr::As {
1152        expr: Box::new(TsExpr::As {
1153            expr: Box::new(expr),
1154            ty: TsType::named("unknown"),
1155        }),
1156        ty: ty.clone(),
1157    }
1158}
1159
1160// ---------------------------------------------------------------------
1161// Names
1162// ---------------------------------------------------------------------
1163
1164/// `GET /orders/:id` is `getOrderById`; `POST /orders` is `postOrders`. A
1165/// static segment before a parameter is singular (`orders/:id` reads "order by
1166/// id"). A route has no name of its own to use (#3508 open question 4).
1167pub fn function_name(method: &str, path: &str) -> String {
1168    let segments: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
1169    let mut out = method.to_lowercase();
1170    if segments.is_empty() {
1171        out.push_str("Root");
1172    }
1173    for (i, seg) in segments.iter().enumerate() {
1174        if let Some(param) = seg.strip_prefix(':') {
1175            out.push_str("By");
1176            out.push_str(&pascal(param));
1177        } else {
1178            let before_param = segments.get(i + 1).is_some_and(|n| n.starts_with(':'));
1179            let words = pascal(seg);
1180            out.push_str(&if before_param {
1181                singular(&words)
1182            } else {
1183                words
1184            });
1185        }
1186    }
1187    out
1188}
1189
1190fn singular(word: &str) -> String {
1191    if let Some(stem) = word.strip_suffix("ies") {
1192        format!("{stem}y")
1193    } else if word.ends_with("ss") || word.len() < 4 {
1194        word.to_string()
1195    } else if let Some(stem) = word.strip_suffix('s') {
1196        stem.to_string()
1197    } else {
1198        word.to_string()
1199    }
1200}
1201
1202/// `get-order_by.id` as `GetOrderById`.
1203fn pascal(s: &str) -> String {
1204    let mut out = String::new();
1205    let mut upper = true;
1206    for c in s.chars() {
1207        if c.is_ascii_alphanumeric() {
1208            if upper {
1209                out.extend(c.to_uppercase());
1210            } else {
1211                out.push(c);
1212            }
1213            upper = false;
1214        } else {
1215            upper = true;
1216        }
1217    }
1218    out
1219}
1220
1221fn sanitise(s: &str) -> String {
1222    s.chars()
1223        .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
1224        .collect()
1225}
1226
1227/// `name`, then `name_`, `name__`, ... until it is not in `taken`; taken.
1228fn unique(mut name: String, taken: &mut BTreeSet<String>) -> String {
1229    while taken.contains(&name) {
1230        name.push('_');
1231    }
1232    taken.insert(name.clone());
1233    name
1234}
1235
1236/// A property name: bare when it is an identifier, quoted otherwise.
1237fn property(name: &str) -> String {
1238    let ident = name.chars().enumerate().all(|(i, c)| {
1239        c == '_' || c == '$' || c.is_ascii_alphabetic() || (i > 0 && c.is_ascii_digit())
1240    });
1241    if ident {
1242        name.to_string()
1243    } else {
1244        format!("{name:?}")
1245    }
1246}
1247
1248/// The `__`-prefixed names a runtime module exports: what generated code calls.
1249fn exported_names(source: &str) -> Vec<String> {
1250    source
1251        .lines()
1252        .filter_map(|l| {
1253            let rest = l.strip_prefix("export ")?;
1254            let rest = rest
1255                .strip_prefix("function ")
1256                .or_else(|| rest.strip_prefix("const "))
1257                .or_else(|| rest.strip_prefix("class "))?;
1258            let name: String = rest
1259                .chars()
1260                .take_while(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == '$')
1261                .collect();
1262            name.starts_with("__").then_some(name)
1263        })
1264        .collect()
1265}
1266
1267/// A runtime module's text with its imports of siblings dropped: after
1268/// concatenation every name lives in one scope.
1269fn strip_imports(source: &str) -> String {
1270    let mut out = String::new();
1271    for line in source.lines() {
1272        let t = line.trim_start();
1273        if t.starts_with("import ") && t.contains("from \"./") {
1274            continue;
1275        }
1276        out.push_str(line);
1277        out.push('\n');
1278    }
1279    out
1280}
1281
1282/// The three printed parts of a client, before they are given files.
1283struct Parts {
1284    /// The boundary types (public and wire), and each route's response and query types.
1285    types: String,
1286    /// The codecs and the conversions between the wire and public shapes.
1287    codecs: String,
1288    /// Each route and `createClient`.
1289    index: String,
1290}
1291
1292/// The `// @generated` header every file of a client carries.
1293fn header(input: &HttpClientInput) -> String {
1294    format!(
1295        "// @generated by `bynk client` — do not edit by hand.\n// bynk {}. Regenerate with `bynk client`; see https://bynk-lang.org/reference/http-client/\n// {EXPERIMENTAL}\n\n",
1296        input.compiler_version
1297    )
1298}
1299
1300/// The inlined runtime for text that uses the names of `scan`: the runtime's own
1301/// `result` module, then the `bytes`, `decimal`, `time` and `keys` modules the
1302/// codecs reach, then this client's own, and the wire version.
1303fn runtime_text(scan: &str) -> String {
1304    // `keys` reads `decimal`.
1305    let mut want = vec![false; OPTIONAL_MODULES.len()];
1306    for (i, (_, source)) in OPTIONAL_MODULES.iter().enumerate() {
1307        want[i] = exported_names(source)
1308            .iter()
1309            .any(|n| scan.contains(n.as_str()));
1310    }
1311    if want[3] {
1312        want[1] = true;
1313    }
1314    let mut chunks = vec![RESULT_MODULE];
1315    for (i, (_, source)) in OPTIONAL_MODULES.iter().enumerate() {
1316        if want[i] {
1317            chunks.push(source);
1318        }
1319    }
1320    chunks.push(RUNTIME);
1321    let mut out = String::new();
1322    for chunk in chunks {
1323        out.push_str(&strip_imports(chunk));
1324        out.push('\n');
1325    }
1326    out.push_str(&format!(
1327        "/** The wire format version this client was generated for. */\nexport const WIRE_VERSION = \"{}\";\n",
1328        bynk_check::wire_format::WIRE_VERSION
1329    ));
1330    out
1331}
1332
1333/// The client's files: one module, or the four of a directory.
1334fn assemble(input: &HttpClientInput, parts: Parts, layout: Layout) -> Vec<(String, String)> {
1335    let head = header(input);
1336    let scan = format!("{}{}{}", parts.types, parts.codecs, parts.index);
1337    let runtime = runtime_text(&scan);
1338    match layout {
1339        Layout::File => vec![(
1340            SINGLE_FILE.to_string(),
1341            format!(
1342                "{head}{runtime}\n{}\n{}\n{}",
1343                parts.types, parts.codecs, parts.index
1344            ),
1345        )],
1346        Layout::Dir => {
1347            let files: Vec<(&str, String)> = vec![
1348                ("runtime.ts", runtime),
1349                ("types.ts", parts.types),
1350                ("codecs.ts", parts.codecs),
1351                (
1352                    "index.ts",
1353                    format!(
1354                        "export * from \"./types.js\";\nexport * from \"./runtime.js\";\n\n{}",
1355                        parts.index
1356                    ),
1357                ),
1358            ];
1359            // Which file declares each name, so each file imports exactly what it
1360            // uses and nothing else (a build with `noUnusedLocals` stays quiet).
1361            let mut declared: BTreeMap<String, (&str, bool)> = BTreeMap::new();
1362            for (name, text) in &files {
1363                for (n, is_type) in declared_exports(text) {
1364                    declared.insert(n, (name, is_type));
1365                }
1366            }
1367            let mut out = Vec::new();
1368            for (name, text) in &files {
1369                let imports = imports_for(name, text, &declared);
1370                out.push((name.to_string(), format!("{head}{imports}{text}")));
1371            }
1372            // Written in the order of [`DIR_FILES`].
1373            out.sort_by_key(|(n, _)| DIR_FILES.iter().position(|f| f == n));
1374            out
1375        }
1376    }
1377}
1378
1379/// The names a file's text declares with `export`, each with whether it is a type.
1380fn declared_exports(text: &str) -> Vec<(String, bool)> {
1381    let mut out = Vec::new();
1382    for line in text.lines() {
1383        let Some(rest) = line.strip_prefix("export ") else {
1384            continue;
1385        };
1386        let (rest, is_type) = if let Some(r) = rest.strip_prefix("type ") {
1387            (r, true)
1388        } else if let Some(r) = rest.strip_prefix("interface ") {
1389            (r, true)
1390        } else if let Some(r) = rest
1391            .strip_prefix("function ")
1392            .or_else(|| rest.strip_prefix("async function "))
1393            .or_else(|| rest.strip_prefix("const "))
1394            .or_else(|| rest.strip_prefix("class "))
1395        {
1396            (r, false)
1397        } else {
1398            continue;
1399        };
1400        let name: String = rest
1401            .chars()
1402            .take_while(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == '$')
1403            .collect();
1404        if !name.is_empty() {
1405            out.push((name, is_type));
1406        }
1407    }
1408    out
1409}
1410
1411/// The `import` lines `file` needs for the names of other files that its code uses.
1412fn imports_for(file: &str, text: &str, declared: &BTreeMap<String, (&str, bool)>) -> String {
1413    let used = code_identifiers(text);
1414    let mut by_file: BTreeMap<&str, Vec<String>> = BTreeMap::new();
1415    for (name, (from, is_type)) in declared {
1416        if *from != file && used.contains(name.as_str()) {
1417            let spec = if *is_type {
1418                format!("type {name}")
1419            } else {
1420                name.clone()
1421            };
1422            by_file.entry(from).or_default().push(spec);
1423        }
1424    }
1425    let mut out = String::new();
1426    for from in ["runtime.ts", "types.ts", "codecs.ts"] {
1427        if let Some(names) = by_file.get(from) {
1428            let module = from.trim_end_matches(".ts");
1429            out.push_str(&format!(
1430                "import {{ {} }} from \"./{module}.js\";\n",
1431                names.join(", ")
1432            ));
1433        }
1434    }
1435    if !out.is_empty() {
1436        out.push('\n');
1437    }
1438    out
1439}
1440
1441/// The identifiers of the code in `text`, leaving out comments and the text of
1442/// string literals (a type named in a doc comment is not a use of it).
1443fn code_identifiers(text: &str) -> BTreeSet<String> {
1444    let chars: Vec<char> = text.chars().collect();
1445    let mut out = BTreeSet::new();
1446    let mut i = 0;
1447    while i < chars.len() {
1448        let c = chars[i];
1449        match c {
1450            '/' if chars.get(i + 1) == Some(&'/') => {
1451                while i < chars.len() && chars[i] != '\n' {
1452                    i += 1;
1453                }
1454            }
1455            '/' if chars.get(i + 1) == Some(&'*') => {
1456                i += 2;
1457                while i + 1 < chars.len() && !(chars[i] == '*' && chars[i + 1] == '/') {
1458                    i += 1;
1459                }
1460                i += 2;
1461            }
1462            '"' | '\'' => {
1463                i += 1;
1464                while i < chars.len() && chars[i] != c {
1465                    i += if chars[i] == '\\' { 2 } else { 1 };
1466                }
1467                i += 1;
1468            }
1469            '`' => {
1470                i += 1;
1471                i = skip_template(&chars, i, &mut out);
1472            }
1473            _ if c.is_ascii_alphabetic() || c == '_' || c == '$' => {
1474                let start = i;
1475                while i < chars.len()
1476                    && (chars[i].is_ascii_alphanumeric() || chars[i] == '_' || chars[i] == '$')
1477                {
1478                    i += 1;
1479                }
1480                out.insert(chars[start..i].iter().collect());
1481            }
1482            _ => i += 1,
1483        }
1484    }
1485    out
1486}
1487
1488/// Past the end of a template literal that starts at `i`, collecting the
1489/// identifiers of its `${ }` expressions; the literal's own text is skipped.
1490fn skip_template(chars: &[char], mut i: usize, out: &mut BTreeSet<String>) -> usize {
1491    while i < chars.len() {
1492        match chars[i] {
1493            '\\' => i += 2,
1494            '`' => return i + 1,
1495            '$' if chars.get(i + 1) == Some(&'{') => {
1496                let start = i + 2;
1497                let mut depth = 1;
1498                i = start;
1499                while i < chars.len() && depth > 0 {
1500                    match chars[i] {
1501                        '{' => depth += 1,
1502                        '}' => depth -= 1,
1503                        _ => {}
1504                    }
1505                    i += 1;
1506                }
1507                let inner: String = chars[start..i.saturating_sub(1)].iter().collect();
1508                out.extend(code_identifiers(&inner));
1509            }
1510            _ => i += 1,
1511        }
1512    }
1513    i
1514}
1515
1516#[cfg(test)]
1517mod tests {
1518    use super::*;
1519
1520    #[test]
1521    fn a_route_is_named_from_its_method_and_path() {
1522        for (method, path, name) in [
1523            ("GET", "/orders/:id", "getOrderById"),
1524            ("POST", "/orders", "postOrders"),
1525            ("DELETE", "/orders/:sku", "deleteOrderBySku"),
1526            ("GET", "/orders/:sku/lines/:line", "getOrderBySkuLineByLine"),
1527            ("GET", "/", "getRoot"),
1528            ("GET", "/health-check", "getHealthCheck"),
1529            ("GET", "/categories/:id", "getCategoryById"),
1530            ("GET", "/address/:id", "getAddressById"),
1531            (
1532                "PUT",
1533                "/v1/user_profiles/:user.id",
1534                "putV1UserProfileByUserId",
1535            ),
1536        ] {
1537            assert_eq!(function_name(method, path), name, "{method} {path}");
1538        }
1539    }
1540
1541    #[test]
1542    fn a_name_not_taken_gains_underscores_until_it_is() {
1543        let mut taken: BTreeSet<String> = ["Order".to_string(), "Order_".to_string()].into();
1544        assert_eq!(unique("Order".to_string(), &mut taken), "Order__");
1545        assert_eq!(unique("Order".to_string(), &mut taken), "Order___");
1546        assert_eq!(unique("Fresh".to_string(), &mut taken), "Fresh");
1547    }
1548
1549    #[test]
1550    fn a_property_is_quoted_only_when_it_must_be() {
1551        assert_eq!(property("orders"), "orders");
1552        assert_eq!(property("unit_Name"), "unit_Name");
1553        assert_eq!(property("a.b"), "\"a.b\"");
1554    }
1555
1556    /// The runtime's own `BoundaryError`, `JsonValue` and `ValidationError`
1557    /// are the ones the server's boundary speaks: this module restates them, so
1558    /// they must not drift.
1559    #[test]
1560    fn the_inlined_boundary_types_are_the_runtimes() {
1561        let boundary = include_str!("../../runtime/src/boundary.ts");
1562        let errors = include_str!("../../runtime/src/errors.ts");
1563        let block = |source: &str, start: &str, end: &str| -> String {
1564            let from = source
1565                .find(start)
1566                .unwrap_or_else(|| panic!("`{start}` in source"));
1567            let to = source[from..]
1568                .find(end)
1569                .unwrap_or_else(|| panic!("`{end}`"))
1570                + from;
1571            source[from..to + end.len()].to_string()
1572        };
1573        for (source, start, end) in [
1574            (
1575                boundary,
1576                "export type JsonValue =",
1577                "{ [k: string]: JsonValue };",
1578            ),
1579            (
1580                boundary,
1581                "export type BoundaryError =",
1582                "status: number; readonly details: string };",
1583            ),
1584            (
1585                errors,
1586                "export interface ValidationError {",
1587                "readonly value: unknown;\n}",
1588            ),
1589        ] {
1590            let want = block(source, start, end);
1591            assert!(
1592                RUNTIME.contains(&want),
1593                "http_client_runtime.ts restates a runtime type that has changed:\n{want}"
1594            );
1595        }
1596    }
1597}